tripal_cv.obo_loader.inc 47 KB

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