tripal_chado.feature.api.inc 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. <?php
  2. /**
  3. * @file
  4. * Provides an application programming interface (API) for working with features
  5. */
  6. /**
  7. * @defgroup tripal_feature_api Chado Feature
  8. * @ingroup tripal_chado_api
  9. * @{
  10. * @}
  11. */
  12. /**
  13. * Used for autocomplete in forms for identifying for publications.
  14. *
  15. * @param $field
  16. * The field in the publication to search on.
  17. * @param $string
  18. * The string to search for.
  19. *
  20. * @return
  21. * A json array of terms that begin with the provided string.
  22. *
  23. * @ingroup tripal_feature_api
  24. */
  25. function chado_autocomplete_feature($string = '') {
  26. $items = array();
  27. $sql = "
  28. SELECT
  29. F.feature_id, F.uniquename, F.name,
  30. O.genus, O,species,
  31. CVT.name as type
  32. FROM {feature} F
  33. INNER JOIN {organism} O ON O.organism_id = F.organism_id
  34. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = F.type_id
  35. WHERE lower(F.uniquename) like lower(:str)
  36. ORDER by F.uniquename
  37. LIMIT 25 OFFSET 0
  38. ";
  39. $features = chado_query($sql, array(':str' => $string . '%'));
  40. while ($feature = $features->fetchObject()) {
  41. $key = "$feature->uniquename [id: $feature->feature_id]";
  42. $items[$key] = "$feature->uniquename ($feature->name, $feature->type, $feature->genus $feature->species)";
  43. }
  44. drupal_json_output($items);
  45. }
  46. /**
  47. * Performs a reverse compliment of a nucleotide sequence.
  48. *
  49. * @param $sequence
  50. * The nucelotide sequence.
  51. *
  52. * @return
  53. * an upper-case reverse complemented sequence.
  54. *
  55. * @ingroup tripal_feature_api
  56. */
  57. function chado_reverse_compliment_sequence($sequence) {
  58. $seq = strtoupper($sequence);
  59. $seq = strrev($seq);
  60. $seq = str_replace("A", "t", $seq);
  61. $seq = str_replace("T", "a", $seq);
  62. $seq = str_replace("G", "c", $seq);
  63. $seq = str_replace("C", "g", $seq);
  64. $seq = str_replace("Y", "r", $seq);
  65. $seq = str_replace("R", "y", $seq);
  66. $seq = str_replace("W", "w", $seq);
  67. $seq = str_replace("S", "s", $seq);
  68. $seq = str_replace("K", "m", $seq);
  69. $seq = str_replace("M", "k", $seq);
  70. $seq = str_replace("D", "h", $seq);
  71. $seq = str_replace("V", "b", $seq);
  72. $seq = str_replace("H", "d", $seq);
  73. $seq = str_replace("B", "v", $seq);
  74. return strtoupper($seq);
  75. }
  76. /**
  77. * Retrieves the sequences for a given feature.
  78. *
  79. * If a feature has multiple alignments or multiple relationships then
  80. * multiple sequences will be returned.
  81. *
  82. * @param $feature
  83. * An associative array describing the feature. Valid keys include:
  84. * - feature_id: The feature_id of the feature for which the sequence will
  85. * be retrieved.
  86. * - name: The feature name. This will appear on the FASTA definition line.
  87. * - parent_id: (optional) only retrieve a sequence if 'derive_from_parent'
  88. * is true and the parent matches this ID.
  89. * - featureloc_id: (optional) only retrieve a sequence if
  90. * 'derive_from_parent' is true and the alignment is defined with this
  91. * 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 chado_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 chado_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 chado_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. $already_processed_children = array();
  348. while ($child = $children->fetchObject()) {
  349. // In some cases, a feature may be discontinuous (i.e. one feature
  350. // spread over several positions). In this case, the feature will
  351. // appear multiple times and we want to prevent addition of the
  352. // sequence multiple times. A simple check to make sure we haven't
  353. // seen the feature already should suffice.
  354. if (count($already_processed_children) > 0 and in_array($child->feature_id, $already_processed_children)){
  355. continue;
  356. }
  357. $already_processed_children[] = $child->feature_id;
  358. // If the callee has specified that only certain sub features should be
  359. // included then continue if this child is not one of those allowed
  360. // subfeatures.
  361. if (count($sub_features) > 0 and !in_array($child->type_name, $sub_features)) {
  362. $i++;
  363. continue;
  364. }
  365. // Keep up with the types.
  366. if (!in_array($child->type_name, $types)) {
  367. $types[] = $child->type_name;
  368. }
  369. // If the first sub feature we need to include the upstream bases.
  370. // First check if the feature is in the foward direction or the
  371. // reverse.
  372. if ($i == 0 and $parent->strand >= 0) { // forward direction
  373. // -------------------------- ref
  374. // ....----> ---->
  375. // up 1 2
  376. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  377. }
  378. elseif ($i == 0 and $parent->strand < 0) { // reverse direction
  379. // -------------------------- ref
  380. // ....<---- <----
  381. // down 1 2
  382. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  383. }
  384. // Next, if the last sub feature we need to include the downstream
  385. // bases. First check if the feature is in teh forward direction or
  386. // the reverse.
  387. elseif ($i == $num_children - 1 and $parent->strand >= 0) { // forward direction
  388. // -------------------------- ref
  389. // ----> ---->....
  390. // 1 2 down
  391. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  392. }
  393. elseif ($i == $num_children - 1 and $parent->strand < 0) { // reverse direction
  394. // -------------------------- ref
  395. // <---- <----....
  396. // 1 2 up
  397. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  398. }
  399. // For internal sub features we don't want upstream or downstream bases.
  400. else {
  401. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => 0, ':feature_id' => $child->feature_id));
  402. }
  403. while ($subseq = $q->fetchObject()) {
  404. // concatenate the sequences of all the sub features
  405. if ($subseq->srcfeature_id == $parent->srcfeature_id) {
  406. $seq .= $subseq->residues;
  407. }
  408. if ($subseq->upstream > 0 ) {
  409. $notes .= "Includes " . $subseq->upstream . " bases upstream. ";
  410. }
  411. if ($subseq->downstream > 0) {
  412. $notes .= "Includes " . $subseq->downstream . " bases downstream. ";
  413. }
  414. }
  415. $i++;
  416. }
  417. }
  418. // If this isn't an aggregate then use the parent residues.
  419. else {
  420. $seq = $parent->residues;
  421. if ($parent->upstream > 0) {
  422. $notes .= "Includes " . $parent->upstream . " bases upstream. ";
  423. }
  424. if ($parent->downstream > 0) {
  425. $notes .= "Includes " . $parent->downstream . " bases downstream. ";
  426. }
  427. }
  428. // Get the reverse compliment if feature is on the reverse strand.
  429. $dir = 'forward';
  430. $length = strlen($seq);
  431. if ($parent->strand < 0) {
  432. $seq = chado_reverse_compliment_sequence($seq);
  433. $dir = 'reverse';
  434. }
  435. // Now format for display.
  436. if ($is_html) {
  437. $seq = wordwrap($seq, $num_bases_per_line, "<br>", TRUE);
  438. }
  439. if ($is_txt) {
  440. $seq = wordwrap($seq, $num_bases_per_line, "\r\n", TRUE);
  441. }
  442. if (!$seq) {
  443. $notes .= "No sequence available.";
  444. }
  445. if (count($types) > 0) {
  446. $notes .= "Excludes all bases but those of type(s): " . implode(', ', $types) . ". " ;
  447. }
  448. // Construct the definition line for this feature. To construct the
  449. // defline we need a featureloc record, so we'll create one using
  450. // the information we have.
  451. $featureloc = new stdClass;
  452. $featureloc->feature_id = $feature;
  453. $featureloc->fmin = $parent->adjfmin;
  454. $featureloc->fmax = $parent->adjfmax;
  455. $featureloc->strand = $parent->strand;
  456. $featureloc->srcfeature_id = new stdClass;
  457. $featureloc->srcfeature_id->name = $parent->srcname;
  458. $featureloc->srcfeature_id->type_id = $parent->srctypename;
  459. $featureloc->srcfeature_id->organism_id = new stdClass;
  460. $featureloc->srcfeature_id->organism_id->genus = $parent->genus;
  461. $featureloc->srcfeature_id->organism_id->species = $parent->species;
  462. // Get a proper feature object.
  463. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  464. $defline = chado_get_fasta_defline($f, $notes, $featureloc, '', $length);
  465. $sequences[] = array(
  466. 'types' => $types,
  467. 'upstream' => $parent->upstream,
  468. 'downstream' => $parent->downstream,
  469. 'defline' => $defline,
  470. 'residues' => $seq,
  471. 'featureloc_id' => $parent->featureloc_id,
  472. 'length' => $length,
  473. );
  474. }
  475. }
  476. // If we are not getting the sequence from the parent sequence then
  477. // use what comes through from the feature record.
  478. else {
  479. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  480. $f = chado_expand_var($f, 'field', 'feature.residues');
  481. $residues = $f->residues;
  482. $length = strlen($residues);
  483. if ($is_html) {
  484. $residues = wordwrap($residues, $num_bases_per_line, "<br>", TRUE);
  485. }
  486. else {
  487. $residues = wordwrap($residues, $num_bases_per_line, "\r\n", TRUE);
  488. }
  489. // Get the definintion line for this feature.
  490. $defline = chado_get_fasta_defline($f, '', NULL, '', $length);
  491. // Add to the sequence array.
  492. $sequences[] = array(
  493. 'types' => $f->type_id->name,
  494. 'upstream' => 0,
  495. 'downstream' => 0,
  496. 'defline' => $defline,
  497. 'residues' => $residues,
  498. 'length' => $length,
  499. );
  500. }
  501. return $sequences;
  502. }
  503. /**
  504. * Retrieves the bulk sequences for a given feature.
  505. *
  506. * @param $options
  507. * An associative array of options for selecting a feature. Valid keys include:
  508. * - org_commonname: The common name of the organism for which sequences
  509. * should be retrieved
  510. * - genus: The genus of the organism for which sequences should be retrieved
  511. * - species: The species of the organism for which sequences should be
  512. * retrieved
  513. * - analysis_name: The name of an analysis to which sequences belong. Only
  514. * those that are associated with the analysis will be retrieved.
  515. * - type: The type of feature (a sequence ontology term).
  516. * - feature_name: the name of the feature. Can be an array of feature names.
  517. * - feature_uname: the uniquename of the feature. Can be an array of
  518. * feature unique names.
  519. * - upstream: An integer specifing the number of upstream bases to include
  520. * in the output
  521. * - downstream: An integer specifying the number of downstream bases to
  522. * include in the output.
  523. * - derive_from_parent: Set to '1' if the sequence should be obtained from
  524. * the parent to which this feature is aligned.
  525. * - aggregate: Set to '1' if the sequence should only contain sub features,
  526. * excluding intro sub feature sequence. For example, set this option to
  527. * obtain just the coding sequence of an mRNA.
  528. * - sub_feature_types: Only include sub features (or child features) of
  529. * the types provided in the array
  530. * - relationship_type: If a relationship name is provided (e.g. sequence_of)
  531. * then any sequences that are in relationships of this type with matched
  532. * sequences are also included
  533. * - relationship_part: If a relationship is provided in the preceeding
  534. * argument then the rel_part must be either 'object' or 'subject' to
  535. * indicate which side of the relationship the matched features belong
  536. * - width: Indicate the number of bases to use per line. A new line will
  537. * be added after the specified number of bases on each line.
  538. * - is_html: Set to '1' if the sequence is meant to be displayed on a
  539. * web page. This will cause a <br> tag to separate lines of the FASTA
  540. * sequence.
  541. * @return
  542. * Returns an array of sequences. The sequences will be in an array with the
  543. * following keys for each sequence:
  544. * 'types' => an array of feature types that were used to derive
  545. * the sequence (e.g. from an aggregated sequence)
  546. * 'upstream' => the number of upstream bases in the sequence
  547. * 'downstream' => the number of downstream bases in the sequence
  548. * 'defline' => the definintion line used to create a FASTA sequence
  549. * 'residues' => the residues
  550. * 'featureloc_id' => the featureloc_id if from an alignment
  551. *
  552. * @ingroup tripal_feature_api
  553. */
  554. function chado_get_bulk_feature_sequences($options) {
  555. // Default values for building the sequence
  556. $org_commonname = array_key_exists('org_commonname', $options) ? $options['org_commonname'] : '';
  557. $genus = array_key_exists('genus', $options) ? $options['genus'] : '';
  558. $species = array_key_exists('species', $options) ? $options['species'] : '';
  559. $analysis_name = array_key_exists('analysis_name', $options) ? $options['analysis_name'] : '';
  560. $type = array_key_exists('type', $options) ? $options['type'] : '';
  561. $feature_name = array_key_exists('feature_name', $options) ? $options['feature_name'] : '';
  562. $feature_uname = array_key_exists('feature_uname', $options) ? $options['feature_uname'] : '';
  563. $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
  564. $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate'] : 0;
  565. $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types'] : array();
  566. $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type'] : '';
  567. $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part'] : '';
  568. $num_bases_per_line = array_key_exists('width', $options) ? $options['width'] : 50;
  569. $upstream = array_key_exists('upstream', $options) ? $options['upstream'] : 0;
  570. $downstream = array_key_exists('downstream', $options) ? $options['downstream'] : 0;
  571. if (!$type and !$feature_name and !$genus) {
  572. print "Please provide a type, feature name or genus\n";
  573. return;
  574. }
  575. // Get the list of features.
  576. $vars = array();
  577. $sql = "
  578. SELECT DISTINCT F.feature_id, F.name, F.uniquename,
  579. O.genus, O.species, CVT.name as feature_type
  580. FROM {feature} F
  581. INNER JOIN {organism} O on O.organism_id = F.organism_id
  582. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  583. ";
  584. if ($analysis_name) {
  585. $sql .= "
  586. INNER JOIN {analysisfeature} AF on AF.feature_id = F.feature_id
  587. INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id
  588. ";
  589. }
  590. $sql .= "WHERE (1=1) ";
  591. if ($org_commonname) {
  592. $sql .= "AND O.common_name = :common_name ";
  593. $vars[':common_name'] = $org_commonname;
  594. }
  595. if ($genus) {
  596. $sql .= "AND O.genus = :genus ";
  597. $vars[':genus'] = $genus;
  598. }
  599. if ($species) {
  600. $sql .= "AND O.species = :species ";
  601. $vars[':species'] = $species;
  602. }
  603. if ($type) {
  604. $sql .= "AND CVT.name = :cvtname ";
  605. $vars[':cvtname'] = $type;
  606. }
  607. if ($feature_name) {
  608. if (is_array($feature_name)) {
  609. $sql .= "AND F.name IN (";
  610. foreach ($feature_name as $i => $fname) {
  611. $sql .= ":fname$i, ";
  612. $vars[":fname$i"] = $fname;
  613. }
  614. // Remove the trailing comma and close the parenthesis.
  615. $sql = substr($sql, 0, -2) . ")";
  616. }
  617. else {
  618. $sql .= "AND F.name = :fname";
  619. $vars[':fname'] = $feature_name;
  620. }
  621. }
  622. if ($feature_uname) {
  623. if (is_array($feature_uname)) {
  624. $sql .= "AND F.uniquename IN (";
  625. foreach ($feature_uname as $i => $funame) {
  626. $sql .= ":funame$i, ";
  627. $vars[":funame$i"] = $funame;
  628. }
  629. // Remove the trailing comma and close the parenthesis.
  630. $sql = substr($sql, 0, -2) . ")";
  631. }
  632. else {
  633. $sql .= "AND F.uniquename = :funame";
  634. $vars[':funame'] = $feature_uname;
  635. }
  636. }
  637. if ($analysis_name) {
  638. $sql .= "AND A.name = :aname";
  639. $vars[':aname'] = $analysis_name;
  640. }
  641. $num_bases_per_line = 50;
  642. $num_seqs = 0;
  643. $q = chado_query($sql, $vars);
  644. $sequences = array();
  645. while ($feature = $q->fetchObject()) {
  646. // get the sequences
  647. $seqs = chado_get_feature_sequences(array('feature_id' => $feature->feature_id), $options);
  648. $sequences = array_merge($sequences, $seqs);
  649. $num_seqs++;
  650. }
  651. return $sequences;
  652. }
  653. /**
  654. * Returns a definition line that can be used in a FASTA file.
  655. *
  656. * @param $feature
  657. * A single feature object containing all the fields from the chado.feature
  658. * table. Best case is to provide an object generated by the
  659. * chado_generate_var() function.
  660. * @param $notes
  661. * Optional: additional notes to be added to the definition line.
  662. * @param $featureloc
  663. * Optional: a single featureloc object generated using chado_generate_var
  664. * that contains a record from the chado.featureloc table. Provide this if the
  665. * sequence was obtained by using the alignment rather than from the
  666. * feature.residues column.
  667. * @param $type
  668. * Optional: the type of sequence. By default the feature type is used.
  669. * @param $length
  670. * Optional: the length of the sequence.
  671. *
  672. * @return
  673. * A string of the format: uniquename|name|type|feature_id
  674. * or if an alignment: srcfeature_name:fmin..fmax[+-]; alignment of
  675. * uniquename|name|type|feature_id.
  676. *
  677. * @ingroup tripal_feature_api
  678. */
  679. function chado_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $type = '', $length = 0) {
  680. // Make sure the featureloc object has the srcfeature if not, then add it.
  681. if ($featureloc) {
  682. if (!is_object($featureloc->srcfeature_id)) {
  683. $featureloc->srcfeature_id = chado_generate_var('feature', array('feature_id' => $featureloc->srcfeature_id));
  684. }
  685. if (!is_object($featureloc->srcfeature_id->organism_id)) {
  686. $featureloc->srcfeature_id->organism_id = chado_generate_var('organism', array('organism_id' => $featureloc->srcfeature_id->organism_id));
  687. }
  688. }
  689. // Make sure the feature object has the organism if not, then add it.
  690. if (!is_object($feature->organism_id)) {
  691. $feature->organism_id = chado_generate_var('organism', array('organism_id' => $feature->organism_id));
  692. }
  693. // If a type is not provided then use the default type.
  694. if (!$type) {
  695. $type = $feature->type_id->name;
  696. }
  697. // Construct the definition line.
  698. $defline = $feature->uniquename . " " .
  699. 'ID=' . $feature->uniquename . "|" .
  700. 'Name=' . $feature->name . "|" .
  701. 'organism=' . $feature->organism_id->genus . " " . $feature->organism_id->species . "|" .
  702. 'type=' . $type . '|';
  703. if ($length > 0) {
  704. $defline .= "length=" . $length . "bp|";
  705. }
  706. if ($featureloc) {
  707. $defline .= "location=Sequence derived from alignment at " . chado_get_location_string($featureloc);
  708. $defline .= " (" . $featureloc->srcfeature_id->organism_id->genus . " " . $featureloc->srcfeature_id->organism_id->species . ")|";
  709. }
  710. if ($notes) {
  711. $defline .= "Notes=$notes|";
  712. }
  713. $defline = substr($defline, 0, -1); // remove the trailing |
  714. return $defline;
  715. }
  716. /**
  717. * Returns a string representing a feature location in an alignment.
  718. *
  719. * @param $featureloc
  720. * A single featureloc object generated using chado_generate_var that
  721. * contains a record from the chado.featureloc table.
  722. *
  723. * @return
  724. * A string of the format: uniquename:featurelocmin..featurelocmax.strand
  725. *
  726. * @ingroup tripal_feature_api
  727. */
  728. function chado_get_location_string($featureloc) {
  729. $feature = $featureloc->feature_id;
  730. $strand = '';
  731. if ($featureloc->strand == 1) {
  732. $strand = '+';
  733. }
  734. elseif ($featureloc->strand == -1) {
  735. $strand = '-';
  736. }
  737. return $featureloc->srcfeature_id->name . ":" . ($featureloc->fmin + 1) . ".." . $featureloc->fmax . $strand;
  738. }
  739. /**
  740. * Quickly retrieves relationships for a feature.
  741. *
  742. * Using the chado_expand_var function to retrieve a set
  743. * of relationships can be very slow, especialy if there are many relationships.
  744. * This function is intended to help speed up the retrieval of relationships
  745. * by only retrieving the base information for the relationship and returning
  746. * an array.
  747. *
  748. * @param $feature
  749. * The feature object
  750. * @return
  751. * An array with two objects
  752. *
  753. * @ingroup tripal_feature_api
  754. */
  755. function chado_get_feature_relationships($feature) {
  756. // Expand the feature object to include the feature relationships.
  757. $options = array(
  758. 'return_array' => 1,
  759. 'order_by' => array('rank' => 'ASC'),
  760. // We don't want to fully recurse we only need information about the
  761. // relationship type and the object and subject features (including feature
  762. // type and organism).
  763. 'include_fk' => array(
  764. 'type_id' => 1,
  765. 'object_id' => array(
  766. 'type_id' => 1,
  767. 'organism_id' => 1
  768. ),
  769. 'subject_id' => array(
  770. 'type_id' => 1,
  771. 'organism_id' => 1
  772. ),
  773. ),
  774. );
  775. $feature = chado_expand_var($feature, 'table', 'feature_relationship', $options);
  776. // Get the subject relationships.
  777. $srelationships = $feature->feature_relationship->subject_id;
  778. $orelationships = $feature->feature_relationship->object_id;
  779. // Get alignment as child. The $feature->featureloc element
  780. // is already populated from the alignment preprocess function.
  781. $options = array(
  782. 'return_array' => 1,
  783. 'include_fk' => array(
  784. 'srcfeature_id' => 1,
  785. 'feature_id' => 1,
  786. ),
  787. );
  788. $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
  789. $cfeaturelocs = $feature->featureloc->feature_id;
  790. if (!$cfeaturelocs) {
  791. $cfeaturelocs = array();
  792. }
  793. elseif (!is_array($cfeaturelocs)) {
  794. $cfeaturelocs = array($cfeaturelocs);
  795. }
  796. // Prepare the SQL statement to get the featureloc for the
  797. // feature in the relationships.
  798. $flrels_sql = "
  799. SELECT
  800. FL.featureloc_id, F.name as srcfeature_name, FL.srcfeature_id,
  801. FL.feature_id, FL.fmin, FL.fmax, FL.strand, FL.phase
  802. FROM {featureloc} FL
  803. INNER JOIN {feature} F ON F.feature_id = FL.srcfeature_id
  804. WHERE FL.feature_id = :feature_id and FL.srcfeature_id = :srcfeature_id
  805. ";
  806. // Combine both object and subject relationshisp into a single array.
  807. $relationships = array();
  808. $relationships['object'] = array();
  809. $relationships['subject'] = array();
  810. // Iterate through the object relationships.
  811. if ($orelationships) {
  812. foreach ($orelationships as $relationship) {
  813. $rel = new stdClass();
  814. // Get locations where the child feature and this feature overlap with the
  815. // same landmark feature.
  816. $rel->child_featurelocs = array();
  817. foreach ($cfeaturelocs as $featureloc) {
  818. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->subject_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  819. while ($loc = $res->fetchObject()) {
  820. // Add in the node id of the src feature if it exists and save this
  821. // location.
  822. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  823. $loc->nid = $featureloc->srcfeature_id->nid;
  824. }
  825. $rel->child_featurelocs[] = $loc;
  826. }
  827. }
  828. $rel->record = $relationship;
  829. // Get the relationship and child types.
  830. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  831. $child_type = $relationship->subject_id->type_id->name;
  832. // get the node id of the subject
  833. // $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  834. // $n = db_query($sql, array(':feature_id' => $relationship->subject_id->feature_id))->fetchObject();
  835. // if ($n) {
  836. // $rel->record->nid = $n->nid;
  837. // }
  838. if (!array_key_exists($rel_type, $relationships['object'])) {
  839. $relationships['object'][$rel_type] = array();
  840. }
  841. if (!array_key_exists($child_type, $relationships['object'][$rel_type])) {
  842. $relationships['object'][$rel_type][$child_type] = array();
  843. }
  844. $relationships['object'][$rel_type][$child_type][] = $rel;
  845. }
  846. }
  847. // Now add in the subject relationships.
  848. if ($srelationships) {
  849. foreach ($srelationships as $relationship) {
  850. $rel = new stdClass();
  851. // Get locations where this feature overlaps with the parent.
  852. $rel->parent_featurelocs = array();
  853. foreach ($cfeaturelocs as $featureloc) {
  854. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->object_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  855. while ($loc = $res->fetchObject()) {
  856. // Add in the node id of the src feature if it exists and save this
  857. // location.
  858. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  859. $loc->nid = $featureloc->srcfeature_id->nid;
  860. }
  861. $rel->parent_featurelocs[] = $loc;
  862. }
  863. }
  864. $rel->record = $relationship;
  865. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  866. $parent_type = $relationship->object_id->type_id->name;
  867. // // get the node id of the subject
  868. // $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  869. // $n = db_query($sql, array(':feature_id' => $relationship->object_id->feature_id))->fetchObject();
  870. // if ($n) {
  871. // $rel->record->nid = $n->nid;
  872. // }
  873. if (!array_key_exists($rel_type, $relationships['subject'])) {
  874. $relationships['subject'][$rel_type] = array();
  875. }
  876. if (!array_key_exists($parent_type, $relationships['subject'][$rel_type])) {
  877. $relationships['subject'][$rel_type][$parent_type] = array();
  878. }
  879. $relationships['subject'][$rel_type][$parent_type][] = $rel;
  880. }
  881. }
  882. return $relationships;
  883. }
  884. /**
  885. *
  886. * @param unknown $feature_id
  887. * @param unknown $featurelocs
  888. * @return multitype:|Ambigous <multitype:, an>
  889. */
  890. function chado_get_featureloc_sequences($feature_id, $featurelocs) {
  891. // if we don't have any featurelocs then no point in continuing
  892. if (!$featurelocs) {
  893. return array();
  894. }
  895. // Get the list of relationships (including any aggregators) and iterate
  896. // through each one to find information needed to color-code the reference
  897. // sequence.
  898. $relationships = _chado_feature_get_aggregate_relationships($feature_id);
  899. if (!$relationships) {
  900. return array();
  901. }
  902. // Iterate through each of the realtionships features and get their
  903. // locations.
  904. foreach ($relationships as $rindex => $rel) {
  905. // Get the featurelocs for each of the relationship features.
  906. $rel_featurelocs = chado_get_featurelocs($rel->subject_id, 'as_child', 0);
  907. foreach ($rel_featurelocs as $rfindex => $rel_featureloc) {
  908. // Keep track of this unique source feature.
  909. $src = $rel_featureloc->src_feature_id . "-" . $rel_featureloc->src_cvterm_id;
  910. // Copy over the results to the relationship object. Since there can
  911. // be more than one feature location for each relationship feature we
  912. // use the '$src' variable to keep track of these.
  913. $rel->featurelocs = new stdClass();
  914. $rel->featurelocs->$src = new stdClass();
  915. $rel->featurelocs->$src->src_uniquename = $rel_featureloc->src_uniquename;
  916. $rel->featurelocs->$src->src_cvterm_id = $rel_featureloc->src_cvterm_id;
  917. $rel->featurelocs->$src->src_cvname = $rel_featureloc->src_cvname;
  918. $rel->featurelocs->$src->fmin = $rel_featureloc->fmin;
  919. $rel->featurelocs->$src->fmax = $rel_featureloc->fmax;
  920. $rel->featurelocs->$src->src_name = $rel_featureloc->src_name;
  921. // keep track of the individual parts for each relationship
  922. $start = $rel->featurelocs->$src->fmin;
  923. $end = $rel->featurelocs->$src->fmax;
  924. $type = $rel->subject_type;
  925. $rel_locs[$src]['parts'][$start][$type]['start'] = $start;
  926. $rel_locs[$src]['parts'][$start][$type]['end'] = $end;
  927. $rel_locs[$src]['parts'][$start][$type]['type'] = $type;
  928. }
  929. }
  930. // The featurelocs array provided to the function contains the locations
  931. // where this feature is found. We want to get the sequence for each
  932. // location and then annotate it with the parts found from the relationships
  933. // locations determiend above.
  934. $floc_sequences = array();
  935. foreach ($featurelocs as $featureloc) {
  936. // build the src name so we can keep track of the different parts for each feature
  937. $src = $featureloc->srcfeature_id->feature_id . "-" . $featureloc->srcfeature_id->type_id->cvterm_id;
  938. // orient the parts to the beginning of the feature sequence
  939. if (!empty($rel_locs[$src]['parts'])) {
  940. $parts = $rel_locs[$src]['parts'];
  941. $rparts = array(); // we will fill this up if we're on the reverse strand
  942. foreach ($parts as $start => $types) {
  943. foreach ($types as $type_name => $type) {
  944. if ($featureloc->strand >= 0) {
  945. // this is on the forward strand. We need to convert the start on the src feature to the
  946. // start on this feature's sequence
  947. $parts[$start][$type_name]['start'] = $parts[$start][$type_name]['start'] - $featureloc->fmin;
  948. $parts[$start][$type_name]['end'] = $parts[$start][$type_name]['end'] - $featureloc->fmin;
  949. $parts[$start][$type_name]['type'] = $type_name;
  950. }
  951. else {
  952. // this is on the reverse strand. We need to swap the start and stop and calculate from the
  953. // begining of the reverse sequence
  954. $size = ($featureloc->fmax - $featureloc->fmin);
  955. $start_orig = $parts[$start][$type_name]['start'];
  956. $end_orig = $parts[$start][$type_name]['end'];
  957. $new_start = $size - ($end_orig - $featureloc->fmin);
  958. $new_end = $size - ($start_orig - $featureloc->fmin);
  959. $rparts[$new_start][$type_name]['start'] = $new_start;
  960. $rparts[$new_start][$type_name]['end'] = $new_end;
  961. $rparts[$new_start][$type_name]['type'] = $type_name;
  962. }
  963. }
  964. }
  965. // now sort the parts
  966. // if we're on the reverse strand we need to resort
  967. if ($featureloc->strand >= 0) {
  968. usort($parts, 'chado_feature__residues_sort_rel_parts_by_start');
  969. }
  970. else {
  971. usort($rparts, 'chado_feature__residues_sort_rel_parts_by_start');
  972. $parts = $rparts;
  973. }
  974. $floc_sequences[$src]['id'] = $src;
  975. $floc_sequences[$src]['type'] = $featureloc->feature_id->type_id->name;
  976. $args = array(':feature_id' => $featureloc->srcfeature_id->feature_id);
  977. $start = $featureloc->fmin + 1;
  978. $size = $featureloc->fmax - $featureloc->fmin;
  979. // TODO: fix the hard coded $start and $size
  980. // the $start and $size variables are hard-coded in the SQL statement
  981. // because the db_query function places quotes around all placeholders
  982. // (e.g. :start & :size) and screws up the substring function
  983. $sql = "
  984. SELECT substring(residues from $start for $size) as residues
  985. FROM {feature}
  986. WHERE feature_id = :feature_id
  987. ";
  988. $sequence = chado_query($sql, $args)->fetchObject();
  989. $residues = $sequence->residues;
  990. if ($featureloc->strand < 0) {
  991. $residues = chado_reverse_compliment_sequence($residues);
  992. }
  993. $strand = '.';
  994. if ($featureloc->strand == 1) {
  995. $strand = '+';
  996. }
  997. elseif ($featureloc->strand == -1) {
  998. $strand = '-';
  999. }
  1000. $floc_sequences[$src]['location'] = chado_get_location_string($featureloc);
  1001. $floc_sequences[$src]['defline'] = chado_get_fasta_defline($featureloc->feature_id, '', $featureloc, '', strlen($residues));
  1002. $floc_sequences[$src]['featureloc'] = $featureloc;
  1003. $floc_sequences[$src]['residues'] = $residues;
  1004. //$floc_sequences[$src]['formatted_seq'] = tripal_feature_color_sequence($residues, $parts, $floc_sequences[$src]['defline']);
  1005. }
  1006. }
  1007. return $floc_sequences;
  1008. }
  1009. /**
  1010. * Get features related to the current feature to a given depth. Recursive function.
  1011. *
  1012. * @param $feature_id
  1013. * @param $substitute
  1014. * @param $levels
  1015. * @param $base_type_id
  1016. * @param $depth
  1017. *
  1018. */
  1019. function chado_get_aggregate_feature_relationships($feature_id, $substitute=1,
  1020. $levels=0, $base_type_id=NULL, $depth=0) {
  1021. // we only want to recurse to as many levels deep as indicated by the
  1022. // $levels variable, but only if this variable is > 0. If 0 then we
  1023. // recurse until we reach the end of the relationships tree.
  1024. if ($levels > 0 and $levels == $depth) {
  1025. return NULL;
  1026. }
  1027. // first get the relationships for this feature
  1028. return chado_get_feature_relationships($feature_id, 'as_object');
  1029. }
  1030. /**
  1031. * Get the relationships for a feature.
  1032. *
  1033. * @param $feature_id
  1034. * The feature to get relationships for
  1035. * @param $side
  1036. * The side of the relationship this feature is (ie: 'as_subject' or 'as_object')
  1037. *
  1038. */
  1039. function chado_get_feature_relationships($feature_id, $side = 'as_subject') {
  1040. $feature = chado_generate_var('feature', array('feature_id' => $feature_id));
  1041. // get the relationships for this feature. The query below is used for both
  1042. // querying the object and subject relationships
  1043. $sql = "
  1044. SELECT
  1045. FS.name as subject_name, FS.uniquename as subject_uniquename,
  1046. CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
  1047. FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
  1048. CVT.name as rel_type,
  1049. FO.name as object_name, FO.uniquename as object_uniquename,
  1050. CVTO.name as object_type, CVTO.cvterm_id as object_type_id
  1051. FROM {feature_relationship} FR
  1052. INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
  1053. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  1054. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  1055. INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
  1056. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1057. ";
  1058. if (strcmp($side, 'as_object')==0) {
  1059. $sql .= " WHERE FR.object_id = :feature_id";
  1060. }
  1061. if (strcmp($side, 'as_subject')==0) {
  1062. $sql .= " WHERE FR.subject_id = :feature_id";
  1063. }
  1064. $sql .= " ORDER BY FR.rank";
  1065. // get the relationships
  1066. $results = chado_query($sql, array(':feature_id' => $feature_id));
  1067. // Get the bundle for this feature type, if one exists.
  1068. $term = tripal_load_term_entity(array(
  1069. 'vocabulary' => $feature->type_id->dbxref_id->db_id->name,
  1070. 'accession' => $feature->type_id->dbxref_id->accession,
  1071. ));
  1072. $bundle = tripal_load_bundle_entity(array('term_id' => $term->id));
  1073. // iterate through the relationships, put these in an array and add
  1074. // in the Drupal node id if one exists
  1075. $i=0;
  1076. $relationships = array();
  1077. while ($rel = $results->fetchObject()) {
  1078. $entity = chado_get_record_entity_by_bundle($bundle, $rel->subject_id);
  1079. if ($entity) {
  1080. $rel->subject_entity_id = $entity->entity_id;
  1081. }
  1082. $entity = chado_get_record_entity_by_bundle($bundle, $rel->object_id);
  1083. if ($entity) {
  1084. $rel->object_entity_id = $entity->entity_id;
  1085. }
  1086. $relationships[$i++] = $rel;
  1087. }
  1088. return $relationships;
  1089. }
  1090. /**
  1091. * Load the locations for a given feature.
  1092. *
  1093. * @param $feature_id
  1094. * The feature to look up locations for.
  1095. * @param $side
  1096. * Whether the feature is the scrfeature, 'as_parent', or feature, 'as_child'.
  1097. * @param $aggregate
  1098. * Whether or not to get the locations for related features.
  1099. *
  1100. * @ingroup tripal_feature_api
  1101. */
  1102. function chado_get_featurelocs($feature_id, $side = 'as_parent', $aggregate = 1) {
  1103. $sql = "
  1104. SELECT
  1105. F.name, F.feature_id, F.uniquename,
  1106. FS.name as src_name, FS.feature_id as src_feature_id, FS.uniquename as src_uniquename,
  1107. CVT.name as cvname, CVT.cvterm_id,
  1108. CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
  1109. FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand, FL.phase
  1110. FROM {featureloc} FL
  1111. INNER JOIN {feature} F ON FL.feature_id = F.feature_id
  1112. INNER JOIN {feature} FS ON FS.feature_id = FL.srcfeature_id
  1113. INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  1114. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1115. ";
  1116. if (strcmp($side, 'as_parent')==0) {
  1117. $sql .= "WHERE FL.srcfeature_id = :feature_id ";
  1118. }
  1119. if (strcmp($side, 'as_child')==0) {
  1120. $sql .= "WHERE FL.feature_id = :feature_id ";
  1121. }
  1122. $flresults = chado_query($sql, array(':feature_id' => $feature_id));
  1123. // Copy the results into an array.
  1124. $i=0;
  1125. $featurelocs = array();
  1126. while ($loc = $flresults->fetchObject()) {
  1127. // If a drupal entity exists for this feature then add the nid to the
  1128. // results object.
  1129. // Get the bundle for this feature type, if one exists.
  1130. $ffeature = chado_generate_var('feature', array('feature_id' => $loc->feature_id));
  1131. $sfeature = chado_generate_var('feature', array('feature_id' => $loc->src_feature_id));
  1132. $fterm = tripal_load_term_entity(array(
  1133. 'vocabulary' => $ffeature->type_id->dbxref_id->db_id->name,
  1134. 'accession' => $ffeature->type_id->dbxref_id->accession,
  1135. ));
  1136. $sterm = tripal_load_term_entity(array(
  1137. 'vocabulary' => $sfeature->type_id->dbxref_id->db_id->name,
  1138. 'accession' => $sfeature->type_id->dbxref_id->accession,
  1139. ));
  1140. if($fterm) {
  1141. $fbundle = tripal_load_bundle_entity(array('term_id' => $fterm->id));
  1142. $loc->feid = chado_get_record_entity_by_bundle($fbundle, $loc->feature_id);
  1143. }
  1144. if ($sterm) {
  1145. $sbundle = tripal_load_bundle_entity(array('term_id' => $sterm->id));
  1146. $loc->seid = chado_get_record_entity_by_bundle($sbundle, $loc->src_feature_id);
  1147. }
  1148. // Add the result to the array.
  1149. $featurelocs[$i++] = $loc;
  1150. }
  1151. // Add the relationship feature locs if aggregate is turned on.
  1152. if ($aggregate and strcmp($side, 'as_parent')==0) {
  1153. // Get the relationships for this feature without substituting any children
  1154. // for the parent. We want all relationships.
  1155. $relationships = _chado_feature_get_aggregate_relationships($feature_id, 0);
  1156. foreach ($relationships as $rindex => $rel) {
  1157. // Get the featurelocs for each of the relationship features.
  1158. $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
  1159. foreach ($rel_featurelocs as $findex => $rfloc) {
  1160. $featurelocs[$i++] = $rfloc;
  1161. }
  1162. }
  1163. }
  1164. usort($featurelocs, 'chado_feature__residues_sort_locations');
  1165. return $featurelocs;
  1166. }
  1167. /**
  1168. * Get features related to the current feature to a given depth.
  1169. * Recursive function.
  1170. *
  1171. * @param $feature_id
  1172. * @param $substitute
  1173. * @param $levels
  1174. * @param $base_type_id
  1175. * @param $depth
  1176. *
  1177. *
  1178. */
  1179. function _chado_feature_get_aggregate_relationships($feature_id, $substitute=1,
  1180. $levels=0, $base_type_id=NULL, $depth=0) {
  1181. // we only want to recurse to as many levels deep as indicated by the
  1182. // $levels variable, but only if this variable is > 0. If 0 then we
  1183. // recurse until we reach the end of the relationships tree.
  1184. if ($levels > 0 and $levels == $depth) {
  1185. return NULL;
  1186. }
  1187. // first get the relationships for this feature
  1188. return _chado_feature_load_relationships($feature_id, 'as_object');
  1189. }
  1190. /**
  1191. * Get the relationships for a feature.
  1192. *
  1193. * @param $feature_id
  1194. * The feature to get relationships for
  1195. * @param $side
  1196. * The side of the relationship this feature is (ie: 'as_subject' or
  1197. * 'as_object')
  1198. *
  1199. *
  1200. */
  1201. function _chado_feature_load_relationships($feature_id, $side = 'as_subject') {
  1202. // Get the relationships for this feature. The query below is used for both
  1203. // querying the object and subject relationships
  1204. $sql = "
  1205. SELECT
  1206. FS.name as subject_name, FS.uniquename as subject_uniquename,
  1207. CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
  1208. FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
  1209. CVT.name as rel_type,
  1210. FO.name as object_name, FO.uniquename as object_uniquename,
  1211. CVTO.name as object_type, CVTO.cvterm_id as object_type_id
  1212. FROM {feature_relationship} FR
  1213. INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
  1214. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  1215. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  1216. INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
  1217. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1218. ";
  1219. if (strcmp($side, 'as_object')==0) {
  1220. $sql .= " WHERE FR.object_id = :feature_id";
  1221. }
  1222. if (strcmp($side, 'as_subject')==0) {
  1223. $sql .= " WHERE FR.subject_id = :feature_id";
  1224. }
  1225. $sql .= " ORDER BY FR.rank";
  1226. // Get the relationships.
  1227. $results = chado_query($sql, array(':feature_id' => $feature_id));
  1228. // Iterate through the relationships, put these in an array and add
  1229. // in the Drupal node id if one exists.
  1230. $i=0;
  1231. $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  1232. $relationships = array();
  1233. while ($rel = $results->fetchObject()) {
  1234. $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
  1235. if ($node) {
  1236. $rel->subject_nid = $node->nid;
  1237. }
  1238. $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
  1239. if ($node) {
  1240. $rel->object_nid = $node->nid;
  1241. }
  1242. $relationships[$i++] = $rel;
  1243. }
  1244. return $relationships;
  1245. }
  1246. /**
  1247. * Used to sort the list of relationship parts by start position.
  1248. *
  1249. * @param $a
  1250. * @param $b
  1251. *
  1252. * @ingroup tripal_feature_api
  1253. */
  1254. function chado_feature__residues_sort_rel_parts_by_start($a, $b) {
  1255. foreach ($a as $type_name => $details) {
  1256. $astart = $a[$type_name]['start'];
  1257. break;
  1258. }
  1259. foreach ($b as $type_name => $details) {
  1260. $bstart = $b[$type_name]['start'];
  1261. break;
  1262. }
  1263. return strnatcmp($astart, $bstart);
  1264. }
  1265. /**
  1266. * Used to sort the feature locs by start position.
  1267. *
  1268. * @param $a
  1269. * One featureloc record (as an object).
  1270. * @param $b
  1271. * The other featureloc record (as an object).
  1272. *
  1273. * @return
  1274. * Which feature location comes first.
  1275. *
  1276. * @ingroup tripal_feature_api
  1277. */
  1278. function chado_feature__residues_sort_locations($a, $b) {
  1279. return strnatcmp($a->fmin, $b->fmin);
  1280. }