blast_ui.api.inc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. <?php
  2. /**
  3. * @file
  4. * Contains more generally applicable functions as well as some meant to help developers
  5. * Plug-in to the BLAST UI functionality
  6. */
  7. /**
  8. * Get a specific BlastDB.
  9. *
  10. * @param $identifiers
  11. * An array of identifiers used to determine which BLAST DB to retrieve.
  12. *
  13. * @return
  14. * A fully-loaded BLAST DB Node
  15. */
  16. function get_blast_database($identifiers) {
  17. $node = FALSE;
  18. if (isset($identifiers['nid'])) {
  19. $node = node_load($identifiers['nid']);
  20. }
  21. elseif (isset($identifiers['name'])) {
  22. $nid = db_query('SELECT nid FROM {blastdb} WHERE name=:name', array(':name' => $identifiers['name']))->fetchField();
  23. $node = node_load($nid);
  24. } elseif (isset($identifiers['path'])) {
  25. $nid = db_query('SELECT nid FROM {blastdb} WHERE path LIKE :path', array(':path' => db_like($identifiers['path']) . '%'))->fetchField();
  26. $node = node_load($nid);
  27. }
  28. return $node;
  29. }
  30. /**
  31. * Returns a list BLAST DATABASE options
  32. *
  33. * @param $type
  34. * The type of BLAST dabases to restrict the list to (ie: n: nucleotide or p: protein)
  35. *
  36. * @return
  37. * An array where the nid is the key and the value is the human-readable name of the option
  38. */
  39. function get_blast_database_options($type) {
  40. global $user;
  41. // Use the Entity API to get a list of BLAST Nodes to load
  42. // We use this function in order respect node access control so that
  43. // administrators can use this module in combination with a node access module
  44. // of their choice to limit access to specific BLAST databases.
  45. $query = new EntityFieldQuery();
  46. $query->entityCondition('entity_type', 'node')
  47. // Restrict to BLASTDB nodes.
  48. ->entityCondition('bundle', 'blastdb')
  49. // Restrict to Published nodes.
  50. ->propertyCondition('status', 1)
  51. // Restrict to nodes the current user has permission to view.
  52. ->addTag('node_access');
  53. $entities = $query->execute();
  54. // Get all BlastDB nodes
  55. $nodes = node_load_multiple(array_keys($entities['node']));
  56. // Support obsolete database type n/p
  57. $obs_type = '';
  58. if ($type == 'protein') {
  59. $obs_type = 'p';
  60. }
  61. else {
  62. $obs_type = 'n';
  63. }
  64. $options = array();
  65. foreach ($nodes as $node) {
  66. if ( isset($node) && isset($node->db_dbtype) ) {
  67. if ( ($node->db_dbtype == $type) OR ($node->db_dbtype == $obs_type) ) {
  68. $options[$node->nid] = $node->db_name;
  69. }
  70. }
  71. }
  72. asort($options);
  73. $options[0] = 'Select a Dataset';
  74. return $options;
  75. }
  76. /**
  77. * Retrieve all the information for a blast job in a standardized node-like format.
  78. *
  79. * @param $job_id
  80. * The non-encoded tripal job_id.
  81. * @retun
  82. * An object describing the blast job.
  83. */
  84. function get_BLAST_job($job_id) {
  85. $blastjob = db_query('SELECT * FROM blastjob WHERE job_id=:id', array(':id' => $job_id))->fetchObject();
  86. $tripal_job = tripal_get_job($job_id);
  87. $job = new stdClass();
  88. $job->job_id = $job_id;
  89. $job->program = $blastjob->blast_program;
  90. $job->options = unserialize($blastjob->options);
  91. $job->date_submitted = $tripal_job->submit_date;
  92. $job->date_started = $tripal_job->start_time;
  93. $job->date_completed = $tripal_job->end_time;
  94. // TARGET BLAST DATABASE.
  95. // If a provided blast database was used then load details.
  96. if ($blastjob->target_blastdb ) {
  97. $job->blastdb = get_blast_database(array('nid' => $blastjob->target_blastdb));
  98. }
  99. // Otherwise the user uploaded their own database so provide what information we can.
  100. else {
  101. $job->blastdb = new stdClass();
  102. $job->blastdb->db_name = 'User Uploaded';
  103. $job->blastdb->db_path = $blastjob->target_file;
  104. $job->blastdb->linkout = new stdClass();
  105. $job->blastdb->linkout->none = TRUE;
  106. if ($job->program == 'blastp' OR $job->program == 'tblastn') {
  107. $job->blastdb->db_dbtype = 'protein';
  108. }
  109. else {
  110. $job->blastdb->db_dbtype = 'nucleotide';
  111. }
  112. }
  113. // FILES.
  114. $job->files = new stdClass();
  115. $job->files->query = $blastjob->query_file;
  116. $job->files->target = $blastjob->target_file;
  117. $job->files->result = new stdClass();
  118. $job->files->result->archive = $blastjob->result_filestub . '.asn';
  119. $job->files->result->xml = $blastjob->result_filestub . '.xml';
  120. $job->files->result->tsv = $blastjob->result_filestub . '.tsv';
  121. $job->files->result->html = $blastjob->result_filestub . '.html';
  122. $job->files->result->gff = $blastjob->result_filestub . '.gff';
  123. return $job;
  124. }
  125. /**
  126. * Run BLAST (should be called from the command-line)
  127. *
  128. * @param $program
  129. * Which BLAST program to run (ie: 'blastn', 'tblastn', tblastx', 'blastp','blastx')
  130. * @param $query
  131. * The full path and filename of the query FASTA file
  132. * @param $database
  133. * The full path and filename prefix (excluding .nhr, .nin, .nsq, etc.)
  134. * @param $output_filestub
  135. * The filename (not including path) to give the results. Should not include file type suffix
  136. * @param $options
  137. * An array of additional option where the key is the name of the option used by
  138. * BLAST (ie: 'num_alignments') and the value is relates to this particular
  139. * BLAST job (ie: 250)
  140. */
  141. function run_BLAST_tripal_job($program, $query, $database, $output_filestub, $options, $job_id = NULL) {
  142. $output_file = $output_filestub . '.asn';
  143. $output_file_xml = $output_filestub . '.xml';
  144. $output_file_tsv = $output_filestub . '.tsv';
  145. $output_file_html = $output_filestub . '.html';
  146. $output_file_gff = $output_filestub . '.gff';
  147. print "\nExecuting $program\n\n";
  148. print "Query: $query\n";
  149. print "Database: $database\n";
  150. print "Results File: $output_file\n";
  151. print "Options:\n";
  152. // Allow administrators to use an absolute path for these commands.
  153. // Defaults to using $PATH.
  154. $blast_path = variable_get('blast_path', '');
  155. $blast_threads = variable_get('blast_threads', 1);
  156. // Strip the extension off the BLAST target
  157. $database = preg_replace("/(.*)\.[pn]\w\w/", '$1', $database);
  158. // The executables:
  159. $program = $blast_path . $program;
  160. $blast_formatter_command = $blast_path . 'blast_formatter';
  161. $blast_cmd = "$program -query '$query' -db '$database' -out '$output_file' -outfmt=11";
  162. if (!empty($options)) {
  163. foreach ($options as $opt => $val) {
  164. $val = trim($val);
  165. if (!empty($val)) {
  166. print "\t$opt: $val\n";
  167. $blast_cmd .= " -$opt $val";
  168. }
  169. }
  170. }
  171. // Setting the value of threads by admin page
  172. $blast_cmd .= " -num_threads ".$blast_threads;
  173. print "\nExecuting the following BLAST command:\n" . $blast_cmd . "\n";
  174. system($blast_cmd);
  175. if (!file_exists($output_file)) {
  176. tripal_report_error(
  177. 'blast_ui',
  178. TRIPAL_ERROR,
  179. "BLAST did not complete successfully as is implied by the lack of output file (%file). The command run was @command",
  180. array('%file' => $output_file, '@command' => $blast_cmd),
  181. array('print' => TRUE)
  182. );
  183. return FALSE;
  184. }
  185. print "\nGenerating additional download formats...\n";
  186. print "\tXML\n";
  187. $format_cmd = "$blast_formatter_command -archive $output_file -outfmt 5 -out $output_file_xml";
  188. print "\nExecuting $format_cmd\n\n";
  189. system($format_cmd);
  190. if (!file_exists($output_file_xml)) {
  191. tripal_report_error(
  192. 'blast_ui',
  193. TRIPAL_ERROR,
  194. "Unable to convert BLAST ASN.1 archive to XML (%archive => %file).",
  195. array('%archive' => $output_file, '%file' => $output_file_xml),
  196. array('print' => TRUE)
  197. );
  198. }
  199. print "\tTab-delimited\n";
  200. system("$blast_formatter_command -archive $output_file -outfmt 7 -out $output_file_tsv");
  201. if (!file_exists($output_file_tsv)) {
  202. tripal_report_error(
  203. 'blast_ui',
  204. TRIPAL_WARNING,
  205. "Unable to convert BLAST ASN.1 archive to Tabular Output (%archive => %file).",
  206. array('%archive' => $output_file, '%file' => $output_file_tsv),
  207. array('print' => TRUE)
  208. );
  209. }
  210. print "\tGFF\n";
  211. convert_tsv2gff3($output_file_tsv,$output_file_gff);
  212. if (!file_exists($output_file_gff)) {
  213. tripal_report_error(
  214. 'blast_ui',
  215. TRIPAL_WARNING,
  216. "Unable to convert BLAST Tabular Output to GFF Output (%archive => %file).",
  217. array('%archive' => $output_file, '%file' => $output_file_gff),
  218. array('print' => TRUE)
  219. );
  220. }
  221. print "\tHTML (includes alignments)\n";
  222. system("$blast_formatter_command -archive $output_file -outfmt 0 -out $output_file_html -html");
  223. if (!file_exists($output_file_tsv)) {
  224. tripal_report_error(
  225. 'blast_ui',
  226. TRIPAL_WARNING,
  227. "Unable to convert BLAST ASN.1 archive to HTML Output (%archive => %file).",
  228. array('%archive' => $output_file, '%file' => $output_file_html),
  229. array('print' => TRUE)
  230. );
  231. }
  232. print "\nDone!\n";
  233. }
  234. /**
  235. * FASTA validating parser
  236. *
  237. * A sequence in FASTA format begins with a single-line description, followed
  238. * by lines of sequence data.The description line is distinguished from the
  239. * sequence data by a greater-than (">") symbol in the first column. The word
  240. * following the ">" symbol is the identifier of the sequence, and the rest of
  241. * the line is the description (both are optional). There should be no space
  242. * between the ">" and the first letter of the identifier. The sequence ends
  243. * if another line starting with a ">" appears which indicates the start of
  244. * another sequence.
  245. *
  246. * @param $type
  247. * The type of sequence to be validated (ie: either nucleotide or protein).
  248. * @param $sequence
  249. * A string of characters to be validated.
  250. *
  251. * @return
  252. * Return a boolean. 1 if the sequence does not pass the format valifation stage and 0 otherwise.
  253. *
  254. */
  255. function validate_fasta_sequence($type, $sequence) {
  256. if ($type == 'nucleotide') {
  257. $fastaIdRegEx = '/^>.*(\\n|\\r)/';
  258. $fastaSeqRegEx = '/[^ATCGNUKMBVSWDYRHatcgnukmbvswdyrh\n\r]/'; //Includes IUPAC codes.
  259. if ( preg_match($fastaSeqRegEx,$sequence) && !(preg_match($fastaIdRegEx,$sequence)) ) {
  260. return TRUE;
  261. } else {
  262. return FALSE;
  263. }
  264. } elseif ($type == 'protein') {
  265. $fastaIdRegEx = '/^>.*(\\n|\\r)/';
  266. $fastaSeqRegEx = '/[^ABCDEFGHIKLMNPQRSTUVWYZXabcdefghiklmnpqrstuvwyzx\*\-\n\r]/';
  267. if ( preg_match($fastaSeqRegEx,$sequence) && !(preg_match($fastaIdRegEx,$sequence)) ) {
  268. return TRUE;
  269. } else {
  270. return FALSE;
  271. }
  272. }
  273. return FALSE;
  274. }
  275. /**
  276. * Retrieve the regex to capture the Link-out Accession from the Hit Def.
  277. *
  278. * @param $nid
  279. * The node ID of the BLAST database the hit is from.
  280. * @param $options
  281. * An array of options that can be passed to this function. Supported
  282. * options include:
  283. * -
  284. *
  285. * @return
  286. * A PHP regex for use with preg_match to cature the Link-out Accession.
  287. */
  288. function get_blastdb_linkout_regex($node, $options = array()) {
  289. if (empty($node->linkout->regex)) {
  290. switch ($node->linkout->regex_type) {
  291. case 'default':
  292. $regex = '/^(\S+).*/';
  293. break;
  294. case 'genbank':
  295. $regex = '/^gb\|([^\|])*\|.*/';
  296. break;
  297. case 'embl':
  298. $regex = '/^embl\|([^\|])*\|.*/';
  299. break;
  300. case 'swissprot':
  301. $regex = '/^sp\|([^\|])*\|.*/';
  302. break;
  303. }
  304. }
  305. else {
  306. $regex = $node->linkout->regex;
  307. }
  308. return $regex;
  309. }
  310. /**
  311. * Return a list of recent blast jobs to be displayed to the user.
  312. *
  313. * @param $programs
  314. * An array of blast programs you want jobs to be displayed for (ie: blastn, blastx, tblastn, blastp)
  315. *
  316. * @return
  317. * An array of recent jobs.
  318. */
  319. function get_recent_blast_jobs($programs = array()) {
  320. $filter_jobs = !empty($programs);
  321. // Retrieve any recent jobs from the session variable.
  322. if (isset($_SESSION['blast_jobs'])) {
  323. $jobs = array();
  324. foreach ($_SESSION['blast_jobs'] as $job_secret) {
  325. $add = TRUE;
  326. $job_id = blast_ui_reveal_secret($job_secret);
  327. $job = get_BLAST_job($job_id);
  328. // @TODO: Check that the results are still available.
  329. // This is meant to replace the arbitrary only show jobs executed less than 48 hrs ago.
  330. // Remove jobs from the list that are not of the correct program.
  331. if ($filter_jobs AND !in_array($job->program, $programs)) {
  332. $add = FALSE;
  333. }
  334. if ($add) {
  335. $job->query_summary = format_query_headers($job->files->query);
  336. $jobs[] = $job;
  337. }
  338. }
  339. return $jobs;
  340. }
  341. else {
  342. return array();
  343. }
  344. }
  345. /**
  346. * Retrieve the number of recent jobs.
  347. */
  348. function get_number_of_recent_jobs() {
  349. if (isset($_SESSION['blast_jobs'])) {
  350. return sizeof($_SESSION['blast_jobs']);
  351. }
  352. return 0;
  353. }
  354. /**
  355. * Summarize a fasta file based on it's headers.
  356. *
  357. * @param $file
  358. * The full path to the FASTA file.
  359. *
  360. * @return
  361. * A string describing the number of sequences and often including the first query header.
  362. */
  363. function format_query_headers($file) {
  364. $headers = array();
  365. exec('grep ">" '.$file, $headers);
  366. // Easiest case: if there is only one query header then show it.
  367. if (sizeof($headers) == 1 AND isset($headers[0])) {
  368. return ltrim($headers[0], '>');
  369. }
  370. // If we have at least one header then show that along with the count of queries.
  371. elseif (isset($headers[0])) {
  372. return sizeof($headers) . ' queries including "' . ltrim($headers[0], '>') . '"';
  373. }
  374. // If they provided a sequence with no header.
  375. elseif (empty($headers)) {
  376. return 'Unnamed Query';
  377. }
  378. // At the very least show the count of queries.
  379. else {
  380. return sizeof($headers) . ' queries';
  381. }
  382. }
  383. /**
  384. * Sort recent blast jobs by the date they were submitted.
  385. * Ascending is in order of submission.
  386. *
  387. * THIS FUNCTION SHOULD BY USED BY USORT().
  388. */
  389. function sort_blast_jobs_by_date_submitted_asc($a, $b) {
  390. return ($a->date_submitted - $b->date_submitted);
  391. }
  392. /**
  393. * Sort recent blast jobs by the date they were submitted.
  394. * Descending is most recent first.
  395. *
  396. * THIS FUNCTION SHOULD BY USED BY USORT().
  397. */
  398. function sort_blast_jobs_by_date_submitted_desc($a, $b) {
  399. return ($b->date_submitted - $a->date_submitted);
  400. }
  401. /**
  402. * Generate an image of HSPs for a given hit.
  403. *
  404. * history:
  405. * 09/23/10 Carson created
  406. * 04/16/12 eksc adapted into POPcorn code
  407. * 03/12/15 deepak Adapted code into Tripal BLAST
  408. * 10/23/15 lacey Fixed deepak's code to be suitable for Drupal.
  409. *
  410. * @param $acc
  411. * target name
  412. * @param $name
  413. * query name, false if none
  414. * @param $tsize
  415. * target size
  416. * @param $qsize
  417. * query size
  418. * @param $hits
  419. * each hit represented in URL as: targetstart_targetend_hspstart_hspend;
  420. * @param $score
  421. * score for each hit
  422. *
  423. * @returm
  424. * A base64 encoded image representing the hit information.
  425. */
  426. function generate_blast_hit_image($acc = '', $scores, $hits, $tsize, $qsize, $name, $hit_name) {
  427. $tok = strtok($hits, ";");
  428. $b_hits = Array();
  429. while ($tok !== false) {
  430. $b_hits[] = $tok;
  431. $tok = strtok(";");
  432. }
  433. // extract score information from score param
  434. $tokscr = strtok($scores, ";");
  435. $b_scores = Array();
  436. while ($tokscr !== false) {
  437. $b_scores[] = $tokscr;
  438. $tokscr = strtok(";");
  439. }
  440. // image measurements
  441. $height = 200 + (count($b_hits) * 16);
  442. $width = 520;
  443. $img = imagecreatetruecolor($width, $height);
  444. $white = imagecolorallocate($img, 255, 255, 255);
  445. $black = imagecolorallocate($img, 0, 0, 0);
  446. $darkgray = imagecolorallocate($img, 100, 100, 100);
  447. $strong = imagecolorallocatealpha($img, 202, 0, 0, 15);
  448. $moderate = imagecolorallocatealpha($img, 204, 102, 0, 20);
  449. $present = imagecolorallocatealpha($img, 204, 204, 0, 35);
  450. $weak = imagecolorallocatealpha($img, 102, 204, 0, 50);
  451. $gray = imagecolorallocate($img, 190, 190, 190);
  452. $lightgray = $white; //imagecolorallocate($img, 230, 230, 230);
  453. imagefill($img, 0, 0, $lightgray);
  454. // Target coordinates
  455. $maxlength = 300;
  456. $t_length = ($tsize > $qsize)
  457. ? $maxlength : $maxlength - 50;
  458. $q_length = ($qsize > $tsize)
  459. ? $maxlength : $maxlength - 50;
  460. $tnormal = $t_length / $tsize;
  461. $qnormal = $q_length / $qsize;
  462. $t_ystart = 30;
  463. $t_yend = $t_ystart + 20;
  464. $t_xstart = 50;
  465. $t_xend = $t_xstart + $t_length;
  466. $t_center = $t_xstart + ($t_length / 2);
  467. // Target labels
  468. $warn = '"'. $hit_name . '"';
  469. imagestring($img, 5, $t_xstart, $t_ystart-20, $acc.$warn, $black);
  470. imagestring($img, 3, 5, $t_ystart+2, "Target", $black);
  471. // Draw bar representing target
  472. imagefilledrectangle($img, $t_xstart, $t_ystart, $t_xend, $t_yend, $gray);
  473. imagerectangle($img, $t_xstart, $t_ystart, $t_xend, $t_yend, $darkgray);
  474. // query coordinates
  475. $q_maxheight = 250;
  476. $q_ystart = $t_yend + 100;
  477. $q_yend = $q_ystart + 20;
  478. $q_xstart = $t_center - $q_length / 2;
  479. $q_xend = $q_xstart + $q_length;
  480. $q_center = ($q_xend + $q_xstart) / 2;
  481. $q_xwidth = $q_xend - $q_xstart;
  482. // Query labels
  483. imagestring($img, 5, $q_xstart, $q_yend+2, $name, $black);
  484. imagestring($img, 3, $q_xstart, $q_ystart+2, 'Query', $black);
  485. // Draw bar representing query
  486. imagefilledrectangle($img, $q_xstart, $q_ystart, $q_xend, $q_yend, $gray);
  487. imagerectangle($img ,$q_xstart, $q_ystart, $q_xend, $q_yend, $darkgray);
  488. // HSP bars will start here
  489. $hsp_bary = $q_yend + 20;
  490. // Draw solids for HSP alignments
  491. for ($ii=count($b_hits)-1; $ii>=0; $ii--) {
  492. // alignment
  493. $cur_hit = $b_hits[$ii];
  494. $cur_score = intval($b_scores[$ii]);
  495. // set color according to score
  496. $cur_color = $darkgray;
  497. if ($cur_score > 200) {
  498. $cur_color = $strong;
  499. }
  500. else if ($cur_score > 80 && $cur_score <= 200) {
  501. $cur_color = $moderate;
  502. }
  503. else if ($cur_score > 50 && $cur_score <= 80) {
  504. $cur_color = $present;
  505. }
  506. else if ($cur_score > 40 && $cur_score <= 50) {
  507. $cur_color = $weak;
  508. }
  509. $t_start = $tnormal * intval(strtok($cur_hit, "_")) + $t_xstart;
  510. $t_end = $tnormal * intval(strtok("_")) + $t_xstart;
  511. $q_start = $qnormal * intval(strtok("_")) + $q_xstart;
  512. $q_end = $qnormal * intval(strtok("_")) + $q_xstart;
  513. $hit1_array = array($t_start, $t_yend, $t_end, $t_yend, $q_end,
  514. $q_ystart, $q_start, $q_ystart);
  515. // HSP coords
  516. imagefilledpolygon($img, $hit1_array, 4, $cur_color);
  517. }//each hit
  518. // Draw lines over fills for HSP alignments
  519. for ($ii=0; $ii<count($b_hits); $ii++) {
  520. // alignment
  521. $cur_hit = $b_hits[$ii];
  522. $t_start = $tnormal * intval(strtok($cur_hit, "_")) + $t_xstart;
  523. $t_end = $tnormal * intval(strtok("_")) + $t_xstart;
  524. $q_start = $qnormal * intval(strtok("_")) + $q_xstart;
  525. $q_end = $qnormal * intval(strtok("_")) + $q_xstart;
  526. $hit1_array = array($t_start, $t_yend, $t_end, $t_yend, $q_end, $q_ystart,
  527. $q_start, $q_ystart,);
  528. imagerectangle($img, $t_start, $t_ystart, $t_end, $t_yend, $black);
  529. imagerectangle($img, $q_start, $q_ystart, $q_end, $q_yend, $black);
  530. imagepolygon ($img, $hit1_array, 4, $black);
  531. // show HSP
  532. imagestring($img, 3, 2, $hsp_bary, ($acc ."HSP" . ($ii + 1)), $black);
  533. $cur_score = intval($b_scores[$ii]);
  534. // set color according to score
  535. $cur_color = $darkgray;
  536. if ($cur_score > 200) {
  537. $cur_color = $strong;
  538. }
  539. else if ($cur_score > 80 && $cur_score <= 200) {
  540. $cur_color = $moderate;
  541. }
  542. else if ($cur_score > 50 && $cur_score <= 80) {
  543. $cur_color = $present;
  544. }
  545. else if ($cur_score > 40 && $cur_score <= 50) {
  546. $cur_color = $weak;
  547. }
  548. imagefilledrectangle($img, $q_start, $hsp_bary, $q_end, $hsp_bary+10, $cur_color);
  549. $hsp_bary += 15;
  550. }//each hit
  551. // Draw the key
  552. $xchart = 390;
  553. $ychart = 10;
  554. $fontsize = 4;
  555. $yinc = 20;
  556. $ywidth = 7;
  557. $xinc = 10;
  558. imagestring($img, 5, $xchart, $ychart - 5, "Bit Scores", $black);
  559. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 1) + $ywidth, ">= 200" , $black);
  560. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 2) + $ywidth, "80 - 200" , $black);
  561. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 3) + $ywidth, "50 - 80" , $black);
  562. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 4) + $ywidth, "40 - 50" , $black);
  563. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 5) + $ywidth, "< 40" , $black);
  564. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 1) + $xinc, $xchart + $yinc, $ychart + ($yinc * 2), $strong);
  565. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 2) + $xinc, $xchart + $yinc, $ychart + ($yinc * 3), $moderate);
  566. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 3) + $xinc, $xchart + $yinc, $ychart + ($yinc * 4), $present);
  567. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 4) + $xinc, $xchart + $yinc, $ychart + ($yinc * 5), $weak);
  568. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 5) + $xinc, $xchart + $yinc, $ychart + ($yinc * 6), $darkgray);
  569. // Now, we have a completed image resource and need to change it to an actual image
  570. // that can be displayed. This is done using imagepng() but unfortuatly that function
  571. // either saves the image to a file or outputs it directly to the screen. Thus, we use
  572. // the following code to capture it and base64 encode it.
  573. ob_start(); // Start buffering the output
  574. imagepng($img, null, 0, PNG_NO_FILTER);
  575. $b64_img = base64_encode(ob_get_contents()); // Get what we've just outputted and base64 it
  576. imagedestroy($img);
  577. ob_end_clean();
  578. return $b64_img;
  579. }
  580. /**
  581. * Convert tsv blast output to gff output file.
  582. *
  583. * Created by Sofia Robb
  584. * 09/15/2016
  585. *
  586. * The subject (hit) will be the source feature.
  587. * The query will be the target.
  588. *
  589. * @todo: find a more efficient way since currently the first loop stores all the blast
  590. * results into an array and then the second loop prints them.
  591. *
  592. * @param $blast_tsv
  593. * The name of the blast tsv output file.
  594. * @param $blast_gff
  595. * The name of the blast gff output file.
  596. */
  597. function convert_tsv2gff3($blast_tsv,$blast_gff){
  598. // Open a new file for writting the gff.
  599. $gff = fopen($blast_gff,"w");
  600. fwrite($gff,"##gff-version 3\n");
  601. // Open the TSV file to read from.
  602. $tsv = fopen($blast_tsv, "r") or die("Unable to open tsv file!");
  603. // For each line in the TSV file...
  604. $results = array();
  605. while(!feof($tsv)) {
  606. $line = fgets($tsv);
  607. $line = rtrim($line);
  608. // Skip the line if it's empty.
  609. if (preg_match('/^#/',$line) or preg_match('/^\s*$/',$line)){
  610. continue;
  611. }
  612. // Each line has the following parts:
  613. // 0: query id,
  614. // 1: subject id,
  615. // 2: % identity,
  616. // 3: alignment length,
  617. // 4: mismatches,
  618. // 5: gap opens,
  619. // 6: q. start,
  620. // 7: q. end,
  621. // 8: s. start,
  622. // 9: s. end,
  623. // 10: evalue,
  624. // 11: bit score
  625. $parts = preg_split('/\t/', $line);
  626. // Assign the important parts of the time to readable variables.
  627. $hitname = $parts[1];
  628. $hspInfo = "$parts[0],$parts[8],$parts[9],$parts[6],$parts[7]";
  629. $eval = $parts[10];
  630. $results[$hitname][$hspInfo] = $eval;
  631. $IDs = array();
  632. $count = 0;
  633. $last_q = NULL;
  634. // Need to go thru each line of tsv to find the first and last hsp of a hit.
  635. // Need to get the smallest and largest coordinate for the parent feature
  636. foreach ($results as $s => $hspInfoArray) {
  637. $hsp = 0;
  638. foreach ($hspInfoArray as $hspInfoStr => $e) {
  639. list($q,$ss,$se,$qs,$qe) = preg_split('/,/',$hspInfoStr);
  640. if (!$last_q or $q != $last_q) {
  641. $count++;
  642. $hsp=0;
  643. }
  644. $q_strand = '+';
  645. if ($qs > $qe) {
  646. list($qs,$qe) = array($qe,$qs);
  647. $q_strand = '-';
  648. }
  649. $IDs["$s,$q"]['strand']='+';
  650. list($start,$end) = array($ss,$se);
  651. if($ss > $se) {
  652. list($start,$end) = array($se,$ss);
  653. $IDs["$s,$q"]['strand']='-';
  654. }
  655. if (!array_key_exists('SS',$IDs["$s,$q"]) or $ss < $IDs["$s,$q"]['SS']) {
  656. $IDs["$s,$q"]['SS'] = $ss;
  657. }
  658. if (!array_key_exists('SE',$IDs["$s,$q"]) or $se > $IDs["$s,$q"]['SE']) {
  659. $IDs["$s,$q"]['SE'] = $se;
  660. }
  661. if (!array_key_exists('E',$IDs["$s,$q"]) or $e < $IDs["$s,$q"]['E']) {
  662. $IDs["$s,$q"]['E'] = $e;
  663. }
  664. $hsp++;
  665. $IDs["$s,$q"]['HSPs'][] = join("\t", array($s, "BLASTRESULT" , "match_part" , $start , $end , $e , $IDs["$s,$q"]['strand'] , '.' , "ID=$s.$count.$hsp;Parent=$s.$count;Target=$q $qs $qe $q_strand"));
  666. $last_q = $q;
  667. }
  668. }
  669. }
  670. // Now can print a parent gff line and all the children.
  671. // Note: the evalues seem to be sorted properly without actually sorting them.
  672. // @todo: need to make sure this is always true.
  673. foreach ($IDs as $sq => $value ) {
  674. list ($s,$q) = preg_split('/,/' , $sq);
  675. $evalue = $IDs["$s,$q"]['E'];
  676. $parent = join ("\t", array($s, "BLASTRESULT" , "match" , $IDs["$s,$q"]['SS'] , $IDs["$s,$q"]['SE'] , $IDs["$s,$q"]['E'] , $IDs["$s,$q"]['strand'] , '.' , "ID=$s.$count;Name=$q($evalue)")) . "\n";
  677. $child = join ("\n",$IDs[$sq]['HSPs']) . "\n";
  678. fwrite($gff,$parent);
  679. fwrite($gff,$child);
  680. }
  681. // Close the files.
  682. fclose($tsv);
  683. fclose($gff);
  684. }