tripal_feature.gff_loader.inc 77 KB

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