tripal_cv.obo_loader.inc 48 KB

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