gff_loader.inc 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. <?php
  2. /**
  3. * @file
  4. * @todo Add file header description
  5. */
  6. /**
  7. * @defgroup gff3_loader GFF3 Feature Loader
  8. * @{
  9. * Provides gff3 loading functionality. Creates features based on their specification in a GFF3 file.
  10. * @}
  11. * @ingroup tripal_feature
  12. */
  13. /**
  14. *
  15. *
  16. * @ingroup gff3_loader
  17. */
  18. function tripal_feature_gff3_load_form() {
  19. $form['gff_file']= array(
  20. '#type' => 'textfield',
  21. '#title' => t('GFF3 File'),
  22. '#description' => t('Please enter the full system path for the GFF file, or a path within the Drupal
  23. installation (e.g. /sites/default/files/xyz.gff). The path must be accessible to the
  24. server on which this Drupal instance is running.'),
  25. '#required' => TRUE,
  26. '#weight' => 1
  27. );
  28. // get the list of organisms
  29. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  30. $org_rset = chado_query($sql);
  31. $organisms = array();
  32. $organisms[''] = '';
  33. while ($organism = db_fetch_object($org_rset)) {
  34. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  35. }
  36. $form['organism_id'] = array(
  37. '#title' => t('Organism'),
  38. '#type' => t('select'),
  39. '#description' => t("Choose the organism to which these sequences are associated"),
  40. '#required' => TRUE,
  41. '#options' => $organisms,
  42. );
  43. $form['import_options'] = array(
  44. '#type' => 'fieldset',
  45. '#title' => t('Import Options'),
  46. '#weight' => 6,
  47. '#collapsed' => TRUE
  48. );
  49. $form['import_options']['add_only']= array(
  50. '#type' => 'checkbox',
  51. '#title' => t('Import only new features'),
  52. '#required' => FALSE,
  53. '#description' => t('The job will skip features in the GFF file that already
  54. exist in the database and import only new features.'),
  55. '#weight' => 2
  56. );
  57. $form['import_options']['update']= array(
  58. '#type' => 'checkbox',
  59. '#title' => t('Import all and update'),
  60. '#required' => FALSE,
  61. '#default_value' => 'checked',
  62. '#description' => t('Existing features will be updated and new features will be added. Attributes
  63. for a feature that are not present in the GFF but which are present in the
  64. database will not be altered.'),
  65. '#weight' => 3
  66. );
  67. $form['import_options']['refresh']= array(
  68. '#type' => 'checkbox',
  69. '#title' => t('Import all and replace'),
  70. '#required' => FALSE,
  71. '#description' => t('Existing features will be updated and feature properties not
  72. present in the GFF file will be removed.'),
  73. '#weight' => 4
  74. );
  75. $form['import_options']['remove']= array(
  76. '#type' => 'checkbox',
  77. '#title' => t('Delete features'),
  78. '#required' => FALSE,
  79. '#description' => t('Features present in the GFF file that exist in the database
  80. will be removed rather than imported'),
  81. '#weight' => 5
  82. );
  83. $form['analysis'] = array(
  84. '#type' => 'fieldset',
  85. '#title' => t('Analysis Used to Derive Features'),
  86. '#weight' => 6,
  87. '#collapsed' => TRUE
  88. );
  89. $form['analysis']['desc'] = array(
  90. '#type' => 'markup',
  91. '#value' => t("Why specify an analysis for a data load? All data comes
  92. from some place, even if downloaded from Genbank. By specifying
  93. analysis details for all data uploads, it allows an end user to reproduce the
  94. data set, but at least indicates the source of the data."),
  95. );
  96. // get the list of analyses
  97. $sql = "SELECT * FROM {analysis} ORDER BY name";
  98. $org_rset = chado_query($sql);
  99. $analyses = array();
  100. $analyses[''] = '';
  101. while ($analysis = db_fetch_object($org_rset)) {
  102. $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
  103. }
  104. $form['analysis']['analysis_id'] = array(
  105. '#title' => t('Analysis'),
  106. '#type' => t('select'),
  107. '#description' => t("Choose the analysis to which these features are associated"),
  108. '#required' => TRUE,
  109. '#options' => $analyses,
  110. );
  111. $form['button'] = array(
  112. '#type' => 'submit',
  113. '#value' => t('Import GFF3 file'),
  114. '#weight' => 10,
  115. );
  116. return $form;
  117. }
  118. /**
  119. *
  120. *
  121. * @ingroup gff3_loader
  122. */
  123. function tripal_feature_gff3_load_form_validate($form, &$form_state) {
  124. $gff_file = $form_state['values']['gff_file'];
  125. $organism_id = $form_state['values']['organism_id'];
  126. $add_only = $form_state['values']['add_only'];
  127. $update = $form_state['values']['update'];
  128. $refresh = $form_state['values']['refresh'];
  129. $remove = $form_state['values']['remove'];
  130. // check to see if the file is located local to Drupal
  131. $gff_file = trim($gff_file);
  132. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  133. if (!file_exists($dfile)) {
  134. // if not local to Drupal, the file must be someplace else, just use
  135. // the full path provided
  136. $dfile = $gff_file;
  137. }
  138. if (!file_exists($dfile)) {
  139. 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."));
  140. }
  141. // @coder-ignore: there are no functions being called here
  142. // @todo: break each line of this conditional into separate variables to make more readable
  143. if (($add_only AND ($update OR $refresh OR $remove)) OR
  144. ($update AND ($add_only OR $refresh OR $remove)) OR
  145. ($refresh AND ($update OR $add_only OR $remove)) OR
  146. ($remove AND ($update OR $refresh OR $add_only))) {
  147. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  148. }
  149. }
  150. /**
  151. *
  152. * @ingroup gff3_loader
  153. */
  154. function tripal_feature_gff3_load_form_submit($form, &$form_state) {
  155. global $user;
  156. $gff_file = $form_state['values']['gff_file'];
  157. $organism_id = $form_state['values']['organism_id'];
  158. $add_only = $form_state['values']['add_only'];
  159. $update = $form_state['values']['update'];
  160. $refresh = $form_state['values']['refresh'];
  161. $remove = $form_state['values']['remove'];
  162. $analysis_id = $form_state['values']['analysis_id'];
  163. $args = array($gff_file, $organism_id, $analysis_id, $add_only, $update, $refresh, $remove);
  164. $type = '';
  165. if ($add_only) {
  166. $type = 'import only new features';
  167. }
  168. if ($update) {
  169. $type = 'import all and update';
  170. }
  171. if ($refresh) {
  172. $type = 'import all and replace';
  173. }
  174. if ($remove) {
  175. $type = 'delete features';
  176. }
  177. $fname = preg_replace("/.*\/(.*)/", "$1", $gff_file);
  178. tripal_add_job("$type GFF3 file: $fname", '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,
  188. $add_only =0, $update = 0, $refresh = 0, $remove = 0, $job = NULL) {
  189. // make sure our temporary table exists
  190. $ret = array();
  191. if (!db_table_exists('tripal_gff_temp')) {
  192. $schema = tripal_feature_get_custom_tables('tripal_gff_temp');
  193. $success = tripal_core_create_custom_table($ret, 'tripal_gff_temp', $schema['tripal_gff_temp']);
  194. if(!$success) {
  195. watchdog('T_gff3_loader', "Cannot creat temporary loading table", array(), WATCHDOG_ERROR);
  196. return;
  197. }
  198. }
  199. // empty the temp table
  200. $sql = "DELETE FROM tripal_gff_temp";
  201. chado_query($sql);
  202. // begin the transaction
  203. $connection = tripal_db_start_transaction();
  204. // if we cannot get a connection then let the user know the loading will be slow
  205. if (!$connection) {
  206. print "A persistant connection was not obtained. Loading will be slow\n";
  207. }
  208. else {
  209. print "\nNOTE: Loading of this GFF file is performed using a database transaction. \n" .
  210. "If the load fails or is terminated prematurely then the entire set of \n" .
  211. "insertions/updates is rolled back and will not be found in the database\n\n";
  212. }
  213. // check to see if the file is located local to Drupal
  214. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  215. if (!file_exists($dfile)) {
  216. // if not local to Drupal, the file must be someplace else, just use
  217. // the full path provided
  218. $dfile = $gff_file;
  219. }
  220. if (!file_exists($dfile)) {
  221. watchdog('T_gff3_loader',"Cannot find the file: %dfile",
  222. array('%dfile' => $dfile), WATCHDOG_ERROR);
  223. return 0;
  224. }
  225. //$previous_db = tripal_db_set_active('chado');
  226. print "Opening $gff_file\n";
  227. //$lines = file($dfile,FILE_SKIP_EMPTY_LINES);
  228. $fh = fopen($dfile, 'r');
  229. if (!$fh) {
  230. watchdog('T_gff3_loader',"cannot open file: %dfile",
  231. array('%dfile' => $dfile), WATCHDOG_ERROR);
  232. return 0;
  233. }
  234. $filesize = filesize($dfile);
  235. // get the controlled vocaubulary that we'll be using. The
  236. // default is the 'sequence' ontology
  237. // @coder-ignore: non-drupal schema thus table prefixing does not apply
  238. $sql = "SELECT * FROM cv WHERE name = '%s'";
  239. $cv = db_fetch_object(chado_query($sql, 'sequence'));
  240. if (!$cv) {
  241. watchdog('T_gff3_loader',"Cannot find the 'sequence' ontology",
  242. array(), WATCHDOG_ERROR);
  243. return '';
  244. }
  245. // get the organism for which this GFF3 file belongs
  246. // @coder-ignore: non-drupal schema thus table prefixing does not apply
  247. $sql = "SELECT * FROM organism WHERE organism_id = %d";
  248. $organism = db_fetch_object(chado_query($sql, $organism_id));
  249. $interval = intval($filesize * 0.01);
  250. if ($interval == 0) {
  251. $interval = 1;
  252. }
  253. $in_fasta = 0;
  254. $line_num = 0;
  255. $num_read = 0;
  256. $intv_read = 0;
  257. // iterate through each line of the GFF file
  258. print "Parsing Line $line_num (0.00%). Memory: " . number_format(memory_get_usage()) . " bytes\r";
  259. while ($line = fgets($fh)) {
  260. $line_num++;
  261. $num_read += drupal_strlen($line);
  262. $intv_read += $num_read;
  263. // update the job status every 1% features
  264. if ($job and $intv_read >= $interval) {
  265. $intv_read = 0;
  266. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  267. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  268. tripal_job_set_progress($job, intval(($num_read / $filesize) * 100));
  269. }
  270. // check to see if we have FASTA section, if so then set the variable
  271. // to start parsing
  272. if (preg_match('/^##FASTA/i', $line)) {
  273. $in_fasta = 1;
  274. break;
  275. }
  276. // skip comments
  277. if (preg_match('/^#/', $line)) {
  278. continue;
  279. }
  280. // skip empty lines
  281. if (preg_match('/^\s*$/', $line)) {
  282. continue;
  283. }
  284. // TODO: handle FASTA section
  285. // get the columns
  286. $cols = explode("\t", $line);
  287. if (sizeof($cols) != 9) {
  288. watchdog('T_gff3_loader','improper number of columns on line %line_num',
  289. array('%line_num' => $line_num), WATCHDOG_ERROR);
  290. return '';
  291. }
  292. // get the column values
  293. $landmark = $cols[0];
  294. $source = $cols[1];
  295. $type = $cols[2];
  296. $start = $cols[3];
  297. $end = $cols[4];
  298. $score = $cols[5];
  299. $strand = $cols[6];
  300. $phase = $cols[7];
  301. $attrs = explode(";", $cols[8]); // split by a semicolon
  302. // ready the start and stop for chado. Chado expects these positions
  303. // to be zero-based, so we substract 1 from the fmin
  304. $fmin = $start - 1;
  305. $fmax = $end;
  306. if ($end < $start) {
  307. $fmin = $end - 1;
  308. $fmax = $start;
  309. }
  310. // format the strand for chado
  311. if (strcmp($strand, '.') == 0) {
  312. $strand = 0;
  313. }
  314. elseif (strcmp($strand, '+') == 0) {
  315. $strand = 1;
  316. }
  317. elseif (strcmp($strand, '-') == 0) {
  318. $strand = -1;
  319. }
  320. if (strcmp($phase, '.') == 0) {
  321. $phase = '';
  322. }
  323. // get the type record
  324. if (!tripal_core_is_sql_prepared('sel_cvterm_cvid_cvtname_synonym')) {
  325. $psql = "PREPARE sel_cvterm_cvid_cvtname_synonym (int, text, text) AS
  326. SELECT CVT.cvterm_id, CVT.cv_id, CVT.name, CVT.definition,
  327. CVT.dbxref_id, CVT.is_obsolete, CVT.is_relationshiptype
  328. FROM {cvterm} CVT
  329. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  330. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  331. WHERE CV.cv_id = $1 and (CVT.name = $2 or CVTS.synonym = $3)";
  332. $status = chado_query($psql);
  333. if (!$status) {
  334. watchdog('T_gff3_loader','cannot prepare statement \'sel_cvterm_cvid_cvtname_synonym\' for ontology term %line_num',
  335. array('%line_num' => $line_num), WATCHDOG_ERROR);
  336. return '';
  337. }
  338. }
  339. $result = chado_query("EXECUTE sel_cvterm_cvid_cvtname_synonym (%d, '%s', '%s')", $cv->cv_id, $type, $type);
  340. $cvterm = db_fetch_object($result);
  341. if (!$cvterm) {
  342. watchdog('T_gff3_loader','cannot find ontology term \'%type\' on line %line_num',
  343. array('%type' => $type, '%line_num' => $line_num), WATCHDOG_ERROR);
  344. return '';
  345. }
  346. // break apart each of the attributes
  347. $tags = array();
  348. $attr_name = '';
  349. $attr_uniquename = '';
  350. $attr_residue_info = '';
  351. $attr_locgroup = 0;
  352. $attr_fmin_partial = 'f';
  353. $attr_fmax_partial = 'f';
  354. $attr_is_obsolete = 'f';
  355. $attr_is_analysis = 'f';
  356. $attr_others = '';
  357. $residues = '';
  358. foreach ($attrs as $attr) {
  359. $attr = rtrim($attr);
  360. $attr = ltrim($attr);
  361. if (strcmp($attr, '')==0) {
  362. continue;
  363. }
  364. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  365. watchdog('T_gff3_loader','Attribute is not correctly formatted on line %line_num: %attr',
  366. array('%line_num' => $line_num, '%attr' => $attr), WATCHDOG_ERROR);
  367. return '';
  368. }
  369. // break apart each tag
  370. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  371. // multiple instances of an attribute are separated by commas
  372. $tag_name = $tag[0];
  373. if (!array_key_exists($tag_name, $tags)) {
  374. $tags[$tag_name] = array();
  375. }
  376. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  377. // replace the URL escape codes for each tag
  378. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  379. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  380. }
  381. // get the name and ID tags
  382. if (strcmp($tag_name, 'ID') == 0) {
  383. $attr_uniquename = $tag[1];
  384. }
  385. elseif (strcmp($tag_name, 'Name') == 0) {
  386. $attr_name = $tag[1];
  387. }
  388. // get the list of non-reserved attributes
  389. elseif (strcmp($tag_name, 'Alias') !=0 and strcmp($tag_name, 'Parent') !=0 and
  390. strcmp($tag_name, 'Target') !=0 and strcmp($tag_name, 'Gap') !=0 and
  391. strcmp($tag_name, 'Derives_from') !=0 and strcmp($tag_name, 'Note') !=0 and
  392. strcmp($tag_name, 'Dbxref') !=0 and strcmp($tag_name, 'Ontology_term') !=0 and
  393. strcmp($tag_name, 'Is_circular') !=0) {
  394. foreach ($tags[$tag_name] as $value){
  395. $attr_others[$tag_name][] = $value;
  396. }
  397. }
  398. }
  399. // if neither name nor uniquename are provided then generate one
  400. if (!$attr_uniquename and !$attr_name) {
  401. if (array_key_exists('Parent', $tags)) {
  402. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark:$fmin..$fmax";
  403. }
  404. else {
  405. watchdog('T_gff3_loader','Cannot generate a uniquename for feature on line %line_num',
  406. array('%line_num' => $line_num), WATCHDOG_ERROR);
  407. exit;
  408. }
  409. $attr_name = $attr_uniquename;
  410. }
  411. // if a name is not specified then use the unique name
  412. if (strcmp($attr_name, '')==0) {
  413. $attr_name = $attr_uniquename;
  414. }
  415. // if an ID attribute is not specified then use the attribute name and
  416. // hope for the best
  417. if (!$attr_uniquename) {
  418. $attr_uniquename = $attr_name;
  419. }
  420. // make sure the landmark sequence exists in the database. We don't
  421. // know the type of the landmark so we'll hope that it's unique across
  422. // all types. If not we'll error out. This test is only necessary if
  423. // if the landmark and the uniquename are different. If they are the same
  424. // then this is the information for the landmark
  425. if (strcmp($landmark, $attr_uniquename) != 0 ) {
  426. $select = array(
  427. 'organism_id' => $organism_id,
  428. 'uniquename' => $landmark,
  429. );
  430. $columns = array('count(*) as num_landmarks');
  431. $options = array('statement_name' => 'sel_feature_organismid_uniquename');
  432. $count = tripal_core_chado_select('feature', $columns, $select, $options);
  433. if (!$count or $count[0]->num_landmarks == 0) {
  434. watchdog('T_gff3_loader',"The landmark '%landmark' cannot be found for this organism. ".
  435. "Please add the landmark and then retry the import of this GFF3 ".
  436. "file", array('%landmark' => $landmark), WATCHDOG_ERROR);
  437. return '';
  438. }
  439. if ($count[0]->num_landmarks > 1) {
  440. watchdog('T_gff3_loader',"The landmark '%landmark' is not unique for this organism. ".
  441. "The features cannot be associated", array('%landmark' => $landmark), WATCHDOG_ERROR);
  442. return '';
  443. }
  444. }
  445. // if the option is to remove or refresh then we want to remove
  446. // the feature from the database.
  447. if ($remove or $refresh) {
  448. $sql = "DELETE FROM {feature}
  449. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  450. $match = array(
  451. 'organism_id' => $organism->organism_id,
  452. 'uniquename' => $attr_uniquename,
  453. 'type_id' => $cvterm->cvterm_id
  454. );
  455. $result = tripal_core_chado_delete('feature',$match);
  456. if (!$result) {
  457. watchdog('T_gff3_loader',"cannot delete feature %attr_uniquename",
  458. array('%attr_uniquename' => $attr_uniquename), WATCHDOG_ERROR);
  459. }
  460. $feature = 0;
  461. unset($result);
  462. }
  463. // add or update the feature and all properties
  464. if ($update or $refresh or $add_only) {
  465. // add/update the feature
  466. $feature = tripal_feature_load_gff3_feature($organism, $analysis_id, $cvterm,
  467. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  468. $attr_is_obsolete, $add_only, $score);
  469. if ($feature) {
  470. // add a record for this feature to the tripal_gff_temp table for
  471. // later lookup
  472. $values = array(
  473. 'feature_id' => $feature->feature_id,
  474. 'organism_id' => $feature->organism_id,
  475. 'type_name' => $type,
  476. 'uniquename' => $feature->uniquename
  477. );
  478. $options = array('statement_name' => 'ins_tripalgfftemp');
  479. $result = tripal_core_chado_insert('tripal_gff_temp', $values, $options);
  480. if (!$result) {
  481. watchdog('T_gff3_loader',"Cound not save record in temporary table, Cannot continue.", array(), WATCHDOG_ERROR);
  482. return;
  483. }
  484. // add/update the featureloc if the landmark and the ID are not the same
  485. // if they are the same then this entry in the GFF is probably a landmark identifier
  486. if (strcmp($landmark, $attr_uniquename) !=0 ) {
  487. tripal_feature_load_gff3_featureloc($feature, $organism,
  488. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  489. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  490. }
  491. continue;
  492. // add any aliases for this feature
  493. if (array_key_exists('Alias', $tags)) {
  494. tripal_feature_load_gff3_alias($feature, $tags['Alias']);
  495. }
  496. // add any dbxrefs for this feature
  497. if (array_key_exists('Dbxref', $tags)) {
  498. tripal_feature_load_gff3_dbxref($feature, $tags['Dbxref']);
  499. }
  500. // add any ontology terms for this feature
  501. if (array_key_exists('Ontology_term', $tags)) {
  502. tripal_feature_load_gff3_ontology($feature, $tags['Ontology_term']);
  503. }
  504. // add parent relationships
  505. if (array_key_exists('Parent', $tags)) {
  506. tripal_feature_load_gff3_parents($feature, $cvterm, $tags['Parent'], $organism_id, $fmin);
  507. }
  508. // add target relationships
  509. if (array_key_exists('Target', $tags)) {
  510. preg_match('/^(.*)\s+\d+\s+\d+\s+(\+|\-)*$/', $tags['Target'][0], $matches);
  511. $target_feature = $matches[1];
  512. $start = $matches[2];
  513. $end = $matches[3];
  514. if ($matches[4]) {
  515. $target_strand = $matches[4];
  516. }
  517. else {
  518. $target_strand = '.';
  519. }
  520. $target_fmin = $start - 1;
  521. $target_fmax = $end;
  522. if ($end < $start) {
  523. $target_fmin = $end - 1;
  524. $target_fmax = $start;
  525. }
  526. #print "Target: $target_feature, $target_fmin-$target_fmax $target_dir\n";
  527. tripal_feature_load_gff3_featureloc($feature, $organism,
  528. $target_feature, $target_fmin, $target_fmax, $target_strand, $phase, $attr_fmin_partial,
  529. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  530. }
  531. // add gap information. This goes in simply as a property
  532. if (array_key_exists('Gap', $tags)) {
  533. foreach ($tags['Gap'] as $value) {
  534. tripal_feature_load_gff3_property($feature, 'Gap', $value);
  535. }
  536. }
  537. // add notes. This goes in simply as a property
  538. if (array_key_exists('Note', $tags)) {
  539. foreach ($tags['Note'] as $value) {
  540. tripal_feature_load_gff3_property($feature, 'Note', $value);
  541. }
  542. }
  543. // add the Derives_from relationship (e.g. polycistronic genes).
  544. if (array_key_exists('Derives_from', $tags)) {
  545. tripal_feature_load_gff3_derives_from($feature, $tags['Derives_from'][0], $organism);
  546. }
  547. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  548. $source_ref = array('GFF_source:' . $source);
  549. tripal_feature_load_gff3_dbxref($feature, $source_ref);
  550. // add any additional attributes
  551. if ($attr_others) {
  552. foreach ($attr_others as $tag_name => $values) {
  553. foreach ($values as $value){
  554. tripal_feature_load_gff3_property($feature, $tag_name, $value);
  555. }
  556. }
  557. }
  558. }
  559. }
  560. }
  561. print "\nSetting ranks of children...\n";
  562. // get features in a parent relationship
  563. $sql = "SELECT DISTINCT F.feature_id, F.organism_id, F.type_id, F.uniquename, FL.strand
  564. FROM tripal_gff_temp TGT
  565. INNER JOIN feature F on TGT.feature_id = F.feature_id
  566. INNER JOIN feature_relationship FR ON FR.object_id = TGT.feature_id
  567. INNER JOIN cvterm CVT on CVT.cvterm_id = FR.type_id
  568. INNER JOIN featureloc FL on FL.feature_id = F.feature_id
  569. WHERE CVT.name = 'part_of'";
  570. $parents = chado_query($sql);
  571. // build and prepare the SQL for selecting the children relationship
  572. $sql = "SELECT FR.feature_relationship_id, FL.fmin, FR.rank
  573. FROM feature_relationship FR
  574. INNER JOIN featureloc FL on FL.feature_id = FR.subject_id";
  575. if (!$connection) {
  576. $sql .= "WHERE FR.object_id = %d ".
  577. "ORDER BY FL.fmin ASC ";
  578. }
  579. else {
  580. $sql = "PREPARE sel_gffchildren (int) AS " . $sql . " WHERE FR.object_id = \$1 ORDER BY FL.fmin ASC";
  581. }
  582. if (!tripal_core_is_sql_prepared('sel_gffchildren')) {
  583. $success = chado_query($sql);
  584. if (!$success) {
  585. watchdog("T_gff3_loader", "Cannot prepare statement 'sel_gffchildren' and cannot set children ranks.",
  586. array(), WATCHDOG_WARNING);
  587. return 0;
  588. }
  589. }
  590. // now set the rank of any parent/child relationships. The order is based
  591. // on the fmin. The start rank is 1. This allows features with other
  592. // relationships to be '0' (the default), and doesn't interfer with the
  593. // ordering defined here.
  594. while ($parent = db_fetch_object($parents)) {
  595. // get the children
  596. if ($connection) {
  597. $result = chado_query('EXECUTE sel_gffchildren (%d)', $parent->feature_id);
  598. }
  599. else {
  600. $result = chado_query($sql, $parent->feature_id);
  601. }
  602. // build an array of the children
  603. $children = array();
  604. while ($child = db_fetch_object($result)) {
  605. $children[] = $child;
  606. }
  607. // sort the children come in order of their fmin position
  608. // but if the parent is on the reverse strand we need to
  609. // reverse the order of the children.
  610. if ($parent->strand == -1) {
  611. arsort($children);
  612. }
  613. // first set the ranks to a negative number so that we don't
  614. // get a duplicate error message when we try to change any of them
  615. $rank = -1;
  616. foreach ($children as $child) {
  617. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  618. $options = array('statement_name' => 'upd_featurerelationship_rank');
  619. $values = array('rank' => $rank);
  620. tripal_core_chado_update('feature_relationship', $match, $values, $options);
  621. $rank--;
  622. }
  623. // now set the rank correctly
  624. $rank = 0;
  625. foreach ($children as $child) {
  626. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  627. $options = array('statement_name' => 'upd_featurerelationship_rank');
  628. $values = array('rank' => $rank);
  629. //print "Was: " . $child->rank . " now $rank ($parent->strand)\n" ;
  630. tripal_core_chado_update('feature_relationship', $match, $values, $options);
  631. $rank++;
  632. }
  633. }
  634. // commit the transaction
  635. tripal_db_commit_transaction();
  636. print "Done\n";
  637. return 1;
  638. }
  639. /**
  640. *
  641. *
  642. * @ingroup gff3_loader
  643. */
  644. function tripal_feature_load_gff3_derives_from($feature, $subject, $organism) {
  645. // get the subject type
  646. $values = array(
  647. 'organism_id' => $organism->organism_id,
  648. 'uniquename' => $subject,
  649. );
  650. $options = array('statement_name' => 'sel_tripalgfftemp_orun');
  651. $result = tripal_core_chado_select('tripal_gff_temp', array('type_name'), $values, $options);
  652. if (count($result) == 0) {
  653. watchdog("T_gff3_loader", "Cannot find subject type for feature in 'derives_from' relationship: %subject", array('%subject' => $subject), WATCHDOG_WARNING);
  654. return '';
  655. }
  656. $subject_type = $result[0]->type_name;
  657. // get the subject feature
  658. $match = array(
  659. 'organism_id' => $organism->organism_id,
  660. 'uniquename' => $subject,
  661. 'type_id' => array(
  662. 'name' => $subject_type,
  663. 'cv_id' => array(
  664. 'name' => 'sequence'
  665. ),
  666. ),
  667. );
  668. $options = array('statement_name' => 'sel_feature_orunty');
  669. $sfeature = tripal_core_chado_select('feature', array('feature_id'), $match, $options);
  670. if (count($sfeature)==0) {
  671. watchdog('T_gff3_loader',"Could not add 'Derives_from' relationship ".
  672. "for %uniquename and %subject. Subject feature, '%subject', ".
  673. "cannot be found", array('%uniquename' => $feature->uniquename, '%subject' => $subject), WATCHDOG_ERROR);
  674. return;
  675. }
  676. // now check to see if the relationship already exists
  677. $values = array(
  678. 'object_id' => $sfeature[0]->feature_id,
  679. 'subject_id' => $feature->feature_id,
  680. 'type_id' => array(
  681. 'cv_id' => array(
  682. 'name' => 'relationship'
  683. ),
  684. 'name' => 'derives_from',
  685. ),
  686. 'rank' => 0
  687. );
  688. $options = array('statement_name' => 'sel_featurerelationship_objectid_subjectid_typeid_rank');
  689. $rel = tripal_core_chado_select('feature_relationship', array('*'), $values, $options);
  690. if (count($rel) > 0) {
  691. return;
  692. }
  693. // finally insert the relationship if it doesn't exist
  694. $options = array('statement_name' => 'ins_featurerelationship_objectid_subjectid_typeid_rank');
  695. $ret = tripal_core_chado_insert('feature_relationship', $values, $options);
  696. if (!$ret) {
  697. watchdog("T_gff3_loader", "Could not add 'Derives_from' relationship for $feature->uniquename and $subject",
  698. array(), WATCHDOG_WARNING);
  699. }
  700. }
  701. /**
  702. *
  703. *
  704. * @ingroup gff3_loader
  705. */
  706. function tripal_feature_load_gff3_parents($feature, $cvterm, $parents, $organism_id, $fmin) {
  707. $uname = $feature->uniquename;
  708. $type = $cvterm->name;
  709. $rel_type = 'part_of';
  710. // prepare these SQL statements that will be used repeatedly.
  711. if (!tripal_core_is_sql_prepared('sel_cvterm_cvname_cvtname_synonym')) {
  712. $psql = "PREPARE sel_cvterm_cvname_cvtname_synonym (text, text, text) AS
  713. SELECT CVT.cvterm_id
  714. FROM cvterm CVT
  715. INNER JOIN cv CV on CVT.cv_id = CV.cv_id
  716. LEFT JOIN cvtermsynonym CVTS on CVTS.cvterm_id = CVT.cvterm_id
  717. WHERE cv.name = $1 and (CVT.name = $2 or CVTS.synonym = $3)";
  718. $status = chado_query($psql);
  719. if (!$status) {
  720. watchdog("T_gff3_loader", "Cannot prepare statement 'sel_cvterm_cvname_cvtname_synonym' for ontology term",
  721. array(), WATCHDOG_WARNING);
  722. return '';
  723. }
  724. }
  725. // iterate through the parents in the list
  726. foreach ($parents as $parent) {
  727. // get the parent cvterm
  728. $values = array(
  729. 'organism_id' => $organism_id,
  730. 'uniquename' => $parent,
  731. );
  732. $options = array('statement_name' => 'sel_tripalgfftemp_orun');
  733. $result = tripal_core_chado_select('tripal_gff_temp', array('type_name'), $values, $options);
  734. if (count($result) == 0) {
  735. watchdog("T_gff3_loader", "Cannot find parent type: %parent", array('%parent' => $parent), WATCHDOG_WARNING);
  736. return '';
  737. }
  738. $parent_type = $result[0]->type_name;
  739. // try to find the parent
  740. $parentcvterm = db_fetch_object(chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym ('%s', '%s', '%s')", 'sequence', $parent_type, $parent_type));
  741. $relcvterm = db_fetch_object(chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym ('%s', '%s', '%s')", 'relationship', $rel_type, $rel_type));
  742. $values = array(
  743. 'organism_id' => $organism_id,
  744. 'uniquename' => $parent,
  745. 'type_id' => $parentcvterm->cvterm_id,
  746. );
  747. $options = array('statement_name' => 'sel_feature_orunty');
  748. $result = tripal_core_chado_select('feature', array('feature_id'), $values, $options);
  749. $parent_feature = $result[0];
  750. // if the parent exists then add the relationship otherwise print error and skip
  751. if ($parent_feature) {
  752. // check to see if the relationship already exists
  753. $values = array(
  754. 'object_id' => $parent_feature->feature_id,
  755. 'subject_id' => $feature->feature_id,
  756. 'type_id' => $relcvterm->cvterm_id,
  757. );
  758. $options = array('statement_name' => 'sel_featurerelationship_objectid_subjectid_typeid');
  759. $rel = tripal_core_chado_select('feature_relationship', array('*'), $values, $options);
  760. if (count($rel) > 0) {
  761. }
  762. else {
  763. // the relationship doesn't already exist, so add it.
  764. $values = array(
  765. 'subject_id' => $feature->feature_id,
  766. 'object_id' => $parent_feature->feature_id,
  767. 'type_id' => $relcvterm->cvterm_id,
  768. );
  769. $options = array('statement_name' => 'ins_featurerelationship_subjectid_objectid_typeid');
  770. $result = tripal_core_chado_insert('feature_relationship', $values, $options);
  771. if (!$result) {
  772. watchdog("T_gff3_loader", "Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)",
  773. array(), WATCHDOG_WARNING);
  774. }
  775. }
  776. }
  777. else {
  778. watchdog("T_gff3_loader", "Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent",
  779. array(), WATCHDOG_WARNING);
  780. }
  781. }
  782. }
  783. /**
  784. *
  785. *
  786. * @ingroup gff3_loader
  787. */
  788. function tripal_feature_load_gff3_dbxref($feature, $dbxrefs) {
  789. // iterate through each of the dbxrefs
  790. foreach ($dbxrefs as $dbxref) {
  791. // get the database name from the reference. If it doesn't exist then create one.
  792. $ref = explode(":", $dbxref);
  793. $dbname = $ref[0];
  794. $accession = $ref[1];
  795. // first look for the database name if it doesn't exist then create one.
  796. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  797. // can't be found then look for the name as is. If it still can't be found
  798. // the create the database
  799. $options = array('statement_name' => 'sel_db_name');
  800. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "DB:$dbname"), $options);
  801. if (count($db) == 0) {
  802. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "$dbname"), $options);
  803. }
  804. if (count($db) == 0) {
  805. $options = array('statement_name' => 'ins_db_name');
  806. $ret = tripal_core_chado_insert('db', array('name' => $dbname,
  807. 'description' => 'Added automatically by the GFF loader'), $options);
  808. if ($ret) {
  809. $options = array('statement_name' => 'sel_db_name');
  810. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "$dbname"), $options);
  811. }
  812. else {
  813. watchdog("T_gff3_loader", "Cannot find or add the database $dbname", array(), WATCHDOG_WARNING);
  814. return 0;
  815. }
  816. }
  817. $db = $db[0];
  818. // now check to see if the accession exists
  819. $options = array('statement_name' => 'sel_dbxref_accession_dbid');
  820. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'), array(
  821. 'accession' => $accession, 'db_id' => $db->db_id), $options);
  822. // if the accession doesn't exist then we want to add it
  823. if (sizeof($dbxref) == 0) {
  824. $options = array('statement_name' => 'ins_dbxref_dbid_accession_version');
  825. $ret = tripal_core_chado_insert('dbxref', array('db_id' => $db->db_id,
  826. 'accession' => $accession, 'version' => ''), $options);
  827. $options = array('statement_name' => 'sel_dbxref_accession_dbid');
  828. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'), array(
  829. 'accession' => $accession, 'db_id' => $db->db_id), $options);
  830. }
  831. $dbxref = $dbxref[0];
  832. // check to see if this feature dbxref already exists
  833. $options = array('statement_name' => 'sel_featuredbxref_dbxrefid_featureid');
  834. $fdbx = tripal_core_chado_select('feature_dbxref', array('feature_dbxref_id'),
  835. array('dbxref_id' => $dbxref->dbxref_id, 'feature_id' => $feature->feature_id), $options);
  836. // now associate this feature with the database reference if it doesn't
  837. // already exist
  838. if (sizeof($fdbx)==0) {
  839. $options = array('statement_name' => 'ins_featuredbxref_dbxrefid_featureid');
  840. $ret = tripal_core_chado_insert('feature_dbxref', array(
  841. 'dbxref_id' => $dbxref->dbxref_id,
  842. 'feature_id' => $feature->feature_id), $options);
  843. if ($ret) {
  844. }
  845. else {
  846. watchdog("T_gff3_loader", "Failed to insert Dbxref: $dbname:$accession", array(), WATCHDOG_WARNING);
  847. return 0;
  848. }
  849. }
  850. else {
  851. }
  852. }
  853. return 1;
  854. }
  855. /**
  856. *
  857. *
  858. * @ingroup gff3_loader
  859. */
  860. function tripal_feature_load_gff3_ontology($feature, $dbxrefs) {
  861. // iterate through each of the dbxrefs
  862. foreach ($dbxrefs as $dbxref) {
  863. // get the database name from the reference. If it doesn't exist then create one.
  864. $ref = explode(":", $dbxref);
  865. $dbname = $ref[0];
  866. $accession = $ref[1];
  867. // first look for the database name
  868. $options = array('statement_name' => 'sel_db_name');
  869. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "DB:$dbname"), $options);
  870. if (sizeof($db) == 0) {
  871. $db = tripal_core_chado_select('db', array('db_id'), array('name' => "$dbname"), $options);
  872. }
  873. if (sizeof($db) == 0) {
  874. watchdog("T_gff3_loader", "Database, $dbname is missing for reference: $dbname:$accession", array(), WATCHDOG_WARNING);
  875. return 0;
  876. }
  877. $db = $db[0];
  878. // now check to see if the accession exists
  879. $options = array('statement_name' => 'sel_dbxref_accession_dbid');
  880. $dbxref = tripal_core_chado_select('dbxref', array('dbxref_id'), array(
  881. 'accession' => $accession, 'db_id' => $db->db_id), $options);
  882. if (sizeof($dbxref) == 0) {
  883. watchdog("T_gff3_loader", "Accession, $accession is missing for reference: $dbname:$accession", array(), WATCHDOG_WARNING);
  884. return 0;
  885. }
  886. $dbxref = $dbxref[0];
  887. // now check to see if the cvterm exists
  888. $options = array('statement_name' => 'sel_cvterm_dbxrefid');
  889. $cvterm = tripal_core_chado_select('cvterm', array('cvterm_id'), array(
  890. 'dbxref_id' => $dbxref->dbxref_id), $options);
  891. // if it doesn't exist in the cvterm table, look for an alternate id
  892. if (sizeof($cvterm) == 0) {
  893. $options = array('statement_name' => 'sel_cvtermdbxref_dbxrefid');
  894. $cvterm = tripal_core_chado_select('cvterm_dbxref', array('cvterm_id'), array(
  895. 'dbxref_id' => $dbxref->dbxref_id), $options);
  896. }
  897. if (sizeof($cvterm) == 0) {
  898. watchdog("T_gff3_loader", "CV Term is missing for reference: $dbname:$accession", array(), WATCHDOG_WARNING);
  899. return 0;
  900. }
  901. $cvterm = $cvterm[0];
  902. // check to see if this feature cvterm already exists
  903. $options = array('statement_name' => 'sel_featurecvterm_cvtermid_featureid');
  904. $fcvt = tripal_core_chado_select('feature_cvterm', array('feature_cvterm_id'),
  905. array('cvterm_id' => $cvterm->cvterm_id, 'feature_id' => $feature->feature_id),
  906. $options);
  907. // now associate this feature with the cvterm if it doesn't already exist
  908. if (sizeof($fcvt)==0) {
  909. $values = array(
  910. 'cvterm_id' => $cvterm->cvterm_id,
  911. 'feature_id' => $feature->feature_id,
  912. 'pub_id' => array(
  913. 'uniquename' => 'null',
  914. ),
  915. );
  916. $options = array('statement_name' => 'ins_featurecvterm_cvtermid_featureid_pubid');
  917. $ret = tripal_core_chado_insert('feature_cvterm', $values, $options);
  918. if ($ret) {
  919. }
  920. else {
  921. watchdog("T_gff3_loader", "Failed to insert ontology term: $dbname:$accession", array(), WATCHDOG_WARNING);
  922. return 0;
  923. }
  924. }
  925. }
  926. return 1;
  927. }
  928. /**
  929. *
  930. *
  931. * @ingroup gff3_loader
  932. */
  933. function tripal_feature_load_gff3_alias($feature, $aliases) {
  934. // make sure we have a 'synonym_type' vocabulary
  935. $select = array('name' => 'synonym_type');
  936. $options = array('statement_name' => 'sel_cv_name');
  937. $results = tripal_core_chado_select('cv', array('*'), $selct, $options);
  938. if (count($results) == 0) {
  939. // insert the 'synonym_type' vocabulary
  940. $values = array(
  941. 'name' => 'synonym_type',
  942. 'definition' => 'vocabulary for synonym types',
  943. );
  944. $options = array('statement_name' => 'ins_cv_name_definition');
  945. $result = tripal_core_chado_insert('cv', $values, $options);
  946. if (!result) {
  947. watchdog("T_gff3_loader", "Failed to add the synonyms type vocabulary", array(), WATCHDOG_WARNING);
  948. return 0;
  949. }
  950. // now that we've added the cv we need to get the record
  951. $options = array('statement_name' => 'sel_cv_name');
  952. $results = tripal_core_chado_select('cv', array('*'), $select, $options);
  953. $syncv = $results[0];
  954. }
  955. else {
  956. $syncv = $results[0];
  957. }
  958. // get the 'exact' cvterm, which is the type of synonym we're adding
  959. $select = array(
  960. 'name' => 'exact',
  961. 'cv_id' => array(
  962. 'name' => 'synonym_type'
  963. ),
  964. );
  965. $options = array('statement_name' => 'sel_cvterm_name_cvid');
  966. $result = tripal_core_chado_select('cvterm', array('*'), $select, $options);
  967. $syntype = $result[0];
  968. if (!$syntype) {
  969. $term = array(
  970. 'name' => 'exact',
  971. 'id' => "internal:exact",
  972. 'definition' => '',
  973. 'is_obsolete' => 0,
  974. );
  975. // TODO: fix the function so it uses prepared statements
  976. $syntype = tripal_cv_add_cvterm($term, $syncv->name, 0, 1);
  977. if (!$syntype) {
  978. watchdog("T_gff3_loader", "Cannot add synonym type: internal:$type", array(), WATCHDOG_WARNING);
  979. return 0;
  980. }
  981. }
  982. // iterate through all of the aliases and add each one
  983. foreach ($aliases as $alias) {
  984. // check to see if the alias already exists in the synonym table
  985. // if not, then add it
  986. $select = array(
  987. 'name' => $alias,
  988. 'type_id' => $syntype->cvterm_id,
  989. );
  990. $options = array('statement_name' => 'sel_synonym_name_typeid');
  991. $result = tripal_core_chado_select('synonym', array('*'), $select, $options);
  992. $synonym = $result[0];
  993. if (!$synonym) {
  994. $values = array(
  995. 'name' => $alias,
  996. 'type_id' => $syntype->cvterm_id,
  997. 'synonym_sgml' => '',
  998. );
  999. $options = array('statement_name' => 'ins_synonym_name_typeid_synonymsgml');
  1000. $result = tripal_core_chado_insert('synonym', $values, $options);
  1001. if (!$result) {
  1002. watchdog("T_gff3_loader", "Cannot add alias $alias to synonym table", array(), WATCHDOG_WARNING);
  1003. }
  1004. }
  1005. $options = array('statement_name' => 'sel_synonym_name_typeid');
  1006. $result = tripal_core_chado_select('synonym', array('*'), $select, $options);
  1007. $synonym = $result[0];
  1008. // check to see if we have a NULL publication in the pub table. If not,
  1009. // then add one.
  1010. // @coder-ignore: non-drupal schema thus table prefixing does not apply
  1011. $select = array('uniquename' => 'null');
  1012. $options = array('statement_name' => 'sel_pub_uniquename');
  1013. $result = tripal_core_chado_select('pub', array('*'), $select, $options);
  1014. $pub = $result[0];
  1015. if (!$pub) {
  1016. // prepare the statement
  1017. if (!tripal_core_is_sql_prepared('ins_pub_uniquename_typeid')) {
  1018. $psql = "PREPARE ins_pub_uniquename_typeid (text, text) AS
  1019. INSERT INTO pub (uniquename,type_id) VALUES ('%s',
  1020. (SELECT cvterm_id
  1021. FROM cvterm CVT
  1022. INNER JOIN dbxref DBX on DBX.dbxref_id = CVT.dbxref_id
  1023. INNER JOIN db DB on DB.db_id = DBX.db_id
  1024. WHERE CVT.name = $1 and DB.name = $2)";
  1025. $status = chado_query($psql);
  1026. if (!$status) {
  1027. watchdog("T_gff3_loader", "Cannot prepare statement 'ins_pub_uniquename_typeid", array(), WATCHDOG_WARNING);
  1028. return 0;
  1029. }
  1030. }
  1031. // insert the null pub
  1032. $result = db_fetch_object(chado_query("EXECUTE ins_pub_uniquename_typeid ('%s', '%s')", 'null', 'null'));
  1033. if (!$result) {
  1034. watchdog("T_gff3_loader", "Cannot add null publication needed for setup of alias", array(), WATCHDOG_WARNING);
  1035. return 0;
  1036. }
  1037. }
  1038. $options = array('statement_name' => 'sel_pub_uniquename');
  1039. $result = tripal_core_chado_select('pub', array('*'), $select, $options);
  1040. $pub = $result[0];
  1041. // check to see if the synonym exists in the feature_synonym table
  1042. // if not, then add it.
  1043. $select = array(
  1044. 'synonym_id' => $synonym->synonym_id,
  1045. 'feature_id' => $feature->feature_id,
  1046. 'pub_id' => $pub->pub_id,
  1047. );
  1048. $options = array('statement_name', 'sel_synonymfeature_synonymid_featureid_pubid');
  1049. $result = tripal_core_chado_select('feature_synonym', array('*'), $select, $options);
  1050. $fsyn = $result[0];
  1051. if (!$fsyn) {
  1052. $values = array(
  1053. 'synonym_id' => $synonym->synonym_id,
  1054. 'feature_id' => $feature->feature_id,
  1055. 'pub_id' => $pub->pub_id,
  1056. );
  1057. $options = array('statement_name', 'ins_synonymfeature_synonymid_featureid_pubid');
  1058. $result = tripal_core_chado_insert('feature_synonym', $values, $options);
  1059. if (!$result) {
  1060. watchdog("T_gff3_loader", "Cannot add alias $alias to feature synonym table", array(), WATCHDOG_WARNING);
  1061. return 0;
  1062. }
  1063. }
  1064. }
  1065. return 1;
  1066. }
  1067. /**
  1068. *
  1069. *
  1070. * @ingroup gff3_loader
  1071. */
  1072. function tripal_feature_load_gff3_feature($organism, $analysis_id, $cvterm, $uniquename, $name,
  1073. $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1074. // check to see if the feature already exists
  1075. $feature = NULL;
  1076. $fselect = array(
  1077. 'organism_id' => $organism->organism_id,
  1078. 'uniquename' => $uniquename,
  1079. 'type_id' => $cvterm->cvterm_id
  1080. );
  1081. $options = array('statement_name' => 'sel_feature_orunty');
  1082. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1083. $result = tripal_core_chado_select('feature', $columns, $fselect, $options);
  1084. if (count($result) > 0) {
  1085. $feature = $result[0];
  1086. }
  1087. if (strcmp($is_obsolete, 'f')==0 or $is_obsolete == 0) {
  1088. $is_obsolete = 'FALSE';
  1089. }
  1090. if (strcmp($is_obsolete, 't')==0 or $is_obsolete == 1) {
  1091. $is_obsolete = 'TRUE';
  1092. }
  1093. if (strcmp($is_analysis, 'f')==0 or $is_analysis == 0) {
  1094. $is_analysis = 'FALSE';
  1095. }
  1096. if (strcmp($is_analysis, 't')==0 or $is_analysis == 1) {
  1097. $is_analysis = 'TRUE';
  1098. }
  1099. // insert the feature if it does not exist otherwise perform an update
  1100. if (!$feature) {
  1101. $values = array(
  1102. 'organism_id' => $organism->organism_id,
  1103. 'name' => $name,
  1104. 'uniquename' => $uniquename,
  1105. // 'residues' => $residues,
  1106. // 'seqlen' => drupal_strlen($residues),
  1107. 'md5checksum' => md5($residues),
  1108. 'type_id' => $cvterm->cvterm_id,
  1109. 'is_analysis' => $is_analysis,
  1110. 'is_obsolete' => $is_obsolete,
  1111. );
  1112. $options = array('statement_name' => 'ins_feature_all');
  1113. $result = tripal_core_chado_insert('feature', $values, $options);
  1114. if (!$result) {
  1115. watchdog("T_gff3_loader", "Failed to insert feature '$uniquename' ($cvterm->name)", array(), WATCHDOG_WARNING);
  1116. return 0;
  1117. }
  1118. }
  1119. elseif (!$add_only) {
  1120. $values = array(
  1121. 'name' => $name,
  1122. // 'residues' => $residues,
  1123. // 'seqlen' => drupal_strlen($residues),
  1124. 'md5checksum' => md5($residues),
  1125. 'is_analysis' => $is_analysis,
  1126. 'is_obsolete' => $is_obsolete,
  1127. );
  1128. $match = array(
  1129. 'organism_id' => $organism->organism_id,
  1130. 'uniquename' => $uniquename,
  1131. 'type_id' => $cvterm->cvterm_id,
  1132. );
  1133. $options = array('statement_name' => 'upd_feature');
  1134. $result = tripal_core_chado_update('feature', $match, $values, $options);
  1135. if (!$result) {
  1136. watchdog("T_gff3_loader", "Failed to update feature '$uniquename' ($cvterm->name)", array(), WATCHDOG_WARNING);
  1137. return 0;
  1138. }
  1139. }
  1140. else {
  1141. // the feature exists and we don't want to update it so return
  1142. // a value of 0. This will stop all downstream property additions
  1143. return 0;
  1144. }
  1145. // get the newly added feature
  1146. $options = array('statement_name' => 'sel_feature_orunty');
  1147. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1148. $result = tripal_core_chado_select('feature', $columns, $fselect, $options);
  1149. $feature = $result[0];
  1150. // add the analysisfeature entry to the analysisfeature table if it doesn't already exist
  1151. $af_values = array(
  1152. 'analysis_id' => $analysis_id,
  1153. 'feature_id' => $feature->feature_id
  1154. );
  1155. $options = array('statement_name' => 'sel_analysisfeature_analysisid_featureid');
  1156. $afeature = tripal_core_chado_select('analysisfeature', array('analysisfeature_id'), $af_values, $options);
  1157. if (count($afeature)==0) {
  1158. // if a score is available then set that to be the significance field
  1159. if (strcmp($score, '.') != 0) {
  1160. $af_values['significance'] = $score;
  1161. $options = array('statement_name' => 'ins_analysisfeature_analysisid_featureid_significance');
  1162. }
  1163. else {
  1164. $options = array('statement_name' => 'ins_analysisfeature_analysisid_featureid');
  1165. }
  1166. if (!tripal_core_chado_insert('analysisfeature', $af_values, $options)) {
  1167. watchdog("T_gff3_loader", "Could not add analysisfeature record: $analysis_id, $feature->feature_id", array(), WATCHDOG_WARNING);
  1168. }
  1169. }
  1170. else {
  1171. // if a score is available then set that to be the significance field
  1172. $new_vals = array();
  1173. if (strcmp($score, '.')!=0) {
  1174. $new_vals['significance'] = $score;
  1175. }
  1176. else {
  1177. $new_vals['significance'] = '__NULL__';
  1178. }
  1179. if (!$add_only) {
  1180. $options = array('statement_name' => 'upd_analysisfeature');
  1181. $ret = tripal_core_chado_update('analysisfeature', $af_values, $new_vals, $options);
  1182. if (!$ret) {
  1183. watchdog("T_gff3_loader", "Could not update analysisfeature record: $analysis_id, $feature->feature_id", array(), WATCHDOG_WARNING);
  1184. }
  1185. }
  1186. }
  1187. return $feature;
  1188. }
  1189. /**
  1190. *
  1191. *
  1192. * @ingroup gff3_loader
  1193. */
  1194. function tripal_feature_load_gff3_featureloc($feature, $organism, $landmark, $fmin,
  1195. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup) {
  1196. $select = array(
  1197. 'organism_id' => $organism->organism_id,
  1198. 'uniquename' => $landmark,
  1199. );
  1200. $options = array('statement_name' => 'sel_feature_orun');
  1201. $r = tripal_core_chado_select('feature', array('feature_id'), $select, $options);
  1202. if (count($r)==0) {
  1203. // so we couldn't find it using the uniquename. Let's try the 'name'.
  1204. // if we return only a singe result then we can proceed. Otherwise give an
  1205. // error message
  1206. $select = array(
  1207. 'organism_id' => $organism->organism_id,
  1208. 'name' => $landmark,
  1209. );
  1210. $options = array('statement_name' => 'sel_feature_organism_id_name');
  1211. $r = tripal_core_chado_select('feature', array('feature_id'), $select, $options);
  1212. if (count($r) == 0){
  1213. watchdog("T_gff3_loader", "Cannot find landmark feature: '$landmark'. Cannot add the feature location record", array(), WATCHDOG_WARNING);
  1214. return 0;
  1215. }
  1216. elseif (count($r) > 1) {
  1217. watchdog("T_gff3_loader", "multiple landmarks exist with the name: '$landmark'. Cannot resolve which one to use. Cannot add the feature location record",
  1218. array(), WATCHDOG_WARNING);
  1219. return 0;
  1220. }
  1221. }
  1222. $srcfeature = $r[0];
  1223. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1224. // is_fmin_partial and is_fmax_partial, right now these are
  1225. // hardcoded to be false and 0 below.
  1226. // check to see if this featureloc already exists, but also keep track of the
  1227. // last rank value
  1228. $rank = 0;
  1229. $exists = 0;
  1230. $select = array('feature_id' => $feature->feature_id);
  1231. $options = array(
  1232. 'statement_name' => 'sel_featureloc_feature_id',
  1233. 'order_by' => array(
  1234. 'rank' => 'ASC'
  1235. ),
  1236. );
  1237. $locrecs = tripal_core_chado_select('featureloc', array('*'), $select, $options);
  1238. foreach ($locrecs as $featureloc) {
  1239. $select = array('feature_id' => $featureloc->srcfeature_id);
  1240. $options = array('statement_name' => 'sel_feature_feature_id');
  1241. $columns = array('feature_id', 'name');
  1242. $locsfeature = tripal_core_chado_select('feature', $columns, $select, $options);
  1243. // the source feature name and at least the fmin and fmax must be the same
  1244. // for an update of the featureloc, otherwise we'll insert a new record.
  1245. if (strcmp($locsfeature[0]->name, $landmark)==0 and
  1246. ($featureloc->fmin == $fmin or $featureloc->fmax == $fmax)) {
  1247. $match = array('featureloc_id' => $featureloc->featureloc_id);
  1248. $values = array();
  1249. $exists = 1;
  1250. if ($featureloc->fmin != $fmin) {
  1251. $values['fmin'] = $fmin;
  1252. }
  1253. if ($featureloc->fmax != $fmax) {
  1254. $values['fmax'] = $fmax;
  1255. }
  1256. if ($featureloc->strand != $strand) {
  1257. $values['strand'] = $strand;
  1258. }
  1259. if (count($values) > 0) {
  1260. $options = array('statement_name' => 'upd_featureloc_all');
  1261. tripal_core_chado_update('featureloc', $match, $values, $options);
  1262. }
  1263. }
  1264. $rank = $featureloc->rank + 1;
  1265. }
  1266. if (!$exists) {
  1267. // this feature location is new so add it
  1268. if (strcmp($is_fmin_partial, 'f')==0 or !$is_fmin_partial) {
  1269. $is_fmin_partial = 'FALSE';
  1270. }
  1271. elseif (strcmp($is_fmin_partial, 't')==0 or $is_fmin_partial = 1) {
  1272. $is_fmin_partial = 'TRUE';
  1273. }
  1274. if (strcmp($is_fmax_partial, 'f')==0 or !$is_fmax_partial) {
  1275. $is_fmax_partial = 'FALSE';
  1276. }
  1277. elseif (strcmp($is_fmax_partial, 't')==0 or $is_fmax_partial = 1) {
  1278. $is_fmax_partial = 'TRUE';
  1279. }
  1280. $values = array(
  1281. 'feature_id' => $feature->feature_id,
  1282. 'srcfeature_id' => $srcfeature->feature_id,
  1283. 'fmin' => $fmin,
  1284. 'is_fmin_partial' => $is_fmin_partial,
  1285. 'fmax' => $fmax,
  1286. 'is_fmax_partial' => $is_fmax_partial,
  1287. 'strand' => $strand,
  1288. 'residue_info' => $residue_info,
  1289. 'locgroup' => $locgroup,
  1290. 'rank' => $rank
  1291. );
  1292. $options = array('statement_name' => 'ins_featureloc_all');
  1293. if($phase) {
  1294. $values['phase'] = $phase;
  1295. $options = array('statement_name' => 'ins_featureloc_allphase');
  1296. }
  1297. $success = tripal_core_chado_insert('featureloc', $values, $options);
  1298. if (!$success) {
  1299. watchdog("T_gff3_loader", "Failed to insert featureloc", array(), WATCHDOG_WARNING);
  1300. exit;
  1301. return 0;
  1302. }
  1303. }
  1304. return 1;
  1305. }
  1306. /**
  1307. *
  1308. *
  1309. * @ingroup gff3_loader
  1310. */
  1311. function tripal_feature_load_gff3_property($feature, $property, $value) {
  1312. // first make sure the cvterm exists. if not, then add it
  1313. $select = array(
  1314. 'name' => $property,
  1315. 'cv_id' => array(
  1316. 'name' => 'feature_property',
  1317. ),
  1318. );
  1319. $options = array('statement_name' => 'sel_cvterm_name_cvid');
  1320. $result = tripal_core_chado_select('cvterm', array('*'), $select, $options);
  1321. $cvterm = $result[0];
  1322. if (!$cvterm) {
  1323. $term = array(
  1324. 'id' => "null:$property",
  1325. 'name' => $property,
  1326. 'namespace' => 'feature_property',
  1327. 'is_obsolete' => 0,
  1328. );
  1329. $cvterm = (object) tripal_cv_add_cvterm($term, 'feature_property', 0, 0);
  1330. }
  1331. if (!$cvterm) {
  1332. watchdog("T_gff3_loader", "Cannot add cvterm, $property", array(), WATCHDOG_WARNING);
  1333. exit;
  1334. }
  1335. // check to see if the property already exists for this feature
  1336. // if it does but the value is unique then increment the rank and add it.
  1337. // if the value is not unique then don't add it.
  1338. $add = 1;
  1339. $rank = 0;
  1340. $select = array(
  1341. 'feature_id' => $feature->feature_id,
  1342. 'type_id' => $cvterm->cvterm_id,
  1343. );
  1344. $options = array(
  1345. 'statement_name' => 'sel_featureprop_featureid_typeid',
  1346. 'order_by' => array(
  1347. 'rank' => 'ASC',
  1348. ),
  1349. );
  1350. $results = tripal_core_chado_select('featureprop', array('*'), $select, $options);
  1351. foreach ($results as $prop){
  1352. if (strcmp($prop->value, $value)==0) {
  1353. $add = NULL; // don't add it, it already exists
  1354. }
  1355. $rank = $prop->rank + 1;
  1356. }
  1357. // add the property if we pass the check above
  1358. if ($add) {
  1359. $values = array(
  1360. 'feature_id' => $feature->feature_id,
  1361. 'type_id' => $cvterm->cvterm_id,
  1362. 'value' => $value,
  1363. 'rank' => $rank,
  1364. );
  1365. $options = array('statement_name' => 'ins_featureprop_all');
  1366. $result = tripal_core_chado_insert('featureprop', $values, $options);
  1367. if(!$result){
  1368. watchdog("T_gff3_loader", "cannot add featureprop, $property", array(), WATCHDOG_WARNING);
  1369. }
  1370. }
  1371. }