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 SEQ_EVALUE_KEY = "label.seq_evalue";
77 static final String DOM_EVALUE_KEY = "label.dom_evalue";
79 static final String SEQ_SCORE_KEY = "label.seq_score";
81 static final String DOM_SCORE_KEY = "label.dom_score";
83 static final String ARG_TRIM = "--trim";
91 public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
94 alignment = af.getViewport().getAlignment();
99 * Answers true if preference HMMER_PATH is set, and its value is the path to
100 * a directory that contains an executable <code>hmmbuild</code> or
101 * <code>hmmbuild.exe</code>, else false
105 public static boolean isHmmerAvailable()
107 File exec = FileUtils.getExecutable(HMMBUILD,
108 Cache.getProperty(Preferences.HMMER_PATH));
113 * Uniquifies the sequences when exporting and stores their details in a
118 protected Hashtable stashSequences(SequenceI[] seqs)
120 return SeqsetUtils.uniquify(seqs, true);
124 * Restores the sequence data lost by uniquifying
129 protected void recoverSequences(Hashtable hashtable, SequenceI[] seqs)
131 SeqsetUtils.deuniquify(hashtable, seqs);
135 * Runs a command as a separate process and waits for it to complete. Answers
136 * true if the process return status is zero, else false.
139 * the executable command and any arguments to it
140 * @throws IOException
142 public boolean runCommand(List<String> commands)
145 List<String> args = Platform.isWindows() ? wrapWithCygwin(commands)
150 ProcessBuilder pb = new ProcessBuilder(args);
151 pb.redirectErrorStream(true); // merge syserr to sysout
152 if (Platform.isWindows())
154 String path = pb.environment().get("Path");
155 path = jalview.bin.Cache.getProperty("CYGWIN_PATH") + ";" + path;
156 pb.environment().put("Path", path);
158 final Process p = pb.start();
159 new Thread(new Runnable()
164 BufferedReader input = new BufferedReader(
165 new InputStreamReader(p.getInputStream()));
168 String line = input.readLine();
171 System.out.println(line);
172 line = input.readLine();
174 } catch (IOException e)
182 int exitValue = p.exitValue();
185 Cache.log.error("Command failed, return code = " + exitValue);
186 Cache.log.error("Command/args were: " + args.toString());
188 return exitValue == 0; // 0 is success, by convention
189 } catch (Exception e)
197 * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
198 * command and any arguments to it are converted into a single parameter to the
203 protected List<String> wrapWithCygwin(List<String> commands)
205 File bash = FileUtils.getExecutable("bash",
206 Cache.getProperty(Preferences.CYGWIN_PATH));
209 Cache.log.error("Cygwin shell not found");
213 List<String> wrapped = new ArrayList<>();
214 // wrapped.add("C:\Users\tva\run");
215 wrapped.add(bash.getAbsolutePath());
219 * combine hmmbuild/search/align and arguments to a single string
221 StringBuilder sb = new StringBuilder();
222 for (String cmd : commands)
224 sb.append(" ").append(cmd);
226 wrapped.add(sb.toString());
232 * Exports an alignment, and reference (RF) annotation if present, to the
233 * specified file, in Stockholm format, removing all HMM sequences
238 * @throws IOException
240 public void exportStockholm(SequenceI[] seqs, File toFile,
241 AnnotatedCollectionI annotated)
248 AlignmentI newAl = new Alignment(seqs);
250 if (!newAl.isAligned())
255 if (toFile != null && annotated != null)
257 AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
260 for (AlignmentAnnotation annot : annots)
262 if (annot.label.contains("Reference") || "RF".equals(annot.label))
264 AlignmentAnnotation newRF;
265 if (annot.annotations.length > newAl.getWidth())
267 Annotation[] rfAnnots = new Annotation[newAl.getWidth()];
268 System.arraycopy(annot.annotations, 0, rfAnnots, 0,
270 newRF = new AlignmentAnnotation("RF", "Reference Positions",
275 newRF = new AlignmentAnnotation(annot);
277 newAl.addAnnotation(newRF);
283 for (SequenceI seq : newAl.getSequencesArray())
285 if (seq.getAnnotation() != null)
287 for (AlignmentAnnotation ann : seq.getAnnotation())
289 seq.removeAlignmentAnnotation(ann);
294 StockholmFile file = new StockholmFile(newAl);
295 String output = file.print(seqs, false);
296 PrintWriter writer = new PrintWriter(toFile);
297 writer.println(output);
302 * Answers the full path to the given hmmer executable, or null if file cannot
303 * be found or is not executable
306 * command short name e.g. hmmalign
308 * @throws IOException
310 protected String getCommandPath(String cmd)
313 String binariesFolder = Cache.getProperty(Preferences.HMMER_PATH);
314 // ensure any symlink to the directory is resolved:
315 binariesFolder = Paths.get(binariesFolder).toRealPath().toString();
316 File file = FileUtils.getExecutable(cmd, binariesFolder);
317 if (file == null && af != null)
319 JvOptionPane.showInternalMessageDialog(af, MessageManager
320 .formatMessage("label.executable_not_found", cmd));
323 return file == null ? null : getFilePath(file, true);
327 * Exports an HMM to the specified file
331 * @throws IOException
333 public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
338 HMMFile file = new HMMFile(hmm);
339 PrintWriter writer = new PrintWriter(hmmFile);
340 writer.print(file.print());
347 * Exports a sequence to the specified file
351 * @throws IOException
353 public void exportSequence(SequenceI seq, File seqFile) throws IOException
357 FastaFile file = new FastaFile();
358 PrintWriter writer = new PrintWriter(seqFile);
359 writer.print(file.print(new SequenceI[] { seq }, false));
365 * Answers the HMM profile for the profile sequence the user selected (default
366 * is just the first HMM sequence in the alignment)
370 protected HiddenMarkovModel getHmmProfile()
372 String alignToParamName = MessageManager.getString("label.use_hmm");
373 for (ArgumentI arg : params)
375 String name = arg.getName();
376 if (name.equals(alignToParamName))
378 String seqName = arg.getValue();
379 SequenceI hmmSeq = alignment.findName(seqName);
380 if (hmmSeq.hasHMMProfile())
382 return hmmSeq.getHMM();
390 * Answers the HMM profile for the profile sequence the user selected (default
391 * is just the first HMM sequence in the alignment)
395 protected SequenceI getSequence()
397 String alignToParamName = MessageManager
398 .getString("label.use_sequence");
399 for (ArgumentI arg : params)
401 String name = arg.getName();
402 if (name.equals(alignToParamName))
404 String seqName = arg.getValue();
405 SequenceI seq = alignment.findName(seqName);
413 * Answers an absolute path to the given file, in a format suitable for
414 * processing by a hmmer command. On a Windows platform, the native Windows file
415 * path is converted to Cygwin format, by replacing '\'with '/' and drive letter
416 * X with /cygdrive/x.
420 * True if file is to be read/written from within the Cygwin
421 * shell. Should be false for any imports.
424 protected String getFilePath(File resultFile, boolean isInCygwin)
426 String path = resultFile.getAbsolutePath();
427 if (Platform.isWindows() && isInCygwin)
429 // the first backslash escapes '\' for the regular expression argument
430 path = path.replaceAll("\\" + File.separator, "/");
431 int colon = path.indexOf(':');
434 String drive = path.substring(0, colon);
435 path = path.replaceAll(drive + ":", "/cygdrive/" + drive);
443 * A helper method that deletes any HMM consensus sequence from the given
444 * collection, and from the parent alignment if <code>ac</code> is a subgroup
448 void deleteHmmSequences(AnnotatedCollectionI ac)
450 List<SequenceI> hmmSeqs = ac.getHmmSequences();
451 for (SequenceI hmmSeq : hmmSeqs)
453 if (ac instanceof SequenceGroup)
455 ((SequenceGroup) ac).deleteSequence(hmmSeq, false);
456 AnnotatedCollectionI context = ac.getContext();
457 if (context != null && context instanceof AlignmentI)
459 ((AlignmentI) context).deleteSequence(hmmSeq);
464 ((AlignmentI) ac).deleteSequence(hmmSeq);
470 * Sets the names of any duplicates within the given sequences to include their
471 * respective lengths. Deletes any duplicates that have the same name after this
476 void renameDuplicates(AlignmentI al)
479 SequenceI[] seqs = al.getSequencesArray();
480 List<Boolean> wasRenamed = new ArrayList<>();
482 for (SequenceI seq : seqs)
484 wasRenamed.add(false);
487 for (int i = 0; i < seqs.length; i++)
489 for (int j = 0; j < seqs.length; j++)
491 if (seqs[i].getName().equals(seqs[j].getName()) && i != j
492 && !wasRenamed.get(j))
495 wasRenamed.set(i, true);
496 String range = "/" + seqs[j].getStart() + "-" + seqs[j].getEnd();
497 // setting sequence name to include range - to differentiate between
498 // sequences of the same name. Currently have to include the range twice
499 // because the range is removed (once) when setting the name
500 // TODO come up with a better way of doing this
501 seqs[j].setName(seqs[j].getName() + range + range);
505 if (wasRenamed.get(i))
507 String range = "/" + seqs[i].getStart() + "-" + seqs[i].getEnd();
508 seqs[i].setName(seqs[i].getName() + range + range);
512 for (int i = 0; i < seqs.length; i++)
514 for (int j = 0; j < seqs.length; j++)
516 if (seqs[i].getName().equals(seqs[j].getName()) && i != j)
518 al.deleteSequence(j);