gff_loader.php 36 KB

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