blast_ui.api.inc 29 KB

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