gff_loader.inc 56 KB

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