obo_loader.inc 34 KB

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