tripal_chado.feature.api.inc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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 tripal_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 tripal_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 'derive_from_parent' is
  90. * true and the alignment is defined with this featureloc_id
  91. * @param $options
  92. * An associative array of options. Valid keys include:
  93. * - width: Indicate the number of bases to use per line. A new line will
  94. * be added after the specified number of bases on each line.
  95. * - is_html: Set to '1' if the sequence is meant to be displayed on a web
  96. * page. This will cause a <br> tag to separate lines of the FASTA sequence.
  97. * - derive_from_parent: Set to '1' if the sequence should be obtained from
  98. * the parent to which this feature is aligned.
  99. * - aggregate: Set to '1' if the sequence should only contain sub features,
  100. * excluding intro sub feature sequence. For example, set this option to
  101. * obtain just the coding sequence of an mRNA.
  102. * - upstream: An integer specifing the number of upstream bases to include
  103. * in the output
  104. * - downstream: An integer specifying the number of downstream bases to
  105. * include in the output.
  106. * - sub_feature_types: Only include sub features (or child features) of
  107. * the types provided in the array
  108. * - relationship_type: If a relationship name is provided (e.g. sequence_of)
  109. * then any sequences that are in relationships of this type with matched
  110. * sequences are also included
  111. * - relationship_part: If a relationship is provided in the preceeding
  112. * argument then the rel_part must be either 'object' or 'subject' to
  113. * indicate which side of the relationship the matched features belong
  114. *
  115. * @return
  116. * an array of matching sequence in the following keys for each sequence:
  117. * 'types' => an array of feature types that were used to derive
  118. * the sequence (e.g. from an aggregated sequence)
  119. * 'upstream' => the number of upstream bases included in the sequence
  120. * 'downstream' => the number of downstream bases included in the
  121. * sequence
  122. * 'defline' => the definintion line used to create a FASTA sequence
  123. * 'residues' => the residues
  124. * 'featureloc_id' => the featureloc_id if the sequences is from an
  125. * alignment
  126. *
  127. * @ingroup tripal_feature_api
  128. */
  129. function tripal_get_feature_sequences($feature, $options) {
  130. // Default values for finding the feature.
  131. $feature_id = array_key_exists('feature_id', $feature) ? $feature['feature_id'] : 0;
  132. $parent_id = array_key_exists('parent_id', $feature) ? $feature['parent_id'] : 0;
  133. $featureloc_id = array_key_exists('featureloc_id', $feature) ? $feature['featureloc_id'] : 0;
  134. $feature_name = array_key_exists('name', $feature) ? $feature['name'] : '';
  135. // Default values for building the sequence.
  136. $num_bases_per_line = array_key_exists('width', $options) ? $options['width'] : 50;
  137. $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
  138. $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate'] : 0;
  139. $upstream = array_key_exists('upstream', $options) ? $options['upstream'] : 0;
  140. $downstream = array_key_exists('downstream', $options) ? $options['downstream'] : 0;
  141. $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types'] : array();
  142. $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type'] : '';
  143. $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part'] : '';
  144. $is_html = array_key_exists('is_html', $options) ? $options['is_html'] : 0;
  145. $is_txt = array_key_exists('is_txt', $options) ? $options['is_txt'] : 0;
  146. $is_raw = array_key_exists('is_raw', $options) ? $options['is_raw'] : 1;
  147. if (!$upstream) {
  148. $upstream = 0;
  149. }
  150. if (!$downstream) {
  151. $downstream = 0;
  152. }
  153. // Make sure the sub_features variable is an array.
  154. if (!is_array($sub_features)) {
  155. tripal_report_error('tripal_feature', TRIPAL_ERROR,
  156. "'sub_features' option must be an array for function tripal_get_feature_sequences().",
  157. array()
  158. );
  159. return array();
  160. }
  161. // If a relationship was specified then retreive and the sequences that
  162. // have the given relationship and the recurse to extract the appropriate
  163. // sequence.
  164. if ($rel_part == "object" or $rel_part == "subject") {
  165. if ($rel_part == "subject") {
  166. $sql = '
  167. SELECT FO.feature_id, FO.name, FO.uniquename, CVTO.name as feature_type, O.genus, O.species
  168. FROM {feature} FS
  169. INNER JOIN {feature_relationship} FR ON FR.subject_id = FS.feature_id
  170. INNER JOIN {cvterm} CVTFR ON CVTFR.cvterm_id = FR.type_id
  171. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  172. INNER JOIN {cvterm} CVTO ON CVTO.cvterm_id = FO.type_id
  173. INNER JOIN {organism} O ON O.organism_id = FO.organism_id
  174. WHERE
  175. FS.feature_id = :feature_id AND
  176. CVTFR.name = :relationship
  177. ';
  178. $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship));
  179. }
  180. if ($rel_part == "object") {
  181. $sql = '
  182. SELECT FS.feature_id, FS.name, FS.uniquename, CVTO.name as feature_type, O.genus, O.species
  183. FROM {feature} FO
  184. INNER JOIN {feature_relationship} FR ON FR.object_id = FO.feature_id
  185. INNER JOIN {cvterm} CVTFR ON CVTFR.cvterm_id = FR.type_id
  186. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  187. INNER JOIN {cvterm} CVTO ON CVTO.cvterm_id = FS.type_id
  188. INNER JOIN {organism} O ON O.organism_id = FS.organism_id
  189. WHERE
  190. FO.feature_id = :feature_id AND
  191. CVTFR.name = :relationship
  192. ';
  193. $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship));
  194. }
  195. $sequences = '';
  196. while ($feature = $features->fetchObject()) {
  197. // Recurse and get the sequences for these in the relationship.
  198. if ($rel_part == "subject") {
  199. $defline = "$feature_name, $relationship, $feature->uniquename $feature->feature_type ($feature->genus $feature->species)";
  200. }
  201. if ($rel_part == "object") {
  202. $defline = "$feature->uniquename $feature->feature_type ($feature->genus $feature->species), $relationship, $feature_name";
  203. }
  204. return tripal_get_feature_sequences(
  205. array(
  206. 'feature_id' => $feature->feature_id,
  207. 'name' => $defline,
  208. 'parent_id' => $parent_id,
  209. ),
  210. array(
  211. 'width' => $num_bases_per_line,
  212. 'derive_from_parent' => $derive_from_parent,
  213. 'aggregate' => $aggregate,
  214. 'upstream' => $upstream,
  215. 'downstream' => $downstream,
  216. 'sub_features' => $sub_features,
  217. )
  218. );
  219. }
  220. }
  221. // Prepare the queries we're going to use later during the render phase
  222. // This SQL statement uses conditionals in the select clause to handle
  223. // cases cases where the alignment is in the reverse direction and when
  224. // the upstream and downstream extensions go beyond the lenght of the
  225. // parent sequence.
  226. $parent_sql ='
  227. SELECT featureloc_id, srcname, srcfeature_id, strand, srctypename, typename,
  228. fmin, fmax, upstream, downstream, adjfmin, adjfmax,
  229. substring(residues from (cast(adjfmin as int4) + 1) for cast((upstream + (fmax - fmin) + downstream) as int4)) as residues,
  230. genus, species
  231. FROM (
  232. SELECT
  233. FL.featureloc_id, OF.name srcname, FL.srcfeature_id, FL.strand,
  234. OCVT.name as srctypename, SCVT.name as typename,
  235. FL.fmin, FL.fmax, OO.genus, OO.species,
  236. CASE
  237. WHEN FL.strand >= 0 THEN
  238. CASE
  239. WHEN FL.fmin - :upstream <= 0 THEN 0
  240. ELSE FL.fmin - :upstream
  241. END
  242. WHEN FL.strand < 0 THEN
  243. CASE
  244. WHEN FL.fmin - :downstream <= 0 THEN 0
  245. ELSE FL.fmin - :downstream
  246. END
  247. END as adjfmin,
  248. CASE
  249. WHEN FL.strand >= 0 THEN
  250. CASE
  251. WHEN FL.fmax + :downstream > OF.seqlen THEN OF.seqlen
  252. ELSE FL.fmax + :downstream
  253. END
  254. WHEN FL.strand < 0 THEN
  255. CASE
  256. WHEN FL.fmax + :upstream > OF.seqlen THEN OF.seqlen
  257. ELSE FL.fmax + :upstream
  258. END
  259. END as adjfmax,
  260. CASE
  261. WHEN FL.strand >= 0 THEN
  262. CASE
  263. WHEN FL.fmin - :upstream <= 0 THEN FL.fmin
  264. ELSE :upstream
  265. END
  266. ELSE
  267. CASE
  268. WHEN FL.fmax + :upstream > OF.seqlen THEN OF.seqlen - FL.fmax
  269. ELSE :upstream
  270. END
  271. END as upstream,
  272. CASE
  273. WHEN FL.strand >= 0 THEN
  274. CASE
  275. WHEN FL.fmax + :downstream > OF.seqlen THEN OF.seqlen - FL.fmax
  276. ELSE :downstream
  277. END
  278. ELSE
  279. CASE
  280. WHEN FL.fmin - :downstream <= 0 THEN FL.fmin
  281. ELSE :downstream
  282. END
  283. END as downstream,
  284. OF.residues
  285. FROM {featureloc} FL
  286. INNER JOIN {feature} SF on FL.feature_id = SF.feature_id
  287. INNER JOIN {cvterm} SCVT on SF.type_id = SCVT.cvterm_id
  288. INNER JOIN {feature} OF on FL.srcfeature_id = OF.feature_id
  289. INNER JOIN {cvterm} OCVT on OF.type_id = OCVT.cvterm_id
  290. INNER JOIN {organism} OO on OF.organism_id = OO.organism_id
  291. WHERE SF.feature_id = :feature_id and NOT (OF.residues = \'\' or OF.residues IS NULL)) as tbl1
  292. ';
  293. // This query is meant to get all of the sub features of any given
  294. // feature (arg #1) and order them as they appear on the reference
  295. // feature (arg #2).
  296. $sfsql = '
  297. SELECT SF.feature_id, CVT.name as type_name, SF.type_id
  298. FROM {feature_relationship} FR
  299. INNER JOIN {feature} SF ON SF.feature_id = FR.subject_id
  300. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = SF.type_id
  301. INNER JOIN {featureloc} FL ON FL.feature_id = FR.subject_id
  302. INNER JOIN {feature} PF ON PF.feature_id = FL.srcfeature_id
  303. WHERE FR.object_id = :feature_id and PF.feature_id = :srcfeature_id
  304. ORDER BY FL.fmin ASC
  305. ';
  306. // For counting the number of children.
  307. $fsql ='
  308. SELECT count(*) as num_children
  309. FROM {feature_relationship} FR
  310. INNER JOIN {feature} SF ON SF.feature_id = FR.subject_id
  311. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = SF.type_id
  312. INNER JOIN {featureloc} FL ON FL.feature_id = FR.subject_id
  313. INNER JOIN {feature} PF ON PF.feature_id = FL.srcfeature_id
  314. WHERE FR.object_id = :feature_id and PF.feature_id = :srcfeature_id
  315. ';
  316. // The array to be returned.
  317. $sequences = array();
  318. // If we need to get the sequence from the parent then do so now.
  319. if ($derive_from_parent) {
  320. // Execute the query to get the sequence from the parent.
  321. $parents = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => $downstream, ':feature_id' => $feature_id));
  322. while ($parent = $parents->fetchObject()) {
  323. // If the user specified a particular parent and this one doesn't
  324. // match then skip it.
  325. if ($parent_id and $parent_id != $parent->srcfeature_id) {
  326. continue;
  327. }
  328. // if the user specified a particular featureloc_id and this one
  329. // doesn't match then skip it.
  330. if ($featureloc_id and $featureloc_id != $parent->featureloc_id) {
  331. continue;
  332. }
  333. // Initialize the sequence for each parent.
  334. $seq = '';
  335. $notes = '';
  336. $types = array();
  337. // if we are to aggregate then we will ignore the feature returned
  338. // by the query above and rebuild it using the sub features
  339. if ($aggregate) {
  340. // now get the sub features that are located on the parent.
  341. $children = chado_query($sfsql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id));
  342. $num_children = chado_query($fsql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id))->fetchField();
  343. // Iterate through the sub features and concat their sequences. They
  344. // should already be in order.
  345. $i = 0;
  346. $already_processed_children = array();
  347. while ($child = $children->fetchObject()) {
  348. // In some cases, a feature may be discontinuous (i.e. one feature
  349. // spread over several positions). In this case, the feature will
  350. // appear multiple times and we want to prevent addition of the
  351. // sequence multiple times. A simple check to make sure we haven't
  352. // seen the feature already should suffice.
  353. if (count($already_processed_children) > 0 and in_array($child->feature_id, $already_processed_children)){
  354. continue;
  355. }
  356. $already_processed_children[] = $child->feature_id;
  357. // If the callee has specified that only certain sub features should be
  358. // included then continue if this child is not one of those allowed
  359. // subfeatures.
  360. if (count($sub_features) > 0 and !in_array($child->type_name, $sub_features)) {
  361. $i++;
  362. continue;
  363. }
  364. // keep up with the types
  365. if (!in_array($child->type_name, $types)) {
  366. $types[] = $child->type_name;
  367. }
  368. // if the first sub feature we need to include the upstream bases. first check if
  369. // the feature is in the foward direction or the reverse.
  370. if ($i == 0 and $parent->strand >= 0) { // forward direction
  371. // -------------------------- ref
  372. // ....----> ---->
  373. // up 1 2
  374. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  375. }
  376. elseif ($i == 0 and $parent->strand < 0) { // reverse direction
  377. // -------------------------- ref
  378. // ....<---- <----
  379. // down 1 2
  380. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  381. }
  382. // Next, if the last sub feature we need to include the downstream bases. first check if
  383. // the feature is in teh forward direction or the reverse
  384. elseif ($i == $num_children - 1 and $parent->strand >= 0) { // forward direction
  385. // -------------------------- ref
  386. // ----> ---->....
  387. // 1 2 down
  388. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
  389. }
  390. elseif ($i == $num_children - 1 and $parent->strand < 0) { // reverse direction
  391. // -------------------------- ref
  392. // <---- <----....
  393. // 1 2 up
  394. $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
  395. }
  396. // for internal sub features we don't want upstream or downstream bases
  397. else {
  398. $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => 0, ':feature_id' => $child->feature_id));
  399. }
  400. while ($subseq = $q->fetchObject()) {
  401. // concatenate the sequences of all the sub features
  402. if ($subseq->srcfeature_id == $parent->srcfeature_id) {
  403. $seq .= $subseq->residues;
  404. }
  405. if ($subseq->upstream > 0 ) {
  406. $notes .= "Includes " . $subseq->upstream . " bases upstream. ";
  407. }
  408. if ($subseq->downstream > 0) {
  409. $notes .= "Includes " . $subseq->downstream . " bases downstream. ";
  410. }
  411. }
  412. $i++;
  413. }
  414. }
  415. // if this isn't an aggregate then use the parent residues
  416. else {
  417. $seq = $parent->residues;
  418. if ($parent->upstream > 0) {
  419. $notes .= "Includes " . $parent->upstream . " bases upstream. ";
  420. }
  421. if ($parent->downstream > 0) {
  422. $notes .= "Includes " . $parent->downstream . " bases downstream. ";
  423. }
  424. }
  425. // get the reverse compliment if feature is on the reverse strand
  426. $dir = 'forward';
  427. $length = strlen($seq);
  428. if ($parent->strand < 0) {
  429. $seq = tripal_reverse_compliment_sequence($seq);
  430. $dir = 'reverse';
  431. }
  432. // now format for display
  433. if ($is_html) {
  434. $seq = wordwrap($seq, $num_bases_per_line, "<br>", TRUE);
  435. }
  436. if ($is_txt) {
  437. $seq = wordwrap($seq, $num_bases_per_line, "\r\n", TRUE);
  438. }
  439. if (!$seq) {
  440. $notes .= "No sequence available.";
  441. }
  442. if (count($types) > 0) {
  443. $notes .= "Excludes all bases but those of type(s): " . implode(', ', $types) . ". " ;
  444. }
  445. // Construct the definition line for this feature. To construct the
  446. // defline we need a featureloc record, so we'll create one using
  447. // the information we have.
  448. $featureloc = new stdClass;
  449. $featureloc->feature_id = $feature;
  450. $featureloc->fmin = $parent->adjfmin;
  451. $featureloc->fmax = $parent->adjfmax;
  452. $featureloc->strand = $parent->strand;
  453. $featureloc->srcfeature_id = new stdClass;
  454. $featureloc->srcfeature_id->name = $parent->srcname;
  455. $featureloc->srcfeature_id->type_id = $parent->srctypename;
  456. $featureloc->srcfeature_id->organism_id = new stdClass;
  457. $featureloc->srcfeature_id->organism_id->genus = $parent->genus;
  458. $featureloc->srcfeature_id->organism_id->species = $parent->species;
  459. // Get a proper feature object.
  460. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  461. $defline = tripal_get_fasta_defline($f, $notes, $featureloc, '', $length);
  462. $sequences[] = array(
  463. 'types' => $types,
  464. 'upstream' => $parent->upstream,
  465. 'downstream' => $parent->downstream,
  466. 'defline' => $defline,
  467. 'residues' => $seq,
  468. 'featureloc_id' => $parent->featureloc_id,
  469. 'length' => $length,
  470. );
  471. }
  472. }
  473. // If we are not getting the sequence from the parent sequence then
  474. // use what comes through from the feature record.
  475. else {
  476. $f = chado_generate_var('feature', array('feature_id' => $feature_id));
  477. $f = chado_expand_var($f, 'field', 'feature.residues');
  478. $residues = $f->residues;
  479. $length = strlen($residues);
  480. if ($is_html) {
  481. $residues = wordwrap($residues, $num_bases_per_line, "<br>", TRUE);
  482. }
  483. else {
  484. $residues = wordwrap($residues, $num_bases_per_line, "\r\n", TRUE);
  485. }
  486. // get the definintion line for this feature
  487. $defline = tripal_get_fasta_defline($f, '', NULL, '', $length);
  488. // add to the sequence array
  489. $sequences[] = array(
  490. 'types' => $f->type_id->name,
  491. 'upstream' => 0,
  492. 'downstream' => 0,
  493. 'defline' => $defline,
  494. 'residues' => $residues,
  495. 'length' => $length,
  496. );
  497. }
  498. return $sequences;
  499. }
  500. /**
  501. *
  502. * @param $options
  503. * An associative array of options for selecting a feature. Valid keys include:
  504. * - org_commonname: The common name of the organism for which sequences
  505. * should be retrieved
  506. * - genus: The genus of the organism for which sequences should be retrieved
  507. * - species: The species of the organism for which sequences should be
  508. * retrieved
  509. * - analysis_name: The name of an analysis to which sequences belong. Only
  510. * those that are associated with the analysis will be retrieved.
  511. * - type: The type of feature (a sequence ontology term).
  512. * - feature_name: the name of the feature. Can be an array of feature names.
  513. * - feature_uname: the uniquename of the feature. Can be an array of
  514. * feature unique names.
  515. * - upstream: An integer specifing the number of upstream bases to include
  516. * in the output
  517. * - downstream: An integer specifying the number of downstream bases to
  518. * include in the output.
  519. * - derive_from_parent: Set to '1' if the sequence should be obtained from
  520. * the parent to which this feature is aligned.
  521. * - aggregate: Set to '1' if the sequence should only contain sub features,
  522. * excluding intro sub feature sequence. For example, set this option to
  523. * obtain just the coding sequence of an mRNA.
  524. * - sub_feature_types: Only include sub features (or child features) of
  525. * the types provided in the array
  526. * - relationship_type: If a relationship name is provided (e.g. sequence_of)
  527. * then any sequences that are in relationships of this type with matched
  528. * sequences are also included
  529. * - relationship_part: If a relationship is provided in the preceeding
  530. * argument then the rel_part must be either 'object' or 'subject' to
  531. * indicate which side of the relationship the matched features belong
  532. * - width: Indicate the number of bases to use per line. A new line will
  533. * be added after the specified number of bases on each line.
  534. * - is_html: Set to '1' if the sequence is meant to be displayed on a
  535. * web page. This will cause a <br> tag to separate lines of the FASTA
  536. * sequence.
  537. * @return
  538. * Returns an array of sequences. The sequences will be in an array with the
  539. * following keys for each sequence:
  540. * 'types' => an array of feature types that were used to derive
  541. * the sequence (e.g. from an aggregated sequence)
  542. * 'upstream' => the number of upstream bases in the sequence
  543. * 'downstream' => the number of downstream bases in the sequence
  544. * 'defline' => the definintion line used to create a FASTA sequence
  545. * 'residues' => the residues
  546. * 'featureloc_id' => the featureloc_id if from an alignment
  547. *
  548. * @ingroup tripal_feature_api
  549. */
  550. function tripal_get_bulk_feature_sequences($options) {
  551. // default values for building the sequence
  552. $org_commonname = array_key_exists('org_commonname', $options) ? $options['org_commonname'] : '';
  553. $genus = array_key_exists('genus', $options) ? $options['genus'] : '';
  554. $species = array_key_exists('species', $options) ? $options['species'] : '';
  555. $analysis_name = array_key_exists('analysis_name', $options) ? $options['analysis_name'] : '';
  556. $type = array_key_exists('type', $options) ? $options['type'] : '';
  557. $feature_name = array_key_exists('feature_name', $options) ? $options['feature_name'] : '';
  558. $feature_uname = array_key_exists('feature_uname', $options) ? $options['feature_uname'] : '';
  559. $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
  560. $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate'] : 0;
  561. $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types'] : array();
  562. $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type'] : '';
  563. $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part'] : '';
  564. $num_bases_per_line = array_key_exists('width', $options) ? $options['width'] : 50;
  565. $upstream = array_key_exists('upstream', $options) ? $options['upstream'] : 0;
  566. $downstream = array_key_exists('downstream', $options) ? $options['downstream'] : 0;
  567. if (!$type and !$feature_name and !$genus) {
  568. print "Please provide a type, feature name or genus\n";
  569. return;
  570. }
  571. // get the list of features
  572. $vars = array();
  573. $sql = "
  574. SELECT DISTINCT F.feature_id, F.name, F.uniquename,
  575. O.genus, O.species, CVT.name as feature_type
  576. FROM {feature} F
  577. INNER JOIN {organism} O on O.organism_id = F.organism_id
  578. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  579. ";
  580. if ($analysis_name) {
  581. $sql .= "
  582. INNER JOIN {analysisfeature} AF on AF.feature_id = F.feature_id
  583. INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id
  584. ";
  585. }
  586. $sql .= "WHERE (1=1) ";
  587. if ($org_commonname) {
  588. $sql .= "AND O.common_name = :common_name ";
  589. $vars[':common_name'] = $org_commonname;
  590. }
  591. if ($genus) {
  592. $sql .= "AND O.genus = :genus ";
  593. $vars[':genus'] = $genus;
  594. }
  595. if ($species) {
  596. $sql .= "AND O.species = :species ";
  597. $vars[':species'] = $species;
  598. }
  599. if ($type) {
  600. $sql .= "AND CVT.name = :cvtname ";
  601. $vars[':cvtname'] = $type;
  602. }
  603. if ($feature_name) {
  604. if (is_array($feature_name)) {
  605. $sql .= "AND F.name IN (";
  606. foreach ($feature_name as $i => $fname) {
  607. $sql .= ":fname$i, ";
  608. $vars[":fname$i"] = $fname;
  609. }
  610. // remove the trailing comma and close the paren
  611. $sql = substr($sql, 0, -2) . ")";
  612. }
  613. else {
  614. $sql .= "AND F.name = :fname";
  615. $vars[':fname'] = $feature_name;
  616. }
  617. }
  618. if ($feature_uname) {
  619. if (is_array($feature_uname)) {
  620. $sql .= "AND F.uniquename IN (";
  621. foreach ($feature_uname as $i => $funame) {
  622. $sql .= ":funame$i, ";
  623. $vars[":funame$i"] = $funame;
  624. }
  625. // remove the trailing comma and close the paren
  626. $sql = substr($sql, 0, -2) . ")";
  627. }
  628. else {
  629. $sql .= "AND F.uniquename = :funame";
  630. $vars[':funame'] = $feature_uname;
  631. }
  632. }
  633. if ($analysis_name) {
  634. $sql .= "AND A.name = :aname";
  635. $vars[':aname'] = $analysis_name;
  636. }
  637. $num_bases_per_line = 50;
  638. $num_seqs = 0;
  639. $q = chado_query($sql, $vars);
  640. $sequences = array();
  641. while ($feature = $q->fetchObject()) {
  642. // get the sequences
  643. $seqs = tripal_get_feature_sequences(array('feature_id' => $feature->feature_id), $options);
  644. $sequences = array_merge($sequences, $seqs);
  645. $num_seqs++;
  646. }
  647. return $sequences;
  648. }
  649. /**
  650. * Returns a definition line that can be used in a FASTA file
  651. *
  652. * @param $feature
  653. * A single feature object containing all the fields from the chado.feature table.
  654. * Best case is to provide an object generated by the chado_generate_var() function.
  655. * @param $notes
  656. * Optional: additional notes to be added to the definition line
  657. * @param $featureloc
  658. * Optional: a single featureloc object generated using chado_generate_var that
  659. * contains a record from the chado.featureloc table. Provide this if the
  660. * sequence was obtained by using the alignment rather than from the feature.residues
  661. * column
  662. * @param $type
  663. * Optional: the type of sequence. By default the feature type is used.
  664. * @param $length
  665. * Optional: the length of the sequence
  666. *
  667. * @return
  668. * A string of the format: uniquename|name|type|feature_id
  669. * or if an alignment: srcfeature_name:fmin..fmax[+-]; alignment of uniquename|name|type|feature_id
  670. */
  671. function tripal_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $type = '', $length = 0) {
  672. // make sure the featureloc object has the srcfeature if not, then add it
  673. if ($featureloc) {
  674. if (!is_object($featureloc->srcfeature_id)) {
  675. $featureloc->srcfeature_id = chado_generate_var('feature', array('feature_id' => $featureloc->srcfeature_id));
  676. }
  677. if (!is_object($featureloc->srcfeature_id->organism_id)) {
  678. $featureloc->srcfeature_id->organism_id = chado_generate_var('organism', array('organism_id' => $featureloc->srcfeature_id->organism_id));
  679. }
  680. }
  681. // make sure the feature object has the organism if not, then add it
  682. if (!is_object($feature->organism_id)) {
  683. $feature->organism_id = chado_generate_var('organism', array('organism_id' => $feature->organism_id));
  684. }
  685. // if a type is not provided then use the default type
  686. if (!$type) {
  687. $type = $feature->type_id->name;
  688. }
  689. // construct the definition line
  690. $defline = $feature->uniquename . " " .
  691. 'ID=' . $feature->uniquename . "|" .
  692. 'Name=' . $feature->name . "|" .
  693. 'organism=' . $feature->organism_id->genus . " " . $feature->organism_id->species . "|" .
  694. 'type=' . $type . '|';
  695. if ($length > 0) {
  696. $defline .= "length=" . $length . "bp|";
  697. }
  698. if ($featureloc) {
  699. $defline .= "location=Sequence derived from alignment at " . tripal_get_location_string($featureloc);
  700. $defline .= " (" . $featureloc->srcfeature_id->organism_id->genus . " " . $featureloc->srcfeature_id->organism_id->species . ")|";
  701. }
  702. if ($notes) {
  703. $defline .= "Notes=$notes|";
  704. }
  705. $defline = substr($defline, 0, -1); // remove the trailing |
  706. return $defline;
  707. }
  708. /**
  709. * Returns a string representing a feature location in an alignment
  710. *
  711. * @param unknown $featureloc
  712. * A single featureloc object generated using chado_generate_var that
  713. * contains a record from the chado.featureloc table.
  714. */
  715. function tripal_get_location_string($featureloc) {
  716. $feature = $featureloc->feature_id;
  717. $strand = '';
  718. if ($featureloc->strand == 1) {
  719. $strand = '+';
  720. }
  721. elseif ($featureloc->strand == -1) {
  722. $strand = '-';
  723. }
  724. return $featureloc->srcfeature_id->name . ":" . ($featureloc->fmin + 1) . ".." . $featureloc->fmax . $strand;
  725. }
  726. /**
  727. * Quickly retrieves relationships for a feature.
  728. *
  729. * Using the chado_expand_var function to retrieve a set
  730. * of relationships can be very slow, especialy if there are many relationships
  731. * This function is intended to help speed up the retrieval of relationships
  732. * by only retrieving the base information for the relationship and returning
  733. * an array with
  734. *
  735. * @param $feature
  736. * The feature object
  737. * @return
  738. * An array with two objects
  739. *
  740. * @ingroup tripal_feature_api
  741. */
  742. function tripal_get_feature_relationships($feature) {
  743. // expand the feature object to include the feature relationships.
  744. $options = array(
  745. 'return_array' => 1,
  746. 'order_by' => array('rank' => 'ASC'),
  747. // we don't want to fully recurse we only need information about the
  748. // relationship type and the object and subject features (including feature type
  749. // and organism)
  750. 'include_fk' => array(
  751. 'type_id' => 1,
  752. 'object_id' => array(
  753. 'type_id' => 1,
  754. 'organism_id' => 1
  755. ),
  756. 'subject_id' => array(
  757. 'type_id' => 1,
  758. 'organism_id' => 1
  759. ),
  760. ),
  761. );
  762. $feature = chado_expand_var($feature, 'table', 'feature_relationship', $options);
  763. // get the subject relationships
  764. $srelationships = $feature->feature_relationship->subject_id;
  765. $orelationships = $feature->feature_relationship->object_id;
  766. // get alignment as child. The $feature->featureloc element
  767. // is already populated from the alignment preprocess function
  768. $options = array(
  769. 'return_array' => 1,
  770. 'include_fk' => array(
  771. 'srcfeature_id' => 1,
  772. 'feature_id' => 1,
  773. ),
  774. );
  775. $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
  776. $cfeaturelocs = $feature->featureloc->feature_id;
  777. if (!$cfeaturelocs) {
  778. $cfeaturelocs = array();
  779. }
  780. elseif (!is_array($cfeaturelocs)) {
  781. $cfeaturelocs = array($cfeaturelocs);
  782. }
  783. // prepare the SQL statement to get the featureloc for the
  784. // feature in the relationships.
  785. $flrels_sql = "
  786. SELECT
  787. FL.featureloc_id, F.name as srcfeature_name, FL.srcfeature_id,
  788. FL.feature_id, FL.fmin, FL.fmax, FL.strand, FL.phase
  789. FROM {featureloc} FL
  790. INNER JOIN {feature} F ON F.feature_id = FL.srcfeature_id
  791. WHERE FL.feature_id = :feature_id and FL.srcfeature_id = :srcfeature_id
  792. ";
  793. // combine both object and subject relationshisp into a single array
  794. $relationships = array();
  795. $relationships['object'] = array();
  796. $relationships['subject'] = array();
  797. // iterate through the object relationships
  798. if ($orelationships) {
  799. foreach ($orelationships as $relationship) {
  800. $rel = new stdClass();
  801. // get locations where the child feature and this feature overlap with the
  802. // same landmark feature.
  803. $rel->child_featurelocs = array();
  804. foreach ($cfeaturelocs as $featureloc) {
  805. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->subject_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  806. while ($loc = $res->fetchObject()) {
  807. // add in the node id of the src feature if it exists and save this location
  808. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  809. $loc->nid = $featureloc->srcfeature_id->nid;
  810. }
  811. $rel->child_featurelocs[] = $loc;
  812. }
  813. }
  814. $rel->record = $relationship;
  815. // get the relationship and child types
  816. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  817. $child_type = $relationship->subject_id->type_id->name;
  818. // get the node id of the subject
  819. // $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  820. // $n = db_query($sql, array(':feature_id' => $relationship->subject_id->feature_id))->fetchObject();
  821. // if ($n) {
  822. // $rel->record->nid = $n->nid;
  823. // }
  824. if (!array_key_exists($rel_type, $relationships['object'])) {
  825. $relationships['object'][$rel_type] = array();
  826. }
  827. if (!array_key_exists($child_type, $relationships['object'][$rel_type])) {
  828. $relationships['object'][$rel_type][$child_type] = array();
  829. }
  830. $relationships['object'][$rel_type][$child_type][] = $rel;
  831. }
  832. }
  833. // now add in the subject relationships
  834. if ($srelationships) {
  835. foreach ($srelationships as $relationship) {
  836. $rel = new stdClass();
  837. // get locations where this feature overlaps with the parent
  838. $rel->parent_featurelocs = array();
  839. foreach ($cfeaturelocs as $featureloc) {
  840. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->object_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  841. while ($loc = $res->fetchObject()) {
  842. // add in the node id of the src feature if it exists and save this location
  843. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  844. $loc->nid = $featureloc->srcfeature_id->nid;
  845. }
  846. $rel->parent_featurelocs[] = $loc;
  847. }
  848. }
  849. $rel->record = $relationship;
  850. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  851. $parent_type = $relationship->object_id->type_id->name;
  852. // // get the node id of the subject
  853. // $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  854. // $n = db_query($sql, array(':feature_id' => $relationship->object_id->feature_id))->fetchObject();
  855. // if ($n) {
  856. // $rel->record->nid = $n->nid;
  857. // }
  858. if (!array_key_exists($rel_type, $relationships['subject'])) {
  859. $relationships['subject'][$rel_type] = array();
  860. }
  861. if (!array_key_exists($parent_type, $relationships['subject'][$rel_type])) {
  862. $relationships['subject'][$rel_type][$parent_type] = array();
  863. }
  864. $relationships['subject'][$rel_type][$parent_type][] = $rel;
  865. }
  866. }
  867. return $relationships;
  868. }
  869. /**
  870. *
  871. * @param unknown $feature_id
  872. * @param unknown $featurelocs
  873. * @return multitype:|Ambigous <multitype:, an>
  874. */
  875. function chado_get_featureloc_sequences($feature_id, $featurelocs) {
  876. // if we don't have any featurelocs then no point in continuing
  877. if (!$featurelocs) {
  878. return array();
  879. }
  880. // Get the list of relationships (including any aggregators) and iterate
  881. // through each one to find information needed to color-code the reference sequence
  882. $relationships = _tripal_feature_get_aggregate_relationships($feature_id);
  883. if (!$relationships) {
  884. return array();
  885. }
  886. // iterate through each of the realtionships features and get their
  887. // locations
  888. foreach ($relationships as $rindex => $rel) {
  889. // get the featurelocs for each of the relationship features
  890. $rel_featurelocs = chado_get_featurelocs($rel->subject_id, 'as_child', 0);
  891. foreach ($rel_featurelocs as $rfindex => $rel_featureloc) {
  892. // keep track of this unique source feature
  893. $src = $rel_featureloc->src_feature_id . "-" . $rel_featureloc->src_cvterm_id;
  894. // copy over the results to the relationship object. Since there can
  895. // be more than one feature location for each relationship feature we
  896. // use the '$src' variable to keep track of these.
  897. $rel->featurelocs = new stdClass();
  898. $rel->featurelocs->$src = new stdClass();
  899. $rel->featurelocs->$src->src_uniquename = $rel_featureloc->src_uniquename;
  900. $rel->featurelocs->$src->src_cvterm_id = $rel_featureloc->src_cvterm_id;
  901. $rel->featurelocs->$src->src_cvname = $rel_featureloc->src_cvname;
  902. $rel->featurelocs->$src->fmin = $rel_featureloc->fmin;
  903. $rel->featurelocs->$src->fmax = $rel_featureloc->fmax;
  904. $rel->featurelocs->$src->src_name = $rel_featureloc->src_name;
  905. // keep track of the individual parts for each relationship
  906. $start = $rel->featurelocs->$src->fmin;
  907. $end = $rel->featurelocs->$src->fmax;
  908. $type = $rel->subject_type;
  909. $rel_locs[$src]['parts'][$start][$type]['start'] = $start;
  910. $rel_locs[$src]['parts'][$start][$type]['end'] = $end;
  911. $rel_locs[$src]['parts'][$start][$type]['type'] = $type;
  912. }
  913. }
  914. // the featurelocs array provided to the function contains the locations
  915. // where this feature is found. We want to get the sequence for each
  916. // location and then annotate it with the parts found from the relationships
  917. // locations determiend above.
  918. $floc_sequences = array();
  919. foreach ($featurelocs as $featureloc) {
  920. // build the src name so we can keep track of the different parts for each feature
  921. $src = $featureloc->srcfeature_id->feature_id . "-" . $featureloc->srcfeature_id->type_id->cvterm_id;
  922. // orient the parts to the beginning of the feature sequence
  923. if (!empty($rel_locs[$src]['parts'])) {
  924. $parts = $rel_locs[$src]['parts'];
  925. $rparts = array(); // we will fill this up if we're on the reverse strand
  926. foreach ($parts as $start => $types) {
  927. foreach ($types as $type_name => $type) {
  928. if ($featureloc->strand >= 0) {
  929. // this is on the forward strand. We need to convert the start on the src feature to the
  930. // start on this feature's sequence
  931. $parts[$start][$type_name]['start'] = $parts[$start][$type_name]['start'] - $featureloc->fmin;
  932. $parts[$start][$type_name]['end'] = $parts[$start][$type_name]['end'] - $featureloc->fmin;
  933. $parts[$start][$type_name]['type'] = $type_name;
  934. }
  935. else {
  936. // this is on the reverse strand. We need to swap the start and stop and calculate from the
  937. // begining of the reverse sequence
  938. $size = ($featureloc->fmax - $featureloc->fmin);
  939. $start_orig = $parts[$start][$type_name]['start'];
  940. $end_orig = $parts[$start][$type_name]['end'];
  941. $new_start = $size - ($end_orig - $featureloc->fmin);
  942. $new_end = $size - ($start_orig - $featureloc->fmin);
  943. $rparts[$new_start][$type_name]['start'] = $new_start;
  944. $rparts[$new_start][$type_name]['end'] = $new_end;
  945. $rparts[$new_start][$type_name]['type'] = $type_name;
  946. }
  947. }
  948. }
  949. // now sort the parts
  950. // if we're on the reverse strand we need to resort
  951. if ($featureloc->strand >= 0) {
  952. usort($parts, 'chado_feature__residues_sort_rel_parts_by_start');
  953. }
  954. else {
  955. usort($rparts, 'chado_feature__residues_sort_rel_parts_by_start');
  956. $parts = $rparts;
  957. }
  958. $floc_sequences[$src]['id'] = $src;
  959. $floc_sequences[$src]['type'] = $featureloc->feature_id->type_id->name;
  960. $args = array(':feature_id' => $featureloc->srcfeature_id->feature_id);
  961. $start = $featureloc->fmin + 1;
  962. $size = $featureloc->fmax - $featureloc->fmin;
  963. // TODO: fix the hard coded $start and $size
  964. // the $start and $size variables are hard-coded in the SQL statement
  965. // because the db_query function places quotes around all placeholders
  966. // (e.g. :start & :size) and screws up the substring function
  967. $sql = "
  968. SELECT substring(residues from $start for $size) as residues
  969. FROM {feature}
  970. WHERE feature_id = :feature_id
  971. ";
  972. $sequence = chado_query($sql, $args)->fetchObject();
  973. $residues = $sequence->residues;
  974. if ($featureloc->strand < 0) {
  975. $residues = tripal_reverse_compliment_sequence($residues);
  976. }
  977. $strand = '.';
  978. if ($featureloc->strand == 1) {
  979. $strand = '+';
  980. }
  981. elseif ($featureloc->strand == -1) {
  982. $strand = '-';
  983. }
  984. $floc_sequences[$src]['location'] = tripal_get_location_string($featureloc);
  985. $floc_sequences[$src]['defline'] = tripal_get_fasta_defline($featureloc->feature_id, '', $featureloc, '', strlen($residues));
  986. $floc_sequences[$src]['featureloc'] = $featureloc;
  987. $floc_sequences[$src]['residues'] = $residues;
  988. //$floc_sequences[$src]['formatted_seq'] = tripal_feature_color_sequence($residues, $parts, $floc_sequences[$src]['defline']);
  989. }
  990. }
  991. return $floc_sequences;
  992. }
  993. /**
  994. * Get features related to the current feature to a given depth. Recursive function.
  995. *
  996. * @param $feature_id
  997. * @param $substitute
  998. * @param $levels
  999. * @param $base_type_id
  1000. * @param $depth
  1001. *
  1002. */
  1003. function chado_get_aggregate_feature_relationships($feature_id, $substitute=1,
  1004. $levels=0, $base_type_id=NULL, $depth=0) {
  1005. // we only want to recurse to as many levels deep as indicated by the
  1006. // $levels variable, but only if this variable is > 0. If 0 then we
  1007. // recurse until we reach the end of the relationships tree.
  1008. if ($levels > 0 and $levels == $depth) {
  1009. return NULL;
  1010. }
  1011. // first get the relationships for this feature
  1012. return chado_get_feature_relationships($feature_id, 'as_object');
  1013. }
  1014. /**
  1015. * Get the relationships for a feature.
  1016. *
  1017. * @param $feature_id
  1018. * The feature to get relationships for
  1019. * @param $side
  1020. * The side of the relationship this feature is (ie: 'as_subject' or 'as_object')
  1021. *
  1022. */
  1023. function chado_get_feature_relationships($feature_id, $side = 'as_subject') {
  1024. $feature = chado_generate_var('feature', array('feature_id' => $feature_id));
  1025. // get the relationships for this feature. The query below is used for both
  1026. // querying the object and subject relationships
  1027. $sql = "
  1028. SELECT
  1029. FS.name as subject_name, FS.uniquename as subject_uniquename,
  1030. CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
  1031. FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
  1032. CVT.name as rel_type,
  1033. FO.name as object_name, FO.uniquename as object_uniquename,
  1034. CVTO.name as object_type, CVTO.cvterm_id as object_type_id
  1035. FROM {feature_relationship} FR
  1036. INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
  1037. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  1038. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  1039. INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
  1040. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1041. ";
  1042. if (strcmp($side, 'as_object')==0) {
  1043. $sql .= " WHERE FR.object_id = :feature_id";
  1044. }
  1045. if (strcmp($side, 'as_subject')==0) {
  1046. $sql .= " WHERE FR.subject_id = :feature_id";
  1047. }
  1048. $sql .= " ORDER BY FR.rank";
  1049. // get the relationships
  1050. $results = chado_query($sql, array(':feature_id' => $feature_id));
  1051. // Get the bundle for this feature type, if one exists.
  1052. $term = tripal_load_term_entity(array(
  1053. 'vocabulary' => $feature->type_id->dbxref_id->db_id->name,
  1054. 'accession' => $feature->type_id->dbxref_id->accession,
  1055. ));
  1056. $bundle = tripal_load_bundle_entity(array('term_id' => $term->id));
  1057. // iterate through the relationships, put these in an array and add
  1058. // in the Drupal node id if one exists
  1059. $i=0;
  1060. $relationships = array();
  1061. while ($rel = $results->fetchObject()) {
  1062. $entity = chado_get_record_entity_by_bundle($bundle, $rel->subject_id);
  1063. if ($entity) {
  1064. $rel->subject_entity_id = $entity->entity_id;
  1065. }
  1066. $entity = chado_get_record_entity_by_bundle($bundle, $rel->object_id);
  1067. if ($entity) {
  1068. $rel->object_entity_id = $entity->entity_id;
  1069. }
  1070. $relationships[$i++] = $rel;
  1071. }
  1072. return $relationships;
  1073. }
  1074. /**
  1075. * Load the locations for a given feature
  1076. *
  1077. * @param $feature_id
  1078. * The feature to look up locations for
  1079. * @param $side
  1080. * Whether the feature is the scrfeature, 'as_parent', or feature, 'as_child'
  1081. * @param $aggregate
  1082. * Whether or not to get the locations for related features
  1083. *
  1084. * @ingroup tripal_feature
  1085. */
  1086. function chado_get_featurelocs($feature_id, $side = 'as_parent', $aggregate = 1) {
  1087. $sql = "
  1088. SELECT
  1089. F.name, F.feature_id, F.uniquename,
  1090. FS.name as src_name, FS.feature_id as src_feature_id, FS.uniquename as src_uniquename,
  1091. CVT.name as cvname, CVT.cvterm_id,
  1092. CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
  1093. FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand, FL.phase
  1094. FROM {featureloc} FL
  1095. INNER JOIN {feature} F ON FL.feature_id = F.feature_id
  1096. INNER JOIN {feature} FS ON FS.feature_id = FL.srcfeature_id
  1097. INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  1098. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1099. ";
  1100. if (strcmp($side, 'as_parent')==0) {
  1101. $sql .= "WHERE FL.srcfeature_id = :feature_id ";
  1102. }
  1103. if (strcmp($side, 'as_child')==0) {
  1104. $sql .= "WHERE FL.feature_id = :feature_id ";
  1105. }
  1106. $flresults = chado_query($sql, array(':feature_id' => $feature_id));
  1107. // copy the results into an array
  1108. $i=0;
  1109. $featurelocs = array();
  1110. while ($loc = $flresults->fetchObject()) {
  1111. // if a drupal entity exists for this feature then add the nid to the
  1112. // results object
  1113. // Get the bundle for this feature type, if one exists.
  1114. $ffeature = chado_generate_var('feature', array('feature_id' => $loc->feature_id));
  1115. $sfeature = chado_generate_var('feature', array('feature_id' => $loc->src_feature_id));
  1116. $fterm = tripal_load_term_entity(array(
  1117. 'vocabulary' => $ffeature->type_id->dbxref_id->db_id->name,
  1118. 'accession' => $ffeature->type_id->dbxref_id->accession,
  1119. ));
  1120. $sterm = tripal_load_term_entity(array(
  1121. 'vocabulary' => $sfeature->type_id->dbxref_id->db_id->name,
  1122. 'accession' => $sfeature->type_id->dbxref_id->accession,
  1123. ));
  1124. if($fterm) {
  1125. $fbundle = tripal_load_bundle_entity(array('term_id' => $fterm->id));
  1126. $loc->feid = chado_get_record_entity_by_bundle($fbundle, $loc->feature_id);
  1127. }
  1128. if ($sterm) {
  1129. $sbundle = tripal_load_bundle_entity(array('term_id' => $sterm->id));
  1130. $loc->seid = chado_get_record_entity_by_bundle($sbundle, $loc->src_feature_id);
  1131. }
  1132. // add the result to the array
  1133. $featurelocs[$i++] = $loc;
  1134. }
  1135. // Add the relationship feature locs if aggregate is turned on
  1136. if ($aggregate and strcmp($side, 'as_parent')==0) {
  1137. // get the relationships for this feature without substituting any children
  1138. // for the parent. We want all relationships
  1139. $relationships = _tripal_feature_get_aggregate_relationships($feature_id, 0);
  1140. foreach ($relationships as $rindex => $rel) {
  1141. // get the featurelocs for each of the relationship features
  1142. $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
  1143. foreach ($rel_featurelocs as $findex => $rfloc) {
  1144. $featurelocs[$i++] = $rfloc;
  1145. }
  1146. }
  1147. }
  1148. usort($featurelocs, 'chado_feature__residues_sort_locations');
  1149. return $featurelocs;
  1150. }
  1151. /**
  1152. * Get features related to the current feature to a given depth. Recursive function.
  1153. *
  1154. * @param $feature_id
  1155. * @param $substitute
  1156. * @param $levels
  1157. * @param $base_type_id
  1158. * @param $depth
  1159. *
  1160. */
  1161. function _tripal_feature_get_aggregate_relationships($feature_id, $substitute=1,
  1162. $levels=0, $base_type_id=NULL, $depth=0) {
  1163. // we only want to recurse to as many levels deep as indicated by the
  1164. // $levels variable, but only if this variable is > 0. If 0 then we
  1165. // recurse until we reach the end of the relationships tree.
  1166. if ($levels > 0 and $levels == $depth) {
  1167. return NULL;
  1168. }
  1169. // first get the relationships for this feature
  1170. return _tripal_feature_load_relationships($feature_id, 'as_object');
  1171. }
  1172. /**
  1173. * Get the relationships for a feature.
  1174. *
  1175. * @param $feature_id
  1176. * The feature to get relationships for
  1177. * @param $side
  1178. * The side of the relationship this feature is (ie: 'as_subject' or 'as_object')
  1179. *
  1180. */
  1181. function _tripal_feature_load_relationships($feature_id, $side = 'as_subject') {
  1182. // Get the relationships for this feature. The query below is used for both
  1183. // querying the object and subject relationships
  1184. $sql = "
  1185. SELECT
  1186. FS.name as subject_name, FS.uniquename as subject_uniquename,
  1187. CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
  1188. FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
  1189. CVT.name as rel_type,
  1190. FO.name as object_name, FO.uniquename as object_uniquename,
  1191. CVTO.name as object_type, CVTO.cvterm_id as object_type_id
  1192. FROM {feature_relationship} FR
  1193. INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
  1194. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  1195. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  1196. INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
  1197. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  1198. ";
  1199. if (strcmp($side, 'as_object')==0) {
  1200. $sql .= " WHERE FR.object_id = :feature_id";
  1201. }
  1202. if (strcmp($side, 'as_subject')==0) {
  1203. $sql .= " WHERE FR.subject_id = :feature_id";
  1204. }
  1205. $sql .= " ORDER BY FR.rank";
  1206. // Get the relationships.
  1207. $results = chado_query($sql, array(':feature_id' => $feature_id));
  1208. // Iterate through the relationships, put these in an array and add
  1209. // in the Drupal node id if one exists.
  1210. $i=0;
  1211. $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  1212. $relationships = array();
  1213. while ($rel = $results->fetchObject()) {
  1214. $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
  1215. if ($node) {
  1216. $rel->subject_nid = $node->nid;
  1217. }
  1218. $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
  1219. if ($node) {
  1220. $rel->object_nid = $node->nid;
  1221. }
  1222. $relationships[$i++] = $rel;
  1223. }
  1224. return $relationships;
  1225. }
  1226. /**
  1227. * Used to sort the list of relationship parts by start position
  1228. *
  1229. * @ingroup tripal_feature
  1230. */
  1231. function chado_feature__residues_sort_rel_parts_by_start($a, $b) {
  1232. foreach ($a as $type_name => $details) {
  1233. $astart = $a[$type_name]['start'];
  1234. break;
  1235. }
  1236. foreach ($b as $type_name => $details) {
  1237. $bstart = $b[$type_name]['start'];
  1238. break;
  1239. }
  1240. return strnatcmp($astart, $bstart);
  1241. }
  1242. /**
  1243. * Used to sort the feature locs by start position
  1244. *
  1245. * @param $a
  1246. * One featureloc record (as an object)
  1247. * @param $b
  1248. * The other featureloc record (as an object)
  1249. *
  1250. * @return
  1251. * Which feature location comes first
  1252. *
  1253. * @ingroup tripal_feature
  1254. */
  1255. function chado_feature__residues_sort_locations($a, $b) {
  1256. return strnatcmp($a->fmin, $b->fmin);
  1257. }