tripal_chado.feature.api.inc 37 KB

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