obo_loader.inc 31 KB

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