tripal_feature.gff_loader.inc 70 KB

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