tripal_feature.gff_loader.inc 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  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. $org = tripal_core_chado_select('organism', array("*"), $values);
  514. if (count($org) == 0) {
  515. if ($create_organism) {
  516. $feature_organism = (object) tripal_core_chado_insert('organism', $values);
  517. if (!$feature_organism) {
  518. watchdog('T_gff3_loader', "Could not add the organism, '%org', from line %line. Skipping this line. ",
  519. array('%org' => $attr_organism, '%line' => $line_num), WATCHDOG_ERROR);
  520. $skip_feature = 1;
  521. }
  522. }
  523. else {
  524. watchdog('T_gff3_loader', "The organism attribute '%org' on line %line does not exist. Skipping this line. ",
  525. array('%org' => $attr_organism, '%line' => $line_num), WATCHDOG_ERROR);
  526. $skip_feature = 1;
  527. }
  528. }
  529. else {
  530. // we found the organism in the database so use it
  531. $feature_organism = $org[0];
  532. }
  533. }
  534. else {
  535. watchdog('T_gff3_loader', "The organism attribute '%org' on line %line is not properly formated. It " .
  536. "should be of the form: organism=Genus:species. Skipping this line.",
  537. array('%org' => $attr_organism, '%line' => $line_num), WATCHDOG_ERROR);
  538. $skip_feature = 1;
  539. }
  540. }
  541. // get the list of non-reserved attributes
  542. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  543. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  544. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  545. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  546. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  547. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  548. foreach ($tags[$tag_name] as $value) {
  549. $attr_others[$tag_name][] = $value;
  550. }
  551. }
  552. }
  553. if ($skip_line) {
  554. continue;
  555. }
  556. // if neither name nor uniquename are provided then generate one
  557. if (!$attr_uniquename and !$attr_name) {
  558. // check if an alternate ID field is suggested, if so, then use
  559. // that for the name
  560. if (array_key_exists($alt_id_attr, $tags)) {
  561. $attr_uniquename = $tags[$alt_id_attr][0];
  562. $attr_name = $attr_uniquename;
  563. }
  564. // if the row has a parent then generate a uniquename using the parent name
  565. // add the date to the name in the event there are more than one child with
  566. // the same parent.
  567. elseif (array_key_exists('Parent', $tags)) {
  568. $date = getdate();
  569. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  570. $attr_name = $attr_uniquename;
  571. }
  572. // generate a unique name based on the date, type and location
  573. // and set the name to simply be the type
  574. else {
  575. $date = getdate();
  576. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  577. $attr_name = $type;
  578. }
  579. }
  580. // if a name is not specified then use the unique name as the name
  581. if (strcmp($attr_name, '')==0) {
  582. $attr_name = $attr_uniquename;
  583. }
  584. // if an ID attribute is not specified then use the attribute name plus the date
  585. if (!$attr_uniquename) {
  586. $date = getdate();
  587. $attr_uniquename = $attr_name . '-' . $date[0];
  588. }
  589. // make sure the landmark sequence exists in the database. If the user
  590. // has not specified a landmark type (and it's not requiredin the GFF foramt)
  591. // then We don't know the type of the landmark so we'll hope that it's unique across
  592. // all types for the orgnaism. Only do this test if the landmark and the feature are
  593. // different.
  594. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0)) {
  595. $select = array(
  596. 'organism_id' => $organism->organism_id,
  597. 'uniquename' => $landmark,
  598. );
  599. $columns = array('count(*) as num_landmarks');
  600. if ($landmark_type) {
  601. $select['type_id'] = array(
  602. 'name' => $landmark_type,
  603. );
  604. }
  605. $count = tripal_core_chado_select('feature', $columns, $select);
  606. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  607. // now look for the landmark using the name rather than uniquename.
  608. $select = array(
  609. 'organism_id' => $organism->organism_id,
  610. 'name' => $landmark,
  611. );
  612. $columns = array('count(*) as num_landmarks');
  613. if ($landmark_type) {
  614. $select['type_id'] = array(
  615. 'name' => $landmark_type,
  616. );
  617. }
  618. $count = tripal_core_chado_select('feature', $columns, $select);
  619. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  620. watchdog('T_gff3_loader', "The landmark '%landmark' cannot be found for this organism (%species) " .
  621. "Please add the landmark and then retry the import of this GFF3 " .
  622. "file", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species), WATCHDOG_ERROR);
  623. return '';
  624. }
  625. elseif ($count[0]->num_landmarks > 1) {
  626. watchdog('T_gff3_loader', "The landmark '%landmark' has more than one entry for this organism (%species) " .
  627. "Cannot continue", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species), WATCHDOG_ERROR);
  628. return '';
  629. }
  630. }
  631. if ($count[0]->num_landmarks > 1) {
  632. watchdog('T_gff3_loader', "The landmark '%landmark' is not unique for this organism. " .
  633. "The features cannot be associated", array('%landmark' => $landmark), WATCHDOG_ERROR);
  634. return '';
  635. }
  636. }
  637. // if the option is to remove or refresh then we want to remove
  638. // the feature from the database.
  639. if ($remove or $refresh) {
  640. $sql = "DELETE FROM {feature}
  641. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  642. $match = array(
  643. 'organism_id' => $feature_organism->organism_id,
  644. 'uniquename' => $attr_uniquename,
  645. 'type_id' => $cvterm->cvterm_id
  646. );
  647. $result = tripal_core_chado_delete('feature', $match);
  648. if (!$result) {
  649. watchdog('T_gff3_loader', "cannot delete feature %attr_uniquename",
  650. array('%attr_uniquename' => $attr_uniquename), WATCHDOG_ERROR);
  651. }
  652. $feature = 0;
  653. unset($result);
  654. }
  655. // add or update the feature and all properties
  656. if ($update or $refresh or $add_only) {
  657. // add/update the feature
  658. $feature = tripal_feature_load_gff3_feature($feature_organism, $analysis_id, $cvterm,
  659. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  660. $attr_is_obsolete, $add_only, $score);
  661. if ($feature) {
  662. // add a record for this feature to the tripal_gff_temp table for
  663. // later lookup
  664. $values = array(
  665. 'feature_id' => $feature->feature_id,
  666. 'organism_id' => $feature->organism_id,
  667. 'type_name' => $type,
  668. 'uniquename' => $feature->uniquename
  669. );
  670. // make sure this record doesn't already exist in oru temp table
  671. $results = tripal_core_chado_select('tripal_gff_temp', array('*'), $values);
  672. if (count($results) == 0) {
  673. $result = tripal_core_chado_insert('tripal_gff_temp', $values);
  674. if (!$result) {
  675. watchdog('T_gff3_loader', "Cound not save record in temporary table, Cannot continue.", array(), WATCHDOG_ERROR);
  676. exit;
  677. }
  678. }
  679. // add/update the featureloc if the landmark and the ID are not the same
  680. // if they are the same then this entry in the GFF is probably a landmark identifier
  681. if (strcmp($landmark, $attr_uniquename) !=0 ) {
  682. tripal_feature_load_gff3_featureloc($feature, $organism,
  683. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  684. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  685. }
  686. // add any aliases for this feature
  687. if (array_key_exists('Alias', $tags)) {
  688. tripal_feature_load_gff3_alias($feature, $tags['Alias']);
  689. }
  690. // add any dbxrefs for this feature
  691. if (array_key_exists('Dbxref', $tags)) {
  692. tripal_feature_load_gff3_dbxref($feature, $tags['Dbxref']);
  693. }
  694. // add any ontology terms for this feature
  695. if (array_key_exists('Ontology_term', $tags)) {
  696. tripal_feature_load_gff3_ontology($feature, $tags['Ontology_term']);
  697. }
  698. // add parent relationships
  699. if (array_key_exists('Parent', $tags)) {
  700. tripal_feature_load_gff3_parents($feature, $cvterm, $tags['Parent'], $feature_organism->organism_id, $fmin);
  701. }
  702. // add target relationships
  703. if (array_key_exists('Target', $tags)) {
  704. tripal_feature_load_gff3_target($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  705. }
  706. // add gap information. This goes in simply as a property
  707. if (array_key_exists('Gap', $tags)) {
  708. foreach ($tags['Gap'] as $value) {
  709. tripal_feature_load_gff3_property($feature, 'Gap', $value);
  710. }
  711. }
  712. // add notes. This goes in simply as a property
  713. if (array_key_exists('Note', $tags)) {
  714. foreach ($tags['Note'] as $value) {
  715. tripal_feature_load_gff3_property($feature, 'Note', $value);
  716. }
  717. }
  718. // add the Derives_from relationship (e.g. polycistronic genes).
  719. if (array_key_exists('Derives_from', $tags)) {
  720. tripal_feature_load_gff3_derives_from($feature, $tags['Derives_from'][0], $feature_organism);
  721. }
  722. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  723. $source_ref = array('GFF_source:' . $source);
  724. tripal_feature_load_gff3_dbxref($feature, $source_ref);
  725. // add any additional attributes
  726. if ($attr_others) {
  727. foreach ($attr_others as $tag_name => $values) {
  728. foreach ($values as $value) {
  729. tripal_feature_load_gff3_property($feature, $tag_name, $value);
  730. }
  731. }
  732. }
  733. }
  734. }
  735. }
  736. if (!$remove) {
  737. print "\nSetting ranks of children...\n";
  738. // get features in a relationship that are also children of an alignment
  739. $sql = "
  740. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  741. F.uniquename, FL.strand
  742. FROM {tripal_gff_temp} TGT
  743. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  744. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  745. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  746. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  747. WHERE CVT.name = 'part_of'
  748. ";
  749. $parents = chado_query($sql);
  750. // build and prepare the SQL for selecting the children relationship
  751. $sel_gffchildren_sql = "
  752. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  753. FROM {feature_relationship} FR
  754. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  755. WHERE FR.object_id = :feature_id ORDER BY FL.fmin ASC
  756. ";
  757. // now set the rank of any parent/child relationships. The order is based
  758. // on the fmin. The start rank is 1. This allows features with other
  759. // relationships to be '0' (the default), and doesn't interfer with the
  760. // ordering defined here.
  761. while ($parent = $parents->fetchObject()) {
  762. // get the children
  763. if ($connection) {
  764. $result = chado_query($sel_gffchildren_sql, array(':feature_id' => $parent->feature_id));
  765. }
  766. else {
  767. $result = chado_query($sql, array(':feature_id' => $parent->feature_id));
  768. }
  769. // build an array of the children
  770. $children = array();
  771. while ($child = $result->fetchObject()) {
  772. $children[] = $child;
  773. }
  774. // the children list comes sorted in ascending fmin
  775. // but if the parent is on the reverse strand we need to
  776. // reverse the order of the children.
  777. if ($parent->strand == -1) {
  778. arsort($children);
  779. }
  780. // first set the ranks to a negative number so that we don't
  781. // get a duplicate error message when we try to change any of them
  782. $rank = -1;
  783. foreach ($children as $child) {
  784. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  785. $values = array('rank' => $rank);
  786. tripal_core_chado_update('feature_relationship', $match, $values);
  787. $rank--;
  788. }
  789. // now set the rank correctly. The rank should start at 0.
  790. $rank = 0;
  791. foreach ($children as $child) {
  792. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  793. $values = array('rank' => $rank);
  794. //print "Was: " . $child->rank . " now $rank ($parent->strand)\n" ;
  795. tripal_core_chado_update('feature_relationship', $match, $values);
  796. $rank++;
  797. }
  798. }
  799. }
  800. }
  801. catch (Exception $e) {
  802. print "\n"; // make sure we start errors on new line
  803. watchdog_exception('T_gff3_loader', $e);
  804. if ($use_transaction) {
  805. $transaction->rollback();
  806. print "FAILED: Rolling back database changes...\n";
  807. }
  808. else {
  809. print "FAILED\n";
  810. }
  811. return 0;
  812. }
  813. print "Done\n";
  814. return 1;
  815. }
  816. /**
  817. *
  818. *
  819. * @ingroup gff3_loader
  820. */
  821. function tripal_feature_load_gff3_derives_from($feature, $subject, $organism) {
  822. // get the subject type
  823. $values = array(
  824. 'organism_id' => $organism->organism_id,
  825. 'uniquename' => $subject,
  826. );
  827. $result = tripal_core_chado_select('tripal_gff_temp', array('type_name'), $values);
  828. if (count($result) == 0) {
  829. watchdog("T_gff3_loader", "Cannot find subject type for feature in 'derives_from' relationship: %subject", array('%subject' => $subject), WATCHDOG_WARNING);
  830. return '';
  831. }
  832. $subject_type = $result[0]->type_name;
  833. // get the subject feature
  834. $match = array(
  835. 'organism_id' => $organism->organism_id,
  836. 'uniquename' => $subject,
  837. 'type_id' => array(
  838. 'name' => $subject_type,
  839. 'cv_id' => array(
  840. 'name' => 'sequence'
  841. ),
  842. ),
  843. );
  844. $sfeature = tripal_core_chado_select('feature', array('feature_id'), $match);
  845. if (count($sfeature)==0) {
  846. watchdog('T_gff3_loader', "Could not add 'Derives_from' relationship " .
  847. "for %uniquename and %subject. Subject feature, '%subject', " .
  848. "cannot be found", array('%uniquename' => $feature->uniquename, '%subject' => $subject), WATCHDOG_ERROR);
  849. return;
  850. }
  851. // now check to see if the relationship already exists
  852. $values = array(
  853. 'object_id' => $sfeature[0]->feature_id,
  854. 'subject_id' => $feature->feature_id,
  855. 'type_id' => array(
  856. 'cv_id' => array(
  857. 'name' => 'relationship'
  858. ),
  859. 'name' => 'derives_from',
  860. ),
  861. 'rank' => 0
  862. );
  863. $rel = tripal_core_chado_select('feature_relationship', array('*'), $values);
  864. if (count($rel) > 0) {
  865. return;
  866. }
  867. // finally insert the relationship if it doesn't exist
  868. $ret = tripal_core_chado_insert('feature_relationship', $values);
  869. if (!$ret) {
  870. watchdog("T_gff3_loader", "Could not add 'Derives_from' relationship for $feature->uniquename and $subject",
  871. array(), WATCHDOG_WARNING);
  872. }
  873. }
  874. /**
  875. *
  876. *
  877. * @ingroup gff3_loader
  878. */
  879. function tripal_feature_load_gff3_parents($feature, $cvterm, $parents, $organism_id, $fmin) {
  880. $uname = $feature->uniquename;
  881. $type = $cvterm->name;
  882. $rel_type = 'part_of';
  883. // prepare these SQL statements that will be used repeatedly.
  884. $cvterm_sql = "
  885. SELECT CVT.cvterm_id
  886. FROM {cvterm} CVT
  887. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  888. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  889. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  890. ";
  891. // iterate through the parents in the list
  892. foreach ($parents as $parent) {
  893. // get the parent cvterm
  894. $values = array(
  895. 'organism_id' => $organism_id,
  896. 'uniquename' => $parent,
  897. );
  898. $result = tripal_core_chado_select('tripal_gff_temp', array('type_name'), $values);
  899. if (count($result) == 0) {
  900. watchdog("T_gff3_loader", "Cannot find parent: %parent", array('%parent' => $parent), WATCHDOG_WARNING);
  901. return '';
  902. }
  903. $parent_type = $result[0]->type_name;
  904. // try to find the parent
  905. $parentcvterm = chado_query($cvterm_sql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
  906. $relcvterm = chado_query($cvterm_sql, array(':cvname' => 'relationship', ':name' => $rel_type, ':synonym' => $rel_type))->fetchObject();
  907. $values = array(
  908. 'organism_id' => $organism_id,
  909. 'uniquename' => $parent,
  910. 'type_id' => $parentcvterm->cvterm_id,
  911. );
  912. $result = tripal_core_chado_select('feature', array('feature_id'), $values);
  913. $parent_feature = $result[0];
  914. // if the parent exists then add the relationship otherwise print error and skip
  915. if ($parent_feature) {
  916. // check to see if the relationship already exists
  917. $values = array(
  918. 'object_id' => $parent_feature->feature_id,
  919. 'subject_id' => $feature->feature_id,
  920. 'type_id' => $relcvterm->cvterm_id,
  921. );
  922. $rel = tripal_core_chado_select('feature_relationship', array('*'), $values);
  923. if (count($rel) > 0) {
  924. }
  925. else {
  926. // the relationship doesn't already exist, so add it.
  927. $values = array(
  928. 'subject_id' => $feature->feature_id,
  929. 'object_id' => $parent_feature->feature_id,
  930. 'type_id' => $relcvterm->cvterm_id,
  931. );
  932. $result = tripal_core_chado_insert('feature_relationship', $values);
  933. if (!$result) {
  934. watchdog("T_gff3_loader", "Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)",
  935. array(), WATCHDOG_WARNING);
  936. }
  937. }
  938. }
  939. else {
  940. watchdog("T_gff3_loader", "Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent",
  941. array(), WATCHDOG_WARNING);
  942. }
  943. }
  944. }
  945. /**
  946. *
  947. *
  948. * @ingroup gff3_loader
  949. */
  950. function tripal_feature_load_gff3_dbxref($feature, $dbxrefs) {
  951. // iterate through each of the dbxrefs
  952. foreach ($dbxrefs as $dbxref) {
  953. // get the database name from the reference. If it doesn't exist then create one.
  954. $ref = explode(":", $dbxref);
  955. $dbname = $ref[0];
  956. $accession = $ref[1];
  957. // first look for the database name if it doesn't exist then create one.
  958. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  959. // can't be found then look for the name as is. If it still can't be found
  960. // the create the database
  961. $values = array('name' => "DB:$dbname");
  962. $db = tripal_core_chado_select('db', array('db_id'), $values);
  963. if (count($db) == 0) {
  964. $values = array('name' => "$dbname");
  965. $db = tripal_core_chado_select('db', array('db_id'), $values);
  966. }
  967. if (count($db) == 0) {
  968. $values = array(
  969. 'name' => $dbname,
  970. 'description' => 'Added automatically by the GFF loader'
  971. );
  972. $success = tripal_core_chado_insert('db', $values);
  973. if ($success) {
  974. $values = array('name' => "$dbname");
  975. $db = tripal_core_chado_select('db', array('db_id'), $values);
  976. }
  977. else {
  978. watchdog("T_gff3_loader", "Cannot find or add the database $dbname", array(), WATCHDOG_WARNING);
  979. return 0;
  980. }
  981. }
  982. $db = $db[0];
  983. // now check to see if the accession exists
  984. $values = array(
  985. 'accession' => $accession,
  986. 'db_id' => $db->db_id
  987. );
  988. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'), $values);
  989. // if the accession doesn't exist then we want to add it
  990. if (sizeof($dbxref) == 0) {
  991. $values = array(
  992. 'db_id' => $db->db_id,
  993. 'accession' => $accession,
  994. 'version' => ''
  995. );
  996. $ret = tripal_core_chado_insert('dbxref', $values);
  997. $values = array(
  998. 'accession' => $accession,
  999. 'db_id' => $db->db_id
  1000. );
  1001. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'), $values);
  1002. }
  1003. $dbxref = $dbxref[0];
  1004. // check to see if this feature dbxref already exists
  1005. $values = array(
  1006. 'dbxref_id' => $dbxref->dbxref_id,
  1007. 'feature_id' => $feature->feature_id
  1008. );
  1009. $fdbx = tripal_core_chado_select('feature_dbxref', array('feature_dbxref_id'), $values);
  1010. // now associate this feature with the database reference if it doesn't
  1011. // already exist
  1012. if (sizeof($fdbx) == 0) {
  1013. $values = array(
  1014. 'dbxref_id' => $dbxref->dbxref_id,
  1015. 'feature_id' => $feature->feature_id
  1016. );
  1017. $success = tripal_core_chado_insert('feature_dbxref', $values);
  1018. if (!$success) {
  1019. watchdog("T_gff3_loader", "Failed to insert Dbxref: $dbname:$accession", array(), WATCHDOG_WARNING);
  1020. return 0;
  1021. }
  1022. }
  1023. }
  1024. return 1;
  1025. }
  1026. /**
  1027. *
  1028. *
  1029. * @ingroup gff3_loader
  1030. */
  1031. function tripal_feature_load_gff3_ontology($feature, $dbxrefs) {
  1032. // iterate through each of the dbxrefs
  1033. foreach ($dbxrefs as $dbxref) {
  1034. // get the database name from the reference. If it doesn't exist then create one.
  1035. $ref = explode(":", $dbxref);
  1036. $dbname = $ref[0];
  1037. $accession = $ref[1];
  1038. // first look for the database name
  1039. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "DB:$dbname"));
  1040. if (sizeof($db) == 0) {
  1041. // now look for the name without the 'DB:' prefix.
  1042. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "$dbname"));
  1043. if (sizeof($db) == 0) {
  1044. watchdog("T_gff3_loader", "Database, $dbname, is not present. Cannot associate term: $dbname:$accession", array(), WATCHDOG_WARNING);
  1045. return 0;
  1046. }
  1047. }
  1048. $db = $db[0];
  1049. // now check to see if the accession exists
  1050. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'),
  1051. array('accession' => $accession, 'db_id' => $db->db_id));
  1052. if (sizeof($dbxref) == 0) {
  1053. watchdog("T_gff3_loader", "Accession, $accession is missing for reference: $dbname:$accession", array(), WATCHDOG_WARNING);
  1054. return 0;
  1055. }
  1056. $dbxref = $dbxref[0];
  1057. // now check to see if the cvterm exists
  1058. $cvterm = tripal_core_chado_select('cvterm', array('cvterm_id'), array(
  1059. 'dbxref_id' => $dbxref->dbxref_id));
  1060. // if it doesn't exist in the cvterm table, look for an alternate id
  1061. if (sizeof($cvterm) == 0) {
  1062. $cvterm = tripal_core_chado_select('cvterm_dbxref', array('cvterm_id'), array(
  1063. 'dbxref_id' => $dbxref->dbxref_id));
  1064. if (sizeof($cvterm) == 0) {
  1065. watchdog("T_gff3_loader", "CV Term is missing for reference: $dbname:$accession", array(), WATCHDOG_WARNING);
  1066. return 0;
  1067. }
  1068. }
  1069. $cvterm = $cvterm[0];
  1070. // check to see if this feature cvterm already exists
  1071. $fcvt = tripal_core_chado_select('feature_cvterm', array('feature_cvterm_id'),
  1072. array('cvterm_id' => $cvterm->cvterm_id, 'feature_id' => $feature->feature_id));
  1073. // now associate this feature with the cvterm if it doesn't already exist
  1074. if (sizeof($fcvt)==0) {
  1075. $values = array(
  1076. 'cvterm_id' => $cvterm->cvterm_id,
  1077. 'feature_id' => $feature->feature_id,
  1078. 'pub_id' => array(
  1079. 'uniquename' => 'null',
  1080. ),
  1081. );
  1082. $success = tripal_core_chado_insert('feature_cvterm', $values);
  1083. if (!$success) {
  1084. watchdog("T_gff3_loader", "Failed to insert ontology term: $dbname:$accession", array(), WATCHDOG_WARNING);
  1085. return 0;
  1086. }
  1087. }
  1088. }
  1089. return 1;
  1090. }
  1091. /**
  1092. *
  1093. *
  1094. * @ingroup gff3_loader
  1095. */
  1096. function tripal_feature_load_gff3_alias($feature, $aliases) {
  1097. // make sure we have a 'synonym_type' vocabulary
  1098. $select = array('name' => 'synonym_type');
  1099. $results = tripal_core_chado_select('cv', array('*'), $select);
  1100. if (count($results) == 0) {
  1101. // insert the 'synonym_type' vocabulary
  1102. $values = array(
  1103. 'name' => 'synonym_type',
  1104. 'definition' => 'vocabulary for synonym types',
  1105. );
  1106. $success = tripal_core_chado_insert('cv', $values);
  1107. if (!$success) {
  1108. watchdog("T_gff3_loader", "Failed to add the synonyms type vocabulary", array(), WATCHDOG_WARNING);
  1109. return 0;
  1110. }
  1111. // now that we've added the cv we need to get the record
  1112. $results = tripal_core_chado_select('cv', array('*'), $select);
  1113. if (count($results) > 0) {
  1114. $syncv = $results[0];
  1115. }
  1116. }
  1117. else {
  1118. $syncv = $results[0];
  1119. }
  1120. // get the 'exact' cvterm, which is the type of synonym we're adding
  1121. $select = array(
  1122. 'name' => 'exact',
  1123. 'cv_id' => array(
  1124. 'name' => 'synonym_type'
  1125. ),
  1126. );
  1127. $result = tripal_core_chado_select('cvterm', array('*'), $select);
  1128. if (count($result) == 0) {
  1129. $term = array(
  1130. 'name' => 'exact',
  1131. 'id' => "internal:exact",
  1132. 'definition' => '',
  1133. 'is_obsolete' => 0,
  1134. );
  1135. $syntype = tripal_cv_add_cvterm($term, $syncv->name, 0, 1);
  1136. if (!$syntype) {
  1137. watchdog("T_gff3_loader", "Cannot add synonym type: internal:$type", array(), WATCHDOG_WARNING);
  1138. return 0;
  1139. }
  1140. }
  1141. else {
  1142. $syntype = $result[0];
  1143. }
  1144. // iterate through all of the aliases and add each one
  1145. foreach ($aliases as $alias) {
  1146. // check to see if the alias already exists in the synonym table
  1147. // if not, then add it
  1148. $select = array(
  1149. 'name' => $alias,
  1150. 'type_id' => $syntype->cvterm_id,
  1151. );
  1152. $result = tripal_core_chado_select('synonym', array('*'), $select);
  1153. if (count($result) == 0) {
  1154. $values = array(
  1155. 'name' => $alias,
  1156. 'type_id' => $syntype->cvterm_id,
  1157. 'synonym_sgml' => '',
  1158. );
  1159. $success = tripal_core_chado_insert('synonym', $values);
  1160. if (!$success) {
  1161. watchdog("T_gff3_loader", "Cannot add alias $alias to synonym table", array(), WATCHDOG_WARNING);
  1162. return 0;
  1163. }
  1164. $result = tripal_core_chado_select('synonym', array('*'), $select);
  1165. $synonym = $result[0];
  1166. }
  1167. else {
  1168. $synonym = $result[0];
  1169. }
  1170. // check to see if we have a NULL publication in the pub table. If not,
  1171. // then add one.
  1172. $select = array('uniquename' => 'null');
  1173. $result = tripal_core_chado_select('pub', array('*'), $select);
  1174. if (count($result) == 0) {
  1175. // prepare the statement
  1176. $pub_sql = "
  1177. INSERT INTO {pub} (uniquename,type_id)
  1178. VALUES (:uname,
  1179. (SELECT cvterm_id
  1180. FROM {cvterm} CVT
  1181. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  1182. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  1183. WHERE CVT.name = :type_id))
  1184. ";
  1185. $status = chado_query($psql);
  1186. if (!$status) {
  1187. watchdog("T_gff3_loader", "Cannot prepare statement 'ins_pub_uniquename_typeid", array(), WATCHDOG_WARNING);
  1188. return 0;
  1189. }
  1190. // insert the null pub
  1191. $result = chado_query($pub_sql, array(':uname' => 'null', ':type_id' => 'null'))->fetchObject();
  1192. if (!$result) {
  1193. watchdog("T_gff3_loader", "Cannot add null publication needed for setup of alias", array(), WATCHDOG_WARNING);
  1194. return 0;
  1195. }
  1196. $result = tripal_core_chado_select('pub', array('*'), $select);
  1197. $pub = $result[0];
  1198. }
  1199. else {
  1200. $pub = $result[0];
  1201. }
  1202. // check to see if the synonym exists in the feature_synonym table
  1203. // if not, then add it.
  1204. $values = array(
  1205. 'synonym_id' => $synonym->synonym_id,
  1206. 'feature_id' => $feature->feature_id,
  1207. 'pub_id' => $pub->pub_id,
  1208. );
  1209. $columns = array('feature_synonym_id');
  1210. $result = tripal_core_chado_select('feature_synonym', $columns, $values);
  1211. if (count($result) == 0) {
  1212. $values = array(
  1213. 'synonym_id' => $synonym->synonym_id,
  1214. 'feature_id' => $feature->feature_id,
  1215. 'pub_id' => $pub->pub_id,
  1216. );
  1217. $success = tripal_core_chado_insert('feature_synonym', $values);
  1218. if (!$success) {
  1219. watchdog("T_gff3_loader", "Cannot add alias $alias to feature synonym table", array(), WATCHDOG_WARNING);
  1220. return 0;
  1221. }
  1222. }
  1223. }
  1224. return 1;
  1225. }
  1226. /**
  1227. *
  1228. *
  1229. * @ingroup gff3_loader
  1230. */
  1231. function tripal_feature_load_gff3_feature($organism, $analysis_id, $cvterm, $uniquename,
  1232. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1233. // check to see if the feature already exists
  1234. $feature = NULL;
  1235. $fselect = array(
  1236. 'organism_id' => $organism->organism_id,
  1237. 'uniquename' => $uniquename,
  1238. 'type_id' => $cvterm->cvterm_id
  1239. );
  1240. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1241. $result = tripal_core_chado_select('feature', $columns, $fselect);
  1242. if (count($result) > 0) {
  1243. $feature = $result[0];
  1244. }
  1245. if (strcmp($is_obsolete, 'f')==0 or $is_obsolete == 0) {
  1246. $is_obsolete = 'FALSE';
  1247. }
  1248. if (strcmp($is_obsolete, 't')==0 or $is_obsolete == 1) {
  1249. $is_obsolete = 'TRUE';
  1250. }
  1251. if (strcmp($is_analysis, 'f')==0 or $is_analysis == 0) {
  1252. $is_analysis = 'FALSE';
  1253. }
  1254. if (strcmp($is_analysis, 't')==0 or $is_analysis == 1) {
  1255. $is_analysis = 'TRUE';
  1256. }
  1257. // insert the feature if it does not exist otherwise perform an update
  1258. if (!$feature) {
  1259. $values = array(
  1260. 'organism_id' => $organism->organism_id,
  1261. 'name' => $name,
  1262. 'uniquename' => $uniquename,
  1263. // 'residues' => $residues,
  1264. // 'seqlen' => drupal_strlen($residues),
  1265. 'md5checksum' => md5($residues),
  1266. 'type_id' => $cvterm->cvterm_id,
  1267. 'is_analysis' => $is_analysis,
  1268. 'is_obsolete' => $is_obsolete,
  1269. );
  1270. $result = tripal_core_chado_insert('feature', $values);
  1271. if (!$result) {
  1272. watchdog("T_gff3_loader", "Failed to insert feature '$uniquename' ($cvterm->name)", array(), WATCHDOG_WARNING);
  1273. return 0;
  1274. }
  1275. }
  1276. elseif (!$add_only) {
  1277. $values = array(
  1278. 'name' => $name,
  1279. // 'residues' => $residues,
  1280. // 'seqlen' => drupal_strlen($residues),
  1281. 'md5checksum' => md5($residues),
  1282. 'is_analysis' => $is_analysis,
  1283. 'is_obsolete' => $is_obsolete,
  1284. );
  1285. $match = array(
  1286. 'organism_id' => $organism->organism_id,
  1287. 'uniquename' => $uniquename,
  1288. 'type_id' => $cvterm->cvterm_id,
  1289. );
  1290. $result = tripal_core_chado_update('feature', $match, $values);
  1291. if (!$result) {
  1292. watchdog("T_gff3_loader", "Failed to update feature '$uniquename' ($cvterm->name)", array(), WATCHDOG_WARNING);
  1293. return 0;
  1294. }
  1295. }
  1296. else {
  1297. // the feature exists and we don't want to update it so return
  1298. // a value of 0. This will stop all downstream property additions
  1299. return 0;
  1300. }
  1301. // get the newly added feature
  1302. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1303. $result = tripal_core_chado_select('feature', $columns, $fselect);
  1304. $feature = $result[0];
  1305. // add the analysisfeature entry to the analysisfeature table if it doesn't already exist
  1306. $af_values = array(
  1307. 'analysis_id' => $analysis_id,
  1308. 'feature_id' => $feature->feature_id
  1309. );
  1310. $afeature = tripal_core_chado_select('analysisfeature', array('analysisfeature_id'), $af_values);
  1311. if (count($afeature)==0) {
  1312. // if a score is available then set that to be the significance field
  1313. if (strcmp($score, '.') != 0) {
  1314. $af_values['significance'] = $score;
  1315. }
  1316. if (!tripal_core_chado_insert('analysisfeature', $af_values)) {
  1317. watchdog("T_gff3_loader", "Could not add analysisfeature record: $analysis_id, $feature->feature_id", array(), WATCHDOG_WARNING);
  1318. }
  1319. }
  1320. else {
  1321. // if a score is available then set that to be the significance field
  1322. $new_vals = array();
  1323. if (strcmp($score, '.')!=0) {
  1324. $new_vals['significance'] = $score;
  1325. }
  1326. else {
  1327. $new_vals['significance'] = '__NULL__';
  1328. }
  1329. if (!$add_only) {
  1330. $ret = tripal_core_chado_update('analysisfeature', $af_values, $new_vals);
  1331. if (!$ret) {
  1332. watchdog("T_gff3_loader", "Could not update analysisfeature record: $analysis_id, $feature->feature_id", array(), WATCHDOG_WARNING);
  1333. }
  1334. }
  1335. }
  1336. return $feature;
  1337. }
  1338. /**
  1339. *
  1340. *
  1341. * @ingroup gff3_loader
  1342. */
  1343. function tripal_feature_load_gff3_featureloc($feature, $organism, $landmark, $fmin,
  1344. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  1345. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  1346. $landmark_is_target = 0) {
  1347. $select = array(
  1348. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1349. 'uniquename' => $landmark,
  1350. );
  1351. if ($landmark_type_id) {
  1352. $select['type_id'] = $landmark_type_id;
  1353. }
  1354. $results = tripal_core_chado_select('feature', array('feature_id'), $select);
  1355. $srcfeature = '';
  1356. if (count($results)==0) {
  1357. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  1358. // if we return only a single result then we can proceed. Otherwise give an
  1359. $select = array(
  1360. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1361. 'name' => $landmark,
  1362. );
  1363. if ($landmark_type_id) {
  1364. $select['type_id'] = $landmark_type_id;
  1365. }
  1366. $results = tripal_core_chado_select('feature', array('feature_id'), $select);
  1367. if (count($results) == 0) {
  1368. // if the landmark is the target feature in a matched alignment then try one more time to
  1369. // find it by querying any feature with the same uniquename. If we find one then use it.
  1370. if ($landmark_is_target) {
  1371. $select = array('uniquename' => $landmark);
  1372. $results = tripal_core_chado_select('feature', array('feature_id'), $select);
  1373. if (count($results) == 1) {
  1374. $srcfeature = $results[0];
  1375. }
  1376. }
  1377. if (!$srcfeature) {
  1378. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  1379. // but only if we have a type id
  1380. if ($create_landmark and $landmark_type_id) {
  1381. $values = array(
  1382. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1383. 'name' => $landmark,
  1384. 'uniquename' => $landmark,
  1385. 'type_id' => $landmark_type_id
  1386. );
  1387. $results = tripal_core_chado_insert('feature', $values);
  1388. if (!$results) {
  1389. watchdog("T_gff3_loader", "Cannot find landmark feature: '%landmark', nor could it be inserted",
  1390. array('%landmark' => $landmark), WATCHDOG_WARNING);
  1391. return 0;
  1392. }
  1393. $srcfeature = new stdClass();
  1394. $srcfeature->feature_id = $results['feature_id'];
  1395. }
  1396. else {
  1397. watchdog("T_gff3_loader", "Cannot find unique landmark feature: '%landmark'.",
  1398. array('%landmark' => $landmark), WATCHDOG_WARNING);
  1399. return 0;
  1400. }
  1401. }
  1402. }
  1403. elseif (count($results) > 1) {
  1404. watchdog("T_gff3_loader", "multiple landmarks exist with the name: '%landmark'. Cannot
  1405. resolve which one to use. Cannot add the feature location record",
  1406. array('%landmark' => $landmark), WATCHDOG_WARNING);
  1407. return 0;
  1408. }
  1409. else {
  1410. $srcfeature = $results[0];
  1411. }
  1412. }
  1413. elseif (count($results) > 1) {
  1414. watchdog("T_gff3_loader", "multiple landmarks exist with the name: '%landmark'. Cannot
  1415. resolve which one to use. Cannot add the feature location record",
  1416. array('%landmark' => $landmark), WATCHDOG_WARNING);
  1417. return 0;
  1418. }
  1419. else {
  1420. $srcfeature = $results[0];
  1421. }
  1422. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1423. // is_fmin_partial and is_fmax_partial, right now these are
  1424. // hardcoded to be false and 0 below.
  1425. // check to see if this featureloc already exists, but also keep track of the
  1426. // last rank value
  1427. $rank = 0;
  1428. $exists = 0;
  1429. $select = array('feature_id' => $feature->feature_id);
  1430. $options = array(
  1431. 'order_by' => array(
  1432. 'rank' => 'ASC'
  1433. ),
  1434. );
  1435. $locrecs = tripal_core_chado_select('featureloc', array('*'), $select, $options);
  1436. foreach ($locrecs as $featureloc) {
  1437. // it is possible for the featureloc->srcfeature_id to be NULL. This can happen if the srcfeature
  1438. // is not known (according to chado table field descriptions). If it's null then just skip this entry
  1439. if (!$featureloc->srcfeature_id) {
  1440. continue;
  1441. }
  1442. $select = array('feature_id' => $featureloc->srcfeature_id);
  1443. $columns = array('feature_id', 'name');
  1444. $locsfeature = tripal_core_chado_select('feature', $columns, $select);
  1445. // the source feature name and at least the fmin and fmax must be the same
  1446. // for an update of the featureloc, otherwise we'll insert a new record.
  1447. if (strcmp($locsfeature[0]->name, $landmark)==0 and
  1448. ($featureloc->fmin == $fmin or $featureloc->fmax == $fmax)) {
  1449. $match = array('featureloc_id' => $featureloc->featureloc_id);
  1450. $values = array();
  1451. $exists = 1;
  1452. if ($featureloc->fmin != $fmin) {
  1453. $values['fmin'] = $fmin;
  1454. }
  1455. if ($featureloc->fmax != $fmax) {
  1456. $values['fmax'] = $fmax;
  1457. }
  1458. if ($featureloc->strand != $strand) {
  1459. $values['strand'] = $strand;
  1460. }
  1461. if (count($values) > 0) {
  1462. tripal_core_chado_update('featureloc', $match, $values);
  1463. }
  1464. }
  1465. $rank = $featureloc->rank + 1;
  1466. }
  1467. if (!$exists) {
  1468. // this feature location is new so add it
  1469. if (strcmp($is_fmin_partial, 'f')==0 or !$is_fmin_partial) {
  1470. $is_fmin_partial = 'FALSE';
  1471. }
  1472. elseif (strcmp($is_fmin_partial, 't')==0 or $is_fmin_partial = 1) {
  1473. $is_fmin_partial = 'TRUE';
  1474. }
  1475. if (strcmp($is_fmax_partial, 'f')==0 or !$is_fmax_partial) {
  1476. $is_fmax_partial = 'FALSE';
  1477. }
  1478. elseif (strcmp($is_fmax_partial, 't')==0 or $is_fmax_partial = 1) {
  1479. $is_fmax_partial = 'TRUE';
  1480. }
  1481. $values = array(
  1482. 'feature_id' => $feature->feature_id,
  1483. 'srcfeature_id' => $srcfeature->feature_id,
  1484. 'fmin' => $fmin,
  1485. 'is_fmin_partial' => $is_fmin_partial,
  1486. 'fmax' => $fmax,
  1487. 'is_fmax_partial' => $is_fmax_partial,
  1488. 'strand' => $strand,
  1489. 'residue_info' => $residue_info,
  1490. 'locgroup' => $locgroup,
  1491. 'rank' => $rank
  1492. );
  1493. if ($phase) {
  1494. $values['phase'] = $phase;
  1495. }
  1496. $success = tripal_core_chado_insert('featureloc', $values);
  1497. if (!$success) {
  1498. watchdog("T_gff3_loader", "Failed to insert featureloc", array(), WATCHDOG_WARNING);
  1499. exit;
  1500. return 0;
  1501. }
  1502. }
  1503. return 1;
  1504. }
  1505. /**
  1506. *
  1507. *
  1508. * @ingroup gff3_loader
  1509. */
  1510. function tripal_feature_load_gff3_property($feature, $property, $value) {
  1511. // first make sure the cvterm exists. if not, then add it
  1512. $select = array(
  1513. 'name' => $property,
  1514. 'cv_id' => array(
  1515. 'name' => 'feature_property',
  1516. ),
  1517. );
  1518. $result = tripal_core_chado_select('cvterm', array('*'), $select);
  1519. // if we don't have a property like this already, then add it otherwise, just return
  1520. if (count($result) == 0) {
  1521. $term = array(
  1522. 'id' => "null:$property",
  1523. 'name' => $property,
  1524. 'namespace' => 'feature_property',
  1525. 'is_obsolete' => 0,
  1526. );
  1527. $cvterm = (object) tripal_cv_add_cvterm($term, 'feature_property', 0, 0);
  1528. if (!$cvterm) {
  1529. watchdog("T_gff3_loader", "Cannot add cvterm, $property", array(), WATCHDOG_WARNING);
  1530. return 0;
  1531. }
  1532. }
  1533. else {
  1534. $cvterm = $result[0];
  1535. }
  1536. // check to see if the property already exists for this feature
  1537. // if it does but the value is unique then increment the rank and add it.
  1538. // if the value is not unique then don't add it.
  1539. $add = 1;
  1540. $rank = 0;
  1541. $select = array(
  1542. 'feature_id' => $feature->feature_id,
  1543. 'type_id' => $cvterm->cvterm_id,
  1544. );
  1545. $options = array(
  1546. 'order_by' => array(
  1547. 'rank' => 'ASC',
  1548. ),
  1549. );
  1550. $results = tripal_core_chado_select('featureprop', array('*'), $select, $options);
  1551. foreach ($results as $prop) {
  1552. if (strcmp($prop->value, $value)==0) {
  1553. $add = NULL; // don't add it, it already exists
  1554. }
  1555. $rank = $prop->rank + 1;
  1556. }
  1557. // add the property if we pass the check above
  1558. if ($add) {
  1559. $values = array(
  1560. 'feature_id' => $feature->feature_id,
  1561. 'type_id' => $cvterm->cvterm_id,
  1562. 'value' => $value,
  1563. 'rank' => $rank,
  1564. );
  1565. $result = tripal_core_chado_insert('featureprop', $values);
  1566. if (!$result) {
  1567. watchdog("T_gff3_loader", "cannot add featureprop, $property", array(), WATCHDOG_WARNING);
  1568. }
  1569. }
  1570. }
  1571. /*
  1572. *
  1573. */
  1574. function tripal_feature_load_gff3_fasta($fh, $interval, &$num_read, &$intv_read, &$line_num) {
  1575. print "Loading FASTA sequences\n";
  1576. $residues = '';
  1577. $sel_gfftemp_un_sql = "
  1578. SELECT feature_id FROM tripal_gff_temp
  1579. WHERE uniquename = :uname
  1580. ";
  1581. $id = NULL;
  1582. // iterate through the remaining lines of the file
  1583. while ($line = fgets($fh)) {
  1584. $line_num++;
  1585. $size = drupal_strlen($line);
  1586. $num_read += $size;
  1587. $intv_read += $size;
  1588. $line = trim($line);
  1589. // update the job status every 1% features
  1590. if ($job and $intv_read >= $interval) {
  1591. $intv_read = 0;
  1592. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  1593. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  1594. tripal_job_set_progress($job, intval(($num_read / $filesize) * 100));
  1595. }
  1596. // if we encounter a definition line then get the name, uniquename,
  1597. // accession and relationship subject from the definition line
  1598. if (preg_match('/^>/', $line)) {
  1599. // if we are beginning a new sequence then save the last one we
  1600. // just finished.
  1601. if ($id) {
  1602. $result = chado_query($sel_gfftemp_un_sql, array(':uname' => $id));
  1603. if (!$result) {
  1604. watchdog('T_gff3_loader', 'Cannot find feature to assign FASTA sequence: %uname',
  1605. array('%uname' => $id), WATCHDOG_WARNING);
  1606. }
  1607. // if we have a feature then add the residues
  1608. else {
  1609. $feature = $result->fetchObject();
  1610. $values = array('residues' => $residues);
  1611. $match = array('feature_id' => $feature->feature_id);
  1612. tripal_core_chado_update('feature', $match, $values);
  1613. }
  1614. }
  1615. // get the feature ID for this ID from the tripal_gff_temp table
  1616. $id = preg_replace('/^>(.*)$/', '\1', $line);
  1617. $residues = '';
  1618. }
  1619. else {
  1620. $residues .= trim($line);
  1621. }
  1622. }
  1623. // add in the last sequence
  1624. $result = chado_query($sel_gfftemp_un_sql, array(':uname' => $id));
  1625. if (!$result) {
  1626. watchdog('T_gff3_loader', 'Cannot find feature to assign FASTA sequence: %uname',
  1627. array('%uname' => $id), WATCHDOG_WARNING);
  1628. }
  1629. // if we have a feature then add the residues
  1630. else {
  1631. $feature = $result->fetchObject();
  1632. $values = array('residues' => $residues);
  1633. $match = array('feature_id' => $feature->feature_id);
  1634. tripal_core_chado_update('feature', $match, $values);
  1635. }
  1636. }
  1637. /*
  1638. *
  1639. */
  1640. function tripal_feature_load_gff3_target($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  1641. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  1642. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  1643. // the organism and type of the target may also be specified as an attribute. If so, then get that
  1644. // information
  1645. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  1646. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  1647. // if we have matches and the Target is in the correct format then load the alignment
  1648. if ($matched) {
  1649. $target_feature = $matches[1];
  1650. $start = $matches[2];
  1651. $end = $matches[3];
  1652. // if we have an optional strand, convert it to a numeric value.
  1653. if ($matches[4]) {
  1654. if (preg_match('/^\+$/', trim($matches[4]))) {
  1655. $target_strand = 1;
  1656. }
  1657. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  1658. $target_strand = -1;
  1659. }
  1660. else {
  1661. $target_strand = 0;
  1662. }
  1663. }
  1664. else {
  1665. $target_strand = 0;
  1666. }
  1667. $target_fmin = $start - 1;
  1668. $target_fmax = $end;
  1669. if ($end < $start) {
  1670. $target_fmin = $end - 1;
  1671. $target_fmax = $start;
  1672. }
  1673. // default the target organism to be the value passed into the function, but if the GFF
  1674. // file species the target organism then use that instead.
  1675. $t_organism_id = $target_organism_id;
  1676. if ($gff_target_organism) {
  1677. // get the genus and species
  1678. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  1679. if ($success) {
  1680. $values = array(
  1681. 'genus' => $matches[1],
  1682. 'species' => $matches[2],
  1683. );
  1684. $torganism = tripal_core_chado_select('organism', array('organism_id'), $values);
  1685. if (count($torganism) == 1) {
  1686. $t_organism_id = $torganism[0]->organism_id;
  1687. }
  1688. else {
  1689. watchdog('T_gff3_loader', "Cannot find organism for target %target.",
  1690. array('%target' => $gff_target_organism), WATCHDOG_WARNING);
  1691. $t_organism_id = '';
  1692. }
  1693. }
  1694. else {
  1695. watchdog('T_gff3_loader', "The target_organism attribute is improperly formatted: %target.
  1696. It should be target_organism=genus:species.",
  1697. array('%target' => $gff_target_organism), WATCHDOG_WARNING);
  1698. $t_organism_id = '';
  1699. }
  1700. }
  1701. // default the target type to be the value passed into the function, but if the GFF file
  1702. // species the target type then use that instead
  1703. $t_type_id = '';
  1704. if ($target_type) {
  1705. $values = array(
  1706. 'name' => $target_type,
  1707. 'cv_id' => array(
  1708. 'name' => 'sequence',
  1709. )
  1710. );
  1711. $type = tripal_core_chado_select('cvterm', array('cvterm_id'), $values);
  1712. if (count($type) == 1) {
  1713. $t_type_id = $type[0]->cvterm_id;
  1714. }
  1715. else {
  1716. watchdog('T_gff3_loader', "The target type does not exist in the sequence ontology: %type. ",
  1717. array('%type' => $target_type), WATCHDOG_ERROR);
  1718. exit;
  1719. }
  1720. }
  1721. if ($gff_target_type) {
  1722. $values = array(
  1723. 'name' => $gff_target_type,
  1724. 'cv_id' => array(
  1725. 'name' => 'sequence',
  1726. )
  1727. );
  1728. $type = tripal_core_chado_select('cvterm', array('cvterm_id'), $values);
  1729. if (count($type) == 1) {
  1730. $t_type_id = $type[0]->cvterm_id;
  1731. }
  1732. else {
  1733. watchdog('T_gff3_loader', "The target_type attribute does not exist in the sequence ontology: %type. ",
  1734. array('%type' => $gff_target_type), WATCHDOG_WARNING);
  1735. $t_type_id = '';
  1736. }
  1737. }
  1738. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  1739. // and the landmark as the feature.
  1740. tripal_feature_load_gff3_featureloc($feature, $organism, $target_feature, $target_fmin,
  1741. $target_fmax, $target_strand, $phase, $attr_fmin_partial, $attr_fmax_partial, $attr_residue_info,
  1742. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  1743. }
  1744. // the target attribute is not correctly formatted
  1745. else {
  1746. watchdog('T_gff3_loader', "Could not add 'Target' alignment as it is improperly formatted: '%target'",
  1747. array('%target' => $tags['Target'][0]), WATCHDOG_ERROR);
  1748. }
  1749. }