tripal_chado.feature.api.inc 32 KB

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