gff_loader.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. <?php
  2. /**
  3. * @defgroup gff3_loader GFF3 Feature Loader
  4. * @{
  5. * Provides gff3 loading functionality. Creates features based on their specification in a GFF3 file.
  6. * @}
  7. * @ingroup tripal_feature
  8. */
  9. // TODO: The rank column on the feature_relationship table needs to be used to
  10. // make sure the ordering of CDS (exons) is correct.
  11. // The entries in the GFF file are not in order so the order of the relationships
  12. // is not put in correctly.
  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. '#weight' => 1
  27. );
  28. // get the list of organisms
  29. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  30. $previous_db = tripal_db_set_active('chado'); // use chado database
  31. $org_rset = db_query($sql);
  32. tripal_db_set_active($previous_db); // now use drupal database
  33. $organisms = array();
  34. $organisms[''] = '';
  35. while($organism = db_fetch_object($org_rset)){
  36. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  37. }
  38. $form['organism_id'] = array (
  39. '#title' => t('Organism'),
  40. '#type' => t('select'),
  41. '#description' => t("Choose the organism to which these sequences are associated "),
  42. '#required' => TRUE,
  43. '#options' => $organisms,
  44. );
  45. $form['import_options'] = array(
  46. '#type' => 'fieldset',
  47. '#title' => t('Import Options'),
  48. '#weight'=> 6,
  49. '#collapsed' => TRUE
  50. );
  51. $form['import_options']['add_only']= array(
  52. '#type' => 'checkbox',
  53. '#title' => t('Import only new features'),
  54. '#required' => FALSE,
  55. '#description' => t('The job will skip features in the GFF file that already
  56. exist in the database and import only new features.'),
  57. '#weight' => 2
  58. );
  59. $form['import_options']['update']= array(
  60. '#type' => 'checkbox',
  61. '#title' => t('Import all and update'),
  62. '#required' => FALSE,
  63. '#default_value' => 'checked',
  64. '#description' => t('Existing features will be updated and new features will be added. Attributes
  65. for a feature that are not present in the GFF but which are present in the
  66. database will not be altered.'),
  67. '#weight' => 3
  68. );
  69. $form['import_options']['refresh']= array(
  70. '#type' => 'checkbox',
  71. '#title' => t('Import all and replace'),
  72. '#required' => FALSE,
  73. '#description' => t('Existing features will be updated and feature properties not
  74. present in the GFF file will be removed.'),
  75. '#weight' => 4
  76. );
  77. $form['import_options']['remove']= array(
  78. '#type' => 'checkbox',
  79. '#title' => t('Delete features'),
  80. '#required' => FALSE,
  81. '#description' => t('Features present in the GFF file that exist in the database
  82. will be removed rather than imported'),
  83. '#weight' => 5
  84. );
  85. $form['analysis'] = array(
  86. '#type' => 'fieldset',
  87. '#title' => t('Analysis Used to Derive Features'),
  88. '#weight'=> 6,
  89. '#collapsed' => TRUE
  90. );
  91. $form['analysis']['desc'] = array(
  92. '#type' => 'markup',
  93. '#value' => t("Why specify an analysis for a data load? All data comes
  94. from some place, even if downloaded from Genbank. By specifying
  95. analysis details for all data uploads, it allows an end user to reproduce the
  96. data set, but at least indicates the source of the data."),
  97. );
  98. // get the list of analyses
  99. $sql = "SELECT * FROM {analysis} ORDER BY name";
  100. $previous_db = tripal_db_set_active('chado'); // use chado database
  101. $org_rset = db_query($sql);
  102. tripal_db_set_active($previous_db); // now use drupal database
  103. $analyses = array();
  104. $analyses[''] = '';
  105. while($analysis = db_fetch_object($org_rset)){
  106. $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
  107. }
  108. $form['analysis']['analysis_id'] = array (
  109. '#title' => t('Analysis'),
  110. '#type' => t('select'),
  111. '#description' => t("Choose the analysis to which these features are associated "),
  112. '#required' => TRUE,
  113. '#options' => $analyses,
  114. );
  115. $form['button'] = array(
  116. '#type' => 'submit',
  117. '#value' => t('Import GFF3 file'),
  118. '#weight' => 10,
  119. );
  120. return $form;
  121. }
  122. /**
  123. *
  124. *
  125. * @ingroup gff3_loader
  126. */
  127. function tripal_feature_gff3_load_form_validate ($form, &$form_state){
  128. $gff_file = $form_state['values']['gff_file'];
  129. $organism_id = $form_state['values']['organism_id'];
  130. $add_only = $form_state['values']['add_only'];
  131. $update = $form_state['values']['update'];
  132. $refresh = $form_state['values']['refresh'];
  133. $remove = $form_state['values']['remove'];
  134. // check to see if the file is located local to Drupal
  135. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  136. if(!file_exists($dfile)){
  137. // if not local to Drupal, the file must be someplace else, just use
  138. // the full path provided
  139. $dfile = $gff_file;
  140. }
  141. if(!file_exists($dfile)){
  142. 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."));
  143. }
  144. if (($add_only and ($update or $refresh or $remove)) or
  145. ($update and ($add_only or $refresh or $remove)) or
  146. ($refresh and ($update or $add_only or $remove)) or
  147. ($remove and ($update or $refresh or $add_only))){
  148. form_set_error('add_only',t("Please select only one checkbox from the import options section"));
  149. }
  150. }
  151. /**
  152. *
  153. * @ingroup gff3_loader
  154. */
  155. function tripal_feature_gff3_load_form_submit ($form, &$form_state){
  156. global $user;
  157. $gff_file = $form_state['values']['gff_file'];
  158. $organism_id = $form_state['values']['organism_id'];
  159. $add_only = $form_state['values']['add_only'];
  160. $update = $form_state['values']['update'];
  161. $refresh = $form_state['values']['refresh'];
  162. $remove = $form_state['values']['remove'];
  163. $analysis_id = $form_state['values']['analysis_id'];
  164. $args = array($gff_file,$organism_id,$analysis_id,$add_only,$update,$refresh,$remove);
  165. $type = '';
  166. if($add_only){
  167. $type = 'import only new features';
  168. }
  169. if($update){
  170. $type = 'import all and update';
  171. }
  172. if($refresh){
  173. $type = 'import all and replace';
  174. }
  175. if($remove){
  176. $type = 'delete features';
  177. }
  178. tripal_add_job("$type GFF3 file $gff_file",'tripal_feature',
  179. 'tripal_feature_load_gff3',$args,$user->uid);
  180. return '';
  181. }
  182. /**
  183. *
  184. *
  185. * @ingroup gff3_loader
  186. */
  187. function tripal_feature_load_gff3($gff_file, $organism_id,$analysis_id,$add_only =0,
  188. $update = 0, $refresh = 0, $remove = 0, $job = NULL)
  189. {
  190. // this array is used to cache all of the features in the GFF file and
  191. // used to lookup parent and target relationships
  192. $gff_features = array();
  193. // check to see if the file is located local to Drupal
  194. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  195. if(!file_exists($dfile)){
  196. // if not local to Drupal, the file must be someplace else, just use
  197. // the full path provided
  198. $dfile = $gff_file;
  199. }
  200. if(!file_exists($dfile)){
  201. print "ERROR: cannot find the file: $dfile\n";
  202. return 0;
  203. }
  204. $previous_db = tripal_db_set_active('chado');
  205. print "Opening $gff_file\n";
  206. $lines = file($dfile,FILE_SKIP_EMPTY_LINES);
  207. $i = 0;
  208. // get the controlled vocaubulary that we'll be using. The
  209. // default is the 'sequence' ontology
  210. $sql = "SELECT * FROM cv WHERE name = '%s'";
  211. $cv = db_fetch_object(db_query($sql,'sequence'));
  212. if(!$cv){
  213. print "ERROR: cannot find the 'sequence' ontology\n";
  214. return '';
  215. }
  216. // get the organism for which this GFF3 file belongs
  217. $sql = "SELECT * FROM organism WHERE organism_id = %d";
  218. $organism = db_fetch_object(db_query($sql,$organism_id));
  219. $num_lines = sizeof($lines);
  220. $interval = intval($num_lines * 0.01);
  221. if($interval == 0){
  222. $interval = $num_lines;
  223. }
  224. $in_fasta = 0;
  225. foreach ($lines as $line_num => $line) {
  226. $i++; // update the line count
  227. // update the job status every 1% features
  228. if($job and $i % $interval == 0){
  229. tripal_job_set_progress($job,intval(($i/$num_lines)*100));
  230. }
  231. // check to see if we have FASTA section, if so then set the variable
  232. // to start parsing
  233. if(preg_match('/^##FASTA/i',$line)){
  234. $in_fasta = 1;
  235. break;
  236. }
  237. // skip comments
  238. if(preg_match('/^#/',$line)){
  239. continue;
  240. }
  241. // skip empty lines
  242. if(preg_match('/^\s*$/',$line)){
  243. continue;
  244. }
  245. // handle FASTA section
  246. // TODO: handle URL encoding
  247. // remove URL encoding and get the columns
  248. $cols = explode("\t",$line);
  249. if(sizeof($cols) != 9){
  250. print "ERROR: improper number of columns on line $i\n";
  251. print_r($cols);
  252. return '';
  253. }
  254. // get the column values
  255. $landmark = $cols[0];
  256. $source = $cols[1];
  257. $type = $cols[2];
  258. $start = $cols[3];
  259. $end = $cols[4];
  260. $score = $cols[5];
  261. $strand = $cols[6];
  262. $phase = $cols[7];
  263. $attrs = explode(";",$cols[8]); // split by a semi-colon
  264. // ready the start and stop for chado. Chado expects these positions
  265. // to be zero-based, so we substract 1 from the fmin
  266. $fmin = $start - 1;
  267. $fmax = $end;
  268. if($end < $start){
  269. $fmin = $end - 1;
  270. $fmax = $start;
  271. }
  272. // format the strand for chado
  273. if(strcmp($strand,'.')==0){
  274. $strand = 0;
  275. }
  276. elseif(strcmp($strand,'+')==0){
  277. $strand = 1;
  278. }
  279. elseif(strcmp($strand,'-')==0){
  280. $strand = -1;
  281. }
  282. if(strcmp($phase,'.')==0){
  283. $phase = '';
  284. }
  285. // get the type record
  286. $cvtermsql = "SELECT CVT.cvterm_id, CVT.cv_id, CVT.name, CVT.definition,
  287. CVT.dbxref_id, CVT.is_obsolete, CVT.is_relationshiptype
  288. FROM {cvterm} CVT
  289. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  290. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  291. WHERE CV.cv_id = %d and (CVT.name = '%s' or CVTS.synonym = '%s')";
  292. $cvterm = db_fetch_object(db_query($cvtermsql,$cv->cv_id,$type,$type));
  293. if(!$cvterm){
  294. print "ERROR: cannot find ontology term '$type' on line $i.\n";
  295. return '';
  296. }
  297. // break apart each of the attributes
  298. $tags = array();
  299. $attr_name = '';
  300. $attr_uniquename = '';
  301. $attr_residue_info = '';
  302. $attr_locgroup = 0;
  303. $attr_fmin_partial = 'f';
  304. $attr_fmax_partial = 'f';
  305. $attr_is_obsolete = 'f';
  306. $attr_is_analysis = 'f';
  307. $attr_others = '';
  308. $residues = '';
  309. foreach($attrs as $attr){
  310. $attr = rtrim($attr);
  311. $attr = ltrim($attr);
  312. if(strcmp($attr,'')==0){
  313. continue;
  314. }
  315. if(!preg_match('/^[^\=]+\=[^\=]+$/',$attr)){
  316. print "ERROR: attribute is not correctly formatted on line $i: $attr\n";
  317. return '';
  318. }
  319. // break apart each tag
  320. $tag = explode("=",$attr); // split by equals sign
  321. // multiple instances of an attribute are separated by commas
  322. $tags[$tag[0]] = explode(",",$tag[1]); // split by comma
  323. if(strcmp($tag[0],'ID')==0){
  324. $attr_uniquename = $tag[1];
  325. }
  326. elseif(strcmp($tag[0],'Name')==0){
  327. $attr_name = $tag[1];
  328. }
  329. // get the list of other attributes other than those reserved ones.
  330. elseif(strcmp($tag[0],'Alias')!=0 and strcmp($tag[0],'Parent')!=0 and
  331. strcmp($tag[0],'Target')!=0 and strcmp($tag[0],'Gap')!=0 and
  332. strcmp($tag[0],'Derives_from')!=0 and strcmp($tag[0],'Note')!=0 and
  333. strcmp($tag[0],'Dbxref')!=0 and strcmp($tag[0],'Ontology_term')!=0 and
  334. strcmp($tag[0],'Is_circular')!=0){
  335. $attr_others[$tag[0]] = $tag[1];
  336. }
  337. }
  338. // if neither name nor uniquename are provided then generate one
  339. if(!$attr_uniquename and !$attr_name){
  340. if(array_key_exists('Parent',$tags)){
  341. $attr_uniquename = $tags['Parent'][0]."-$type-$landmark:$fmin..$fmax";
  342. } else {
  343. print "ERROR: cannot generate a uniquename for feature on line $i\n";
  344. exit;
  345. }
  346. $attr_name = $attr_uniquename;
  347. }
  348. // if a name is not specified then use the unique name
  349. if(strcmp($attr_name,'')==0){
  350. $attr_name = $attr_uniquename;
  351. }
  352. // if an ID attribute is not specified then use the attribute name and
  353. // hope for the best
  354. if(!$attr_uniquename){
  355. $attr_uniquename = $attr_name;
  356. }
  357. // make sure the landmark sequence exists in the database. We don't
  358. // know the type of the landmark so we'll hope that it's unique across
  359. // all types. If not we'll error out. This test is only necessary if
  360. // if the landmark and the uniquename are different. If they are the same
  361. // then this is the information for the landmark
  362. if(strcmp($landmark,$attr_uniquename)!=0){
  363. $feature_sql = "SELECT count(*) as num_landmarks
  364. FROM {feature}
  365. WHERE organism_id = %d and uniquename = '%s'";
  366. $count = db_fetch_object(db_query($feature_sql,$organism_id,$landmark));
  367. if(!$count or $count->num_landmarks == 0){
  368. print "ERROR: the landmark '$landmark' cannot be found for this organism. ".
  369. "Please add the landmark and then retry the import of this GFF3 ".
  370. "file.\n";
  371. return '';
  372. }
  373. if($count->num_landmarks > 1){
  374. print "ERROR: the landmark '$landmark' is not unique for this organism. ".
  375. "The features cannot be associated.\n";
  376. return '';
  377. }
  378. }
  379. // if the option is to remove or refresh then we want to remove
  380. // the feature from the database.
  381. if($remove or $refresh){
  382. print "Removing feature '$attr_uniquename'\n";
  383. $sql = "DELETE FROM {feature}
  384. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  385. $result = db_query($sql,$organism->organism_id,$attr_uniquename,$cvterm->cvterm_id);
  386. if(!$result){
  387. print "ERROR: cannot delete feature $attr_uniquename\n";
  388. }
  389. $feature = 0;
  390. }
  391. // add or update the feature and all properties
  392. if($update or $refresh or $add_only){
  393. // add/update the feature
  394. print "$i ";
  395. $feature = tripal_feature_load_gff3_feature($organism,$analysis_id,$cvterm,
  396. $attr_uniquename,$attr_name,$residues,$attr_is_analysis,
  397. $attr_is_obsolete, $add_only);
  398. // store all of the features for use later by parent and target
  399. // relationships
  400. $gff_features[$feature->uniquename]['type'] = $type;
  401. $gff_features[$feature->uniquename]['strand'] = $strand;
  402. if($feature){
  403. // add/update the featureloc if the landmark and the ID are not the same
  404. // if they are the same then this entry in the GFF is probably a landmark identifier
  405. if(strcmp($landmark,$attr_uniquename)!=0){
  406. tripal_feature_load_gff3_featureloc($feature,$organism,
  407. $landmark,$fmin,$fmax,$strand,$phase,$attr_fmin_partial,
  408. $attr_fmax_partial,$attr_residue_info,$attr_locgroup);
  409. }
  410. // add any aliases for this feature
  411. if(array_key_exists('Alias',$tags)){
  412. tripal_feature_load_gff3_alias($feature,$tags['Alias']);
  413. }
  414. // add any aliases for this feature
  415. if(array_key_exists('Dbxref',$tags)){
  416. tripal_feature_load_gff3_dbxref($feature,$tags['Dbxref']);
  417. }
  418. // add any aliases for this feature
  419. if(array_key_exists('Ontology_term',$tags)){
  420. tripal_feature_load_gff3_ontology($feature,$tags['Ontology_term']);
  421. }
  422. // add parent relationships
  423. if(array_key_exists('Parent',$tags)){
  424. tripal_feature_load_gff3_parents($feature,$cvterm,$tags['Parent'],$gff_features,$organism_id,$fmin);
  425. }
  426. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  427. $source_ref = array('GFF_source:'.$source);
  428. tripal_feature_load_gff3_dbxref($feature,$source_ref);
  429. // add any additional attributes
  430. if($attr_others){
  431. foreach($attr_others as $property => $value){
  432. print " Setting feature property: $property -> $value\n";
  433. tripal_feature_load_gff3_property($feature,$property,$value);
  434. }
  435. }
  436. }
  437. }
  438. }
  439. // now set the rank of any parent/child relationships. The order is based
  440. // on the fmin. The start rank is 1. This allows features with other
  441. // relationships to be '0' (the default), and doesn't interfer with the
  442. // ordering defined here.
  443. foreach($gff_features as $parent => $details){
  444. // only iterate through parents that have children
  445. if($details['children']){
  446. // get the parent
  447. $values = array(
  448. 'uniquename' => $parent,
  449. 'type_id' => array(
  450. 'cv_id' => array(
  451. 'name' => 'sequence'
  452. ),
  453. 'name' => $details['type'],
  454. ),
  455. 'organism_id' => $organism->organism_id,
  456. );
  457. $pfeature = tripal_core_chado_select('feature',array('*'),$values);
  458. // sort the children by order of their fmin positions (values of assoc. array)
  459. // if the parent is on the reverse strand then sort in reverse
  460. if($details['strand'] == -1){
  461. arsort($details['children']);
  462. } else {
  463. asort($details['children']);
  464. }
  465. // now iterate through the children and set their rank
  466. $rank = 1;
  467. print "Updating child ranks for $parent (".$details['type'].")\n";
  468. foreach($details['children'] as $kfeature_id => $kfmin){
  469. $match = array(
  470. 'object_id' => $pfeature[0]->feature_id,
  471. 'subject_id' => $kfeature_id,
  472. 'type_id' => array(
  473. 'cv_id' => array(
  474. 'name' => 'relationship'
  475. ),
  476. 'name' => 'part_of',
  477. ),
  478. );
  479. $values = array(
  480. 'rank' => $rank,
  481. );
  482. tripal_core_chado_update('feature_relationship',$match,$values);
  483. $rank++;
  484. }
  485. }
  486. }
  487. tripal_db_set_active($previous_db);
  488. return '';
  489. }
  490. /**
  491. *
  492. *
  493. * @ingroup gff3_loader
  494. */
  495. function tripal_feature_load_gff3_parents($feature,$cvterm,$parents,&$gff_features,$organism_id,$fmin){
  496. $uname = $feature->uniquename;
  497. $type = $cvterm->name;
  498. $rel_type = 'part_of';
  499. // create these SQL statements that will be used repeatedly below.
  500. $cvtermsql = "SELECT CVT.cvterm_id
  501. FROM {cvterm} CVT
  502. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  503. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  504. WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
  505. $feature_sql = "SELECT * FROM {feature}
  506. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  507. // iterate through the parents in the list
  508. foreach($parents as $parent){
  509. $parent_type = $gff_features[$parent]['type'];
  510. // try to find the parent
  511. $parentcvterm = db_fetch_object(db_query($cvtermsql,'sequence',$parent_type,$parent_type));
  512. $relcvterm = db_fetch_object(db_query($cvtermsql,'relationship',$rel_type,$rel_type));
  513. $parent_feature = db_fetch_object(db_query($feature_sql,$organism_id,$parent,$parentcvterm->cvterm_id));
  514. // we want to add this feature to the child list for the parent
  515. // when the loader finishes, it will go back through the parent
  516. // features and rank the children by position
  517. $gff_features[$parent]['children'][$feature->feature_id] = $fmin;
  518. // if the parent exists then add the relationship otherwise print error and skip
  519. if($parent_feature){
  520. // check to see if the relationship already exists
  521. $sql = "SELECT * FROM {feature_relationship} WHERE subject_id = %d and object_id = %d and type_id = %d";
  522. $rel = db_fetch_object(db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id));
  523. if($rel){
  524. print " Relationship already exists, skipping '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  525. } else {
  526. // the relationship doesn't already exist, so add it.
  527. $sql = "INSERT INTO {feature_relationship} (subject_id,object_id,type_id)
  528. VALUES (%d,%d,%d)";
  529. $result = db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id);
  530. if(!$result){
  531. print "WARNING: failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  532. } else {
  533. print " Inserted relationship relationship: '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  534. }
  535. }
  536. }
  537. else {
  538. print "WARNING: cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent\n";
  539. }
  540. }
  541. }
  542. /**
  543. *
  544. *
  545. * @ingroup gff3_loader
  546. */
  547. function tripal_feature_load_gff3_dbxref($feature,$dbxrefs){
  548. // iterate through each of the dbxrefs
  549. foreach($dbxrefs as $dbxref){
  550. // get the database name from the reference. If it doesn't exist then create one.
  551. $ref = explode(":",$dbxref);
  552. $dbname = $ref[0];
  553. $accession = $ref[1];
  554. // first look for the database name if it doesn't exist then create one.
  555. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  556. // can't be found then look for the name as is. If it still can't be found
  557. // the create the database
  558. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "DB:$dbname"));
  559. if(sizeof($db) == 0){
  560. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  561. }
  562. if(sizeof($db) == 0){
  563. $ret = tripal_core_chado_insert('db',array('name' => $dbname,
  564. 'description' => 'Added automatically by the GFF loader'));
  565. if($ret){
  566. print " Added new database: $dbname\n";
  567. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  568. } else {
  569. print "ERROR: cannot find or add the database $dbname\n";
  570. return 0;
  571. }
  572. }
  573. $db = $db[0];
  574. // now check to see if the accession exists
  575. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  576. 'accession' => $accession,'db_id' => $db->db_id));
  577. // if the accession doesn't exist then we want to add it
  578. if(sizeof($dbxref) == 0){
  579. $ret = tripal_core_chado_insert('dbxref',array('db_id' => $db->db_id,
  580. 'accession' => $accession,'version' => ''));
  581. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  582. 'accession' => $accession,'db_id' => $db->db_id));
  583. }
  584. $dbxref = $dbxref[0];
  585. // check to see if this feature dbxref already exists
  586. $fdbx = tripal_core_chado_select('feature_dbxref',array('feature_dbxref_id'),
  587. array('dbxref_id' => $dbxref->dbxref_id,'feature_id' => $feature->feature_id));
  588. // now associate this feature with the database reference if it doesn't
  589. // already exist
  590. if(sizeof($fdbx)==0){
  591. $ret = tripal_core_chado_insert('feature_dbxref',array(
  592. 'feature_id' => $feature->feature_id,
  593. 'dbxref_id' => $dbxref->dbxref_id));
  594. if($ret){
  595. print " Adding Dbxref $dbname:$accession\n";
  596. } else {
  597. print "ERROR: failed to insert Dbxref: $dbname:$accession\n";
  598. return 0;
  599. }
  600. } else {
  601. print " Dbxref already associated, skipping $dbname:$accession\n";
  602. }
  603. }
  604. return 1;
  605. }
  606. /**
  607. *
  608. *
  609. * @ingroup gff3_loader
  610. */
  611. function tripal_feature_load_gff3_ontology($feature,$dbxrefs){
  612. // iterate through each of the dbxrefs
  613. foreach($dbxrefs as $dbxref){
  614. // get the database name from the reference. If it doesn't exist then create one.
  615. $ref = explode(":",$dbxref);
  616. $dbname = $ref[0];
  617. $accession = $ref[1];
  618. // first look for the database name
  619. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "DB:$dbname"));
  620. if(sizeof($db) == 0){
  621. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  622. }
  623. if(sizeof($db) == 0){
  624. print "ERROR: Database, $dbname is missing for reference: $dbname:$accession\n";
  625. return 0;
  626. }
  627. $db = $db[0];
  628. // now check to see if the accession exists
  629. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  630. 'accession' => $accession,'db_id' => $db->db_id));
  631. if(sizeof($dbxref) == 0){
  632. print "ERROR: Accession, $accession is missing for reference: $dbname:$accession\n";
  633. return 0;
  634. }
  635. $dbxref = $dbxref[0];
  636. // now check to see if the cvterm exists
  637. $cvterm = tripal_core_chado_select('cvterm',array('cvterm_id'),array(
  638. 'dbxref_id' => $dbxref->dbxref_id));
  639. // if it doesn't exist in the cvterm table, look for an alternate id
  640. if(sizeof($cvterm) == 0){
  641. $cvterm = tripal_core_chado_select('cvterm_dbxref',array('cvterm_id'),array(
  642. 'dbxref_id' => $dbxref->dbxref_id));
  643. }
  644. if(sizeof($cvterm) == 0){
  645. print "ERROR: CVTerm is missing for reference: $dbname:$accession\n";
  646. return 0;
  647. }
  648. $cvterm = $cvterm[0];
  649. // check to see if this feature cvterm already exists
  650. $fcvt = tripal_core_chado_select('feature_cvterm',array('feature_cvterm_id'),
  651. array('cvterm_id' => $cvterm->cvterm_id,'feature_id' => $feature->feature_id));
  652. // now associate this feature with the cvterm if it doesn't already exist
  653. if(sizeof($fcvt)==0){
  654. $values = array(
  655. 'feature_id' => $feature->feature_id,
  656. 'cvterm_id' => $cvterm->cvterm_id,
  657. 'pub_id' => array(
  658. 'uniquename' => 'null',
  659. ),
  660. );
  661. $ret = tripal_core_chado_insert('feature_cvterm',$values);
  662. if($ret){
  663. print " Adding ontology term $dbname:$accession\n";
  664. } else {
  665. print "ERROR: failed to insert ontology term: $dbname:$accession\n";
  666. return 0;
  667. }
  668. } else {
  669. print " Ontology term already associated, skipping $dbname:$accession\n";
  670. }
  671. }
  672. return 1;
  673. }
  674. /**
  675. *
  676. *
  677. * @ingroup gff3_loader
  678. */
  679. function tripal_feature_load_gff3_alias($feature,$aliases){
  680. // make sure we have a 'synonym_type' vocabulary
  681. $sql = "SELECT * FROM {cv} WHERE name='synonym_type'";
  682. $syncv = db_fetch_object(db_query($sql));
  683. if(!$syncv){
  684. $sql = "INSERT INTO {cv} (name,definition) VALUES ('synonym_type','')";
  685. if(!db_query($sql)){
  686. print("ERROR: Failed to add the synonyms type vocabulary");
  687. return 0;
  688. }
  689. $syncv = db_fetch_object(db_query($sql));
  690. }
  691. // get the 'exact' cvterm, which is the type of synonym we're adding
  692. $cvtsql = "
  693. SELECT * FROM {cvterm} CVT
  694. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  695. WHERE CVT.name = '%s' and CV.name = '%s'
  696. ";
  697. $syntype = db_fetch_object(db_query($cvtsql,'exact','synonym_type'));
  698. if(!$syntype){
  699. $term = array(
  700. 'name' => array('exact'),
  701. 'id' => array("internal:exact"),
  702. 'definition' => array(''),
  703. 'is_obsolete' => array(0),
  704. );
  705. $syntype = tripal_cv_add_cvterm($term,$syncv,0,1);
  706. if(!$syntype){
  707. print("Cannot add synonym type: internal:$type");
  708. return 0;
  709. }
  710. }
  711. // iterate through all of the aliases and add each one
  712. foreach($aliases as $alias){
  713. print " Adding Alias $alias\n";
  714. // check to see if the alias already exists in the synonym table
  715. // if not, then add it
  716. $synsql = "SELECT * FROM {synonym}
  717. WHERE name = '%s' and type_id = %d";
  718. $synonym = db_fetch_object(db_query($synsql,$alias,$syntype->cvterm_id));
  719. if(!$synonym){
  720. $sql = "INSERT INTO {synonym}
  721. (name,type_id,synonym_sgml)
  722. VALUES ('%s',%d,'%s')";
  723. $result = db_query($sql,$alias,$syntype->cvterm_id,'');
  724. if(!$result){
  725. print "ERROR: cannot add alias $alias to synonym table\n";
  726. }
  727. }
  728. $synonym = db_fetch_object(db_query($synsql,$alias,$syntype->cvterm_id));
  729. // check to see if we have a NULL publication in the pub table. If not,
  730. // then add one.
  731. $pubsql = "SELECT * FROM {pub} WHERE uniquename = 'null'";
  732. $pub = db_fetch_object(db_query($pubsql));
  733. if(!$pub){
  734. $sql = "INSERT INTO pub (uniquename,type_id) VALUES ('%s',
  735. (SELECT cvterm_id
  736. FROM cvterm CVT
  737. INNER JOIN dbxref DBX on DBX.dbxref_id = CVT.dbxref_id
  738. INNER JOIN db DB on DB.db_id = DBX.db_id
  739. WHERE CVT.name = 'null' and DB.name = 'null')";
  740. $result = db_query($sql,'null');
  741. if(!$result){
  742. print "ERROR: cannot add null publication needed for setup of alias\n";
  743. return 0;
  744. }
  745. }
  746. $pub = db_fetch_object(db_query($pubsql));
  747. // check to see if the synonym exists in the feature_synonym table
  748. // if not, then add it.
  749. $synsql = "SELECT * FROM {feature_synonym}
  750. WHERE synonym_id = %d and feature_id = %d and pub_id = %d";
  751. $fsyn = db_fetch_object(db_query($synsql,$synonym->synonym_id,$feature->feature_id,$pub->pub_id));
  752. if(!$fsyn){
  753. $sql = "INSERT INTO {feature_synonym}
  754. (synonym_id,feature_id,pub_id)
  755. VALUES (%d,%d,%d)";
  756. $result = db_query($sql,$synonym->synonym_id,$feature->feature_id,$pub->pub_id);
  757. if(!$result){
  758. print "ERROR: cannot add alias $alias to feature synonym table\n";
  759. return 0;
  760. }
  761. } else {
  762. print " Synonym $alias already exists. Skipping\n";
  763. }
  764. }
  765. return 1;
  766. }
  767. /**
  768. *
  769. *
  770. * @ingroup gff3_loader
  771. */
  772. function tripal_feature_load_gff3_feature($organism,$analysis_id,$cvterm,$uniquename,$name,
  773. $residues,$is_analysis='f',$is_obsolete='f',$add_only) {
  774. // check to see if the feature already exists
  775. $feature_sql = "SELECT * FROM {feature}
  776. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  777. $feature = db_fetch_object(db_query($feature_sql,$organism->organism_id,$uniquename,$cvterm->cvterm_id));
  778. if(strcmp($is_obsolete,'f')==0){
  779. $is_obsolete = 'false';
  780. }
  781. if(strcmp($is_analysis,'f')==0){
  782. $is_analysis = 'false';
  783. }
  784. // insert the feature if it does not exist otherwise perform an update
  785. if(!$feature){
  786. print "Adding feature '$uniquename' ($cvterm->name)\n";
  787. $isql = "INSERT INTO {feature} (organism_id, name, uniquename, residues, seqlen,
  788. md5checksum, type_id,is_analysis,is_obsolete)
  789. VALUES(%d,'%s','%s','%s',%d, '%s', %d, %s, %s)";
  790. $result = db_query($isql,$organism->organism_id,$name,$uniquename,$residues,strlen($residues),
  791. md5($residues),$cvterm->cvterm_id,$is_analysis,$is_obsolete);
  792. if(!$result){
  793. print "ERROR: failed to insert feature '$uniquename' ($cvterm->name)\n";
  794. return 0;
  795. }
  796. }
  797. elseif(!$add_only) {
  798. print "Updating feature '$uniquename' ($cvterm->name)\n";
  799. $usql = "UPDATE {feature}
  800. SET name = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s',
  801. is_analysis = %s, is_obsolete = %s
  802. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  803. $result = db_query($usql,$name,$residues,strlen($residues),md5($residues),$is_analysis,$is_obsolete,
  804. $organism_id,$uniquename,$cvterm->cvterm_id);
  805. if(!$result){
  806. print "ERROR: failed to update feature '$uniquename' ($cvterm->name)\n";
  807. return 0;
  808. }
  809. }
  810. else {
  811. // the feature exists and we don't want to update it so return
  812. // a value of 0. This will stop all downstream property additions
  813. print "Skipping existing feature: '$uniquename' ($cvterm->name).\n";
  814. return 0;
  815. }
  816. // get the newly added feature
  817. $feature = db_fetch_object(db_query($feature_sql,$organism->organism_id,$uniquename,$cvterm->cvterm_id));
  818. // add the analysisfeature entry to the analysisfeature table if it doesn't already exist
  819. $af_values = array('analysis_id' => $analysis_id, 'feature_id' => $feature->feature_id);
  820. if(tripal_core_chado_select('analysisfeature',array('analysisfeature_id'),$af_values,array('has_record'))){
  821. if(!tripal_core_chado_insert('analysisfeature',$af_values)){
  822. print "ERROR: could not add analysisfeature record: $analysis_id, $feature->feature_id\n";
  823. } else {
  824. print " Added analysisfeature record\n";
  825. }
  826. }
  827. return $feature;
  828. }
  829. /**
  830. *
  831. *
  832. * @ingroup gff3_loader
  833. */
  834. function tripal_feature_load_gff3_featureloc($feature,$organism,$landmark,$fmin,
  835. $fmax,$strand,$phase,$is_fmin_partial,$is_fmax_partial,$residue_info,$locgroup)
  836. {
  837. // get the source feature
  838. $sql = "SELECT * FROM {feature}
  839. WHERE organism_id = %d and uniquename = '%s'";
  840. $srcfeature = db_fetch_object(db_query($sql,$organism->organism_id,$landmark));
  841. if(!$srcfeature){
  842. print "ERROR: cannot find landmark feature $landmark. Cannot add the feature location record\n";
  843. return 0;
  844. }
  845. // TODO: create an attribute that recognizes the residue_info,locgroup, is_fmin_partial and is_fmax_partial, right now these are
  846. // hardcoded to be false and 0 below.
  847. // check to see if this featureloc already exists, but also keep track of the
  848. // last rank value
  849. $rank = -1;
  850. $exists = 0;
  851. $featureloc_sql = "SELECT FL.featureloc_id,FL.fmin,FL.fmax,F.uniquename as srcname
  852. FROM {featureloc} FL
  853. INNER JOIN {feature} F on F.feature_id = FL.srcfeature_id
  854. WHERE FL.feature_id = %d
  855. ORDER BY rank ASC";
  856. $recs = db_query($featureloc_sql,$feature->feature_id);
  857. while ($featureloc = db_fetch_object($recs)){
  858. if(strcmp($featureloc->srcname,$landmark)==0 and
  859. $featureloc->fmin == $fmin and $featureloc->fmax == $fmax){
  860. // this is the same featureloc, so do nothing... no need to update
  861. //TODO: need more checks here
  862. print " No change to featureloc\n";
  863. $exists = 1;
  864. }
  865. $rank = $featureloc->rank;
  866. }
  867. if(!$exists){
  868. $rank++;
  869. // this feature location is new so add it
  870. if(!$phase){
  871. $phase = 'NULL';
  872. }
  873. if(strcmp($is_fmin_partial,'f')==0){
  874. $is_fmin_partial = 'false';
  875. }
  876. elseif(strcmp($is_fmin_partial,'t')==0){
  877. $is_fmin_partial = 'true';
  878. }
  879. if(strcmp($is_fmax_partial,'f')==0){
  880. $is_fmax_partial = 'false';
  881. }
  882. elseif(strcmp($is_fmax_partial,'t')==0){
  883. $is_fmax_partial = 'true';
  884. }
  885. print " Adding featureloc $srcfeature->uniquename fmin: $fmin, fmax: $fmax, strand: $strand, phase: $phase, rank: $rank\n";
  886. $fl_isql = "INSERT INTO {featureloc}
  887. (feature_id, srcfeature_id, fmin, is_fmin_partial, fmax, is_fmax_partial,
  888. strand, phase, residue_info, locgroup, rank)
  889. VALUES (%d,%d,%d,%s,%d,%s,%d,%s,'%s',%d,%d)";
  890. $result = db_query($fl_isql,$feature->feature_id,$srcfeature->feature_id,$fmin,$is_fmin_partial,$fmax,$is_fmax_partial,
  891. $strand,$phase,$residue_info,$locgroup,$rank);
  892. if(!$result){
  893. print "ERROR: failed to insert featureloc\n";
  894. exit;
  895. return 0;
  896. }
  897. }
  898. return 1;
  899. }
  900. /**
  901. *
  902. *
  903. * @ingroup gff3_loader
  904. */
  905. function tripal_feature_load_gff3_property($feature,$property,$value){
  906. // first make sure the cvterm exists. If the term already exists then
  907. // the function should return it
  908. $match = array(
  909. 'name' => $property,
  910. 'cv_id' => array(
  911. 'name' => 'feature_property',
  912. ),
  913. );
  914. $cvterm = tripal_core_chado_select('cvterm',array('*'),$match);
  915. if(sizeof($cvterm) == 0){
  916. $term = array(
  917. 'id' => "null:$property",
  918. 'name' => $property,
  919. 'namespace' => 'feature_property',
  920. 'is_obsolete' => 0,
  921. );
  922. print " Adding cvterm, $property\n";
  923. $cvterm = tripal_cv_add_cvterm($term,'feature_property',0,0);
  924. }
  925. if(!$cvterm){
  926. print "ERROR: cannot add cvterm, $property, before adding property\n";
  927. exit;
  928. }
  929. // next give the feature the property
  930. tripal_core_insert_property('feature',$feature->feature_id,$property,'feature_property',$value,1);
  931. }