tripal_chado.feature.api.inc 49 KB

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