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.SequenceI;
12 import jalview.gui.AlignFrame;
13 import jalview.gui.JvOptionPane;
14 import jalview.gui.Preferences;
15 import jalview.io.FastaFile;
16 import jalview.io.HMMFile;
17 import jalview.io.StockholmFile;
18 import jalview.util.FileUtils;
19 import jalview.util.MessageManager;
20 import jalview.util.Platform;
21 import jalview.ws.params.ArgumentI;
23 import java.io.BufferedReader;
25 import java.io.FileNotFoundException;
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 REPORTING_CUTOFF_KEY = "label.reporting_cutoff";
67 static final String CUTOFF_NONE = "None";
69 static final String CUTOFF_SCORE = "Score";
71 static final String CUTOFF_EVALUE = "E-Value";
73 static final String SEQ_EVALUE_KEY = "label.seq_evalue";
75 static final String DOM_EVALUE_KEY = "label.dom_evalue";
77 static final String SEQ_SCORE_KEY = "label.seq_score";
79 static final String DOM_SCORE_KEY = "label.dom_score";
81 static final String ARG_TRIM = "--trim";
89 public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
92 alignment = af.getViewport().getAlignment();
97 * Answers true if preference HMMER_PATH is set, and its value is the path to
98 * a directory that contains an executable <code>hmmbuild</code> or
99 * <code>hmmbuild.exe</code>, else false
103 public static boolean isHmmerAvailable()
105 File exec = FileUtils.getExecutable(HMMBUILD,
106 Cache.getProperty(Preferences.HMMER_PATH));
111 * Uniquifies the sequences when exporting and stores their details in a
116 protected Hashtable stashSequences(SequenceI[] seqs)
118 return SeqsetUtils.uniquify(seqs, true);
122 * Restores the sequence data lost by uniquifying
127 protected void recoverSequences(Hashtable hashtable, SequenceI[] seqs)
129 SeqsetUtils.deuniquify(hashtable, seqs);
133 * Runs a command as a separate process and waits for it to complete. Answers
134 * true if the process return status is zero, else false.
137 * the executable command and any arguments to it
138 * @throws IOException
140 public boolean runCommand(List<String> commands)
143 List<String> args = Platform.isWindows() ? wrapWithCygwin(commands)
148 ProcessBuilder pb = new ProcessBuilder(args);
149 pb.redirectErrorStream(true); // merge syserr to sysout
150 if (Platform.isWindows())
152 String path = pb.environment().get("Path");
153 path = jalview.bin.Cache.getProperty("CYGWIN_PATH") + ";" + path;
154 pb.environment().put("Path", path);
156 final Process p = pb.start();
157 new Thread(new Runnable()
162 BufferedReader input = new BufferedReader(
163 new InputStreamReader(p.getInputStream()));
166 String line = input.readLine();
169 System.out.println(line);
170 line = input.readLine();
172 } catch (IOException e)
180 int exitValue = p.exitValue();
183 Cache.log.error("Command failed, return code = " + exitValue);
184 Cache.log.error("Command/args were: " + args.toString());
186 return exitValue == 0; // 0 is success, by convention
187 } catch (Exception e)
195 * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
196 * command and any arguments to it are converted into a single parameter to the
201 protected List<String> wrapWithCygwin(List<String> commands)
203 File bash = FileUtils.getExecutable("bash",
204 Cache.getProperty(Preferences.CYGWIN_PATH));
207 Cache.log.error("Cygwin shell not found");
211 List<String> wrapped = new ArrayList<>();
212 // wrapped.add("C:\Users\tva\run");
213 wrapped.add(bash.getAbsolutePath());
217 * combine hmmbuild/search/align and arguments to a single string
219 StringBuilder sb = new StringBuilder();
220 for (String cmd : commands)
222 sb.append(" ").append(cmd);
224 wrapped.add(sb.toString());
230 * Exports an alignment, and reference (RF) annotation if present, to the
231 * specified file, in Stockholm format
236 * @throws IOException
238 public void exportStockholm(SequenceI[] seqs, File toFile,
239 AnnotatedCollectionI annotated) throws IOException
245 AlignmentI newAl = new Alignment(seqs);
246 if (!newAl.isAligned())
251 if (toFile != null && annotated != null)
253 AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
256 for (AlignmentAnnotation annot : annots)
258 if (annot.label.contains("Reference") || "RF".equals(annot.label))
260 AlignmentAnnotation newRF;
261 if (annot.annotations.length > newAl.getWidth())
263 Annotation[] rfAnnots = new Annotation[newAl.getWidth()];
264 System.arraycopy(annot.annotations, 0, rfAnnots, 0,
266 newRF = new AlignmentAnnotation("RF", "Reference Positions",
271 newRF = new AlignmentAnnotation(annot);
273 newAl.addAnnotation(newRF);
279 StockholmFile file = new StockholmFile(newAl);
280 String output = file.print(seqs, false);
281 PrintWriter writer = new PrintWriter(toFile);
282 writer.println(output);
286 public void exportFasta(SequenceI[] seqs, File toFile)
288 FastaFile file = new FastaFile();
289 String output = file.print(seqs, false);
293 writer = new PrintWriter(toFile);
294 writer.println(output);
296 } catch (FileNotFoundException e)
304 * Answers the full path to the given hmmer executable, or null if file cannot
305 * be found or is not executable
308 * command short name e.g. hmmalign
310 * @throws IOException
312 protected String getCommandPath(String cmd)
315 String binariesFolder = Cache.getProperty(Preferences.HMMER_PATH);
316 // ensure any symlink to the directory is resolved:
317 binariesFolder = Paths.get(binariesFolder).toRealPath().toString();
318 File file = FileUtils.getExecutable(cmd, binariesFolder);
319 if (file == null && af != null)
321 JvOptionPane.showInternalMessageDialog(af, MessageManager
322 .formatMessage("label.executable_not_found", cmd));
325 return file == null ? null : getFilePath(file, true);
329 * Exports an HMM to the specified file
333 * @throws IOException
335 public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
340 HMMFile file = new HMMFile(hmm);
341 PrintWriter writer = new PrintWriter(hmmFile);
342 writer.print(file.print());
349 * Exports a sequence to the specified file
353 * @throws IOException
355 public void exportSequence(SequenceI seq, File seqFile) throws IOException
359 FastaFile file = new FastaFile();
360 PrintWriter writer = new PrintWriter(seqFile);
361 writer.print(file.print(new SequenceI[] { seq }, false));
367 * Answers the HMM profile for the profile sequence the user selected (default
368 * is just the first HMM sequence in the alignment)
372 protected HiddenMarkovModel getHmmProfile()
374 String alignToParamName = MessageManager.getString("label.use_hmm");
375 for (ArgumentI arg : params)
377 String name = arg.getName();
378 if (name.equals(alignToParamName))
380 String seqName = arg.getValue();
381 SequenceI hmmSeq = alignment.findName(seqName);
382 if (hmmSeq.hasHMMProfile())
384 return hmmSeq.getHMM();
392 * Answers the HMM profile for the profile sequence the user selected (default
393 * is just the first HMM sequence in the alignment)
397 protected SequenceI getSequence()
399 String alignToParamName = MessageManager
400 .getString("label.use_sequence");
401 for (ArgumentI arg : params)
403 String name = arg.getName();
404 if (name.equals(alignToParamName))
406 String seqName = arg.getValue();
407 SequenceI seq = alignment.findName(seqName);
415 * Answers an absolute path to the given file, in a format suitable for
416 * processing by a hmmer command. On a Windows platform, the native Windows file
417 * path is converted to Cygwin format, by replacing '\'with '/' and drive letter
418 * X with /cygdrive/x.
422 * True if file is to be read/written from within the Cygwin
423 * shell. Should be false for any imports.
426 protected String getFilePath(File resultFile, boolean isInCygwin)
428 String path = resultFile.getAbsolutePath();
429 if (Platform.isWindows() && isInCygwin)
431 // the first backslash escapes '\' for the regular expression argument
432 path = path.replaceAll("\\" + File.separator, "/");
433 int colon = path.indexOf(':');
436 String drive = path.substring(0, colon);
437 path = path.replaceAll(drive + ":", "/cygdrive/" + drive);