GFF3Importer.inc 88 KB

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