tripal_feature.gff_loader.inc 85 KB

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