GFF3Importer.inc 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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 (.*?) (\d+) (\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. /*
  712. // If the option is to remove or refresh then we want to remove
  713. // the feature from the database.
  714. if ($remove or $refresh) {
  715. // Next remove the feature itself.
  716. $sql = "DELETE FROM {feature}
  717. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  718. $match = array(
  719. 'organism_id' => $feature_organism->organism_id,
  720. 'uniquename' => $attr_uniquename,
  721. 'type_id' => $cvterm->cvterm_id
  722. );
  723. $result = chado_delete_record('feature', $match);
  724. if (!$result) {
  725. $this->logMessage("Cannot delete feature %attr_uniquename",
  726. array('%attr_uniquename' => $attr_uniquename), TRIPAL_ERROR);
  727. }
  728. $feature = 0;
  729. unset($result);
  730. }
  731. */
  732. // Add or update the feature and all properties.
  733. if ($update or $refresh or $add_only) {
  734. // Add/update the feature.
  735. $feature = $this->loadFeature($feature_organism, $analysis_id, $cvterm,
  736. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  737. $attr_is_obsolete, $add_only, $score);
  738. if ($feature) {
  739. // Add a record for this feature to the tripal_gff_temp table for
  740. // later lookup.
  741. $values = [
  742. 'feature_id' => $feature->feature_id,
  743. 'organism_id' => $feature->organism_id,
  744. 'type_name' => $type,
  745. 'uniquename' => $feature->uniquename,
  746. ];
  747. // make sure this record doesn't already exist in our temp table
  748. $results = chado_select_record('tripal_gff_temp', ['*'], $values);
  749. if (count($results) == 0) {
  750. $result = chado_insert_record('tripal_gff_temp', $values);
  751. if (!$result) {
  752. throw new Exception(t("Cound not save record in temporary table, Cannot continue.", []));
  753. }
  754. }
  755. // Add/update the featureloc if the landmark and the ID are not the
  756. // same if they are the same then this entry in the GFF is probably
  757. // a landmark identifier.
  758. if (strcmp($landmark, $attr_uniquename) != 0) {
  759. $this->loadFeatureLoc($feature, $organism,
  760. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  761. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  762. }
  763. // Add any aliases for this feature.
  764. if (array_key_exists('Alias', $tags)) {
  765. $this->loadAlias($feature, $tags['Alias']);
  766. }
  767. // Add any dbxrefs for this feature.
  768. if (array_key_exists('Dbxref', $tags)) {
  769. $this->loadDbxref($feature, $tags['Dbxref']);
  770. }
  771. // Add any ontology terms for this feature.
  772. if (array_key_exists('Ontology_term', $tags)) {
  773. $this->loadOntology($feature, $tags['Ontology_term']);
  774. }
  775. // Add parent relationships.
  776. if (array_key_exists('Parent', $tags)) {
  777. $this->loadParents($feature, $cvterm, $tags['Parent'],
  778. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  779. }
  780. // Add target relationships.
  781. if (array_key_exists('Target', $tags)) {
  782. $this->loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  783. }
  784. // Add gap information. This goes in simply as a property.
  785. if (array_key_exists('Gap', $tags)) {
  786. foreach ($tags['Gap'] as $value) {
  787. $this->loadProperty($feature, 'Gap', $value);
  788. }
  789. }
  790. // Add notes. This goes in simply as a property.
  791. if (array_key_exists('Note', $tags)) {
  792. foreach ($tags['Note'] as $value) {
  793. $this->loadProperty($feature, 'Note', $value);
  794. }
  795. }
  796. // Add the Derives_from relationship (e.g. polycistronic genes).
  797. if (array_key_exists('Derives_from', $tags)) {
  798. $this->loadDerivesFrom($feature, $cvterm, $tags['Derives_from'][0],
  799. $feature_organism, $fmin, $fmax);
  800. }
  801. // Add in the GFF3_source dbxref so that GBrowse can find the feature
  802. // using the source column.
  803. $source_ref = ['GFF_source:' . $source];
  804. $this->loadDbxref($feature, $source_ref);
  805. // Add any additional attributes.
  806. if ($attr_others) {
  807. foreach ($attr_others as $tag_name => $values) {
  808. foreach ($values as $value) {
  809. $this->loadProperty($feature, $tag_name, $value);
  810. }
  811. }
  812. }
  813. }
  814. }
  815. }
  816. // Do some last bit of processing.
  817. if (!$remove) {
  818. // First, add any protein sequences if needed.
  819. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  820. $has_cds = chado_query($sql)->fetchField();
  821. if ($has_cds) {
  822. $this->logMessage("\nAdding protein sequences if CDS exist and no proteins in GFF...");
  823. $sql = "
  824. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  825. CVT.cvterm_id, CVT.name as feature_type,
  826. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  827. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  828. TGPT.fmax as protein_fmax, FLM.uniquename as landmark
  829. FROM {tripal_gffcds_temp} TGCT
  830. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  831. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  832. INNER JOIN {featureloc} L on F.feature_id = L.feature_id
  833. INNER JOIN {feature} FLM on L.srcfeature_id = FLM.feature_id
  834. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  835. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  836. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
  837. ";
  838. $results = chado_query($sql);
  839. $protein_cvterm = $this->getCvterm('polypeptide');
  840. while ($result = $results->fetchObject()) {
  841. // If a protein exists with this same parent then don't add a new
  842. // protein.
  843. if (!$result->protein_id) {
  844. // Get details about this protein
  845. if ($re_mrna and $re_protein) {
  846. // We use a regex to generate protein name from mRNA name
  847. $uname = preg_replace("/$re_mrna/", $re_protein, $result->uniquename);
  848. $name = $result->name;
  849. }
  850. else {
  851. // No regex, use the default '-protein' suffix
  852. $uname = $result->uniquename . '-protein';
  853. $name = $result->name;
  854. }
  855. $values = [
  856. 'parent_id' => $result->feature_id,
  857. 'fmin' => $result->fmin,
  858. ];
  859. $min_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  860. $values = [
  861. 'parent_id' => $result->feature_id,
  862. 'fmax' => $result->fmax,
  863. ];
  864. $max_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  865. $pfmin = $result->fmin;
  866. $pfmax = $result->fmax;
  867. if ($result->strand == '-1') {
  868. $pfmax -= $max_phase[0]->phase;
  869. }
  870. else {
  871. $pfmin += $min_phase[0]->phase;
  872. }
  873. if ($skip_protein == 0) {
  874. // Add the new protein record.
  875. $feature = $this->loadFeature($organism, $analysis_id,
  876. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  877. // Add the derives_from relationship.
  878. $cvterm = $this->getCvterm($result->feature_type);
  879. $this->loadDerivesFrom($feature, $cvterm,
  880. $result->uniquename, $organism, $pfmin, $pfmax);
  881. // Add the featureloc record. Set the start of the protein to
  882. // be the start of the coding sequence minus the phase.
  883. $this->loadFeatureLoc($feature, $organism, $result->landmark,
  884. $pfmin, $pfmax, $result->strand, '', 'f', 'f', '', 0);
  885. }
  886. }
  887. }
  888. }
  889. $this->logMessage("Setting ranks of children...");
  890. // Get features in a relationship that are also children of an alignment.
  891. $sql = "
  892. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  893. F.uniquename, FL.strand
  894. FROM {tripal_gff_temp} TGT
  895. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  896. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  897. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  898. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  899. WHERE CVT.name = 'part_of'
  900. ";
  901. $parents = chado_query($sql);
  902. // Build and prepare the SQL for selecting the children relationship.
  903. $sel_gffchildren_sql = "
  904. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  905. FROM {feature_relationship} FR
  906. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  907. INNER JOIN {cvterm} CVT on CVT.cvterm_id = FR.type_id
  908. WHERE FR.object_id = :feature_id AND CVT.name = 'part_of'
  909. ORDER BY FL.fmin ASC
  910. ";
  911. // Now set the rank of any parent/child relationships. The order is based
  912. // on the fmin. The start rank is 1. This allows features with other
  913. // relationships to be '0' (the default), and doesn't interfer with the
  914. // ordering defined here.
  915. $num_recs = $parents->rowCount();
  916. $i = 1;
  917. while ($parent = $parents->fetchObject()) {
  918. // get the children
  919. $result = chado_query($sel_gffchildren_sql, [':feature_id' => $parent->feature_id]);
  920. // build an array of the children
  921. $children = [];
  922. while ($child = $result->fetchObject()) {
  923. $children[] = $child;
  924. }
  925. // the children list comes sorted in ascending fmin
  926. // but if the parent is on the reverse strand we need to
  927. // reverse the order of the children.
  928. if ($parent->strand == -1) {
  929. arsort($children);
  930. }
  931. // first set the ranks to a negative number so that we don't
  932. // get a duplicate error message when we try to change any of them
  933. $rank = -1;
  934. foreach ($children as $child) {
  935. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  936. $values = ['rank' => $rank];
  937. chado_update_record('feature_relationship', $match, $values);
  938. $rank--;
  939. }
  940. // now set the rank correctly. The rank should start at 0.
  941. $rank = 0;
  942. foreach ($children as $child) {
  943. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  944. $values = ['rank' => $rank];
  945. chado_update_record('feature_relationship', $match, $values);
  946. $rank++;
  947. }
  948. $i++;
  949. }
  950. }
  951. return 1;
  952. }
  953. /**
  954. * Load a controlled vocabulary term.
  955. *
  956. * This method first checks if the term has already been loaded in the
  957. * cvterm_lookup array, which helps a lot with performance.
  958. *
  959. * @param $type
  960. * @param $cv_id
  961. *
  962. * @ingroup gff3_loader
  963. */
  964. private function getCvterm($type, $cv_id = NULL) {
  965. if (!isset($cv_id)) {
  966. $cv_id = $this->sequence_cv_id;
  967. }
  968. if (array_key_exists($type, $this->cvterm_lookup)) {
  969. return $this->cvterm_lookup[$type];
  970. }
  971. else {
  972. $sel_cvterm_sql = "
  973. SELECT CVT.cvterm_id
  974. FROM {cvterm} CVT
  975. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  976. WHERE CVT.cv_id = {$cv_id} and
  977. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  978. ";
  979. $result = chado_query($sel_cvterm_sql, [
  980. ':name' => $type,
  981. ':synonym' => $type,
  982. ]);
  983. $cvterm = $result->fetchObject() ?? NULL;
  984. if ($cvterm) {
  985. $cvterm = chado_get_cvterm(array('cvterm_id' => $cvterm->cvterm_id)) ?? NULL;
  986. }
  987. $this->cvterm_lookup[$type] = $cvterm;
  988. return $cvterm;
  989. }
  990. }
  991. /**
  992. * Load the derives from attribute for a gff3 feature
  993. *
  994. * @param $feature
  995. * @param $subject
  996. * @param $organism
  997. *
  998. * @ingroup gff3_loader
  999. */
  1000. private function loadDerivesFrom($feature, $cvterm, $object,
  1001. $organism, $fmin, $fmax) {
  1002. $type = $cvterm->name;
  1003. $derivesfrom_term = $this->getCvterm('derives_from');
  1004. // First look for the object feature in the temp table to get it's type.
  1005. $values = [
  1006. 'organism_id' => $organism->organism_id,
  1007. 'uniquename' => $object,
  1008. ];
  1009. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  1010. $type_id = NULL;
  1011. if (count($result) > 0) {
  1012. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  1013. }
  1014. // If the object wasn't in the temp table then look for it in the
  1015. // feature table and get it's type.
  1016. if (!$type_id) {
  1017. $result = chado_select_record('feature', ['type_id'], $values);
  1018. if (count($result) > 1) {
  1019. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  1020. ['!subject' => $object], TRIPAL_WARNING);
  1021. return;
  1022. }
  1023. else {
  1024. if (count($result) == 0) {
  1025. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  1026. ['!subject' => $object], TRIPAL_WARNING);
  1027. return '';
  1028. }
  1029. else {
  1030. $type_id = $result->type_id;
  1031. }
  1032. }
  1033. }
  1034. // Get the object feature.
  1035. $match = [
  1036. 'organism_id' => $organism->organism_id,
  1037. 'uniquename' => $object,
  1038. 'type_id' => $type_id,
  1039. ];
  1040. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  1041. if (count($ofeature) == 0) {
  1042. $this->logMessage("Could not add 'Derives_from' relationship " .
  1043. "for %uniquename and %subject. Subject feature, '%subject', " .
  1044. "cannot be found.", [
  1045. '%uniquename' => $feature->uniquename,
  1046. '%subject' => $subject,
  1047. ], TRIPAL_ERROR);
  1048. return;
  1049. }
  1050. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  1051. if ($type == 'protein' or $type == 'polypeptide') {
  1052. $values = [
  1053. 'feature_id' => $feature->feature_id,
  1054. 'parent_id' => $ofeature[0]->feature_id,
  1055. 'fmin' => $fmin,
  1056. 'fmax' => $fmax,
  1057. ];
  1058. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  1059. if (!$result) {
  1060. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  1061. }
  1062. }
  1063. // Now check to see if the relationship already exists. If it does
  1064. // then just return.
  1065. $values = [
  1066. 'object_id' => $ofeature[0]->feature_id,
  1067. 'subject_id' => $feature->feature_id,
  1068. 'type_id' => $derivesfrom_term->cvterm_id,
  1069. 'rank' => 0,
  1070. ];
  1071. $rel = chado_select_record('feature_relationship', ['*'], $values);
  1072. if (count($rel) > 0) {
  1073. return;
  1074. }
  1075. // finally insert the relationship if it doesn't exist
  1076. $ret = chado_insert_record('feature_relationship', $values, array(
  1077. 'skip_validation' => TRUE,
  1078. ));
  1079. if (!$ret) {
  1080. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  1081. [
  1082. ':uniquename' => $feature->uniquename,
  1083. ':subject' => $subject,
  1084. ], TRIPAL_WARNING);
  1085. }
  1086. }
  1087. /**
  1088. * Load the parents for a gff3 feature
  1089. *
  1090. * @param $feature
  1091. * @param $cvterm
  1092. * @param $parents
  1093. * @param $organism_id
  1094. * @param $fmin
  1095. *
  1096. * @ingroup gff3_loader
  1097. */
  1098. private function loadParents($feature, $cvterm, $parents,
  1099. $organism_id, $strand, $phase, $fmin, $fmax) {
  1100. $uname = $feature->uniquename;
  1101. $type = $cvterm->name;
  1102. $rel_type = 'part_of';
  1103. $relcvterm = $this->getCvterm($rel_type);
  1104. if (!$relcvterm) {
  1105. 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."));
  1106. }
  1107. // Iterate through the parents in the list.
  1108. foreach ($parents as $parent) {
  1109. // Get the parent cvterm.
  1110. $values = [
  1111. 'organism_id' => $organism_id,
  1112. 'uniquename' => $parent,
  1113. ];
  1114. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  1115. if (count($result) == 0) {
  1116. $this->logMessage("Cannot find parent: %parent.", ['%parent' => $parent], TRIPAL_WARNING);
  1117. return '';
  1118. }
  1119. $parent_type = $result[0]->type_name;
  1120. // try to find the parent
  1121. $parentcvterm = $this->getCvterm($parent_type);
  1122. $values = [
  1123. 'organism_id' => $organism_id,
  1124. 'uniquename' => $parent,
  1125. 'type_id' => $parentcvterm->cvterm_id,
  1126. ];
  1127. $result = chado_select_record('feature', ['feature_id'], $values);
  1128. $parent_feature = $result[0];
  1129. // if the parent exists then add the relationship otherwise print error and skip
  1130. if ($parent_feature) {
  1131. // check to see if the relationship already exists
  1132. $values = [
  1133. 'object_id' => $parent_feature->feature_id,
  1134. 'subject_id' => $feature->feature_id,
  1135. 'type_id' => $relcvterm->cvterm_id,
  1136. ];
  1137. $rel = chado_select_record('feature_relationship', ['*'], $values);
  1138. if (count($rel) > 0) {
  1139. }
  1140. else {
  1141. // the relationship doesn't already exist, so add it.
  1142. $values = [
  1143. 'subject_id' => $feature->feature_id,
  1144. 'object_id' => $parent_feature->feature_id,
  1145. 'type_id' => $relcvterm->cvterm_id,
  1146. ];
  1147. $result = chado_insert_record('feature_relationship', $values, array(
  1148. 'skip_validation' => TRUE,
  1149. ));
  1150. if (!$result) {
  1151. $this->logMessage("Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type).",
  1152. [], TRIPAL_WARNING);
  1153. }
  1154. }
  1155. // If this feature is a CDS and now that we know the parent we can
  1156. // add it to the tripal_gffcds_temp table for later lookup.
  1157. if ($type == 'CDS') {
  1158. $values = [
  1159. 'feature_id' => $feature->feature_id,
  1160. 'parent_id' => $parent_feature->feature_id,
  1161. 'fmin' => $fmin,
  1162. 'fmax' => $fmax,
  1163. 'strand' => $strand,
  1164. ];
  1165. if (isset($phase)) {
  1166. $values['phase'] = $phase;
  1167. }
  1168. $result = chado_insert_record('tripal_gffcds_temp', $values, array(
  1169. 'skip_validation' => TRUE,
  1170. ));
  1171. if (!$result) {
  1172. throw new Exception(t("Cound not save record in temporary CDS table, Cannot continue.", []));
  1173. exit;
  1174. }
  1175. }
  1176. }
  1177. else {
  1178. $this->logMessage("Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent.",
  1179. [], TRIPAL_WARNING);
  1180. }
  1181. }
  1182. }
  1183. /**
  1184. * Load the dbxref attribute for a feature
  1185. *
  1186. * @param $feature
  1187. * @param $dbxrefs
  1188. *
  1189. * @ingroup gff3_loader
  1190. */
  1191. private function loadDbxref($feature, $dbxrefs) {
  1192. // iterate through each of the dbxrefs
  1193. foreach ($dbxrefs as $dbxref) {
  1194. // get the database name from the reference. If it doesn't exist then create one.
  1195. $ref = explode(":", $dbxref);
  1196. $dbname = trim($ref[0]);
  1197. $accession = trim($ref[1]);
  1198. // first look for the database name if it doesn't exist then create one.
  1199. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  1200. // can't be found then look for the name as is. If it still can't be found
  1201. // the create the database
  1202. $values = ['name' => "DB:$dbname"];
  1203. $db = chado_select_record('db', ['db_id'], $values);
  1204. if (count($db) == 0) {
  1205. $values = ['name' => "$dbname"];
  1206. $db = chado_select_record('db', ['db_id'], $values);
  1207. }
  1208. if (count($db) == 0) {
  1209. $values = [
  1210. 'name' => $dbname,
  1211. 'description' => 'Added automatically by the GFF loader',
  1212. ];
  1213. $success = chado_insert_record('db', $values, array(
  1214. 'skip_validation' => TRUE,
  1215. ));
  1216. if ($success) {
  1217. $values = ['name' => "$dbname"];
  1218. $db = chado_select_record('db', ['db_id'], $values);
  1219. }
  1220. else {
  1221. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  1222. return 0;
  1223. }
  1224. }
  1225. $db = $db[0];
  1226. // now check to see if the accession exists
  1227. $values = [
  1228. 'accession' => $accession,
  1229. 'db_id' => $db->db_id,
  1230. ];
  1231. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  1232. // if the accession doesn't exist then we want to add it
  1233. if (sizeof($dbxref) == 0) {
  1234. $values = [
  1235. 'db_id' => $db->db_id,
  1236. 'accession' => $accession,
  1237. 'version' => '',
  1238. ];
  1239. $ret = chado_insert_record('dbxref', $values, array(
  1240. 'skip_validation' => TRUE,
  1241. ));
  1242. $values = [
  1243. 'accession' => $accession,
  1244. 'db_id' => $db->db_id,
  1245. ];
  1246. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  1247. }
  1248. $dbxref = $dbxref[0];
  1249. // check to see if this feature dbxref already exists
  1250. $values = [
  1251. 'dbxref_id' => $dbxref->dbxref_id,
  1252. 'feature_id' => $feature->feature_id,
  1253. ];
  1254. $fdbx = chado_select_record('feature_dbxref', ['feature_dbxref_id'], $values);
  1255. // now associate this feature with the database reference if it doesn't
  1256. // already exist
  1257. if (sizeof($fdbx) == 0) {
  1258. $values = [
  1259. 'dbxref_id' => $dbxref->dbxref_id,
  1260. 'feature_id' => $feature->feature_id,
  1261. ];
  1262. $success = chado_insert_record('feature_dbxref', $values, array(
  1263. 'skip_validation' => TRUE,
  1264. ));
  1265. if (!$success) {
  1266. $this->logMessage("Failed to insert Dbxref: $dbname:$accession.", [], TRIPAL_WARNING);
  1267. return 0;
  1268. }
  1269. }
  1270. }
  1271. return 1;
  1272. }
  1273. /**
  1274. * Load the cvterms for a feature.
  1275. *
  1276. * Assumes there is a dbxref.accession matching a cvterm.name
  1277. *
  1278. * @param $feature
  1279. * @param $dbxrefs
  1280. *
  1281. * @ingroup gff3_loader
  1282. */
  1283. private function loadOntology($feature, $dbxrefs) {
  1284. // iterate through each of the dbxrefs
  1285. foreach ($dbxrefs as $dbxref) {
  1286. // get the database name from the reference. If it doesn't exist then create one.
  1287. $ref = explode(":", $dbxref);
  1288. $dbname = trim($ref[0]);
  1289. $accession = trim($ref[1]);
  1290. // first look for the database name
  1291. $db = chado_select_record('db', ['db_id'], ['name' => "DB:$dbname"]);
  1292. if (sizeof($db) == 0) {
  1293. // now look for the name without the 'DB:' prefix.
  1294. $db = chado_select_record('db', ['db_id'], ['name' => "$dbname"]);
  1295. if (sizeof($db) == 0) {
  1296. $this->logMessage("Database, $dbname, is not present. Cannot associate term: $dbname:$accession.", [], TRIPAL_WARNING);
  1297. continue;
  1298. }
  1299. }
  1300. $db = $db[0];
  1301. // now check to see if the accession exists
  1302. $dbxref = chado_select_record('dbxref', ['dbxref_id'],
  1303. ['accession' => $accession, 'db_id' => $db->db_id]);
  1304. if (sizeof($dbxref) == 0) {
  1305. $this->logMessage("Accession, $accession is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  1306. continue;
  1307. }
  1308. $dbxref = $dbxref[0];
  1309. // now check to see if the cvterm exists
  1310. $cvterm = chado_select_record('cvterm', ['cvterm_id'], [
  1311. 'dbxref_id' => $dbxref->dbxref_id,
  1312. ]);
  1313. // if it doesn't exist in the cvterm table, look for an alternate id
  1314. if (sizeof($cvterm) == 0) {
  1315. $cvterm = chado_select_record('cvterm_dbxref', ['cvterm_id'], [
  1316. 'dbxref_id' => $dbxref->dbxref_id,
  1317. ]);
  1318. if (sizeof($cvterm) == 0) {
  1319. $this->logMessage("CV Term is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  1320. continue;
  1321. }
  1322. }
  1323. $cvterm = $cvterm[0];
  1324. // check to see if this feature cvterm already exists
  1325. $fcvt = chado_select_record('feature_cvterm', ['feature_cvterm_id'],
  1326. [
  1327. 'cvterm_id' => $cvterm->cvterm_id,
  1328. 'feature_id' => $feature->feature_id,
  1329. ]);
  1330. // now associate this feature with the cvterm if it doesn't already exist
  1331. if (sizeof($fcvt) == 0) {
  1332. $values = [
  1333. 'cvterm_id' => $cvterm->cvterm_id,
  1334. 'feature_id' => $feature->feature_id,
  1335. 'pub_id' => [
  1336. 'uniquename' => 'null',
  1337. ],
  1338. ];
  1339. $success = chado_insert_record('feature_cvterm', $values, array(
  1340. 'skip_validation' => TRUE,
  1341. ));
  1342. if (!$success) {
  1343. $this->logMessage("Failed to insert ontology term: $dbname:$accession.", [], TRIPAL_WARNING);
  1344. continue;
  1345. }
  1346. }
  1347. }
  1348. }
  1349. /**
  1350. * Load any aliases for a feature
  1351. *
  1352. * @param $feature
  1353. * @param $aliases
  1354. *
  1355. * @ingroup gff3_loader
  1356. */
  1357. private function loadAlias($feature, $aliases) {
  1358. // make sure we have a 'synonym_type' vocabulary
  1359. $select = ['name' => 'synonym_type'];
  1360. $results = chado_select_record('cv', ['*'], $select);
  1361. if (count($results) == 0) {
  1362. // insert the 'synonym_type' vocabulary
  1363. $values = [
  1364. 'name' => 'synonym_type',
  1365. 'definition' => 'vocabulary for synonym types',
  1366. ];
  1367. $success = chado_insert_record('cv', $values, array(
  1368. 'skip_validation' => TRUE,
  1369. ));
  1370. if (!$success) {
  1371. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  1372. return 0;
  1373. }
  1374. // now that we've added the cv we need to get the record
  1375. $results = chado_select_record('cv', ['*'], $select);
  1376. if (count($results) > 0) {
  1377. $syncv = $results[0];
  1378. }
  1379. }
  1380. else {
  1381. $syncv = $results[0];
  1382. }
  1383. // get the 'exact' cvterm, which is the type of synonym we're adding
  1384. $select = [
  1385. 'name' => 'exact',
  1386. 'cv_id' => [
  1387. 'name' => 'synonym_type',
  1388. ],
  1389. ];
  1390. $result = chado_select_record('cvterm', ['*'], $select);
  1391. if (count($result) == 0) {
  1392. $term = [
  1393. 'name' => 'exact',
  1394. 'id' => "synonym_type:exact",
  1395. 'definition' => '',
  1396. 'is_obsolete' => 0,
  1397. 'cv_name' => $syncv->name,
  1398. 'is_relationship' => FALSE,
  1399. ];
  1400. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  1401. if (!$syntype) {
  1402. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  1403. return 0;
  1404. }
  1405. }
  1406. else {
  1407. $syntype = $result[0];
  1408. }
  1409. // iterate through all of the aliases and add each one
  1410. foreach ($aliases as $alias) {
  1411. // check to see if the alias already exists in the synonym table
  1412. // if not, then add it
  1413. $select = [
  1414. 'name' => $alias,
  1415. 'type_id' => $syntype->cvterm_id,
  1416. ];
  1417. $result = chado_select_record('synonym', ['*'], $select);
  1418. if (count($result) == 0) {
  1419. $values = [
  1420. 'name' => $alias,
  1421. 'type_id' => $syntype->cvterm_id,
  1422. 'synonym_sgml' => '',
  1423. ];
  1424. $success = chado_insert_record('synonym', $values, array(
  1425. 'skip_validation' => TRUE,
  1426. ));
  1427. if (!$success) {
  1428. $this->logMessage("Cannot add alias $alias to synonym table.", [], TRIPAL_WARNING);
  1429. return 0;
  1430. }
  1431. $result = chado_select_record('synonym', ['*'], $select);
  1432. $synonym = $result[0];
  1433. }
  1434. else {
  1435. $synonym = $result[0];
  1436. }
  1437. // check to see if we have a NULL publication in the pub table. If not,
  1438. // then add one.
  1439. $select = ['uniquename' => 'null'];
  1440. $result = chado_select_record('pub', ['*'], $select);
  1441. if (count($result) == 0) {
  1442. $pub_sql = "
  1443. INSERT INTO {pub} (uniquename,type_id)
  1444. VALUES (:uname,
  1445. (SELECT cvterm_id
  1446. FROM {cvterm} CVT
  1447. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  1448. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  1449. WHERE CVT.name = :type_id))
  1450. ";
  1451. $status = chado_query($psql);
  1452. if (!$status) {
  1453. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  1454. return 0;
  1455. }
  1456. // insert the null pub
  1457. $result = chado_query($pub_sql, [
  1458. ':uname' => 'null',
  1459. ':type_id' => 'null',
  1460. ])->fetchObject();
  1461. if (!$result) {
  1462. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  1463. return 0;
  1464. }
  1465. $result = chado_select_record('pub', ['*'], $select);
  1466. $pub = $result[0];
  1467. }
  1468. else {
  1469. $pub = $result[0];
  1470. }
  1471. // check to see if the synonym exists in the feature_synonym table
  1472. // if not, then add it.
  1473. $values = [
  1474. 'synonym_id' => $synonym->synonym_id,
  1475. 'feature_id' => $feature->feature_id,
  1476. 'pub_id' => $pub->pub_id,
  1477. ];
  1478. $columns = ['feature_synonym_id'];
  1479. $result = chado_select_record('feature_synonym', $columns, $values);
  1480. if (count($result) == 0) {
  1481. $values = [
  1482. 'synonym_id' => $synonym->synonym_id,
  1483. 'feature_id' => $feature->feature_id,
  1484. 'pub_id' => $pub->pub_id,
  1485. ];
  1486. $success = chado_insert_record('feature_synonym', $values, array(
  1487. 'skip_validation' => TRUE,
  1488. ));
  1489. if (!$success) {
  1490. $this->logMessage("Cannot add alias $alias to feature synonym table.", [], TRIPAL_WARNING);
  1491. return 0;
  1492. }
  1493. }
  1494. }
  1495. return 1;
  1496. }
  1497. /**
  1498. * Create the feature record & link it to it's analysis
  1499. *
  1500. * @param $organism
  1501. * @param $analysis_id
  1502. * @param $cvterm
  1503. * @param $uniquename
  1504. * @param $name
  1505. * @param $residues
  1506. * @param $is_analysis
  1507. * @param $is_obsolete
  1508. * @param $add_only
  1509. * @param $score
  1510. *
  1511. * @ingroup gff3_loader
  1512. */
  1513. private function loadFeature($organism, $analysis_id, $cvterm, $uniquename,
  1514. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1515. // Check to see if the feature already exists.
  1516. $feature = NULL;
  1517. $fselect = [
  1518. 'organism_id' => $organism->organism_id,
  1519. 'uniquename' => $uniquename,
  1520. 'type_id' => $cvterm->cvterm_id,
  1521. ];
  1522. $columns = [
  1523. 'feature_id',
  1524. 'name',
  1525. 'uniquename',
  1526. 'seqlen',
  1527. 'organism_id',
  1528. 'type_id',
  1529. ];
  1530. $result = chado_select_record('feature', $columns, $fselect);
  1531. if (count($result) > 0) {
  1532. $feature = $result[0];
  1533. }
  1534. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  1535. $is_obsolete = 'FALSE';
  1536. }
  1537. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  1538. $is_obsolete = 'TRUE';
  1539. }
  1540. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  1541. $is_analysis = 'FALSE';
  1542. }
  1543. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  1544. $is_analysis = 'TRUE';
  1545. }
  1546. // Insert the feature if it does not exist otherwise perform an update.
  1547. if (!$feature) {
  1548. $values = [
  1549. 'organism_id' => $organism->organism_id,
  1550. 'name' => $name,
  1551. 'uniquename' => $uniquename,
  1552. 'md5checksum' => md5($residues),
  1553. 'type_id' => $cvterm->cvterm_id,
  1554. 'is_analysis' => $is_analysis,
  1555. 'is_obsolete' => $is_obsolete,
  1556. ];
  1557. $feature = (object) chado_insert_record('feature', $values, array(
  1558. 'skip_validation' => TRUE,
  1559. ));
  1560. if (!$feature) {
  1561. $this->logMessage("Failed to insert feature '$uniquename' ($cvterm->name).", [], TRIPAL_WARNING);
  1562. return 0;
  1563. }
  1564. }
  1565. elseif (!$add_only) {
  1566. $values = [
  1567. 'name' => $name,
  1568. 'md5checksum' => md5($residues),
  1569. 'is_analysis' => $is_analysis,
  1570. 'is_obsolete' => $is_obsolete,
  1571. ];
  1572. $match = [
  1573. 'organism_id' => $organism->organism_id,
  1574. 'uniquename' => $uniquename,
  1575. 'type_id' => $cvterm->cvterm_id,
  1576. ];
  1577. $result = chado_update_record('feature', $match, $values);
  1578. if (!$result) {
  1579. $this->logMessage("Failed to update feature '$uniquename' ($cvterm->name).", [], TRIPAL_WARNING);
  1580. return 0;
  1581. }
  1582. }
  1583. else {
  1584. // The feature exists and we don't want to update it so return
  1585. // a value of 0. This will stop all downstream property additions
  1586. return $feature;
  1587. }
  1588. // Add the analysisfeature entry to the analysisfeature table if
  1589. // it doesn't already exist.
  1590. $af_values = [
  1591. 'analysis_id' => $analysis_id,
  1592. 'feature_id' => $feature->feature_id,
  1593. ];
  1594. $afeature = chado_select_record('analysisfeature', ['analysisfeature_id'], $af_values);
  1595. if (count($afeature) == 0) {
  1596. // if a score is available then set that to be the significance field
  1597. if (strcmp($score, '.') != 0) {
  1598. $af_values['significance'] = $score;
  1599. }
  1600. if (!chado_insert_record('analysisfeature', $af_values, array('skip_validation' => TRUE))) {
  1601. $this->logMessage("Could not add analysisfeature record: $analysis_id, $feature->feature_id.", [], TRIPAL_WARNING);
  1602. }
  1603. }
  1604. else {
  1605. // if a score is available then set that to be the significance field
  1606. $new_vals = [];
  1607. if (strcmp($score, '.') != 0) {
  1608. $new_vals['significance'] = $score;
  1609. }
  1610. else {
  1611. $new_vals['significance'] = '__NULL__';
  1612. }
  1613. if (!$add_only) {
  1614. $ret = chado_update_record('analysisfeature', $af_values, $new_vals);
  1615. if (!$ret) {
  1616. $this->logMessage("Could not update analysisfeature record: $analysis_id, $feature->feature_id.", [], TRIPAL_WARNING);
  1617. }
  1618. }
  1619. }
  1620. return $feature;
  1621. }
  1622. /**
  1623. * Insert the location of the feature
  1624. *
  1625. * @param $feature
  1626. * @param $organism
  1627. * @param $landmark
  1628. * @param $fmin
  1629. * @param $fmax
  1630. * @param $strand
  1631. * @param $phase
  1632. * @param $is_fmin_partial
  1633. * @param $is_fmax_partial
  1634. * @param $residue_info
  1635. * @param $locgroup
  1636. * @param $landmark_type_id
  1637. * @param $landmark_organism_id
  1638. * @param $create_landmark
  1639. * @param $landmark_is_target
  1640. *
  1641. * @ingroup gff3_loader
  1642. */
  1643. private function loadFeatureLoc($feature, $organism, $landmark, $fmin,
  1644. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  1645. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  1646. $landmark_is_target = 0) {
  1647. $select = [
  1648. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1649. 'uniquename' => $landmark,
  1650. ];
  1651. if ($landmark_type_id) {
  1652. $select['type_id'] = $landmark_type_id;
  1653. }
  1654. $results = chado_select_record('feature', ['feature_id'], $select);
  1655. $srcfeature = '';
  1656. if (count($results) == 0) {
  1657. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  1658. // if we return only a single result then we can proceed. Otherwise give an
  1659. $select = [
  1660. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1661. 'name' => $landmark,
  1662. ];
  1663. if ($landmark_type_id) {
  1664. $select['type_id'] = $landmark_type_id;
  1665. }
  1666. $results = chado_select_record('feature', ['feature_id'], $select);
  1667. if (count($results) == 0) {
  1668. // if the landmark is the target feature in a matched alignment then try one more time to
  1669. // find it by querying any feature with the same uniquename. If we find one then use it.
  1670. if ($landmark_is_target) {
  1671. $select = ['uniquename' => $landmark];
  1672. $results = chado_select_record('feature', ['feature_id'], $select);
  1673. if (count($results) == 1) {
  1674. $srcfeature = $results[0];
  1675. }
  1676. }
  1677. if (!$srcfeature) {
  1678. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  1679. // but only if we have a type id
  1680. if ($create_landmark and $landmark_type_id) {
  1681. $values = [
  1682. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1683. 'name' => $landmark,
  1684. 'uniquename' => $landmark,
  1685. 'type_id' => $landmark_type_id,
  1686. ];
  1687. $results = chado_insert_record('feature', $values, array(
  1688. 'skip_validation' => TRUE,
  1689. ));
  1690. if (!$results) {
  1691. $this->logMessage("Cannot find landmark feature: '%landmark', nor could it be inserted.",
  1692. ['%landmark' => $landmark], TRIPAL_WARNING);
  1693. return 0;
  1694. }
  1695. $srcfeature = new stdClass();
  1696. $srcfeature->feature_id = $results['feature_id'];
  1697. }
  1698. else {
  1699. $this->logMessage("Cannot find unique landmark feature: '%landmark'.",
  1700. ['%landmark' => $landmark], TRIPAL_WARNING);
  1701. return 0;
  1702. }
  1703. }
  1704. }
  1705. elseif (count($results) > 1) {
  1706. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1707. "resolve which one to use. Cannot add the feature location record.",
  1708. ['%landmark' => $landmark], TRIPAL_WARNING);
  1709. return 0;
  1710. }
  1711. else {
  1712. $srcfeature = $results[0];
  1713. }
  1714. }
  1715. elseif (count($results) > 1) {
  1716. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1717. "resolve which one to use. Cannot add the feature location record.",
  1718. ['%landmark' => $landmark, TRIPAL_WARNING]);
  1719. return 0;
  1720. }
  1721. else {
  1722. $srcfeature = $results[0];
  1723. }
  1724. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1725. // is_fmin_partial and is_fmax_partial, right now these are
  1726. // hardcoded to be false and 0 below.
  1727. // check to see if this featureloc already exists, but also keep track of the
  1728. // last rank value
  1729. $rank = 0;
  1730. $exists = 0;
  1731. $select = ['feature_id' => $feature->feature_id];
  1732. $options = [
  1733. 'order_by' => [
  1734. 'rank' => 'ASC',
  1735. ],
  1736. ];
  1737. $locrecs = chado_select_record('featureloc', ['*'], $select, $options);
  1738. foreach ($locrecs as $featureloc) {
  1739. // it is possible for the featureloc->srcfeature_id to be NULL. This can happen if the srcfeature
  1740. // is not known (according to chado table field descriptions). If it's null then just skip this entry
  1741. if (!$featureloc->srcfeature_id) {
  1742. continue;
  1743. }
  1744. $select = ['feature_id' => $featureloc->srcfeature_id];
  1745. $columns = ['feature_id', 'name'];
  1746. $locsfeature = chado_select_record('feature', $columns, $select);
  1747. // the source feature name and at least the fmin and fmax must be the same
  1748. // for an update of the featureloc, otherwise we'll insert a new record.
  1749. if (strcmp($locsfeature[0]->name, $landmark) == 0 and
  1750. ($featureloc->fmin == $fmin or $featureloc->fmax == $fmax)) {
  1751. $match = ['featureloc_id' => $featureloc->featureloc_id];
  1752. $values = [];
  1753. $exists = 1;
  1754. if ($featureloc->fmin != $fmin) {
  1755. $values['fmin'] = $fmin;
  1756. }
  1757. if ($featureloc->fmax != $fmax) {
  1758. $values['fmax'] = $fmax;
  1759. }
  1760. if ($featureloc->strand != $strand) {
  1761. $values['strand'] = $strand;
  1762. }
  1763. if (count($values) > 0) {
  1764. chado_update_record('featureloc', $match, $values);
  1765. }
  1766. }
  1767. $rank = $featureloc->rank + 1;
  1768. }
  1769. if (!$exists) {
  1770. // this feature location is new so add it
  1771. if (strcmp($is_fmin_partial, 'f') == 0 or !$is_fmin_partial) {
  1772. $is_fmin_partial = 'FALSE';
  1773. }
  1774. elseif (strcmp($is_fmin_partial, 't') == 0 or $is_fmin_partial == 1) {
  1775. $is_fmin_partial = 'TRUE';
  1776. }
  1777. if (strcmp($is_fmax_partial, 'f') == 0 or !$is_fmax_partial) {
  1778. $is_fmax_partial = 'FALSE';
  1779. }
  1780. elseif (strcmp($is_fmax_partial, 't') == 0 or $is_fmax_partial == 1) {
  1781. $is_fmax_partial = 'TRUE';
  1782. }
  1783. $values = [
  1784. 'feature_id' => $feature->feature_id,
  1785. 'srcfeature_id' => $srcfeature->feature_id,
  1786. 'fmin' => $fmin,
  1787. 'is_fmin_partial' => $is_fmin_partial,
  1788. 'fmax' => $fmax,
  1789. 'is_fmax_partial' => $is_fmax_partial,
  1790. 'strand' => $strand,
  1791. 'residue_info' => $residue_info,
  1792. 'locgroup' => $locgroup,
  1793. 'rank' => $rank,
  1794. ];
  1795. if ($phase) {
  1796. $values['phase'] = $phase;
  1797. }
  1798. $success = chado_insert_record('featureloc', $values, array(
  1799. 'skip_validation' => TRUE,
  1800. ));
  1801. if (!$success) {
  1802. throw new Exception("Failed to insert featureloc.");
  1803. }
  1804. }
  1805. return 1;
  1806. }
  1807. /**
  1808. * Load a preoprty (featurepop) for the feature
  1809. *
  1810. * @param $feature
  1811. * @param $property
  1812. * @param $value
  1813. *
  1814. * @ingroup gff3_loader
  1815. */
  1816. private function loadProperty($feature, $property, $value) {
  1817. // First make sure the cvterm exists. if not, then add it.
  1818. $result = $this->getCvterm($property, $this->feature_property_cv_id);
  1819. // If we don't have a property like this already, then add it otherwise,
  1820. // just return.
  1821. if (empty($result)) {
  1822. $term = [
  1823. 'id' => "local:$property",
  1824. 'name' => $property,
  1825. 'is_obsolete' => 0,
  1826. 'cv_name' => 'feature_property',
  1827. 'db_name' => 'local',
  1828. 'is_relationship' => FALSE,
  1829. ];
  1830. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  1831. if (!$cvterm) {
  1832. $this->logMessage("Cannot add cvterm, $property.", [], TRIPAL_WARNING);
  1833. return 0;
  1834. }
  1835. }
  1836. else {
  1837. $cvterm = $result;
  1838. }
  1839. // Check to see if the property already exists for this feature
  1840. // if it does but the value is unique then increment the rank and add it.
  1841. // if the value is not unique then don't add it.
  1842. $add = 1;
  1843. $rank = 0;
  1844. $select = [
  1845. 'feature_id' => $feature->feature_id,
  1846. 'type_id' => $cvterm->cvterm_id,
  1847. ];
  1848. $options = [
  1849. 'order_by' => [
  1850. 'rank' => 'ASC',
  1851. ],
  1852. ];
  1853. $results = chado_select_record('featureprop', ['*'], $select, $options);
  1854. foreach ($results as $prop) {
  1855. if (strcmp($prop->value, $value) == 0) {
  1856. $add = NULL; // don't add it, it already exists
  1857. }
  1858. $rank = $prop->rank + 1;
  1859. }
  1860. // add the property if we pass the check above
  1861. if ($add) {
  1862. $values = [
  1863. 'feature_id' => $feature->feature_id,
  1864. 'type_id' => $cvterm->cvterm_id,
  1865. 'value' => $value,
  1866. 'rank' => $rank,
  1867. ];
  1868. $result = chado_insert_record('featureprop', $values);
  1869. if (!$result) {
  1870. $this->logMessage("cannot add featureprop, $property.", [], TRIPAL_WARNING);
  1871. }
  1872. }
  1873. }
  1874. /**
  1875. * Load the FASTA sequences at the bottom of a GFF3 file
  1876. *
  1877. * @param $fh
  1878. * @param $interval
  1879. * @param $num_read
  1880. * @param $line_num
  1881. * @param $filesize
  1882. *
  1883. * @ingroup gff3_loader
  1884. */
  1885. private function loadFasta($fh, $interval, &$num_read, &$line_num, $filesize) {
  1886. $this->logMessage("Loading FASTA sequences...");
  1887. $residues = '';
  1888. $id = NULL;
  1889. // iterate through the remaining lines of the file
  1890. while ($line = fgets($fh)) {
  1891. $line_num++;
  1892. $size = drupal_strlen($line);
  1893. $this->addItemsHandled($size);
  1894. $num_read += $size;
  1895. $line = trim($line);
  1896. // if we encounter a definition line then get the name, uniquename,
  1897. // accession and relationship subject from the definition line
  1898. if (preg_match('/^>/', $line)) {
  1899. // if we are beginning a new sequence then save to the database the last one we just finished.
  1900. if ($id) {
  1901. $values = ['uniquename' => $id];
  1902. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  1903. if (count($result) == 0) {
  1904. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1905. ['%uname' => $id], TRIPAL_WARNING);
  1906. }
  1907. else {
  1908. // if we have a feature then add the residues
  1909. $feature = $result[0];
  1910. $values = [
  1911. 'residues' => $residues,
  1912. 'seqlen' => strlen($residues),
  1913. ];
  1914. $match = ['feature_id' => $feature->feature_id];
  1915. chado_update_record('feature', $match, $values);
  1916. }
  1917. }
  1918. // get the feature ID for this ID from the tripal_gff_temp table. It
  1919. // should be the name up to the first space
  1920. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  1921. $residues = '';
  1922. }
  1923. else {
  1924. $residues .= trim($line);
  1925. }
  1926. }
  1927. // add in the last sequence
  1928. $values = ['uniquename' => $id];
  1929. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  1930. if (count($result) == 0) {
  1931. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1932. ['%uname' => $id], TRIPAL_WARNING);
  1933. }
  1934. else {
  1935. // if we have a feature then add the residues
  1936. $feature = $result[0];
  1937. $values = [
  1938. 'residues' => $residues,
  1939. 'seqlen' => strlen($residues),
  1940. ];
  1941. $match = ['feature_id' => $feature->feature_id];
  1942. chado_update_record('feature', $match, $values);
  1943. }
  1944. }
  1945. /**
  1946. * Load the target attribute of a gff3 record
  1947. *
  1948. * @param $feature
  1949. * @param $tags
  1950. * @param $target_organism_id
  1951. * @param $target_type
  1952. * @param $create_target
  1953. * @param $attr_locgroup
  1954. *
  1955. * @ingroup gff3_loader
  1956. */
  1957. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  1958. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  1959. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  1960. // the organism and type of the target may also be specified as an attribute. If so, then get that
  1961. // information
  1962. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  1963. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  1964. // if we have matches and the Target is in the correct format then load the alignment
  1965. if ($matched) {
  1966. $target_feature = $matches[1];
  1967. $start = $matches[2];
  1968. $end = $matches[3];
  1969. // if we have an optional strand, convert it to a numeric value.
  1970. if (!empty($matches[4])) {
  1971. if (preg_match('/^\+$/', trim($matches[4]))) {
  1972. $target_strand = 1;
  1973. }
  1974. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  1975. $target_strand = -1;
  1976. }
  1977. else {
  1978. $target_strand = 0;
  1979. }
  1980. }
  1981. else {
  1982. $target_strand = 0;
  1983. }
  1984. $target_fmin = $start - 1;
  1985. $target_fmax = $end;
  1986. if ($end < $start) {
  1987. $target_fmin = $end - 1;
  1988. $target_fmax = $start;
  1989. }
  1990. // default the target organism to be the value passed into the function, but if the GFF
  1991. // file species the target organism then use that instead.
  1992. $t_organism_id = $target_organism_id;
  1993. if ($gff_target_organism) {
  1994. // get the genus and species
  1995. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  1996. if ($success) {
  1997. $values = [
  1998. 'genus' => $matches[1],
  1999. 'species' => $matches[2],
  2000. ];
  2001. $torganism = chado_select_record('organism', ['organism_id'], $values);
  2002. if (count($torganism) == 1) {
  2003. $t_organism_id = $torganism[0]->organism_id;
  2004. }
  2005. else {
  2006. $this->logMessage("Cannot find organism for target %target.",
  2007. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2008. $t_organism_id = '';
  2009. }
  2010. }
  2011. else {
  2012. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  2013. "It should be target_organism=genus:species.",
  2014. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2015. $t_organism_id = '';
  2016. }
  2017. }
  2018. // default the target type to be the value passed into the function, but if the GFF file
  2019. // species the target type then use that instead
  2020. $t_type_id = '';
  2021. if ($target_type) {
  2022. $values = [
  2023. 'name' => $target_type,
  2024. 'cv_id' => [
  2025. 'name' => 'sequence',
  2026. ],
  2027. ];
  2028. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2029. if (count($type) == 1) {
  2030. $t_type_id = $type[0]->cvterm_id;
  2031. }
  2032. else {
  2033. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  2034. ['%type' => $target_type]));
  2035. }
  2036. }
  2037. if ($gff_target_type) {
  2038. $values = [
  2039. 'name' => $gff_target_type,
  2040. 'cv_id' => [
  2041. 'name' => 'sequence',
  2042. ],
  2043. ];
  2044. // get the cvterm_id for the target type
  2045. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2046. if (count($type) == 1) {
  2047. $t_type_id = $type[0]->cvterm_id;
  2048. }
  2049. else {
  2050. // check to see if this is a synonym
  2051. $sql = "
  2052. SELECT CVTS.cvterm_id
  2053. FROM {cvtermsynonym} CVTS
  2054. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  2055. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  2056. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  2057. ";
  2058. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  2059. if ($synonym) {
  2060. $t_type_id = $synonym->cvterm_id;
  2061. }
  2062. else {
  2063. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  2064. ['%type' => $gff_target_type], TRIPAL_WARNING);
  2065. $t_type_id = '';
  2066. }
  2067. }
  2068. }
  2069. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2070. // and the landmark as the feature.
  2071. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  2072. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  2073. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2074. }
  2075. // the target attribute is not correctly formatted
  2076. else {
  2077. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2078. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  2079. }
  2080. }
  2081. }