tripal_chado.feature.api.inc 54 KB

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