tripal_feature.theme.inc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. <?php
  2. /**
  3. * @ingroup tripal_legacy_feature
  4. */
  5. function tripal_feature_preprocess_tripal_feature_sequence(&$variables) {
  6. // we want to provide a new variable that contains the matched features.
  7. $feature = $variables['node']->feature;
  8. // get the featureloc src features
  9. $options = array(
  10. 'return_array' => 1,
  11. 'include_fk' => array(
  12. 'srcfeature_id' => array(
  13. 'type_id' => 1
  14. ),
  15. ),
  16. );
  17. $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
  18. // because there are two foriegn keys in the featureloc table with the feature table
  19. // we have to access the records for each by specifying the field name after the table name:
  20. $ffeaturelocs = $feature->featureloc->feature_id;
  21. // now extract the sequences
  22. $featureloc_sequences = tripal_feature_load_featureloc_sequences($feature->feature_id, $ffeaturelocs);
  23. $feature->featureloc_sequences = $featureloc_sequences;
  24. // if this feature has associated protein sequences (or others via relationships
  25. // then we want to make sure the relationships are added so that we can
  26. // show the protein sequences
  27. if (!property_exists($feature, 'all_relationships')) {
  28. $feature->all_relationships = tripal_feature_get_feature_relationships($feature);
  29. }
  30. }
  31. /**
  32. * Get the sequence this feature is located on
  33. *
  34. * @param $feature_id
  35. * @param $featurelocs
  36. *
  37. * @ingroup tripal_legacy_feature
  38. */
  39. function tripal_feature_load_featureloc_sequences($feature_id, $featurelocs) {
  40. // if we don't have any featurelocs then no point in continuing
  41. if (!$featurelocs) {
  42. return array();
  43. }
  44. // get the list of relationships (including any aggregators) and iterate
  45. // through each one to find information needed to color-code the reference sequence
  46. $relationships = tripal_feature_get_aggregate_relationships($feature_id);
  47. if (!$relationships) {
  48. return array();
  49. }
  50. // iterate through each of the realtionships features and get their
  51. // locations
  52. foreach ($relationships as $rindex => $rel) {
  53. // get the featurelocs for each of the relationship features
  54. $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
  55. foreach ($rel_featurelocs as $rfindex => $rel_featureloc) {
  56. // keep track of this unique source feature
  57. $src = $rel_featureloc->src_feature_id . "-" . $rel_featureloc->src_cvterm_id;
  58. // copy over the results to the relationship object. Since there can
  59. // be more than one feature location for each relationship feature we
  60. // use the '$src' variable to keep track of these.
  61. $rel->featurelocs = new stdClass();
  62. $rel->featurelocs->$src = new stdClass();
  63. $rel->featurelocs->$src->src_uniquename = $rel_featureloc->src_uniquename;
  64. $rel->featurelocs->$src->src_cvterm_id = $rel_featureloc->src_cvterm_id;
  65. $rel->featurelocs->$src->src_cvname = $rel_featureloc->src_cvname;
  66. $rel->featurelocs->$src->fmin = $rel_featureloc->fmin;
  67. $rel->featurelocs->$src->fmax = $rel_featureloc->fmax;
  68. $rel->featurelocs->$src->src_name = $rel_featureloc->src_name;
  69. // keep track of the individual parts for each relationship
  70. $start = $rel->featurelocs->$src->fmin;
  71. $end = $rel->featurelocs->$src->fmax;
  72. $type = $rel->subject_type;
  73. $rel_locs[$src]['parts'][$start][$type]['start'] = $start;
  74. $rel_locs[$src]['parts'][$start][$type]['end'] = $end;
  75. $rel_locs[$src]['parts'][$start][$type]['type'] = $type;
  76. }
  77. }
  78. // the featurelocs array provided to the function contains the locations
  79. // where this feature is found. We want to get the sequence for each
  80. // location and then annotate it with the parts found from the relationships
  81. // locations determiend above.
  82. $floc_sequences = array();
  83. foreach ($featurelocs as $featureloc) {
  84. // build the src name so we can keep track of the different parts for each feature
  85. $src = $featureloc->srcfeature_id->feature_id . "-" . $featureloc->srcfeature_id->type_id->cvterm_id;
  86. // orient the parts to the beginning of the feature sequence
  87. if (!empty($rel_locs[$src]['parts'])) {
  88. $parts = $rel_locs[$src]['parts'];
  89. $rparts = array(); // we will fill this up if we're on the reverse strand
  90. foreach ($parts as $start => $types) {
  91. foreach ($types as $type_name => $type) {
  92. if ($featureloc->strand >= 0) {
  93. // this is on the forward strand. We need to convert the start on the src feature to the
  94. // start on this feature's sequence
  95. $parts[$start][$type_name]['start'] = $parts[$start][$type_name]['start'] - $featureloc->fmin;
  96. $parts[$start][$type_name]['end'] = $parts[$start][$type_name]['end'] - $featureloc->fmin;
  97. $parts[$start][$type_name]['type'] = $type_name;
  98. }
  99. else {
  100. // this is on the reverse strand. We need to swap the start and stop and calculate from the
  101. // begining of the reverse sequence
  102. $size = ($featureloc->fmax - $featureloc->fmin);
  103. $start_orig = $parts[$start][$type_name]['start'];
  104. $end_orig = $parts[$start][$type_name]['end'];
  105. $new_start = $size - ($end_orig - $featureloc->fmin);
  106. $new_end = $size - ($start_orig - $featureloc->fmin);
  107. $rparts[$new_start][$type_name]['start'] = $new_start;
  108. $rparts[$new_start][$type_name]['end'] = $new_end;
  109. $rparts[$new_start][$type_name]['type'] = $type_name;
  110. }
  111. }
  112. }
  113. // now sort the parts
  114. // if we're on the reverse strand we need to resort
  115. if ($featureloc->strand >= 0) {
  116. usort($parts, 'tripal_feature_sort_rel_parts_by_start');
  117. }
  118. else {
  119. usort($rparts, 'tripal_feature_sort_rel_parts_by_start');
  120. $parts = $rparts;
  121. }
  122. $floc_sequences[$src]['id'] = $src;
  123. $floc_sequences[$src]['type'] = $featureloc->feature_id->type_id->name;
  124. $args = array(':feature_id' => $featureloc->srcfeature_id->feature_id);
  125. $start = $featureloc->fmin + 1;
  126. $size = $featureloc->fmax - $featureloc->fmin;
  127. // TODO: fix the hard coded $start and $size
  128. // the $start and $size variables are hard-coded in the SQL statement
  129. // because the db_query function places quotes around all placeholders
  130. // (e.g. :start & :size) and screws up the substring function
  131. $sql = "
  132. SELECT substring(residues from $start for $size) as residues
  133. FROM {feature}
  134. WHERE feature_id = :feature_id
  135. ";
  136. $sequence = chado_query($sql, $args)->fetchObject();
  137. $residues = $sequence->residues;
  138. if ($featureloc->strand < 0) {
  139. $residues = tripal_reverse_compliment_sequence($residues);
  140. }
  141. $strand = '.';
  142. if ($featureloc->strand == 1) {
  143. $strand = '+';
  144. }
  145. elseif ($featureloc->strand == -1) {
  146. $strand = '-';
  147. }
  148. $floc_sequences[$src]['location'] = tripal_get_location_string($featureloc);
  149. $floc_sequences[$src]['defline'] = tripal_get_fasta_defline($featureloc->feature_id, '', $featureloc, '', strlen($residues));
  150. $floc_sequences[$src]['featureloc'] = $featureloc;
  151. $floc_sequences[$src]['formatted_seq'] = tripal_feature_color_sequence($residues, $parts, $floc_sequences[$src]['defline']);
  152. }
  153. }
  154. return $floc_sequences;
  155. }
  156. /**
  157. * Used to sort the list of relationship parts by start position
  158. *
  159. * @ingroup tripal_legacy_feature
  160. */
  161. function tripal_feature_sort_rel_parts_by_start($a, $b) {
  162. foreach ($a as $type_name => $details) {
  163. $astart = $a[$type_name]['start'];
  164. break;
  165. }
  166. foreach ($b as $type_name => $details) {
  167. $bstart = $b[$type_name]['start'];
  168. break;
  169. }
  170. return strnatcmp($astart, $bstart);
  171. }
  172. /**
  173. * Load the locations for a given feature
  174. *
  175. * @param $feature_id
  176. * The feature to look up locations for
  177. * @param $side
  178. * Whether the feature is the scrfeature, 'as_parent', or feature, 'as_child'
  179. * @param $aggregate
  180. * Whether or not to get the locations for related features
  181. *
  182. * @ingroup tripal_legacy_feature
  183. */
  184. function tripal_feature_load_featurelocs($feature_id, $side = 'as_parent', $aggregate = 1) {
  185. $sql = "
  186. SELECT
  187. F.name, F.feature_id, F.uniquename,
  188. FS.name as src_name, FS.feature_id as src_feature_id, FS.uniquename as src_uniquename,
  189. CVT.name as cvname, CVT.cvterm_id,
  190. CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
  191. FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand, FL.phase
  192. FROM {featureloc} FL
  193. INNER JOIN {feature} F ON FL.feature_id = F.feature_id
  194. INNER JOIN {feature} FS ON FS.feature_id = FL.srcfeature_id
  195. INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  196. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  197. ";
  198. if (strcmp($side, 'as_parent')==0) {
  199. $sql .= "WHERE FL.srcfeature_id = :feature_id ";
  200. }
  201. if (strcmp($side, 'as_child')==0) {
  202. $sql .= "WHERE FL.feature_id = :feature_id ";
  203. }
  204. $flresults = chado_query($sql, array(':feature_id' => $feature_id));
  205. // copy the results into an array
  206. $i=0;
  207. $featurelocs = array();
  208. while ($loc = $flresults->fetchObject()) {
  209. // if a drupal node exists for this feature then add the nid to the
  210. // results object
  211. $loc->fnid = chado_get_nid_from_id('feature', $loc->feature_id);
  212. $loc->snid = chado_get_nid_from_id('feature', $loc->src_feature_id);
  213. // add the result to the array
  214. $featurelocs[$i++] = $loc;
  215. }
  216. // Add the relationship feature locs if aggregate is turned on
  217. if ($aggregate and strcmp($side, 'as_parent')==0) {
  218. // get the relationships for this feature without substituting any children
  219. // for the parent. We want all relationships
  220. $relationships = tripal_feature_get_aggregate_relationships($feature_id, 0);
  221. foreach ($relationships as $rindex => $rel) {
  222. // get the featurelocs for each of the relationship features
  223. $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
  224. foreach ($rel_featurelocs as $findex => $rfloc) {
  225. $featurelocs[$i++] = $rfloc;
  226. }
  227. }
  228. }
  229. usort($featurelocs, 'tripal_feature_sort_locations');
  230. return $featurelocs;
  231. }
  232. /**
  233. * Used to sort the feature locs by start position
  234. *
  235. * @param $a
  236. * One featureloc record (as an object)
  237. * @param $b
  238. * The other featureloc record (as an object)
  239. *
  240. * @return
  241. * Which feature location comes first
  242. *
  243. * @ingroup tripal_legacy_feature
  244. */
  245. function tripal_feature_sort_locations($a, $b) {
  246. return strnatcmp($a->fmin, $b->fmin);
  247. }
  248. /**
  249. * Returns the marked up fasta sequence for the described feature
  250. *
  251. * @param $sequence
  252. * @param $parts
  253. * @param $defline
  254. *
  255. * @ingroup tripal_legacy_feature
  256. */
  257. function tripal_feature_color_sequence($sequence, $parts, $defline) {
  258. $types = array();
  259. // first get the list of types so we can create a color legend
  260. foreach ($parts as $index => $t) {
  261. foreach ($t as $type_name => $details) {
  262. $types[$type_name] = 1;
  263. }
  264. }
  265. $newseq = "<div id=\"tripal_feature-featureloc_sequence-legend\">Legend: ";
  266. foreach ($types as $type_name => $present) {
  267. $newseq .= "<span id=\"tripal_feature-legend-$type_name\" class=\"tripal_feature-legend-item tripal_feature-featureloc_sequence-$type_name\" script=\"\">$type_name</span>";
  268. }
  269. $newseq .= "</div>Hold the cursor over a type above to highlight its positions in the sequence below.";
  270. // set the background color of the rows based on the type
  271. $pos = 0;
  272. $newseq .= "<pre class=\"tripal_feature-sequence\">";
  273. $newseq .= ">$defline<br>";
  274. // iterate through the parts. They should be in order.
  275. $starts = array(); // an array holding all of the children starting locations
  276. $ends = array(); // an array holding all of the children's ending locations
  277. $seqcount = 0;
  278. foreach ($parts as $index => $types) {
  279. // get the start for this part. All types in this part start at the
  280. // same position so we only need the first record
  281. foreach ($types as $type => $child) {
  282. $start = $child['start'];
  283. $starts[$start][] = $type;
  284. }
  285. // next, sort the parts by their end. We want the span tag to
  286. // to be added in the order the parts end.
  287. usort($types, 'tripal_feature_sort_rel_parts_by_end');
  288. // iterate through the types in order that then end and create a
  289. // span for it.
  290. foreach ($types as $type) {
  291. $end = $type['end'];
  292. $ends[$end][] = $type;
  293. }
  294. }
  295. // iterate through each nucleotide in the sequence, add a new line very
  296. // 50 characters and add the spans as we encounter them
  297. for ($i = 0; $i < strlen($sequence); $i++) {
  298. // if we are at and end of a span then close it
  299. if (array_key_exists($i, $ends)) {
  300. foreach ($ends[$i] as $index => $type) {
  301. $newseq .= "</span>";
  302. }
  303. }
  304. // if we are at and end of a span then close it
  305. if (array_key_exists($i, $starts)) {
  306. foreach ($starts[$i] as $index => $type) {
  307. $class = "tripal_feature-featureloc_sequence-" . $type;
  308. $newseq .= "<span class=\"$class\">";
  309. }
  310. }
  311. $newseq .= $sequence{$i};
  312. $seqcount++;
  313. if ($seqcount % 50 == 0) {
  314. $newseq .= "\n";
  315. }
  316. }
  317. $newseq .= "</pre>";
  318. return $newseq;
  319. }
  320. /**
  321. * Used to sort the list of relationship parts by start position
  322. *
  323. * @ingroup tripal_legacy_feature
  324. */
  325. function tripal_feature_sort_rel_parts_by_end($a, $b) {
  326. $val = strnatcmp($b['end'], $a['end']);
  327. if ($val == 0) {
  328. return strcmp($a['type'], $b['type']);
  329. }
  330. return $val;
  331. }
  332. /**
  333. *
  334. *
  335. * @ingroup tripal_legacy_feature
  336. */
  337. function tripal_feature_preprocess_tripal_feature_relationships(&$variables) {
  338. // we want to provide a new variable that contains the matched features.
  339. $feature = $variables['node']->feature;
  340. if (!property_exists($feature, 'all_relationships')) {
  341. $feature->all_relationships = tripal_feature_get_feature_relationships($feature);
  342. }
  343. }
  344. /**
  345. *
  346. *
  347. * @ingroup tripal_legacy_feature
  348. */
  349. function tripal_feature_preprocess_tripal_feature_proteins(&$variables) {
  350. // we want to provide a new variable that contains the matched features.
  351. $feature = $variables['node']->feature;
  352. if (!property_exists($feature, 'all_relationships')) {
  353. $feature->all_relationships = tripal_feature_get_feature_relationships($feature);
  354. }
  355. }
  356. /**
  357. *
  358. *
  359. * @ingroup tripal_legacy_feature
  360. */
  361. function tripal_feature_preprocess_tripal_feature_alignments(&$variables) {
  362. // we want to provide a new variable that contains the matched features.
  363. $feature = $variables['node']->feature;
  364. $options = array(
  365. 'return_array' => 1,
  366. 'include_fk' => array(
  367. 'srcfeature_id' => array(
  368. 'type_id' => 1,
  369. ),
  370. 'feature_id' => array(
  371. 'type_id' => 1
  372. ),
  373. )
  374. );
  375. $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
  376. // get alignments as child
  377. $cfeaturelocs = $feature->featureloc->feature_id;
  378. if (!$cfeaturelocs) {
  379. $cfeaturelocs = array();
  380. }
  381. // get alignment as parent
  382. $pfeaturelocs = $feature->featureloc->srcfeature_id;
  383. if (!$pfeaturelocs) {
  384. $pfeaturelocs = array();
  385. }
  386. // get matched alignments (those with an itermediate 'match' or 'EST_match', etc
  387. $mfeaturelocs = tripal_feature_get_matched_alignments($feature);
  388. $feature->matched_featurelocs = $mfeaturelocs;
  389. // combine all three alignments into a single array for printing together in
  390. // a single list
  391. $alignments = array();
  392. foreach ($pfeaturelocs as $featureloc) {
  393. // if type is a 'match' then ignore it. We will handle those below
  394. if (preg_match('/(^match$|^.*?_match|match_part)$/', $featureloc->feature_id->type_id->name)) {
  395. continue;
  396. }
  397. $alignment = new stdClass();
  398. $alignment->record = $featureloc;
  399. $alignment->name = $featureloc->feature_id->name;
  400. $alignment->type = $featureloc->feature_id->type_id->name;
  401. $alignment->fmin = $featureloc->fmin;
  402. $alignment->fmax = $featureloc->fmax;
  403. $alignment->phase = $featureloc->phase;
  404. $alignment->strand = $featureloc->strand;
  405. $alignments[] = $alignment;
  406. if (property_exists($featureloc->feature_id, 'nid')) {
  407. $alignment->nid = $featureloc->feature_id->nid;
  408. }
  409. }
  410. foreach ($cfeaturelocs as $featureloc) {
  411. // if type is a 'match' then ignore it. We will handle those below
  412. if (preg_match('/(^match$|^.*?_match|match_part)$/', $featureloc->feature_id->type_id->name)) {
  413. continue;
  414. }
  415. $alignment = new stdClass();
  416. $alignment->record = $featureloc;
  417. $alignment->name = $featureloc->srcfeature_id->name;
  418. $alignment->type = $featureloc->srcfeature_id->type_id->name;
  419. $alignment->fmin = $featureloc->fmin;
  420. $alignment->is_fmin_partial = $featureloc->is_fmin_partial;
  421. $alignment->fmax = $featureloc->fmax;
  422. $alignment->is_fmax_partial = $featureloc->is_fmax_partial;
  423. $alignment->phase = $featureloc->phase;
  424. $alignment->strand = $featureloc->strand;
  425. $alignments[] = $alignment;
  426. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  427. $alignment->nid = $featureloc->srcfeature_id->nid;
  428. }
  429. }
  430. // in matching features, the left feature is always the feature
  431. // provided to this function.
  432. foreach ($mfeaturelocs as $featureloc) {
  433. // get more information about the right feature
  434. $select = array('feature_id' => $featureloc->right_srcfeature_id);
  435. $rfeature = chado_generate_var('feature', $select);
  436. // now add to the list
  437. $alignment = new stdClass();
  438. $alignment->record = $featureloc;
  439. $alignment->right_feature = $rfeature;
  440. $alignment->name = $rfeature->name;
  441. $alignment->type = $rfeature->type_id->name;
  442. $alignment->fmin = $featureloc->left_fmin;
  443. $alignment->is_fmin_partial = $featureloc->left_is_fmin_partial;
  444. $alignment->fmax = $featureloc->left_fmax;
  445. $alignment->is_fmax_partial = $featureloc->left_is_fmax_partial;
  446. $alignment->phase = $featureloc->left_phase;
  447. $alignment->strand = $featureloc->left_strand;
  448. $alignment->right_fmin = $featureloc->right_fmin;
  449. $alignment->right_is_fmin_partial = $featureloc->right_is_fmin_partial;
  450. $alignment->right_fmax = $featureloc->right_fmax;
  451. $alignment->right_is_fmax_partial = $featureloc->right_is_fmax_partial;
  452. $alignment->right_phase = $featureloc->right_phase;
  453. $alignment->right_strand = $featureloc->right_strand;
  454. $alignments[] = $alignment;
  455. if (property_exists($rfeature, 'nid')) {
  456. $alignment->nid = $rfeature->nid;
  457. }
  458. }
  459. $feature->all_featurelocs = $alignments;
  460. }
  461. /**
  462. * This function is for features that align through an intermediate such
  463. * as 'EST_match' or 'match'. This occurs in the case where two sequences
  464. * align but where one does not align perfectly. Some ESTs may be in a contig
  465. * but not all of the EST. Portions may overhang and not be included in the
  466. * consensus if quality is bad.
  467. * For example:
  468. * Feature 1: Contig --------------------
  469. * Feature 2: EST_match -------
  470. * Feature 3: EST ---------
  471. *
  472. * The feature provided to the function will always be the feature 1. The
  473. * featureloc columns prefixed with 'right' (e.g. right_fmin) belong to the
  474. * alignment of feature 3 with feature 2
  475. *
  476. * Features may align to more than one feature and are not matches. We do
  477. * not want to include these, so we have to filter on the SO terms:
  478. * match, or %_match
  479. *
  480. * @ingroup tripal_legacy_feature
  481. */
  482. function tripal_feature_get_matched_alignments($feature) {
  483. $sql = "
  484. SELECT
  485. FL1.featureloc_id as left_featureloc_id,
  486. FL1.srcfeature_id as left_srcfeature_id,
  487. FL1.feature_id as left_feature_id,
  488. FL1.fmin as left_fmin,
  489. FL1.is_fmin_partial as left_is_fmin_partial,
  490. FL1.fmax as left_fmax,
  491. FL1.is_fmax_partial as left_is_fmax_partial,
  492. FL1.strand as left_strand,
  493. FL1.phase as left_phase,
  494. FL1.locgroup as left_locgroup,
  495. FL1.rank as left_rank,
  496. FL2.featureloc_id as right_featureloc_id,
  497. FL2.srcfeature_id as right_srcfeature_id,
  498. FL2.feature_id as right_feature_id,
  499. FL2.fmin as right_fmin,
  500. FL2.is_fmin_partial as right_is_fmin_partial,
  501. FL2.fmax as right_fmax,
  502. FL2.is_fmax_partial as right_is_fmax_partial,
  503. FL2.strand as right_strand,
  504. FL2.phase as right_phase,
  505. FL2.locgroup as right_locgroup,
  506. FL2.rank as right_rank
  507. FROM {feature} F1
  508. INNER JOIN {featureloc} FL1 on FL1.srcfeature_id = F1.feature_id
  509. INNER JOIN {feature} F2 on FL1.feature_id = F2.feature_id
  510. INNER JOIN {featureloc} FL2 on FL2.feature_id = F2.feature_id
  511. INNER JOIN {cvterm} CVT2 on F2.type_id = CVT2.cvterm_id
  512. WHERE
  513. F1.feature_id = :feature_id AND
  514. (CVT2.name = 'match' or CVT2.name like '%_match')
  515. ORDER BY FL1.fmin
  516. ";
  517. $results = chado_query($sql, array(':feature_id' => $feature->feature_id));
  518. // iterate through the results and add them to our featurelocs array
  519. $featurelocs = array();
  520. while ($fl = $results->fetchObject()) {
  521. // ignore featurelocs where the left and right srcfeature is the same
  522. if (strcmp($fl->left_srcfeature_id, $fl->right_srcfeature_id) == 0) {
  523. continue;
  524. }
  525. $featurelocs[] = $fl ;
  526. }
  527. return $featurelocs;
  528. }
  529. /**
  530. *
  531. *
  532. * @ingroup tripal_legacy_feature
  533. */
  534. function tripal_feature_preprocess_tripal_organism_feature_counts(&$variables, $hook) {
  535. $organism = $variables['node']->organism;
  536. $organism->feature_counts = tripal_feature_load_organism_feature_counts($organism);
  537. }
  538. /**
  539. * Load the arguments for the organism feature counts browser
  540. *
  541. * @param $organism
  542. * The organism of interest
  543. *
  544. * @ingroup tripal_legacy_feature
  545. */
  546. function tripal_feature_load_organism_feature_counts($organism) {
  547. $args = array();
  548. $order = array();
  549. $names = array();
  550. // We should not assume this table is present since it is a materialized view.
  551. if (!chado_table_exists('organism_feature_count')) {
  552. return NULL;
  553. }
  554. // build the where clause for the SQL statement if we have a custom term list
  555. // we'll also keep track of the names the admin provided (if any) and the
  556. // order that the terms should appear.
  557. $is_custom = 0;
  558. $temp = rtrim(variable_get('tripal_feature_summary_report_mapping', ''));
  559. $where = '';
  560. if ($temp) {
  561. $is_custom = 1;
  562. $temp = explode("\n", $temp);
  563. $i = 0;
  564. foreach ($temp as $value) {
  565. // separate the key value pairs
  566. $temp2 = explode("=", $value);
  567. $feature_type = rtrim($temp2[0]);
  568. $order[] = $feature_type; // save the order of the these terms
  569. $where .= " OFC.feature_type = :name$i OR ";
  570. $args[":name$i"] = rtrim($temp2[0]);
  571. // if the admin specified a new name then store that otherwise use the
  572. // the default sequence ontology term name
  573. if(count($temp2) == 2) {
  574. $names[] = rtrim($temp2[1]);
  575. }
  576. else {
  577. $names[] = $feature_type;
  578. }
  579. $i++;
  580. }
  581. if ($where) {
  582. $where = drupal_substr($where, 0, -4); # remove OR from the end
  583. $where = "($where) AND";
  584. }
  585. }
  586. // get the feature counts. This is dependent on a materialized view
  587. // installed with the organism module
  588. $sql = "
  589. SELECT OFC.num_features,OFC.feature_type,CVT.definition
  590. FROM {organism_feature_count} OFC
  591. INNER JOIN {cvterm} CVT on OFC.cvterm_id = CVT.cvterm_id
  592. WHERE $where organism_id = :organism_id
  593. ORDER BY num_features desc
  594. ";
  595. $args[':organism_id'] = $organism->organism_id;
  596. $org_features = chado_query($sql, $args);
  597. // iterate through the types
  598. $types = array();
  599. while ($type = $org_features->fetchObject()) {
  600. $types[$type->feature_type] = $type;
  601. // if we don't have an order this means we didn't go through the loop
  602. // above to set the names, so do that now
  603. if (!$is_custom) {
  604. $names[] = $type->feature_type;
  605. $order[] = $type->feature_type;
  606. }
  607. }
  608. // now reorder the types
  609. $ordered_types = array();
  610. foreach ($order as $type) {
  611. if (array_key_exists($type, $types)) {
  612. $ordered_types[] = $types[$type];
  613. }
  614. }
  615. return array(
  616. 'types' => $ordered_types,
  617. 'names' => $names
  618. );
  619. }
  620. /**
  621. * Using the chado_expand_var function to retrieve a set
  622. * of relationships can be very slow, especialy if there are many relationships
  623. * This function is intended to help speed up the retrieval of relationships
  624. * by only retrieving the base information for the relationship and returning
  625. * an array with
  626. *
  627. * @param $feature
  628. * The feature object
  629. * @return
  630. * An array with two objects
  631. *
  632. * @ingroup tripal_legacy_feature_api
  633. */
  634. function tripal_feature_get_feature_relationships($feature) {
  635. // expand the feature object to include the feature relationships.
  636. $options = array(
  637. 'return_array' => 1,
  638. 'order_by' => array('rank' => 'ASC'),
  639. // we don't want to fully recurse we only need information about the
  640. // relationship type and the object and subject features (including feature type
  641. // and organism)
  642. 'include_fk' => array(
  643. 'type_id' => 1,
  644. 'object_id' => array(
  645. 'type_id' => 1,
  646. 'organism_id' => 1
  647. ),
  648. 'subject_id' => array(
  649. 'type_id' => 1,
  650. 'organism_id' => 1
  651. ),
  652. ),
  653. );
  654. $feature = chado_expand_var($feature, 'table', 'feature_relationship', $options);
  655. // get the subject relationships
  656. $srelationships = $feature->feature_relationship->subject_id;
  657. $orelationships = $feature->feature_relationship->object_id;
  658. // get alignment as child. The $feature->featureloc element
  659. // is already populated from the alignment preprocess function
  660. $options = array(
  661. 'include_fk' => array(
  662. 'srcfeature_id' => 1,
  663. 'feature_id' => 1,
  664. ),
  665. );
  666. $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
  667. $cfeaturelocs = $feature->featureloc->feature_id;
  668. if (!$cfeaturelocs) {
  669. $cfeaturelocs = array();
  670. }
  671. elseif (!is_array($cfeaturelocs)) {
  672. $cfeaturelocs = array($cfeaturelocs);
  673. }
  674. // prepare the SQL statement to get the featureloc for the
  675. // feature in the relationships.
  676. $flrels_sql = "
  677. SELECT
  678. FL.featureloc_id, F.name as srcfeature_name, FL.srcfeature_id,
  679. FL.feature_id, FL.fmin, FL.fmax, FL.strand, FL.phase
  680. FROM {featureloc} FL
  681. INNER JOIN {feature} F ON F.feature_id = FL.srcfeature_id
  682. WHERE FL.feature_id = :feature_id and FL.srcfeature_id = :srcfeature_id
  683. ";
  684. // combine both object and subject relationshisp into a single array
  685. $relationships = array();
  686. $relationships['object'] = array();
  687. $relationships['subject'] = array();
  688. // iterate through the object relationships
  689. if ($orelationships) {
  690. foreach ($orelationships as $relationship) {
  691. $rel = new stdClass();
  692. // get locations where the child feature and this feature overlap with the
  693. // same landmark feature.
  694. $rel->child_featurelocs = array();
  695. foreach ($cfeaturelocs as $featureloc) {
  696. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->subject_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  697. while ($loc = $res->fetchObject()) {
  698. // add in the node id of the src feature if it exists and save this location
  699. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  700. $loc->nid = $featureloc->srcfeature_id->nid;
  701. }
  702. $rel->child_featurelocs[] = $loc;
  703. }
  704. }
  705. $rel->record = $relationship;
  706. // get the relationship and child types
  707. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  708. $child_type = $relationship->subject_id->type_id->name;
  709. // get the node id of the subject
  710. $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  711. $n = db_query($sql, array(':feature_id' => $relationship->subject_id->feature_id))->fetchObject();
  712. if ($n) {
  713. $rel->record->nid = $n->nid;
  714. }
  715. if (!array_key_exists($rel_type, $relationships['object'])) {
  716. $relationships['object'][$rel_type] = array();
  717. }
  718. if (!array_key_exists($child_type, $relationships['object'][$rel_type])) {
  719. $relationships['object'][$rel_type][$child_type] = array();
  720. }
  721. $relationships['object'][$rel_type][$child_type][] = $rel;
  722. }
  723. }
  724. // now add in the subject relationships
  725. if ($srelationships) {
  726. foreach ($srelationships as $relationship) {
  727. $rel = new stdClass();
  728. // get locations where this feature overlaps with the parent
  729. $rel->parent_featurelocs = array();
  730. foreach ($cfeaturelocs as $featureloc) {
  731. $res = chado_query($flrels_sql, array(':feature_id' => $relationship->object_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
  732. while ($loc = $res->fetchObject()) {
  733. // add in the node id of the src feature if it exists and save this location
  734. if (property_exists($featureloc->srcfeature_id, 'nid')) {
  735. $loc->nid = $featureloc->srcfeature_id->nid;
  736. }
  737. $rel->parent_featurelocs[] = $loc;
  738. }
  739. }
  740. $rel->record = $relationship;
  741. $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
  742. $parent_type = $relationship->object_id->type_id->name;
  743. // get the node id of the subject
  744. $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  745. $n = db_query($sql, array(':feature_id' => $relationship->object_id->feature_id))->fetchObject();
  746. if ($n) {
  747. $rel->record->nid = $n->nid;
  748. }
  749. if (!array_key_exists($rel_type, $relationships['subject'])) {
  750. $relationships['subject'][$rel_type] = array();
  751. }
  752. if (!array_key_exists($parent_type, $relationships['subject'][$rel_type])) {
  753. $relationships['subject'][$rel_type][$parent_type] = array();
  754. }
  755. $relationships['subject'][$rel_type][$parent_type][] = $rel;
  756. }
  757. }
  758. return $relationships;
  759. }
  760. /**
  761. *
  762. */
  763. function tripal_feature_preprocess_tripal_feature_bar_chart_type_organism_summary(&$vars) {
  764. // Add in all the javascript/css files.
  765. tripal_add_d3js();
  766. drupal_add_css(drupal_get_path('module','tripal_feature') . '/theme/css/tripal_feature.css');
  767. drupal_add_js(drupal_get_path('module','tripal_feature') . '/theme/js/tripalFeature.adminChart.js');
  768. // Retrieve and process all the data and save it as javascript settings.
  769. //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  770. // We are using the organism_feature_count materialized view as the source for our data.
  771. // Thus grab all the records from this materialized view.
  772. $organism_feature_count = chado_select_record(
  773. 'organism_feature_count',
  774. array('*'),
  775. array(),
  776. array('order_by' => array('genus' => 'ASC', 'species' => 'ASC', 'feature_type' => 'ASC', 'num_features' => 'DESC'))
  777. );
  778. // Initialize variables.
  779. $chart = array();
  780. $type_names = array();
  781. $organism_names = array();
  782. $max_bar_height = 0;
  783. // Process each row of the materialzied view into the chart array.
  784. // Note: it's first keyed by type since each type will be a bar. Each type will have
  785. // a "bars" array with the start (y0) and end (y1) height on the bar for a given
  786. // organism. Finally we keep a record of the names of the types & organisms
  787. // for axis' and legend generation respectively.
  788. foreach ($organism_feature_count as $row) {
  789. // Build up the easy details for the current row's type. These will be overridden
  790. // multiple times but that's more efficient than checking each time.
  791. $chart[$row->cvterm_id]['cvterm_id'] = $row->cvterm_id;
  792. $chart[$row->cvterm_id]['name'] = str_replace('_', ' ', $row->feature_type);
  793. // Save the name of the type and organism into their respective arrays
  794. // for generation of axis' and legends for the chart.
  795. $type_names[$row->cvterm_id] = $row->feature_type;
  796. $organism_names[$row->organism_id] = $row->genus . ' ' . $row->species;
  797. // Save information about the current organism. This isn't actually used by the
  798. // chart but can be used to debug the bar generation to follow.
  799. $chart[$row->cvterm_id]['organisms'][] = array(
  800. 'name' => $row->genus . ' ' . $row->species,
  801. 'value' => (int) $row->num_features
  802. );
  803. // Now to build the bar array with the start (y0) and end (y1) height on the
  804. // bar for a given organism.
  805. // NOTE: we cannot assume the types are all in order so store y0 & y1 in the
  806. // $chart[type] array.
  807. // If y0 has not yet been set for this type then we're starting with the first
  808. // chunk (organism) on the bar.
  809. if (!isset($chart[$row->cvterm_id]['y0'])) {
  810. $chart[$row->cvterm_id]['y0'] = 0;
  811. $chart[$row->cvterm_id]['y1'] = $row->num_features;
  812. }
  813. // Otherwise, add the next chunk (organism) on top of the pre-existing bar.
  814. else {
  815. $chart[$row->cvterm_id]['y0'] = $chart[$row->cvterm_id]['y1'];
  816. $chart[$row->cvterm_id]['y1'] = $chart[$row->cvterm_id]['y0'] + $row->num_features;
  817. }
  818. // Now save the bar chunk we just determined.
  819. $chart[$row->cvterm_id]['bars'][] = array(
  820. 'name' => $row->genus . ' ' . $row->species,
  821. 'y0' => $chart[$row->cvterm_id]['y0'],
  822. 'y1' => $chart[$row->cvterm_id]['y1'],
  823. );
  824. // We also need to keep track of the total number of features for a single bar (Type).
  825. $chart[$row->cvterm_id]['total_features'] = (int) $chart[$row->cvterm_id]['y1'];
  826. // And the maximum "height" for all bars.
  827. if ($max_bar_height < $chart[$row->cvterm_id]['total_features']) {
  828. $max_bar_height = (int) $chart[$row->cvterm_id]['total_features'];
  829. }
  830. }
  831. // Sort based on the total number of features.
  832. // NOTE: This changes the keys so it's no longer the organism/type_id.
  833. usort($chart, 'tripal_feature_admin_summary_sort');
  834. sort($type_names);
  835. sort($organism_names);
  836. // We also need to add information about the materialized views
  837. // so that admin can update it and know how recent the data is.
  838. $mview = db_query('
  839. SELECT mview_id, name, last_update
  840. FROM tripal_mviews
  841. WHERE mv_table=:mv_table',
  842. array(':mv_table' => 'organism_feature_count')
  843. )->fetchObject();
  844. $vars['chart_details'] = array(
  845. 'summary' => $chart,
  846. 'types' => $type_names,
  847. 'organisms' => $organism_names,
  848. 'legendPosition' => 'top',
  849. 'maxBarHeight' => $max_bar_height,
  850. 'mviewUrl' => url('admin/tripal/storage/chado/mviews/update/' . $mview->mview_id),
  851. 'mviewTable' => $mview->name,
  852. 'mviewLastUpdate' => $mview->last_update ? format_date($mview->last_update) : '',
  853. );
  854. // Save everything we just determined as a Drupal JS settings so that we have access to
  855. // it in our js script.
  856. drupal_add_js(array('tripalFeature' => array('admin' => $vars['chart_details'])), 'setting');
  857. }
  858. /**
  859. * Get features related to the current feature to a given depth. Recursive function.
  860. *
  861. * @param $feature_id
  862. * @param $substitute
  863. * @param $levels
  864. * @param $base_type_id
  865. * @param $depth
  866. *
  867. */
  868. function tripal_feature_get_aggregate_relationships($feature_id, $substitute=1,
  869. $levels=0, $base_type_id=NULL, $depth=0) {
  870. // we only want to recurse to as many levels deep as indicated by the
  871. // $levels variable, but only if this variable is > 0. If 0 then we
  872. // recurse until we reach the end of the relationships tree.
  873. if ($levels > 0 and $levels == $depth) {
  874. return NULL;
  875. }
  876. // first get the relationships for this feature
  877. return tripal_feature_load_relationships($feature_id, 'as_object');
  878. }
  879. /**
  880. * Get the relationships for a feature.
  881. *
  882. * @param $feature_id
  883. * The feature to get relationships for
  884. * @param $side
  885. * The side of the relationship this feature is (ie: 'as_subject' or
  886. * 'as_object')
  887. *
  888. *
  889. */
  890. function tripal_feature_load_relationships($feature_id, $side = 'as_subject') {
  891. // Get the relationships for this feature. The query below is used for both
  892. // querying the object and subject relationships
  893. $sql = "
  894. SELECT
  895. FS.name as subject_name, FS.uniquename as subject_uniquename,
  896. CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
  897. FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
  898. CVT.name as rel_type,
  899. FO.name as object_name, FO.uniquename as object_uniquename,
  900. CVTO.name as object_type, CVTO.cvterm_id as object_type_id
  901. FROM {feature_relationship} FR
  902. INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
  903. INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
  904. INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
  905. INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
  906. INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
  907. ";
  908. if (strcmp($side, 'as_object')==0) {
  909. $sql .= " WHERE FR.object_id = :feature_id";
  910. }
  911. if (strcmp($side, 'as_subject')==0) {
  912. $sql .= " WHERE FR.subject_id = :feature_id";
  913. }
  914. $sql .= " ORDER BY FR.rank";
  915. // Get the relationships.
  916. $results = chado_query($sql, array(':feature_id' => $feature_id));
  917. // Iterate through the relationships, put these in an array and add
  918. // in the Drupal node id if one exists.
  919. $i=0;
  920. $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
  921. $relationships = array();
  922. while ($rel = $results->fetchObject()) {
  923. $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
  924. if ($node) {
  925. $rel->subject_nid = $node->nid;
  926. }
  927. $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
  928. if ($node) {
  929. $rel->object_nid = $node->nid;
  930. }
  931. $relationships[$i++] = $rel;
  932. }
  933. return $relationships;
  934. }