tripal_cv.obo_loader.inc 38 KB

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