tripal_chado.obo_loader.inc 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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_chado
  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_chado/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_chado_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("/^https:\/\//", $obo->path) or
  330. preg_match("/^http:\/\//", $obo->path) or
  331. preg_match("/^ftp:\/\//", $obo->path)) {
  332. tripal_chado_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_chado_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_chado_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_chado_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_chado_load_obo_v1_2($file, $jobid, $newcvs);
  377. if ($success) {
  378. // update the cvtermpath table
  379. tripal_chado_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_chado_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_chado_load_obo_v1_2($temp, $jobid, $newcvs);
  423. if ($success) {
  424. // update the cvtermpath table
  425. tripal_chado_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_chado_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_chado_load_obo_v1_2_id,
  453. * tripal_chado_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_chado_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. // parse the obo file
  483. $default_db = tripal_cv_obo_parse($file, $header, $jobid);
  484. // add the CV for this ontology to the database. The v1.2 definition
  485. // specifies a 'default-namespace' to be used if a 'namespace' is not
  486. // present for each stanza. Some ontologies have adopted the v1.4 method
  487. // in their v1.2 files and not including it.
  488. if (array_key_exists('default-namespace', $header)) {
  489. $defaultcv = tripal_insert_cv($header['default-namespace'][0], '');
  490. if (!$defaultcv) {
  491. tripal_cv_obo_quiterror('Cannot add namespace ' . $header['default-namespace'][0]);
  492. }
  493. $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
  494. }
  495. // if the 'default-namespace' is missing
  496. else {
  497. // look to see if an 'ontology' key is present. It is part of the v1.4
  498. // specification so it shouldn't be in the file, but just in case
  499. if (array_key_exists('ontology', $header)) {
  500. $defaultcv = tripal_insert_cv(strtoupper($header['ontology'][0]), '');
  501. if (!$defaultcv) {
  502. tripal_cv_obo_quiterror('Cannot add namespace ' . strtoupper($header['ontology'][0]));
  503. }
  504. $newcvs[strtoupper(strtoupper($header['ontology'][0]))] = $defaultcv->cv_id;
  505. }
  506. else {
  507. tripal_cv_obo_quiterror("Could not find a namespace for this OBO file.");
  508. }
  509. 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.",
  510. array('%vocab' => $defaultcv->name), WATCHDOG_WARNING);
  511. }
  512. // add any typedefs to the vocabulary first
  513. print "\nStep 2: Loading type defs...\n";
  514. tripal_cv_obo_load_typedefs($defaultcv, $newcvs, $default_db, $jobid);
  515. // next add terms to the vocabulary
  516. print "\nStep 3: Loading terms...\n";
  517. if (!tripal_cv_obo_process_terms($defaultcv, $jobid, $newcvs, $default_db)) {
  518. tripal_cv_obo_quiterror('Cannot add terms from this ontology');
  519. }
  520. }
  521. catch (Exception $e) {
  522. $transaction->rollback();
  523. print "\n"; // make sure we start errors on new line
  524. print "FAILED. Rolling back database changes...\n";
  525. watchdog_exception('T_obo_loader', $e);
  526. return FALSE;
  527. }
  528. return TRUE;
  529. }
  530. /**
  531. * Immediately terminates loading of the OBO file.
  532. *
  533. * @param $message
  534. * The error message to present to the user
  535. *
  536. * @ingroup tripal_obo_loader
  537. */
  538. function tripal_cv_obo_quiterror($message) {
  539. tripal_report_error("T_obo_loader", TRIPAL_ERROR, $message, array());
  540. exit;
  541. }
  542. /**
  543. * OBO files are divided into a typedefs terms section and vocabulary terms section.
  544. * This function loads the typedef terms from the OBO.
  545. *
  546. * @param $defaultcv
  547. * A database object containing a record from the cv table for the
  548. * default controlled vocabulary
  549. * @param $newcvs
  550. * An associative array of controlled vocabularies for this OBO. The key must be
  551. * the name of the vocabulary and the value the cv_id from the cv table of chado.
  552. * @param $default_db
  553. * The name of the default database.
  554. * @param $jobid
  555. * The job_id of the job from the Tripal jobs management system.
  556. *
  557. * @ingroup tripal_obo_loader
  558. */
  559. function tripal_cv_obo_load_typedefs($defaultcv, $newcvs, $default_db, $jobid) {
  560. $sql = "SELECT * FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  561. $typedefs = chado_query($sql);
  562. $sql = "
  563. SELECT count(*) as num_terms
  564. FROM {tripal_obo_temp}
  565. WHERE type = 'Typedef'
  566. ";
  567. $result = chado_query($sql)->fetchObject();
  568. $count = $result->num_terms;
  569. // calculate the interval for updates
  570. $interval = intval($count * 0.0001);
  571. if ($interval < 1) {
  572. $interval = 1;
  573. }
  574. $i = 0;
  575. foreach ($typedefs as $typedef) {
  576. $term = unserialize(base64_decode($typedef->stanza));
  577. // update the job status every interval
  578. if ($jobid and $i % $interval == 0) {
  579. $complete = ($i / $count) * 33.33333333;
  580. tripal_set_job_progress($jobid, intval($complete + 33.33333333));
  581. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  582. }
  583. tripal_cv_obo_process_term($term, $defaultcv->name, 1, $newcvs, $default_db);
  584. $i++;
  585. }
  586. // set the final status
  587. if ($jobid) {
  588. if ($count > 0) {
  589. $complete = ($i / $count) * 33.33333333;
  590. }
  591. else {
  592. $complete = 33.33333333;
  593. }
  594. tripal_set_job_progress($jobid, intval($complete + 33.33333333));
  595. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  596. }
  597. return 1;
  598. }
  599. /**
  600. * OBO files are divided into a typedefs section and a terms section. This
  601. * function loads the typedef terms from the OBO.
  602. *
  603. * @param $defaultcv
  604. * A database object containing a record from the cv table for the
  605. * default controlled vocabulary
  606. * @param $jobid
  607. * The job_id of the job from the Tripal jobs management system.
  608. * @param $newcvs
  609. * An associative array of controlled vocabularies for this OBO. The key must be
  610. * the name of the vocabulary and the value the cv_id from the cv table of chado.
  611. * @param $default_db
  612. * The name of the default database.
  613. * @ingroup tripal_obo_loader
  614. */
  615. function tripal_cv_obo_process_terms($defaultcv, $jobid = NULL, &$newcvs, $default_db) {
  616. $i = 0;
  617. // iterate through each term from the OBO file and add it
  618. $sql = "
  619. SELECT * FROM {tripal_obo_temp}
  620. WHERE type = 'Term'
  621. ORDER BY id
  622. ";
  623. $terms = chado_query($sql);
  624. $sql = "
  625. SELECT count(*) as num_terms
  626. FROM {tripal_obo_temp}
  627. WHERE type = 'Term'
  628. ";
  629. $result = chado_query($sql)->fetchObject();
  630. $count = $result->num_terms;
  631. // calculate the interval for updates
  632. $interval = intval($count * 0.0001);
  633. if ($interval < 1) {
  634. $interval = 1;
  635. }
  636. foreach ($terms as $t) {
  637. $term = unserialize(base64_decode($t->stanza));
  638. // update the job status every interval
  639. if ($jobid and $i % $interval == 0) {
  640. $complete = ($i / $count) * 33.33333333;
  641. tripal_set_job_progress($jobid, intval($complete + 66.666666));
  642. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  643. }
  644. // add/update this term
  645. if (!tripal_cv_obo_process_term($term, $defaultcv->name, 0, $newcvs, $default_db)) {
  646. tripal_cv_obo_quiterror("Failed to process terms from the ontology");
  647. }
  648. $i++;
  649. }
  650. // set the final status
  651. if ($jobid) {
  652. if ($count > 0) {
  653. $complete = ($i / $count) * 33.33333333;
  654. }
  655. else {
  656. $complete = 33.33333333;
  657. }
  658. tripal_set_job_progress($jobid, intval($complete + 66.666666));
  659. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  660. }
  661. return 1;
  662. }
  663. /**
  664. * Uses the provided term array to add/update information to Chado about the
  665. * term including the term, dbxref, synonyms, properties, and relationships.
  666. *
  667. * @param $term
  668. * An array representing the cvterm.
  669. * @param $defaultcv
  670. * The name of the default controlled vocabulary
  671. * @is_relationship
  672. * Set to 1 if this term is a relationship term
  673. * @default_db
  674. * The name of the default database.
  675. *
  676. * @ingroup tripal_obo_loader
  677. */
  678. function tripal_cv_obo_process_term($term, $defaultcv, $is_relationship = 0, &$newcvs, $default_db) {
  679. // make sure we have a namespace for this term
  680. if (!array_key_exists('namespace', $term) and !($defaultcv or $defaultcv == '')) {
  681. tripal_cv_obo_quiterror("Cannot add the term: no namespace defined. " . $term['id'][0]);
  682. }
  683. // construct the term array for sending to the tripal_chado_add_cvterm function
  684. // for adding a new cvterm
  685. $t = array();
  686. $t['id'] = $term['id'][0];
  687. $t['name'] = $term['name'][0];
  688. if (array_key_exists('def', $term)) {
  689. $t['definition'] = $term['def'][0];
  690. }
  691. if (array_key_exists('subset', $term)) {
  692. $t['subset'] = $term['subset'][0];
  693. }
  694. if (array_key_exists('namespace', $term)) {
  695. $t['namespace'] = $term['namespace'][0];
  696. }
  697. if (array_key_exists('is_obsolete', $term)) {
  698. $t['is_obsolete'] = $term['is_obsolete'][0];
  699. }
  700. $t['cv_name'] = $defaultcv;
  701. $t['is_relationship'] = $is_relationship;
  702. $t['db_name'] = $default_db;
  703. // add the cvterm
  704. $cvterm = tripal_insert_cvterm($t, array('update_existing' => TRUE));
  705. if (!$cvterm) {
  706. tripal_cv_obo_quiterror("Cannot add the term " . $term['id'][0]);
  707. }
  708. if (array_key_exists('namespace', $term)) {
  709. $newcvs[$term['namespace'][0]] = $cvterm->cv_id;
  710. }
  711. // now handle other properites
  712. if (array_key_exists('is_anonymous', $term)) {
  713. //print "WARNING: unhandled tag: is_anonymous\n";
  714. }
  715. if (array_key_exists('alt_id', $term)) {
  716. foreach ($term['alt_id'] as $alt_id) {
  717. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $alt_id)) {
  718. tripal_cv_obo_quiterror("Cannot add alternate id $alt_id");
  719. }
  720. }
  721. }
  722. if (array_key_exists('subset', $term)) {
  723. //print "WARNING: unhandled tag: subset\n";
  724. }
  725. // add synonyms for this cvterm
  726. if (array_key_exists('synonym', $term)) {
  727. if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
  728. tripal_cv_obo_quiterror("Cannot add synonyms");
  729. }
  730. }
  731. // reformat the deprecated 'exact_synonym, narrow_synonym, and broad_synonym'
  732. // types to be of the v1.2 standard
  733. if (array_key_exists('exact_synonym', $term) or array_key_exists('narrow_synonym', $term) or array_key_exists('broad_synonym', $term)) {
  734. if (array_key_exists('exact_synonym', $term)) {
  735. foreach ($term['exact_synonym'] as $synonym) {
  736. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  737. $term['synonym'][] = $new;
  738. }
  739. }
  740. if (array_key_exists('narrow_synonym', $term)) {
  741. foreach ($term['narrow_synonym'] as $synonym) {
  742. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  743. $term['synonym'][] = $new;
  744. }
  745. }
  746. if (array_key_exists('broad_synonym', $term)) {
  747. foreach ($term['broad_synonym'] as $synonym) {
  748. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  749. $term['synonym'][] = $new;
  750. }
  751. }
  752. if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
  753. tripal_cv_obo_quiterror("Cannot add/update synonyms");
  754. }
  755. }
  756. // add the comment to the cvtermprop table
  757. if (array_key_exists('comment', $term)) {
  758. $comments = $term['comment'];
  759. $j = 0;
  760. foreach ($comments as $comment) {
  761. if (!tripal_cv_obo_add_cvterm_prop($cvterm, 'comment', $comment, $j)) {
  762. tripal_cv_obo_quiterror("Cannot add/update cvterm property");
  763. }
  764. $j++;
  765. }
  766. }
  767. // add any other external dbxrefs
  768. if (array_key_exists('xref', $term)) {
  769. foreach ($term['xref'] as $xref) {
  770. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  771. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  772. }
  773. }
  774. }
  775. if (array_key_exists('xref_analog', $term)) {
  776. foreach ($term['xref_analog'] as $xref) {
  777. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  778. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  779. }
  780. }
  781. }
  782. if (array_key_exists('xref_unk', $term)) {
  783. foreach ($term['xref_unk'] as $xref) {
  784. if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
  785. tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
  786. }
  787. }
  788. }
  789. // add is_a relationships for this cvterm
  790. if (array_key_exists('is_a', $term)) {
  791. foreach ($term['is_a'] as $is_a) {
  792. if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, 'is_a', $is_a, $is_relationship, $default_db)) {
  793. tripal_cv_obo_quiterror("Cannot add relationship is_a: $is_a");
  794. }
  795. }
  796. }
  797. if (array_key_exists('intersection_of', $term)) {
  798. //print "WARNING: unhandled tag: intersection_of\n";
  799. }
  800. if (array_key_exists('union_of', $term)) {
  801. //print "WARNING: unhandled tag: union_on\n";
  802. }
  803. if (array_key_exists('disjoint_from', $term)) {
  804. //print "WARNING: unhandled tag: disjoint_from\n";
  805. }
  806. if (array_key_exists('relationship', $term)) {
  807. foreach ($term['relationship'] as $value) {
  808. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  809. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  810. if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, $rel, $object, $is_relationship, $default_db)) {
  811. tripal_cv_obo_quiterror("Cannot add relationship $rel: $object");
  812. }
  813. }
  814. }
  815. if (array_key_exists('replaced_by', $term)) {
  816. //print "WARNING: unhandled tag: replaced_by\n";
  817. }
  818. if (array_key_exists('consider', $term)) {
  819. //print "WARNING: unhandled tag: consider\n";
  820. }
  821. if (array_key_exists('use_term', $term)) {
  822. //print "WARNING: unhandled tag: user_term\n";
  823. }
  824. if (array_key_exists('builtin', $term)) {
  825. //print "WARNING: unhandled tag: builtin\n";
  826. }
  827. return 1;
  828. }
  829. /**
  830. * Adds a cvterm relationship
  831. *
  832. * @param $cvterm
  833. * A database object for the cvterm
  834. * @param $rel
  835. * The relationship name
  836. * @param $objname
  837. * The relationship term name
  838. * @param $defaultcv
  839. * A database object containing a record from the cv table for the
  840. * default controlled vocabulary
  841. * @object_is_relationship
  842. * Set to 1 if this term is a relationship term
  843. * @default_db
  844. * The name of the default database.
  845. *
  846. * @ingroup tripal_obo_loader
  847. */
  848. function tripal_cv_obo_add_relationship($cvterm, $defaultcv, $rel,
  849. $objname, $object_is_relationship = 0, $default_db = 'OBO_REL') {
  850. // make sure the relationship cvterm exists
  851. $term = array(
  852. 'name' => $rel,
  853. 'id' => "$default_db:$rel",
  854. 'definition' => '',
  855. 'is_obsolete' => 0,
  856. 'cv_name' => $defaultcv,
  857. 'is_relationship' => TRUE,
  858. 'db_naame' => $default_db
  859. );
  860. $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  861. if (!$relcvterm) {
  862. // if the relationship term couldn't be found in the default_db provided
  863. // then do on more check to find it in the relationship ontology
  864. $term = array(
  865. 'name' => $rel,
  866. 'id' => "OBO_REL:$rel",
  867. 'definition' => '',
  868. 'is_obsolete' => 0,
  869. 'cv_name' => $defaultcv,
  870. 'is_relationship' => TRUE,
  871. 'db_name' => 'OBO_REL'
  872. );
  873. $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  874. if (!$relcvterm) {
  875. tripal_cv_obo_quiterror("Cannot find the relationship term in the current ontology or in the relationship ontology: $rel\n");
  876. }
  877. }
  878. // get the object term
  879. $oterm = tripal_cv_obo_get_term($objname);
  880. if (!$oterm) {
  881. tripal_cv_obo_quiterror("Could not find object term $objname\n");
  882. }
  883. $objterm = array();
  884. $objterm['id'] = $oterm['id'][0];
  885. $objterm['name'] = $oterm['name'][0];
  886. if (array_key_exists('def', $oterm)) {
  887. $objterm['definition'] = $oterm['def'][0];
  888. }
  889. if (array_key_exists('subset', $oterm)) {
  890. $objterm['subset'] = $oterm['subset'][0];
  891. }
  892. if (array_key_exists('namespace', $oterm)) {
  893. $objterm['namespace'] = $oterm['namespace'][0];
  894. }
  895. if (array_key_exists('is_obsolete', $oterm)) {
  896. $objterm['is_obsolete'] = $oterm['is_obsolete'][0];
  897. }
  898. $objterm['cv_name' ] = $defaultcv;
  899. $objterm['is_relationship'] = $object_is_relationship;
  900. $objterm['db_name'] = $default_db;
  901. $objcvterm = tripal_insert_cvterm($objterm, array('update_existing' => TRUE));
  902. if (!$objcvterm) {
  903. tripal_cv_obo_quiterror("Cannot add cvterm " . $oterm['name'][0]);
  904. }
  905. // check to see if the cvterm_relationship already exists, if not add it
  906. $values = array(
  907. 'type_id' => $relcvterm->cvterm_id,
  908. 'subject_id' => $cvterm->cvterm_id,
  909. 'object_id' => $objcvterm->cvterm_id
  910. );
  911. $result = chado_select_record('cvterm_relationship', array('*'), $values);
  912. if (count($result) == 0) {
  913. $options = array('return_record' => FALSE);
  914. $success = chado_insert_record('cvterm_relationship', $values, $options);
  915. if (!$success) {
  916. tripal_cv_obo_quiterror("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
  917. }
  918. }
  919. return TRUE;
  920. }
  921. /**
  922. * Retreives the term array from the temp loading table for a given term id.
  923. *
  924. * @param id
  925. * The id of the term to retrieve
  926. *
  927. * @ingroup tripal_obo_loader
  928. */
  929. function tripal_cv_obo_get_term($id) {
  930. $values = array('id' => $id);
  931. $result = chado_select_record('tripal_obo_temp', array('stanza'), $values);
  932. if (count($result) == 0) {
  933. return FALSE;
  934. }
  935. return unserialize(base64_decode($result[0]->stanza));
  936. }
  937. /**
  938. * Adds the synonyms to a term
  939. *
  940. * @param term
  941. * An array representing the cvterm. It must have a 'synonym' key/value pair.
  942. * @param cvterm
  943. * The database object of the cvterm to which the synonym will be added.
  944. *
  945. * @ingroup tripal_obo_loader
  946. */
  947. function tripal_cv_obo_add_synonyms($term, $cvterm) {
  948. // make sure we have a 'synonym_type' vocabulary
  949. $syncv = tripal_insert_cv(
  950. 'synonym_type',
  951. 'A local vocabulary added for synonym types.'
  952. );
  953. // now add the synonyms
  954. if (array_key_exists('synonym', $term)) {
  955. foreach ($term['synonym'] as $synonym) {
  956. // separate out the synonym definition and the synonym type
  957. $def = preg_replace('/^\s*"(.*)"\s*.*$/', '\1', $synonym);
  958. // the scope will be 'EXACT', etc...
  959. $scope = drupal_strtolower(preg_replace('/^.*"\s+(.*?)\s+.*$/', '\1', $synonym));
  960. if (!$scope) { // if no scope then default to 'exact'
  961. $scope = 'exact';
  962. }
  963. // make sure the synonym type exists in the 'synonym_type' vocabulary
  964. $values = array(
  965. 'name' => $scope,
  966. 'cv_id' => array(
  967. 'name' => 'synonym_type',
  968. ),
  969. );
  970. $syntype = tripal_get_cvterm($values);
  971. // if it doesn't exist then add it
  972. if (!$syntype) {
  973. // build a 'term' object so we can add the missing term
  974. $term = array(
  975. 'name' => $scope,
  976. 'id' => "synonym_type:$scope",
  977. 'definition' => '',
  978. 'is_obsolete' => 0,
  979. 'cv_name' => $syncv->name,
  980. 'is_relationship' => FALSE
  981. );
  982. $syntype = tripal_insert_cvterm($term, array('update_existing' => TRUE));
  983. if (!$syntype) {
  984. tripal_cv_obo_quiterror("Cannot add synonym type: internal:$scope");
  985. }
  986. }
  987. // make sure the synonym doesn't already exists
  988. $values = array(
  989. 'cvterm_id' => $cvterm->cvterm_id,
  990. 'synonym' => $def
  991. );
  992. $results = chado_select_record('cvtermsynonym', array('*'), $values);
  993. if (count($results) == 0) {
  994. $values = array(
  995. 'cvterm_id' => $cvterm->cvterm_id,
  996. 'synonym' => $def,
  997. 'type_id' => $syntype->cvterm_id
  998. );
  999. $options = array('return_record' => FALSE);
  1000. $success = chado_insert_record('cvtermsynonym', $values, $options);
  1001. if (!$success) {
  1002. tripal_cv_obo_quiterror("Failed to insert the synonym for term: $name ($def)");
  1003. }
  1004. }
  1005. // now add the dbxrefs for the synonym if we have a comma in the middle
  1006. // of a description then this will cause problems when splitting os lets
  1007. // just change it so it won't mess up our splitting and then set it back
  1008. // later.
  1009. /**
  1010. $synonym = preg_replace('/(".*?),\s(.*?")/','$1,_$2',$synonym);
  1011. $dbxrefs = preg_split("/, /",preg_replace('/^.*\[(.*?)\]$/','\1',$synonym));
  1012. foreach ($dbxrefs as $dbxref) {
  1013. $dbxref = preg_replace('/,_/',", ",$dbxref);
  1014. if ($dbxref) {
  1015. tripal_cv_obo_add_cvterm_dbxref($syn,$dbxref);
  1016. }
  1017. }
  1018. */
  1019. }
  1020. }
  1021. return TRUE;
  1022. }
  1023. /**
  1024. * Parse the OBO file and populate the templ loading table
  1025. *
  1026. * @param $file
  1027. * The path on the file system where the ontology can be found
  1028. * @param $header
  1029. * An array passed by reference that will be populated with the header
  1030. * information from the OBO file
  1031. * @param $jobid
  1032. * The job_id of the job from the Tripal jobs management system.
  1033. *
  1034. * @ingroup tripal_obo_loader
  1035. */
  1036. function tripal_cv_obo_parse($obo_file, &$header, $jobid) {
  1037. $in_header = 1;
  1038. $stanza = array();
  1039. $default_db = '';
  1040. $line_num = 0;
  1041. $num_read = 0;
  1042. $intv_read = 0;
  1043. $filesize = filesize($obo_file);
  1044. $interval = intval($filesize * 0.01);
  1045. if ($interval < 1) {
  1046. $interval = 1;
  1047. }
  1048. // iterate through the lines in the OBO file and parse the stanzas
  1049. $fh = fopen($obo_file, 'r');
  1050. while ($line = fgets($fh)) {
  1051. $line_num++;
  1052. $size = drupal_strlen($line);
  1053. $num_read += $size;
  1054. $intv_read += $size;
  1055. $line = trim($line);
  1056. // update the job status every 1% features
  1057. if ($jobid and $intv_read >= $interval) {
  1058. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  1059. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  1060. tripal_set_job_progress($jobid, intval(($num_read / $filesize) * 33.33333333));
  1061. $intv_read = 0;
  1062. }
  1063. // remove newlines
  1064. $line = rtrim($line);
  1065. // remove any special characters that may be hiding
  1066. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  1067. // skip empty lines
  1068. if (strcmp($line, '') == 0) {
  1069. continue;
  1070. }
  1071. //remove comments from end of lines
  1072. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line); // TODO: if the explamation is escaped
  1073. // at the first stanza we're out of header
  1074. if (preg_match('/^\s*\[/', $line)) {
  1075. $in_header = 0;
  1076. // store the stanza we just finished reading
  1077. if (sizeof($stanza) > 0) {
  1078. // add the term to the temp table
  1079. $values = array(
  1080. 'id' => $stanza['id'][0],
  1081. 'stanza' => base64_encode(serialize($stanza)),
  1082. 'type' => $type,
  1083. );
  1084. $success = chado_insert_record('tripal_obo_temp', $values);
  1085. if (!$success) {
  1086. tripal_report_error('T_obo_loader', "ERROR: Cannot insert stanza into temporary table.", array(), 'error');
  1087. exit;
  1088. }
  1089. }
  1090. // get the stanza type: Term, Typedef or Instance
  1091. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  1092. // start fresh with a new array
  1093. $stanza = array();
  1094. continue;
  1095. }
  1096. // break apart the line into the tag and value but ignore any escaped colons
  1097. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  1098. $pair = explode(":", $line, 2);
  1099. $tag = $pair[0];
  1100. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  1101. // if this is the ID then look for the default DB
  1102. $matches = array();
  1103. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  1104. $default_db = $matches[1];
  1105. }
  1106. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  1107. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  1108. if ($in_header) {
  1109. if (!array_key_exists($tag, $header)) {
  1110. $header[$tag] = array();
  1111. }
  1112. $header[$tag][] = $value;
  1113. }
  1114. else {
  1115. if (!array_key_exists($tag, $stanza)) {
  1116. $stanza[$tag] = array();
  1117. }
  1118. $stanza[$tag][] = $value;
  1119. }
  1120. }
  1121. // now add the last term in the file
  1122. if (sizeof($stanza) > 0) {
  1123. $values = array(
  1124. 'id' => $stanza['id'][0],
  1125. 'stanza' => base64_encode(serialize($stanza)),
  1126. 'type' => $type,
  1127. );
  1128. chado_insert_record('tripal_obo_temp', $values);
  1129. if (!$success) {
  1130. tripal_report_error('T_obo_loader', "ERROR: Cannot insert stanza into temporary table.", array(), 'error');
  1131. exit;
  1132. }
  1133. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  1134. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  1135. tripal_set_job_progress($jobid, intval(($num_read / $filesize) * 33.33333333));
  1136. }
  1137. return $default_db;
  1138. }
  1139. /**
  1140. * Adds a database reference to a cvterm
  1141. *
  1142. * @param cvterm
  1143. * The database object of the cvterm to which the synonym will be added.
  1144. * @param xref
  1145. * The cross refernce. It should be of the form from the OBO specification
  1146. *
  1147. * @ingroup tripal_obo_loader
  1148. */
  1149. function tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref) {
  1150. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  1151. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  1152. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  1153. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  1154. if (!$accession) {
  1155. tripal_cv_obo_quiterror();
  1156. tripal_report_error("T_obo_loader", TRIPAL_WARNING, "Cannot add a dbxref without an accession: '$xref'", NULL);
  1157. return FALSE;
  1158. }
  1159. // if the xref is a database link, handle that specially
  1160. if (strcmp($dbname, 'http') == 0) {
  1161. $accession = $xref;
  1162. $dbname = 'URL';
  1163. }
  1164. // add the database
  1165. $db = tripal_insert_db(array('name' => $dbname));
  1166. if (!$db) {
  1167. tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
  1168. }
  1169. // now add the dbxref
  1170. $dbxref = tripal_cv_obo_add_dbxref($db->db_id, $accession, '', $description);
  1171. if (!$dbxref) {
  1172. tripal_cv_obo_quiterror("Cannot find or add the database reference (dbxref)");
  1173. }
  1174. // finally add the cvterm_dbxref but first check to make sure it exists
  1175. $values = array(
  1176. 'cvterm_id' => $cvterm->cvterm_id,
  1177. 'dbxref_id' => $dbxref->dbxref_id,
  1178. );
  1179. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  1180. if (count($result) == 0) {
  1181. $ins_options = array('return_record' => FALSE);
  1182. $result = chado_insert_record('cvterm_dbxref', $values, $ins_options);
  1183. if (!$result) {
  1184. tripal_cv_obo_quiterror("Cannot add cvterm_dbxref: $xref");
  1185. return FALSE;
  1186. }
  1187. }
  1188. return TRUE;
  1189. }
  1190. /**
  1191. * Adds a property to a cvterm
  1192. *
  1193. * @param cvterm
  1194. * A database object for the cvterm to which properties will be added
  1195. * @param $property
  1196. * The name of the property to add
  1197. * @param $value
  1198. * The value of the property
  1199. * @param rank
  1200. * The rank of the property
  1201. *
  1202. * @ingroup tripal_obo_loader
  1203. */
  1204. function tripal_cv_obo_add_cvterm_prop($cvterm, $property, $value, $rank) {
  1205. // make sure the 'cvterm_property_type' CV exists
  1206. $cv = tripal_insert_cv('cvterm_property_type', '');
  1207. if (!$cv) {
  1208. tripal_cv_obo_quiterror("Cannot add/find cvterm_property_type cvterm");
  1209. }
  1210. // get the property type cvterm. If it doesn't exist then we want to add it
  1211. $values = array(
  1212. 'name' => $property,
  1213. 'cv_id' => $cv->cv_id,
  1214. );
  1215. $results = chado_select_record('cvterm', array('*'), $values);
  1216. if (count($results) == 0) {
  1217. $term = array(
  1218. 'name' => $property,
  1219. 'id' => "internal:$property",
  1220. 'definition' => '',
  1221. 'is_obsolete' => 0,
  1222. 'cv_name' => $cv->name,
  1223. 'is_relationship' => FALSE,
  1224. );
  1225. $cvproptype = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  1226. if (!$cvproptype) {
  1227. tripal_cv_obo_quiterror("Cannot add cvterm property: internal:$property");
  1228. return FALSE;
  1229. }
  1230. }
  1231. else {
  1232. $cvproptype = $results[0];
  1233. }
  1234. // remove any properties that currently exist for this term. We'll reset them
  1235. if ($rank == 0) {
  1236. $values = array('cvterm_id' => $cvterm->cvterm_id);
  1237. $success = chado_delete_record('cvtermprop', $values);
  1238. if (!$success) {
  1239. tripal_cv_obo_quiterror("Could not remove existing properties to update property $property for term\n");
  1240. return FALSE;
  1241. }
  1242. }
  1243. // now add the property
  1244. $values = array(
  1245. 'cvterm_id' => $cvterm->cvterm_id,
  1246. 'type_id' => $cvproptype->cvterm_id,
  1247. 'value' => $value,
  1248. 'rank' => $rank,
  1249. );
  1250. $options = array('return_record' => FALSE);
  1251. $result = chado_insert_record('cvtermprop', $values, $options);
  1252. if (!$result) {
  1253. tripal_cv_obo_quiterror("Could not add property $property for term\n");
  1254. return FALSE;
  1255. }
  1256. return TRUE;
  1257. }
  1258. /**
  1259. * Adds a database cross reference to a cvterm
  1260. *
  1261. * @param db_id
  1262. * The database ID of the cross reference
  1263. * @param accession
  1264. * The cross reference's accession
  1265. * @param $version
  1266. * The version of the dbxref
  1267. * @param $description
  1268. * The description of the cross reference
  1269. *
  1270. * @ingroup tripal_obo_loader
  1271. */
  1272. function tripal_cv_obo_add_dbxref($db_id, $accession, $version='', $description='') {
  1273. // check to see if the dbxref exists if not, add it
  1274. $values = array(
  1275. 'db_id' => $db_id,
  1276. 'accession' => $accession,
  1277. );
  1278. $result = chado_select_record('dbxref', array('dbxref_id'), $values);
  1279. if (count($result) == 0) {
  1280. $ins_values = array(
  1281. 'db_id' => $db_id,
  1282. 'accession' => $accession,
  1283. 'version' => $version,
  1284. 'description' => $description,
  1285. );
  1286. $ins_options = array('return_record' => FALSE);
  1287. $result = chado_insert_record('dbxref', $ins_values, $ins_options);
  1288. if (!$result) {
  1289. tripal_cv_obo_quiterror("Failed to insert the dbxref record $accession");
  1290. return FALSE;
  1291. }
  1292. $result = chado_select_record('dbxref', array('dbxref_id'), $values, $options);
  1293. }
  1294. return $result[0];
  1295. }
  1296. function tripal_cv_obo_form_ajax_callback($form, $form_state) {
  1297. return $form['obo_existing'];
  1298. }