GFF3Importer.inc 83 KB

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