blast_ui.api.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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 Blast executeable.
  159. $program = $blast_path . $program;
  160. if (!file_exists($program)) {
  161. tripal_report_error(
  162. 'blast_ui',
  163. TRIPAL_ERROR,
  164. "Unable to find the BLAST executable (ie: /urs/bin/blastn). This can be changed in the admin settings; you supplied: @command",
  165. array('@command' => $program),
  166. array('print' => TRUE)
  167. );
  168. return FALSE;
  169. }
  170. // The blast db formatter executable.
  171. $blast_formatter_command = $blast_path . 'blast_formatter';
  172. if (!file_exists($blast_formatter_command)) {
  173. tripal_report_error(
  174. 'blast_ui',
  175. TRIPAL_ERROR,
  176. "Unable to find the BLAST Formatter executable (ie: /urs/bin/blast_formatter). This can be changed in the admin settings; you supplied: @command",
  177. array('@command' => $blast_formatter_command),
  178. array('print' => TRUE)
  179. );
  180. return FALSE;
  181. }
  182. // Note: all variables are escaped (adds single quotes around their values) for security reasons.
  183. $blast_cmd = escapeshellarg($program) . ' -query ' . escapeshellarg($query) . ' -db ' . escapeshellarg($database) . ' -out ' . escapeshellarg($output_file) . ' -outfmt=11';
  184. if (!empty($options)) {
  185. foreach ($options as $opt => $val) {
  186. $val = trim($val);
  187. if (!empty($val)) {
  188. print "\t$opt: $val\n";
  189. // We want to escape all the option values since they were supplied via
  190. // user input. These values should also have been checked in the
  191. // advanced form _validate functions but this adds an extra layer of
  192. // protection.
  193. $blast_cmd .= ' -' . escapeshellarg($opt) . ' ' . escapeshellarg($val);
  194. }
  195. }
  196. }
  197. // Setting the value of threads by admin page
  198. $blast_cmd .= ' -num_threads ' . escapeshellarg($blast_threads);
  199. print "\nExecuting the following BLAST command:\n" . $blast_cmd . "\n";
  200. system($blast_cmd);
  201. if (!file_exists($output_file)) {
  202. tripal_report_error(
  203. 'blast_ui',
  204. TRIPAL_ERROR,
  205. "BLAST did not complete successfully as is implied by the lack of output file (%file). The command run was @command",
  206. array('%file' => $output_file, '@command' => $blast_cmd),
  207. array('print' => TRUE)
  208. );
  209. return FALSE;
  210. }
  211. print "\nGenerating additional download formats...\n";
  212. print "\tXML\n";
  213. $format_cmd = escapeshellarg($blast_formatter_command) . ' -archive ' . escapeshellarg($output_file) . ' -outfmt 5 -out ' . escapeshellarg($output_file_xml);
  214. print "\t\tExecuting $format_cmd\n\n";
  215. system($format_cmd);
  216. if (!file_exists($output_file_xml)) {
  217. tripal_report_error(
  218. 'blast_ui',
  219. TRIPAL_ERROR,
  220. "Unable to convert BLAST ASN.1 archive to XML (%archive => %file).",
  221. array('%archive' => $output_file, '%file' => $output_file_xml),
  222. array('print' => TRUE)
  223. );
  224. }
  225. print "\tTab-delimited\n";
  226. $format_cmd = escapeshellarg($blast_formatter_command) . ' -archive ' . escapeshellarg($output_file) . ' -outfmt 7 -out ' . escapeshellarg($output_file_tsv);
  227. print "\t\tExecuting $format_cmd\n\n";
  228. system($format_cmd);
  229. if (!file_exists($output_file_tsv)) {
  230. tripal_report_error(
  231. 'blast_ui',
  232. TRIPAL_WARNING,
  233. "Unable to convert BLAST ASN.1 archive to Tabular Output (%archive => %file).",
  234. array('%archive' => $output_file, '%file' => $output_file_tsv),
  235. array('print' => TRUE)
  236. );
  237. }
  238. print "\tGFF\n";
  239. convert_tsv2gff3($output_file_tsv,$output_file_gff);
  240. if (!file_exists($output_file_gff)) {
  241. tripal_report_error(
  242. 'blast_ui',
  243. TRIPAL_WARNING,
  244. "Unable to convert BLAST Tabular Output to GFF Output (%archive => %file).",
  245. array('%archive' => $output_file, '%file' => $output_file_gff),
  246. array('print' => TRUE)
  247. );
  248. }
  249. print "\tHTML (includes alignments)\n";
  250. $format_cmd = escapeshellarg($blast_formatter_command) . ' -archive ' . escapeshellarg($output_file) . ' -outfmt 0 -out ' . escapeshellarg($output_file_html) . ' -html';
  251. print "\t\tExecuting $format_cmd\n\n";
  252. system($format_cmd);
  253. if (!file_exists($output_file_tsv)) {
  254. tripal_report_error(
  255. 'blast_ui',
  256. TRIPAL_WARNING,
  257. "Unable to convert BLAST ASN.1 archive to HTML Output (%archive => %file).",
  258. array('%archive' => $output_file, '%file' => $output_file_html),
  259. array('print' => TRUE)
  260. );
  261. }
  262. print "\nDone!\n";
  263. }
  264. /**
  265. * FASTA validating parser
  266. *
  267. * A sequence in FASTA format begins with a single-line description, followed
  268. * by lines of sequence data.The description line is distinguished from the
  269. * sequence data by a greater-than (">") symbol in the first column. The word
  270. * following the ">" symbol is the identifier of the sequence, and the rest of
  271. * the line is the description (both are optional). There should be no space
  272. * between the ">" and the first letter of the identifier. The sequence ends
  273. * if another line starting with a ">" appears which indicates the start of
  274. * another sequence.
  275. *
  276. * @param $type
  277. * The type of sequence to be validated (ie: either nucleotide or protein).
  278. * @param $sequence
  279. * A string of characters to be validated.
  280. *
  281. * @return
  282. * Return a boolean. 1 if the sequence does not pass the format valifation stage and 0 otherwise.
  283. *
  284. */
  285. function validate_fasta_sequence($type, $sequence) {
  286. if ($type == 'nucleotide') {
  287. $fastaIdRegEx = '/^>.*(\\n|\\r)/';
  288. $fastaSeqRegEx = '/[^ATCGNUKMBVSWDYRHatcgnukmbvswdyrh\n\r]/'; //Includes IUPAC codes.
  289. if ( preg_match($fastaSeqRegEx,$sequence) && !(preg_match($fastaIdRegEx,$sequence)) ) {
  290. return TRUE;
  291. } else {
  292. return FALSE;
  293. }
  294. } elseif ($type == 'protein') {
  295. $fastaIdRegEx = '/^>.*(\\n|\\r)/';
  296. $fastaSeqRegEx = '/[^ABCDEFGHIKLMNPQRSTUVWYZXabcdefghiklmnpqrstuvwyzx\*\-\n\r]/';
  297. if ( preg_match($fastaSeqRegEx,$sequence) && !(preg_match($fastaIdRegEx,$sequence)) ) {
  298. return TRUE;
  299. } else {
  300. return FALSE;
  301. }
  302. }
  303. return FALSE;
  304. }
  305. /**
  306. * Retrieve the regex to capture the Link-out Accession from the Hit Def.
  307. *
  308. * @param $nid
  309. * The node ID of the BLAST database the hit is from.
  310. * @param $options
  311. * An array of options that can be passed to this function. Supported
  312. * options include:
  313. * -
  314. *
  315. * @return
  316. * A PHP regex for use with preg_match to cature the Link-out Accession.
  317. */
  318. function get_blastdb_linkout_regex($node, $options = array()) {
  319. if (empty($node->linkout->regex)) {
  320. switch ($node->linkout->regex_type) {
  321. case 'default':
  322. $regex = '/^(\S+).*/';
  323. break;
  324. case 'genbank':
  325. $regex = '/^gb\|([^\|])*\|.*/';
  326. break;
  327. case 'embl':
  328. $regex = '/^embl\|([^\|])*\|.*/';
  329. break;
  330. case 'swissprot':
  331. $regex = '/^sp\|([^\|])*\|.*/';
  332. break;
  333. }
  334. }
  335. else {
  336. $regex = $node->linkout->regex;
  337. }
  338. return $regex;
  339. }
  340. /**
  341. * Return a list of recent blast jobs to be displayed to the user.
  342. *
  343. * @param $programs
  344. * An array of blast programs you want jobs to be displayed for (ie: blastn, blastx, tblastn, blastp)
  345. *
  346. * @return
  347. * An array of recent jobs.
  348. */
  349. function get_recent_blast_jobs($programs = array()) {
  350. $filter_jobs = !empty($programs);
  351. // Retrieve any recent jobs from the session variable.
  352. if (isset($_SESSION['blast_jobs'])) {
  353. $jobs = array();
  354. foreach ($_SESSION['blast_jobs'] as $job_secret) {
  355. $add = TRUE;
  356. $job_id = blast_ui_reveal_secret($job_secret);
  357. $job = get_BLAST_job($job_id);
  358. // @TODO: Check that the results are still available.
  359. // This is meant to replace the arbitrary only show jobs executed less than 48 hrs ago.
  360. // Remove jobs from the list that are not of the correct program.
  361. if ($filter_jobs AND !in_array($job->program, $programs)) {
  362. $add = FALSE;
  363. }
  364. if ($add) {
  365. $job->query_summary = format_query_headers($job->files->query);
  366. $jobs[] = $job;
  367. }
  368. }
  369. return $jobs;
  370. }
  371. else {
  372. return array();
  373. }
  374. }
  375. /**
  376. * Retrieve the number of recent jobs.
  377. */
  378. function get_number_of_recent_jobs() {
  379. if (isset($_SESSION['blast_jobs'])) {
  380. return sizeof($_SESSION['blast_jobs']);
  381. }
  382. return 0;
  383. }
  384. /**
  385. * Summarize a fasta file based on it's headers.
  386. *
  387. * @param $file
  388. * The full path to the FASTA file.
  389. *
  390. * @return
  391. * A string describing the number of sequences and often including the first query header.
  392. */
  393. function format_query_headers($file) {
  394. $headers = array();
  395. exec('grep ">" ' . escapeshellarg($file), $headers);
  396. // Easiest case: if there is only one query header then show it.
  397. if (sizeof($headers) == 1 AND isset($headers[0])) {
  398. return ltrim($headers[0], '>');
  399. }
  400. // If we have at least one header then show that along with the count of queries.
  401. elseif (isset($headers[0])) {
  402. return sizeof($headers) . ' queries including "' . ltrim($headers[0], '>') . '"';
  403. }
  404. // If they provided a sequence with no header.
  405. elseif (empty($headers)) {
  406. return 'Unnamed Query';
  407. }
  408. // At the very least show the count of queries.
  409. else {
  410. return sizeof($headers) . ' queries';
  411. }
  412. }
  413. /**
  414. * Sort recent blast jobs by the date they were submitted.
  415. * Ascending is in order of submission.
  416. *
  417. * THIS FUNCTION SHOULD BY USED BY USORT().
  418. */
  419. function sort_blast_jobs_by_date_submitted_asc($a, $b) {
  420. return ($a->date_submitted - $b->date_submitted);
  421. }
  422. /**
  423. * Sort recent blast jobs by the date they were submitted.
  424. * Descending is most recent first.
  425. *
  426. * THIS FUNCTION SHOULD BY USED BY USORT().
  427. */
  428. function sort_blast_jobs_by_date_submitted_desc($a, $b) {
  429. return ($b->date_submitted - $a->date_submitted);
  430. }
  431. /**
  432. * Generate an image of HSPs for a given hit.
  433. *
  434. * history:
  435. * 09/23/10 Carson created
  436. * 04/16/12 eksc adapted into POPcorn code
  437. * 03/12/15 deepak Adapted code into Tripal BLAST
  438. * 10/23/15 lacey Fixed deepak's code to be suitable for Drupal.
  439. *
  440. * @param $acc
  441. * target name
  442. * @param $name
  443. * query name, false if none
  444. * @param $tsize
  445. * target size
  446. * @param $qsize
  447. * query size
  448. * @param $hits
  449. * each hit represented in URL as: targetstart_targetend_hspstart_hspend;
  450. * @param $score
  451. * score for each hit
  452. *
  453. * @returm
  454. * A base64 encoded image representing the hit information.
  455. */
  456. function generate_blast_hit_image($acc = '', $scores, $hits, $tsize, $qsize, $name, $hit_name) {
  457. $tok = strtok($hits, ";");
  458. $b_hits = Array();
  459. while ($tok !== false) {
  460. $b_hits[] = $tok;
  461. $tok = strtok(";");
  462. }
  463. // extract score information from score param
  464. $tokscr = strtok($scores, ";");
  465. $b_scores = Array();
  466. while ($tokscr !== false) {
  467. $b_scores[] = $tokscr;
  468. $tokscr = strtok(";");
  469. }
  470. // image measurements
  471. $height = 200 + (count($b_hits) * 16);
  472. $width = 520;
  473. $img = imagecreatetruecolor($width, $height);
  474. $white = imagecolorallocate($img, 255, 255, 255);
  475. $black = imagecolorallocate($img, 0, 0, 0);
  476. $darkgray = imagecolorallocate($img, 100, 100, 100);
  477. $strong = imagecolorallocatealpha($img, 202, 0, 0, 15);
  478. $moderate = imagecolorallocatealpha($img, 204, 102, 0, 20);
  479. $present = imagecolorallocatealpha($img, 204, 204, 0, 35);
  480. $weak = imagecolorallocatealpha($img, 102, 204, 0, 50);
  481. $gray = imagecolorallocate($img, 190, 190, 190);
  482. $lightgray = $white; //imagecolorallocate($img, 230, 230, 230);
  483. imagefill($img, 0, 0, $lightgray);
  484. // Target coordinates
  485. $maxlength = 300;
  486. $t_length = ($tsize > $qsize)
  487. ? $maxlength : $maxlength - 50;
  488. $q_length = ($qsize > $tsize)
  489. ? $maxlength : $maxlength - 50;
  490. $tnormal = $t_length / $tsize;
  491. $qnormal = $q_length / $qsize;
  492. $t_ystart = 30;
  493. $t_yend = $t_ystart + 20;
  494. $t_xstart = 50;
  495. $t_xend = $t_xstart + $t_length;
  496. $t_center = $t_xstart + ($t_length / 2);
  497. // Target labels
  498. $warn = '"'. $hit_name . '"';
  499. imagestring($img, 5, $t_xstart, $t_ystart-20, $acc.$warn, $black);
  500. imagestring($img, 3, 5, $t_ystart+2, "Target", $black);
  501. // Draw bar representing target
  502. imagefilledrectangle($img, $t_xstart, $t_ystart, $t_xend, $t_yend, $gray);
  503. imagerectangle($img, $t_xstart, $t_ystart, $t_xend, $t_yend, $darkgray);
  504. // query coordinates
  505. $q_maxheight = 250;
  506. $q_ystart = $t_yend + 100;
  507. $q_yend = $q_ystart + 20;
  508. $q_xstart = $t_center - $q_length / 2;
  509. $q_xend = $q_xstart + $q_length;
  510. $q_center = ($q_xend + $q_xstart) / 2;
  511. $q_xwidth = $q_xend - $q_xstart;
  512. // Query labels
  513. imagestring($img, 5, $q_xstart, $q_yend+2, $name, $black);
  514. imagestring($img, 3, $q_xstart, $q_ystart+2, 'Query', $black);
  515. // Draw bar representing query
  516. imagefilledrectangle($img, $q_xstart, $q_ystart, $q_xend, $q_yend, $gray);
  517. imagerectangle($img ,$q_xstart, $q_ystart, $q_xend, $q_yend, $darkgray);
  518. // HSP bars will start here
  519. $hsp_bary = $q_yend + 20;
  520. // Draw solids for HSP alignments
  521. for ($ii=count($b_hits)-1; $ii>=0; $ii--) {
  522. // alignment
  523. $cur_hit = $b_hits[$ii];
  524. $cur_score = intval($b_scores[$ii]);
  525. // set color according to score
  526. $cur_color = $darkgray;
  527. if ($cur_score > 200) {
  528. $cur_color = $strong;
  529. }
  530. else if ($cur_score > 80 && $cur_score <= 200) {
  531. $cur_color = $moderate;
  532. }
  533. else if ($cur_score > 50 && $cur_score <= 80) {
  534. $cur_color = $present;
  535. }
  536. else if ($cur_score > 40 && $cur_score <= 50) {
  537. $cur_color = $weak;
  538. }
  539. $t_start = $tnormal * intval(strtok($cur_hit, "_")) + $t_xstart;
  540. $t_end = $tnormal * intval(strtok("_")) + $t_xstart;
  541. $q_start = $qnormal * intval(strtok("_")) + $q_xstart;
  542. $q_end = $qnormal * intval(strtok("_")) + $q_xstart;
  543. $hit1_array = array($t_start, $t_yend, $t_end, $t_yend, $q_end,
  544. $q_ystart, $q_start, $q_ystart);
  545. // HSP coords
  546. imagefilledpolygon($img, $hit1_array, 4, $cur_color);
  547. }//each hit
  548. // Draw lines over fills for HSP alignments
  549. for ($ii=0; $ii<count($b_hits); $ii++) {
  550. // alignment
  551. $cur_hit = $b_hits[$ii];
  552. $t_start = $tnormal * intval(strtok($cur_hit, "_")) + $t_xstart;
  553. $t_end = $tnormal * intval(strtok("_")) + $t_xstart;
  554. $q_start = $qnormal * intval(strtok("_")) + $q_xstart;
  555. $q_end = $qnormal * intval(strtok("_")) + $q_xstart;
  556. $hit1_array = array($t_start, $t_yend, $t_end, $t_yend, $q_end, $q_ystart,
  557. $q_start, $q_ystart,);
  558. imagerectangle($img, $t_start, $t_ystart, $t_end, $t_yend, $black);
  559. imagerectangle($img, $q_start, $q_ystart, $q_end, $q_yend, $black);
  560. imagepolygon ($img, $hit1_array, 4, $black);
  561. // show HSP
  562. imagestring($img, 3, 2, $hsp_bary, ($acc ."HSP" . ($ii + 1)), $black);
  563. $cur_score = intval($b_scores[$ii]);
  564. // set color according to score
  565. $cur_color = $darkgray;
  566. if ($cur_score > 200) {
  567. $cur_color = $strong;
  568. }
  569. else if ($cur_score > 80 && $cur_score <= 200) {
  570. $cur_color = $moderate;
  571. }
  572. else if ($cur_score > 50 && $cur_score <= 80) {
  573. $cur_color = $present;
  574. }
  575. else if ($cur_score > 40 && $cur_score <= 50) {
  576. $cur_color = $weak;
  577. }
  578. imagefilledrectangle($img, $q_start, $hsp_bary, $q_end, $hsp_bary+10, $cur_color);
  579. $hsp_bary += 15;
  580. }//each hit
  581. // Draw the key
  582. $xchart = 390;
  583. $ychart = 10;
  584. $fontsize = 4;
  585. $yinc = 20;
  586. $ywidth = 7;
  587. $xinc = 10;
  588. imagestring($img, 5, $xchart, $ychart - 5, "Bit Scores", $black);
  589. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 1) + $ywidth, ">= 200" , $black);
  590. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 2) + $ywidth, "80 - 200" , $black);
  591. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 3) + $ywidth, "50 - 80" , $black);
  592. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 4) + $ywidth, "40 - 50" , $black);
  593. imagestring($img, $fontsize, $xchart + $yinc + $xinc,$ychart + ($yinc * 5) + $ywidth, "< 40" , $black);
  594. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 1) + $xinc, $xchart + $yinc, $ychart + ($yinc * 2), $strong);
  595. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 2) + $xinc, $xchart + $yinc, $ychart + ($yinc * 3), $moderate);
  596. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 3) + $xinc, $xchart + $yinc, $ychart + ($yinc * 4), $present);
  597. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 4) + $xinc, $xchart + $yinc, $ychart + ($yinc * 5), $weak);
  598. imagefilledRectangle($img, $xchart, $ychart + ($yinc * 5) + $xinc, $xchart + $yinc, $ychart + ($yinc * 6), $darkgray);
  599. // Now, we have a completed image resource and need to change it to an actual image
  600. // that can be displayed. This is done using imagepng() but unfortuatly that function
  601. // either saves the image to a file or outputs it directly to the screen. Thus, we use
  602. // the following code to capture it and base64 encode it.
  603. ob_start(); // Start buffering the output
  604. imagepng($img, null, 0, PNG_NO_FILTER);
  605. $b64_img = base64_encode(ob_get_contents()); // Get what we've just outputted and base64 it
  606. imagedestroy($img);
  607. ob_end_clean();
  608. return $b64_img;
  609. }
  610. /**
  611. * Convert tsv blast output to gff output file.
  612. *
  613. * Created by Sofia Robb
  614. * 09/15/2016
  615. * counter bugfix 10/27/2016
  616. *
  617. * The subject (hit) will be the source feature.
  618. * The query will be the target.
  619. *
  620. * @todo: find a more efficient way since currently the first loop stores all the blast
  621. * results into an array and then the second loop prints them.
  622. *
  623. * @param $blast_tsv
  624. * The name of the blast tsv output file.
  625. * @param $blast_gff
  626. * The name of the blast gff output file.
  627. */
  628. function convert_tsv2gff3($blast_tsv,$blast_gff){
  629. // Open a new file for writting the gff.
  630. $gff = fopen($blast_gff,"w");
  631. fwrite($gff,"##gff-version 3\n");
  632. // Open the TSV file to read from.
  633. $tsv = fopen($blast_tsv, "r") or die("Unable to open tsv file!");
  634. // For each line in the TSV file...
  635. // Need to go thru each line of tsv to find the first and last hsp of a hit.
  636. $last_s = NULL;
  637. $hsp = NULL;
  638. $HitResult=array();
  639. while(!feof($tsv)) {
  640. $line = fgets($tsv);
  641. $line = rtrim($line);
  642. // Skip the line if it's empty.
  643. if (preg_match('/^#/',$line) or preg_match('/^\s*$/',$line)){
  644. continue;
  645. }
  646. ## for keeping track of new queries and hits
  647. // Each line has the following parts:
  648. // 0: query id,
  649. // 1: subject id,
  650. // 2: % identity,
  651. // 3: alignment length,
  652. // 4: mismatches,
  653. // 5: gap opens,
  654. // 6: q. start,
  655. // 7: q. end,
  656. // 8: s. start,
  657. // 9: s. end,
  658. // 10: evalue,
  659. // 11: bit score
  660. $parts = preg_split('/\t/', $line);
  661. // Assign the important parts of the line to readable variables.
  662. $s = $parts[1];
  663. $q = $parts[0];
  664. $ss = $parts[8];
  665. $se = $parts[9];
  666. $qs = $parts[6];
  667. $qe = $parts[7];
  668. $e = $parts[10];
  669. // if this is a new hit print the last and
  670. // empty the $HitResult array and
  671. // reset hsp counter
  672. if ($last_s != NULL and $s != $last_s ) {
  673. printGFF_parent_children($gff,$HitResult);
  674. $HitResult = array();
  675. $hsp=0;
  676. }
  677. // every line is a new hsp
  678. $hsp++;
  679. // determine query strand to use in match_part line, no need to store, just print
  680. $q_strand = '+';
  681. if ($qs > $qe) {
  682. list($qs,$qe) = array($qe,$qs);
  683. $q_strand = '-';
  684. }
  685. // determine subject (hit) strand to use in match line, needs to be stored
  686. $HitResult["$s,$q"]['strand']='+';
  687. list($start,$end) = array($ss,$se);
  688. if($ss > $se) {
  689. list($start,$end) = array($se,$ss);
  690. $HitResult["$s,$q"]['strand']='-';
  691. }
  692. // store smallest start
  693. if (!array_key_exists('SS',$HitResult["$s,$q"]) or $ss < $HitResult["$s,$q"]['SS']) {
  694. $HitResult["$s,$q"]['SS'] = $ss;
  695. }
  696. // store largest end
  697. if (!array_key_exists('SE',$HitResult["$s,$q"]) or $se > $HitResult["$s,$q"]['SE']) {
  698. $HitResult["$s,$q"]['SE'] = $se;
  699. }
  700. // store best evalue
  701. if (!array_key_exists('E',$HitResult["$s,$q"]) or $e < $HitResult["$s,$q"]['E']) {
  702. $HitResult["$s,$q"]['E'] = $e;
  703. }
  704. // generate the match_part line for each hsp
  705. $HitResult["$s,$q"]['HSPs'][] = join("\t", array($s, "BLASTRESULT" , "match_part" , $start , $end , $e , $HitResult["$s,$q"]['strand'] , '.' , "ID=$s.$q.$hsp;Parent=$s.$q;Target=$q $qs $qe $q_strand"));
  706. $last_s = $s;
  707. } // end tsv file while
  708. // print hit and hsp for the last hit
  709. printGFF_parent_children($gff,$HitResult);
  710. // Close the files.
  711. fclose($tsv);
  712. fclose($gff);
  713. }
  714. /**
  715. * printGFF_parent_children
  716. * prints the GFF parent feature and all of its children features
  717. *
  718. *
  719. * @param $blast_feature_array
  720. * an array of the all the child features which is used to generate the smallest and largest coordinates for the parent
  721. *
  722. *
  723. */
  724. function printGFF_parent_children ($gff,$blast_feature_array){
  725. foreach ($blast_feature_array as $sq => $value ) {
  726. list ($s,$q) = preg_split('/,/' , $sq);
  727. $evalue = $blast_feature_array["$s,$q"]['E'];
  728. $parent = join ("\t", array($s, "BLASTRESULT" , "match" , $blast_feature_array["$s,$q"]['SS'] , $blast_feature_array["$s,$q"]['SE'] , $blast_feature_array["$s,$q"]['E'] , $blast_feature_array["$s,$q"]['strand'] , '.' , "ID=$s.$q;Name=$q($evalue)")) . "\n";
  729. $child = join ("\n",$blast_feature_array["$s,$q"]['HSPs']) . "\n";
  730. fwrite($gff,$parent);
  731. fwrite($gff,$child);
  732. }
  733. }