GFF3Importer.inc 82 KB

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