tripal_chado.feature.api.inc 53 KB

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