gff_loader.inc 51 KB

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