OBOImporter.inc 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  1. <?php
  2. class OBOImporter extends TripalImporter {
  3. // --------------------------------------------------------------------------
  4. // EDITABLE STATIC CONSTANTS
  5. //
  6. // The following constants SHOULD be set for each descendent class. They are
  7. // used by the static functions to provide information to Drupal about
  8. // the field and it's default widget and formatter.
  9. // --------------------------------------------------------------------------
  10. /**
  11. * The name of this loader. This name will be presented to the site
  12. * user.
  13. */
  14. public static $name = 'OBO Vocabulary Loader';
  15. /**
  16. * The machine name for this loader. This name will be used to construct
  17. * the URL for the loader.
  18. */
  19. public static $machine_name = 'chado_obo_loader';
  20. /**
  21. * A brief description for this loader. This description will be
  22. * presented to the site user.
  23. */
  24. public static $description = 'Import vocabularies and terms in OBO format.';
  25. /**
  26. * An array containing the extensions of allowed file types.
  27. */
  28. public static $file_types = array('obo');
  29. /**
  30. * Provides information to the user about the file upload. Typically this
  31. * may include a description of the file types allowed.
  32. */
  33. public static $upload_description = 'Please provide the details for importing a new OBO file. The file must have a .obo extension.';
  34. /**
  35. * The title that should appear above the upload button.
  36. */
  37. public static $upload_title = 'New OBO File';
  38. /**
  39. * If the loader should require an analysis record. To maintain provenance
  40. * we should always indiate where the data we are uploading comes from.
  41. * The method that Tripal attempts to use for this by associating upload files
  42. * with an analysis record. The analysis record provides the details for
  43. * how the file was created or obtained. Set this to FALSE if the loader
  44. * should not require an analysis when loading. if $use_analysis is set to
  45. * true then the form values will have an 'analysis_id' key in the $form_state
  46. * array on submitted forms.
  47. */
  48. public static $use_analysis = FALSE;
  49. /**
  50. * If the $use_analysis value is set above then this value indicates if the
  51. * analysis should be required.
  52. */
  53. public static $require_analysis = TRUE;
  54. /**
  55. * Text that should appear on the button at the bottom of the importer
  56. * form.
  57. */
  58. public static $button_text = 'Import OBO File';
  59. /**
  60. * Indicates the methods that the file uploader will support.
  61. */
  62. public static $methods = array(
  63. // Allow the user to upload a file to the server.
  64. 'file_upload' => FALSE,
  65. // Allow the user to provide the path on the Tripal server for the file.
  66. 'file_local' => FALSE,
  67. // Allow the user to provide a remote URL for the file.
  68. 'file_remote' => FALSE,
  69. );
  70. /**
  71. * Be default, all loaders are automaticlly added to the Admin >
  72. * Tripal > Data Laders menu. However, if this loader should be
  73. * made available via a different menu path, then set it here. If the
  74. * value is empty then the path will be the default.
  75. */
  76. public static $menu_path = 'admin/tripal/loaders/chado_vocabs/obo_loader';
  77. public static $file_required = FALSE;
  78. /**
  79. * Keep track of vocabularies that have been added.
  80. *
  81. * @var array
  82. */
  83. private $obo_namespaces = array();
  84. /**
  85. * Holds the list of all CVs on this site. By storing them here it saves
  86. * us query time later.
  87. */
  88. private $all_cvs = [];
  89. /**
  90. * Holds the list of all DBs on this site. By storing them here it saves
  91. * us query time later.
  92. *
  93. * @var array
  94. */
  95. private $all_dbs = [];
  96. /**
  97. * When adding synonyms we need to know the cvterm_ids of the synonym types.
  98. * This array holds those.
  99. *
  100. * @var array
  101. */
  102. private $syn_types = [
  103. 'exact' => NULL,
  104. 'broad' => NULL,
  105. 'narrow' => NULL,
  106. 'related' => NULL,
  107. ];
  108. // An alternative cache to the temp_obo table.
  109. private $termStanzaCache = [
  110. 'ids' => [],
  111. 'count' => [
  112. 'Typedef' => 0,
  113. 'Term' => 0,
  114. 'Instance' => 0,
  115. ],
  116. 'types' => [
  117. 'Typedef' => [],
  118. 'Term' => [],
  119. 'Instance' => [],
  120. ],
  121. ];
  122. /**
  123. * Indicates how terms are cached. Values can be 'memory' or 'table'. If
  124. * 'memory' then the $termStanzaCache variable is used. If 'table', then the
  125. * tripal_obo_temp table is used.
  126. * @var string
  127. */
  128. private $cache_type = 'memory';
  129. /**
  130. * The default namespace for all terms that don't have a 'namespace' in their
  131. * term stanza.
  132. *
  133. * @var string
  134. */
  135. private $default_namespace = '';
  136. /**
  137. * The default database preix for this ontology.
  138. *
  139. * @var string
  140. */
  141. private $default_db = '';
  142. /**
  143. * An array of used cvterm objects so that we don't have to lookup them
  144. * up repeatedly.
  145. */
  146. private $used_terms = [];
  147. /**
  148. * An array of base IRIs returned from the EBI OLS lookup servcie. We
  149. * don't want to continually query OLS for the same ontology base IRIs.
  150. */
  151. private $baseIRIs = [];
  152. /**
  153. * A flag to keep track if the user was warned about slownesss when doing
  154. * EBI Lookups.
  155. *
  156. * @var string
  157. */
  158. private $ebi_warned = FALSE;
  159. /**
  160. * A flag that indicates if this ontology is just a subset of a much larger
  161. * one. Examples include the GO slims.
  162. *
  163. * @var string
  164. */
  165. private $is_subset = FALSE;
  166. /**
  167. * @see TripalImporter::form()
  168. */
  169. public function form($form, &$form_state) {
  170. // get a list of db from chado for user to choose
  171. $sql = "SELECT * FROM {tripal_cv_obo} ORDER BY name";
  172. $results = db_query($sql);
  173. $obos = array();
  174. $obos[] = 'Select a Vocabulary';
  175. foreach ($results as $obo) {
  176. $obos[$obo->obo_id] = $obo->name;
  177. }
  178. $obo_id = '';
  179. if (array_key_exists('values', $form_state)) {
  180. $obo_id = array_key_exists('obo_id', $form_state['values']) ? $form_state['values']['obo_id'] : '';
  181. }
  182. $form['instructions']['info'] = array(
  183. '#type' => 'item',
  184. '#markup' => t('This page allows you to load vocabularies and ontologies
  185. that are in OBO format. Once loaded, the terms from these
  186. vocabularies can be used to create content.
  187. You may use the form below to either reload a vocabulary that is already
  188. loaded (as when new updates to that vocabulary are available) or load a new
  189. vocabulary.'),
  190. );
  191. $form['obo_existing'] = array(
  192. '#type' => 'fieldset',
  193. '#title' => t('Use a Saved Ontology OBO Reference'),
  194. '#prefix' => '<span id="obo-existing-fieldset">',
  195. '#suffix' => '</span>'
  196. );
  197. $form['obo_existing']['existing_instructions']= array(
  198. '#type' => 'item',
  199. '#markup' => t('The vocabularies listed in the select box below have bene pre-populated
  200. upon installation of Tripal or have been previously loaded. Select one to edit
  201. its settings or submit for loading. You may reload any vocabulary that has
  202. already been loaded to retrieve any new updates.'),
  203. );
  204. $form['obo_existing']['obo_id'] = array(
  205. '#title' => t('Ontology OBO File Reference'),
  206. '#type' => 'select',
  207. '#options' => $obos,
  208. '#ajax' => array(
  209. 'callback' => 'tripal_cv_obo_form_ajax_callback',
  210. 'wrapper' => 'obo-existing-fieldset',
  211. ),
  212. '#description' => t('Select a vocabulary to import.')
  213. );
  214. // If the user has selected an OBO ID then get the form elements for
  215. // updating.
  216. if ($obo_id) {
  217. $uobo_name = '';
  218. $uobo_url = '';
  219. $uobo_file = '';
  220. $vocab = db_select('tripal_cv_obo', 't')
  221. ->fields('t', array('name', 'path'))
  222. ->condition('obo_id', $obo_id)
  223. ->execute()
  224. ->fetchObject();
  225. $uobo_name = $vocab->name;
  226. if (preg_match('/^http/', $vocab->path)) {
  227. $uobo_url = $vocab->path;
  228. }
  229. else {
  230. $uobo_file = trim($vocab->path);
  231. $matches = array();
  232. if (preg_match('/\{(.*?)\}/', $uobo_file, $matches)) {
  233. $modpath = drupal_get_path('module', $matches[1]);
  234. $uobo_file = preg_replace('/\{.*?\}/', $modpath, $uobo_file);
  235. }
  236. }
  237. // We don't want the previous value to remain. We want the new default to
  238. // show up, so remove the input values
  239. unset($form_state['input']['uobo_name']);
  240. unset($form_state['input']['uobo_url']);
  241. unset($form_state['input']['uobo_file']);
  242. $form['obo_existing']['uobo_name']= array(
  243. '#type' => 'textfield',
  244. '#title' => t('Vocabulary Name'),
  245. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  246. list above for use again later.'),
  247. '#default_value' => $uobo_name,
  248. );
  249. $form['obo_existing']['uobo_url']= array(
  250. '#type' => 'textfield',
  251. '#title' => t('Remote URL'),
  252. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  253. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  254. '#default_value' => $uobo_url,
  255. );
  256. $form['obo_existing']['uobo_file']= array(
  257. '#type' => 'textfield',
  258. '#title' => t('Local File'),
  259. '#description' => t('Please enter the file system path for an OBO
  260. definition file. If entering a path relative to
  261. the Drupal installation you may use a relative path that excludes the
  262. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  263. that Drupal relative paths have no preceeding slash.
  264. Otherwise, please provide the full path on the filesystem. The path
  265. must be accessible to the web server on which this Drupal instance is running.'),
  266. '#default_value' => $uobo_file,
  267. );
  268. $form['obo_existing']['update_obo_details'] = array(
  269. '#type' => 'submit',
  270. '#value' => 'Update Ontology Details',
  271. '#name' => 'update_obo_details'
  272. );
  273. }
  274. $form['obo_new'] = array(
  275. '#type' => 'fieldset',
  276. '#title' => t('Add a New Ontology OBO Reference'),
  277. '#collapsible' => TRUE,
  278. '#collapsed' => TRUE,
  279. );
  280. $form['obo_new']['path_instructions']= array(
  281. '#value' => t('Provide the name and path for the OBO file. If the vocabulary OBO file
  282. is stored local to the server provide a file name. If the vocabulry is stored remotely,
  283. provide a URL. Only provide a URL or a local file, not both.'),
  284. );
  285. $form['obo_new']['obo_name']= array(
  286. '#type' => 'textfield',
  287. '#title' => t('New Vocabulary Name'),
  288. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  289. list above for use again later. Additionally, if a default namespace is not provided in the OBO
  290. header this name will be used as the default_namespace.'),
  291. );
  292. $form['obo_new']['obo_url']= array(
  293. '#type' => 'textfield',
  294. '#title' => t('Remote URL'),
  295. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  296. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  297. );
  298. $form['obo_new']['obo_file']= array(
  299. '#type' => 'textfield',
  300. '#title' => t('Local File'),
  301. '#description' => t('Please enter the file system path for an OBO
  302. definition file. If entering a path relative to
  303. the Drupal installation you may use a relative path that excludes the
  304. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  305. that Drupal relative paths have no preceeding slash.
  306. Otherwise, please provide the full path on the filesystem. The path
  307. must be accessible to the web server on which this Drupal instance is running.'),
  308. );
  309. return $form;
  310. }
  311. /**
  312. * @see TripalImporter::formSubmit()
  313. */
  314. public function formSubmit($form, &$form_state) {
  315. $obo_id = $form_state['values']['obo_id'];
  316. $obo_name = trim($form_state['values']['obo_name']);
  317. $obo_url = trim($form_state['values']['obo_url']);
  318. $obo_file = trim($form_state['values']['obo_file']);
  319. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  320. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  321. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  322. // If the user requested to alter the details then do that.
  323. if ($form_state['clicked_button']['#name'] == 'update_obo_details') {
  324. $form_state['rebuild'] = TRUE;
  325. $success = db_update('tripal_cv_obo')
  326. ->fields(array(
  327. 'name' => $uobo_name,
  328. 'path' => $uobo_url ? $uobo_url : $uobo_file,
  329. ))
  330. ->condition('obo_id', $obo_id)
  331. ->execute();
  332. if ($success) {
  333. drupal_set_message(t("The vocabulary !vocab has been updated.", array('!vocab' => $uobo_name)));
  334. }
  335. else {
  336. drupal_set_message(t("The vocabulary !vocab could not be updated.", array('!vocab' => $uobo_name)), 'error');
  337. }
  338. }
  339. elseif (!empty($obo_name)) {
  340. $obo_id = db_insert('tripal_cv_obo')
  341. ->fields(array(
  342. 'name' => $obo_name,
  343. 'path' => $obo_url ? $obo_url : $obo_file,
  344. ))
  345. ->execute();
  346. // Add the obo_id to the form_state vaules.
  347. $form_state['values']['obo_id'] = $obo_id;
  348. if ($obo_id) {
  349. drupal_set_message(t("The vocabulary !vocab has been added.", array('!vocab' => $obo_name)));
  350. }
  351. else {
  352. $form_state['rebuild'] = TRUE;
  353. drupal_set_message(t("The vocabulary !vocab could not be added.", array('!vocab' => $obo_name)), 'error');
  354. }
  355. }
  356. }
  357. /**
  358. * @see TripalImporter::formValidate()
  359. */
  360. public function formValidate($form, &$form_state) {
  361. $obo_id = $form_state['values']['obo_id'];
  362. $obo_name = trim($form_state['values']['obo_name']);
  363. $obo_url = trim($form_state['values']['obo_url']);
  364. $obo_file = trim($form_state['values']['obo_file']);
  365. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  366. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  367. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  368. // Make sure if the name is changed it doesn't conflict with another OBO.
  369. if ($form_state['clicked_button']['#name'] == 'update_obo_details' or
  370. $form_state['clicked_button']['#name'] == 'update_load_obo') {
  371. // Get the current record
  372. $vocab = db_select('tripal_cv_obo', 't')
  373. ->fields('t', array('obo_id', 'name', 'path'))
  374. ->condition('name', $uobo_name)
  375. ->execute()
  376. ->fetchObject();
  377. if ($vocab and $vocab->obo_id != $obo_id) {
  378. form_set_error('uobo_name', 'The vocabulary name must be different from existing vocabularies');
  379. }
  380. // Make sure the file exists. First check if it is a relative path
  381. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $uobo_file;
  382. if (!file_exists($dfile)) {
  383. if (!file_exists($uobo_file)) {
  384. form_set_error('uobo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
  385. }
  386. }
  387. if (!$uobo_url and !$uobo_file) {
  388. form_set_error('uobo_url', 'Please provide a URL or a path for the vocabulary.');
  389. }
  390. if ($uobo_url and $uobo_file) {
  391. form_set_error('uobo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  392. }
  393. }
  394. if ($form_state['clicked_button']['#name'] == 'add_new_obo') {
  395. // Get the current record
  396. $vocab = db_select('tripal_cv_obo', 't')
  397. ->fields('t', array('obo_id', 'name', 'path'))
  398. ->condition('name', $obo_name)
  399. ->execute()
  400. ->fetchObject();
  401. if ($vocab) {
  402. form_set_error('obo_name', 'The vocabulary name must be different from existing vocabularies');
  403. }
  404. // Make sure the file exists. First check if it is a relative path
  405. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo_file;
  406. if (!file_exists($dfile)) {
  407. if (!file_exists($obo_file)) {
  408. form_set_error('obo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
  409. }
  410. }
  411. if (!$obo_url and !$obo_file) {
  412. form_set_error('obo_url', 'Please provide a URL or a path for the vocabulary.');
  413. }
  414. if ($obo_url and $obo_file) {
  415. form_set_error('obo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  416. }
  417. }
  418. }
  419. /**
  420. * @see TripalImporter::run()
  421. *
  422. * @param $details
  423. * The following arguments are supported:
  424. * - obo_id: (required) The ID of the ontology to be imported.
  425. */
  426. public function run() {
  427. $arguments = $this->arguments['run_args'];
  428. $obo_id = $arguments['obo_id'];
  429. // Make sure the $obo_id is valid
  430. $obo = db_select('tripal_cv_obo', 'tco')
  431. ->fields('tco')
  432. ->condition('obo_id', $obo_id)
  433. ->execute()
  434. ->fetchObject();
  435. if (!$obo) {
  436. throw new Exception("Invalid OBO ID provided: '$obo_id'.");
  437. }
  438. // Get the list of all CVs so we can save on lookups later
  439. $sql = "SELECT * FROM {cv} CV";
  440. $cvs = chado_query($sql);
  441. while ($cv = $cvs->fetchObject()) {
  442. $this->all_cvs[$cv->name] = $cv;
  443. }
  444. // Get the list of all DBs so we can save on lookups later
  445. $sql = "SELECT * FROM {db} DB";
  446. $dbs = chado_query($sql);
  447. while ($db = $dbs->fetchObject()) {
  448. $this->all_dbs[$db->name] = $db;
  449. }
  450. // Get the 'Subgroup' term that we will use for adding subsets.
  451. $term = chado_get_cvterm(['id' => 'NCIT:C25693']);
  452. $this->used_terms['NCIT:C25693'] = $term->cvterm_id;
  453. // Get the 'Comment' term that we will use for adding comments.
  454. $term = chado_get_cvterm(['id' => 'rdfs:comment']);
  455. $this->used_terms['rdfs:comment'] = $term->cvterm_id;
  456. // Make sure we have a 'synonym_type' vocabulary.
  457. $syn_cv = new ChadoRecord('cv');
  458. $syn_cv->setValues(['name' => 'synonym_type']);
  459. $syn_cv->save();
  460. $this->all_cvs['synonym_type'] = (object) $syn_cv->getValues();
  461. // Make sure we have a 'synonym_type' database.
  462. $syn_db = new ChadoRecord('db');
  463. $syn_db->setValues(['name' => 'synonym_type']);
  464. $syn_db->save();
  465. $this->all_dbs['synonym_type'] = (object) $syn_db->getValues();
  466. // Make sure the synonym types exists in the 'synonym_type' vocabulary.
  467. foreach (array_keys($this->syn_types) as $syn_type) {
  468. $syn_dbxref = new ChadoRecord('dbxref');
  469. $syn_dbxref->setValues([
  470. 'accession' => $syn_type,
  471. 'db_id' => $syn_db->getID(),
  472. ]);
  473. $syn_dbxref->save();
  474. $syn_term = new ChadoRecord('cvterm');
  475. $syn_term->setValues([
  476. 'name' => $syn_type,
  477. 'definition' => '',
  478. 'is_obsolete' => 0,
  479. 'cv_id' => $syn_cv->getID(),
  480. 'is_relationshiptype' => 0,
  481. 'dbxref_id' => $syn_dbxref->getID(),
  482. ]);
  483. $syn_term->save();
  484. $this->syn_types[$syn_type] = (object) $syn_term->getValues();
  485. }
  486. // Run the importer!
  487. $this->loadOBO_v1_2_id($obo);
  488. }
  489. /**
  490. * @see TripalImporter::postRun()
  491. *
  492. */
  493. public function postRun() {
  494. // Update the cv_root_mview materiailzed view.
  495. $this->logMessage("Updating the cv_root_mview materialized view...");
  496. $mview_id = tripal_get_mview_id('cv_root_mview');
  497. tripal_populate_mview($mview_id);
  498. $this->logMessage("Updating the db2cv_mview materialized view...");
  499. $mview_id = tripal_get_mview_id('db2cv_mview');
  500. tripal_populate_mview($mview_id);
  501. // Upate the cvtermpath table for each newly added CV.
  502. $this->logMessage("Updating cvtermpath table. This may take a while...");
  503. foreach ($this->obo_namespaces as $namespace => $cv_id) {
  504. $this->logMessage("- Loading paths for @vocab", array('@vocab' => $namespace));
  505. tripal_update_cvtermpath($cv_id);
  506. }
  507. }
  508. /**
  509. * A wrapper function for importing the user specified OBO file into Chado by
  510. * specifying the obo_id of the OBO. It requires that the file be in OBO v1.2
  511. * compatible format. This function is typically executed via the Tripal jobs
  512. * management after a user submits a job via the Load Onotloies form.
  513. *
  514. * @param $obo_id
  515. * An obo_id from the tripal_cv_obo file that specifies which OBO file to import
  516. * @ingroup tripal_obo_loader
  517. */
  518. private function loadOBO_v1_2_id($obo) {
  519. // Convert the module name to the real path if present
  520. if (preg_match("/\{(.*?)\}/", $obo->path, $matches)) {
  521. $module = $matches[1];
  522. $path = drupal_realpath(drupal_get_path('module', $module));
  523. $obo->path = preg_replace("/\{.*?\}/", $path, $obo->path);
  524. }
  525. // if the reference is for a remote URL then run the URL processing function
  526. if (preg_match("/^https:\/\//", $obo->path) or
  527. preg_match("/^http:\/\//", $obo->path) or
  528. preg_match("/^ftp:\/\//", $obo->path)) {
  529. $this->loadOBO_v1_2_url($obo->name, $obo->path, 0);
  530. }
  531. // if the reference is for a local file then run the file processing function
  532. else {
  533. // check to see if the file is located local to Drupal
  534. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
  535. if (file_exists($dfile)) {
  536. $this->loadOBO_v1_2_file($obo->name, $dfile, 0);
  537. }
  538. // if not local to Drupal, the file must be someplace else, just use
  539. // the full path provided
  540. else {
  541. if (file_exists($obo->path)) {
  542. $this->loadOBO_v1_2_file($obo->name, $obo->path, 0);
  543. }
  544. else {
  545. print "ERROR: could not find OBO file: '$obo->path'\n";
  546. }
  547. }
  548. }
  549. }
  550. /**
  551. * A wrapper function for importing the user specified OBO file into Chado by
  552. * specifying the filename and path of the OBO. It requires that the file be in OBO v1.2
  553. * compatible format. This function is typically executed via the Tripal jobs
  554. * management after a user submits a job via the Load Onotloies form.
  555. *
  556. * @param $obo_name
  557. * The name of the OBO (typially the ontology or controlled vocabulary name)
  558. * @param $file
  559. * The path on the file system where the ontology can be found
  560. * @param $is_new
  561. * Set to TRUE if this is a new ontology that does not yet exist in the
  562. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  563. *
  564. * @ingroup tripal_obo_loader
  565. */
  566. private function loadOBO_v1_2_file($obo_name, $file, $is_new = TRUE) {
  567. if ($is_new) {
  568. tripal_insert_obo($obo_name, $file);
  569. }
  570. $success = $this->loadOBO_v1_2($file, $obo_name);
  571. }
  572. /**
  573. * A wrapper function for importing the user specified OBO file into Chado by
  574. * specifying the remote URL of the OBO. It requires that the file be in OBO v1.2
  575. * compatible format. This function is typically executed via the Tripal jobs
  576. * management after a user submits a job via the Load Onotloies form.
  577. *
  578. * @param $obo_name
  579. * The name of the OBO (typially the ontology or controlled vocabulary name)
  580. * @param $url
  581. * The remote URL of the OBO file.
  582. * @param $is_new
  583. * Set to TRUE if this is a new ontology that does not yet exist in the
  584. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  585. *
  586. * @ingroup tripal_obo_loader
  587. */
  588. private function loadOBO_v1_2_url($obo_name, $url, $is_new = TRUE) {
  589. // first download the OBO
  590. $temp = tempnam(sys_get_temp_dir(), 'obo_');
  591. print "Downloading URL $url, saving to $temp\n";
  592. $url_fh = fopen($url, "r");
  593. $obo_fh = fopen($temp, "w");
  594. if (!$url_fh) {
  595. throw new Exception("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? " .
  596. " if you are unable to download the file you may manually downlod the OBO file and use the web interface to " .
  597. " specify the location of the file on your server.");
  598. }
  599. while (!feof($url_fh)) {
  600. fwrite($obo_fh, fread($url_fh, 255), 255);
  601. }
  602. fclose($url_fh);
  603. fclose($obo_fh);
  604. if ($is_new) {
  605. tripal_insert_obo($obo_name, $url);
  606. }
  607. // second, parse the OBO
  608. $this->loadOBO_v1_2($temp, $obo_name);
  609. // now remove the temp file
  610. unlink($temp);
  611. }
  612. /**
  613. * Imports a given OBO file into Chado. This function is usually called by
  614. * one of three wrapper functions: loadOBO_v1_2_id,
  615. * loadOBO_v1_2_file or tirpal_cv_load_obo_v1_2_url. But, it can
  616. * be called directly if the full path to an OBO file is available on the
  617. * file system.
  618. *
  619. * @param $flie
  620. * The full path to the OBO file on the file system
  621. *
  622. * @ingroup tripal_obo_loader
  623. */
  624. private function loadOBO_v1_2($file, $obo_name) {
  625. $header = array();
  626. $ret = array();
  627. // Empty the temp table.
  628. $this->clearTermStanzaCache();
  629. // Parse the obo file.
  630. $this->logMessage("Step 1: Preloading File $file...");
  631. $this->parse($file, $header);
  632. // Cache the relationships of terms.
  633. $this->logMessage("Step 2: Examining relationships...");
  634. $this->cacheRelationships();
  635. // Add any typedefs to the vocabulary first.
  636. $this->logMessage("Step 3: Loading type defs...");
  637. $this->processTypeDefs();
  638. // Next add terms to the vocabulary.
  639. $this->logMessage("Step 4: Loading terms...");
  640. $this->processTerms();
  641. // Empty the term cache.
  642. $this->logMessage("Step 5: Cleanup...");
  643. $this->clearTermStanzaCache();
  644. }
  645. /**
  646. * OBO files are divided into a typedefs terms section and vocabulary terms section.
  647. * This function loads the typedef terms from the OBO.
  648. *
  649. * @ingroup tripal_obo_loader
  650. */
  651. private function processTypeDefs() {
  652. $typedefs = $this->getCachedTermStanzas('Typedef');
  653. $count = $this->getCacheSize('Typedef');
  654. $this->setTotalItems($count);
  655. $this->setItemsHandled(0);
  656. $this->setInterval(5);
  657. $i = 1;
  658. foreach ($typedefs as $t) {
  659. // TODO: it would be better if we had a term iterator so that we
  660. // don't have to distinguish here between the table vs memory cache type.
  661. if ($this->cache_type == 'table') {
  662. $stanza = unserialize(base64_decode($t->stanza));
  663. }
  664. else {
  665. $stanza = $this->termStanzaCache['ids'][$t];
  666. }
  667. $this->setItemsHandled($i++);
  668. $this->processTerm($stanza, TRUE);
  669. }
  670. $this->setItemsHandled($i);
  671. return 1;
  672. }
  673. /**
  674. * This function loads all of the [Term] termsfrom the OBO.
  675. */
  676. private function processTerms() {
  677. $i = 0;
  678. $external = FALSE;
  679. $terms = $this->getCachedTermStanzas('Term');
  680. $count = $this->getCacheSize('Term');
  681. $this->setTotalItems($count);
  682. $this->setItemsHandled(0);
  683. $this->setInterval(1);
  684. // Iterate through the terms.
  685. foreach ($terms as $t) {
  686. // TODO: it would be better if we had a term iterator so that we
  687. // don't have to distringuish here between the table vs memory cache type.
  688. if ($this->cache_type == 'table') {
  689. $term = unserialize(base64_decode($t->stanza));
  690. }
  691. else {
  692. $term = $this->termStanzaCache['ids'][$t];
  693. }
  694. $this->setItemsHandled($i);
  695. // Add/update this term.
  696. $this->processTerm($term, FALSE);
  697. $i++;
  698. }
  699. $this->setItemsHandled($i);
  700. return 1;
  701. }
  702. /**
  703. * Sets the default CV and DB for this loader.
  704. *
  705. * Unfortunately, not all OBOs include both the 'ontology' and the
  706. * 'default-namespace' in their headers, so we have to do our best to
  707. * work out what these two should be.
  708. *
  709. */
  710. private function setDefaults($header) {
  711. $short_name = '';
  712. $namespace = '';
  713. // Get the 'ontology' and 'default-namespace' headers. Unfortunately,
  714. // not all OBO files contain these.
  715. if (array_key_exists('ontology', $header)) {
  716. $short_name = strtoupper($header['ontology'][0]);
  717. }
  718. if (array_key_exists('default-namespace', $header)) {
  719. $namespace = $header['default-namespace'][0];
  720. }
  721. // The OBO specification allows the 'ontology' header tag to be nested for
  722. // subsets (e.g. go/subsets/goslim_plant). We need to simplify that down
  723. // to the top-level item.
  724. $matches = [];
  725. if (preg_match('/^(.+?)\/.*/', $short_name, $matches)) {
  726. $short_name = $matches[1];
  727. $this->is_subset = TRUE;
  728. }
  729. // If we have the DB short name (or ontology header) but not the default
  730. // namespace then we may be able to find it via an EBI lookup.
  731. if (!$namespace and $short_name) {
  732. $namespace = $this->findEBIOntologyNamespace($short_name);
  733. }
  734. // If we have the namespace but not the short name then we have to
  735. // do a few tricks to try and find it.
  736. if ($namespace and !$short_name) {
  737. // First see if we've seen this ontology before and get it's currently
  738. // loaded database.
  739. $sql = "SELECT dbname FROM {db2cv_mview} WHERE cvname = :cvname";
  740. $short_name = chado_query($sql, [':cvname' => $namespace])->fetchField();
  741. if (!$short_name and array_key_exists('namespace-id-rule', $header)) {
  742. $matches = [];
  743. if (preg_match('/^.*\s(.+?):.+$/', $header['namespace-id-rule'][0],$matches)){
  744. $short_name = $matches[1];
  745. }
  746. }
  747. // Try the EBI Lookup: still experimental.
  748. if (!$short_name) {
  749. //$short_name = $this->findEBIOntologyPrefix($namespace);
  750. }
  751. }
  752. // If we can't find the namespace or the short_name then bust.
  753. if (!$namespace and !$short_name) {
  754. throw new ErrorException('Cannot determine the namespace or ontology prefix from this OBO file. It is missing both the "default-namespace" and "ontology" headers.');
  755. }
  756. // Set the defaults.
  757. $this->default_namespace = $namespace;
  758. $this->default_db = $short_name;
  759. $this->addDB($this->default_db);
  760. $this->addCV($this->default_namespace);
  761. }
  762. /**
  763. * This function searches EBI to find the ontology details for this OBO.
  764. *
  765. * @param $ontology
  766. * The ontology name from the OBO headers.
  767. *
  768. * @throws Exception
  769. */
  770. private function findEBIOntologyNamespace($ontology) {
  771. // Check if the EBI ontology search has this ontology:
  772. try {
  773. $results = $this->oboEbiLookup($ontology, 'ontology');
  774. if (array_key_exists('default-namespace', $results['config']['annotations'])) {
  775. $namespace = $results['config']['annotations']['default-namespace'];
  776. if (is_array($namespace)) {
  777. $namespace = $namespace[0];
  778. }
  779. }
  780. elseif (array_key_exists('namespace', $results['config'])) {
  781. $namespace = $results['config']['namespace'];
  782. }
  783. // If we can't find the namespace at EBI, then just default to using the
  784. // same namespace as the DB short name.
  785. else {
  786. $namespace = $this->default_db;
  787. }
  788. return $namespace;
  789. }
  790. catch (Exception $e) {
  791. watchdog_exception('Cannot find the namespace for this ontology.', $e);
  792. throw $e;
  793. }
  794. }
  795. /**
  796. * Finds the ontology prefix (DB short name) using EBI.
  797. *
  798. * @param $namespace
  799. * The namespace for ontology.
  800. */
  801. private function findEBIOntologyPrefix($namespace) {
  802. // NOTE: this code is not yet completed.. It's not clear it will
  803. // actually work.
  804. $options = array();
  805. $page = 1;
  806. $size = 25;
  807. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page. '&size=' . $size;
  808. while ($response = drupal_http_request($full_url, $options)) {
  809. $response = drupal_json_decode($response->data);
  810. foreach ($response['_embedded']['ontologies'] as $ontology) {
  811. $namespace = $ontology['config']['namespace'];
  812. }
  813. $page++;
  814. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page. '&size=' . $size;
  815. }
  816. }
  817. /**
  818. * A helper function to get details about a foreign term.
  819. *
  820. * A foreign term is one that does not belong to the ontology.
  821. *
  822. * @param $t
  823. * A term array that contains these keys at a minimum: id, name,
  824. * definition, subset, namespace, is_obsolete.
  825. */
  826. private function findEBITerm($id) {
  827. // Warn the user if we're looking up terms in EBI as this will slow the
  828. // loader if there are many lookups.
  829. if ($this->ebi_warned == FALSE) {
  830. $this->logMessage(
  831. "A term that belongs to another ontology is used within this " .
  832. "vocabulary. Therefore a lookup will be performed with the EBI Ontology " .
  833. "Lookup Service to retrieve the information for this term. " .
  834. "Please note, that vocabularies with many non-local terms " .
  835. "require remote lookups and these lookups can dramatically " .
  836. "decrease loading time. " ,
  837. ['!vocab' => $this->default_namespace], TRIPAL_WARNING);
  838. $this->ebi_warned = TRUE;
  839. // This ontology may havem ultiple remote terms and that takes a while
  840. // to load so lets change the progress interval down to give
  841. // updates more often.
  842. $this->setInterval(1);
  843. }
  844. $this->logMessage("Performing EBI OLS Lookup for: !id", ['!id' => $id]);
  845. // Get the short name and accession for the term.
  846. $pair = explode(":", $id, 2);
  847. $short_name = $pair[0];
  848. $accession = $pair[1];
  849. // First get the ontology so we can build an IRI for the term
  850. $base_iri = '';
  851. $ontologyID = '';
  852. if (array_key_exists($short_name, $this->baseIRIs)) {
  853. list($ontologyID, $base_iri) = $this->baseIRIs[$short_name];
  854. }
  855. else {
  856. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $short_name;
  857. $response = drupal_http_request($full_url, []);
  858. if (!$response) {
  859. throw new Exception(t('Did not get a response from EBI OLS trying to lookup ontology: !ontology',
  860. ['!ontology' => $short_name]));
  861. }
  862. $ontology_results = drupal_json_decode($response->data);
  863. if ($ontology_results['error']) {
  864. throw new Exception(t('Cannot find the ontology via an EBI OLS lookup: !short_name. ' .
  865. 'EBI Reported: !message. ' .
  866. 'Consider finding the OBO file for this ontology and manually loading it first.',
  867. ['!message' => $ontology_results['message'], '!short_name' => $short_name]));
  868. }
  869. $base_iri = $ontology_results['config']['baseUris'][0];
  870. $ontologyID = $ontology_results['ontologyId'];
  871. $this->baseIRIs[$short_name] = [$ontologyID, $base_iri];
  872. }
  873. // Next get the term.
  874. $iri = urlencode(urlencode($base_iri . $accession));
  875. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontologyID . '/terms/' . $iri;
  876. $response = drupal_http_request($full_url, []);
  877. if(!$response){
  878. throw new Exception(t('Did not get a response from EBI OLS trying to lookup term: !id',
  879. ['!id' => $id]));
  880. }
  881. $results = drupal_json_decode($response->data);
  882. // If EBI sent an error message then throw an error.
  883. if ($results['error']) {
  884. throw new Exception(t('Cannot find the term via an EBI OLS lookup: !term. ' .
  885. 'EBI Reported: !message.' .
  886. 'Consider finding the OBO file for this ontology and manually loading it first.',
  887. ['!message' => $results['message'], '!term' => $id]));
  888. }
  889. // TODO: what do we do if the term is not defined by this ontology?
  890. if ($results['is_defining_ontology'] != 1) {
  891. }
  892. // Make an OBO stanza array as if this term were in the OBO file and
  893. // return it.
  894. $this->logMessage("Found !term in EBI OLS.", ['!term' => $id]);
  895. $stanza = [];
  896. $stanza['id'][] = $id;
  897. $stanza['name'][] = $results['label'];
  898. $stanza['def'][] = $results['def'];
  899. $stanza['namespace'][] = $results['ontology_name'];
  900. $stanza['is_obsolete'][] = $results['is_obsolete'];
  901. $stanza['db_name'][] = $short_name;
  902. $stanza['comment'][] = 'Term obtained using the EBI Ontology Lookup Service.';
  903. if (array_key_exists('subset', $results)) {
  904. $stanza['subset'][] = $results['subset'];
  905. }
  906. // If this term has been replaced then get the new term.
  907. if (array_key_exists('term_replaced_by', $results) and isset($results['term_replaced_by'])) {
  908. $replaced_by = $results['term_replaced_by'];
  909. $replaced_by = preg_replace('/_/', ':', $replaced_by);
  910. $this->logMessage("The term, !term, is replaced by, !replaced",
  911. ['!term' => $id, '!replaced' => $replaced_by]);
  912. // Before we try to look for the replacement term, let's try to find it.
  913. // in our list of cached terms.
  914. if (array_key_exists($replaced_by, $this->termStanzaCache['ids'])) {
  915. $this->logMessage("Found term, !replaced in the term cache.",
  916. ['!term' => $id, '!replaced' => $replaced_by]);
  917. return $this->termStanzaCache['ids'][$id];
  918. }
  919. // Next look in the database.
  920. $rpair = explode(":", $replaced_by, 2);
  921. $found = $this->lookupTerm($rpair[0], $rpair[1]);
  922. if ($found) {
  923. $this->logMessage("Found term, !replaced in the local data store.",
  924. ['!term' => $id, '!replaced' => $replaced_by]);
  925. return $found;
  926. }
  927. // Look for this new term.
  928. $stanza = $this->findEBITerm($replaced_by);
  929. }
  930. return $stanza;
  931. }
  932. /**
  933. * Inserts a new cvterm using the OBO stanza array provided.
  934. *
  935. * The stanza passed to this function should always come from the term cache,
  936. * not directly from the OBO file because the cached terms have been
  937. * updated to include all necessary values. This function also removes
  938. * all properties assocaited with the term so that those can be added
  939. * fresh.
  940. *
  941. * @param $stanza
  942. * An OBO stanza array as returned by getCachedTermStanza().
  943. * @param $is_relationship
  944. * Set to TRUE if this term is a relationship term.
  945. * @param $update_if_exists
  946. * Set to TRUE to update the term if it exists.
  947. *
  948. * @return
  949. * The cvterm ID.
  950. */
  951. private function saveTerm($stanza, $is_relationship = FALSE) {
  952. // Get the term ID.
  953. $id = $stanza['id'][0];
  954. // First check if we've already used this term.
  955. if ($this->used_terms[$id]) {
  956. return $this->used_terms[$id];
  957. }
  958. // Get the term properties.
  959. $id = $stanza['id'][0];
  960. $name = $stanza['name'][0];
  961. $cvname = $stanza['namespace'][0];
  962. $dbname = $stanza['db_name'][0];
  963. $namespace = $stanza['namespace'][0];
  964. // Does this term ID have both a short name and accession? If so, then
  965. // separate out these components, otherwise we will use the id as both
  966. // the id and accession.
  967. $accession = '';
  968. $matches = [];
  969. if (preg_match('/^(.+?):(.*)$/', $id, $matches)) {
  970. $accession = $matches[2];
  971. }
  972. else {
  973. $accession = $id;
  974. }
  975. // Get the definition if there is one.
  976. $definition = '';
  977. if (array_key_exists('definition', $stanza)) {
  978. $definition = preg_replace('/^\"(.*)\"/', '\1', $stanza['def'][0]);
  979. }
  980. // Set the flag if this term is obsolete.
  981. $is_obsolete = 0;
  982. if (array_key_exists('is_obsolete', $stanza)) {
  983. $is_obsolete = $stanza['is_obsolete'][0] == TRUE ? 1 : 0;
  984. }
  985. // Is this term borrowed from another ontology?
  986. $is_borrowed = $this->isTermBorrowed($stanza);
  987. // The cvterm ChadoRecord object.
  988. $cvterm = NULL;
  989. // Get the CV and DB objects.
  990. $cv = $this->all_cvs[$cvname];
  991. $db = $this->all_dbs[$dbname];
  992. // If this is set to TRUE then we should insert the term.
  993. $do_cvterm_insert = FALSE;
  994. // We need to locate terms using their dbxref. This is because term names
  995. // can sometimes change, so we don't want to look up the term by it's name.
  996. // the unique ID which is in the accession will never change.
  997. $dbxref = new ChadoRecord('dbxref');
  998. $dbxref->setValues([
  999. 'db_id' => $db->db_id,
  1000. 'accession' => $accession
  1001. ]);
  1002. if ($dbxref->find()) {
  1003. // Now see if there is a cvterm for this dbxref. A dbxref can only be
  1004. // used one time. If so, then update the term, but only if this term
  1005. // belongs to namespace created by this OBO. We don't want to update
  1006. // terms from other OBOs that may be borrowed by this one.
  1007. $cvterm = new ChadoRecord('cvterm');
  1008. $cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
  1009. if ($cvterm->find()) {
  1010. if (!$is_borrowed) {
  1011. $cvterm->setValue('name', $name);
  1012. $cvterm->setValue('definition', $definition);
  1013. $cvterm->setValue('is_obsolete', $is_obsolete);
  1014. $cvterm->update();
  1015. }
  1016. }
  1017. else {
  1018. $do_cvterm_insert = TRUE;
  1019. }
  1020. }
  1021. else {
  1022. // The dbxref doesn't exist, so let's add it.
  1023. $dbxref->insert();
  1024. $do_cvterm_insert = TRUE;
  1025. }
  1026. if ($do_cvterm_insert) {
  1027. // Before inserting the term let's check to see if it already exists. The
  1028. // cvterm table has two unique constraints, one on the dbxref and another
  1029. // on the name, cv_id and is_obsolete columns. If for some reason the
  1030. // term exists but is assocaited with a different dbxref we'll have
  1031. // a problem. Because the is_obsolete may be set this time, but the
  1032. // term may not have it set from a previous load we will check for the
  1033. // presence of the term without the is_obsolete.
  1034. $cvterm = new ChadoRecord('cvterm');
  1035. $cvterm->setValues([
  1036. 'cv_id' => $cv->cv_id,
  1037. 'name' => $name,
  1038. ]);
  1039. if ($cvterm->find()) {
  1040. // We found the term so that means it's assocaited with a different
  1041. // dbxref. We need to correct it.
  1042. if (!$is_borrowed) {
  1043. $cvterm->setValue('dbxref_id', $dbxref->getID());
  1044. $cvterm->setValue('definition', $definition);
  1045. $cvterm->setValue('dbxref_id', $dbxref->getID());
  1046. $cvterm->setValue('is_obsolete', $is_obsolete);
  1047. $cvterm->update();
  1048. }
  1049. }
  1050. else {
  1051. // The term doesnt exist, so let's just do our insert.
  1052. $cvterm->setValues([
  1053. 'cv_id' => $cv->cv_id,
  1054. 'name' => $name,
  1055. 'definition' => $definition,
  1056. 'dbxref_id' => $dbxref->getID(),
  1057. 'is_relationshiptype' => $is_relationship,
  1058. 'is_obsolete' => $is_obsolete,
  1059. ]);
  1060. $cvterm->insert();
  1061. }
  1062. }
  1063. // Save the cvterm_id for this term so we don't look it up again.
  1064. $cvterm_id = $cvterm->getID();
  1065. $this->used_terms[$id] = $cvterm_id;
  1066. // Return the cvterm_id.
  1067. return $cvterm_id;
  1068. }
  1069. /**
  1070. * Uses the provided term array to add/update information to Chado about the
  1071. * term including the term, dbxref, synonyms, properties, and relationships.
  1072. *
  1073. * @param $term
  1074. * An array representing the cvterm.
  1075. * @is_relationship
  1076. * Set to 1 if this term is a relationship term
  1077. *
  1078. * @ingroup tripal_obo_loader
  1079. */
  1080. private function processTerm($stanza, $is_relationship = 0) {
  1081. //
  1082. // First things first--save the term.
  1083. //
  1084. // If the term does not exist it is inserted, if it does exist it just
  1085. // retrieves the cvterm_id.
  1086. //
  1087. $cvterm_id = $this->saveTerm($stanza, FALSE);
  1088. $id = $stanza['id'][0];
  1089. // If this term is borrowed from another ontology? If so then we will
  1090. // not update it.
  1091. if ($this->isTermBorrowed($stanza)) {
  1092. return;
  1093. }
  1094. // If this term belongs to this OBO (not borrowed from another OBO) then
  1095. // remove any relationships, properties, xrefs, and synonyms that this
  1096. // term alreadyn has so that they can be re-added.
  1097. $sql = "
  1098. DELETE FROM {cvterm_relationship}
  1099. WHERE subject_id = :cvterm_id
  1100. ";
  1101. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1102. $sql = "
  1103. DELETE FROM {cvtermprop}
  1104. WHERE cvterm_id = :cvterm_id
  1105. ";
  1106. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1107. $sql = "
  1108. DELETE FROM {cvterm_dbxref}
  1109. WHERE cvterm_id = :cvterm_id
  1110. ";
  1111. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1112. $sql = "
  1113. DELETE FROM {cvtermsynonym} CVTSYN
  1114. WHERE cvterm_id = :cvterm_id
  1115. ";
  1116. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1117. // We should never have the problem where we don't have a cvterm_id. The
  1118. // saveTerm() function should always return on. But if for some unkonwn
  1119. // reason we don't have one then fail.
  1120. if (!$cvterm_id) {
  1121. throw new Exception(t('Missing cvterm after saving term: !term',
  1122. ['!term' => print_r($stanza, TRUE)]));
  1123. }
  1124. //
  1125. // Handle: alt_id
  1126. //
  1127. if (array_key_exists('alt_id', $stanza)) {
  1128. foreach ($stanza['alt_id'] as $alt_id) {
  1129. $this->addAltID($id, $cvterm_id, $alt_id);
  1130. }
  1131. }
  1132. //
  1133. // Handle: synonym
  1134. //
  1135. if (array_key_exists('synonym', $stanza)) {
  1136. foreach ($stanza['synonym'] as $synonym) {
  1137. $this->addSynonym($id, $cvterm_id, $synonym);
  1138. }
  1139. }
  1140. //
  1141. // Handle: exact_synonym
  1142. //
  1143. if (array_key_exists('exact_synonym', $stanza)) {
  1144. foreach ($stanza['exact_synonym'] as $synonym) {
  1145. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  1146. $this->addSynonym($id, $cvterm_id, $fixed);
  1147. }
  1148. }
  1149. //
  1150. // Handle: narrow_synonym
  1151. //
  1152. if (array_key_exists('narrow_synonym', $stanza)) {
  1153. foreach ($stanza['narrow_synonym'] as $synonym) {
  1154. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  1155. $this->addSynonym($id, $cvterm_id, $fixed);
  1156. }
  1157. }
  1158. //
  1159. // Handle: broad_synonym
  1160. //
  1161. if (array_key_exists('broad_synonym', $stanza)) {
  1162. foreach ($stanza['broad_synonym'] as $synonym) {
  1163. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  1164. $this->addSynonym($id, $cvterm_id, $fixed);
  1165. }
  1166. }
  1167. //
  1168. // Handle: comment
  1169. //
  1170. if (array_key_exists('comment', $stanza)) {
  1171. $comments = $stanza['comment'];
  1172. foreach ($comments as $rank => $comment) {
  1173. $this->addComment($id, $cvterm_id, $comment, $rank);
  1174. }
  1175. }
  1176. //
  1177. // Handle: xref
  1178. //
  1179. if (array_key_exists('xref', $stanza)) {
  1180. foreach ($stanza['xref'] as $xref) {
  1181. $this->addXref($id, $cvterm_id, $xref);
  1182. }
  1183. }
  1184. //
  1185. // Handle: xref_analog
  1186. //
  1187. if (array_key_exists('xref_analog', $stanza)) {
  1188. foreach ($stanza['xref_analog'] as $xref) {
  1189. $this->addXref($id, $cvterm_id, $xref);
  1190. }
  1191. }
  1192. //
  1193. // Handle: xref_unk
  1194. //
  1195. if (array_key_exists('xref_unk', $stanza)) {
  1196. foreach ($stanza['xref_unk'] as $xref) {
  1197. $this->addXref($id, $cvterm_id, $xref);
  1198. }
  1199. }
  1200. //
  1201. // Handle: subset
  1202. //
  1203. if (array_key_exists('subset', $stanza)) {
  1204. foreach ($stanza['subset'] as $subset) {
  1205. $this->addSubset($id, $cvterm_id, $subset);
  1206. }
  1207. }
  1208. //
  1209. // Handle: is_a
  1210. //
  1211. if (array_key_exists('is_a', $stanza)) {
  1212. foreach ($stanza['is_a'] as $is_a) {
  1213. $this->addRelationship($id, $cvterm_id, 'is_a', $is_a);
  1214. }
  1215. }
  1216. //
  1217. // Handle: relationship
  1218. //
  1219. if (array_key_exists('relationship', $stanza)) {
  1220. foreach ($stanza['relationship'] as $value) {
  1221. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1222. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1223. $this->addRelationship($id, $cvterm_id, $rel, $object);
  1224. }
  1225. }
  1226. /**
  1227. * The following properties are currently unsupported:
  1228. *
  1229. * - intersection_of
  1230. * - union_of
  1231. * - disjoint_from
  1232. * - replaced_by
  1233. * - consider
  1234. * - use_term
  1235. * - builtin
  1236. * - is_anonymous
  1237. *
  1238. */
  1239. }
  1240. /**
  1241. * Adds a cvterm relationship
  1242. *
  1243. * @param $cvterm_id
  1244. * A cvterm_id of the term to which the relationship will be added.
  1245. * @param $rel_id
  1246. * The relationship term ID
  1247. * @param $obj_id
  1248. * The relationship object term ID.
  1249. *
  1250. * @ingroup tripal_obo_loader
  1251. */
  1252. private function addRelationship($id, $cvterm_id, $rel_id, $obj_id) {
  1253. // Get the cached terms for both the relationship and the object. They
  1254. // shold be there, but just in case something went wrong, we'll throw
  1255. // an exception if we can't find them.
  1256. $rel_stanza = $this->getCachedTermStanza($rel_id);
  1257. if (!$rel_stanza) {
  1258. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1259. 'The term, !rel, is not in the term cache.',
  1260. ['!source' => $id, '!rel' => $rel_id, '!name' => $obj_id]));
  1261. }
  1262. $rel_cvterm_id = $this->saveTerm($rel_stanza, TRUE);
  1263. // Make sure the object term exists in the cache.
  1264. $obj_stanza = $this->getCachedTermStanza($obj_id);
  1265. if (!$obj_stanza) {
  1266. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1267. 'The term, !object, is not in the term cache.',
  1268. ['!source' => $id, '!rel' => $rel_id, '!object' => $obj_id]));
  1269. }
  1270. $obj_cvterm_id = $this->saveTerm($obj_stanza);
  1271. // Add the cvterm_relationship.
  1272. $cvterm_relationship = new ChadoRecord('cvterm_relationship');
  1273. $cvterm_relationship->setValues([
  1274. 'type_id' => $rel_cvterm_id,
  1275. 'subject_id' => $cvterm_id,
  1276. 'object_id' => $obj_cvterm_id
  1277. ]);
  1278. // If the insert fails then catch the error and generate a more meaningful
  1279. // message that helps with debugging.
  1280. try {
  1281. $cvterm_relationship->insert();
  1282. }
  1283. catch (Exception $e) {
  1284. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1285. 'ERROR: !error.',
  1286. ['!source' => $id, '!rel' => $rel_id, '!object' => $obj_id, '!error' => $e->getMessage()]));
  1287. }
  1288. }
  1289. /**
  1290. * Retrieves the term array from the temp loading table for a given term id.
  1291. *
  1292. * @param id
  1293. * The id of the term to retrieve
  1294. *
  1295. * @ingroup tripal_obo_loader
  1296. */
  1297. private function getCachedTermStanza($id) {
  1298. if ($this->cache_type == 'table') {
  1299. $values = array('id' => $id);
  1300. $result = chado_select_record('tripal_obo_temp', array('stanza'), $values);
  1301. if (count($result) == 0) {
  1302. return FALSE;
  1303. }
  1304. return unserialize(base64_decode($result['stanza']));
  1305. }
  1306. if (array_key_exists($id, $this->termStanzaCache['ids'])) {
  1307. return $this->termStanzaCache['ids'][$id];
  1308. }
  1309. else {
  1310. return FALSE;
  1311. }
  1312. }
  1313. /**
  1314. * Using the term's short-name and accession try to find it in Chado.
  1315. *
  1316. * @param $short_name
  1317. * The term's ontolgy prefix (database short name)
  1318. * @param $accession
  1319. * The term's accession.
  1320. * @return array|NULL
  1321. */
  1322. private function lookupTerm($short_name, $accession) {
  1323. // Does the database already exist?
  1324. if (!array_key_exists($short_name, $this->all_dbs)) {
  1325. return NULL;
  1326. }
  1327. $db = $this->all_dbs[$short_name];
  1328. // Check if the dbxref exists.
  1329. $dbxref = new ChadoRecord('dbxref');
  1330. $dbxref->setValues([
  1331. 'db_id' => $db->db_id,
  1332. 'accession' => $accession,
  1333. ]);
  1334. if (!$dbxref->find()) {
  1335. return NULL;
  1336. }
  1337. // If the dbxref exists then see if it has a corresponding cvterm.
  1338. $cvterm = new ChadoRecord('cvterm');
  1339. $cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
  1340. if (!$cvterm->find()) {
  1341. return NULL;
  1342. }
  1343. // Get the CV for this term.
  1344. $cv = new ChadoRecord('cv');
  1345. $cv->setValues(['cv_id' => $cvterm->getValue('cv_id')]);
  1346. $cv->find();
  1347. // Create a new stanza using the values of this cvterm.
  1348. $stanza = [];
  1349. $stanza['id'][0] = $short_name . ':' . $accession;
  1350. $stanza['name'][0] = $cvterm->getValue('name');
  1351. $stanza['def'][0] = $cvterm->getValue('definition');
  1352. $stanza['namespace'][0] = $cv->getValue('name');
  1353. $stanza['is_obsolete'][] = $cvterm->getValue('is_obsolete');
  1354. $stanza['db_name'][] = $db->name;
  1355. $stanza['cv_name'][] = $cv->getValue('name');
  1356. return $stanza;
  1357. }
  1358. /**
  1359. * Adds a term stanza from the OBO file to the cache for easier lookup.
  1360. *
  1361. * @param $stanza
  1362. * The stanza from the OBO file for the term.
  1363. * @throws Exception
  1364. */
  1365. private function cacheTermStanza($stanza, $type) {
  1366. // Make sure we have defaults.
  1367. if (!$this->default_namespace) {
  1368. throw new Exception('Cannot cache terms without a default CV.' . print_r($stanza, TRUE));
  1369. }
  1370. if (!$this->default_db) {
  1371. throw new Exception('Cannot cache terms without a default DB.' . print_r($stanza, TRUE));
  1372. }
  1373. $id = $stanza['id'][0];
  1374. // First check if this term is already in the cache, if so then skip it.
  1375. if ($this->getCachedTermStanza($id)) {
  1376. return;
  1377. }
  1378. // Does this term have a database short name prefix in the ID (accession)?
  1379. // If not then we'll add the default CV as the namespace. If it does and
  1380. // the short name is not the default for this vocabulary then we'll look
  1381. // it up.
  1382. $matches = [];
  1383. if (preg_match('/^(.+):(.+)$/', $id, $matches)) {
  1384. $short_name = $matches[1];
  1385. $accession = $matches[2];
  1386. // If the term is borrowed then let's try to deal with it.
  1387. if ($short_name != $this->default_db) {
  1388. // First try to lookup the term and replace the stanza with the updated
  1389. // details.
  1390. $found = $this->lookupTerm($short_name, $accession);
  1391. if ($found) {
  1392. $stanza = $found;
  1393. }
  1394. // If we can't find the term in the database then do an EBI lookup.
  1395. else {
  1396. $stanza = $this->findEBITerm($id);
  1397. // Make sure the DBs and CVs exist and are added to our cache.
  1398. $this->addDB($stanza['db_name'][0]);
  1399. $this->addCV($stanza['namespace'][0]);
  1400. }
  1401. }
  1402. // If the term belongs to this OBO then let's set the 'db_name'.
  1403. else {
  1404. if (!array_key_exists('namespace', $stanza)) {
  1405. $stanza['namespace'][] = $this->default_namespace;
  1406. }
  1407. $stanza['db_name'][] = $short_name;
  1408. }
  1409. // Make sure the db for this term is added to Chado. If it already is
  1410. // then this function won't re-add it.
  1411. $this->addDB($short_name);
  1412. }
  1413. // If there is no DB short name prefix for the id.
  1414. else {
  1415. if (!array_key_exists('namespace', $stanza)) {
  1416. $stanza['namespace'][] = $this->default_namespace;
  1417. }
  1418. $stanza['db_name'][] = $this->default_db;
  1419. }
  1420. if ($this->cache_type == 'table') {
  1421. // Add the term to the temp table.
  1422. $values = [
  1423. 'id' => $id,
  1424. 'stanza' => base64_encode(serialize($stanza)),
  1425. 'type' => $type,
  1426. ];
  1427. $success = chado_insert_record('tripal_obo_temp', $values);
  1428. if (!$success) {
  1429. throw new Exception("Cannot insert stanza into temporary table.");
  1430. }
  1431. return;
  1432. }
  1433. // The is_a field can have constructs like this: {is_inferred="true"}
  1434. // We need to remove those if they exist.
  1435. if (array_key_exists('is_a', $stanza)) {
  1436. foreach ($stanza['is_a'] as $index => $is_a) {
  1437. $stanza['is_a'][$index] = trim(preg_replace('/\{.+?\}/', '', $is_a));
  1438. }
  1439. }
  1440. if (array_key_exists('relationship', $stanza)) {
  1441. foreach ($stanza['relationship'] as $index => $relationship) {
  1442. $stanza['relationship'][$index] = trim(preg_replace('/\{.+?\}/', '', $relationship));
  1443. }
  1444. }
  1445. // Clean up any synonym definitions. We only handle the synonym in
  1446. // quotes and the type.
  1447. if (array_key_exists('synonym', $stanza)) {
  1448. foreach ($stanza['synonym'] as $index => $synonym) {
  1449. if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
  1450. $stanza['synonym'][$index] = '"' . $matches[1] . '" ' . $matches[2];
  1451. }
  1452. }
  1453. }
  1454. // Now before saving, remove any duplicates. Sometimes the OBOs have
  1455. // the same item duplicated in the stanza multiple times. This will
  1456. // result in duplicate contraint violations in the tables. We can either
  1457. // check on every insert if the record exists increasing loading time or
  1458. // remove duplicates here.
  1459. foreach ($stanza as $key => $values) {
  1460. $stanza[$key] = array_unique($values);
  1461. }
  1462. $this->termStanzaCache['ids'][$id] = $stanza;
  1463. $this->termStanzaCache['count'][$type]++;
  1464. $this->termStanzaCache['types'][$type][] = $id;
  1465. }
  1466. /**
  1467. * Returns the size of a given term type from the cache.
  1468. * @param $type
  1469. * The term type: Typedef, Term, etc.
  1470. */
  1471. private function getCacheSize($type) {
  1472. if ($this->cache_type == 'table') {
  1473. $sql = "
  1474. SELECT count(*) as num_terms
  1475. FROM {tripal_obo_temp}
  1476. WHERE type = :type
  1477. ";
  1478. $result = chado_query($sql, [':type' => $type])->fetchObject();
  1479. return $result->num_terms;
  1480. }
  1481. return $this->termStanzaCache['count'][$type];
  1482. }
  1483. /**
  1484. * Retrieves all term IDs for a given type.
  1485. *
  1486. * If the cache is using the tripal_obo_temp table then it
  1487. * returns an iterable Database handle.
  1488. */
  1489. private function getCachedTermStanzas($type) {
  1490. if ($this->cache_type == 'table') {
  1491. $sql = "SELECT id FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  1492. $typedefs = chado_query($sql);
  1493. return $typedefs;
  1494. }
  1495. return $this->termStanzaCache['types'][$type];
  1496. }
  1497. /**
  1498. * Clear's the term cache.
  1499. */
  1500. private function clearTermStanzaCache() {
  1501. if ($this->cache_type == 'table') {
  1502. $sql = "DELETE FROM {tripal_obo_temp}";
  1503. chado_query($sql);
  1504. return;
  1505. }
  1506. $this->termStanzaCache = [
  1507. 'ids' => [],
  1508. 'count' => [
  1509. 'Typedef' => 0,
  1510. 'Term' => 0,
  1511. 'Instance' => 0,
  1512. ],
  1513. 'types' => [
  1514. 'Typedef' => [],
  1515. 'Term' => [],
  1516. 'Instance' => [],
  1517. ],
  1518. ];
  1519. }
  1520. /**
  1521. * Adds the synonyms to a term
  1522. *
  1523. * @param $cvterm_id
  1524. * The cvterm_id of the term to which the synonym will be added.
  1525. * @param $synonym
  1526. * The value of the 'synonym' line of the term stanza.
  1527. *
  1528. * @ingroup tripal_obo_loader
  1529. */
  1530. private function addSynonym($id, $cvterm_id, $synonym) {
  1531. $def = $synonym;
  1532. $syn_type = '';
  1533. // Separate out the synonym definition and type (e.g. EXACT).
  1534. $matches = [];
  1535. if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
  1536. $def = $matches[1];
  1537. $syn_type = $matches[2];
  1538. }
  1539. // Get the syn type cvterm.
  1540. if (!$syn_type) {
  1541. $syn_type = 'exact';
  1542. }
  1543. $syn_type = $this->syn_types[$syn_type];
  1544. // Now save the new synonym.
  1545. $cvtermsynonym = new ChadoRecord('cvtermsynonym');
  1546. $cvtermsynonym->setValues([
  1547. 'cvterm_id' => $cvterm_id,
  1548. 'synonym' => $def,
  1549. 'type_id' => $syn_type->cvterm_id
  1550. ]);
  1551. // If the insert fails then catch the error and generate a more meaningful
  1552. // message that helps with debugging.
  1553. try {
  1554. $cvtermsynonym->insert();
  1555. }
  1556. catch (Exception $e) {
  1557. throw new Exception(t('Cannot add synonym, "!synonym" to term: !id. ' .
  1558. 'ERROR: !error.',
  1559. ['!synonym' => $def, '!id' => $id, '!error' => $e->getMessage()]));
  1560. }
  1561. }
  1562. /**
  1563. * Parse the OBO file and populate the templ loading table
  1564. *
  1565. * @param $file
  1566. * The path on the file system where the ontology can be found
  1567. * @param $header
  1568. * An array passed by reference that will be populated with the header
  1569. * information from the OBO file
  1570. *
  1571. * @ingroup tripal_obo_loader
  1572. */
  1573. private function parse($obo_file, &$header) {
  1574. // Set to 1 if we are in the top header lines of the file.
  1575. $in_header = TRUE;
  1576. // Holds the full stanza for the term.
  1577. $stanza = array();
  1578. // Holds the default database for the term.
  1579. $db_short_name = '';
  1580. $line_num = 0;
  1581. $num_read = 0;
  1582. // The type of term: Typedef or Term (inside the [] brackets]
  1583. $type = '';
  1584. $filesize = filesize($obo_file);
  1585. $this->setTotalItems($filesize);
  1586. $this->setItemsHandled(0);
  1587. $this->setInterval(5);
  1588. // iterate through the lines in the OBO file and parse the stanzas
  1589. $fh = fopen($obo_file, 'r');
  1590. while ($line = fgets($fh)) {
  1591. $line_num++;
  1592. $size = drupal_strlen($line);
  1593. $num_read += $size;
  1594. $line = trim($line);
  1595. $this->setItemsHandled($num_read);
  1596. // remove newlines
  1597. $line = rtrim($line);
  1598. // remove any special characters that may be hiding
  1599. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  1600. // skip empty lines
  1601. if (strcmp($line, '') == 0) {
  1602. continue;
  1603. }
  1604. // Remove comments from end of lines.
  1605. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line);
  1606. // At the first stanza we're out of header.
  1607. if (preg_match('/^\s*\[/', $line)) {
  1608. // After parsing the header we need to get information about this OBO.
  1609. if ($in_header == TRUE) {
  1610. $this->setDefaults($header);
  1611. $in_header = FALSE;
  1612. }
  1613. // Store the stanza we just finished reading.
  1614. if (sizeof($stanza) > 0) {
  1615. // If this term has a namespace then we want to keep track of it.
  1616. if (array_key_exists('namespace', $stanza)) {
  1617. $namespace = $stanza['namespace'][0];
  1618. $cv = $this->all_cvs[$namespace];
  1619. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1620. }
  1621. $this->cacheTermStanza($stanza, $type);
  1622. }
  1623. // Get the stanza type: Term, Typedef or Instance
  1624. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  1625. // start fresh with a new array
  1626. $stanza = array();
  1627. continue;
  1628. }
  1629. // break apart the line into the tag and value but ignore any escaped colons
  1630. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  1631. $pair = explode(":", $line, 2);
  1632. $tag = $pair[0];
  1633. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  1634. // if this is the ID line then get the database short name from the ID.
  1635. $matches = array();
  1636. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  1637. $db_short_name = $matches[1];
  1638. }
  1639. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  1640. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  1641. if ($in_header) {
  1642. if (!array_key_exists($tag, $header)) {
  1643. $header[$tag] = array();
  1644. }
  1645. $header[$tag][] = $value;
  1646. }
  1647. else {
  1648. if (!array_key_exists($tag, $stanza)) {
  1649. $stanza[$tag] = array();
  1650. }
  1651. $stanza[$tag][] = $value;
  1652. }
  1653. }
  1654. // now add the last term in the file
  1655. if (sizeof($stanza) > 0) {
  1656. // If this term has a namespace then we want to keep track of it.
  1657. if (array_key_exists('namespace', $stanza)) {
  1658. $namespace = $stanza['namespace'][0];
  1659. $cv = $this->all_cvs[$namespace];
  1660. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1661. }
  1662. $this->cacheTermStanza($stanza, $type);
  1663. $this->setItemsHandled($num_read);
  1664. }
  1665. // Make sure there are CV records for all namespaces.
  1666. $message = t('Found the following namespaces: !namespaces.',
  1667. ['!namespaces' => implode(', ', array_keys($this->obo_namespaces))]);
  1668. foreach ($this->obo_namespaces as $namespace => $cv_id) {
  1669. $this->addCV($namespace);
  1670. }
  1671. $this->logMessage($message);
  1672. }
  1673. /**
  1674. * Iterates through all of the cached terms and caches any relationships
  1675. */
  1676. private function cacheRelationships() {
  1677. // Now that we have all of the terms parsed and loaded into the cache,
  1678. // lets run through them one more time cache any terms in relationships
  1679. // as well.
  1680. $terms = $this->getCachedTermStanzas('Term');
  1681. $count = $this->getCacheSize('Term');
  1682. $this->setTotalItems($count);
  1683. $this->setItemsHandled(0);
  1684. $this->setInterval(25);
  1685. // Iterate through the terms.
  1686. $i = 1;
  1687. foreach ($terms as $t) {
  1688. // TODO: it would be better if we had a term iterator so that we
  1689. // don't have to distinguish here between the table vs memory cache type.
  1690. if ($this->cache_type == 'table') {
  1691. $stanza = unserialize(base64_decode($t->stanza));
  1692. }
  1693. else {
  1694. $stanza = $this->termStanzaCache['ids'][$t];
  1695. }
  1696. // Check if this stanza has an is_a relationship that needs lookup.
  1697. if (array_key_exists('is_a', $stanza)) {
  1698. foreach ($stanza['is_a'] as $object_term) {
  1699. $rstanza = [];
  1700. $rstanza['id'][] = $object_term;
  1701. $this->cacheTermStanza($rstanza, 'Term');
  1702. }
  1703. }
  1704. // Check if this stanza has any additional relationships for lookup.
  1705. if (array_key_exists('relationship', $stanza)) {
  1706. foreach ($stanza['relationship'] as $value) {
  1707. // Get the relationship term and the object term
  1708. $rel_term = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1709. $object_term = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1710. $rstanza = [];
  1711. $rstanza['id'][] = $rel_term;
  1712. $this->cacheTermStanza($rstanza, 'Typedef');
  1713. $rstanza = [];
  1714. $rstanza['id'][] = $object_term;
  1715. $this->cacheTermStanza($rstanza, 'Term');
  1716. }
  1717. }
  1718. }
  1719. $this->setItemsHandled($i++);
  1720. // Last of all, we need to add the "is_a" relationship It's part of the
  1721. // OBO specification as a built-in relationship but not all vocabularies
  1722. // include that term.
  1723. if (!$this->getCachedTermStanza('is_a')) {
  1724. $stanza = [];
  1725. $stanza['id'][] = 'is_a';
  1726. $stanza['name'][] = 'is_a';
  1727. $stanza['namespace'][] = $this->default_namespace;
  1728. $stanza['db_name'][] = $this->default_db;
  1729. $this->cacheTermStanza($stanza, 'Typedef');
  1730. }
  1731. }
  1732. /**
  1733. * Adds a property to the cvterm indicating it belongs to a subset.
  1734. * @param $cvterm_id
  1735. * The cvterm_id of the term to which the subset will be added.
  1736. * @param $subset
  1737. * The name of the subset.
  1738. */
  1739. private function addSubset($id, $cvterm_id, $subset) {
  1740. $cvtermprop = new ChadoRecord('cvtermprop');
  1741. $cvtermprop->setValues([
  1742. 'cvterm_id' => $cvterm_id,
  1743. 'type_id' => $this->used_terms['NCIT:C25693'],
  1744. 'value' => $subset
  1745. ]);
  1746. // If the insert fails then catch the error and generate a more meaningful
  1747. // message that helps with debugging.
  1748. try {
  1749. $cvtermprop->insert();
  1750. }
  1751. catch (Exception $e) {
  1752. throw new Exception(t('Cannot add subset, "!subset" to term: !id. ' .
  1753. 'ERROR: !error.',
  1754. ['!subset' => $subset, '!id' => $id, '!error' => $e->getMessage()]));
  1755. }
  1756. }
  1757. /**
  1758. * Adds a database to Chado if it doesn't exist.
  1759. *
  1760. * @param $dbname
  1761. * The name of the database to add.
  1762. *
  1763. * @return
  1764. * A Chado database object.
  1765. */
  1766. private function addDB($dbname) {
  1767. // Add the database if it doesn't exist.
  1768. $db = NULL;
  1769. if (array_key_exists($dbname, $this->all_dbs)) {
  1770. $db = $this->all_dbs[$dbname];
  1771. }
  1772. else {
  1773. // If it's not in the cache we can assume it doesn't exist and insert.
  1774. $db = new ChadoRecord('db');
  1775. $db->setValues(['name' => $dbname]);
  1776. $db->insert();
  1777. $db = (object) $db->getValues();
  1778. $this->all_dbs[$dbname] = $db;
  1779. }
  1780. return $db;
  1781. }
  1782. /**
  1783. * Adds a vocabulary to Chado if it doesn't exist.
  1784. *
  1785. * @param $cvname
  1786. * The name of the vocabulary to add.
  1787. *
  1788. * @return
  1789. * A Chado cv object.
  1790. */
  1791. private function addCV($cvname) {
  1792. // TODO: we need to get the description and title from EBI for these
  1793. // ontology so that we can put something in the proper fields when
  1794. // adding a new CV or DB.
  1795. // Add the CV record if it doesn't exist.
  1796. $cv = NULL;
  1797. if (array_key_exists($cvname, $this->all_cvs)) {
  1798. $cv = $this->all_dbs[$cvname];
  1799. }
  1800. else {
  1801. // If it's not in the cache we can assume it doesn't exist and insert.
  1802. $cv = new ChadoRecord('cv');
  1803. $cv->setValues(['name' => $cvname]);
  1804. $cv->insert();
  1805. $cv = (object) $cv->getValues();
  1806. $this->all_cvs[$cvname] = $cv;
  1807. $this->obo_namespaces[$cvname] = $cv->cv_id;
  1808. }
  1809. return $cv;
  1810. }
  1811. /**
  1812. * Indicates if the term belongs to this OBO or if it was borrowed
  1813. * .
  1814. * @param $stanza
  1815. */
  1816. private function isTermBorrowed($stanza) {
  1817. $namespace = $stanza['namespace'][0];
  1818. if (array_key_exists($namespace, $this->obo_namespaces)) {
  1819. return FALSE;
  1820. }
  1821. return TRUE;
  1822. }
  1823. /**
  1824. * Adds an alternative ID
  1825. *
  1826. * @param $cvterm_id
  1827. * The cvterm_id of the term to which the synonym will be added.
  1828. * @param $alt_id
  1829. * The cross refernce. It should be of the form from the OBO specification
  1830. *
  1831. * @ingroup tripal_obo_loader
  1832. */
  1833. private function addAltID($id, $cvterm_id, $alt_id) {
  1834. $dbname = '';
  1835. $accession = '';
  1836. $matches = [];
  1837. if (preg_match('/^(.+?):(.*)$/', $alt_id, $matches)) {
  1838. $dbname = $matches[1];
  1839. $accession = $matches[2];
  1840. }
  1841. if (!$accession) {
  1842. throw new Exception("Cannot add an Alt ID without an accession: '$alt_id'");
  1843. }
  1844. // Add the database if it doesn't exist.
  1845. $db = $this->addDB($dbname);
  1846. $db_id = $db->db_id;
  1847. // Now add the dbxref if it doesn't alredy exist
  1848. $dbxref = new ChadoRecord('dbxref');
  1849. $dbxref->setValues([
  1850. 'db_id' => $db_id,
  1851. 'accession' => $accession
  1852. ]);
  1853. if (!$dbxref->find()) {
  1854. $dbxref->insert();
  1855. }
  1856. // Now add the cvterm_dbxref record.
  1857. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  1858. $cvterm_dbxref->setValues([
  1859. 'cvterm_id' => $cvterm_id,
  1860. 'dbxref_id' => $dbxref->getID(),
  1861. ]);
  1862. $cvterm_dbxref->insert();
  1863. }
  1864. /**
  1865. * Adds a database reference to a cvterm
  1866. *
  1867. * @param $cvterm_id
  1868. * The cvterm_id of the term to which the synonym will be added.
  1869. * @param xref
  1870. * The cross refernce. It should be of the form from the OBO specification
  1871. *
  1872. * @ingroup tripal_obo_loader
  1873. */
  1874. private function addXref($id, $cvterm_id, $xref) {
  1875. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  1876. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  1877. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  1878. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  1879. if (!$accession) {
  1880. throw new Exception("Cannot add an xref without an accession: '$xref'");
  1881. }
  1882. // If the xref is a database link then skip those for now.
  1883. if (strcmp($dbname, 'http') == 0) {
  1884. return;
  1885. }
  1886. // Add the database if it doesn't exist.
  1887. $db = $this->addDB($dbname);
  1888. $db_id = $db->db_id;
  1889. // Now add the dbxref if it doesn't alredy exist
  1890. $dbxref = new ChadoRecord('dbxref');
  1891. $dbxref->setValues([
  1892. 'db_id' => $db_id,
  1893. 'accession' => $accession
  1894. ]);
  1895. if (!$dbxref->find()) {
  1896. $dbxref->insert();
  1897. }
  1898. // Now add the cvterm_dbxref record.
  1899. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  1900. $cvterm_dbxref->setValues([
  1901. 'cvterm_id' => $cvterm_id,
  1902. 'dbxref_id' => $dbxref->getID(),
  1903. ]);
  1904. $cvterm_dbxref->insert();
  1905. }
  1906. /**
  1907. * Adds a comment to a cvterm.
  1908. *
  1909. * @param $cvterm_id
  1910. * A cvterm_id of the term to which properties will be added
  1911. * @param $comment
  1912. * The comment to add to the cvterm.
  1913. * @param rank
  1914. * The rank of the comment
  1915. *
  1916. * @ingroup tripal_obo_loader
  1917. */
  1918. private function addComment($id, $cvterm_id, $comment, $rank) {
  1919. // Get the comment type id.
  1920. $comment_type_id = $this->used_terms['rdfs:comment'];
  1921. // Add the comment as a property of the cvterm.
  1922. $cvtermprop = new ChadoRecord('cvtermprop');
  1923. $cvtermprop->setValues([
  1924. 'cvterm_id' => $cvterm_id,
  1925. 'type_id' => $comment_type_id,
  1926. 'value' => $comment,
  1927. 'rank' => $rank,
  1928. ]);
  1929. // If the insert fails then catch the error and generate a more meaningful
  1930. // message that helps with debugging.
  1931. try {
  1932. $cvtermprop->insert();
  1933. }
  1934. catch (Exception $e) {
  1935. throw new Exception(t('Cannot add comment, "!comment" to term: !id. ' .
  1936. 'ERROR: !error.',
  1937. ['!comment' => $comment, '!id' => $id, '!error' => $e->getMessage()]));
  1938. }
  1939. }
  1940. /**
  1941. * API call to Ontology Lookup Service provided by
  1942. * https://www.ebi.ac.uk/ols/docs/api#resources-terms
  1943. *
  1944. * @param accession
  1945. * Accession term for query
  1946. * @param type_of_search
  1947. * Either ontology, term, query, or query-non-local
  1948. *
  1949. * @ingroup tripal_obo_loader
  1950. */
  1951. private function oboEbiLookup($accession, $type_of_search) {
  1952. //Grab just the ontology from the $accession.
  1953. $parts = explode(':', $accession);
  1954. $ontology = strtolower($parts[0]);
  1955. $ontology = preg_replace('/\s+/', '', $ontology);
  1956. if ($type_of_search == 'ontology') {
  1957. $options = array();
  1958. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology;
  1959. $response = drupal_http_request($full_url, $options);
  1960. if(!empty($response)){
  1961. $response = drupal_json_decode($response->data);
  1962. }
  1963. }
  1964. elseif ($type_of_search == 'term') {
  1965. //The IRI of the terms, this value must be double URL encoded
  1966. $iri = urlencode(urlencode("http://purl.obolibrary.org/obo/" . str_replace(':' , '_', $accession)));
  1967. $options = array();
  1968. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology . '/' . 'terms/' . $iri;
  1969. $response = drupal_http_request($full_url, $options);
  1970. if(!empty($response)){
  1971. $response = drupal_json_decode($response->data);
  1972. }
  1973. }
  1974. elseif($type_of_search == 'query') {
  1975. $options = array();
  1976. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id&local=true';
  1977. $response = drupal_http_request($full_url, $options);
  1978. if(!empty($response)){
  1979. $response = drupal_json_decode($response->data);
  1980. }
  1981. }
  1982. elseif($type_of_search == 'query-non-local') {
  1983. $options = array();
  1984. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id';
  1985. $response = drupal_http_request($full_url, $options);
  1986. if(!empty($response)){
  1987. $response = drupal_json_decode($response->data);
  1988. }
  1989. }
  1990. return $response;
  1991. }
  1992. }
  1993. /**
  1994. * Ajax callback for the OBOImporter::form() function.
  1995. */
  1996. function tripal_cv_obo_form_ajax_callback($form, $form_state) {
  1997. return $form['obo_existing'];
  1998. }