3 import jalview.analysis.SeqsetUtils;
4 import jalview.bin.Cache;
5 import jalview.datamodel.Alignment;
6 import jalview.datamodel.AlignmentAnnotation;
7 import jalview.datamodel.AlignmentI;
8 import jalview.datamodel.AnnotatedCollectionI;
9 import jalview.datamodel.Annotation;
10 import jalview.datamodel.HiddenMarkovModel;
11 import jalview.datamodel.SequenceGroup;
12 import jalview.datamodel.SequenceI;
13 import jalview.gui.AlignFrame;
14 import jalview.gui.JvOptionPane;
15 import jalview.gui.Preferences;
16 import jalview.io.FastaFile;
17 import jalview.io.HMMFile;
18 import jalview.io.StockholmFile;
19 import jalview.util.FileUtils;
20 import jalview.util.MessageManager;
21 import jalview.util.Platform;
22 import jalview.ws.params.ArgumentI;
24 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStreamReader;
28 import java.io.PrintWriter;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.Hashtable;
32 import java.util.List;
35 * Base class for hmmbuild, hmmalign and hmmsearch
40 public abstract class HmmerCommand implements Runnable
42 public static final String HMMBUILD = "hmmbuild";
44 protected final AlignFrame af;
46 protected final AlignmentI alignment;
48 protected final List<ArgumentI> params;
51 * constants for i18n lookup of passed parameter names
53 static final String DATABASE_KEY = "label.database";
55 static final String THIS_ALIGNMENT_KEY = "label.this_alignment";
57 static final String USE_ACCESSIONS_KEY = "label.use_accessions";
59 static final String AUTO_ALIGN_SEQS_KEY = "label.auto_align_seqs";
61 static final String NUMBER_OF_RESULTS_KEY = "label.number_of_results";
63 static final String TRIM_TERMINI_KEY = "label.trim_termini";
65 static final String RETURN_N_NEW_SEQ = "label.check_for_new_sequences";
67 static final String REPORTING_CUTOFF_KEY = "label.reporting_cutoff";
69 static final String CUTOFF_NONE = "label.default";
71 static final String CUTOFF_SCORE = "label.score";
73 static final String CUTOFF_EVALUE = "label.evalue";
75 static final String REPORTING_SEQ_EVALUE_KEY = "label.reporting_seq_evalue";
77 static final String REPORTING_DOM_EVALUE_KEY = "label.reporting_dom_evalue";
79 static final String REPORTING_SEQ_SCORE_KEY = "label.reporting_seq_score";
81 static final String REPORTING_DOM_SCORE_KEY = "label.reporting_dom_score";
83 static final String INCLUSION_SEQ_EVALUE_KEY = "label.inclusion_seq_evalue";
85 static final String INCLUSION_DOM_EVALUE_KEY = "label.inclusion_dom_evalue";
87 static final String INCLUSION_SEQ_SCORE_KEY = "label.inclusion_seq_score";
89 static final String INCLUSION_DOM_SCORE_KEY = "label.inclusion_dom_score";
91 static final String ARG_TRIM = "--trim";
93 static final String INCLUSION_THRESHOLD_KEY = "label.inclusion_threshold";
101 public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
104 alignment = af.getViewport().getAlignment();
109 * Answers true if preference HMMER_PATH is set, and its value is the path to
110 * a directory that contains an executable <code>hmmbuild</code> or
111 * <code>hmmbuild.exe</code>, else false
115 public static boolean isHmmerAvailable()
117 File exec = FileUtils.getExecutable(HMMBUILD,
118 Cache.getProperty(Preferences.HMMER_PATH));
123 * Uniquifies the sequences when exporting and stores their details in a
128 protected Hashtable stashSequences(SequenceI[] seqs)
130 return SeqsetUtils.uniquify(seqs, true);
134 * Restores the sequence data lost by uniquifying
139 protected void recoverSequences(Hashtable hashtable, SequenceI[] seqs)
141 SeqsetUtils.deuniquify(hashtable, seqs);
145 * Runs a command as a separate process and waits for it to complete. Answers
146 * true if the process return status is zero, else false.
149 * the executable command and any arguments to it
150 * @throws IOException
152 public boolean runCommand(List<String> commands)
155 List<String> args = Platform.isWindows() ? wrapWithCygwin(commands)
160 ProcessBuilder pb = new ProcessBuilder(args);
161 pb.redirectErrorStream(true); // merge syserr to sysout
162 if (Platform.isWindows())
164 String path = pb.environment().get("Path");
165 path = jalview.bin.Cache.getProperty("CYGWIN_PATH") + ";" + path;
166 pb.environment().put("Path", path);
168 final Process p = pb.start();
169 new Thread(new Runnable()
174 BufferedReader input = new BufferedReader(
175 new InputStreamReader(p.getInputStream()));
178 String line = input.readLine();
181 System.out.println(line);
182 line = input.readLine();
184 } catch (IOException e)
192 int exitValue = p.exitValue();
195 Cache.log.error("Command failed, return code = " + exitValue);
196 Cache.log.error("Command/args were: " + args.toString());
198 return exitValue == 0; // 0 is success, by convention
199 } catch (Exception e)
207 * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
208 * command and any arguments to it are converted into a single parameter to the
213 protected List<String> wrapWithCygwin(List<String> commands)
215 File bash = FileUtils.getExecutable("bash",
216 Cache.getProperty(Preferences.CYGWIN_PATH));
219 Cache.log.error("Cygwin shell not found");
223 List<String> wrapped = new ArrayList<>();
224 // wrapped.add("C:\Users\tva\run");
225 wrapped.add(bash.getAbsolutePath());
229 * combine hmmbuild/search/align and arguments to a single string
231 StringBuilder sb = new StringBuilder();
232 for (String cmd : commands)
234 sb.append(" ").append(cmd);
236 wrapped.add(sb.toString());
242 * Exports an alignment, and reference (RF) annotation if present, to the
243 * specified file, in Stockholm format, removing all HMM sequences
248 * @throws IOException
250 public void exportStockholm(SequenceI[] seqs, File toFile,
251 AnnotatedCollectionI annotated)
258 AlignmentI newAl = new Alignment(seqs);
260 if (!newAl.isAligned())
265 if (toFile != null && annotated != null)
267 AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
270 for (AlignmentAnnotation annot : annots)
272 if (annot.label.contains("Reference") || "RF".equals(annot.label))
274 AlignmentAnnotation newRF;
275 if (annot.annotations.length > newAl.getWidth())
277 Annotation[] rfAnnots = new Annotation[newAl.getWidth()];
278 System.arraycopy(annot.annotations, 0, rfAnnots, 0,
280 newRF = new AlignmentAnnotation("RF", "Reference Positions",
285 newRF = new AlignmentAnnotation(annot);
287 newAl.addAnnotation(newRF);
293 for (SequenceI seq : newAl.getSequencesArray())
295 if (seq.getAnnotation() != null)
297 for (AlignmentAnnotation ann : seq.getAnnotation())
299 seq.removeAlignmentAnnotation(ann);
304 StockholmFile file = new StockholmFile(newAl);
305 String output = file.print(seqs, false);
306 PrintWriter writer = new PrintWriter(toFile);
307 writer.println(output);
312 * Answers the full path to the given hmmer executable, or null if file cannot
313 * be found or is not executable
316 * command short name e.g. hmmalign
318 * @throws IOException
320 protected String getCommandPath(String cmd)
323 String binariesFolder = Cache.getProperty(Preferences.HMMER_PATH);
324 // ensure any symlink to the directory is resolved:
325 binariesFolder = Paths.get(binariesFolder).toRealPath().toString();
326 File file = FileUtils.getExecutable(cmd, binariesFolder);
327 if (file == null && af != null)
329 JvOptionPane.showInternalMessageDialog(af, MessageManager
330 .formatMessage("label.executable_not_found", cmd));
333 return file == null ? null : getFilePath(file, true);
337 * Exports an HMM to the specified file
341 * @throws IOException
343 public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
348 HMMFile file = new HMMFile(hmm);
349 PrintWriter writer = new PrintWriter(hmmFile);
350 writer.print(file.print());
357 * Exports a sequence to the specified file
361 * @throws IOException
363 public void exportSequence(SequenceI seq, File seqFile) throws IOException
367 FastaFile file = new FastaFile();
368 PrintWriter writer = new PrintWriter(seqFile);
369 writer.print(file.print(new SequenceI[] { seq }, false));
375 * Answers the HMM profile for the profile sequence the user selected (default
376 * is just the first HMM sequence in the alignment)
380 protected HiddenMarkovModel getHmmProfile()
382 String alignToParamName = MessageManager.getString("label.use_hmm");
383 for (ArgumentI arg : params)
385 String name = arg.getName();
386 if (name.equals(alignToParamName))
388 String seqName = arg.getValue();
389 SequenceI hmmSeq = alignment.findName(seqName);
390 if (hmmSeq.hasHMMProfile())
392 return hmmSeq.getHMM();
400 * Answers the query sequence the user selected (default is just the first
401 * sequence in the alignment)
405 protected SequenceI getSequence()
407 String alignToParamName = MessageManager
408 .getString("label.use_sequence");
409 for (ArgumentI arg : params)
411 String name = arg.getName();
412 if (name.equals(alignToParamName))
414 String seqName = arg.getValue();
415 SequenceI seq = alignment.findName(seqName);
423 * Answers an absolute path to the given file, in a format suitable for
424 * processing by a hmmer command. On a Windows platform, the native Windows file
425 * path is converted to Cygwin format, by replacing '\'with '/' and drive letter
426 * X with /cygdrive/x.
430 * True if file is to be read/written from within the Cygwin
431 * shell. Should be false for any imports.
434 protected String getFilePath(File resultFile, boolean isInCygwin)
436 String path = resultFile.getAbsolutePath();
437 if (Platform.isWindows() && isInCygwin)
439 // the first backslash escapes '\' for the regular expression argument
440 path = path.replaceAll("\\" + File.separator, "/");
441 int colon = path.indexOf(':');
444 String drive = path.substring(0, colon);
445 path = path.replaceAll(drive + ":", "/cygdrive/" + drive);
453 * A helper method that deletes any HMM consensus sequence from the given
454 * collection, and from the parent alignment if <code>ac</code> is a subgroup
458 void deleteHmmSequences(AnnotatedCollectionI ac)
460 List<SequenceI> hmmSeqs = ac.getHmmSequences();
461 for (SequenceI hmmSeq : hmmSeqs)
463 if (ac instanceof SequenceGroup)
465 ((SequenceGroup) ac).deleteSequence(hmmSeq, false);
466 AnnotatedCollectionI context = ac.getContext();
467 if (context != null && context instanceof AlignmentI)
469 ((AlignmentI) context).deleteSequence(hmmSeq);
474 ((AlignmentI) ac).deleteSequence(hmmSeq);
480 * Sets the names of any duplicates within the given sequences to include their
481 * respective lengths. Deletes any duplicates that have the same name after this
486 void renameDuplicates(AlignmentI al)
489 SequenceI[] seqs = al.getSequencesArray();
490 List<Boolean> wasRenamed = new ArrayList<>();
492 for (SequenceI seq : seqs)
494 wasRenamed.add(false);
497 for (int i = 0; i < seqs.length; i++)
499 for (int j = 0; j < seqs.length; j++)
501 if (seqs[i].getName().equals(seqs[j].getName()) && i != j
502 && !wasRenamed.get(j))
505 wasRenamed.set(i, true);
506 String range = "/" + seqs[j].getStart() + "-" + seqs[j].getEnd();
507 // setting sequence name to include range - to differentiate between
508 // sequences of the same name. Currently have to include the range twice
509 // because the range is removed (once) when setting the name
510 // TODO come up with a better way of doing this
511 seqs[j].setName(seqs[j].getName() + range + range);
515 if (wasRenamed.get(i))
517 String range = "/" + seqs[i].getStart() + "-" + seqs[i].getEnd();
518 seqs[i].setName(seqs[i].getName() + range + range);
522 for (int i = 0; i < seqs.length; i++)
524 for (int j = 0; j < seqs.length; j++)
526 if (seqs[i].getName().equals(seqs[j].getName()) && i != j)
528 al.deleteSequence(j);