obo_loader.inc 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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. global $user;
  93. $obo_id = $form_state['values']['obo_id'];
  94. $obo_name = $form_state['values']['obo_name'];
  95. $obo_url = $form_state['values']['obo_url'];
  96. $obo_file = $form_state['values']['obo_file'];
  97. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = %d";
  98. $obo = db_fetch_object(db_query($sql, $obo_id));
  99. if ($obo_id) {
  100. $args = array($obo_id);
  101. tripal_add_job("Load OBO $obo->name", 'tripal_cv',
  102. "tripal_cv_load_obo_v1_2_id", $args, $user->uid);
  103. }
  104. else {
  105. if ($obo_url) {
  106. $args = array($obo_name, $obo_url);
  107. tripal_add_job("Load OBO $obo_name", 'tripal_cv',
  108. "tripal_cv_load_obo_v1_2_url", $args, $user->uid);
  109. }
  110. elseif ($obo_file) {
  111. $args = array($obo_name, $obo_file);
  112. tripal_add_job("Load OBO $obo_name", 'tripal_cv',
  113. "tripal_cv_load_obo_v1_2_file", $args, $user->uid);
  114. }
  115. }
  116. }
  117. /**
  118. * Form for re-doing the cvterm path
  119. *
  120. * @ingroup tripal_cv
  121. */
  122. function tripal_cv_cvtermpath_form() {
  123. // get a list of db from chado for user to choose
  124. $sql = "SELECT * FROM {cv} WHERE NOT name = 'tripal' ORDER BY name ";
  125. $results = chado_query($sql);
  126. $cvs = array();
  127. $cvs[] = '';
  128. while ($cv = db_fetch_object($results)) {
  129. $cvs[$cv->cv_id] = $cv->name;
  130. }
  131. $form['cvid'] = array(
  132. '#title' => t('Controlled Vocabulary/Ontology Name'),
  133. '#type' => 'select',
  134. '#options' => $cvs,
  135. '#description' => t('The Chado cvtermpath is a database table that provides lineage for ontology terms
  136. and is useful for quickly finding any ancestor parent of a term. This table must be populated for each
  137. ontology. Select a controlled vocabulary for which you would like to upate the cvtermpath.'),
  138. );
  139. $form['description'] = array(
  140. '#type' => 'item',
  141. '#value' => t("Submit a job to update chado cvtermpath table."),
  142. '#weight' => 1,
  143. );
  144. $form['button'] = array(
  145. '#type' => 'submit',
  146. '#value' => t('Update cvtermpath'),
  147. '#weight' => 2,
  148. );
  149. return $form;
  150. }
  151. /**
  152. *
  153. * @ingroup tripal_obo_loader
  154. */
  155. function tripal_cv_load_obo_v1_2_id($obo_id, $jobid = NULL) {
  156. // get the OBO reference
  157. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = %d";
  158. $obo = db_fetch_object(db_query($sql, $obo_id));
  159. // if the reference is for a remote URL then run the URL processing function
  160. if (preg_match("/^http:\/\//", $obo->path) or preg_match("/^ftp:\/\//", $obo->path)) {
  161. tripal_cv_load_obo_v1_2_url($obo->name, $obo->path, $jobid, 0);
  162. }
  163. // if the reference is for a local file then run the file processing function
  164. else {
  165. // check to see if the file is located local to Drupal
  166. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
  167. if (file_exists($dfile)) {
  168. tripal_cv_load_obo_v1_2_file($obo->name, $dfile , $jobid, 0);
  169. }
  170. // if not local to Drupal, the file must be someplace else, just use
  171. // the full path provided
  172. else {
  173. if (file_exists($obo->path)) {
  174. tripal_cv_load_obo_v1_2_file($obo->name, $obo->path, $jobid, 0);
  175. }
  176. else {
  177. print "ERROR: counld not find OBO file: '$obo->path'\n";
  178. }
  179. }
  180. }
  181. }
  182. /**
  183. *
  184. * @ingroup tripal_obo_loader
  185. */
  186. function tripal_cv_load_obo_v1_2_file($obo_name, $file, $jobid = NULL, $is_new = TRUE) {
  187. $newcvs = array();
  188. // TODO: need better error detection
  189. tripal_cv_load_obo_v1_2($file, $jobid, $newcvs);
  190. if ($is_new) {
  191. tripal_cv_load_obo_add_ref($obo_name, $file);
  192. }
  193. print "Ontology Sucessfully loaded!\n";
  194. // update the cvtermpath table
  195. tripal_cv_load_update_cvtermpath($newcvs, $jobid);
  196. }
  197. /**
  198. *
  199. * @ingroup tripal_obo_loader
  200. */
  201. function tripal_cv_load_obo_v1_2_url($obo_name, $url, $jobid = NULL, $is_new = TRUE) {
  202. $newcvs = array();
  203. // first download the OBO
  204. $temp = tempnam(sys_get_temp_dir(), 'obo_');
  205. print "Downloading URL $url, saving to $temp\n";
  206. $url_fh = fopen($url, "r");
  207. $obo_fh = fopen($temp, "w");
  208. if (!$url_fh) {
  209. tripal_cv_obo_quiterror("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? ".
  210. " if you are unable to download the file you may manually downlod the OBO file and use the web interface to ".
  211. " specify the location of the file on your server.");
  212. }
  213. while (!feof($url_fh)) {
  214. fwrite($obo_fh, fread($url_fh, 255), 255);
  215. }
  216. fclose($url_fh);
  217. fclose($obo_fh);
  218. // second, parse the OBO
  219. tripal_cv_load_obo_v1_2($temp, $jobid, $newcvs);
  220. // now remove the temp file
  221. unlink($temp);
  222. if ($is_new) {
  223. tripal_cv_load_obo_add_ref($obo_name, $url);
  224. }
  225. // update the cvtermpath table
  226. tripal_cv_load_update_cvtermpath($newcvs, $jobid);
  227. print "Ontology Sucessfully loaded!\n";
  228. }
  229. /**
  230. *
  231. * @ingroup tripal_obo_loader
  232. */
  233. function tripal_cv_load_update_cvtermpath($newcvs, $jobid) {
  234. print "\nUpdating cvtermpath table. This may take a while...\n";
  235. foreach ($newcvs as $namespace => $cvid) {
  236. tripal_cv_update_cvtermpath($cvid, $jobid);
  237. }
  238. }
  239. /**
  240. * Add the obo to the tripal_cv_obo table in the Drupal database
  241. */
  242. function tripal_cv_load_obo_add_ref($name, $path) {
  243. $isql = "INSERT INTO {tripal_cv_obo} (name,path) VALUES ('%s','%s')";
  244. db_query($isql, $name, $path);
  245. }
  246. /**
  247. *
  248. * @ingroup tripal_obo_loader
  249. */
  250. function tripal_cv_load_obo_v1_2($file, $jobid = NULL, &$newcvs) {
  251. $header = array();
  252. // make sure our temporary table exists
  253. $ret = array();
  254. if (!db_table_exists('tripal_obo_temp')) {
  255. $schema = tripal_cv_get_custom_tables('tripal_obo_temp');
  256. $success = tripal_core_create_custom_table($ret, 'tripal_obo_temp', $schema['tripal_obo_temp']);
  257. if (!$success) {
  258. watchdog('T_obo_loader', "Cannot create temporary loading table", array(), WATCHDOG_ERROR);
  259. return;
  260. }
  261. }
  262. // empty the temp table
  263. $sql = "DELETE FROM tripal_obo_temp";
  264. chado_query($sql);
  265. // get a persistent connection
  266. $connection = tripal_db_persistent_chado();
  267. if (!$connection) {
  268. print "A persistant connection was not obtained. Loading will be slow\n";
  269. }
  270. // if we cannot get a connection then let the user know the loading will be slow
  271. tripal_db_start_transaction();
  272. if ($connection) {
  273. print "\nNOTE: Loading of this OBO file is performed using a database transaction. \n" .
  274. "If the load fails or is terminated prematurely then the entire set of \n" .
  275. "insertions/updates is rolled back and will not be found in the database\n\n";
  276. }
  277. print "Step 1: Preloading File $file\n";
  278. // make sure we have an 'internal' and a '_global' database
  279. if (!tripal_db_add_db('internal')) {
  280. tripal_cv_obo_quiterror("Cannot add 'internal' database");
  281. }
  282. if (!tripal_db_add_db('_global')) {
  283. tripal_cv_obo_quiterror("Cannot add '_global' database");
  284. }
  285. // parse the obo file
  286. $default_db = tripal_cv_obo_parse($file, $header, $jobid);
  287. // add the CV for this ontology to the database
  288. $defaultcv = tripal_cv_add_cv($header['default-namespace'][0], '');
  289. if (!$defaultcv) {
  290. tripal_cv_obo_quiterror('Cannot add namespace ' . $header['default-namespace'][0]);
  291. }
  292. $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
  293. // add any typedefs to the vocabulary first
  294. $sql = "
  295. SELECT * FROM tripal_obo_temp
  296. WHERE type = 'Typedef'
  297. ";
  298. $typedefs = chado_query($sql);
  299. while ($typedef = db_fetch_object($typedefs)) {
  300. $term = unserialize(base64_decode($typedef->stanza));
  301. tripal_cv_obo_process_term($term, $defaultcv->name, 1, $newcvs, $default_db);
  302. }
  303. // next add terms to the vocabulary
  304. print "\nStep 2: Loading terms...\n";
  305. if (!tripal_cv_obo_process_terms($defaultcv->name, $jobid, $newcvs, $default_db)) {
  306. tripal_cv_obo_quiterror('Cannot add terms from this ontology');
  307. }
  308. // transaction is complete
  309. tripal_db_commit_transaction();
  310. return;
  311. }
  312. /**
  313. *
  314. * @ingroup tripal_obo_loader
  315. */
  316. function tripal_cv_obo_quiterror($message) {
  317. watchdog("T_obo_loader", $message, array(), WATCHDOG_ERROR);;
  318. exit;
  319. }
  320. /**
  321. *
  322. * @ingroup tripal_obo_loader
  323. */
  324. function tripal_cv_obo_process_terms($defaultcv, $jobid = NULL, &$newcvs, $default_db) {
  325. $i = 0;
  326. // iterate through each term from the OBO file and add it
  327. $sql = "
  328. SELECT * FROM tripal_obo_temp
  329. WHERE type = 'Term'
  330. ORDER BY id
  331. ";
  332. $terms = chado_query($sql);
  333. $count = pg_num_rows($terms);
  334. // calculate the interval for updates
  335. $interval = intval($count * 0.0001);
  336. if ($interval < 1) {
  337. $interval = 1;
  338. }
  339. while($t = db_fetch_object($terms)) {
  340. $term = unserialize(base64_decode($t->stanza));
  341. // update the job status every interval
  342. if ($jobid and $i % $interval == 0) {
  343. $complete = ($i / $count) * 50;
  344. tripal_job_set_progress($jobid + 50, intval($complete));
  345. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 2, number_format(memory_get_usage()));
  346. }
  347. // add/update this term
  348. if (!tripal_cv_obo_process_term($term, $defaultcv, 0, $newcvs, $default_db)) {
  349. tripal_cv_obo_quiterror("Failed to process terms from the ontology");
  350. }
  351. $i++;
  352. }
  353. // set the final status
  354. if ($jobid) {
  355. $complete = ($i / $count) * 50;
  356. tripal_job_set_progress($jobid + 50, intval($complete));
  357. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 2, 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']);
  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) * 50));
  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. }
  783. return $default_db;
  784. }
  785. /**
  786. * Add database reference to cvterm
  787. *
  788. * @ingroup tripal_obo_loader
  789. */
  790. function tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref) {
  791. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  792. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  793. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  794. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  795. if (!$accession) {
  796. tripal_cv_obo_quiterror();
  797. watchdog("T_obo_loader", "Cannot add a dbxref without an accession: '$xref'", NULL, WATCHDOG_WARNING);
  798. return FALSE;
  799. }
  800. // if the xref is a database link, handle that specially
  801. if (strcmp($dbname, 'http') == 0) {
  802. $accession = $xref;
  803. $dbname = 'URL';
  804. }
  805. // add the database
  806. $db = tripal_db_add_db($dbname);
  807. if (!$db) {
  808. tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
  809. }
  810. // now add the dbxref
  811. $dbxref = tripal_cv_obo_add_dbxref($db->db_id, $accession, '', $description);
  812. if (!$dbxref) {
  813. tripal_cv_obo_quiterror("Cannot find or add the database reference (dbxref)");
  814. }
  815. // finally add the cvterm_dbxref but first check to make sure it exists
  816. $values = array(
  817. 'cvterm_id' => $cvterm->cvterm_id,
  818. 'dbxref_id' => $dbxref->dbxref_id,
  819. );
  820. $options = array('statement_name' => 'sel_cvtermdbxref_cvdb');
  821. $result = tripal_core_chado_select('cvterm_dbxref', array('*'), $values, $options);
  822. if (count($result) == 0) {
  823. $ins_options = array(
  824. 'statement_name' => 'ins_cvtermdbxref_cvdb',
  825. 'return_record' => FALSE
  826. );
  827. $result = tripal_core_chado_insert('cvterm_dbxref', $values, $ins_options);
  828. if (!$result){
  829. tripal_cv_obo_quiterror("Cannot add cvterm_dbxref: $xref");
  830. return FALSE;
  831. }
  832. }
  833. return TRUE;
  834. }
  835. /**
  836. * Add property to CVterm
  837. * @ingroup tripal_obo_loader
  838. */
  839. function tripal_cv_obo_add_cvterm_prop($cvterm, $property, $value, $rank) {
  840. // make sure the 'cvterm_property_type' CV exists
  841. $cv = tripal_cv_add_cv('cvterm_property_type', '');
  842. if (!$cv) {
  843. tripal_cv_obo_quiterror("Cannot add/find cvterm_property_type cvterm");
  844. }
  845. // get the property type cvterm. If it doesn't exist then we want to add it
  846. $values = array(
  847. 'name' => $property,
  848. 'cv_id' => $cv->cv_id,
  849. );
  850. $options = array('statement_name' => 'sel_cvterm_nacv_na');
  851. $results = tripal_core_chado_select('cvterm', array('*'), $values, $options);
  852. if (count($results) == 0) {
  853. $term = array(
  854. 'name' => $property,
  855. 'id' => "internal:$property",
  856. 'definition' => '',
  857. 'is_obsolete' => 0,
  858. );
  859. $cvproptype = tripal_cv_add_cvterm($term, $cv->name, 0, 0);
  860. if (!$cvproptype) {
  861. tripal_cv_obo_quiterror("Cannot add cvterm property: internal:$property");
  862. return FALSE;
  863. }
  864. }
  865. else {
  866. $cvproptype = $results[0];
  867. }
  868. // remove any properties that currently exist for this term. We'll reset them
  869. if ($rank == 0) {
  870. $values = array('cvterm_id' => $cvterm->cvterm_id);
  871. $options = array('statement_name' => 'del_cvtermprop_cv');
  872. $success = tripal_core_chado_delete('cvtermprop', $values, $options);
  873. if (!$success) {
  874. tripal_cv_obo_quiterror("Could not remove existing properties to update property $property for term\n");
  875. return FALSE;
  876. }
  877. }
  878. // now add the property
  879. $values = array(
  880. 'cvterm_id' => $cvterm->cvterm_id,
  881. 'type_id' => $cvproptype->cvterm_id,
  882. 'value' => $value,
  883. 'rank' => $rank,
  884. );
  885. $options = array(
  886. 'statement_name' => 'ins_cvtermprop_cvtyvara',
  887. 'return_record' => FALSE,
  888. );
  889. $result = tripal_core_chado_insert('cvtermprop', $values, $options);
  890. if (!$result) {
  891. tripal_cv_obo_quiterror("Could not add property $property for term\n");
  892. return FALSE;
  893. }
  894. return TRUE;
  895. }
  896. /**
  897. * Add Database Reference
  898. * @ingroup tripal_obo_loader
  899. */
  900. function tripal_cv_obo_add_dbxref($db_id, $accession, $version='', $description='') {
  901. // check to see if the dbxref exists if not, add it
  902. $values = array(
  903. 'db_id' => $db_id,
  904. 'accession' => $accession,
  905. );
  906. $options = array('statement_name' => 'sel_dbxref_idac');
  907. $result = tripal_core_chado_select('dbxref', array('dbxref_id'), $values, $options);
  908. if (count($result) == 0){
  909. $ins_values = array(
  910. 'db_id' => $db_id,
  911. 'accession' => $accession,
  912. 'version' => $version,
  913. 'description' => $description,
  914. );
  915. $ins_options = array(
  916. 'statement_name' => 'ins_dbxref_idacvede',
  917. 'return_record' => FALSE
  918. );
  919. $result = tripal_core_chado_insert('dbxref', $ins_values, $ins_options);
  920. if (!$result) {
  921. tripal_cv_obo_quiterror("Failed to insert the dbxref record $accession");
  922. return FALSE;
  923. }
  924. $result = tripal_core_chado_select('dbxref', array('dbxref_id'), $values, $options);
  925. }
  926. return $result[0];
  927. }