gff_loader.inc 76 KB

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