obo_loader.inc 32 KB

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