obo_loader.inc 34 KB

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