gff_loader.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. $fh = fopen($dfile,'r');
  208. if(!$fh){
  209. print "ERROR: cannot open file: $dfile\n";
  210. return 0;
  211. }
  212. $filesize = filesize($dfile);
  213. // get the controlled vocaubulary that we'll be using. The
  214. // default is the 'sequence' ontology
  215. $sql = "SELECT * FROM cv WHERE name = '%s'";
  216. $cv = db_fetch_object(db_query($sql,'sequence'));
  217. if(!$cv){
  218. print "ERROR: cannot find the 'sequence' ontology\n";
  219. return '';
  220. }
  221. // get the organism for which this GFF3 file belongs
  222. $sql = "SELECT * FROM organism WHERE organism_id = %d";
  223. $organism = db_fetch_object(db_query($sql,$organism_id));
  224. $interval = intval($filesize * 0.01);
  225. if($interval == 0){
  226. $interval = 1;
  227. }
  228. $in_fasta = 0;
  229. // foreach ($lines as $line_num => $line) {
  230. $line_num = 0;
  231. $num_read = 0;
  232. while($line = fgets($fh)){
  233. $line_num++;
  234. $num_read += strlen($line);
  235. // update the job status every 1% features
  236. if($job and $num_read % $interval == 0){
  237. tripal_job_set_progress($job,intval(($num_read/$filesize)*100));
  238. }
  239. // check to see if we have FASTA section, if so then set the variable
  240. // to start parsing
  241. if(preg_match('/^##FASTA/i',$line)){
  242. $in_fasta = 1;
  243. break;
  244. }
  245. // skip comments
  246. if(preg_match('/^#/',$line)){
  247. continue;
  248. }
  249. // skip empty lines
  250. if(preg_match('/^\s*$/',$line)){
  251. continue;
  252. }
  253. // handle FASTA section
  254. // TODO: handle URL encoding
  255. // remove URL encoding and get the columns
  256. $cols = explode("\t",$line);
  257. if(sizeof($cols) != 9){
  258. print "ERROR: improper number of columns on line $line_num\n";
  259. print_r($cols);
  260. return '';
  261. }
  262. // get the column values
  263. $landmark = $cols[0];
  264. $source = $cols[1];
  265. $type = $cols[2];
  266. $start = $cols[3];
  267. $end = $cols[4];
  268. $score = $cols[5];
  269. $strand = $cols[6];
  270. $phase = $cols[7];
  271. $attrs = explode(";",$cols[8]); // split by a semi-colon
  272. // ready the start and stop for chado. Chado expects these positions
  273. // to be zero-based, so we substract 1 from the fmin
  274. $fmin = $start - 1;
  275. $fmax = $end;
  276. if($end < $start){
  277. $fmin = $end - 1;
  278. $fmax = $start;
  279. }
  280. // format the strand for chado
  281. if(strcmp($strand,'.')==0){
  282. $strand = 0;
  283. }
  284. elseif(strcmp($strand,'+')==0){
  285. $strand = 1;
  286. }
  287. elseif(strcmp($strand,'-')==0){
  288. $strand = -1;
  289. }
  290. if(strcmp($phase,'.')==0){
  291. $phase = '';
  292. }
  293. // get the type record
  294. $cvtermsql = "SELECT CVT.cvterm_id, CVT.cv_id, CVT.name, CVT.definition,
  295. CVT.dbxref_id, CVT.is_obsolete, CVT.is_relationshiptype
  296. FROM {cvterm} CVT
  297. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  298. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  299. WHERE CV.cv_id = %d and (CVT.name = '%s' or CVTS.synonym = '%s')";
  300. $cvterm = db_fetch_object(db_query($cvtermsql,$cv->cv_id,$type,$type));
  301. if(!$cvterm){
  302. print "ERROR: cannot find ontology term '$type' on line $line_num.\n";
  303. return '';
  304. }
  305. // break apart each of the attributes
  306. $tags = array();
  307. $attr_name = '';
  308. $attr_uniquename = '';
  309. $attr_residue_info = '';
  310. $attr_locgroup = 0;
  311. $attr_fmin_partial = 'f';
  312. $attr_fmax_partial = 'f';
  313. $attr_is_obsolete = 'f';
  314. $attr_is_analysis = 'f';
  315. $attr_others = '';
  316. $residues = '';
  317. foreach($attrs as $attr){
  318. $attr = rtrim($attr);
  319. $attr = ltrim($attr);
  320. if(strcmp($attr,'')==0){
  321. continue;
  322. }
  323. if(!preg_match('/^[^\=]+\=[^\=]+$/',$attr)){
  324. print "ERROR: attribute is not correctly formatted on line $line_num: $attr\n";
  325. return '';
  326. }
  327. // break apart each tag
  328. $tag = explode("=",$attr); // split by equals sign
  329. // multiple instances of an attribute are separated by commas
  330. $tags[$tag[0]] = explode(",",$tag[1]); // split by comma
  331. if(strcmp($tag[0],'ID')==0){
  332. $attr_uniquename = $tag[1];
  333. }
  334. elseif(strcmp($tag[0],'Name')==0){
  335. $attr_name = $tag[1];
  336. }
  337. // get the list of other attributes other than those reserved ones.
  338. elseif(strcmp($tag[0],'Alias')!=0 and strcmp($tag[0],'Parent')!=0 and
  339. strcmp($tag[0],'Target')!=0 and strcmp($tag[0],'Gap')!=0 and
  340. strcmp($tag[0],'Derives_from')!=0 and strcmp($tag[0],'Note')!=0 and
  341. strcmp($tag[0],'Dbxref')!=0 and strcmp($tag[0],'Ontology_term')!=0 and
  342. strcmp($tag[0],'Is_circular')!=0){
  343. $attr_others[$tag[0]] = $tag[1];
  344. }
  345. }
  346. // if neither name nor uniquename are provided then generate one
  347. if(!$attr_uniquename and !$attr_name){
  348. if(array_key_exists('Parent',$tags)){
  349. $attr_uniquename = $tags['Parent'][0]."-$type-$landmark:$fmin..$fmax";
  350. } else {
  351. print "ERROR: cannot generate a uniquename for feature on line $line_num\n";
  352. exit;
  353. }
  354. $attr_name = $attr_uniquename;
  355. }
  356. // if a name is not specified then use the unique name
  357. if(strcmp($attr_name,'')==0){
  358. $attr_name = $attr_uniquename;
  359. }
  360. // if an ID attribute is not specified then use the attribute name and
  361. // hope for the best
  362. if(!$attr_uniquename){
  363. $attr_uniquename = $attr_name;
  364. }
  365. // make sure the landmark sequence exists in the database. We don't
  366. // know the type of the landmark so we'll hope that it's unique across
  367. // all types. If not we'll error out. This test is only necessary if
  368. // if the landmark and the uniquename are different. If they are the same
  369. // then this is the information for the landmark
  370. if(strcmp($landmark,$attr_uniquename)!=0){
  371. $feature_sql = "SELECT count(*) as num_landmarks
  372. FROM {feature}
  373. WHERE organism_id = %d and uniquename = '%s'";
  374. $count = db_fetch_object(db_query($feature_sql,$organism_id,$landmark));
  375. if(!$count or $count->num_landmarks == 0){
  376. print "ERROR: the landmark '$landmark' cannot be found for this organism. ".
  377. "Please add the landmark and then retry the import of this GFF3 ".
  378. "file.\n";
  379. return '';
  380. }
  381. if($count->num_landmarks > 1){
  382. print "ERROR: the landmark '$landmark' is not unique for this organism. ".
  383. "The features cannot be associated.\n";
  384. return '';
  385. }
  386. }
  387. // if the option is to remove or refresh then we want to remove
  388. // the feature from the database.
  389. if($remove or $refresh){
  390. print "Removing feature '$attr_uniquename'\n";
  391. $sql = "DELETE FROM {feature}
  392. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  393. $result = db_query($sql,$organism->organism_id,$attr_uniquename,$cvterm->cvterm_id);
  394. if(!$result){
  395. print "ERROR: cannot delete feature $attr_uniquename\n";
  396. }
  397. $feature = 0;
  398. }
  399. // add or update the feature and all properties
  400. if($update or $refresh or $add_only){
  401. // add/update the feature
  402. print "line $line_num, ". intval(($num_read/$filesize)*100). "%. ";
  403. $feature = tripal_feature_load_gff3_feature($organism,$analysis_id,$cvterm,
  404. $attr_uniquename,$attr_name,$residues,$attr_is_analysis,
  405. $attr_is_obsolete, $add_only,$score);
  406. // store all of the features for use later by parent and target
  407. // relationships
  408. $gff_features[$feature->uniquename]['type'] = $type;
  409. $gff_features[$feature->uniquename]['strand'] = $strand;
  410. if($feature){
  411. // add/update the featureloc if the landmark and the ID are not the same
  412. // if they are the same then this entry in the GFF is probably a landmark identifier
  413. if(strcmp($landmark,$attr_uniquename)!=0){
  414. tripal_feature_load_gff3_featureloc($feature,$organism,
  415. $landmark,$fmin,$fmax,$strand,$phase,$attr_fmin_partial,
  416. $attr_fmax_partial,$attr_residue_info,$attr_locgroup);
  417. }
  418. // add any aliases for this feature
  419. if(array_key_exists('Alias',$tags)){
  420. tripal_feature_load_gff3_alias($feature,$tags['Alias']);
  421. }
  422. // add any aliases for this feature
  423. if(array_key_exists('Dbxref',$tags)){
  424. tripal_feature_load_gff3_dbxref($feature,$tags['Dbxref']);
  425. }
  426. // add any aliases for this feature
  427. if(array_key_exists('Ontology_term',$tags)){
  428. tripal_feature_load_gff3_ontology($feature,$tags['Ontology_term']);
  429. }
  430. // add parent relationships
  431. if(array_key_exists('Parent',$tags)){
  432. tripal_feature_load_gff3_parents($feature,$cvterm,$tags['Parent'],$gff_features,$organism_id,$fmin);
  433. }
  434. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  435. $source_ref = array('GFF_source:'.$source);
  436. tripal_feature_load_gff3_dbxref($feature,$source_ref);
  437. // add any additional attributes
  438. if($attr_others){
  439. foreach($attr_others as $property => $value){
  440. tripal_feature_load_gff3_property($feature,$property,$value);
  441. }
  442. }
  443. }
  444. }
  445. }
  446. // now set the rank of any parent/child relationships. The order is based
  447. // on the fmin. The start rank is 1. This allows features with other
  448. // relationships to be '0' (the default), and doesn't interfer with the
  449. // ordering defined here.
  450. foreach($gff_features as $parent => $details){
  451. // only iterate through parents that have children
  452. if($details['children']){
  453. // get the parent
  454. $values = array(
  455. 'uniquename' => $parent,
  456. 'type_id' => array(
  457. 'cv_id' => array(
  458. 'name' => 'sequence'
  459. ),
  460. 'name' => $details['type'],
  461. ),
  462. 'organism_id' => $organism->organism_id,
  463. );
  464. $pfeature = tripal_core_chado_select('feature',array('*'),$values);
  465. // sort the children by order of their fmin positions (values of assoc. array)
  466. // if the parent is on the reverse strand then sort in reverse
  467. if($details['strand'] == -1){
  468. arsort($details['children']);
  469. } else {
  470. asort($details['children']);
  471. }
  472. // now iterate through the children and set their rank
  473. $rank = 1;
  474. print "Updating child ranks for $parent (".$details['type'].")\n";
  475. foreach($details['children'] as $kfeature_id => $kfmin){
  476. $match = array(
  477. 'object_id' => $pfeature[0]->feature_id,
  478. 'subject_id' => $kfeature_id,
  479. 'type_id' => array(
  480. 'cv_id' => array(
  481. 'name' => 'relationship'
  482. ),
  483. 'name' => 'part_of',
  484. ),
  485. );
  486. $values = array(
  487. 'rank' => $rank,
  488. );
  489. tripal_core_chado_update('feature_relationship',$match,$values);
  490. $rank++;
  491. }
  492. }
  493. }
  494. tripal_db_set_active($previous_db);
  495. return '';
  496. }
  497. /**
  498. *
  499. *
  500. * @ingroup gff3_loader
  501. */
  502. function tripal_feature_load_gff3_parents($feature,$cvterm,$parents,&$gff_features,$organism_id,$fmin){
  503. $uname = $feature->uniquename;
  504. $type = $cvterm->name;
  505. $rel_type = 'part_of';
  506. // create these SQL statements that will be used repeatedly below.
  507. $cvtermsql = "SELECT CVT.cvterm_id
  508. FROM {cvterm} CVT
  509. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  510. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  511. WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
  512. $feature_sql = "SELECT * FROM {feature}
  513. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  514. // iterate through the parents in the list
  515. foreach($parents as $parent){
  516. $parent_type = $gff_features[$parent]['type'];
  517. // try to find the parent
  518. $parentcvterm = db_fetch_object(db_query($cvtermsql,'sequence',$parent_type,$parent_type));
  519. $relcvterm = db_fetch_object(db_query($cvtermsql,'relationship',$rel_type,$rel_type));
  520. $parent_feature = db_fetch_object(db_query($feature_sql,$organism_id,$parent,$parentcvterm->cvterm_id));
  521. // we want to add this feature to the child list for the parent
  522. // when the loader finishes, it will go back through the parent
  523. // features and rank the children by position
  524. $gff_features[$parent]['children'][$feature->feature_id] = $fmin;
  525. // if the parent exists then add the relationship otherwise print error and skip
  526. if($parent_feature){
  527. // check to see if the relationship already exists
  528. $sql = "SELECT * FROM {feature_relationship} WHERE subject_id = %d and object_id = %d and type_id = %d";
  529. $rel = db_fetch_object(db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id));
  530. if($rel){
  531. print " Relationship already exists, skipping '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  532. } else {
  533. // the relationship doesn't already exist, so add it.
  534. $sql = "INSERT INTO {feature_relationship} (subject_id,object_id,type_id)
  535. VALUES (%d,%d,%d)";
  536. $result = db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id);
  537. if(!$result){
  538. print "WARNING: failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  539. } else {
  540. print " Inserted relationship relationship: '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
  541. }
  542. }
  543. }
  544. else {
  545. print "WARNING: cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent\n";
  546. }
  547. }
  548. }
  549. /**
  550. *
  551. *
  552. * @ingroup gff3_loader
  553. */
  554. function tripal_feature_load_gff3_dbxref($feature,$dbxrefs){
  555. // iterate through each of the dbxrefs
  556. foreach($dbxrefs as $dbxref){
  557. // get the database name from the reference. If it doesn't exist then create one.
  558. $ref = explode(":",$dbxref);
  559. $dbname = $ref[0];
  560. $accession = $ref[1];
  561. // first look for the database name if it doesn't exist then create one.
  562. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  563. // can't be found then look for the name as is. If it still can't be found
  564. // the create the database
  565. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "DB:$dbname"));
  566. if(sizeof($db) == 0){
  567. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  568. }
  569. if(sizeof($db) == 0){
  570. $ret = tripal_core_chado_insert('db',array('name' => $dbname,
  571. 'description' => 'Added automatically by the GFF loader'));
  572. if($ret){
  573. print " Added new database: $dbname\n";
  574. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  575. } else {
  576. print "ERROR: cannot find or add the database $dbname\n";
  577. return 0;
  578. }
  579. }
  580. $db = $db[0];
  581. // now check to see if the accession exists
  582. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  583. 'accession' => $accession,'db_id' => $db->db_id));
  584. // if the accession doesn't exist then we want to add it
  585. if(sizeof($dbxref) == 0){
  586. $ret = tripal_core_chado_insert('dbxref',array('db_id' => $db->db_id,
  587. 'accession' => $accession,'version' => ''));
  588. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  589. 'accession' => $accession,'db_id' => $db->db_id));
  590. }
  591. $dbxref = $dbxref[0];
  592. // check to see if this feature dbxref already exists
  593. $fdbx = tripal_core_chado_select('feature_dbxref',array('feature_dbxref_id'),
  594. array('dbxref_id' => $dbxref->dbxref_id,'feature_id' => $feature->feature_id));
  595. // now associate this feature with the database reference if it doesn't
  596. // already exist
  597. if(sizeof($fdbx)==0){
  598. $ret = tripal_core_chado_insert('feature_dbxref',array(
  599. 'feature_id' => $feature->feature_id,
  600. 'dbxref_id' => $dbxref->dbxref_id));
  601. if($ret){
  602. print " Adding Dbxref $dbname:$accession\n";
  603. } else {
  604. print "ERROR: failed to insert Dbxref: $dbname:$accession\n";
  605. return 0;
  606. }
  607. } else {
  608. print " Dbxref already associated, skipping $dbname:$accession\n";
  609. }
  610. }
  611. return 1;
  612. }
  613. /**
  614. *
  615. *
  616. * @ingroup gff3_loader
  617. */
  618. function tripal_feature_load_gff3_ontology($feature,$dbxrefs){
  619. // iterate through each of the dbxrefs
  620. foreach($dbxrefs as $dbxref){
  621. // get the database name from the reference. If it doesn't exist then create one.
  622. $ref = explode(":",$dbxref);
  623. $dbname = $ref[0];
  624. $accession = $ref[1];
  625. // first look for the database name
  626. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "DB:$dbname"));
  627. if(sizeof($db) == 0){
  628. $db = tripal_core_chado_select('db',array('db_id'),array('name' => "$dbname"));
  629. }
  630. if(sizeof($db) == 0){
  631. print "ERROR: Database, $dbname is missing for reference: $dbname:$accession\n";
  632. return 0;
  633. }
  634. $db = $db[0];
  635. // now check to see if the accession exists
  636. $dbxref = tripal_core_chado_select('dbxref',array('dbxref_id'),array(
  637. 'accession' => $accession,'db_id' => $db->db_id));
  638. if(sizeof($dbxref) == 0){
  639. print "ERROR: Accession, $accession is missing for reference: $dbname:$accession\n";
  640. return 0;
  641. }
  642. $dbxref = $dbxref[0];
  643. // now check to see if the cvterm exists
  644. $cvterm = tripal_core_chado_select('cvterm',array('cvterm_id'),array(
  645. 'dbxref_id' => $dbxref->dbxref_id));
  646. // if it doesn't exist in the cvterm table, look for an alternate id
  647. if(sizeof($cvterm) == 0){
  648. $cvterm = tripal_core_chado_select('cvterm_dbxref',array('cvterm_id'),array(
  649. 'dbxref_id' => $dbxref->dbxref_id));
  650. }
  651. if(sizeof($cvterm) == 0){
  652. print "ERROR: CVTerm is missing for reference: $dbname:$accession\n";
  653. return 0;
  654. }
  655. $cvterm = $cvterm[0];
  656. // check to see if this feature cvterm already exists
  657. $fcvt = tripal_core_chado_select('feature_cvterm',array('feature_cvterm_id'),
  658. array('cvterm_id' => $cvterm->cvterm_id,'feature_id' => $feature->feature_id));
  659. // now associate this feature with the cvterm if it doesn't already exist
  660. if(sizeof($fcvt)==0){
  661. $values = array(
  662. 'feature_id' => $feature->feature_id,
  663. 'cvterm_id' => $cvterm->cvterm_id,
  664. 'pub_id' => array(
  665. 'uniquename' => 'null',
  666. ),
  667. );
  668. $ret = tripal_core_chado_insert('feature_cvterm',$values);
  669. if($ret){
  670. print " Adding ontology term $dbname:$accession\n";
  671. } else {
  672. print "ERROR: failed to insert ontology term: $dbname:$accession\n";
  673. return 0;
  674. }
  675. } else {
  676. print " Ontology term already associated, skipping $dbname:$accession\n";
  677. }
  678. }
  679. return 1;
  680. }
  681. /**
  682. *
  683. *
  684. * @ingroup gff3_loader
  685. */
  686. function tripal_feature_load_gff3_alias($feature,$aliases){
  687. // make sure we have a 'synonym_type' vocabulary
  688. $sql = "SELECT * FROM {cv} WHERE name='synonym_type'";
  689. $syncv = db_fetch_object(db_query($sql));
  690. if(!$syncv){
  691. $sql = "INSERT INTO {cv} (name,definition) VALUES ('synonym_type','')";
  692. if(!db_query($sql)){
  693. print("ERROR: Failed to add the synonyms type vocabulary");
  694. return 0;
  695. }
  696. $syncv = db_fetch_object(db_query($sql));
  697. }
  698. // get the 'exact' cvterm, which is the type of synonym we're adding
  699. $cvtsql = "
  700. SELECT * FROM {cvterm} CVT
  701. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  702. WHERE CVT.name = '%s' and CV.name = '%s'
  703. ";
  704. $syntype = db_fetch_object(db_query($cvtsql,'exact','synonym_type'));
  705. if(!$syntype){
  706. $term = array(
  707. 'name' => array('exact'),
  708. 'id' => array("internal:exact"),
  709. 'definition' => array(''),
  710. 'is_obsolete' => array(0),
  711. );
  712. $syntype = tripal_cv_add_cvterm($term,$syncv,0,1);
  713. if(!$syntype){
  714. print("Cannot add synonym type: internal:$type");
  715. return 0;
  716. }
  717. }
  718. // iterate through all of the aliases and add each one
  719. foreach($aliases as $alias){
  720. print " Adding Alias $alias\n";
  721. // check to see if the alias already exists in the synonym table
  722. // if not, then add it
  723. $synsql = "SELECT * FROM {synonym}
  724. WHERE name = '%s' and type_id = %d";
  725. $synonym = db_fetch_object(db_query($synsql,$alias,$syntype->cvterm_id));
  726. if(!$synonym){
  727. $sql = "INSERT INTO {synonym}
  728. (name,type_id,synonym_sgml)
  729. VALUES ('%s',%d,'%s')";
  730. $result = db_query($sql,$alias,$syntype->cvterm_id,'');
  731. if(!$result){
  732. print "ERROR: cannot add alias $alias to synonym table\n";
  733. }
  734. }
  735. $synonym = db_fetch_object(db_query($synsql,$alias,$syntype->cvterm_id));
  736. // check to see if we have a NULL publication in the pub table. If not,
  737. // then add one.
  738. $pubsql = "SELECT * FROM {pub} WHERE uniquename = 'null'";
  739. $pub = db_fetch_object(db_query($pubsql));
  740. if(!$pub){
  741. $sql = "INSERT INTO pub (uniquename,type_id) VALUES ('%s',
  742. (SELECT cvterm_id
  743. FROM cvterm CVT
  744. INNER JOIN dbxref DBX on DBX.dbxref_id = CVT.dbxref_id
  745. INNER JOIN db DB on DB.db_id = DBX.db_id
  746. WHERE CVT.name = 'null' and DB.name = 'null')";
  747. $result = db_query($sql,'null');
  748. if(!$result){
  749. print "ERROR: cannot add null publication needed for setup of alias\n";
  750. return 0;
  751. }
  752. }
  753. $pub = db_fetch_object(db_query($pubsql));
  754. // check to see if the synonym exists in the feature_synonym table
  755. // if not, then add it.
  756. $synsql = "SELECT * FROM {feature_synonym}
  757. WHERE synonym_id = %d and feature_id = %d and pub_id = %d";
  758. $fsyn = db_fetch_object(db_query($synsql,$synonym->synonym_id,$feature->feature_id,$pub->pub_id));
  759. if(!$fsyn){
  760. $sql = "INSERT INTO {feature_synonym}
  761. (synonym_id,feature_id,pub_id)
  762. VALUES (%d,%d,%d)";
  763. $result = db_query($sql,$synonym->synonym_id,$feature->feature_id,$pub->pub_id);
  764. if(!$result){
  765. print "ERROR: cannot add alias $alias to feature synonym table\n";
  766. return 0;
  767. }
  768. } else {
  769. print " Synonym $alias already exists. Skipping\n";
  770. }
  771. }
  772. return 1;
  773. }
  774. /**
  775. *
  776. *
  777. * @ingroup gff3_loader
  778. */
  779. function tripal_feature_load_gff3_feature($organism,$analysis_id,$cvterm,$uniquename,$name,
  780. $residues,$is_analysis='f',$is_obsolete='f',$add_only,$score) {
  781. // check to see if the feature already exists
  782. $feature_sql = "SELECT * FROM {feature}
  783. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  784. $feature = db_fetch_object(db_query($feature_sql,$organism->organism_id,$uniquename,$cvterm->cvterm_id));
  785. if(strcmp($is_obsolete,'f')==0){
  786. $is_obsolete = 'false';
  787. }
  788. if(strcmp($is_analysis,'f')==0){
  789. $is_analysis = 'false';
  790. }
  791. // insert the feature if it does not exist otherwise perform an update
  792. if(!$feature){
  793. print "Adding feature '$uniquename' ($cvterm->name)\n";
  794. $isql = "INSERT INTO {feature} (organism_id, name, uniquename, residues, seqlen,
  795. md5checksum, type_id,is_analysis,is_obsolete)
  796. VALUES(%d,'%s','%s','%s',%d, '%s', %d, %s, %s)";
  797. $result = db_query($isql,$organism->organism_id,$name,$uniquename,$residues,strlen($residues),
  798. md5($residues),$cvterm->cvterm_id,$is_analysis,$is_obsolete);
  799. if(!$result){
  800. print "ERROR: failed to insert feature '$uniquename' ($cvterm->name)\n";
  801. return 0;
  802. }
  803. }
  804. elseif(!$add_only) {
  805. print "Updating feature '$uniquename' ($cvterm->name)\n";
  806. $usql = "UPDATE {feature}
  807. SET name = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s',
  808. is_analysis = %s, is_obsolete = %s
  809. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  810. $result = db_query($usql,$name,$residues,strlen($residues),md5($residues),$is_analysis,$is_obsolete,
  811. $organism_id,$uniquename,$cvterm->cvterm_id);
  812. if(!$result){
  813. print "ERROR: failed to update feature '$uniquename' ($cvterm->name)\n";
  814. return 0;
  815. }
  816. }
  817. else {
  818. // the feature exists and we don't want to update it so return
  819. // a value of 0. This will stop all downstream property additions
  820. print "Skipping existing feature: '$uniquename' ($cvterm->name).\n";
  821. return 0;
  822. }
  823. // get the newly added feature
  824. $feature = db_fetch_object(db_query($feature_sql,$organism->organism_id,$uniquename,$cvterm->cvterm_id));
  825. // add the analysisfeature entry to the analysisfeature table if it doesn't already exist
  826. $af_values = array(
  827. 'analysis_id' => $analysis_id,
  828. 'feature_id' => $feature->feature_id
  829. );
  830. $afeature = tripal_core_chado_select('analysisfeature',array('analysisfeature_id'),$af_values,array('has_record'));
  831. if(count($afeature)==0){
  832. // if a score is avaialble then set that to be the significance field
  833. if(strcmp($score,'.')!=0){
  834. $af_values['significance'] = $score;
  835. }
  836. if(!tripal_core_chado_insert('analysisfeature',$af_values)){
  837. print "ERROR: could not add analysisfeature record: $analysis_id, $feature->feature_id\n";
  838. } else {
  839. print " Added analysisfeature record\n";
  840. }
  841. } else {
  842. // if a score is avaialble then set that to be the significance field
  843. $new_vals = array();
  844. if(strcmp($score,'.')!=0){
  845. $new_vals['significance'] = $score;
  846. }
  847. if(!$add_only and !tripal_core_chado_update('analysisfeature',$af_values,$new_vals)){
  848. print "ERROR: could not update analysisfeature record: $analysis_id, $feature->feature_id\n";
  849. } else {
  850. print " Updated analysisfeature record\n";
  851. }
  852. }
  853. return $feature;
  854. }
  855. /**
  856. *
  857. *
  858. * @ingroup gff3_loader
  859. */
  860. function tripal_feature_load_gff3_featureloc($feature,$organism,$landmark,$fmin,
  861. $fmax,$strand,$phase,$is_fmin_partial,$is_fmax_partial,$residue_info,$locgroup)
  862. {
  863. // get the source feature
  864. $sql = "SELECT * FROM {feature}
  865. WHERE organism_id = %d and uniquename = '%s'";
  866. $srcfeature = db_fetch_object(db_query($sql,$organism->organism_id,$landmark));
  867. if(!$srcfeature){
  868. print "ERROR: cannot find landmark feature $landmark. Cannot add the feature location record\n";
  869. return 0;
  870. }
  871. // TODO: create an attribute that recognizes the residue_info,locgroup, is_fmin_partial and is_fmax_partial, right now these are
  872. // hardcoded to be false and 0 below.
  873. // check to see if this featureloc already exists, but also keep track of the
  874. // last rank value
  875. $rank = 0;
  876. $exists = 0;
  877. $featureloc_sql = "SELECT FL.featureloc_id,FL.fmin,FL.fmax,F.uniquename as srcname,
  878. rank
  879. FROM {featureloc} FL
  880. INNER JOIN {feature} F on F.feature_id = FL.srcfeature_id
  881. WHERE FL.feature_id = %d
  882. ORDER BY rank ASC";
  883. $recs = db_query($featureloc_sql,$feature->feature_id);
  884. while ($featureloc = db_fetch_object($recs)){
  885. if(strcmp($featureloc->srcname,$landmark)==0 and
  886. $featureloc->fmin == $fmin and $featureloc->fmax == $fmax){
  887. // this is the same featureloc, so do nothing... no need to update
  888. //TODO: need more checks here
  889. print " No change to featureloc\n";
  890. $exists = 1;
  891. }
  892. $rank = $featureloc->rank + 1;
  893. }
  894. if(!$exists){
  895. $rank++;
  896. // this feature location is new so add it
  897. if(!$phase){
  898. $phase = 'NULL';
  899. }
  900. if(strcmp($is_fmin_partial,'f')==0){
  901. $is_fmin_partial = 'false';
  902. }
  903. elseif(strcmp($is_fmin_partial,'t')==0){
  904. $is_fmin_partial = 'true';
  905. }
  906. if(strcmp($is_fmax_partial,'f')==0){
  907. $is_fmax_partial = 'false';
  908. }
  909. elseif(strcmp($is_fmax_partial,'t')==0){
  910. $is_fmax_partial = 'true';
  911. }
  912. print " Adding featureloc $srcfeature->uniquename fmin: $fmin, fmax: $fmax, strand: $strand, phase: $phase, rank: $rank\n";
  913. $fl_isql = "INSERT INTO {featureloc}
  914. (feature_id, srcfeature_id, fmin, is_fmin_partial, fmax, is_fmax_partial,
  915. strand, phase, residue_info, locgroup, rank)
  916. VALUES (%d,%d,%d,%s,%d,%s,%d,%s,'%s',%d,%d)";
  917. $result = db_query($fl_isql,$feature->feature_id,$srcfeature->feature_id,$fmin,$is_fmin_partial,$fmax,$is_fmax_partial,
  918. $strand,$phase,$residue_info,$locgroup,$rank);
  919. if(!$result){
  920. print "ERROR: failed to insert featureloc\n";
  921. exit;
  922. return 0;
  923. }
  924. }
  925. return 1;
  926. }
  927. /**
  928. *
  929. *
  930. * @ingroup gff3_loader
  931. */
  932. function tripal_feature_load_gff3_property($feature,$property,$value){
  933. // first make sure the cvterm exists. If the term already exists then
  934. // the function should return it of not, then add it
  935. $cvt_sql = "SELECT * FROM {cvterm} CVT
  936. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  937. WHERE CV.name = '%s' and CVT.name = '%s'";
  938. $cvterm = db_fetch_object(db_query($cvt_sql,'feature_property',$property));
  939. if(!$cvterm){
  940. $term = array(
  941. 'id' => "null:$property",
  942. 'name' => $property,
  943. 'namespace' => 'feature_property',
  944. 'is_obsolete' => 0,
  945. );
  946. print " Adding cvterm, $property\n";
  947. $cvterm = (object) tripal_cv_add_cvterm($term,'feature_property',0,0);
  948. }
  949. if(!$cvterm){
  950. print "ERROR: cannot add cvterm, $property\n";
  951. exit;
  952. }
  953. // check to see if the property already exists for this feature
  954. // if it does but the value is unique then increment the rank and add it.
  955. // if the value is not unique then don't add it.
  956. $add = 1;
  957. $rank = 0;
  958. $sql = "SELECT rank,value FROM {featureprop}
  959. WHERE feature_id = %d and type_id = %d
  960. ORDER BY rank ASC";
  961. $result = db_query($sql,$feature->feature_id,$cvterm->cvterm_id);
  962. while($prop = db_fetch_object($result)){
  963. if(strcmp($prop->value,$value)==0){
  964. $add = NULL; // don't add it, it already exists
  965. print " Property already exists, skipping\n";
  966. }
  967. $rank = $prop->rank + 1;
  968. }
  969. // add the property if we pass the check above
  970. if($add){
  971. print " Setting feature property. $property: $value\n";
  972. $isql = "INSERT INTO {featureprop} (feature_id,type_id,value,rank)
  973. VALUES (%d,%d,'%s',%d)";
  974. db_query($isql,$feature->feature_id,$cvterm->cvterm_id,$value,$rank);
  975. }
  976. }
  977. /*
  978. function tripal_feature_load_gff3_property($feature,$property,$value){
  979. // first make sure the cvterm exists. If the term already exists then
  980. // the function should return it
  981. $match = array(
  982. 'name' => $property,
  983. 'cv_id' => array(
  984. 'name' => 'feature_property',
  985. ),
  986. );
  987. $cvterm = tripal_core_chado_select('cvterm',array('*'),$match);
  988. if(sizeof($cvterm) == 0){
  989. $term = array(
  990. 'id' => "null:$property",
  991. 'name' => $property,
  992. 'namespace' => 'feature_property',
  993. 'is_obsolete' => 0,
  994. );
  995. print " Adding cvterm, $property\n";
  996. $cvterm = tripal_cv_add_cvterm($term,'feature_property',0,0);
  997. }
  998. if(!$cvterm){
  999. print "ERROR: cannot add cvterm, $property, before adding property\n";
  1000. exit;
  1001. }
  1002. // next give the feature the property
  1003. tripal_core_insert_property('feature',$feature->feature_id,$property,'feature_property',$value,1);
  1004. }
  1005. */