obo_loader.inc 31 KB

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