tripal_analysis_kegg.module 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. <?php
  2. /*******************************************************************************
  3. *
  4. ******************************************************************************/
  5. function tripal_analysis_kegg_init(){
  6. // add the tripal_analysis_kegg JS and CSS
  7. drupal_add_js(drupal_get_path('theme', 'tripal').'/js/tripal_analysis_kegg.js');
  8. drupal_add_css(drupal_get_path('theme', 'tripal').'/css/tripal_analysis_kegg.css');
  9. // add the jsTree JS and CSS
  10. drupal_add_css(drupal_get_path('theme', 'tripal').'/js/jsTree/source/tree_component.css');
  11. drupal_add_js (drupal_get_path('theme', 'tripal').'/js/jsTree/source/_lib.js');
  12. drupal_add_js (drupal_get_path('theme', 'tripal').'/js/jsTree/source/tree_component.js');
  13. }
  14. /*******************************************************************************
  15. * Provide information to drupal about the node types that we're creating
  16. * in this module
  17. */
  18. function tripal_analysis_kegg_node_info() {
  19. $nodes = array();
  20. $nodes['chado_analysis_kegg'] = array(
  21. 'name' => t('Analysis: KEGG'),
  22. 'module' => 'chado_analysis_kegg',
  23. 'description' => t('Results from a KEGG/KAAS analysis'),
  24. 'has_title' => FALSE,
  25. 'title_label' => t('Analysis: KEGG'),
  26. 'has_body' => FALSE,
  27. 'body_label' => t('KEGG Analysis Description'),
  28. 'locked' => TRUE
  29. );
  30. return $nodes;
  31. }
  32. /*******************************************************************************
  33. * Menu items are automatically added for the new node types created
  34. * by this module to the 'Create Content' Navigation menu item. This function
  35. * adds more menu items needed for this module.
  36. */
  37. function tripal_analysis_kegg_menu() {
  38. $items['brite/%'] = array(
  39. 'title' => t('KEGG BRITE'),
  40. 'page callback' => 'tripal_analysis_kegg_brite',
  41. 'page arguments' => array(1, 2),
  42. 'access arguments' => array('access content'),
  43. 'type' => MENU_CALLBACK
  44. );
  45. $items['tripal_analysis_kegg_org_report/%'] = array(
  46. 'path' => 'tripal_analysis_kegg_org_report',
  47. 'title' => t('Analysis KEGG report'),
  48. 'page callback' => 'tripal_analysis_kegg_org_report',
  49. 'page arguments' => array(1),
  50. 'access arguments' => array('access chado_analysis_kegg content'),
  51. 'type' => MENU_CALLBACK
  52. );
  53. return $items;
  54. }
  55. /*******************************************************************************
  56. * Set the permission types that the chado module uses. Essentially we
  57. * want permissionis that protect creation, editing and deleting of chado
  58. * data objects
  59. */
  60. function tripal_analysis_kegg_perm(){
  61. return array(
  62. 'access chado_analysis_kegg content',
  63. 'create chado_analysis_kegg content',
  64. 'delete chado_analysis_kegg content',
  65. 'edit chado_analysis_kegg content',
  66. );
  67. }
  68. /*******************************************************************************
  69. * The following function proves access control for users trying to
  70. * perform actions on data managed by this module
  71. */
  72. function chado_analysis_kegg_access($op, $node, $account){
  73. if ($op == 'create') {
  74. return user_access('create chado_analysis_kegg content', $account);
  75. }
  76. if ($op == 'update') {
  77. if (user_access('edit chado_analysis_kegg content', $account)) {
  78. return TRUE;
  79. }
  80. }
  81. if ($op == 'delete') {
  82. if (user_access('delete chado_analysis_kegg content', $account)) {
  83. return TRUE;
  84. }
  85. }
  86. if ($op == 'view') {
  87. if (user_access('access chado_analysis_kegg content', $account)) {
  88. return TRUE;
  89. }
  90. }
  91. return FALSE;
  92. }
  93. /*******************************************************************************
  94. */
  95. function tripal_analysis_kegg_brite($analysis_id, $type_id, $ajax){
  96. // If not called by ajax
  97. if (!$ajax) {
  98. $content .=
  99. "<div id=\"tripal_kegg_brite_results\" class=\"tripal_kegg_brite-info-box\">
  100. <table>
  101. <tr>
  102. <th>KEGG BRITE</th>
  103. <th id=\"tripal_kegg_brite_header\">Hierarchy:</th>
  104. </tr>
  105. <tr>
  106. <td nowrap valign=\"top\">
  107. ";
  108. // List all BRITE terms on the left
  109. $sql = "SELECT DISTINCT CVT.name, CVT.cvterm_id
  110. FROM {cvterm} CVT
  111. INNER JOIN analysisprop AP ON CVT.cvterm_id = AP.type_id
  112. WHERE AP.analysis_id = %d AND CVT.definition LIKE 'KEGG BRITE term: %'
  113. ORDER BY CVT.cvterm_id";
  114. $previous_db = tripal_db_set_active('chado');
  115. $result = db_query($sql, $analysis_id);
  116. tripal_db_set_active($previous_db);
  117. while ($brite_term = db_fetch_object($result)) {
  118. $url = url("brite/$analysis_id/$brite_term->cvterm_id/1");
  119. $content .= "<li class=\"tripal_kegg_brite_terms\"><a onclick=\"return tripal_update_brite(".
  120. "this,$brite_term->cvterm_id)\" href=\"$url\">
  121. $brite_term->name
  122. </a></li>";
  123. }
  124. // Show the hierarchy tree
  125. $content .="</td>
  126. <td nowrap id=\"tripal_kegg_brite_hierarchy\" valign=\"top\">";
  127. $content .= "<i>Note:</i> Click a BRITE term for its functional hierarchy";
  128. // If called by ajax, generate tree structure
  129. } else {
  130. // Get BRITE term from cvterm table
  131. $previous_db = tripal_db_set_active('chado');
  132. $sql = 'SELECT name FROM {cvterm} WHERE cvterm_id=%d';
  133. $brite_term = db_result(db_query($sql, $type_id));
  134. // Get BRITE hierarchy tree
  135. $sql = "SELECT value
  136. FROM {analysisprop} AP
  137. INNER JOIN CVterm CVT on AP.type_id = CVT.cvterm_id
  138. INNER JOIN CV on CVT.cv_id = CV.cv_id
  139. WHERE CV.name = 'tripal' and CVT.name = '%s'
  140. AND AP.analysis_id = %d";
  141. $result = db_fetch_object(db_query($sql, $brite_term, $analysis_id));
  142. tripal_db_set_active($previous_db);
  143. $content .= "<div class=\"tripal_kegg_brite_tree\" id=\"tripal_kegg_brite_tree_$type_id\">$result->value</div>";
  144. }
  145. if (!$ajax) {
  146. $content .= " </td>
  147. </tr>
  148. </table>
  149. </div>";
  150. }
  151. // since this function provides output for addition into
  152. // an analysis page, as well as an AJAX refresh of content
  153. // within the BRITE hierarchy we need to setup the return
  154. // different depending on the request type
  155. if($ajax){
  156. drupal_json(array('update' => $content,
  157. 'id' => "tripal_kegg_brite_tree_$type_id",
  158. 'brite_term' => "Hierarchy: $brite_term"));
  159. } else {
  160. return $content;
  161. }
  162. }
  163. /*******************************************************************************
  164. * Provide a KEGG Analysis form
  165. */
  166. function chado_analysis_kegg_form ($node){
  167. // add in the default fields
  168. $form = chado_analysis_form($node);
  169. // set the defaults
  170. $kegg = $node->analysis->tripal_analysis_kegg;
  171. $query_re = $kegg->query_re;
  172. $query_type = $kegg->query_type;
  173. $query_uniquename = $kegg->query_uniquename;
  174. $hierfile = $kegg->hierfile;
  175. $moreSettings ['kegg'] = 'KEGG Analysis Settings';
  176. $form['kegg'] = array(
  177. '#title' => t('KEGG Settings'),
  178. '#type' => 'fieldset',
  179. '#description' => t('Specific Settings for KEGG Analysis.'),
  180. '#collapsible' => TRUE,
  181. '#attributes' => array('id' => 'kegg-extra-settings'),
  182. '#weight' => 11
  183. );
  184. $form['kegg']['hierfile'] = array(
  185. '#title' => t('KAAS hier.tar.gz Output File'),
  186. '#type' => 'textfield',
  187. '#description' => t('The full path to the hier.tar.gz file generated by KAAS.
  188. Alternatively, you can input the full path to the directory
  189. that contains decompressed kegg files.'),
  190. '#default_value' => $hierfile,
  191. );
  192. $form['kegg']['query_re'] = array(
  193. '#title' => t('Query Name RE'),
  194. '#type' => 'textfield',
  195. '#description' => t('Enter the regular expression that will extract the '.
  196. 'feature name from the results line in the KEGG heir results. This will be '.
  197. 'the same as the definition line in the query FASTA file used for the analysis. This option is '.
  198. 'is only required when the query does not identically match a feature '.
  199. 'in the database.'),
  200. '#default_value' => $query_re,
  201. );
  202. $form['kegg']['query_type'] = array(
  203. '#title' => t('Query Type'),
  204. '#type' => 'textfield',
  205. '#description' => t('Please enter the Sequence Ontology term that describes '.
  206. 'the query sequences used for KEGG. This is only necessary if two '.
  207. 'or more sequences have the same name.'),
  208. '#default_value' => $query_type,
  209. );
  210. $form['kegg']['query_uniquename'] = array(
  211. '#title' => t('Use Unique Name'),
  212. '#type' => 'checkbox',
  213. '#description' => t('Select this checboxk if the feature name in the KEGG heir file '.
  214. 'matches the uniquename in the database. By default, the feature will '.
  215. 'be mapped to the "name" of the feature.'),
  216. '#default_value' => $query_uniquename,
  217. );
  218. $form['kegg']['keggjob'] = array(
  219. '#type' => 'checkbox',
  220. '#title' => t('Submit a job to parse the kegg output into analysisfeatureprop table'),
  221. '#description' => t('Note: features associated with the KAAS results must '.
  222. 'exist in chado before parsing the file. Otherwise, KEGG '.
  223. 'results that cannot be linked to a feature will be '.
  224. 'discarded.'),
  225. );
  226. return $form;
  227. }
  228. /*******************************************************************************
  229. *
  230. */
  231. function chado_analysis_kegg_insert($node){
  232. // insert the analysis
  233. chado_analysis_insert($node);
  234. // set the type for this analysis
  235. tripal_analysis_insert_property($node->analysis_id,'analysis_type','tripal_analysis_kegg');
  236. // now add in the remaining settings as a single property but separated by bars
  237. tripal_analysis_insert_property($node->analysis_id,'analysis_kegg_settings',$node->hierfile);
  238. tripal_analysis_insert_property($node->analysis_id,'analysis_kegg_query_re',$node->query_re);
  239. tripal_analysis_insert_property($node->analysis_id,'analysis_kegg_query_type',$node->query_type);
  240. tripal_analysis_insert_property($node->analysis_id,'analysis_kegg_query_uniquename',$node->query_uniquename);
  241. // Add a job if the user wants to parse the html output
  242. chado_analysis_kegg_submit_job($node);
  243. }
  244. /**
  245. *
  246. */
  247. function chado_analysis_kegg_submit_job($node){
  248. global $user;
  249. if($node->keggjob) {
  250. $job_args[0] = $node->analysis_id;
  251. $job_args[1] = $node->hierfile;
  252. $job_args[2] = base_path();
  253. $job_args[3] = $node->query_re;
  254. $job_args[4] = $node->query_type;
  255. $job_args[5] = $node->query_uniquename;
  256. if (is_readable($node->hierfile)) {
  257. $fname = preg_replace("/.*\/(.*)/", "$1", $node->hierfile);
  258. tripal_add_job("Parse KAAS output: $fname",'tripal_analysis_kegg',
  259. 'tripal_analysis_kegg_parseHierFile', $job_args, $user->uid);
  260. } else {
  261. drupal_set_message("Can not open KAAS hier.tar.gz output file. Job not scheduled.");
  262. }
  263. }
  264. }
  265. /*******************************************************************************
  266. * Delete KEGG anlysis
  267. */
  268. function chado_analysis_kegg_delete($node){
  269. chado_analysis_delete($node);
  270. }
  271. /*******************************************************************************
  272. * Update KEGG analysis
  273. */
  274. function chado_analysis_kegg_update($node){
  275. // insert the analysis
  276. chado_analysis_update($node);
  277. // set the type for this analysis
  278. tripal_analysis_update_property($node->analysis_id,'analysis_type','tripal_analysis_kegg',1);
  279. // now add in the remaining settings as a single property but separated by bars
  280. tripal_analysis_update_property($node->analysis_id,'analysis_kegg_settings',$node->hierfile,1);
  281. tripal_analysis_update_property($node->analysis_id,'analysis_kegg_query_re',$node->query_re,1);
  282. tripal_analysis_update_property($node->analysis_id,'analysis_kegg_query_type',$node->query_type,1);
  283. tripal_analysis_update_property($node->analysis_id,'analysis_kegg_query_uniquename',$node->query_uniquename,1);
  284. // Add a job if the user wants to parse the html output
  285. chado_analysis_kegg_submit_job($node);
  286. }
  287. /*******************************************************************************
  288. * When a node is requested by the user this function is called to allow us
  289. * to add auxiliary data to the node object.
  290. */
  291. function chado_analysis_kegg_load($node){
  292. // load the default set of analysis fields
  293. $additions = chado_analysis_load($node);
  294. // create some variables for easier lookup
  295. $analysis = $additions->analysis;
  296. $analysis_id = $analysis->analysis_id;
  297. // get the heirfile name
  298. $hierfile = tripal_analysis_get_property($analysis_id,'analysis_kegg_settings');
  299. $query_re = tripal_analysis_get_property($analysis->analysis_id,'analysis_kegg_query_re');
  300. $query_type = tripal_analysis_get_property($analysis->analysis_id,'analysis_kegg_query_type');
  301. $query_uniquename= tripal_analysis_get_property($analysis->analysis_id,'analysis_kegg_query_uniquename');
  302. $analysis->tripal_analysis_kegg->hierfile = $hierfile->value;
  303. $analysis->tripal_analysis_kegg->query_re = $query_re->value;
  304. $analysis->tripal_analysis_kegg->query_type = $query_type->value;
  305. $analysis->tripal_analysis_kegg->query_uniquename= $query_uniquename->value;
  306. return $additions;
  307. }
  308. /**
  309. *
  310. */
  311. function chado_analysis_kegg_view ($node, $teaser = FALSE, $page = FALSE) {
  312. // use drupal's default node view:
  313. if (!$teaser) {
  314. $node = node_prepare($node, $teaser);
  315. // When previewing a node submitting form, it shows 'Array' instead of
  316. // correct date format. We need to format the date here
  317. $time = $node->timeexecuted;
  318. if(is_array($time)){
  319. $month = $time['month'];
  320. $day = $time['day'];
  321. $year = $time['year'];
  322. $timestamp = $year.'-'.$month.'-'.$day;
  323. $node->timeexecuted = $timestamp;
  324. }
  325. }
  326. return $node;
  327. }
  328. /********************************************************************************
  329. */
  330. function tripal_analysis_kegg_parseHierFile ($analysis_id, $hierfile, $base_path,
  331. $query_re,$query_type,$query_uniquename,$job_id) {
  332. // If user input a file (e.g. hier.tar.gz), decompress it first
  333. if (is_file($hierfile)) {
  334. $data_dir = file_directory_path() . "/tripal/tripal_analysis_kegg";
  335. $stderr = shell_exec("cd $data_dir; tar -zxf $hierfile;");
  336. print "$stderr\n";
  337. $hierdir = $data_dir."/hier";
  338. // Otherwise, treat it as a directory
  339. } else {
  340. $hierdir = $hierfile;
  341. }
  342. $dir_handle = @opendir($hierdir) or die("Unable to open $hierdir");
  343. $total_files = count(glob($hierdir . '/*.*'));
  344. print "There are $total_files keg file(s).\n";
  345. $interval = intval($total_files * 0.01);
  346. $no_file = 0;
  347. // Remove the analysis feature this analysis
  348. // we will rebuild them from just this parsing
  349. $select = array('analysis_id' => $analysis_id);
  350. if(!tripal_core_chado_delete('analysisfeature',$select)){
  351. print "ERROR: Cannot prepare the analysis for adding features\n";
  352. exit;
  353. }
  354. while ($file = readdir($dir_handle)) {
  355. if(preg_match("/^.*\.keg/",$file)){
  356. // Update the progress
  357. if ($no_file % $interval == 0) {
  358. $percentage = (int) ($no_file / $total_files * 100);
  359. tripal_job_set_progress($job_id, $percentage);
  360. print $percentage."% ";
  361. }
  362. $no_file ++;
  363. # $heirarchy variable will be set in tripal_analysis_kegg_parse_kegg_file()
  364. $results = tripal_analysis_kegg_parse_kegg_file("$hierdir/$file",$heirarchy,
  365. $analysis_id, $base_path, $query_re,$query_type,$query_uniquename);
  366. # add the item to the database
  367. if(count($results) > 0){
  368. //------------------------------------------------------
  369. // Insert into analysisprop table
  370. //------------------------------------------------------
  371. // Remove the property if it already exists we'll replace it
  372. $sql = "DELETE
  373. FROM {analysisprop}
  374. WHERE analysis_id = %d
  375. AND type_id = (SELECT cvterm_id
  376. FROM {cvterm} CVT
  377. INNER JOIN CV ON CVT.cv_id = CV.cv_id
  378. WHERE CV.name = 'tripal' AND CVT.name = '%s'
  379. )
  380. ";
  381. $previous_db = tripal_db_set_active('chado');
  382. db_result(db_query($sql, $analysis_id, $heirarchy));
  383. tripal_db_set_active($previous_db);
  384. $previous_db = tripal_db_set_active('chado'); // Use chado database
  385. // Get type_id for the BRITE term
  386. $sql = "SELECT cvterm_id
  387. FROM {cvterm} CVT
  388. INNER JOIN CV ON CVT.cv_id = CV.cv_id
  389. WHERE CV.name = 'tripal' AND CVT.name = '%s'";
  390. $brite_cvterm_id = db_result(db_query($sql, $heirarchy));
  391. // convert the array to text for saving in the database
  392. // Replace all single quote as HTML code before insert
  393. $i = 0;
  394. $content = '<ul>';
  395. tripal_analysis_kegg_array2list($results,$content,$i);
  396. $content .= '</ul>';
  397. $content = preg_replace("/\'/", "&#39;", $content);
  398. // Insert the value
  399. $sql = "INSERT INTO {analysisprop} (analysis_id, type_id, value)
  400. VALUES (%d, %d,'$content')";
  401. db_query($sql, $analysis_id, $brite_cvterm_id);
  402. tripal_db_set_active($previous_db); // Use drupal database
  403. }
  404. }
  405. }
  406. print "Done.\n";
  407. closedir($dir_handle);
  408. // If user input a file, remove decompressed files after parsing
  409. if (is_file($hierfile)) {
  410. $stderr = shell_exec("rm -r $hierdir;");
  411. print "$stderr\n";
  412. }
  413. return;
  414. }
  415. /**
  416. *
  417. */
  418. function tripal_analysis_kegg_array2list($array,&$content,&$i){
  419. foreach($array as $index => $item){
  420. if(is_array($item)){
  421. if(is_numeric($index)){
  422. tripal_analysis_kegg_array2list($item,$content,$i);
  423. } else {
  424. $content .= "<li id=\"term_$i\"><a></a>$index\n<ul>";
  425. $i++;
  426. tripal_analysis_kegg_array2list($item,$content,$i);
  427. $content .= "</ul>\n</li>\n";
  428. }
  429. } else {
  430. $content .= "<li id=\"term_$i\"><a></a>$item</li>\n";
  431. $i++;
  432. }
  433. }
  434. }
  435. /*******************************************************************************
  436. * Parse *.keg files.
  437. * Each file has a definition line. BRITE term is extracted * from this line
  438. * and added to chado as a cvterm. Tree structure for this cvterm is then
  439. * generated and saved to analysisfeature and analysisfeatureprop tables.
  440. */
  441. function tripal_analysis_kegg_parse_kegg_file ($file, &$heirarchy, $analysis_id,
  442. $base_path, $query_re, $query_type, $query_uniquename)
  443. {
  444. print "Parsing $file\n";
  445. // get the 'kegg_brite_data' cvterm
  446. $select = array('name' => 'kegg_brite_data',
  447. 'cv_id' => array('name' => 'tripal'));
  448. $bdt_arr = tripal_core_chado_select('cvterm',array('cvterm_id'),$select);
  449. $brite_id = $bdt_arr[0]->cvterm_id;
  450. $filepos = 0;
  451. // iterate through the lines of the file and recurse through the various levels
  452. $handle = fopen($file,'r');
  453. while($line = fgets($handle)){
  454. $filepos += strlen($line);
  455. $line = trim($line);
  456. // the first line of the file provides the BRITE heirarchy name
  457. if(preg_match("/#.*nbsp;\s(.*)<\/h2>$/",$line,$matches)){
  458. // For each BRITE heirarchy file we'll add an analysisprop where we'll
  459. // store the report. If the CVTerm doesn't exist then add it.
  460. $heirarchy = $matches[1];
  461. $select = array('name' => $heirarchy,'cv_id' => array('name' => 'tripal'));
  462. $cvt_arr = tripal_core_chado_select('cvterm',array('cvterm_id'),$select);
  463. if (count($cvt_arr) == 0) {
  464. tripal_add_cvterms($type, "KEGG BRITE term: $type");
  465. $cvt_arr = tripal_core_chado_select('cvterm',array('cvterm_id'),$select);
  466. }
  467. $heirarchy_id = $cvt_arr[0]->cvterm_id;
  468. // now that we have the file type we can recurse
  469. $next = tripal_analysis_kegg_get_next_line($handle,$filepos);
  470. $results = tripal_analysis_kegg_recurse_heir($handle,$next,$query_re,
  471. $query_type,$query_uniquename,$base_path,$analysis_id,
  472. $brite_id,$heirarchy,$filepos);
  473. }
  474. }
  475. fclose($handle);
  476. return $results;
  477. }
  478. /**
  479. *
  480. */
  481. function tripal_analysis_kegg_recurse_heir($handle, $line,$query_re,
  482. $query_type, $query_uniquename, $base_path, $analysis_id, $brite_id,
  483. $heirarchy,&$filepos)
  484. {
  485. $results = array();
  486. // get the current level and the value
  487. $level = $line[0];
  488. $value = $line[1];
  489. // now get the next line to see what is coming next. If the
  490. // next level is greater then recurse immediately.
  491. $prevpos = $filepos;
  492. while($next = tripal_analysis_kegg_get_next_line($handle,$filepos)){
  493. $next_level = $next[0];
  494. $next_value = $next[1];
  495. // check this line to see if it has a feature we need to keep
  496. $ret = tripal_analysis_kegg_check_line_handle_feature($query_re,
  497. $query_type, $query_uniquename, $base_path, $analysis_id, $brite_id,
  498. $heirarchy,$value);
  499. if($ret){
  500. $results[] = $ret;
  501. }
  502. // if we're going up a level then recurse immediately and add results to our array
  503. if(ord($next_level) > ord($level)){
  504. // now recurse
  505. $ret = tripal_analysis_kegg_recurse_heir($handle,$next,
  506. $query_re,$query_type, $query_uniquename, $base_path, $analysis_id,
  507. $brite_id,$heirarchy,$filepos);
  508. if(count($ret) > 0){
  509. $results[][$value] = $ret;
  510. }
  511. }
  512. // if we go down a level on the next line then reset the
  513. // filepointer and return
  514. elseif(ord($next_level) < ord($level)){
  515. fseek($handle,$prevpos);
  516. $filepos = $prevpos;
  517. return $results;
  518. }
  519. else {
  520. $line = $next;
  521. $level = $next[0];
  522. $value = $next[1];
  523. }
  524. $prevpos = $filepos;
  525. }
  526. return $results;
  527. }
  528. /**
  529. *
  530. */
  531. function tripal_analysis_kegg_get_next_line($handle,&$filepos){
  532. $good = 0;
  533. // get the next line in the file
  534. $line = fgets($handle);
  535. $filepos += strlen($line);
  536. // we hit the end of the file, so exit with a null
  537. if(!$line){
  538. return null;
  539. }
  540. while(!$good){
  541. $line = trim($line);
  542. preg_match("/^([ABCDEFGHIJKLMNOP])\s*(.*)/",$line,$matches);
  543. $level = $matches[1];
  544. $value = $matches[2];
  545. // skip lines that aren't data or are empty
  546. if($level and $value) {
  547. // change all relative paths to absolute paths pointing to KEGG (www.genome.jp)
  548. // add id to <a> tags so we can link kegg.gif to it in tripal_analysis_kegg.css
  549. $value = preg_replace("/<a href=\"\//i","<a href=\"http://www.genome.jp/",$value);
  550. $value = preg_replace("/<a href=\"/i","<a id=\"tripal_kegg_brite_links\" target=\"_blank\" href=\"",$value);
  551. // this line is good so let's exit out
  552. $good = 1;
  553. } else {
  554. $line = fgets($handle);
  555. $filepos += strlen($line);
  556. // we hit the end of the file, so exit with a null
  557. if(!$line){
  558. return null;
  559. }
  560. }
  561. }
  562. return array($level,$value);
  563. }
  564. /**
  565. *
  566. */
  567. function tripal_analysis_kegg_check_line_handle_feature($query_re,
  568. $query_type, $query_uniquename, $base_path, $analysis_id, $brite_id,
  569. $heirarchy,$value)
  570. {
  571. // extract the features that have been mapped to the KEGG IDs
  572. if(preg_match("/^(.*?);\s*(\<a.+)/",$value,$matches)){
  573. $has_feature = 1;
  574. $fname = $matches[1];
  575. $keggterm = $matches[2];
  576. // get the feature name using the user's regular expression
  577. if ($query_re and preg_match("/$query_re/", $fname, $matches)) {
  578. $feature = $matches[1];
  579. }
  580. // If not in above format then pull up to the first space
  581. else {
  582. if (preg_match('/^(.*?)\s.*$/', $fname, $matches)) {
  583. $feature = $matches[1];
  584. }
  585. // if no match up to the first space then just use the entire string
  586. else {
  587. $feature = $fname;
  588. }
  589. }
  590. // now find the feature in chado
  591. $select = array();
  592. if($query_uniquename){
  593. $select['uniquename'] = $feature;
  594. } else {
  595. $select['name'] = $feature;
  596. }
  597. if($query_type){
  598. $select['type_id'] = array(
  599. 'cv_id' => array(
  600. 'name' => 'sequence'
  601. ),
  602. 'name' => $query_type,
  603. );
  604. }
  605. $feature_arr = tripal_core_chado_select('feature',array('feature_id'),$select);
  606. if(count($feature_arr) > 1){
  607. print "Ambiguous: '$feature' matches more than one feature and is being skipped.\n";
  608. continue;
  609. }
  610. if(count($feature_arr) == 0){
  611. print "Failed: '$feature' cannot find a matching feature in the database.\n";
  612. continue;
  613. }
  614. $feature_id = $feature_arr[0]->feature_id;
  615. if($feature_id){
  616. print "Adding KEGG term for $feature ($feature_id,$analysis_id). $heirarchy\n";
  617. // add this term to the analysis feature properties
  618. tripal_analysis_kegg_insert_featureprop($feature_id,$analysis_id,
  619. $brite_id,$keggterm);
  620. // get the node ID of the feature if one exists
  621. $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
  622. $nid = db_result(db_query($sql, $feature_id));
  623. // Add link to each matched feature
  624. if($nid){
  625. $value = preg_replace("/^(.*?)(;\s*\<a)/","<a id=\"tripal_kegg_feature_links\" target=\"_blank\" href=\"".url("node/$nid")."\">"."$1"."</a>"."$2",$value);
  626. }
  627. // if we have a feature match then add this to our results array
  628. return $value;
  629. }
  630. }
  631. return null;
  632. }
  633. /**
  634. *
  635. */
  636. function tripal_analysis_kegg_insert_featureprop ($feature_id, $analysis_id,
  637. $brite_id,$keggterm)
  638. {
  639. // add the analysisfeature record if it doesn't already exist.
  640. $values = array('feature_id' => $feature_id,'analysis_id' => $analysis_id);
  641. $analysisfeature_arr = tripal_core_chado_select('analysisfeature',
  642. array('analysisfeature_id'),$values);
  643. if(count($analysisfeature_arr) == 0){
  644. tripal_core_chado_insert('analysisfeature',$values);
  645. $analysisfeature_arr = tripal_core_chado_select('analysisfeature',
  646. array('analysisfeature_id'),$values);
  647. }
  648. $analysisfeature_id = $analysisfeature_arr[0]->analysisfeature_id;
  649. // Insert into analysisfeatureprop if the value doesn't already exist
  650. // KEGG heir results sometimes have the same record more than once.
  651. if($analysisfeature_id){
  652. // Get the highest rank for this feature_id in analysisfeatureprop table
  653. $sql = "SELECT rank FROM analysisfeatureprop WHERE analysisfeature_id = %d and type_id = %d ORDER BY rank DESC";
  654. $previous_db = tripal_db_set_active('chado');
  655. $result = db_fetch_object(db_query($sql,$analysisfeature_id,$brite_id));
  656. tripal_db_set_active($previous);
  657. $rank = 0;
  658. if ($result and $result->rank > 0) {
  659. $rank = $result->rank + 1;
  660. }
  661. $values = array(
  662. 'analysisfeature_id' => $analysisfeature_id,
  663. 'type_id' => $brite_id,
  664. 'value' => $keggterm,
  665. 'rank' => $rank,
  666. );
  667. return tripal_core_chado_insert('analysisfeatureprop',$values);
  668. }
  669. else {
  670. return 0;
  671. }
  672. }
  673. /*******************************************************************************
  674. * HOOK: Implementation of hook_nodeapi()
  675. * Display library information for associated features or organisms
  676. * This function also provides contents for indexing
  677. */
  678. function tripal_analysis_kegg_nodeapi(&$node, $op, $teaser, $page) {
  679. switch ($op) {
  680. case 'view':
  681. // add the library to the organism/feature search indexing
  682. if($node->build_mode == NODE_BUILD_SEARCH_INDEX){
  683. $node->content['tripal_analysis_kegg_search_index'] = array(
  684. '#value' => theme('tripal_analysis_kegg_search_index',$node),
  685. '#weight' => 6,
  686. );
  687. } else if ($node->build_mode == NODE_BUILD_SEARCH_RESULT) {
  688. $node->content['tripal_analysis_kegg_search_result'] = array(
  689. '#value' => theme('tripal_analysis_kegg_search_result',$node),
  690. '#weight' => 6,
  691. );
  692. } else {
  693. switch($node->type){
  694. case 'chado_organism':
  695. // Show KEGG report on the analysis page
  696. $node->content['tripal_organism_kegg_summary'] = array(
  697. '#value' => theme('tripal_organism_kegg_summary', $node),
  698. );
  699. break;
  700. case 'chado_feature':
  701. // Show KEGG terms on a feature page
  702. $node->content['tripal_feature_kegg_terms'] = array(
  703. '#value' => theme('tripal_feature_kegg_terms', $node),
  704. );
  705. }
  706. }
  707. break;
  708. }
  709. }
  710. /************************************************************************
  711. * We need to let drupal know about our theme functions and their arguments.
  712. * We create theme functions to allow users of the module to customize the
  713. * look and feel of the output generated in this module
  714. */
  715. function tripal_analysis_kegg_theme () {
  716. return array(
  717. 'tripal_analysis_kegg_search_index' => array (
  718. 'arguments' => array('node'),
  719. ),
  720. 'tripal_analysis_kegg_search_result' => array (
  721. 'arguments' => array('node'),
  722. ),
  723. 'tripal_organism_kegg_summary' => array (
  724. 'arguments' => array('node'=> null),
  725. 'template' => 'tripal_organism_kegg_summary',
  726. ),
  727. 'tripal_feature_kegg_terms' => array (
  728. 'arguments' => array('node'=> null),
  729. 'template' => 'tripal_feature_kegg_terms',
  730. ),
  731. 'tripal_analysis_kegg_report' => array (
  732. 'arguments' => array('node'=> null),
  733. 'template' => 'tripal_analysis_kegg_report',
  734. ),
  735. );
  736. }
  737. /**
  738. *
  739. *
  740. * @ingroup tripal_analysis_kegg
  741. */
  742. function tripal_analysis_kegg_preprocess(&$variables){
  743. // if the template file is the default node template file then we want
  744. // to add all of our variables.
  745. if($variables['template_files'][0] == 'node-chado_analysis_kegg'){
  746. $analysis = $variables['node']->analysis;
  747. $report = tripal_analysis_kegg_full_report($analysis->analysis_id);
  748. $analysis->tripal_analysis_kegg->kegg_report = $report;
  749. }
  750. }
  751. /*******************************************************************************
  752. *
  753. */
  754. function tripal_analysis_kegg_preprocess_tripal_organism_kegg_summary(&$variables){
  755. $node = $variables['node'];
  756. $variables['tripal_analysis_kegg']['select_form'] = tripal_analysis_kegg_load_organism_kegg_summary($node);
  757. }
  758. /**
  759. *
  760. */
  761. function tripal_analysis_kegg_preprocess_tripal_feature_kegg_terms(&$variables){
  762. $node = $variables['node'];
  763. $feature = $node->feature;
  764. $variables['tripal_analysis_kegg']['results'] = tripal_analysis_kegg_load_feature_terms($feature);
  765. }
  766. /************************************************************************
  767. */
  768. function theme_tripal_analysis_kegg_search_index($node){
  769. if ($node->type == 'chado_feature') {
  770. // Find cvterm_id for 'kegg_brite_data'
  771. $sql = "SELECT cvterm_id
  772. FROM {cvterm} CVT
  773. INNER JOIN cv ON cv.cv_id = CVT.cv_id
  774. WHERE cv.name = 'tripal'
  775. AND CVT.name = '%s'";
  776. $previous_db = tripal_db_set_active('chado');
  777. $brite_id = db_result(db_query($sql, 'kegg_brite_data'));
  778. // Get analysis id
  779. $sql = "SELECT analysis_id AS aid
  780. FROM {analysisfeature} AF
  781. INNER JOIN analysisfeatureprop AFP ON AF.analysisfeature_id = AFP.analysisfeature_id
  782. WHERE feature_id = %d
  783. AND AFP.type_id = %d
  784. GROUP BY analysis_id";
  785. $feature = $node->feature;
  786. $feature_id = $feature->feature_id;
  787. $hasResult = db_result(db_query($sql, $feature_id, $brite_id));
  788. $result = db_query($sql, $feature->feature_id, $brite_id);
  789. // Show kegg result ORDER BY time
  790. if ($hasResult) { // If there is any result, show expandable box
  791. $content = "";
  792. while ($ana = db_fetch_object($result)) {
  793. // Show analysis date
  794. $sql = "SELECT name, to_char(timeexecuted, 'MM-DD-YYYY') AS time
  795. FROM {analysis}
  796. WHERE analysis_id = %d";
  797. $ana_details = db_fetch_object(db_query($sql, $ana->aid));
  798. // Find node id for the analysis
  799. tripal_db_set_active($previous_db);
  800. $ana_nid = db_result(db_query("SELECT nid FROM {chado_analysis} WHERE analysis_id = %d", $ana->aid));
  801. $ana_url = url("node/".$ana_nid);
  802. $previous_db = tripal_db_set_active('chado');
  803. // Show content
  804. $content .= "$ana_details->name";
  805. // Show Kegg results
  806. $sql = "SELECT AFP.value AS afpvalue
  807. FROM {analysisfeatureprop} AFP
  808. INNER JOIN analysisfeature AF on AF.analysisfeature_id = AFP.analysisfeature_id
  809. WHERE AF.analysis_id = %d
  810. AND AF.feature_id = %d
  811. ";
  812. $kegg_results = db_query($sql, $ana->aid, $feature_id);
  813. while ($afp = db_fetch_object($kegg_results)) {
  814. $content .= " $afp->afpvalue";
  815. }
  816. }
  817. }
  818. tripal_db_set_active($previous_db);
  819. return $content;
  820. }
  821. }
  822. /************************************************************************
  823. */
  824. function theme_tripal_analysis_kegg_search_result($node){
  825. $content = theme_tripal_analysis_kegg_node_add($node);
  826. return $content;
  827. }
  828. /************************************************************************
  829. */
  830. function tripal_analysis_kegg_load_organism_kegg_summary($node) {
  831. $organism = $node->organism;
  832. // find analyses that have KEGG terms
  833. $sql = "
  834. SELECT *
  835. FROM {kegg_by_organism} KBO
  836. WHERE organism_id = %d
  837. ORDER BY analysis_id DESC
  838. ";
  839. $previous_db = tripal_db_set_active('chado');
  840. $results = db_fetch_object(db_query($sql,$organism->organism_id));
  841. tripal_db_set_active($previous_db);
  842. $has_results = 0;
  843. if($results){
  844. $has_results = 1;
  845. }
  846. return array (
  847. 'has_results' => $has_results,
  848. 'form' => drupal_get_form('tripal_analysis_kegg_select_form',$node),
  849. );
  850. }
  851. /************************************************************************
  852. // Show Kegg additional information on a KEGG Analysis page
  853. if ($node->type == 'chado_analysis_kegg') {
  854. return tripal_analysis_kegg_full_report($node->analysis_id);
  855. }
  856. // Show Kegg-info-box on a Feature page
  857. else if ($node->type == 'chado_feature') {
  858. return tripal_analysis_kegg_feature_add($node);
  859. }
  860. return $content;
  861. }
  862. */
  863. function tripal_analysis_kegg_org_report($analysis_id){
  864. $content = tripal_analysis_kegg_full_report($analysis_id);
  865. $opt = array($content);
  866. return drupal_json($opt);
  867. }
  868. /************************************************************************
  869. */
  870. function tripal_analysis_kegg_full_report($analysis_id){
  871. // Test if brite data have been parsed into the database
  872. $sql = "SELECT CVT.name, CVT.cvterm_id
  873. FROM {cvterm} CVT
  874. INNER JOIN analysisprop AP ON CVT.cvterm_id = AP.type_id
  875. WHERE AP.analysis_id = %d
  876. AND CVT.definition LIKE 'KEGG BRITE term: %'
  877. ORDER BY CVT.cvterm_id";
  878. $previous_db = tripal_db_set_active('chado');
  879. $result = db_query($sql, $analysis_id);
  880. tripal_db_set_active($previous_db);
  881. if (db_result($result)) {
  882. $content = tripal_analysis_kegg_brite($analysis_id, $type_id, 0);
  883. } else {
  884. $content = "<i>Note:</i> Analysis result is not available. Please schedule and run the job to parse the kegg output.";
  885. }
  886. return $content;
  887. }
  888. /*******************************************************************************
  889. * Tripal Kegg administrative setting form. This function is called by
  890. * tripal_analysis module which asks for an admin form to show on the page
  891. */
  892. function tripal_analysis_kegg_get_settings() {
  893. // Get an array of node types with internal names as keys
  894. $options = node_get_types('names');
  895. // Add 'chado_feature' to allowed content types for showing kegg results
  896. $allowedoptions ['chado_feature'] = "Show KEGG results on feature pages";
  897. $allowedoptions ['chado_analysis_kegg'] = "Show KEGG BRITE results on the analysis page.";
  898. $allowedoptions ['chado_organism'] = "Show KEGG BRITE results on the organism pages.";
  899. $form['description'] = array(
  900. '#type' => 'item',
  901. '#value' => t("Some chado features were analyzed by KEGG automatic annotation server (KAAS). This option allows user to display the kegg analysis results. Please read user manual for storage and display of kegg files. Check the box to enable the analysis results. Uncheck to disable it."),
  902. '#weight' => 0,
  903. );
  904. $form['tripal_analysis_kegg_setting'] = array(
  905. '#type' => 'checkboxes',
  906. '#options' => $allowedoptions,
  907. '#default_value' => variable_get('tripal_analysis_kegg_setting',
  908. array('chado_feature', 'chado_analysis_kegg')),
  909. );
  910. $settings->form = $form;
  911. $settings->title = "Tripal Kegg";
  912. return $settings;
  913. }
  914. /************************************************************************
  915. */
  916. function tripal_analysis_kegg_organism_results($node) {
  917. $node = node_load($node);
  918. return tripal_analysis_kegg_organism_add($node);
  919. }
  920. /************************************************************************
  921. */
  922. function tripal_analysis_kegg_load_feature_terms($feature) {
  923. $feature_id = $feature->feature_id;
  924. // Get the KEGG results stored using the term 'kegg_brite_data'
  925. $select = array(
  926. 'analysisfeature_id' => array(
  927. 'feature_id' => $feature_id,
  928. ),
  929. 'type_id' => array(
  930. 'name' => 'kegg_brite_data',
  931. 'cv_id' => array(
  932. 'name' => 'tripal'
  933. ),
  934. ),
  935. );
  936. $afeatureprops = tripal_core_chado_select('analysisfeatureprop',array('*'),$select);
  937. // iterate through all of the KEGG properties for this feature
  938. $results = array();
  939. foreach ($afeatureprops as $index => $afeatureprop) {
  940. // get the analysis feature record
  941. $analysisfeature_arr = tripal_core_chado_select('analysisfeature',array('analysis_id'),
  942. array('analysisfeature_id' => $afeatureprop->analysisfeature_id));
  943. $analysisfeature = $analysisfeature_arr[0];
  944. // get the analysis record and the analysis_id
  945. $analysis = tripal_core_generate_chado_var('analysis',
  946. array('analysis_id' => $analysisfeature->analysis_id));
  947. $analysis_id = $analysis->analysis_id;
  948. $results[$analysis_id]['analysis'] = $analysis;
  949. }
  950. // now get all the terms for each analysis
  951. foreach($results as $analysis_id => $arr){
  952. $select = array(
  953. 'analysisfeature_id' => array(
  954. 'analysis_id' => $analysis_id,
  955. 'feature_id' => $feature_id,
  956. ),
  957. 'type_id' => array(
  958. 'name' => 'kegg_brite_data',
  959. 'cv_id' => array(
  960. 'name' => 'tripal',
  961. ),
  962. ),
  963. );
  964. $terms = tripal_core_chado_select('analysisfeatureprop',array('*'),$select);
  965. foreach ($terms as $term){
  966. $results[$analysis_id]['terms'][] = $term->value;
  967. }
  968. }
  969. return $results;
  970. }
  971. /************************************************************************
  972. */
  973. function tripal_analysis_kegg_select_form(&$form_state = NULL,$node){
  974. $form = array();
  975. // find analyses that have KEGG terms
  976. $sql = "
  977. SELECT *
  978. FROM {kegg_by_organism} KBO
  979. WHERE organism_id = %d
  980. ORDER BY analysis_id DESC
  981. ";
  982. $previous_db = tripal_db_set_active('chado');
  983. $results = db_query($sql,$node->organism->organism_id);
  984. tripal_db_set_active($previous_db);
  985. $analyses = array();
  986. $analyses[''] = '';
  987. while($analysis = db_fetch_object($results)){
  988. $analyses[$analysis->analysis_id] = "$analysis->analysis_name";
  989. }
  990. # create the select box
  991. $form['tripal_analysis_kegg_select'] = array(
  992. '#title' => t('Select a KEGG report to view'),
  993. '#description' => t('Any analysis with KEGG results related to this organism are available for viewing. For further information, see the analysis information page.'),
  994. '#type' => 'select',
  995. '#options' => $analyses,
  996. '#attributes' => array (
  997. 'onchange' => 'tripal_analysis_kegg_org_report(this.options[this.selectedIndex].value)'
  998. ),
  999. );
  1000. return $form;
  1001. }