GFF3Importer.inc 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  1. <?php
  2. class GFF3Importer extends TripalImporter {
  3. /**
  4. * The name of this loader. This name will be presented to the site
  5. * user.
  6. */
  7. public static $name = 'Chado GFF3 File Loader';
  8. /**
  9. * The machine name for this loader. This name will be used to construct
  10. * the URL for the loader.
  11. */
  12. public static $machine_name = 'chado_gff3_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Import a GFF3 file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = ['gff', 'gff3'];
  22. /**
  23. * Provides information to the user about the file upload. Typically this
  24. * may include a description of the file types allowed.
  25. */
  26. public static $upload_description = 'Please provide the GFF3 file.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 file';
  36. /**
  37. * @see TripalImporter::form()
  38. */
  39. public function form($form, &$form_state) {
  40. // get the list of organisms
  41. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  42. $org_rset = chado_query($sql);
  43. $organisms = [];
  44. $organisms[''] = '';
  45. while ($organism = $org_rset->fetchObject()) {
  46. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  47. }
  48. $form['organism_id'] = [
  49. '#title' => t('Organism'),
  50. '#type' => t('select'),
  51. '#description' => t("Choose the organism to which these sequences are associated"),
  52. '#required' => TRUE,
  53. '#options' => $organisms,
  54. ];
  55. // Advanced Options
  56. $form['advanced'] = [
  57. '#type' => 'fieldset',
  58. '#title' => t('Additional Options'),
  59. '#collapsible' => TRUE,
  60. '#collapsed' => TRUE,
  61. ];
  62. $form['advanced']['line_number'] = [
  63. '#type' => 'textfield',
  64. '#title' => t('Start Line Number'),
  65. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  66. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  67. '#size' => 10,
  68. ];
  69. $form['advanced']['landmark_type'] = [
  70. '#title' => t('Landmark Type'),
  71. '#type' => t('textfield'),
  72. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  73. for the landmark sequences in the GFF fie (e.g. 'chromosome'). If the GFF file
  74. contains a '##sequence-region' line that describes the landmark sequences to
  75. which all others are aligned and a type is provided here then the features
  76. will be created if they do not already exist. If they do exist then this
  77. field is not used."),
  78. ];
  79. $form['advanced']['alt_id_attr'] = [
  80. '#title' => t('ID Attribute'),
  81. '#type' => t('textfield'),
  82. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  83. required ID attribute that specifies the unique name of the feature, but there
  84. may be another attribute that can uniquely identify the feature. If so,
  85. you may specify the name of the attribute to use for the name."),
  86. ];
  87. $form['advanced']['skip_protein'] = [
  88. '#type' => 'checkbox',
  89. '#title' => t('Skip automatic protein creation'),
  90. '#required' => FALSE,
  91. '#description' => t('The GFF loader will automatically create a protein feature for each transcript in the GFF file if a protein feature is missing in the GFF file. Check this box to disable this functionality. Protein features that are specifically present in the GFF will always be created.'),
  92. '#default_value' => 0,
  93. ];
  94. $form['advanced']['protein_names'] = [
  95. '#type' => 'fieldset',
  96. '#title' => t('Protein Names'),
  97. '#collapsible' => TRUE,
  98. '#collapsed' => FALSE,
  99. '#weight' => 5,
  100. ];
  101. $form['advanced']['protein_names']['re_help'] = [
  102. '#type' => 'item',
  103. '#markup' => t('A regular expression is an advanced method for extracting information from a string of text.
  104. If your GFF3 file does not contain polypeptide (or protein) features, but contains CDS features, proteins will be automatically created.
  105. By default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  106. If you want to customize the name of the created protein, you can use the following regex.'),
  107. ];
  108. $form['advanced']['protein_names']['re_mrna'] = [
  109. '#type' => 'textfield',
  110. '#title' => t('Regular expression for the mRNA name'),
  111. '#required' => FALSE,
  112. '#description' => t('Enter the regular expression that will extract portions of
  113. the mRNA unique name. For example, for a
  114. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  115. the regular expression would be, "^(.*?)-R([A-Z]+)$".'),
  116. ];
  117. $form['advanced']['protein_names']['re_protein'] = [
  118. '#type' => 'textfield',
  119. '#title' => t('Replacement string for the protein name'),
  120. '#required' => FALSE,
  121. '#description' => t('Enter the replacement string that will be used to create
  122. the protein name based on the mRNA regular expression. For example, for a
  123. mRNA regular expression "^(.*?)-R()[A-Z]+)$", the corresponding protein regular
  124. expression would be "$1-P$2".'),
  125. ];
  126. $form['advanced']['add_only'] = [
  127. '#type' => 'checkbox',
  128. '#title' => t('Import only new features'),
  129. '#required' => FALSE,
  130. '#description' => t('The job will skip features in the GFF file that already
  131. exist in the database and import only new features.'),
  132. ];
  133. $form['advanced']['update'] = [
  134. '#type' => 'checkbox',
  135. '#title' => t('Import all and update'),
  136. '#required' => FALSE,
  137. '#default_value' => 'checked',
  138. '#description' => t('Existing features will be updated and new features will be added. Attributes
  139. for a feature that are not present in the GFF but which are present in the
  140. database will not be altered.'),
  141. '#default_value' => 1,
  142. ];
  143. // SPF: there are bugs in refreshing and removing features. The bugs arise
  144. // if a feature in the GFF does not have a uniquename. GenSAS will auto
  145. // generate this uniquename and it will not be the same as a previous
  146. // load because it uses the date. This causes orphaned CDS/exons, UTRs
  147. // to be left behind during a delete or refresh. So, the short term
  148. // fix is to remove these options.
  149. // $form['import_options']['refresh']= array(
  150. // '#type' => 'checkbox',
  151. // '#title' => t('Import all and replace'),
  152. // '#required' => FALSE,
  153. // '#description' => t('Existing features will be updated and feature properties not
  154. // present in the GFF file will be removed.'),
  155. // );
  156. // $form['import_options']['remove']= array(
  157. // '#type' => 'checkbox',
  158. // '#title' => t('Delete features'),
  159. // '#required' => FALSE,
  160. // '#description' => t('Features present in the GFF file that exist in the database
  161. // will be removed rather than imported'),
  162. // );
  163. $form['advanced']['create_organism'] = [
  164. '#type' => 'checkbox',
  165. '#title' => t('Create organism'),
  166. '#required' => FALSE,
  167. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  168. different organism to be aligned to the landmark sequence of another species. The format of the
  169. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  170. species name. Check this box to automatically add the organism to the database if it does not already exists.
  171. Otherwise lines with an oraganism attribute where the organism is not present in the database will be skipped.'),
  172. ];
  173. $form['advanced']['targets'] = [
  174. '#type' => 'fieldset',
  175. '#title' => t('Targets'),
  176. '#collapsible' => TRUE,
  177. '#collapsed' => FALSE,
  178. '#weight' => 1,
  179. ];
  180. $form['advanced']['targets']['adesc'] = [
  181. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  182. alignments of cDNA sequences to a whole genome, or blast matches), they are
  183. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  184. and 'match_part'. These features may also have a 'Target' attribute to
  185. specify the sequence that is being aligned.
  186. However, the organism to which the aligned sequence belongs may not be present in the
  187. GFF file. Here you can specify the organism and feature type of the target sequences.
  188. The options here will apply to all targets unless the organism and type are explicity
  189. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  190. ];
  191. $form['advanced']['targets']['target_organism_id'] = [
  192. '#title' => t('Target Organism'),
  193. '#type' => t('select'),
  194. '#description' => t("Optional. Choose the organism to which target sequences belong.
  195. Select this only if target sequences belong to a different organism than the
  196. one specified above. And only choose an organism here if all of the target sequences
  197. belong to the same species. If the targets in the GFF file belong to multiple
  198. different species then the organism must be specified using the 'target_organism=genus:species'
  199. attribute in the GFF file."),
  200. '#options' => $organisms,
  201. ];
  202. $form['advanced']['targets']['target_type'] = [
  203. '#title' => t('Target Type'),
  204. '#type' => t('textfield'),
  205. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  206. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  207. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  208. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  209. ];
  210. $form['advanced']['targets']['create_target'] = [
  211. '#type' => 'checkbox',
  212. '#title' => t('Create Target'),
  213. '#required' => FALSE,
  214. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  215. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  216. GFF file take precedence over those specified above."),
  217. ];
  218. return $form;
  219. }
  220. /**
  221. * @see TripalImporter::formValidate()
  222. */
  223. public function formValidate($form, &$form_state) {
  224. $organism_id = $form_state['values']['organism_id'];
  225. $target_organism_id = $form_state['values']['target_organism_id'];
  226. $target_type = trim($form_state['values']['target_type']);
  227. $create_target = $form_state['values']['create_target'];
  228. $create_organism = $form_state['values']['create_organism'];
  229. $add_only = $form_state['values']['add_only'];
  230. $update = $form_state['values']['update'];
  231. $refresh = 0; //$form_state['values']['refresh'];
  232. $remove = 0; //$form_state['values']['remove'];
  233. $line_number = trim($form_state['values']['line_number']);
  234. $landmark_type = trim($form_state['values']['landmark_type']);
  235. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  236. $re_mrna = trim($form_state['values']['re_mrna']);
  237. $re_protein = trim($form_state['values']['re_protein']);
  238. // @coder-ignore: there are no functions being called here
  239. if (($add_only AND ($update OR $refresh OR $remove)) OR
  240. ($update AND ($add_only OR $refresh OR $remove)) OR
  241. ($refresh AND ($update OR $add_only OR $remove)) OR
  242. ($remove AND ($update OR $refresh OR $add_only))) {
  243. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  244. }
  245. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  246. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  247. }
  248. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  249. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  250. }
  251. // check the regular expression to make sure it is valid
  252. set_error_handler(function () {
  253. }, E_WARNING);
  254. $result_re = preg_match("/" . $re_mrna . "/", NULL);
  255. $result = preg_replace("/" . $re_mrna . "/", $re_protein, NULL);
  256. restore_error_handler();
  257. if ($result_re === FALSE) {
  258. form_set_error('re_mrna', 'Invalid regular expression.');
  259. }
  260. else {
  261. if ($result === FALSE) {
  262. form_set_error('re_protein', 'Invalid replacement string.');
  263. }
  264. }
  265. }
  266. /**
  267. * @see TripalImporter::run()
  268. */
  269. public function run() {
  270. $arguments = $this->arguments['run_args'];
  271. $file_path = $this->arguments['files'][0]['file_path'];
  272. $organism_id = $arguments['organism_id'];
  273. $analysis_id = $arguments['analysis_id'];
  274. $add_only = $arguments['add_only'];
  275. $update = $arguments['update'];
  276. $refresh = FALSE;
  277. $remove = FALSE;
  278. $target_organism_id = $arguments['target_organism_id'];
  279. $target_type = $arguments['target_type'];
  280. $create_target = $arguments['create_target'];
  281. $start_line = $arguments['line_number'];
  282. $landmark_type = $arguments['landmark_type'];
  283. $alt_id_attr = $arguments['alt_id_attr'];
  284. $create_organism = $arguments['create_organism'];
  285. $re_mrna = $arguments['re_mrna'];
  286. $re_protein = $arguments['re_protein'];
  287. $skip_protein = $arguments['skip_protein'];
  288. // An array that stores CVterms that have been looked up so we don't have
  289. // to do the database query every time.
  290. $this->cvterm_lookup = [];
  291. $this->loadGFF3($file_path, $organism_id, $analysis_id,
  292. $add_only, $update, $refresh, $remove,
  293. $target_organism_id, $target_type, $create_target,
  294. $start_line, $landmark_type, $alt_id_attr, $create_organism,
  295. $re_mrna, $re_protein, $skip_protein);
  296. }
  297. /**
  298. * Actually load a GFF3 file. This is the function called by tripal jobs
  299. *
  300. * @param $gff_file
  301. * The full path to the GFF file on the filesystem
  302. * @param $organism_id
  303. * The organism_id of the organism to which the features in the GFF belong
  304. * @param $analysis_id
  305. * The anlaysis_id of the analysis from which the features in the GFF were
  306. * generated
  307. * @param $add_only
  308. * Set to 1 if feature should be added only. In the case where a feature
  309. * already exists, it will not be updated. Default is 0
  310. * @param $update
  311. * Set to 1 to update existing features. New features will be added.
  312. * Attributes for a feature that are not present in the GFF but which are
  313. * present in the database will not be altered. Default is 1
  314. * @param $refresh
  315. * Set to 1 to update existing features. New features will be added.
  316. * Attributes for a feature that are not present in the GFF but which are
  317. * present in the database will be removed. Default is 0
  318. * @param $remove
  319. * Set to 1 to remove features present in the GFF file that exist in the
  320. * database. Default is 0.
  321. * @param $target_organism_id
  322. * If the GFF file contains a 'Target' attribute then the feature and the
  323. * target will have an alignment created, but to find the proper target
  324. * feature the target organism must also be known. If different from the
  325. * organism specified for the GFF file, then use this argument to specify
  326. * the target organism. Only use this argument if all target sequences
  327. * belong to the same species. If the targets in the GFF file belong to
  328. * multiple different species then the organism must be specified using the
  329. * 'target_organism=genus:species' attribute in the GFF file. Default is
  330. * NULL.
  331. * @param $target_type
  332. * If the GFF file contains a 'Target' attribute then the feature and the
  333. * target will have an alignment created, but to find the proper target
  334. * feature the target organism must also be known. This can be used to
  335. * specify the target feature type to help with identification of the
  336. * target
  337. * feature. Only use this argument if all target sequences types are the
  338. * same. If the targets are of different types then the type must be
  339. * specified using the 'target_type=type' attribute in the GFF file. This
  340. * must be a valid Sequence Ontology (SO) term. Default is NULL
  341. * @param $create_target
  342. * Set to 1 to create the target feature if it cannot be found in the
  343. * database. Default is 0
  344. * @param $start_line
  345. * Set this to the line in the GFF file where importing should start. This
  346. * is useful for testing and debugging GFF files that may have problems and
  347. * you want to start at a particular line to speed testing. Default = 1
  348. * @param $landmark_type
  349. * Use this argument to specify a Sequence Ontology term name for the
  350. * landmark sequences in the GFF fie (e.g. 'chromosome'), if the GFF file
  351. * contains a
  352. * '##sequence-region' line that describes the landmark sequences. Default
  353. * = ''
  354. * @param $alt_id_attr
  355. * Sometimes lines in the GFF file are missing the required ID attribute
  356. * that specifies the unique name of the feature. If so, you may specify
  357. * the name of an existing attribute to use for the ID.
  358. * @param $create_organism
  359. * The Tripal GFF loader supports the "organism" attribute. This allows
  360. * features of a different organism to be aligned to the landmark sequence
  361. * of another species. The format of the attribute is
  362. * "organism=[genus]:[species]", where [genus] is the organism's genus and
  363. * [species] is the species name. Check this box to automatically add the
  364. * organism to the database if it does not already exists. Otherwise lines
  365. * with an oraganism attribute where the organism is not present in the
  366. * database will be skipped.
  367. * @param $re_mrna A
  368. * regular expression to extract portions from mRNA id
  369. * @param $re_protein A
  370. * replacement string to generate the protein id
  371. * @PARAM $skip_protein
  372. * BOOL: Will the loader create the proteins inferred from the CDS?
  373. *
  374. * @ingroup gff3_loader
  375. */
  376. private function loadGFF3($gff_file, $organism_id, $analysis_id,
  377. $add_only = 0, $update = 1, $refresh = 0, $remove = 0,
  378. $target_organism_id = NULL, $target_type = NULL, $create_target = 0,
  379. $start_line = 1, $landmark_type = '', $alt_id_attr = '', $create_organism = FALSE,
  380. $re_mrna = '', $re_protein = '', $skip_protein = 0) {
  381. $ret = [];
  382. $date = getdate();
  383. // An array that stores Landmarks that have been looked up so we don't have
  384. // to do the database query every time.
  385. $landmark_lookup = [];
  386. // empty the temp tables
  387. $sql = "DELETE FROM {tripal_gff_temp}";
  388. chado_query($sql);
  389. $sql = "DELETE FROM {tripal_gffcds_temp}";
  390. chado_query($sql);
  391. $sql = "DELETE FROM {tripal_gffprotein_temp}";
  392. chado_query($sql);
  393. // check to see if the file is located local to Drupal
  394. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  395. if (!file_exists($dfile)) {
  396. // if not local to Drupal, the file must be someplace else, just use
  397. // the full path provided
  398. $dfile = $gff_file;
  399. }
  400. if (!file_exists($dfile)) {
  401. throw new Exception(t("Cannot find the file: !dfile", ['!dfile' => $dfile]));
  402. }
  403. $this->logMessage("Opening !gff_file", ['!gff_file' => $gff_file]);
  404. //$lines = file($dfile,FILE_SKIP_EMPTY_LINES);
  405. $fh = fopen($dfile, 'r');
  406. if (!$fh) {
  407. throw new Exception(t("Cannot open file: !dfile", ['!dfile' => $dfile]));
  408. }
  409. $filesize = filesize($dfile);
  410. $this->setTotalItems($filesize);
  411. // get the controlled vocaubulary that we'll be using. The
  412. // default is the 'sequence' ontology
  413. $sql = "SELECT * FROM {cv} WHERE name = :cvname";
  414. $cv = chado_query($sql, [':cvname' => 'feature_property'])->fetchObject();
  415. if (!$cv) {
  416. throw new Exception(t("Cannot find the 'feature_property' ontology'", []));
  417. }
  418. $this->feature_property_cv_id = $cv->cv_id;
  419. $cv = chado_query($sql, [':cvname' => 'sequence'])->fetchObject();
  420. if (!$cv) {
  421. throw new Exception(t("Cannot find the 'sequence' ontology", []));
  422. }
  423. $this->sequence_cv_id = $cv->cv_id;
  424. // get the organism for which this GFF3 file belongs
  425. $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
  426. $organism = chado_query($sql, [':organism_id' => $organism_id])->fetchObject();
  427. $in_fasta = 0;
  428. $line_num = 0;
  429. $num_read = 0;
  430. // If a landmark type was provided then pre-retrieve that.
  431. if ($landmark_type) {
  432. $landmark_cvterm = $this->getCvterm($landmark_type);
  433. if (!$landmark_cvterm) {
  434. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', ['%landmark_type' => $landmark_type]));
  435. }
  436. }
  437. // iterate through each line of the GFF file
  438. while ($line = fgets($fh)) {
  439. $line_num++;
  440. $this->line_num = $line_num;
  441. $size = drupal_strlen($line);
  442. $this->addItemsHandled($size);
  443. $num_read += $size;
  444. if ($line_num < $start_line) {
  445. continue;
  446. }
  447. // check to see if we have FASTA section, if so then set the variable
  448. // to start parsing
  449. if (preg_match('/^##FASTA/i', $line)) {
  450. $this->logMessage("Parsing FASTA portion...");
  451. if ($remove) {
  452. // we're done because this is a delete operation so break out of the loop.
  453. break;
  454. }
  455. $this->loadFasta($fh, $interval, $num_read, $line_num, $filesize);
  456. continue;
  457. }
  458. // if the ##sequence-region line is present then we want to add a new feature
  459. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  460. $rid = $region_matches[1];
  461. $rstart = $region_matches[2];
  462. $rend = $region_matches[3];
  463. if ($landmark_type) {
  464. $this->loadFeature($organism, $analysis_id, $landmark_cvterm, $rid,
  465. $rid, '', 'f', 'f', 1, 0);
  466. }
  467. continue;
  468. }
  469. // skip comments
  470. if (preg_match('/^#/', $line)) {
  471. continue;
  472. }
  473. // skip empty lines
  474. if (preg_match('/^\s*$/', $line)) {
  475. continue;
  476. }
  477. // get the columns
  478. $cols = explode("\t", $line);
  479. if (sizeof($cols) != 9) {
  480. throw new Exception(t('Improper number of columns on line %line_num', ['%line_num' => $line_num]));
  481. }
  482. // get the column values
  483. $landmark = $cols[0];
  484. $source = $cols[1];
  485. $type = $cols[2];
  486. $start = $cols[3];
  487. $end = $cols[4];
  488. $score = $cols[5];
  489. $strand = $cols[6];
  490. $phase = $cols[7];
  491. $attrs = explode(";", $cols[8]); // split by a semicolon
  492. // ready the start and stop for chado. Chado expects these positions
  493. // to be zero-based, so we substract 1 from the fmin
  494. $fmin = $start - 1;
  495. $fmax = $end;
  496. if ($end < $start) {
  497. $fmin = $end - 1;
  498. $fmax = $start;
  499. }
  500. // format the strand for chado
  501. if (strcmp($strand, '.') == 0) {
  502. $strand = 0;
  503. }
  504. elseif (strcmp($strand, '+') == 0) {
  505. $strand = 1;
  506. }
  507. elseif (strcmp($strand, '-') == 0) {
  508. $strand = -1;
  509. }
  510. if (strcmp($phase, '.') == 0) {
  511. if ($type == 'CDS') {
  512. $phase = '0';
  513. }
  514. else {
  515. $phase = '';
  516. }
  517. }
  518. $cvterm = $this->getCvterm($type);
  519. if (!$cvterm) {
  520. throw new Exception(t('Cannot find feature term \'%type\' on line %line_num of the GFF file',
  521. ['%type' => $type, '%line_num' => $line_num]));
  522. }
  523. // break apart each of the attributes
  524. $tags = [];
  525. $attr_name = '';
  526. $attr_uniquename = '';
  527. $attr_residue_info = '';
  528. $attr_locgroup = 0;
  529. $attr_fmin_partial = 'f';
  530. $attr_fmax_partial = 'f';
  531. $attr_is_obsolete = 'f';
  532. $attr_is_analysis = 'f';
  533. $attr_others = [];
  534. $residues = '';
  535. // the organism to which a feature belongs can be set in the GFF
  536. // file using the 'organism' attribute. By default we
  537. // set the $feature_organism variable to the default organism for the landmark
  538. $attr_organism = '';
  539. $feature_organism = $organism;
  540. foreach ($attrs as $attr) {
  541. $attr = rtrim($attr);
  542. $attr = ltrim($attr);
  543. if (strcmp($attr, '') == 0) {
  544. continue;
  545. }
  546. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  547. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  548. ['%line_num' => $line_num, '%attr' => $attr]));
  549. }
  550. // break apart each tag
  551. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  552. // multiple instances of an attribute are separated by commas
  553. $tag_name = $tag[0];
  554. if (!array_key_exists($tag_name, $tags)) {
  555. $tags[$tag_name] = [];
  556. }
  557. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  558. // replace the URL escape codes for each tag
  559. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  560. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  561. }
  562. // get the name and ID tags
  563. $skip_feature = 0; // if there is a problem with any of the attributes this variable gets set
  564. if (strcmp($tag_name, 'ID') == 0) {
  565. $attr_uniquename = urldecode($tag[1]);
  566. }
  567. elseif (strcmp($tag_name, 'Name') == 0) {
  568. $attr_name = urldecode($tag[1]);
  569. }
  570. elseif (strcmp($tag_name, 'organism') == 0) {
  571. $attr_organism = urldecode($tag[1]);
  572. $org_matches = [];
  573. if (preg_match('/^(.*?):(.*?)$/', $attr_organism, $org_matches)) {
  574. $values = [
  575. 'genus' => $org_matches[1],
  576. 'species' => $org_matches[2],
  577. ];
  578. $org = chado_select_record('organism', ["*"], $values);
  579. if (count($org) == 0) {
  580. if ($create_organism) {
  581. $feature_organism = (object) chado_insert_record('organism', $values, array(
  582. 'skip_validation' => TRUE,
  583. ));
  584. if (!$feature_organism) {
  585. $this->logMessage("Could not add the organism, '%org', from line %line. Skipping this line.",
  586. [
  587. '%org' => $attr_organism,
  588. '%line' => $line_num,
  589. ], TRIPAL_ERROR);
  590. $skip_feature = 1;
  591. }
  592. }
  593. else {
  594. $this->logMessage("The organism attribute '%org' on line %line does not exist. Skipping this line.",
  595. [
  596. '%org' => $attr_organism,
  597. '%line' => $line_num,
  598. ], TRIPAL_ERROR);
  599. $skip_feature = 1;
  600. }
  601. }
  602. else {
  603. // We found the organism in the database so use it.
  604. $feature_organism = $org[0];
  605. }
  606. }
  607. else {
  608. $this->logMessage("The organism attribute '%org' on line %line is not properly formated. It " .
  609. "should be of the form: organism=Genus:species. Skipping this line.",
  610. ['%org' => $attr_organism, '%line' => $line_num], TRIPAL_ERROR);
  611. $skip_feature = 1;
  612. }
  613. }
  614. // Get the list of non-reserved attributes.
  615. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  616. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  617. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  618. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  619. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  620. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  621. foreach ($tags[$tag_name] as $value) {
  622. $attr_others[$tag_name][] = $value;
  623. }
  624. }
  625. }
  626. // If neither name nor uniquename are provided then generate one.
  627. if (!$attr_uniquename and !$attr_name) {
  628. // Check if an alternate ID field is suggested, if so, then use
  629. // that for the name.
  630. if (array_key_exists($alt_id_attr, $tags)) {
  631. $attr_uniquename = $tags[$alt_id_attr][0];
  632. $attr_name = $attr_uniquename;
  633. }
  634. // If the row has a parent then generate a uniquename using the parent name
  635. // add the date to the name in the event there are more than one child with
  636. // the same parent.
  637. elseif (array_key_exists('Parent', $tags)) {
  638. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  639. $attr_name = $attr_uniquename;
  640. }
  641. // Generate a unique name based on the date, type and location
  642. // and set the name to simply be the type.
  643. else {
  644. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  645. $attr_name = $type;
  646. }
  647. }
  648. // If a name is not specified then use the unique name as the name
  649. if (strcmp($attr_name, '') == 0) {
  650. $attr_name = $attr_uniquename;
  651. }
  652. // If an ID attribute is not specified then we must generate a
  653. // unique ID. Do this by combining the attribute name with the date
  654. // and line number.
  655. if (!$attr_uniquename) {
  656. $attr_uniquename = $attr_name . '-' . $date[0] . '-' . $line_num;
  657. }
  658. // Make sure the landmark sequence exists in the database. If the user
  659. // has not specified a landmark type (and it's not required in the GFF
  660. // format) then we don't know the type of the landmark so we'll hope
  661. // that it's unique across all types for the organism. Only do this
  662. // test if the landmark and the feature are different.
  663. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0) and !in_array($landmark, $landmark_lookup)) {
  664. $select = [
  665. 'organism_id' => $organism->organism_id,
  666. 'uniquename' => $landmark,
  667. ];
  668. $columns = ['count(*) as num_landmarks'];
  669. if ($landmark_type) {
  670. $select['type_id'] = [
  671. 'name' => $landmark_type,
  672. ];
  673. }
  674. $count = chado_select_record('feature', $columns, $select);
  675. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  676. // now look for the landmark using the name rather than uniquename.
  677. $select = [
  678. 'organism_id' => $organism->organism_id,
  679. 'name' => $landmark,
  680. ];
  681. $columns = ['count(*) as num_landmarks'];
  682. if ($landmark_type) {
  683. $select['type_id'] = [
  684. 'name' => $landmark_type,
  685. ];
  686. }
  687. $count = chado_select_record('feature', $columns, $select);
  688. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  689. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  690. "Please add the landmark and then retry the import of this GFF3 " .
  691. "file", [
  692. '%landmark' => $landmark,
  693. '%species' => $organism->genus . " " . $organism->species,
  694. ]));
  695. }
  696. elseif ($count[0]->num_landmarks > 1) {
  697. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species) " .
  698. "Cannot continue", [
  699. '%landmark' => $landmark,
  700. '%species' => $organism->genus . " " . $organism->species,
  701. ]));
  702. }
  703. }
  704. if ($count[0]->num_landmarks > 1) {
  705. throw new Exception(t("The landmark '%landmark' is not unique for this organism. " .
  706. "The features cannot be associated", ['%landmark' => $landmark]));
  707. }
  708. // The landmark was found, remember it
  709. $landmark_lookup[] = $landmark;
  710. }
  711. // Add or update the feature and all properties.
  712. if ($update or $refresh or $add_only) {
  713. // Add/update the feature.
  714. $feature = $this->loadFeature($feature_organism, $analysis_id, $cvterm,
  715. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  716. $attr_is_obsolete, $add_only, $score);
  717. if ($feature) {
  718. // Add a record for this feature to the tripal_gff_temp table for
  719. // later lookup.
  720. $values = [
  721. 'feature_id' => $feature->getID(),
  722. 'organism_id' => $feature->getValue('organism_id'),
  723. 'type_name' => $type,
  724. 'uniquename' => $feature->getValue('uniquename'),
  725. ];
  726. // make sure this record doesn't already exist in our temp table
  727. $results = chado_select_record('tripal_gff_temp', ['*'], $values);
  728. if (count($results) == 0) {
  729. $result = chado_insert_record('tripal_gff_temp', $values);
  730. if (!$result) {
  731. throw new Exception(t("Cound not save record in temporary table, Cannot continue.", []));
  732. }
  733. }
  734. // Add/update the featureloc if the landmark and the ID are not the
  735. // same if they are the same then this entry in the GFF is probably
  736. // a landmark identifier.
  737. if (strcmp($landmark, $attr_uniquename) != 0) {
  738. $this->loadFeatureLoc($feature, $organism,
  739. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  740. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  741. }
  742. // Add any aliases for this feature.
  743. if (array_key_exists('Alias', $tags)) {
  744. $this->loadAlias($feature, $tags['Alias']);
  745. }
  746. // Add any dbxrefs for this feature.
  747. if (array_key_exists('Dbxref', $tags)) {
  748. $this->loadDbxref($feature, $tags['Dbxref']);
  749. }
  750. // Add any ontology terms for this feature.
  751. if (array_key_exists('Ontology_term', $tags)) {
  752. $this->loadOntology($feature, $tags['Ontology_term']);
  753. }
  754. // Add parent relationships.
  755. if (array_key_exists('Parent', $tags)) {
  756. $this->loadParents($feature, $cvterm, $tags['Parent'],
  757. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  758. }
  759. // Add target relationships.
  760. if (array_key_exists('Target', $tags)) {
  761. $this->loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  762. }
  763. // Add gap information. This goes in simply as a property.
  764. if (array_key_exists('Gap', $tags)) {
  765. foreach ($tags['Gap'] as $value) {
  766. $this->loadProperty($feature, 'Gap', $value);
  767. }
  768. }
  769. // Add notes. This goes in simply as a property.
  770. if (array_key_exists('Note', $tags)) {
  771. foreach ($tags['Note'] as $value) {
  772. $this->loadProperty($feature, 'Note', $value);
  773. }
  774. }
  775. // Add the Derives_from relationship (e.g. polycistronic genes).
  776. if (array_key_exists('Derives_from', $tags)) {
  777. $this->loadDerivesFrom($feature, $cvterm, $tags['Derives_from'][0],
  778. $feature_organism, $fmin, $fmax);
  779. }
  780. // Add in the GFF3_source dbxref so that GBrowse can find the feature
  781. // using the source column.
  782. $source_ref = ['GFF_source:' . $source];
  783. $this->loadDbxref($feature, $source_ref);
  784. // Add any additional attributes.
  785. if ($attr_others) {
  786. foreach ($attr_others as $tag_name => $values) {
  787. foreach ($values as $value) {
  788. $this->loadProperty($feature, $tag_name, $value);
  789. }
  790. }
  791. }
  792. }
  793. }
  794. }
  795. // Do some last bit of processing.
  796. if (!$remove) {
  797. // First, add any protein sequences if needed.
  798. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  799. $has_cds = chado_query($sql)->fetchField();
  800. if ($has_cds) {
  801. $this->logMessage("\nAdding protein sequences if CDS exist and no proteins in GFF...");
  802. $sql = "
  803. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  804. CVT.cvterm_id, CVT.name as feature_type,
  805. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  806. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  807. TGPT.fmax as protein_fmax, FLM.uniquename as landmark
  808. FROM {tripal_gffcds_temp} TGCT
  809. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  810. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  811. INNER JOIN {featureloc} L on F.feature_id = L.feature_id
  812. INNER JOIN {feature} FLM on L.srcfeature_id = FLM.feature_id
  813. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  814. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  815. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
  816. ";
  817. $results = chado_query($sql);
  818. $protein_cvterm = $this->getCvterm('polypeptide');
  819. while ($result = $results->fetchObject()) {
  820. // If a protein exists with this same parent then don't add a new
  821. // protein.
  822. if (!$result->protein_id) {
  823. // Get details about this protein
  824. if ($re_mrna and $re_protein) {
  825. // We use a regex to generate protein name from mRNA name
  826. $uname = preg_replace("/$re_mrna/", $re_protein, $result->uniquename);
  827. $name = $result->name;
  828. }
  829. else {
  830. // No regex, use the default '-protein' suffix
  831. $uname = $result->uniquename . '-protein';
  832. $name = $result->name;
  833. }
  834. $values = [
  835. 'parent_id' => $result->feature_id,
  836. 'fmin' => $result->fmin,
  837. ];
  838. $min_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  839. $values = [
  840. 'parent_id' => $result->feature_id,
  841. 'fmax' => $result->fmax,
  842. ];
  843. $max_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  844. $pfmin = $result->fmin;
  845. $pfmax = $result->fmax;
  846. if ($result->strand == '-1') {
  847. $pfmax -= $max_phase[0]->phase;
  848. }
  849. else {
  850. $pfmin += $min_phase[0]->phase;
  851. }
  852. if ($skip_protein == 0) {
  853. // Add the new protein record.
  854. $feature = $this->loadFeature($organism, $analysis_id,
  855. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  856. // Add the derives_from relationship.
  857. $cvterm = $this->getCvterm($result->feature_type);
  858. $this->loadDerivesFrom($feature, $cvterm,
  859. $result->uniquename, $organism, $pfmin, $pfmax);
  860. // Add the featureloc record. Set the start of the protein to
  861. // be the start of the coding sequence minus the phase.
  862. $this->loadFeatureLoc($feature, $organism, $result->landmark,
  863. $pfmin, $pfmax, $result->strand, '', 'f', 'f', '', 0);
  864. }
  865. }
  866. }
  867. }
  868. $this->logMessage("Setting ranks of children...");
  869. // Get features in a relationship that are also children of an alignment.
  870. $sql = "
  871. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  872. F.uniquename, FL.strand
  873. FROM {tripal_gff_temp} TGT
  874. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  875. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  876. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  877. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  878. WHERE CVT.name = 'part_of'
  879. ";
  880. $parents = chado_query($sql);
  881. // Build and prepare the SQL for selecting the children relationship.
  882. $sel_gffchildren_sql = "
  883. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  884. FROM {feature_relationship} FR
  885. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  886. INNER JOIN {cvterm} CVT on CVT.cvterm_id = FR.type_id
  887. WHERE FR.object_id = :feature_id AND CVT.name = 'part_of'
  888. ORDER BY FL.fmin ASC
  889. ";
  890. // Now set the rank of any parent/child relationships. The order is based
  891. // on the fmin. The start rank is 1. This allows features with other
  892. // relationships to be '0' (the default), and doesn't interfer with the
  893. // ordering defined here.
  894. $num_recs = $parents->rowCount();
  895. $i = 1;
  896. while ($parent = $parents->fetchObject()) {
  897. // get the children
  898. $result = chado_query($sel_gffchildren_sql, [':feature_id' => $parent->feature_id]);
  899. // build an array of the children
  900. $children = [];
  901. while ($child = $result->fetchObject()) {
  902. $children[] = $child;
  903. }
  904. // the children list comes sorted in ascending fmin
  905. // but if the parent is on the reverse strand we need to
  906. // reverse the order of the children.
  907. if ($parent->strand == -1) {
  908. arsort($children);
  909. }
  910. // first set the ranks to a negative number so that we don't
  911. // get a duplicate error message when we try to change any of them
  912. $rank = -1;
  913. foreach ($children as $child) {
  914. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  915. $values = ['rank' => $rank];
  916. chado_update_record('feature_relationship', $match, $values);
  917. $rank--;
  918. }
  919. // now set the rank correctly. The rank should start at 0.
  920. $rank = 0;
  921. foreach ($children as $child) {
  922. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  923. $values = ['rank' => $rank];
  924. chado_update_record('feature_relationship', $match, $values);
  925. $rank++;
  926. }
  927. $i++;
  928. }
  929. }
  930. return 1;
  931. }
  932. /**
  933. * Load a controlled vocabulary term.
  934. *
  935. * This method first checks if the term has already been loaded in the
  936. * cvterm_lookup array, which helps a lot with performance.
  937. *
  938. * @param $type
  939. * @param $cv_id
  940. *
  941. * @ingroup gff3_loader
  942. */
  943. private function getCvterm($type, $cv_id = NULL) {
  944. if (!isset($cv_id)) {
  945. $cv_id = $this->sequence_cv_id;
  946. }
  947. if (array_key_exists($type, $this->cvterm_lookup)) {
  948. return $this->cvterm_lookup[$type];
  949. }
  950. else {
  951. $sel_cvterm_sql = "
  952. SELECT CVT.cvterm_id
  953. FROM {cvterm} CVT
  954. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  955. WHERE CVT.cv_id = {$cv_id} and
  956. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  957. ";
  958. $result = chado_query($sel_cvterm_sql, [
  959. ':name' => $type,
  960. ':synonym' => $type,
  961. ]);
  962. $cvterm = $result->fetchObject() ?? NULL;
  963. if ($cvterm) {
  964. $cvterm = chado_get_cvterm(array('cvterm_id' => $cvterm->cvterm_id)) ?? NULL;
  965. }
  966. $this->cvterm_lookup[$type] = $cvterm;
  967. return $cvterm;
  968. }
  969. }
  970. /**
  971. * Load the derives from attribute for a gff3 feature
  972. *
  973. * @param $feature
  974. * @param $subject
  975. * @param $organism
  976. *
  977. * @ingroup gff3_loader
  978. */
  979. private function loadDerivesFrom($feature, $cvterm, $object,
  980. $organism, $fmin, $fmax) {
  981. $type = $cvterm->name;
  982. $derivesfrom_term = $this->getCvterm('derives_from');
  983. // First look for the object feature in the temp table to get it's type.
  984. $values = [
  985. 'organism_id' => $organism->organism_id,
  986. 'uniquename' => $object,
  987. ];
  988. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  989. $type_id = NULL;
  990. if (count($result) > 0) {
  991. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  992. }
  993. // If the object wasn't in the temp table then look for it in the
  994. // feature table and get it's type.
  995. if (!$type_id) {
  996. $result = chado_select_record('feature', ['type_id'], $values);
  997. if (count($result) > 1) {
  998. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  999. ['!subject' => $object], TRIPAL_WARNING);
  1000. return;
  1001. }
  1002. else {
  1003. if (count($result) == 0) {
  1004. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  1005. ['!subject' => $object], TRIPAL_WARNING);
  1006. return '';
  1007. }
  1008. else {
  1009. $type_id = $result->type_id;
  1010. }
  1011. }
  1012. }
  1013. // Get the object feature.
  1014. $match = [
  1015. 'organism_id' => $organism->organism_id,
  1016. 'uniquename' => $object,
  1017. 'type_id' => $type_id,
  1018. ];
  1019. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  1020. if (count($ofeature) == 0) {
  1021. $this->logMessage("Could not add 'Derives_from' relationship " .
  1022. "for %uniquename and %subject. Subject feature, '%subject', " .
  1023. "cannot be found.", [
  1024. '%uniquename' => $feature->getValue('uniquename'),
  1025. '%subject' => $subject,
  1026. ], TRIPAL_ERROR);
  1027. return;
  1028. }
  1029. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  1030. if ($type == 'protein' or $type == 'polypeptide') {
  1031. $values = [
  1032. 'feature_id' => $feature->getID(),
  1033. 'parent_id' => $ofeature[0]->feature_id,
  1034. 'fmin' => $fmin,
  1035. 'fmax' => $fmax,
  1036. ];
  1037. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  1038. if (!$result) {
  1039. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  1040. }
  1041. }
  1042. // Now check to see if the relationship already exists. If it does
  1043. // then just return.
  1044. $values = [
  1045. 'object_id' => $ofeature[0]->feature_id,
  1046. 'subject_id' => $feature->getID(),
  1047. 'type_id' => $derivesfrom_term->cvterm_id,
  1048. 'rank' => 0,
  1049. ];
  1050. $rel = chado_select_record('feature_relationship', ['*'], $values);
  1051. if (count($rel) > 0) {
  1052. return;
  1053. }
  1054. // finally insert the relationship if it doesn't exist
  1055. $ret = chado_insert_record('feature_relationship', $values, array(
  1056. 'skip_validation' => TRUE,
  1057. ));
  1058. if (!$ret) {
  1059. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  1060. [
  1061. ':uniquename' => $feature->getValue('uniquename'),
  1062. ':subject' => $subject,
  1063. ], TRIPAL_WARNING);
  1064. }
  1065. }
  1066. /**
  1067. * Load the parents for a gff3 feature
  1068. *
  1069. * @param $feature
  1070. * @param $cvterm
  1071. * @param $parents
  1072. * @param $organism_id
  1073. * @param $fmin
  1074. *
  1075. * @ingroup gff3_loader
  1076. */
  1077. private function loadParents($feature, $cvterm, $parents,
  1078. $organism_id, $strand, $phase, $fmin, $fmax) {
  1079. $uname = $feature->getValue('uniquename');
  1080. $type = $cvterm->name;
  1081. $rel_type = 'part_of';
  1082. $relcvterm = $this->getCvterm($rel_type);
  1083. if (!$relcvterm) {
  1084. throw new Exception(t("Cannot find the term, 'part_of', from the sequence ontology. This term is used for associating parent and children features. Please check that the ontology is fully imported."));
  1085. }
  1086. // Iterate through the parents in the list.
  1087. foreach ($parents as $parent) {
  1088. // Get the parent cvterm.
  1089. $values = [
  1090. 'organism_id' => $organism_id,
  1091. 'uniquename' => $parent,
  1092. ];
  1093. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  1094. if (count($result) == 0) {
  1095. $this->logMessage("Cannot find parent: %parent.", ['%parent' => $parent], TRIPAL_WARNING);
  1096. return '';
  1097. }
  1098. $parent_type = $result[0]->type_name;
  1099. // try to find the parent
  1100. $parentcvterm = $this->getCvterm($parent_type);
  1101. $values = [
  1102. 'organism_id' => $organism_id,
  1103. 'uniquename' => $parent,
  1104. 'type_id' => $parentcvterm->cvterm_id,
  1105. ];
  1106. $result = chado_select_record('feature', ['feature_id'], $values);
  1107. $parent_feature = $result[0];
  1108. // if the parent exists then add the relationship otherwise print error and skip
  1109. if ($parent_feature) {
  1110. // check to see if the relationship already exists
  1111. $values = [
  1112. 'object_id' => $parent_feature->feature_id,
  1113. 'subject_id' => $feature->getID(),
  1114. 'type_id' => $relcvterm->cvterm_id,
  1115. ];
  1116. $rel = chado_select_record('feature_relationship', ['*'], $values);
  1117. if (count($rel) > 0) {
  1118. }
  1119. else {
  1120. // the relationship doesn't already exist, so add it.
  1121. $values = [
  1122. 'subject_id' => $feature->getID(),
  1123. 'object_id' => $parent_feature->feature_id,
  1124. 'type_id' => $relcvterm->cvterm_id,
  1125. ];
  1126. $result = chado_insert_record('feature_relationship', $values, array(
  1127. 'skip_validation' => TRUE,
  1128. ));
  1129. if (!$result) {
  1130. $this->logMessage("Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type).",
  1131. [], TRIPAL_WARNING);
  1132. }
  1133. }
  1134. // If this feature is a CDS and now that we know the parent we can
  1135. // add it to the tripal_gffcds_temp table for later lookup.
  1136. if ($type == 'CDS') {
  1137. $values = [
  1138. 'feature_id' => $feature->getID(),
  1139. 'parent_id' => $parent_feature->feature_id,
  1140. 'fmin' => $fmin,
  1141. 'fmax' => $fmax,
  1142. 'strand' => $strand,
  1143. ];
  1144. if (isset($phase)) {
  1145. $values['phase'] = $phase;
  1146. }
  1147. $result = chado_insert_record('tripal_gffcds_temp', $values, array(
  1148. 'skip_validation' => TRUE,
  1149. ));
  1150. if (!$result) {
  1151. throw new Exception(t("Cound not save record in temporary CDS table, Cannot continue.", []));
  1152. exit;
  1153. }
  1154. }
  1155. }
  1156. else {
  1157. $this->logMessage("Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent.",
  1158. [], TRIPAL_WARNING);
  1159. }
  1160. }
  1161. }
  1162. /**
  1163. * Load the dbxref attribute for a feature
  1164. *
  1165. * @param $feature
  1166. * @param $dbxrefs
  1167. *
  1168. * @ingroup gff3_loader
  1169. */
  1170. private function loadDbxref($feature, $dbxrefs) {
  1171. // iterate through each of the dbxrefs
  1172. foreach ($dbxrefs as $dbxref) {
  1173. // get the database name from the reference. If it doesn't exist then create one.
  1174. $ref = explode(":", $dbxref);
  1175. $dbname = trim($ref[0]);
  1176. $accession = trim($ref[1]);
  1177. // first look for the database name if it doesn't exist then create one.
  1178. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  1179. // can't be found then look for the name as is. If it still can't be found
  1180. // the create the database
  1181. $values = ['name' => "DB:$dbname"];
  1182. $db = chado_select_record('db', ['db_id'], $values);
  1183. if (count($db) == 0) {
  1184. $values = ['name' => "$dbname"];
  1185. $db = chado_select_record('db', ['db_id'], $values);
  1186. }
  1187. if (count($db) == 0) {
  1188. $values = [
  1189. 'name' => $dbname,
  1190. 'description' => 'Added automatically by the GFF loader',
  1191. ];
  1192. $success = chado_insert_record('db', $values, array(
  1193. 'skip_validation' => TRUE,
  1194. ));
  1195. if ($success) {
  1196. $values = ['name' => "$dbname"];
  1197. $db = chado_select_record('db', ['db_id'], $values);
  1198. }
  1199. else {
  1200. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  1201. return 0;
  1202. }
  1203. }
  1204. $db = $db[0];
  1205. // now check to see if the accession exists
  1206. $values = [
  1207. 'accession' => $accession,
  1208. 'db_id' => $db->db_id,
  1209. ];
  1210. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  1211. // if the accession doesn't exist then we want to add it
  1212. if (sizeof($dbxref) == 0) {
  1213. $values = [
  1214. 'db_id' => $db->db_id,
  1215. 'accession' => $accession,
  1216. 'version' => '',
  1217. ];
  1218. $ret = chado_insert_record('dbxref', $values, array(
  1219. 'skip_validation' => TRUE,
  1220. ));
  1221. $values = [
  1222. 'accession' => $accession,
  1223. 'db_id' => $db->db_id,
  1224. ];
  1225. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  1226. }
  1227. $dbxref = $dbxref[0];
  1228. // check to see if this feature dbxref already exists
  1229. $values = [
  1230. 'dbxref_id' => $dbxref->dbxref_id,
  1231. 'feature_id' => $feature->getID(),
  1232. ];
  1233. $fdbx = chado_select_record('feature_dbxref', ['feature_dbxref_id'], $values);
  1234. // now associate this feature with the database reference if it doesn't
  1235. // already exist
  1236. if (sizeof($fdbx) == 0) {
  1237. $values = [
  1238. 'dbxref_id' => $dbxref->dbxref_id,
  1239. 'feature_id' => $feature->getID(),
  1240. ];
  1241. $success = chado_insert_record('feature_dbxref', $values, array(
  1242. 'skip_validation' => TRUE,
  1243. ));
  1244. if (!$success) {
  1245. $this->logMessage("Failed to insert Dbxref: $dbname:$accession.", [], TRIPAL_WARNING);
  1246. return 0;
  1247. }
  1248. }
  1249. }
  1250. return 1;
  1251. }
  1252. /**
  1253. * Load the cvterms for a feature.
  1254. *
  1255. * Assumes there is a dbxref.accession matching a cvterm.name
  1256. *
  1257. * @param $feature
  1258. * @param $dbxrefs
  1259. *
  1260. * @ingroup gff3_loader
  1261. */
  1262. private function loadOntology($feature, $dbxrefs) {
  1263. // iterate through each of the dbxrefs
  1264. foreach ($dbxrefs as $dbxref) {
  1265. // get the database name from the reference. If it doesn't exist then create one.
  1266. $ref = explode(":", $dbxref);
  1267. $dbname = trim($ref[0]);
  1268. $accession = trim($ref[1]);
  1269. // first look for the database name
  1270. $db = chado_select_record('db', ['db_id'], ['name' => "DB:$dbname"]);
  1271. if (sizeof($db) == 0) {
  1272. // now look for the name without the 'DB:' prefix.
  1273. $db = chado_select_record('db', ['db_id'], ['name' => "$dbname"]);
  1274. if (sizeof($db) == 0) {
  1275. $this->logMessage("Database, $dbname, is not present. Cannot associate term: $dbname:$accession.", [], TRIPAL_WARNING);
  1276. continue;
  1277. }
  1278. }
  1279. $db = $db[0];
  1280. // now check to see if the accession exists
  1281. $dbxref = chado_select_record('dbxref', ['dbxref_id'],
  1282. ['accession' => $accession, 'db_id' => $db->db_id]);
  1283. if (sizeof($dbxref) == 0) {
  1284. $this->logMessage("Accession, $accession is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  1285. continue;
  1286. }
  1287. $dbxref = $dbxref[0];
  1288. // now check to see if the cvterm exists
  1289. $cvterm = chado_select_record('cvterm', ['cvterm_id'], [
  1290. 'dbxref_id' => $dbxref->dbxref_id,
  1291. ]);
  1292. // if it doesn't exist in the cvterm table, look for an alternate id
  1293. if (sizeof($cvterm) == 0) {
  1294. $cvterm = chado_select_record('cvterm_dbxref', ['cvterm_id'], [
  1295. 'dbxref_id' => $dbxref->dbxref_id,
  1296. ]);
  1297. if (sizeof($cvterm) == 0) {
  1298. $this->logMessage("CV Term is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  1299. continue;
  1300. }
  1301. }
  1302. $cvterm = $cvterm[0];
  1303. // check to see if this feature cvterm already exists
  1304. $fcvt = chado_select_record('feature_cvterm', ['feature_cvterm_id'],
  1305. [
  1306. 'cvterm_id' => $cvterm->cvterm_id,
  1307. 'feature_id' => $feature->getID(),
  1308. ]);
  1309. // now associate this feature with the cvterm if it doesn't already exist
  1310. if (sizeof($fcvt) == 0) {
  1311. $values = [
  1312. 'cvterm_id' => $cvterm->cvterm_id,
  1313. 'feature_id' => $feature->getID(),
  1314. 'pub_id' => [
  1315. 'uniquename' => 'null',
  1316. ],
  1317. ];
  1318. $success = chado_insert_record('feature_cvterm', $values, array(
  1319. 'skip_validation' => TRUE,
  1320. ));
  1321. if (!$success) {
  1322. $this->logMessage("Failed to insert ontology term: $dbname:$accession.", [], TRIPAL_WARNING);
  1323. continue;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * Load any aliases for a feature
  1330. *
  1331. * @param $feature
  1332. * @param $aliases
  1333. *
  1334. * @ingroup gff3_loader
  1335. */
  1336. private function loadAlias($feature, $aliases) {
  1337. // make sure we have a 'synonym_type' vocabulary
  1338. $select = ['name' => 'synonym_type'];
  1339. $results = chado_select_record('cv', ['*'], $select);
  1340. if (count($results) == 0) {
  1341. // insert the 'synonym_type' vocabulary
  1342. $values = [
  1343. 'name' => 'synonym_type',
  1344. 'definition' => 'vocabulary for synonym types',
  1345. ];
  1346. $success = chado_insert_record('cv', $values, array(
  1347. 'skip_validation' => TRUE,
  1348. ));
  1349. if (!$success) {
  1350. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  1351. return 0;
  1352. }
  1353. // now that we've added the cv we need to get the record
  1354. $results = chado_select_record('cv', ['*'], $select);
  1355. if (count($results) > 0) {
  1356. $syncv = $results[0];
  1357. }
  1358. }
  1359. else {
  1360. $syncv = $results[0];
  1361. }
  1362. // get the 'exact' cvterm, which is the type of synonym we're adding
  1363. $select = [
  1364. 'name' => 'exact',
  1365. 'cv_id' => [
  1366. 'name' => 'synonym_type',
  1367. ],
  1368. ];
  1369. $result = chado_select_record('cvterm', ['*'], $select);
  1370. if (count($result) == 0) {
  1371. $term = [
  1372. 'name' => 'exact',
  1373. 'id' => "synonym_type:exact",
  1374. 'definition' => '',
  1375. 'is_obsolete' => 0,
  1376. 'cv_name' => $syncv->name,
  1377. 'is_relationship' => FALSE,
  1378. ];
  1379. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  1380. if (!$syntype) {
  1381. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  1382. return 0;
  1383. }
  1384. }
  1385. else {
  1386. $syntype = $result[0];
  1387. }
  1388. // iterate through all of the aliases and add each one
  1389. foreach ($aliases as $alias) {
  1390. // check to see if the alias already exists in the synonym table
  1391. // if not, then add it
  1392. $select = [
  1393. 'name' => $alias,
  1394. 'type_id' => $syntype->cvterm_id,
  1395. ];
  1396. $result = chado_select_record('synonym', ['*'], $select);
  1397. if (count($result) == 0) {
  1398. $values = [
  1399. 'name' => $alias,
  1400. 'type_id' => $syntype->cvterm_id,
  1401. 'synonym_sgml' => '',
  1402. ];
  1403. $success = chado_insert_record('synonym', $values, array(
  1404. 'skip_validation' => TRUE,
  1405. ));
  1406. if (!$success) {
  1407. $this->logMessage("Cannot add alias $alias to synonym table.", [], TRIPAL_WARNING);
  1408. return 0;
  1409. }
  1410. $result = chado_select_record('synonym', ['*'], $select);
  1411. $synonym = $result[0];
  1412. }
  1413. else {
  1414. $synonym = $result[0];
  1415. }
  1416. // check to see if we have a NULL publication in the pub table. If not,
  1417. // then add one.
  1418. $select = ['uniquename' => 'null'];
  1419. $result = chado_select_record('pub', ['*'], $select);
  1420. if (count($result) == 0) {
  1421. $pub_sql = "
  1422. INSERT INTO {pub} (uniquename,type_id)
  1423. VALUES (:uname,
  1424. (SELECT cvterm_id
  1425. FROM {cvterm} CVT
  1426. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  1427. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  1428. WHERE CVT.name = :type_id))
  1429. ";
  1430. $status = chado_query($psql);
  1431. if (!$status) {
  1432. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  1433. return 0;
  1434. }
  1435. // insert the null pub
  1436. $result = chado_query($pub_sql, [
  1437. ':uname' => 'null',
  1438. ':type_id' => 'null',
  1439. ])->fetchObject();
  1440. if (!$result) {
  1441. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  1442. return 0;
  1443. }
  1444. $result = chado_select_record('pub', ['*'], $select);
  1445. $pub = $result[0];
  1446. }
  1447. else {
  1448. $pub = $result[0];
  1449. }
  1450. // check to see if the synonym exists in the feature_synonym table
  1451. // if not, then add it.
  1452. $values = [
  1453. 'synonym_id' => $synonym->synonym_id,
  1454. 'feature_id' => $feature->getID(),
  1455. 'pub_id' => $pub->pub_id,
  1456. ];
  1457. $columns = ['feature_synonym_id'];
  1458. $result = chado_select_record('feature_synonym', $columns, $values);
  1459. if (count($result) == 0) {
  1460. $values = [
  1461. 'synonym_id' => $synonym->synonym_id,
  1462. 'feature_id' => $feature->getID(),
  1463. 'pub_id' => $pub->pub_id,
  1464. ];
  1465. $success = chado_insert_record('feature_synonym', $values, array(
  1466. 'skip_validation' => TRUE,
  1467. ));
  1468. if (!$success) {
  1469. $this->logMessage("Cannot add alias $alias to feature synonym table.", [], TRIPAL_WARNING);
  1470. return 0;
  1471. }
  1472. }
  1473. }
  1474. return 1;
  1475. }
  1476. /**
  1477. * Create the feature record & link it to it's analysis
  1478. *
  1479. * @param $organism
  1480. * @param $analysis_id
  1481. * @param $cvterm
  1482. * @param $uniquename
  1483. * @param $name
  1484. * @param $residues
  1485. * @param $is_analysis
  1486. * @param $is_obsolete
  1487. * @param $add_only
  1488. * @param $score
  1489. *
  1490. * @ingroup gff3_loader
  1491. */
  1492. private function loadFeature($organism, $analysis_id, $cvterm, $uniquename,
  1493. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1494. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  1495. $is_obsolete = 'FALSE';
  1496. }
  1497. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  1498. $is_obsolete = 'TRUE';
  1499. }
  1500. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  1501. $is_analysis = 'FALSE';
  1502. }
  1503. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  1504. $is_analysis = 'TRUE';
  1505. }
  1506. // Check to see if the feature already exists.
  1507. $feature = new ChadoRecord('feature');
  1508. $feature->setValues([
  1509. 'organism_id' => $organism->organism_id,
  1510. 'uniquename' => $uniquename,
  1511. 'type_id' => $cvterm->cvterm_id,
  1512. ]);
  1513. $num_matches = $feature->find();
  1514. // Insert the feature if it does not exist otherwise perform an update.
  1515. if ($num_matches == 0) {
  1516. $feature->setValue('name', $name);
  1517. $feature->setValue('md5checksum', md5($residues));
  1518. $feature->setValue('is_analysis', $is_analysis);
  1519. $feature->setValue('is_obsolete', $is_obsolete);
  1520. try {
  1521. $feature->insert();
  1522. }
  1523. catch (Exception $e) {
  1524. $this->logMessage("Failed to insert feature '$uniquename' ($cvterm->name).", [], TRIPAL_WARNING);
  1525. return 0;
  1526. }
  1527. }
  1528. elseif (!$add_only) {
  1529. if ($num_matches > 1) {
  1530. $this->logMessage("Failed to update feature '$uniquename' ($cvterm->name). More than one feature exists with these criteria", [], TRIPAL_WARNING);
  1531. return 0;
  1532. }
  1533. $feature->setValue('name', $name);
  1534. $feature->setValue('md5checksum', md5($residues));
  1535. $feature->setValue('is_analysis', $is_analysis);
  1536. $feature->setValue('is_obsolete', $is_obsolete);
  1537. try {
  1538. $feature->update();
  1539. }
  1540. catch (Exception $e) {
  1541. $this->logMessage("Failed to update feature '$uniquename' ($cvterm->name).", [], TRIPAL_WARNING);
  1542. return 0;
  1543. }
  1544. }
  1545. else {
  1546. // The feature exists and we don't want to update it so return
  1547. // a value of 0. This will stop all downstream property additions
  1548. return $feature;
  1549. }
  1550. // Add the analysisfeature entry to the analysisfeature table if
  1551. // it doesn't already exist.
  1552. $af = new ChadoRecord('analysisfeature');
  1553. $af->setValues([
  1554. 'analysis_id' => $analysis_id,
  1555. 'feature_id' => $feature->getID(),
  1556. ]);
  1557. $num_afs = $af->find();
  1558. if ($num_afs == 0) {
  1559. // if a score is available then set that to be the significance field
  1560. if (strcmp($score, '.') != 0) {
  1561. $af->setValue('significance', $score);
  1562. }
  1563. try {
  1564. $af->insert();
  1565. }
  1566. catch (Exception $e) {
  1567. $this->logMessage("Could not add analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  1568. }
  1569. }
  1570. else {
  1571. // if a score is available then set that to be the significance field
  1572. $new_vals = [];
  1573. if (strcmp($score, '.') != 0) {
  1574. $af->setValue('significance', $score);
  1575. }
  1576. else {
  1577. $af->setValue('significance', '__NULL__');
  1578. }
  1579. if (!$add_only) {
  1580. try {
  1581. $af->update();
  1582. }
  1583. catch (Exception $e) {
  1584. $this->logMessage("Could not update analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  1585. }
  1586. }
  1587. }
  1588. return $feature;
  1589. }
  1590. /**
  1591. * Insert the location of the feature
  1592. *
  1593. * @param $feature
  1594. * @param $organism
  1595. * @param $landmark
  1596. * @param $fmin
  1597. * @param $fmax
  1598. * @param $strand
  1599. * @param $phase
  1600. * @param $is_fmin_partial
  1601. * @param $is_fmax_partial
  1602. * @param $residue_info
  1603. * @param $locgroup
  1604. * @param $landmark_type_id
  1605. * @param $landmark_organism_id
  1606. * @param $create_landmark
  1607. * @param $landmark_is_target
  1608. *
  1609. * @ingroup gff3_loader
  1610. */
  1611. private function loadFeatureLoc($feature, $organism, $landmark, $fmin,
  1612. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  1613. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  1614. $landmark_is_target = 0) {
  1615. $srcfeature = new ChadoRecord('feature');
  1616. $srcfeature->setValues([
  1617. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1618. 'uniquename' => $landmark,
  1619. ]);
  1620. if ($landmark_type_id) {
  1621. $srcfeature->setValue('type_id', $landmark_type_id);
  1622. }
  1623. $num_srcf = $srcfeature->find();
  1624. if ($num_srcf == 0) {
  1625. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  1626. // if we return only a single result then we can proceed. Otherwise give an
  1627. $srcfeature = new ChadoRecord('feature');
  1628. $srcfeature->setValues([
  1629. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1630. 'name' => $landmark,
  1631. ]);
  1632. if ($landmark_type_id) {
  1633. $srcfeature->setValue('type_id', $landmark_type_id);
  1634. }
  1635. $num_srcf = $srcfeature->find();
  1636. if ($num_srcf == 0) {
  1637. // if the landmark is the target feature in a matched alignment then try one more time to
  1638. // find it by querying any feature with the same uniquename. If we find one then use it.
  1639. if ($landmark_is_target) {
  1640. $srcfeature = new ChadoRecord('feature');
  1641. $srcfeature->setValues([
  1642. 'uniquename' => $landmark,
  1643. ]);
  1644. $num_srcf = $srcfeature->find();
  1645. if ($num_srcf > 1) {
  1646. $this->logMessage("Multiple landmarks exist for a matached target with the name: '%landmark'. Cannot " .
  1647. "resolve which one to use. Cannot add the feature location record.",
  1648. ['%landmark' => $landmark], TRIPAL_WARNING);
  1649. }
  1650. }
  1651. if ($num_srcf == 0) {
  1652. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  1653. // but only if we have a type id
  1654. if ($create_landmark and $landmark_type_id) {
  1655. $srcfeature = new ChadoRecord('feature');
  1656. $srcfeature->setValues([
  1657. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1658. 'name' => $landmark,
  1659. 'uniquename' => $landmark,
  1660. 'type_id' => $landmark_type_id,
  1661. ]);
  1662. try {
  1663. $srcfeature->insert();
  1664. }
  1665. catch (Exception $e) {
  1666. $this->logMessage("Cannot find landmark feature: '%landmark', nor could it be inserted. " . $e->getMessage() ,
  1667. ['%landmark' => $landmark], TRIPAL_WARNING);
  1668. return 0;
  1669. }
  1670. }
  1671. else {
  1672. $this->logMessage("Cannot find unique landmark feature: '%landmark'.",
  1673. ['%landmark' => $landmark], TRIPAL_WARNING);
  1674. return 0;
  1675. }
  1676. }
  1677. }
  1678. elseif ($num_srcf > 1) {
  1679. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1680. "resolve which one to use. Cannot add the feature location record.",
  1681. ['%landmark' => $landmark], TRIPAL_WARNING);
  1682. return 0;
  1683. }
  1684. }
  1685. elseif ($num_srcf > 1) {
  1686. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1687. "resolve which one to use. Cannot add the feature location record.",
  1688. ['%landmark' => $landmark, TRIPAL_WARNING]);
  1689. return 0;
  1690. }
  1691. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1692. // is_fmin_partial and is_fmax_partial, right now these are
  1693. // hardcoded to be false and 0 below.
  1694. // check to see if this featureloc already exists, but also keep track of the
  1695. // last rank value
  1696. $rank = 0;
  1697. $exists = 0;
  1698. $select = ['feature_id' => $feature->getID()];
  1699. $options = [
  1700. 'order_by' => [
  1701. 'rank' => 'ASC',
  1702. ],
  1703. ];
  1704. $locrecs = chado_select_record('featureloc', ['*'], $select, $options);
  1705. foreach ($locrecs as $locrec) {
  1706. // it is possible for the featureloc->srcfeature_id to be NULL.
  1707. // This can happen if the srcfeature is not known (according to chado
  1708. // table field descriptions). If it's null then just skip this entry.
  1709. if (!$locrec->srcfeature_id) {
  1710. continue;
  1711. }
  1712. $select = ['feature_id' => $locrec->srcfeature_id];
  1713. $columns = ['feature_id', 'name'];
  1714. $locsfeature = chado_select_record('feature', $columns, $select);
  1715. // the source feature name and at least the fmin and fmax must be the same
  1716. // for an update of the featureloc, otherwise we'll insert a new record.
  1717. if (strcmp($locsfeature[0]->name, $landmark) == 0 and
  1718. ($locrec->fmin == $fmin or $locrec->fmax == $fmax)) {
  1719. $featureloc = new ChadoRecord('featureloc');
  1720. $featureloc->setValue('featureloc_id', $locrec->featureloc_id);
  1721. $values = [];
  1722. $exists = 1;
  1723. if ($featureloc->fmin != $fmin) {
  1724. $featureloc->setValue('fmin', $fmin);
  1725. }
  1726. if ($featureloc->fmax != $fmax) {
  1727. $featureloc->setValue('fmax', $fmax);
  1728. }
  1729. if ($featureloc->strand != $strand) {
  1730. $featureloc->setValue('strand', $strand);
  1731. }
  1732. if (count($featureloc->getValues()) > 0) {
  1733. $featureloc->update();
  1734. }
  1735. }
  1736. $rank = $locrec->rank + 1;
  1737. }
  1738. if (!$exists) {
  1739. // this feature location is new so add it
  1740. if (strcmp($is_fmin_partial, 'f') == 0 or !$is_fmin_partial) {
  1741. $is_fmin_partial = 'FALSE';
  1742. }
  1743. elseif (strcmp($is_fmin_partial, 't') == 0 or $is_fmin_partial == 1) {
  1744. $is_fmin_partial = 'TRUE';
  1745. }
  1746. if (strcmp($is_fmax_partial, 'f') == 0 or !$is_fmax_partial) {
  1747. $is_fmax_partial = 'FALSE';
  1748. }
  1749. elseif (strcmp($is_fmax_partial, 't') == 0 or $is_fmax_partial == 1) {
  1750. $is_fmax_partial = 'TRUE';
  1751. }
  1752. $featureloc = new ChadoRecord('featureloc');
  1753. $featureloc->setValues([
  1754. 'feature_id' => $feature->getID(),
  1755. 'srcfeature_id' => $srcfeature->getID(),
  1756. 'fmin' => $fmin,
  1757. 'is_fmin_partial' => $is_fmin_partial,
  1758. 'fmax' => $fmax,
  1759. 'is_fmax_partial' => $is_fmax_partial,
  1760. 'strand' => $strand,
  1761. 'residue_info' => $residue_info,
  1762. 'locgroup' => $locgroup,
  1763. 'rank' => $rank,
  1764. ]);
  1765. if (!$residue_info) {
  1766. $featureloc->setValue('residue_info', '__NULL__');
  1767. }
  1768. if ($phase) {
  1769. $featureloc->setValue('phase', $phase);
  1770. }
  1771. $featureloc->insert();
  1772. }
  1773. return 1;
  1774. }
  1775. /**
  1776. * Load a preoprty (featurepop) for the feature
  1777. *
  1778. * @param $feature
  1779. * @param $property
  1780. * @param $value
  1781. *
  1782. * @ingroup gff3_loader
  1783. */
  1784. private function loadProperty($feature, $property, $value) {
  1785. // First make sure the cvterm exists. if not, then add it.
  1786. $result = $this->getCvterm($property, $this->feature_property_cv_id);
  1787. // If we don't have a property like this already, then add it otherwise,
  1788. // just return.
  1789. if (empty($result)) {
  1790. $term = [
  1791. 'id' => "local:$property",
  1792. 'name' => $property,
  1793. 'is_obsolete' => 0,
  1794. 'cv_name' => 'feature_property',
  1795. 'db_name' => 'local',
  1796. 'is_relationship' => FALSE,
  1797. ];
  1798. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  1799. if (!$cvterm) {
  1800. $this->logMessage("Cannot add cvterm, $property.", [], TRIPAL_WARNING);
  1801. return 0;
  1802. }
  1803. }
  1804. else {
  1805. $cvterm = $result;
  1806. }
  1807. // Check to see if the property already exists for this feature
  1808. // if it does but the value is unique then increment the rank and add it.
  1809. // if the value is not unique then don't add it.
  1810. $add = 1;
  1811. $rank = 0;
  1812. $select = [
  1813. 'feature_id' => $feature->getId(),
  1814. 'type_id' => $cvterm->cvterm_id,
  1815. ];
  1816. $options = [
  1817. 'order_by' => [
  1818. 'rank' => 'ASC',
  1819. ],
  1820. ];
  1821. $results = chado_select_record('featureprop', ['*'], $select, $options);
  1822. foreach ($results as $prop) {
  1823. if (strcmp($prop->value, $value) == 0) {
  1824. $add = NULL; // don't add it, it already exists
  1825. }
  1826. $rank = $prop->rank + 1;
  1827. }
  1828. // add the property if we pass the check above
  1829. if ($add) {
  1830. $values = [
  1831. 'feature_id' => $feature->getID(),
  1832. 'type_id' => $cvterm->cvterm_id,
  1833. 'value' => $value,
  1834. 'rank' => $rank,
  1835. ];
  1836. $result = chado_insert_record('featureprop', $values);
  1837. if (!$result) {
  1838. $this->logMessage("cannot add featureprop, $property.", [], TRIPAL_WARNING);
  1839. }
  1840. }
  1841. }
  1842. /**
  1843. * Load the FASTA sequences at the bottom of a GFF3 file
  1844. *
  1845. * @param $fh
  1846. * @param $interval
  1847. * @param $num_read
  1848. * @param $line_num
  1849. * @param $filesize
  1850. *
  1851. * @ingroup gff3_loader
  1852. */
  1853. private function loadFasta($fh, $interval, &$num_read, &$line_num, $filesize) {
  1854. $this->logMessage("Loading FASTA sequences...");
  1855. $residues = '';
  1856. $id = NULL;
  1857. // iterate through the remaining lines of the file
  1858. while ($line = fgets($fh)) {
  1859. $line_num++;
  1860. $size = drupal_strlen($line);
  1861. $this->addItemsHandled($size);
  1862. $num_read += $size;
  1863. $line = trim($line);
  1864. // if we encounter a definition line then get the name, uniquename,
  1865. // accession and relationship subject from the definition line
  1866. if (preg_match('/^>/', $line)) {
  1867. // if we are beginning a new sequence then save to the database the last one we just finished.
  1868. if ($id) {
  1869. $values = ['uniquename' => $id];
  1870. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  1871. if (count($result) == 0) {
  1872. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1873. ['%uname' => $id], TRIPAL_WARNING);
  1874. }
  1875. else {
  1876. // if we have a feature then add the residues
  1877. $feature = $result[0];
  1878. $values = [
  1879. 'residues' => $residues,
  1880. 'seqlen' => strlen($residues),
  1881. ];
  1882. $match = ['feature_id' => $feature->feature_id];
  1883. chado_update_record('feature', $match, $values);
  1884. }
  1885. }
  1886. // get the feature ID for this ID from the tripal_gff_temp table. It
  1887. // should be the name up to the first space
  1888. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  1889. $residues = '';
  1890. }
  1891. else {
  1892. $residues .= trim($line);
  1893. }
  1894. }
  1895. // add in the last sequence
  1896. $values = ['uniquename' => $id];
  1897. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  1898. if (count($result) == 0) {
  1899. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1900. ['%uname' => $id], TRIPAL_WARNING);
  1901. }
  1902. else {
  1903. // if we have a feature then add the residues
  1904. $feature = $result[0];
  1905. $values = [
  1906. 'residues' => $residues,
  1907. 'seqlen' => strlen($residues),
  1908. ];
  1909. $match = ['feature_id' => $feature->feature_id];
  1910. chado_update_record('feature', $match, $values);
  1911. }
  1912. }
  1913. /**
  1914. * Load the target attribute of a gff3 record
  1915. *
  1916. * @param $feature
  1917. * @param $tags
  1918. * @param $target_organism_id
  1919. * @param $target_type
  1920. * @param $create_target
  1921. * @param $attr_locgroup
  1922. *
  1923. * @ingroup gff3_loader
  1924. */
  1925. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  1926. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  1927. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  1928. // the organism and type of the target may also be specified as an attribute. If so, then get that
  1929. // information
  1930. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  1931. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  1932. // if we have matches and the Target is in the correct format then load the alignment
  1933. if ($matched) {
  1934. $target_feature = $matches[1];
  1935. $start = $matches[2];
  1936. $end = $matches[3];
  1937. // if we have an optional strand, convert it to a numeric value.
  1938. if (!empty($matches[4])) {
  1939. if (preg_match('/^\+$/', trim($matches[4]))) {
  1940. $target_strand = 1;
  1941. }
  1942. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  1943. $target_strand = -1;
  1944. }
  1945. else {
  1946. $target_strand = 0;
  1947. }
  1948. }
  1949. else {
  1950. $target_strand = 0;
  1951. }
  1952. $target_fmin = $start - 1;
  1953. $target_fmax = $end;
  1954. if ($end < $start) {
  1955. $target_fmin = $end - 1;
  1956. $target_fmax = $start;
  1957. }
  1958. // default the target organism to be the value passed into the function, but if the GFF
  1959. // file species the target organism then use that instead.
  1960. $t_organism_id = $target_organism_id;
  1961. if ($gff_target_organism) {
  1962. // get the genus and species
  1963. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  1964. if ($success) {
  1965. $values = [
  1966. 'genus' => $matches[1],
  1967. 'species' => $matches[2],
  1968. ];
  1969. $torganism = chado_select_record('organism', ['organism_id'], $values);
  1970. if (count($torganism) == 1) {
  1971. $t_organism_id = $torganism[0]->organism_id;
  1972. }
  1973. else {
  1974. $this->logMessage("Cannot find organism for target %target.",
  1975. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  1976. $t_organism_id = '';
  1977. }
  1978. }
  1979. else {
  1980. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  1981. "It should be target_organism=genus:species.",
  1982. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  1983. $t_organism_id = '';
  1984. }
  1985. }
  1986. // default the target type to be the value passed into the function, but if the GFF file
  1987. // species the target type then use that instead
  1988. $t_type_id = '';
  1989. if ($target_type) {
  1990. $values = [
  1991. 'name' => $target_type,
  1992. 'cv_id' => [
  1993. 'name' => 'sequence',
  1994. ],
  1995. ];
  1996. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  1997. if (count($type) == 1) {
  1998. $t_type_id = $type[0]->cvterm_id;
  1999. }
  2000. else {
  2001. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  2002. ['%type' => $target_type]));
  2003. }
  2004. }
  2005. if ($gff_target_type) {
  2006. $values = [
  2007. 'name' => $gff_target_type,
  2008. 'cv_id' => [
  2009. 'name' => 'sequence',
  2010. ],
  2011. ];
  2012. // get the cvterm_id for the target type
  2013. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2014. if (count($type) == 1) {
  2015. $t_type_id = $type[0]->cvterm_id;
  2016. }
  2017. else {
  2018. // check to see if this is a synonym
  2019. $sql = "
  2020. SELECT CVTS.cvterm_id
  2021. FROM {cvtermsynonym} CVTS
  2022. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  2023. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  2024. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  2025. ";
  2026. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  2027. if ($synonym) {
  2028. $t_type_id = $synonym->cvterm_id;
  2029. }
  2030. else {
  2031. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  2032. ['%type' => $gff_target_type], TRIPAL_WARNING);
  2033. $t_type_id = '';
  2034. }
  2035. }
  2036. }
  2037. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2038. // and the landmark as the feature.
  2039. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  2040. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  2041. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2042. }
  2043. // the target attribute is not correctly formatted
  2044. else {
  2045. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2046. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  2047. }
  2048. }
  2049. }