79fcb4c44ea640761caa0b5329b0c81ba9ff4104
[jalview.git] / src / jalview / hmmer / HmmerCommand.java
1 package jalview.hmmer;
2
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;
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.io.PrintWriter;
30 import java.nio.file.Paths;
31 import java.util.ArrayList;
32 import java.util.Hashtable;
33 import java.util.List;
34
35 /**
36  * Base class for hmmbuild, hmmalign and hmmsearch
37  * 
38  * @author TZVanaalten
39  *
40  */
41 public abstract class HmmerCommand implements Runnable
42 {
43   public static final String HMMBUILD = "hmmbuild";
44
45   protected final AlignFrame af;
46
47   protected final AlignmentI alignment;
48
49   protected final List<ArgumentI> params;
50
51   /*
52    * constants for i18n lookup of passed parameter names
53    */
54   static final String DATABASE_KEY = "label.database";
55
56   static final String THIS_ALIGNMENT_KEY = "label.this_alignment";
57
58   static final String USE_ACCESSIONS_KEY = "label.use_accessions";
59
60   static final String AUTO_ALIGN_SEQS_KEY = "label.auto_align_seqs";
61
62   static final String NUMBER_OF_RESULTS_KEY = "label.number_of_results";
63
64   static final String TRIM_TERMINI_KEY = "label.trim_termini";
65
66   static final String REPORTING_CUTOFF_KEY = "label.reporting_cutoff";
67
68   static final String CUTOFF_NONE = "None";
69
70   static final String CUTOFF_SCORE = "Score";
71
72   static final String CUTOFF_EVALUE = "E-Value";
73
74   static final String SEQ_EVALUE_KEY = "label.seq_evalue";
75
76   static final String DOM_EVALUE_KEY = "label.dom_evalue";
77
78   static final String SEQ_SCORE_KEY = "label.seq_score";
79
80   static final String DOM_SCORE_KEY = "label.dom_score";
81
82   static final String ARG_TRIM = "--trim";
83
84   /**
85    * Constructor
86    * 
87    * @param alignFrame
88    * @param args
89    */
90   public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
91   {
92     af = alignFrame;
93     alignment = af.getViewport().getAlignment();
94     params = args;
95   }
96
97   /**
98    * Answers true if preference HMMER_PATH is set, and its value is the path to
99    * a directory that contains an executable <code>hmmbuild</code> or
100    * <code>hmmbuild.exe</code>, else false
101    * 
102    * @return
103    */
104   public static boolean isHmmerAvailable()
105   {
106     File exec = FileUtils.getExecutable(HMMBUILD,
107             Cache.getProperty(Preferences.HMMER_PATH));
108     return exec != null;
109   }
110
111   /**
112    * Uniquifies the sequences when exporting and stores their details in a
113    * hashtable
114    * 
115    * @param seqs
116    */
117   protected Hashtable stashSequences(SequenceI[] seqs)
118   {
119     return SeqsetUtils.uniquify(seqs, true);
120   }
121
122   /**
123    * Restores the sequence data lost by uniquifying
124    * 
125    * @param hashtable
126    * @param seqs
127    */
128   protected void recoverSequences(Hashtable hashtable, SequenceI[] seqs)
129   {
130     SeqsetUtils.deuniquify(hashtable, seqs);
131   }
132
133   /**
134    * Runs a command as a separate process and waits for it to complete. Answers
135    * true if the process return status is zero, else false.
136    * 
137    * @param commands
138    *          the executable command and any arguments to it
139    * @throws IOException
140    */
141   public boolean runCommand(List<String> commands)
142           throws IOException
143   {
144     List<String> args = Platform.isWindows() ? wrapWithCygwin(commands)
145             : commands;
146
147     try
148     {
149       ProcessBuilder pb = new ProcessBuilder(args);
150       pb.redirectErrorStream(true); // merge syserr to sysout
151       if (Platform.isWindows())
152       {
153         String path = pb.environment().get("Path");
154         path = jalview.bin.Cache.getProperty("CYGWIN_PATH") + ";" + path;
155         pb.environment().put("Path", path);
156       }
157       final Process p = pb.start();
158       new Thread(new Runnable()
159       {
160         @Override
161         public void run()
162         {
163           BufferedReader input = new BufferedReader(
164                   new InputStreamReader(p.getInputStream()));
165           try
166           {
167             String line = input.readLine();
168             while (line != null)
169             {
170               System.out.println(line);
171               line = input.readLine();
172             }
173           } catch (IOException e)
174           {
175             e.printStackTrace();
176           }
177         }
178       }).start();
179
180       p.waitFor();
181       int exitValue = p.exitValue();
182       if (exitValue != 0)
183       {
184         Cache.log.error("Command failed, return code = " + exitValue);
185         Cache.log.error("Command/args were: " + args.toString());
186       }
187       return exitValue == 0; // 0 is success, by convention
188     } catch (Exception e)
189     {
190       e.printStackTrace();
191       return false;
192     }
193   }
194
195   /**
196    * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
197    * command and any arguments to it are converted into a single parameter to the
198    * bash command.
199    * 
200    * @param commands
201    */
202   protected List<String> wrapWithCygwin(List<String> commands)
203   {
204     File bash = FileUtils.getExecutable("bash",
205             Cache.getProperty(Preferences.CYGWIN_PATH));
206     if (bash == null)
207     {
208       Cache.log.error("Cygwin shell not found");
209       return commands;
210     }
211
212     List<String> wrapped = new ArrayList<>();
213     // wrapped.add("C:\Users\tva\run");
214     wrapped.add(bash.getAbsolutePath());
215     wrapped.add("-c");
216
217     /*
218      * combine hmmbuild/search/align and arguments to a single string
219      */
220     StringBuilder sb = new StringBuilder();
221     for (String cmd : commands)
222     {
223       sb.append(" ").append(cmd);
224     }
225     wrapped.add(sb.toString());
226
227     return wrapped;
228   }
229
230   /**
231    * Exports an alignment, and reference (RF) annotation if present, to the
232    * specified file, in Stockholm format, removing all HMM sequences
233    * 
234    * @param seqs
235    * @param toFile
236    * @param annotated
237    * @throws IOException
238    */
239   public void exportStockholm(SequenceI[] seqs, File toFile,
240           AnnotatedCollectionI annotated) throws IOException
241   {
242     if (seqs == null)
243     {
244       return;
245     }
246     AlignmentI newAl = new Alignment(seqs);
247     if (!newAl.isAligned())
248     {
249       newAl.padGaps();
250     }
251
252     if (toFile != null && annotated != null)
253     {
254       AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
255       if (annots != null)
256       {
257         for (AlignmentAnnotation annot : annots)
258         {
259           if (annot.label.contains("Reference") || "RF".equals(annot.label))
260           {
261             AlignmentAnnotation newRF;
262             if (annot.annotations.length > newAl.getWidth())
263             {
264               Annotation[] rfAnnots = new Annotation[newAl.getWidth()];
265               System.arraycopy(annot.annotations, 0, rfAnnots, 0,
266                       rfAnnots.length);
267               newRF = new AlignmentAnnotation("RF", "Reference Positions",
268                       rfAnnots);
269             }
270             else
271             {
272               newRF = new AlignmentAnnotation(annot);
273             }
274             newAl.addAnnotation(newRF);
275           }
276         }
277       }
278     }
279
280     StockholmFile file = new StockholmFile(newAl);
281     String output = file.print(seqs, false);
282     PrintWriter writer = new PrintWriter(toFile);
283     writer.println(output);
284     writer.close();
285   }
286
287   /**
288    * Exports the given alignment withotu any anotations to a fasta file
289    * 
290    * @param seqs
291    * @param toFile
292    */
293   public void exportFasta(AlignmentI al, File toFile)
294   {
295     FastaFile file = new FastaFile();
296
297     String output = file.print(al.getSequencesArray(), false);
298     PrintWriter writer;
299     try
300     {
301       writer = new PrintWriter(toFile);
302       writer.println(output);
303       writer.close();
304     } catch (FileNotFoundException e)
305     {
306       e.printStackTrace();
307     }
308
309   }
310
311   /**
312    * Answers the full path to the given hmmer executable, or null if file cannot
313    * be found or is not executable
314    * 
315    * @param cmd
316    *          command short name e.g. hmmalign
317    * @return
318    * @throws IOException
319    */
320   protected String getCommandPath(String cmd)
321           throws IOException
322   {
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)
328     {
329       JvOptionPane.showInternalMessageDialog(af, MessageManager
330               .formatMessage("label.executable_not_found", cmd));
331     }
332
333     return file == null ? null : getFilePath(file, true);
334   }
335
336   /**
337    * Exports an HMM to the specified file
338    * 
339    * @param hmm
340    * @param hmmFile
341    * @throws IOException
342    */
343   public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
344           throws IOException
345   {
346     if (hmm != null)
347     {
348       HMMFile file = new HMMFile(hmm);
349       PrintWriter writer = new PrintWriter(hmmFile);
350       writer.print(file.print());
351       writer.close();
352     }
353   }
354
355   // TODO is needed?
356   /**
357    * Exports a sequence to the specified file
358    * 
359    * @param hmm
360    * @param hmmFile
361    * @throws IOException
362    */
363   public void exportSequence(SequenceI seq, File seqFile) throws IOException
364   {
365     if (seq != null)
366     {
367       FastaFile file = new FastaFile();
368       PrintWriter writer = new PrintWriter(seqFile);
369       writer.print(file.print(new SequenceI[] { seq }, false));
370       writer.close();
371     }
372   }
373
374   /**
375    * Answers the HMM profile for the profile sequence the user selected (default
376    * is just the first HMM sequence in the alignment)
377    * 
378    * @return
379    */
380   protected HiddenMarkovModel getHmmProfile()
381   {
382     String alignToParamName = MessageManager.getString("label.use_hmm");
383     for (ArgumentI arg : params)
384     {
385       String name = arg.getName();
386       if (name.equals(alignToParamName))
387       {
388         String seqName = arg.getValue();
389         SequenceI hmmSeq = alignment.findName(seqName);
390         if (hmmSeq.hasHMMProfile())
391         {
392           return hmmSeq.getHMM();
393         }
394       }
395     }
396     return null;
397   }
398
399   /**
400    * Answers the HMM profile for the profile sequence the user selected (default
401    * is just the first HMM sequence in the alignment)
402    * 
403    * @return
404    */
405   protected SequenceI getSequence()
406   {
407     String alignToParamName = MessageManager
408             .getString("label.use_sequence");
409     for (ArgumentI arg : params)
410     {
411       String name = arg.getName();
412       if (name.equals(alignToParamName))
413       {
414         String seqName = arg.getValue();
415         SequenceI seq = alignment.findName(seqName);
416         return seq;
417       }
418     }
419     return null;
420   }
421
422   /**
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.
427    * 
428    * @param resultFile
429    * @param isInCygwin
430    *                     True if file is to be read/written from within the Cygwin
431    *                     shell. Should be false for any imports.
432    * @return
433    */
434   protected String getFilePath(File resultFile, boolean isInCygwin)
435   {
436     String path = resultFile.getAbsolutePath();
437     if (Platform.isWindows() && isInCygwin)
438     {
439       // the first backslash escapes '\' for the regular expression argument
440       path = path.replaceAll("\\" + File.separator, "/");
441       int colon = path.indexOf(':');
442       if (colon > 0)
443       {
444         String drive = path.substring(0, colon);
445         path = path.replaceAll(drive + ":", "/cygdrive/" + drive);
446       }
447     }
448
449     return path;
450   }
451
452   /**
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
455    * 
456    * @param ac
457    */
458   void deleteHmmSequences(AnnotatedCollectionI ac)
459   {
460     List<SequenceI> hmmSeqs = ac.getHmmSequences();
461     for (SequenceI hmmSeq : hmmSeqs)
462     {
463       if (ac instanceof SequenceGroup)
464       {
465         ((SequenceGroup) ac).deleteSequence(hmmSeq, false);
466         AnnotatedCollectionI context = ac.getContext();
467         if (context != null && context instanceof AlignmentI)
468         {
469           ((AlignmentI) context).deleteSequence(hmmSeq);
470         }
471       }
472       else
473       {
474         ((AlignmentI) ac).deleteSequence(hmmSeq);
475       }
476     }
477   }
478 }