tripal_chado.feature.api.inc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. <?php
  2. /**
  3. * @file
  4. * Provides API functions specificially for managing feature
  5. * records in Chado.
  6. */
  7. /**
  8. * @defgroup tripal_feature_api Chado Feature
  9. * @ingroup tripal_chado_api
  10. * @{
  11. * Provides API functions specificially for managing feature
  12. * records in Chado especially retrieving relationships and sequences derived
  13. * from relationships and feature alignments.
  14. * @}
  15. */
  16. /**
  17. * Used for autocomplete in forms for identifying for publications.
  18. *
  19. * @param $field
  20. * The field in the publication to search on.
  21. * @param $string
  22. * The string to search for.
  23. *
  24. * @return
  25. * A json array of terms that begin with the provided string.
  26. *
  27. * @ingroup tripal_feature_api
  28. */
  29. function chado_autocomplete_feature($string = '') {
  30. $items = array();
  31. $sql = "
  32. SELECT
  33. F.feature_id, F.uniquename, F.name,
  34. O.genus, O,species,
  35. CVT.name as type
  36. FROM {feature} F
  37. INNER JOIN {organism} O ON O.organism_id = F.organism_id
  38. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = F.type_id
  39. WHERE lower(F.uniquename) like lower(:str)
  40. ORDER by F.uniquename
  41. LIMIT 25 OFFSET 0
  42. ";
  43. $features = chado_query($sql, array(':str' => $string . '%'));
  44. while ($feature = $features->fetchObject()) {
  45. $key = "$feature->uniquename [id: $feature->feature_id]";
  46. $items[$key] = "$feature->uniquename ($feature->name, $feature->type, $feature->genus $feature->species)";
  47. }
  48. drupal_json_output($items);
  49. }
  50. /**
  51. * Performs a reverse compliment of a nucleotide sequence.
  52. *
  53. * @param $sequence
  54. * The nucelotide sequence.
  55. *
  56. * @return
  57. * an upper-case reverse complemented sequence.
  58. *
  59. * @ingroup tripal_feature_api
  60. */
  61. function chado_reverse_compliment_sequence($sequence) {
  62. $seq = strtoupper($sequence);
  63. $seq = strrev($seq);
  64. $seq = str_replace("A", "t", $seq);
  65. $seq = str_replace("T", "a", $seq);
  66. $seq = str_replace("G", "c", $seq);
  67. $seq = str_replace("C", "g", $seq);
  68. $seq = str_replace("Y", "r", $seq);
  69. $seq = str_replace("R", "y", $seq);
  70. $seq = str_replace("W", "w", $seq);
  71. $seq = str_replace("S", "s", $seq);
  72. $seq = str_replace("K", "m", $seq);
  73. $seq = str_replace("M", "k", $seq);
  74. $seq = str_replace("D", "h", $seq);
  75. $seq = str_replace("V", "b", $seq);
  76. $seq = str_replace("H", "d", $seq);
  77. $seq = str_replace("B", "v", $seq);
  78. return strtoupper($seq);
  79. }
  80. /**
  81. * Retrieves the sequences for a given feature.
  82. *
  83. * If a feature has multiple alignments or multiple relationships then
  84. * multiple sequences will be returned.
  85. *
  86. * @param $feature
  87. * An associative array describing the feature. Valid keys include:
  88. * - feature_id: The feature_id of the feature for which the sequence will
  89. * be retrieved.
  90. * - name: The feature name. This will appear on the FASTA definition line.
  91. * - parent_id: (optional) only retrieve a sequence if 'derive_from_parent'
  92. * is true and the parent matches this ID.
  93. * - featureloc_id: (optional) only retrieve a sequence if
  94. * 'derive_from_parent' is true and the alignment is defined with this
  95. * featureloc_id.
  96. * @param $options
  97. * An associative array of options. Valid keys include:
  98. * - width: Indicate the number of bases to use per line. A new line will
  99. * be added after the specified number of bases on each line.
  100. * - is_html: Set to '1' if the sequence is meant to be displayed on a web
  101. * page. This will cause a <br> tag to separate lines of the FASTA sequence.
  102. * - derive_from_parent: Set to '1' if the sequence should be obtained from
  103. * the parent to which this feature is aligned.
  104. * - aggregate: Set to '1' if the sequence should only contain sub features,
  105. * excluding intro sub feature sequence. For example, set this option to
  106. * obtain just the coding sequence of an mRNA.
  107. * - upstream: An integer specifing the number of upstream bases to include
  108. * in the output.
  109. * - downstream: An integer specifying the number of downstream bases to
  110. * include in the output.
  111. * - sub_feature_types: Only include sub features (or child features) of
  112. * the types provided in the array.
  113. * - relationship_type: If a relationship name is provided (e.g. sequence_of)
  114. * then any sequences that are in relationships of this type with matched
  115. * sequences are also included.
  116. * - relationship_part: If a relationship is provided in the preceeding
  117. * argument then the rel_part must be either 'object' or 'subject' to
  118. * indicate which side of the relationship the matched features belong.
  119. *
  120. * @return
  121. * an array of matching sequence in the following keys for each sequence:
  122. * - types: an array of feature types that were used to derive
  123. * the sequence (e.g. from an aggregated sequence)
  124. * - upstream: the number of upstream bases included in the sequence
  125. * - downstream: the number of downstream bases included in the
  126. * sequence
  127. * - defline: the definintion line used to create a FASTA sequence
  128. * - residues: the residues
  129. * - featureloc_id: the featureloc_id if the sequences is from an
  130. * alignment
  131. *
  132. * @ingroup tripal_feature_api
  133. */
  134. function chado_get_feature_sequences($feature, $options) {
  135. // Default values for finding the feature.
  136. $feature_id = array_key_exists('feature_id', $feature) ? $feature['feature_id'] : 0;
  137. $parent_id = array_key_exists('parent_id', $feature) ? $feature['parent_id'] : 0;
  138. $featureloc_id = array_key_exists('featureloc_id', $feature) ? $feature['featureloc_id'] : 0;
  139. $feature_name = array_key_exists('name', $feature) ? $feature['name'] : '';
  140. // Default values for building the sequence.
  141. $num_bases_per_line = array_key_exists('width', $options) ? $options['width'] : 50;
  142. $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
  143. $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate'] : 0;
  144. $upstream = array_key_exists('upstream', $options) ? $options['upstream'] : 0;
  145. $downstream = array_key_exists('downstream', $options) ? $options['downstream'] : 0;
  146. $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types'] : array();
  147. $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type'] : '';
  148. $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part'] : '';
  149. $is_html = array_key_exists('is_html', $options) ? $options['is_html'] : 0;
  150. $is_txt = array_key_exists('is_txt', $options) ? $options['is_txt'] : 0;
  151. $is_raw = array_key_exists('is_raw', $options) ? $options['is_raw'] : 1;
  152. if (!$upstream) {
  153. $upstream = 0;
  154. }
  155. if (!$downstream) {
  156. $downstream = 0;
  157. }
  158. // Make sure the sub_features variable is an array.
  159. if (!is_array($sub_features)) {
  160. tripal_report_error('tripal_feature', TRIPAL_ERROR,
  161. "'sub_features' option must be an array for function chado_get_feature_sequences().",
  162. array()
  163. );
  164. return array();
  165. }
  166. // If a relationship was specified then retreive and the sequences that
  167. // have the given relationship and the recurse to extract the appropriate
  168. // sequence.
  169. if ($rel_part == "object" or $rel_part == "subject") {
  170. if ($rel_part == "subject") {
  171. $sql = '
  172. SELECT FO.feature_id, FO.name, FO.uniquename, CVTO.name as feature_type, O.genus, O.species
  173. FROM {feature} FS
  174. INNER JOIN {feature_relationship} FR ON FR.subject_id = FS.feature_id
  175. INNER JOIN {cvterm} CVTFR ON CVTFR.cvterm_id = FR.type_id
  176. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  177. INNER JOIN {cvterm} CVTO ON CVTO.cvterm_id = FO.type_id
  178. INNER JOIN {organism} O ON O.organism_id = FO.organism_id
  179. WHERE
  180. FS.feature_id = :feature_id AND
  181. CVTFR.name = :relationship
  182. ';
  183. $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship));
  184. }
  185. if ($rel_part == "object") {
  186. $sql = '
  187. SELECT FS.feature_id, FS.name, FS.uniquename, CVTO.name as feature_type, O.genus, O.species
  188. FROM {feature} FO
  189. INNER JOIN {feature_relationship} FR ON FR.object_id = FO.feature_id
  190. INNER JOIN {cvterm} CVTFR ON CVTFR.cvterm_id = FR.type_id
  191. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  192. INNER JOIN {cvterm} CVTO ON CVTO.cvterm_id = FS.type_id
  193. INNER JOIN {organism} O ON O.organism_id = FS.organism_id
  194. WHERE
  195. FO.feature_id = :feature_id AND
  196. CVTFR.name = :relationship
  197. ';
  198. $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship));
  199. }
  200. $sequences = '';
  201. while ($feature = $features->fetchObject()) {
  202. // Recurse and get the sequences for these in the relationship.
  203. if ($rel_part == "subject") {
  204. $defline = "$feature_name, $relationship, $feature->uniquename $feature->feature_type ($feature->genus $feature->species)";
  205. }
  206. if ($rel_part == "object") {
  207. $defline = "$feature->uniquename $feature->feature_type ($feature->genus $feature->species), $relationship, $feature_name";
  208. }
  209. return chado_get_feature_sequences(
  210. array(
  211. 'feature_id' => $feature->feature_id,
  212. 'name' => $defline,
  213. 'parent_id' => $parent_id,
  214. ),
  215. array(
  216. 'width' => $num_bases_per_line,
  217. 'derive_from_parent' => $derive_from_parent,
  218. 'aggregate' => $aggregate,
  219. 'upstream' => $upstream,
  220. 'downstream' => $downstream,
  221. 'sub_features' => $sub_features,
  222. )
  223. );
  224. }
  225. }
  226. // Prepare the queries we're going to use later during the render phase
  227. // This SQL statement uses conditionals in the select clause to handle
  228. // cases cases where the alignment is in the reverse direction and when
  229. // the upstream and downstream extensions go beyond the lenght of the
  230. // parent sequence.
  231. $parent_sql ='
  232. SELECT featureloc_id, srcname, srcfeature_id, strand, srctypename, typename,
  233. fmin, fmax, upstream, downstream, adjfmin, adjfmax,
  234. substring(residues from (cast(adjfmin as int4) + 1) for cast((upstream + (fmax - fmin) + downstream) as int4)) as residues,
  235. genus, species
  236. FROM (
  237. SELECT
  238. FL.featureloc_id, OF.name srcname, FL.srcfeature_id, FL.strand,
  239. OCVT.name as srctypename, SCVT.name as typename,
  240. FL.fmin, FL.fmax, OO.genus, OO.species,
  241. CASE
  242. WHEN FL.strand >= 0 THEN
  243. CASE
  244. WHEN FL.fmin - :upstream <= 0 THEN 0
  245. ELSE FL.fmin - :upstream
  246. END
  247. WHEN FL.strand < 0 THEN
  248. CASE
  249. WHEN FL.fmin - :downstream <= 0 THEN 0
  250. ELSE FL.fmin - :downstream
  251. END
  252. END as adjfmin,
  253. CASE
  254. WHEN FL.strand >= 0 THEN
  255. CASE
  256. WHEN FL.fmax + :downstream > OF.seqlen THEN OF.seqlen
  257. ELSE FL.fmax + :downstream
  258. END
  259. WHEN FL.strand < 0 THEN
  260. CASE
  261. WHEN FL.fmax + :upstream > OF.seqlen THEN OF.seqlen
  262. ELSE FL.fmax + :upstream
  263. END
  264. END as adjfmax,
  265. CASE
  266. WHEN FL.strand >= 0 THEN
  267. CASE
  268. WHEN FL.fmin - :upstream <= 0 THEN FL.fmin
  269. ELSE :upstream
  270. END
  271. ELSE
  272. CASE
  273. WHEN FL.fmax + :upstream > OF.seqlen THEN OF.seqlen - FL.fmax
  274. ELSE :upstream
  275. END
  276. END as upstream,
  277. CASE
  278. WHEN FL.strand >= 0 THEN
  279. CASE
  280. WHEN FL.fmax + :downstream > OF.seqlen THEN OF.seqlen - FL.fmax
  281. ELSE :downstream
  282. END
  283. ELSE
  284. CASE
  285. WHEN FL.fmin - :downstream <= 0 THEN FL.fmin
  286. ELSE :downstream
  287. END
  288. END as downstream,
  289. OF.residues
  290. FROM {featureloc} FL
  291. INNER JOIN {feature} SF on FL.feature_id = SF.feature_id
  292. INNER JOIN {cvterm} SCVT on SF.type_id = SCVT.cvterm_id
  293. INNER JOIN {feature} OF on FL.srcfeature_id = OF.feature_id
  294. INNER JOIN {cvterm} OCVT on OF.type_id = OCVT.cvterm_id
  295. INNER JOIN {organism} OO on OF.organism_id = OO.organism_id
  296. WHERE SF.feature_id = :feature_id and NOT (OF.residues = \'\' or OF.residues IS NULL)) as tbl1
  297. ';
  298. // This query is meant to get all of the sub features of any given
  299. // feature (arg #1) and order them as they appear on the reference
  300. // feature (arg #2).
  301. $sfsql = '
  302. SELECT SF.feature_id, CVT.name as type_name, SF.type_id
  303. FROM {feature_relationship} FR
  304. INNER JOIN {feature} SF ON SF.feature_id = FR.subject_id
  305. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = SF.type_id
  306. INNER JOIN {featureloc} FL ON FL.feature_id = FR.subject_id
  307. INNER JOIN {feature} PF ON PF.feature_id = FL.srcfeature_id
  308. WHERE FR.object_id = :feature_id and PF.feature_id = :srcfeature_id
  309. ORDER BY FL.fmin ASC
  310. ';
  311. // For counting the number of children.
  312. $fsql ='
  313. SELECT count(*) as num_children
  314. FROM {feature_relationship} FR
  315. INNER JOIN {feature} SF ON SF.feature_id = FR.subject_id
  316. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = SF.type_id
  317. INNER JOIN {featureloc} FL ON FL.feature_id = FR.subject_id
  318. INNER JOIN {feature} PF ON PF.feature_id = FL.srcfeature_id
  319. WHERE FR.object_id = :feature_id and PF.feature_id = :srcfeature_id
  320. ';
  321. // The array to be returned.
  322. $sequences = array();
  323. // If we need to get the sequence from the parent then do so now.
  324. if ($derive_from_parent) {
  325. // Execute the query to get the sequence from the parent.
  326. $parents = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => $downstream, ':feature_id' => $feature_id));
  327. while ($parent = $parents->fetchObject()) {
  328. // If the user specified a particular parent and this one doesn't
  329. // match then skip it.
  330. if ($parent_id and $parent_id != $parent->srcfeature_id) {
  331. continue;
  332. }
  333. // If the user specified a particular featureloc_id and this one
  334. // doesn't match then skip it.
  335. if ($featureloc_id and $featureloc_id != $parent->featureloc_id) {
  336. continue;
  337. }
  338. // Initialize the sequence for each parent.
  339. $seq = '';
  340. $notes = '';
  341. $types = array();
  342. // If we are to aggregate then we will ignore the feature returned
  343. // by the query above and rebuild it using the sub features.
  344. if ($aggregate) {
  345. // now get the sub features that are located on the parent.
  346. $children = chado_query($sfsql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id));
  347. $num_children = chado_query($fsql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id))->fetchField();
  348. // Iterate through the sub features and concat their sequences. They
  349. // should already be in order.
  350. $i = 0;
  351. $already_processed_children = array();
  352. while ($child = $children->fetchObject()) {
  353. // In some cases, a feature may be discontinuous (i.e. one feature
  354. // spread over several positions). In this case, the feature will
  355. // appear multiple times and we want to prevent addition of the
  356. // sequence multiple times. A simple check to make sure we haven't
  357. // seen the feature already should suffice.
  358. if (count($already_processed_children) > 0 and in_array($child->feature_id, $already_processed_children)){
  359. continue;
  360. }
  361. $already_processed_children[] = $child->feature_id;
  362. // If the callee has specified that only certain sub features should be
  363. // included then continue if this child is not one of those allowed
  364. // subfeatures.
  365. if (count($sub_features) > 0 and !in_array($child->type_name, $sub_features)) {
  366. $i++;
  367. continue;
  368. }
  369. // Keep up with the types.
  370. if (!in_array($child->type_name, $types)) {
  371. $types[] = $child->type_name;
  372. }
  373. // If the first sub feature we need to include the upstream bases.
  374. // First check if the feature is in the foward direction or the
  375. // reverse.
  376. if ($i == 0 and $parent->strand >= 0) { // forward direction
  377. // -------------------------- ref
  378. // ....----> ---->
  379. // up 1 2
  380. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  381. }
  382. elseif ($i == 0 and $parent->strand < 0) { // reverse direction
  383. // -------------------------- ref
  384. // ....<---- <----
  385. // down 1 2
  386. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  387. }
  388. // Next, if the last sub feature we need to include the downstream
  389. // bases. First check if the feature is in teh forward direction or
  390. // the reverse.
  391. elseif ($i == $num_children - 1 and $parent->strand >= 0) { // forward direction
  392. // -------------------------- ref
  393. // ----> ---->....
  394. // 1 2 down
  395. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  396. }
  397. elseif ($i == $num_children - 1 and $parent->strand < 0) { // reverse direction
  398. // -------------------------- ref
  399. // <---- <----....
  400. // 1 2 up
  401. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  402. }
  403. // For internal sub features we don't want upstream or downstream bases.
  404. else {
  405. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => 0, ':feature_id' => $child->feature_id));
  406. }
  407. while ($subseq = $q->fetchObject()) {
  408. // concatenate the sequences of all the sub features
  409. if ($subseq->srcfeature_id == $parent->srcfeature_id) {
  410. $seq .= $subseq->residues;
  411. }
  412. if ($subseq->upstream > 0 ) {
  413. $notes .= "Includes " . $subseq->upstream . " bases upstream. ";
  414. }
  415. if ($subseq->downstream > 0) {
  416. $notes .= "Includes " . $subseq->downstream . " bases downstream. ";
  417. }
  418. }
  419. $i++;
  420. }
  421. }
  422. // If this isn't an aggregate then use the parent residues.
  423. else {
  424. $seq = $parent->residues;
  425. if ($parent->upstream > 0) {
  426. $notes .= "Includes " . $parent->upstream . " bases upstream. ";
  427. }
  428. if ($parent->downstream > 0) {
  429. $notes .= "Includes " . $parent->downstream . " bases downstream. ";
  430. }
  431. }
  432. // Get the reverse compliment if feature is on the reverse strand.
  433. $dir = 'forward';
  434. $length = strlen($seq);
  435. if ($parent->strand < 0) {
  436. $seq = chado_reverse_compliment_sequence($seq);
  437. $dir = 'reverse';
  438. }
  439. // Now format for display.
  440. if ($is_html) {
  441. $seq = wordwrap($seq, $num_bases_per_line, "<br>", TRUE);
  442. }
  443. if ($is_txt) {
  444. $seq = wordwrap($seq, $num_bases_per_line, "\r\n", TRUE);
  445. }
  446. if (!$seq) {
  447. $notes .= "No sequence available.";
  448. }
  449. if (count($types) > 0) {
  450. $notes .= "Excludes all bases but those of type(s): " . implode(', ', $types) . ". " ;
  451. }
  452. // Construct the definition line for this feature. To construct the
  453. // defline we need a featureloc record, so we'll create one using
  454. // the information we have.
  455. $featureloc = new stdClass;
  456. $featureloc->feature_id = $feature;
  457. $featureloc->fmin = $parent->adjfmin;
  458. $featureloc->fmax = $parent->adjfmax;
  459. $featureloc->strand = $parent->strand;
  460. $featureloc->srcfeature_id = new stdClass;
  461. $featureloc->srcfeature_id->name = $parent->srcname;
  462. $featureloc->srcfeature_id->type_id = $parent->srctypename;
  463. $featureloc->srcfeature_id->organism_id = new stdClass;
  464. $featureloc->srcfeature_id->organism_id->genus = $parent->genus;
  465. $featureloc->srcfeature_id->organism_id->species = $parent->species;
  466. // Get a proper feature object.
  467. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  468. $defline = chado_get_fasta_defline($f, $notes, $featureloc, '', $length);
  469. $sequences[] = array(
  470. 'types' => $types,
  471. 'upstream' => $parent->upstream,
  472. 'downstream' => $parent->downstream,
  473. 'defline' => $defline,
  474. 'residues' => $seq,
  475. 'featureloc_id' => $parent->featureloc_id,
  476. 'length' => $length,
  477. );
  478. }
  479. }
  480. // If we are not getting the sequence from the parent sequence then
  481. // use what comes through from the feature record.
  482. else {
  483. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  484. $f = chado_expand_var($f, 'field', 'feature.residues');
  485. $residues = $f->residues;
  486. $length = strlen($residues);
  487. if ($is_html) {
  488. $residues = wordwrap($residues, $num_bases_per_line, "<br>", TRUE);
  489. }
  490. else {
  491. $residues = wordwrap($residues, $num_bases_per_line, "\r\n", TRUE);
  492. }
  493. // Get the definintion line for this feature.
  494. $defline = chado_get_fasta_defline($f, '', NULL, '', $length);
  495. // Add to the sequence array.
  496. $sequences[] = array(
  497. 'types' => $f->type_id->name,
  498. 'upstream' => 0,
  499. 'downstream' => 0,
  500. 'defline' => $defline,
  501. 'residues' => $residues,
  502. 'length' => $length,
  503. );
  504. }
  505. return $sequences;
  506. }
  507. /**
  508. * Retrieves the bulk sequences for a given feature.
  509. *
  510. * @param $options
  511. * An associative array of options for selecting a feature. Valid keys include:
  512. * - org_commonname: The common name of the organism for which sequences
  513. * should be retrieved
  514. * - genus: The genus of the organism for which sequences should be retrieved
  515. * - species: The species of the organism for which sequences should be
  516. * retrieved
  517. * - analysis_name: The name of an analysis to which sequences belong. Only
  518. * those that are associated with the analysis will be retrieved.
  519. * - type: The type of feature (a sequence ontology term).
  520. * - feature_name: the name of the feature. Can be an array of feature names.
  521. * - feature_uname: the uniquename of the feature. Can be an array of
  522. * feature unique names.
  523. * - upstream: An integer specifing the number of upstream bases to include
  524. * in the output
  525. * - downstream: An integer specifying the number of downstream bases to
  526. * include in the output.
  527. * - derive_from_parent: Set to '1' if the sequence should be obtained from
  528. * the parent to which this feature is aligned.
  529. * - aggregate: Set to '1' if the sequence should only contain sub features,
  530. * excluding intro sub feature sequence. For example, set this option to
  531. * obtain just the coding sequence of an mRNA.
  532. * - sub_feature_types: Only include sub features (or child features) of
  533. * the types provided in the array
  534. * - relationship_type: If a relationship name is provided (e.g. sequence_of)
  535. * then any sequences that are in relationships of this type with matched
  536. * sequences are also included
  537. * - relationship_part: If a relationship is provided in the preceeding
  538. * argument then the rel_part must be either 'object' or 'subject' to
  539. * indicate which side of the relationship the matched features belong
  540. * - width: Indicate the number of bases to use per line. A new line will
  541. * be added after the specified number of bases on each line.
  542. * - is_html: Set to '1' if the sequence is meant to be displayed on a
  543. * web page. This will cause a <br> tag to separate lines of the FASTA
  544. * sequence.
  545. * @return
  546. * Returns an array of sequences. The sequences will be in an array with the
  547. * following keys for each sequence:
  548. * 'types' => an array of feature types that were used to derive
  549. * the sequence (e.g. from an aggregated sequence)
  550. * 'upstream' => the number of upstream bases in the sequence
  551. * 'downstream' => the number of downstream bases in the sequence
  552. * 'defline' => the definintion line used to create a FASTA sequence
  553. * 'residues' => the residues
  554. * 'featureloc_id' => the featureloc_id if from an alignment
  555. *
  556. * @ingroup tripal_feature_api
  557. */
  558. function chado_get_bulk_feature_sequences($options) {
  559. // Default values for building the sequence
  560. $org_commonname = array_key_exists('org_commonname', $options) ? $options['org_commonname'] : '';
  561. $genus = array_key_exists('genus', $options) ? $options['genus'] : '';
  562. $species = array_key_exists('species', $options) ? $options['species'] : '';
  563. $analysis_name = array_key_exists('analysis_name', $options) ? $options['analysis_name'] : '';
  564. $type = array_key_exists('type', $options) ? $options['type'] : '';
  565. $feature_name = array_key_exists('feature_name', $options) ? $options['feature_name'] : '';
  566. $feature_uname = array_key_exists('feature_uname', $options) ? $options['feature_uname'] : '';
  567. $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
  568. $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate'] : 0;
  569. $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types'] : array();
  570. $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type'] : '';
  571. $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part'] : '';
  572. $num_bases_per_line = array_key_exists('width', $options) ? $options['width'] : 50;
  573. $upstream = array_key_exists('upstream', $options) ? $options['upstream'] : 0;
  574. $downstream = array_key_exists('downstream', $options) ? $options['downstream'] : 0;
  575. if (!$type and !$feature_name and !$genus) {
  576. print "Please provide a type, feature name or genus\n";
  577. return;
  578. }
  579. // Get the list of features.
  580. $vars = array();
  581. $sql = "
  582. SELECT DISTINCT F.feature_id, F.name, F.uniquename,
  583. O.genus, O.species, CVT.name as feature_type
  584. FROM {feature} F
  585. INNER JOIN {organism} O on O.organism_id = F.organism_id
  586. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  587. ";
  588. if ($analysis_name) {
  589. $sql .= "
  590. INNER JOIN {analysisfeature} AF on AF.feature_id = F.feature_id
  591. INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id
  592. ";
  593. }
  594. $sql .= "WHERE (1=1) ";
  595. if ($org_commonname) {
  596. $sql .= "AND O.common_name = :common_name ";
  597. $vars[':common_name'] = $org_commonname;
  598. }
  599. if ($genus) {
  600. $sql .= "AND O.genus = :genus ";
  601. $vars[':genus'] = $genus;
  602. }
  603. if ($species) {
  604. $sql .= "AND O.species = :species ";
  605. $vars[':species'] = $species;
  606. }
  607. if ($type) {
  608. $sql .= "AND CVT.name = :cvtname ";
  609. $vars[':cvtname'] = $type;
  610. }
  611. if ($feature_name) {
  612. if (is_array($feature_name)) {
  613. $sql .= "AND F.name IN (";
  614. foreach ($feature_name as $i => $fname) {
  615. $sql .= ":fname$i, ";
  616. $vars[":fname$i"] = $fname;
  617. }
  618. // Remove the trailing comma and close the parenthesis.
  619. $sql = substr($sql, 0, -2) . ")";
  620. }
  621. else {
  622. $sql .= "AND F.name = :fname";
  623. $vars[':fname'] = $feature_name;
  624. }
  625. }
  626. if ($feature_uname) {
  627. if (is_array($feature_uname)) {
  628. $sql .= "AND F.uniquename IN (";
  629. foreach ($feature_uname as $i => $funame) {
  630. $sql .= ":funame$i, ";
  631. $vars[":funame$i"] = $funame;
  632. }
  633. // Remove the trailing comma and close the parenthesis.
  634. $sql = substr($sql, 0, -2) . ")";
  635. }
  636. else {
  637. $sql .= "AND F.uniquename = :funame";
  638. $vars[':funame'] = $feature_uname;
  639. }
  640. }
  641. if ($analysis_name) {
  642. $sql .= "AND A.name = :aname";
  643. $vars[':aname'] = $analysis_name;
  644. }
  645. $num_bases_per_line = 50;
  646. $num_seqs = 0;
  647. $q = chado_query($sql, $vars);
  648. $sequences = array();
  649. while ($feature = $q->fetchObject()) {
  650. // get the sequences
  651. $seqs = chado_get_feature_sequences(array('feature_id' => $feature->feature_id), $options);
  652. $sequences = array_merge($sequences, $seqs);
  653. $num_seqs++;
  654. }
  655. return $sequences;
  656. }
  657. /**
  658. * Returns a definition line that can be used in a FASTA file.
  659. *
  660. * @param $feature
  661. * A single feature object containing all the fields from the chado.feature
  662. * table. Best case is to provide an object generated by the
  663. * chado_generate_var() function.
  664. * @param $notes
  665. * Optional: additional notes to be added to the definition line.
  666. * @param $featureloc
  667. * Optional: a single featureloc object generated using chado_generate_var
  668. * that contains a record from the chado.featureloc table. Provide this if the
  669. * sequence was obtained by using the alignment rather than from the
  670. * feature.residues column.
  671. * @param $type
  672. * Optional: the type of sequence. By default the feature type is used.
  673. * @param $length
  674. * Optional: the length of the sequence.
  675. *
  676. * @return
  677. * A string of the format: uniquename|name|type|feature_id
  678. * or if an alignment: srcfeature_name:fmin..fmax[+-]; alignment of
  679. * uniquename|name|type|feature_id.
  680. *
  681. * @ingroup tripal_feature_api
  682. */
  683. function chado_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $type = '', $length = 0) {
  684. // Make sure the featureloc object has the srcfeature if not, then add it.
  685. if ($featureloc) {
  686. if (!is_object($featureloc->srcfeature_id)) {
  687. $featureloc->srcfeature_id = chado_generate_var('feature', array('feature_id' => $featureloc->srcfeature_id));
  688. }
  689. if (!is_object($featureloc->srcfeature_id->organism_id)) {
  690. $featureloc->srcfeature_id->organism_id = chado_generate_var('organism', array('organism_id' => $featureloc->srcfeature_id->organism_id));
  691. }
  692. }
  693. // Make sure the feature object has the organism if not, then add it.
  694. if (!is_object($feature->organism_id)) {
  695. $feature->organism_id = chado_generate_var('organism', array('organism_id' => $feature->organism_id));
  696. }
  697. // If a type is not provided then use the default type.
  698. if (!$type) {
  699. $type = $feature->type_id->name;
  700. }
  701. // Construct the definition line.
  702. $defline = $feature->uniquename . " " .
  703. 'ID=' . $feature->uniquename . "|" .
  704. 'Name=' . $feature->name . "|" .
  705. 'organism=' . $feature->organism_id->genus . " " . $feature->organism_id->species . "|" .
  706. 'type=' . $type . '|';
  707. if ($length > 0) {
  708. $defline .= "length=" . $length . "bp|";
  709. }
  710. if ($featureloc) {
  711. $defline .= "location=Sequence derived from alignment at " . chado_get_location_string($featureloc);
  712. $defline .= " (" . $featureloc->srcfeature_id->organism_id->genus . " " . $featureloc->srcfeature_id->organism_id->species . ")|";
  713. }
  714. if ($notes) {
  715. $defline .= "Notes=$notes|";
  716. }
  717. $defline = substr($defline, 0, -1); // remove the trailing |
  718. return $defline;
  719. }
  720. /**
  721. * Returns a string representing a feature location in an alignment.
  722. *
  723. * @param $featureloc
  724. * A single featureloc object generated using chado_generate_var that
  725. * contains a record from the chado.featureloc table.
  726. *
  727. * @return
  728. * A string of the format: uniquename:featurelocmin..featurelocmax.strand
  729. *
  730. * @ingroup tripal_feature_api
  731. */
  732. function chado_get_location_string($featureloc) {
  733. $feature = $featureloc->feature_id;
  734. $strand = '';
  735. if ($featureloc->strand == 1) {
  736. $strand = '+';
  737. }
  738. elseif ($featureloc->strand == -1) {
  739. $strand = '-';
  740. }
  741. return $featureloc->srcfeature_id->name . ":" . ($featureloc->fmin + 1) . ".." . $featureloc->fmax . $strand;
  742. }