gff_loader.inc 54 KB

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