3 import jalview.bin.Cache;
4 import jalview.datamodel.Alignment;
5 import jalview.datamodel.AlignmentAnnotation;
6 import jalview.datamodel.AlignmentI;
7 import jalview.datamodel.Annotation;
8 import jalview.datamodel.HiddenMarkovModel;
9 import jalview.datamodel.SequenceI;
10 import jalview.gui.AlignFrame;
11 import jalview.gui.Desktop;
12 import jalview.gui.JvOptionPane;
13 import jalview.io.DataSourceType;
14 import jalview.io.FileParse;
15 import jalview.io.StockholmFile;
16 import jalview.util.FileUtils;
17 import jalview.util.MessageManager;
18 import jalview.ws.params.ArgumentI;
19 import jalview.ws.params.simple.BooleanOption;
20 import jalview.ws.params.simple.Option;
22 import java.io.BufferedReader;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.Hashtable;
29 import java.util.List;
30 import java.util.Scanner;
32 import javax.swing.JOptionPane;
34 public class HMMSearch extends HmmerCommand
36 static final String HMMSEARCH = "hmmsearch";
38 boolean realign = false;
42 int seqsToReturn = Integer.MAX_VALUE;
46 private String databaseName;
48 Hashtable sequencesHash;
51 * Constructor for the HMMSearchThread
55 public HMMSearch(AlignFrame af, List<ArgumentI> args)
61 * Runs the HMMSearchThread: the data on the alignment or group is exported,
62 * then the command is executed in the command line and then the data is
63 * imported and displayed in a new frame. Call this method directly to execute
64 * synchronously, or via start() in a new Thread for asynchronously.
69 HiddenMarkovModel hmm = getHmmProfile();
72 // shouldn't happen if we got this far
73 Cache.log.error("Error: no hmm for hmmsearch");
77 SequenceI hmmSeq = hmm.getConsensusSequence();
78 long msgId = System.currentTimeMillis();
79 af.setProgressBar(MessageManager.getString("status.running_search"),
84 File hmmFile = FileUtils.createTempFile("hmm", ".hmm");
85 File hitsAlignmentFile = FileUtils.createTempFile("hitAlignment",
87 File searchOutputFile = FileUtils.createTempFile("searchOutput",
90 exportHmm(hmm, hmmFile.getAbsoluteFile());
92 boolean ran = runCommand(searchOutputFile, hitsAlignmentFile, hmmFile);
95 JvOptionPane.showInternalMessageDialog(af, MessageManager
96 .formatMessage("warn.command_failed", "hmmsearch"));
100 importData(hmmSeq, hitsAlignmentFile, hmmFile, searchOutputFile);
101 // TODO make realignment of search results a step at this level
102 // and make it conditional on this.realign
103 } catch (IOException | InterruptedException e)
109 af.setProgressBar("", msgId);
114 * Executes an hmmsearch with the given hmm as input. The database to be
115 * searched is a local file as specified by the 'Database' parameter, or the
116 * current alignment (written to file) if none is specified.
118 * @param searchOutputFile
119 * @param hitsAlignmentFile
123 * @throws IOException
125 private boolean runCommand(File searchOutputFile, File hitsAlignmentFile,
126 File hmmFile) throws IOException
128 String command = getCommandPath(HMMSEARCH);
134 List<String> args = new ArrayList<>();
136 buildArguments(args, searchOutputFile, hitsAlignmentFile, hmmFile);
138 return runCommand(args);
142 * Appends command line arguments to the given list, to specify input and
143 * output files for the search, and any additional options that may have been
144 * passed from the parameters dialog
147 * @param searchOutputFile
148 * @param hitsAlignmentFile
150 * @throws IOException
152 protected void buildArguments(List<String> args, File searchOutputFile,
153 File hitsAlignmentFile, File hmmFile) throws IOException
156 args.add(getFilePath(searchOutputFile, true));
158 args.add(getFilePath(hitsAlignmentFile, true));
160 boolean dbFound = false;
162 File databaseFile = null;
164 boolean useEvalueCutoff = false;
165 boolean useScoreCutoff = false;
166 String seqEvalueCutoff = null;
167 String domEvalueCutoff = null;
168 String seqScoreCutoff = null;
169 String domScoreCutoff = null;
170 databaseName = "Alignment";
171 boolean searchAlignment = false;
175 for (ArgumentI arg : params)
177 String name = arg.getName();
178 if (MessageManager.getString(NUMBER_OF_RESULTS_KEY)
181 seqsToReturn = Integer.parseInt(arg.getValue());
183 else if (MessageManager.getString("action.search").equals(name))
185 searchAlignment = arg.getValue().equals(
186 MessageManager.getString(HMMSearch.THIS_ALIGNMENT_KEY));
188 else if (MessageManager.getString(DATABASE_KEY).equals(name))
190 dbPath = arg.getValue();
191 int pos = dbPath.lastIndexOf(File.separator);
192 databaseName = dbPath.substring(pos + 1);
193 databaseFile = new File(dbPath);
195 else if (MessageManager.getString(AUTO_ALIGN_SEQS_KEY)
200 else if (MessageManager.getString(USE_ACCESSIONS_KEY)
205 else if (MessageManager.getString(REPORTING_CUTOFF_KEY)
208 if (CUTOFF_EVALUE.equals(arg.getValue()))
210 useEvalueCutoff = true;
212 else if (CUTOFF_SCORE.equals(arg.getValue()))
214 useScoreCutoff = true;
217 else if (MessageManager.getString(SEQ_EVALUE_KEY).equals(name))
219 seqEvalueCutoff = arg.getValue();
221 else if (MessageManager.getString(SEQ_SCORE_KEY).equals(name))
223 seqScoreCutoff = arg.getValue();
225 else if (MessageManager.getString(DOM_EVALUE_KEY)
228 domEvalueCutoff = arg.getValue();
230 else if (MessageManager.getString(DOM_SCORE_KEY).equals(name))
232 domScoreCutoff = arg.getValue();
234 else if (MessageManager.getString(TRIM_TERMINI_KEY)
239 else if (MessageManager.getString(DATABASE_KEY).equals(name))
242 dbPath = arg.getValue();
243 if (!MessageManager.getString(THIS_ALIGNMENT_KEY)
246 int pos = dbPath.lastIndexOf(File.separator);
247 databaseName = dbPath.substring(pos + 1);
248 databaseFile = new File(dbPath);
257 args.add(seqEvalueCutoff);
259 args.add(domEvalueCutoff);
261 else if (useScoreCutoff)
264 args.add(seqScoreCutoff);
266 args.add(domScoreCutoff);
269 // if (!dbFound || MessageManager.getString(THIS_ALIGNMENT_KEY)
274 * no external database specified for search, so
275 * export current alignment as 'database' to search,
276 * excluding any HMM consensus sequences it contains
278 databaseFile = FileUtils.createTempFile("database", ".sto");
279 AlignmentI al = af.getViewport().getAlignment();
280 AlignmentI copy = new Alignment(al);
281 deleteHmmSequences(copy);
283 sequencesHash = stashSequences(copy.getSequencesArray());
285 exportStockholm(copy.getSequencesArray(), databaseFile, null);
289 args.add(getFilePath(hmmFile, true));
290 args.add(getFilePath(databaseFile, true));
294 * Imports the data from the temporary file to which the output of hmmsearch
295 * was directed. The results are optionally realigned using hmmalign.
299 private void importData(SequenceI hmmSeq, File inputAlignmentTemp,
300 File hmmTemp, File searchOutputFile)
301 throws IOException, InterruptedException
303 BufferedReader br = new BufferedReader(
304 new FileReader(inputAlignmentTemp));
307 if (br.readLine() == null)
309 JOptionPane.showMessageDialog(af,
310 MessageManager.getString("label.no_sequences_found"));
313 StockholmFile file = new StockholmFile(new FileParse(
314 inputAlignmentTemp.getAbsolutePath(), DataSourceType.FILE));
315 seqs = file.getSeqsAsArray();
317 recoverSequences(sequencesHash, seqs);
319 // look for PP cons and ref seq in alignment only annotation
320 AlignmentAnnotation modelpos = null, ppcons = null;
321 for (AlignmentAnnotation aa : file.getAnnotations())
323 if (aa.sequenceRef == null)
325 if (aa.label.equals("Reference Positions")) // RF feature type in
330 if (aa.label.equals("Posterior Probability"))
336 readTable(searchOutputFile);
338 int seqCount = Math.min(seqs.length, seqsToReturn);
339 SequenceI[] hmmAndSeqs = new SequenceI[seqCount + 1];
340 hmmSeq = hmmSeq.deriveSequence(); // otherwise all bad things happen
341 hmmAndSeqs[0] = hmmSeq;
342 System.arraycopy(seqs, 0, hmmAndSeqs, 1, seqCount);
343 if (modelpos != null)
345 // TODO need - get ungapped sequence method
347 hmmSeq.getDatasetSequence().getSequenceAsString());
348 Annotation[] refpos = modelpos.annotations;
349 // insert gaps to match with refseq positions
350 int gc = 0, lcol = 0;
351 for (int c = 0; c < refpos.length; c++)
353 if (refpos[c] != null && ("x".equals(refpos[c].displayCharacter)))
357 hmmSeq.insertCharAt(lcol + 1, gc, '-');
370 realignResults(hmmAndSeqs);
374 AlignmentI al = new Alignment(hmmAndSeqs);
377 al.addAnnotation(ppcons);
379 if (modelpos != null)
381 al.addAnnotation(modelpos);
383 AlignFrame alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
384 AlignFrame.DEFAULT_HEIGHT);
385 String ttl = "hmmSearch of " + databaseName + " using "
387 Desktop.addInternalFrame(alignFrame, ttl, AlignFrame.DEFAULT_WIDTH,
388 AlignFrame.DEFAULT_HEIGHT);
392 inputAlignmentTemp.delete();
393 searchOutputFile.delete();
404 * Realigns the given sequences using hmmalign, to the HMM profile sequence
405 * which is the first in the array, and opens the results in a new frame
409 protected void realignResults(SequenceI[] hmmAndSeqs)
412 * and align the search results to the HMM profile
414 AlignmentI al = new Alignment(hmmAndSeqs);
415 AlignFrame frame = new AlignFrame(al, 1, 1);
416 List<ArgumentI> alignArgs = new ArrayList<>();
417 String alignTo = hmmAndSeqs[0].getName();
418 List<String> options = Collections.singletonList(alignTo);
419 Option option = new Option(MessageManager.getString("label.use_hmm"),
420 "", true, alignTo, alignTo, options, null);
421 alignArgs.add(option);
424 alignArgs.add(new BooleanOption(
425 MessageManager.getString(TRIM_TERMINI_KEY),
426 MessageManager.getString("label.trim_termini_desc"), true,
429 HmmerCommand hmmalign = new HMMAlign(frame, alignArgs);
434 * Reads in the scores table output by hmmsearch and adds annotation to
435 * sequences for E-value and bit score
437 * @param inputTableTemp
438 * @throws IOException
440 void readTable(File inputTableTemp) throws IOException
442 BufferedReader br = new BufferedReader(new FileReader(inputTableTemp));
444 while (!line.startsWith("Query:"))
446 line = br.readLine();
448 while (!line.contains("-------"))
450 line = br.readLine();
452 line = br.readLine();
455 while (!" ------ inclusion threshold ------".equals(line)
458 SequenceI seq = seqs[index];
459 Scanner scanner = new Scanner(line);
460 String evalue = scanner.next();
461 String score = scanner.next();
462 addScoreAnnotations(evalue, score, seq);
464 line = br.readLine();
472 protected void addScoreAnnotations(String eValue, String bitScore,
475 String label = "Search Scores";
476 String description = "Full sequence bit score and E-Value";
480 AlignmentAnnotation annot = new AlignmentAnnotation(label,
484 annot.description = description;
486 annot.setCalcId(HMMSEARCH);
488 double dEValue = Double.parseDouble(eValue);
489 annot.setEValue(dEValue);
491 double dBitScore = Double.parseDouble(bitScore);
492 annot.setBitScore(dBitScore);
494 annot.setSequenceRef(seq);
495 seq.addAlignmentAnnotation(annot);
496 } catch (NumberFormatException e)
498 System.err.println("Error parsing " + label + " from " + eValue