obo_loader.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. <?php
  2. /**
  3. * @file
  4. * Tripal Ontology Loader
  5. *
  6. * @defgroup tripal_obo_loader Ontology Loader
  7. * @ingroup tripal_cv
  8. */
  9. /**
  10. * Purpose: Provides the form to load an already existing controlled
  11. * Vocabulary into chado
  12. *
  13. * @ingroup tripal_obo_loader
  14. */
  15. function tripal_cv_obo_form($form, &$form_state) {
  16. // get a list of db from chado for user to choose
  17. $sql = "SELECT * FROM {tripal_cv_obo} ORDER BY name";
  18. $results = db_query($sql);
  19. $obos = array();
  20. $obos[] = '';
  21. foreach ($results as $obo) {
  22. // $obos[$obo->obo_id] = "$obo->name | $obo->path";
  23. $obos[$obo->obo_id] = $obo->name;
  24. }
  25. $form['obo_existing'] = array(
  26. '#type' => 'fieldset',
  27. '#title' => t('Use a Saved Ontology OBO Reference')
  28. );
  29. $form['obo_new'] = array(
  30. '#type' => 'fieldset',
  31. '#title' => t('Use a New Ontology OBO Reference')
  32. );
  33. $form['obo_existing']['existing_instructions']= array(
  34. '#value' => t('The Ontology OBO files listed in the drop down below have been automatically added upon
  35. installation of the Tripal CV module or were added from a previous upload. Select
  36. an OBO, then click the submit button to load the vocabulary into the database. If the
  37. vocabularies already exist then the ontology will be updated.'),
  38. );
  39. $form['obo_existing']['obo_id'] = array(
  40. '#title' => t('Ontology OBO File Reference'),
  41. '#type' => 'select',
  42. '#options' => $obos,
  43. );
  44. $form['obo_new']['path_instructions']= array(
  45. '#value' => t('Provide the name and path for the OBO file. If the vocabulary OBO file
  46. is stored local to the server provide a file name. If the vocabulry is stored remotely,
  47. provide a URL. Only provide a URL or a local file, not both.'),
  48. );
  49. $form['obo_new']['obo_name']= array(
  50. '#type' => 'textfield',
  51. '#title' => t('New Vocabulary Name'),
  52. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  53. list above for use again later.'),
  54. );
  55. $form['obo_new']['obo_url']= array(
  56. '#type' => 'textfield',
  57. '#title' => t('Remote URL'),
  58. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  59. (e.g. http://www.obofoundry.org/ro/ro.obo'),
  60. );
  61. $form['obo_new']['obo_file']= array(
  62. '#type' => 'textfield',
  63. '#title' => t('Local File'),
  64. '#description' => t('Please enter the full system path for an OBO definition file, or a path within the Drupal
  65. installation (e.g. /sites/default/files/xyz.obo). The path must be accessible to the
  66. server on which this Drupal instance is running.'),
  67. );
  68. $form['submit'] = array(
  69. '#type' => 'submit',
  70. '#value' => t('Submit'),
  71. '#executes_submit_callback' => TRUE,
  72. );
  73. $form['#redirect'] = 'admin/tripal/tripal_cv/obo_loader';
  74. return $form;
  75. }
  76. /**
  77. * Purpose: The submit function for the load ontology form. It registers a
  78. * tripal job to run the obo_loader.php script
  79. *
  80. * @ingroup tripal_obo_loader
  81. */
  82. function tripal_cv_obo_form_submit($form, &$form_state) {
  83. $obo_id = $form_state['values']['obo_id'];
  84. $obo_name = $form_state['values']['obo_name'];
  85. $obo_url = $form_state['values']['obo_url'];
  86. $obo_file = $form_state['values']['obo_file'];
  87. tripal_cv_submit_obo_job($obo_id, $obo_name, $obo_url, $obo_file);
  88. }
  89. /**
  90. *
  91. * @ingroup tripal_obo_loader
  92. */
  93. function tripal_cv_load_obo_v1_2_id($obo_id, $jobid = NULL) {
  94. // get the OBO reference
  95. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  96. $obo = db_query($sql, array(':obo_id' => $obo_id))->fetchObject();
  97. // if the reference is for a remote URL then run the URL processing function
  98. if (preg_match("/^http:\/\//", $obo->path) or preg_match("/^ftp:\/\//", $obo->path)) {
  99. tripal_cv_load_obo_v1_2_url($obo->name, $obo->path, $jobid, 0);
  100. }
  101. // if the reference is for a local file then run the file processing function
  102. else {
  103. // check to see if the file is located local to Drupal
  104. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
  105. if (file_exists($dfile)) {
  106. tripal_cv_load_obo_v1_2_file($obo->name, $dfile , $jobid, 0);
  107. }
  108. // if not local to Drupal, the file must be someplace else, just use
  109. // the full path provided
  110. else {
  111. if (file_exists($obo->path)) {
  112. tripal_cv_load_obo_v1_2_file($obo->name, $obo->path, $jobid, 0);
  113. }
  114. else {
  115. print "ERROR: counld not find OBO file: '$obo->path'\n";
  116. }
  117. }
  118. }
  119. }
  120. /**
  121. *
  122. * @ingroup tripal_obo_loader
  123. */
  124. function tripal_cv_load_obo_v1_2_file($obo_name, $file, $jobid = NULL, $is_new = TRUE) {
  125. $newcvs = array();
  126. // TODO: need better error detection
  127. tripal_cv_load_obo_v1_2($file, $jobid, $newcvs);
  128. if ($is_new) {
  129. tripal_cv_add_obo_ref($obo_name, $file);
  130. }
  131. print "\nDone\n";
  132. // update the cvtermpath table
  133. tripal_cv_load_update_cvtermpath($newcvs, $jobid);
  134. }
  135. /**
  136. *
  137. * @ingroup tripal_obo_loader
  138. */
  139. function tripal_cv_load_obo_v1_2_url($obo_name, $url, $jobid = NULL, $is_new = TRUE) {
  140. $newcvs = array();
  141. // first download the OBO
  142. $temp = tempnam(sys_get_temp_dir(), 'obo_');
  143. print "Downloading URL $url, saving to $temp\n";
  144. $url_fh = fopen($url, "r");
  145. $obo_fh = fopen($temp, "w");
  146. if (!$url_fh) {
  147. tripal_cv_obo_quiterror("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? " .
  148. " if you are unable to download the file you may manually downlod the OBO file and use the web interface to " .
  149. " specify the location of the file on your server.");
  150. }
  151. while (!feof($url_fh)) {
  152. fwrite($obo_fh, fread($url_fh, 255), 255);
  153. }
  154. fclose($url_fh);
  155. fclose($obo_fh);
  156. // second, parse the OBO
  157. tripal_cv_load_obo_v1_2($temp, $jobid, $newcvs);
  158. // now remove the temp file
  159. unlink($temp);
  160. if ($is_new) {
  161. tripal_cv_add_obo_ref($obo_name, $url);
  162. }
  163. // update the cvtermpath table
  164. tripal_cv_load_update_cvtermpath($newcvs, $jobid);
  165. print "Done\n";
  166. }
  167. /**
  168. *
  169. * @ingroup tripal_obo_loader
  170. */
  171. function tripal_cv_load_update_cvtermpath($newcvs, $jobid) {
  172. print "\nUpdating cvtermpath table. This may take a while...\n";
  173. foreach ($newcvs as $namespace => $cvid) {
  174. tripal_cv_update_cvtermpath($cvid, $jobid);
  175. }
  176. }
  177. /**
  178. *
  179. * @ingroup tripal_obo_loader
  180. */
  181. function tripal_cv_load_obo_v1_2($file, $jobid = NULL, &$newcvs) {
  182. $header = array();
  183. // make sure our temporary table exists
  184. $ret = array();
  185. // empty the temp table
  186. $sql = "DELETE FROM {tripal_obo_temp}";
  187. chado_query($sql);
  188. print "Step 1: Preloading File $file\n";
  189. // make sure we have an 'internal' and a '_global' database
  190. if (!tripal_db_add_db('internal')) {
  191. tripal_cv_obo_quiterror("Cannot add 'internal' database");
  192. }
  193. if (!tripal_db_add_db('_global')) {
  194. tripal_cv_obo_quiterror("Cannot add '_global' database");
  195. }
  196. // parse the obo file
  197. $default_db = tripal_cv_obo_parse($file, $header, $jobid);
  198. // add the CV for this ontology to the database
  199. $defaultcv = tripal_cv_add_cv($header['default-namespace'][0], '');
  200. if (!$defaultcv) {
  201. tripal_cv_obo_quiterror('Cannot add namespace ' . $header['default-namespace'][0]);
  202. }
  203. $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
  204. // add any typedefs to the vocabulary first
  205. print "\nStep 2: Loading type defs...\n";
  206. tripal_cv_obo_load_typedefs($defaultcv, $newcvs, $default_db, $jobid);
  207. // next add terms to the vocabulary
  208. print "\nStep 3: Loading terms...\n";
  209. if (!tripal_cv_obo_process_terms($defaultcv, $jobid, $newcvs, $default_db)) {
  210. tripal_cv_obo_quiterror('Cannot add terms from this ontology');
  211. }
  212. // transaction is complete
  213. tripal_db_commit_transaction();
  214. return;
  215. }
  216. /**
  217. *
  218. * @ingroup tripal_obo_loader
  219. */
  220. function tripal_cv_obo_quiterror($message) {
  221. watchdog("T_obo_loader", $message, array(), WATCHDOG_ERROR);;
  222. exit;
  223. }
  224. /*
  225. *
  226. */
  227. function tripal_cv_obo_load_typedefs($defaultcv, $newcvs, $default_db, $jobid) {
  228. $sql = "SELECT * FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  229. $typedefs = chado_query($sql);
  230. $sql = "
  231. SELECT count(*) as num_terms
  232. FROM {tripal_obo_temp}
  233. WHERE type = 'Typedef'
  234. ";
  235. $result = chado_query($sql)->fetchObject();
  236. $count = $result->num_terms;
  237. // calculate the interval for updates
  238. $interval = intval($count * 0.0001);
  239. if ($interval < 1) {
  240. $interval = 1;
  241. }
  242. $i = 0;
  243. foreach ($typedefs as $typedef) {
  244. $term = unserialize(base64_decode($typedef->stanza));
  245. // update the job status every interval
  246. if ($jobid and $i % $interval == 0) {
  247. $complete = ($i / $count) * 33.33333333;
  248. tripal_job_set_progress($jobid, intval($complete + 33.33333333));
  249. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  250. }
  251. tripal_cv_obo_process_term($term, $defaultcv->name, 1, $newcvs, $default_db);
  252. $i++;
  253. }
  254. // set the final status
  255. if ($jobid) {
  256. if ($count > 0) {
  257. $complete = ($i / $count) * 33.33333333;
  258. }
  259. else {
  260. $complete = 33.33333333;
  261. }
  262. tripal_job_set_progress($jobid, intval($complete + 33.33333333));
  263. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  264. }
  265. return 1;
  266. }
  267. /**
  268. *
  269. * @ingroup tripal_obo_loader
  270. */
  271. function tripal_cv_obo_process_terms($defaultcv, $jobid = NULL, &$newcvs, $default_db) {
  272. $i = 0;
  273. // iterate through each term from the OBO file and add it
  274. $sql = "
  275. SELECT * FROM {tripal_obo_temp}
  276. WHERE type = 'Term'
  277. ORDER BY id
  278. ";
  279. $terms = chado_query($sql);
  280. $sql = "
  281. SELECT count(*) as num_terms
  282. FROM {tripal_obo_temp}
  283. WHERE type = 'Term'
  284. ";
  285. $result = chado_query($sql)->fetchObject();
  286. $count = $result->num_terms;
  287. // calculate the interval for updates
  288. $interval = intval($count * 0.0001);
  289. if ($interval < 1) {
  290. $interval = 1;
  291. }
  292. foreach ($terms as $t) {
  293. $term = unserialize(base64_decode($t->stanza));
  294. // update the job status every interval
  295. if ($jobid and $i % $interval == 0) {
  296. $complete = ($i / $count) * 33.33333333;
  297. tripal_job_set_progress($jobid, intval($complete + 66.666666));
  298. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  299. }
  300. // add/update this term
  301. if (!tripal_cv_obo_process_term($term, $defaultcv->name, 0, $newcvs, $default_db)) {
  302. tripal_cv_obo_quiterror("Failed to process terms from the ontology");
  303. }
  304. $i++;
  305. }
  306. // set the final status
  307. if ($jobid) {
  308. if ($count > 0) {
  309. $complete = ($i / $count) * 33.33333333;
  310. }
  311. else {
  312. $complete = 33.33333333;
  313. }
  314. tripal_job_set_progress($jobid, intval($complete + 66.666666));
  315. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  316. }
  317. return 1;
  318. }
  319. /**
  320. *
  321. * @ingroup tripal_obo_loader
  322. */
  323. function tripal_cv_obo_process_term($term, $defaultcv, $is_relationship = 0, &$newcvs, $default_db) {
  324. // construct the term array for sending to the tripal_cv_add_cvterm function
  325. // for adding a new cvterm
  326. $t = array();
  327. $t['id'] = $term['id'][0];
  328. $t['name'] = $term['name'][0];
  329. if (array_key_exists('def', $term)) {
  330. $t['def'] = $term['def'][0];
  331. }
  332. if (array_key_exists('subset', $term)) {
  333. $t['subset'] = $term['subset'][0];
  334. }
  335. if (array_key_exists('namespace', $term)) {
  336. $t['namespace'] = $term['namespace'][0];
  337. }
  338. if (array_key_exists('is_obsolete', $term)) {
  339. $t['is_obsolete'] = $term['is_obsolete'][0];
  340. }
  341. // add the cvterm
  342. $cvterm = tripal_cv_add_cvterm($t, $defaultcv, $is_relationship, 1, $default_db);
  343. if (!$cvterm) {
  344. tripal_cv_obo_quiterror("Cannot add the term " . $term['id'][0]);
  345. }
  346. if (array_key_exists('namespace', $term)) {
  347. $newcvs[$term['namespace'][0]] = $cvterm->cv_id;
  348. }
  349. // now handle other properites
  350. if (array_key_exists('is_anonymous', $term)) {
  351. //print "WARNING: unhandled tag: is_anonymous\n";
  352. }
  353. if (array_key_exists('alt_id', $term)) {
  354. foreach ($term['alt_id'] as $alt_id) {
  355. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $alt_id)) {
  356. tripal_cv_obo_quiterror("Cannot add alternate id $alt_id");
  357. }
  358. }
  359. }
  360. if (array_key_exists('subset', $term)) {
  361. //print "WARNING: unhandled tag: subset\n";
  362. }
  363. // add synonyms for this cvterm
  364. if (array_key_exists('synonym', $term)) {
  365. if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
  366. tripal_cv_obo_quiterror("Cannot add synonyms");
  367. }
  368. }
  369. // reformat the deprecated 'exact_synonym, narrow_synonym, and broad_synonym'
  370. // types to be of the v1.2 standard
  371. if (array_key_exists('exact_synonym', $term) or array_key_exists('narrow_synonym', $term) or array_key_exists('broad_synonym', $term)) {
  372. if (array_key_exists('exact_synonym', $term)) {
  373. foreach ($term['exact_synonym'] as $synonym) {
  374. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  375. $term['synonym'][] = $new;
  376. }
  377. }
  378. if (array_key_exists('narrow_synonym', $term)) {
  379. foreach ($term['narrow_synonym'] as $synonym) {
  380. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  381. $term['synonym'][] = $new;
  382. }
  383. }
  384. if (array_key_exists('broad_synonym', $term)) {
  385. foreach ($term['broad_synonym'] as $synonym) {
  386. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  387. $term['synonym'][] = $new;
  388. }
  389. }
  390. if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
  391. tripal_cv_obo_quiterror("Cannot add/update synonyms");
  392. }
  393. }
  394. // add the comment to the cvtermprop table
  395. if (array_key_exists('comment', $term)) {
  396. $comments = $term['comment'];
  397. $j = 0;
  398. foreach ($comments as $comment) {
  399. if (!tripal_cv_obo_add_cvterm_prop($cvterm, 'comment', $comment, $j)) {
  400. tripal_cv_obo_quiterror("Cannot add/update cvterm property");
  401. }
  402. $j++;
  403. }
  404. }
  405. // add any other external dbxrefs
  406. if (array_key_exists('xref', $term)) {
  407. foreach ($term['xref'] as $xref) {
  408. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  409. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  410. }
  411. }
  412. }
  413. if (array_key_exists('xref_analog', $term)) {
  414. foreach ($term['xref_analog'] as $xref) {
  415. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  416. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  417. }
  418. }
  419. }
  420. if (array_key_exists('xref_unk', $term)) {
  421. foreach ($term['xref_unk'] as $xref) {
  422. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  423. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  424. }
  425. }
  426. }
  427. // add is_a relationships for this cvterm
  428. if (array_key_exists('is_a', $term)) {
  429. foreach ($term['is_a'] as $is_a) {
  430. if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, 'is_a', $is_a, $is_relationship, $default_db)) {
  431. tripal_cv_obo_quiterror("Cannot add relationship is_a: $is_a");
  432. }
  433. }
  434. }
  435. if (array_key_exists('intersection_of', $term)) {
  436. //print "WARNING: unhandled tag: intersection_of\n";
  437. }
  438. if (array_key_exists('union_of', $term)) {
  439. //print "WARNING: unhandled tag: union_on\n";
  440. }
  441. if (array_key_exists('disjoint_from', $term)) {
  442. //print "WARNING: unhandled tag: disjoint_from\n";
  443. }
  444. if (array_key_exists('relationship', $term)) {
  445. foreach ($term['relationship'] as $value) {
  446. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  447. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  448. if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, $rel, $object, $is_relationship, $default_db)) {
  449. tripal_cv_obo_quiterror("Cannot add relationship $rel: $object");
  450. }
  451. }
  452. }
  453. if (array_key_exists('replaced_by', $term)) {
  454. //print "WARNING: unhandled tag: replaced_by\n";
  455. }
  456. if (array_key_exists('consider', $term)) {
  457. //print "WARNING: unhandled tag: consider\n";
  458. }
  459. if (array_key_exists('use_term', $term)) {
  460. //print "WARNING: unhandled tag: user_term\n";
  461. }
  462. if (array_key_exists('builtin', $term)) {
  463. //print "WARNING: unhandled tag: builtin\n";
  464. }
  465. return 1;
  466. }
  467. /**
  468. * Add a cvterm relationship
  469. *
  470. * @ingroup tripal_obo_loader
  471. */
  472. function tripal_cv_obo_add_relationship($cvterm, $defaultcv, $rel,
  473. $objname, $object_is_relationship = 0, $default_db = 'OBO_REL') {
  474. // make sure the relationship cvterm exists
  475. $term = array(
  476. 'name' => $rel,
  477. 'id' => "$default_db:$rel",
  478. 'definition' => '',
  479. 'is_obsolete' => 0,
  480. );
  481. $relcvterm = tripal_cv_add_cvterm($term, $defaultcv, 1, 0, $default_db);
  482. if (!$relcvterm) {
  483. // if the relationship term couldn't be found in the default_db provided
  484. // then do on more check to find it in the relationship ontology
  485. $term = array(
  486. 'name' => $rel,
  487. 'id' => "OBO_REL:$rel",
  488. 'definition' => '',
  489. 'is_obsolete' => 0,
  490. );
  491. $relcvterm = tripal_cv_add_cvterm($term, $defaultcv, 1, 0, 'OBO_REL');
  492. if (!$relcvterm) {
  493. tripal_cv_obo_quiterror("Cannot find the relationship term in the current ontology or in the relationship ontology: $rel\n");
  494. }
  495. }
  496. // get the object term
  497. $oterm = tripal_cv_obo_get_term($objname);
  498. if (!$oterm) {
  499. tripal_cv_obo_quiterror("Could not find object term $objname\n");
  500. }
  501. $objterm = array();
  502. $objterm['id'] = $oterm['id'][0];
  503. $objterm['name'] = $oterm['name'][0];
  504. if (array_key_exists('def', $oterm)) {
  505. $objterm['def'] = $oterm['def'][0];
  506. }
  507. if (array_key_exists('subset', $oterm)) {
  508. $objterm['subset'] = $oterm['subset'][0];
  509. }
  510. if (array_key_exists('namespace', $oterm)) {
  511. $objterm['namespace'] = $oterm['namespace'][0];
  512. }
  513. if (array_key_exists('is_obsolete', $oterm)) {
  514. $objterm['is_obsolete'] = $oterm['is_obsolete'][0];
  515. }
  516. $objcvterm = tripal_cv_add_cvterm($objterm, $defaultcv, $object_is_relationship, 1, $default_db);
  517. if (!$objcvterm) {
  518. tripal_cv_obo_quiterror("Cannot add cvterm " . $oterm['name'][0]);
  519. }
  520. // check to see if the cvterm_relationship already exists, if not add it
  521. $values = array(
  522. 'type_id' => $relcvterm->cvterm_id,
  523. 'subject_id' => $cvterm->cvterm_id,
  524. 'object_id' => $objcvterm->cvterm_id
  525. );
  526. $options = array('statement_name' => 'sel_cvtermrelationship_tysuob');
  527. $result = tripal_core_chado_select('cvterm_relationship', array('*'), $values, $options);
  528. if (count($result) == 0) {
  529. $options = array(
  530. 'statement_name' => 'ins_cvtermrelationship_tysuob',
  531. 'return_record' => FALSE
  532. );
  533. $success = tripal_core_chado_insert('cvterm_relationship', $values, $options);
  534. if (!$success) {
  535. tripal_cv_obo_quiterror("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
  536. }
  537. }
  538. return TRUE;
  539. }
  540. /**
  541. *
  542. * @ingroup tripal_obo_loader
  543. */
  544. function tripal_cv_obo_get_term($id) {
  545. $values = array('id' => $id);
  546. $options = array('statement_name' => 'sel_tripalobotemp_id');
  547. $result = tripal_core_chado_select('tripal_obo_temp', array('stanza'), $values, $options);
  548. if (count($result) == 0) {
  549. return FALSE;
  550. }
  551. return unserialize(base64_decode($result[0]->stanza));
  552. }
  553. /**
  554. *
  555. * @ingroup tripal_obo_loader
  556. */
  557. function tripal_cv_obo_add_synonyms($term, $cvterm) {
  558. // make sure we have a 'synonym_type' vocabulary
  559. $syncv = tripal_cv_add_cv('synonym_type', 'A vocabulary added by the Tripal CV module OBO loader for storing synonym types.');
  560. // now add the synonyms
  561. if (array_key_exists('synonym', $term)) {
  562. foreach ($term['synonym'] as $synonym) {
  563. // separate out the synonym definition and the synonym type
  564. $def = preg_replace('/^\s*"(.*)"\s*.*$/', '\1', $synonym);
  565. // the scope will be 'EXACT', etc...
  566. $scope = drupal_strtolower(preg_replace('/^.*"\s+(.*?)\s+.*$/', '\1', $synonym));
  567. if (!$scope) { // if no scope then default to 'exact'
  568. $scope = 'exact';
  569. }
  570. // make sure the synonym type exists in the 'synonym_type' vocabulary
  571. $values = array(
  572. 'name' => $scope,
  573. 'cv_id' => array(
  574. 'name' => 'synonym_type',
  575. ),
  576. );
  577. $options = array('statement_name' => 'sel_cvterm_nacv', 'is_updlicate' => 1);
  578. $results = tripal_core_chado_select('cvterm', array('*'), $values, $options);
  579. // if it doesn't exist then add it
  580. if (!$results) {
  581. // build a 'term' object so we can add the missing term
  582. $term = array(
  583. 'name' => $scope,
  584. 'id' => "internal:$scope",
  585. 'definition' => '',
  586. 'is_obsolete' => 0,
  587. );
  588. $syntype = tripal_cv_add_cvterm($term, $syncv->name, 0, 1);
  589. if (!$syntype) {
  590. tripal_cv_obo_quiterror("Cannot add synonym type: internal:$scope");
  591. }
  592. }
  593. else {
  594. $syntype = $results[0];
  595. }
  596. // make sure the synonym doesn't already exists
  597. $values = array(
  598. 'cvterm_id' => $cvterm->cvterm_id,
  599. 'synonym' => $def
  600. );
  601. $options = array('statement_name' => 'sel_cvtermsynonym_cvsy');
  602. $results = tripal_core_chado_select('cvtermsynonym', array('*'), $values, $options);
  603. if (count($results) == 0) {
  604. $values = array(
  605. 'cvterm_id' => $cvterm->cvterm_id,
  606. 'synonym' => $def,
  607. 'type_id' => $syntype->cvterm_id
  608. );
  609. $options = array(
  610. 'statement_name' => 'ins_cvtermsynonym_cvsy',
  611. 'return_record' => FALSE
  612. );
  613. $success = tripal_core_chado_insert('cvtermsynonym', $values, $options);
  614. if (!$success) {
  615. tripal_cv_obo_quiterror("Failed to insert the synonym for term: $name ($def)");
  616. }
  617. }
  618. // now add the dbxrefs for the synonym if we have a comma in the middle
  619. // of a description then this will cause problems when splitting os lets
  620. // just change it so it won't mess up our splitting and then set it back
  621. // later.
  622. /**
  623. $synonym = preg_replace('/(".*?),\s(.*?")/','$1,_$2',$synonym);
  624. $dbxrefs = preg_split("/, /",preg_replace('/^.*\[(.*?)\]$/','\1',$synonym));
  625. foreach ($dbxrefs as $dbxref) {
  626. $dbxref = preg_replace('/,_/',", ",$dbxref);
  627. if ($dbxref) {
  628. tripal_cv_obo_add_cvterm_dbxref($syn,$dbxref);
  629. }
  630. }
  631. */
  632. }
  633. }
  634. return TRUE;
  635. }
  636. /**
  637. * Actually parse the OBO file
  638. *
  639. * @ingroup tripal_obo_loader
  640. */
  641. function tripal_cv_obo_parse($obo_file, &$header, $jobid) {
  642. $in_header = 1;
  643. $stanza = array();
  644. $default_db = '_global';
  645. $line_num = 0;
  646. $num_read = 0;
  647. $intv_read = 0;
  648. $filesize = filesize($obo_file);
  649. $interval = intval($filesize * 0.01);
  650. if ($interval < 1) {
  651. $interval = 1;
  652. }
  653. // iterate through the lines in the OBO file and parse the stanzas
  654. $fh = fopen($obo_file, 'r');
  655. while ($line = fgets($fh)) {
  656. $line_num++;
  657. $size = drupal_strlen($line);
  658. $num_read += $size;
  659. $intv_read += $size;
  660. $line = trim($line);
  661. // update the job status every 1% features
  662. if ($jobid and $intv_read >= $interval) {
  663. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  664. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  665. tripal_job_set_progress($jobid, intval(($num_read / $filesize) * 33.33333333));
  666. $intv_read = 0;
  667. }
  668. // remove newlines
  669. $line = rtrim($line);
  670. // remove any special characters that may be hiding
  671. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  672. // skip empty lines
  673. if (strcmp($line, '') == 0) {
  674. continue;
  675. }
  676. //remove comments from end of lines
  677. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line); // TODO: if the explamation is escaped
  678. // at the first stanza we're out of header
  679. if (preg_match('/^\s*\[/', $line)) {
  680. $in_header = 0;
  681. // store the stanza we just finished reading
  682. if (sizeof($stanza) > 0) {
  683. // add the term to the temp table
  684. $values = array(
  685. 'id' => $stanza['id'][0],
  686. 'stanza' => base64_encode(serialize($stanza)),
  687. 'type' => $type,
  688. );
  689. $options = array('statement_name' => 'ins_tripalobotemp_all');
  690. $success = tripal_core_chado_insert('tripal_obo_temp', $values, $options);
  691. if (!$success) {
  692. watchdog('T_obo_loader', "ERROR: Cannot insert stanza into temporary table.", array(), 'error');
  693. exit;
  694. }
  695. }
  696. // get the stanza type: Term, Typedef or Instance
  697. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  698. // start fresh with a new array
  699. $stanza = array();
  700. continue;
  701. }
  702. // break apart the line into the tag and value but ignore any escaped colons
  703. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  704. $pair = explode(":", $line, 2);
  705. $tag = $pair[0];
  706. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  707. // if this is the ID then look for the default DB
  708. $matches = array();
  709. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  710. $default_db = $matches[1];
  711. }
  712. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  713. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  714. if ($in_header) {
  715. if (!array_key_exists($tag, $header)) {
  716. $header[$tag] = array();
  717. }
  718. $header[$tag][] = $value;
  719. }
  720. else {
  721. if (!array_key_exists($tag, $stanza)) {
  722. $stanza[$tag] = array();
  723. }
  724. $stanza[$tag][] = $value;
  725. }
  726. }
  727. // now add the last term in the file
  728. if (sizeof($stanza) > 0) {
  729. $values = array(
  730. 'id' => $stanza['id'][0],
  731. 'stanza' => base64_encode(serialize($stanza)),
  732. 'type' => $type,
  733. );
  734. $options = array('statement_name' => 'ins_tripalobotemp_all');
  735. tripal_core_chado_insert('tripal_obo_temp', $values, $options);
  736. if (!$success) {
  737. watchdog('T_obo_loader', "ERROR: Cannot insert stanza into temporary table.", array(), 'error');
  738. exit;
  739. }
  740. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  741. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  742. tripal_job_set_progress($jobid, intval(($num_read / $filesize) * 33.33333333));
  743. }
  744. return $default_db;
  745. }
  746. /**
  747. * Add database reference to cvterm
  748. *
  749. * @ingroup tripal_obo_loader
  750. */
  751. function tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref) {
  752. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  753. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  754. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  755. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  756. if (!$accession) {
  757. tripal_cv_obo_quiterror();
  758. watchdog("T_obo_loader", "Cannot add a dbxref without an accession: '$xref'", NULL, WATCHDOG_WARNING);
  759. return FALSE;
  760. }
  761. // if the xref is a database link, handle that specially
  762. if (strcmp($dbname, 'http') == 0) {
  763. $accession = $xref;
  764. $dbname = 'URL';
  765. }
  766. // add the database
  767. $db = tripal_db_add_db($dbname);
  768. if (!$db) {
  769. tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
  770. }
  771. // now add the dbxref
  772. $dbxref = tripal_cv_obo_add_dbxref($db->db_id, $accession, '', $description);
  773. if (!$dbxref) {
  774. tripal_cv_obo_quiterror("Cannot find or add the database reference (dbxref)");
  775. }
  776. // finally add the cvterm_dbxref but first check to make sure it exists
  777. $values = array(
  778. 'cvterm_id' => $cvterm->cvterm_id,
  779. 'dbxref_id' => $dbxref->dbxref_id,
  780. );
  781. $options = array('statement_name' => 'sel_cvtermdbxref_cvdb');
  782. $result = tripal_core_chado_select('cvterm_dbxref', array('*'), $values, $options);
  783. if (count($result) == 0) {
  784. $ins_options = array(
  785. 'statement_name' => 'ins_cvtermdbxref_cvdb',
  786. 'return_record' => FALSE
  787. );
  788. $result = tripal_core_chado_insert('cvterm_dbxref', $values, $ins_options);
  789. if (!$result) {
  790. tripal_cv_obo_quiterror("Cannot add cvterm_dbxref: $xref");
  791. return FALSE;
  792. }
  793. }
  794. return TRUE;
  795. }
  796. /**
  797. * Add property to CVterm
  798. * @ingroup tripal_obo_loader
  799. */
  800. function tripal_cv_obo_add_cvterm_prop($cvterm, $property, $value, $rank) {
  801. // make sure the 'cvterm_property_type' CV exists
  802. $cv = tripal_cv_add_cv('cvterm_property_type', '');
  803. if (!$cv) {
  804. tripal_cv_obo_quiterror("Cannot add/find cvterm_property_type cvterm");
  805. }
  806. // get the property type cvterm. If it doesn't exist then we want to add it
  807. $values = array(
  808. 'name' => $property,
  809. 'cv_id' => $cv->cv_id,
  810. );
  811. $options = array('statement_name' => 'sel_cvterm_nacv_na');
  812. $results = tripal_core_chado_select('cvterm', array('*'), $values, $options);
  813. if (count($results) == 0) {
  814. $term = array(
  815. 'name' => $property,
  816. 'id' => "internal:$property",
  817. 'definition' => '',
  818. 'is_obsolete' => 0,
  819. );
  820. $cvproptype = tripal_cv_add_cvterm($term, $cv->name, 0, 0);
  821. if (!$cvproptype) {
  822. tripal_cv_obo_quiterror("Cannot add cvterm property: internal:$property");
  823. return FALSE;
  824. }
  825. }
  826. else {
  827. $cvproptype = $results[0];
  828. }
  829. // remove any properties that currently exist for this term. We'll reset them
  830. if ($rank == 0) {
  831. $values = array('cvterm_id' => $cvterm->cvterm_id);
  832. $options = array('statement_name' => 'del_cvtermprop_cv');
  833. $success = tripal_core_chado_delete('cvtermprop', $values, $options);
  834. if (!$success) {
  835. tripal_cv_obo_quiterror("Could not remove existing properties to update property $property for term\n");
  836. return FALSE;
  837. }
  838. }
  839. // now add the property
  840. $values = array(
  841. 'cvterm_id' => $cvterm->cvterm_id,
  842. 'type_id' => $cvproptype->cvterm_id,
  843. 'value' => $value,
  844. 'rank' => $rank,
  845. );
  846. $options = array(
  847. 'statement_name' => 'ins_cvtermprop_cvtyvara',
  848. 'return_record' => FALSE,
  849. );
  850. $result = tripal_core_chado_insert('cvtermprop', $values, $options);
  851. if (!$result) {
  852. tripal_cv_obo_quiterror("Could not add property $property for term\n");
  853. return FALSE;
  854. }
  855. return TRUE;
  856. }
  857. /**
  858. * Add Database Reference
  859. * @ingroup tripal_obo_loader
  860. */
  861. function tripal_cv_obo_add_dbxref($db_id, $accession, $version='', $description='') {
  862. // check to see if the dbxref exists if not, add it
  863. $values = array(
  864. 'db_id' => $db_id,
  865. 'accession' => $accession,
  866. );
  867. $options = array('statement_name' => 'sel_dbxref_idac');
  868. $result = tripal_core_chado_select('dbxref', array('dbxref_id'), $values, $options);
  869. if (count($result) == 0) {
  870. $ins_values = array(
  871. 'db_id' => $db_id,
  872. 'accession' => $accession,
  873. 'version' => $version,
  874. 'description' => $description,
  875. );
  876. $ins_options = array(
  877. 'statement_name' => 'ins_dbxref_idacvede',
  878. 'return_record' => FALSE
  879. );
  880. $result = tripal_core_chado_insert('dbxref', $ins_values, $ins_options);
  881. if (!$result) {
  882. tripal_cv_obo_quiterror("Failed to insert the dbxref record $accession");
  883. return FALSE;
  884. }
  885. $result = tripal_core_chado_select('dbxref', array('dbxref_id'), $values, $options);
  886. }
  887. return $result[0];
  888. }