obo_loader.inc 33 KB

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