JAL-2937 hmmbuild input data generated via AlignmentView from alignment, not directly...
[jalview.git] / src / jalview / hmmer / HMMBuild.java
1 package jalview.hmmer;
2
3 import jalview.api.AlignViewportI;
4 import jalview.bin.Cache;
5 import jalview.datamodel.Alignment;
6 import jalview.datamodel.AlignmentI;
7 import jalview.datamodel.AlignmentView;
8 import jalview.datamodel.AnnotatedCollectionI;
9 import jalview.datamodel.SequenceGroup;
10 import jalview.datamodel.SequenceI;
11 import jalview.gui.AlignFrame;
12 import jalview.gui.JvOptionPane;
13 import jalview.io.DataSourceType;
14 import jalview.io.FileParse;
15 import jalview.io.HMMFile;
16 import jalview.util.FileUtils;
17 import jalview.util.MessageManager;
18 import jalview.ws.params.ArgumentI;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.Hashtable;
24 import java.util.List;
25
26 /**
27  * A class that runs the hmmbuild command as a separate process.
28  * 
29  * @author gmcarstairs
30  *
31  */
32 public class HMMBuild extends HmmerCommand
33 {
34   static final String ARG_AMINO = "--amino";
35
36   static final String ARG_DNA = "--dna";
37
38   static final String ARG_RNA = "--rna";
39
40   /**
41    * Constructor
42    * 
43    * @param alignFrame
44    * @param args
45    */
46   public HMMBuild(AlignFrame alignFrame, List<ArgumentI> args)
47   {
48     super(alignFrame, args);
49   }
50
51   /**
52    * Builds a HMM from an alignment (and/or groups), then imports and adds it to
53    * the alignment (and/or groups). Call this method directly to execute
54    * synchronously, or via start() in a new Thread for asynchronously.
55    */
56   @Override
57   public void run()
58   {
59     if (params == null || params.isEmpty())
60     {
61       Cache.log.error("No parameters to HMMBuild!|");
62       return;
63     }
64
65     long msgID = System.currentTimeMillis();
66     af.setProgressBar(MessageManager.getString("status.running_hmmbuild"),
67             msgID);
68
69     AlignViewportI viewport = af.getViewport();
70     try
71     {
72       /*
73        * run hmmbuild for alignment and/or groups as selected
74        */
75       List<AnnotatedCollectionI> runBuildFor = parseParameters(viewport);
76
77       for (AnnotatedCollectionI grp : runBuildFor)
78       {
79         runHMMBuild(grp);
80       }
81     } finally
82     {
83       af.setProgressBar("", msgID);
84       viewport.alignmentChanged(af.alignPanel);
85       af.buildColourMenu(); // to enable HMMER colour schemes
86     }
87   }
88
89   /**
90    * Scans the parameters to determine whether to run hmmmbuild for the whole
91    * alignment or specified subgroup(s) or both
92    * 
93    * @param viewport
94    * @return
95    */
96   protected List<AnnotatedCollectionI> parseParameters(
97           AlignViewportI viewport)
98   {
99     List<AnnotatedCollectionI> runBuildFor = new ArrayList<>();
100     boolean foundArg = false;
101
102     for (ArgumentI arg : params)
103     {
104       String name = arg.getName();
105       if (MessageManager.getString("label.hmmbuild_for").equals(name))
106       {
107         foundArg = true;
108         String value = arg.getValue();
109
110         if (MessageManager.getString("label.alignment").equals(value))
111         {
112           runBuildFor.add(viewport.getAlignmentView(false)
113                   .getVisibleAlignment('-'));
114         }
115         else if (MessageManager.getString("label.groups_and_alignment")
116                 .equals(value))
117         {
118           AlignmentView av = viewport.getAlignmentView(true);
119           runBuildFor.add(av.getVisibleAlignment('-'));
120           runBuildFor.addAll(av.getVisibleGroups('-'));
121         }
122         else if (MessageManager.getString("label.groups").equals(value))
123         {
124           AlignmentView av = viewport.getAlignmentView(false);
125           runBuildFor.addAll(av.getVisibleGroups('-'));
126         }
127         else if (MessageManager.getString("label.selected_group")
128                 .equals(value))
129         {
130           AlignmentView av = viewport.getAlignmentView(true);
131           runBuildFor.add(av.getVisibleAlignment('-'));
132         }
133       }
134       else if (MessageManager.getString("label.use_reference")
135               .equals(name))
136       {
137         // todo disable this option if no RF annotation on alignment
138         if (!af.getViewport().hasReferenceAnnotation())
139         {
140           JvOptionPane.showInternalMessageDialog(af, MessageManager
141                   .getString("warn.no_reference_annotation"));
142           // return;
143         }
144       }
145     }
146
147     /*
148      * default is to build for the whole alignment
149      */
150     if (!foundArg)
151     {
152       runBuildFor.add(alignment);
153     }
154
155     return runBuildFor;
156   }
157
158   /**
159    * Runs hmmbuild on the given sequences (alignment or group)
160    * 
161    * @param grp
162    */
163   private void runHMMBuild(AnnotatedCollectionI ac)
164   {
165     File hmmFile = null;
166     File alignmentFile = null;
167     try
168     {
169       hmmFile = FileUtils.createTempFile("hmm", ".hmm");
170       alignmentFile = FileUtils.createTempFile("output", ".sto");
171
172       if (ac instanceof Alignment)
173       {
174         AlignmentI al = (Alignment) ac;
175         // todo pad gaps in an unaligned SequenceGroup as well?
176         if (!al.isAligned())
177         {
178           al.padGaps();
179         }
180       }
181
182       deleteHmmSequences(ac);
183
184       List<SequenceI> copy = new ArrayList<>();
185       if (ac instanceof Alignment)
186       {
187         copy.addAll(ac.getSequences());
188       }
189       else
190       {
191         SequenceI[] sel = ((SequenceGroup) ac)
192                 .getSelectionAsNewSequences((AlignmentI) ac.getContext(),
193                         false);
194         for (SequenceI seq : sel)
195         {
196           copy.add(seq);
197         }
198       }
199
200       SequenceI[] copyArray = copy.toArray(new SequenceI[copy.size()]);
201       Hashtable sequencesHash = stashSequences(copyArray);
202
203       exportStockholm(copyArray, alignmentFile, ac);
204
205       recoverSequences(sequencesHash, copy.toArray(new SequenceI[] {}));
206
207       boolean ran = runCommand(alignmentFile, hmmFile, ac);
208       if (!ran)
209       {
210         JvOptionPane.showInternalMessageDialog(af, MessageManager
211                 .formatMessage("warn.command_failed", "hmmbuild"));
212         return;
213       }
214       importData(hmmFile, ac);
215     } catch (Exception e)
216     {
217       e.printStackTrace();
218     } finally
219     {
220       if (hmmFile != null)
221       {
222         hmmFile.delete();
223       }
224       if (alignmentFile != null)
225       {
226         alignmentFile.delete();
227       }
228     }
229   }
230
231   /**
232    * A helper method that deletes any HMM consensus sequence from the given
233    * collection, and from the parent alignment if <code>ac</code> is a subgroup
234    * 
235    * @param ac
236    */
237   void deleteHmmSequences(AnnotatedCollectionI ac)
238   {
239     List<SequenceI> hmmSeqs = ac.getHmmSequences();
240     for (SequenceI hmmSeq : hmmSeqs)
241     {
242       if (ac instanceof SequenceGroup)
243       {
244         ((SequenceGroup) ac).deleteSequence(hmmSeq, false);
245         AnnotatedCollectionI context = ac.getContext();
246         if (context != null && context instanceof AlignmentI)
247         {
248           ((AlignmentI) context).deleteSequence(hmmSeq);
249         }
250       }
251       else
252       {
253         ((AlignmentI) ac).deleteSequence(hmmSeq);
254       }
255     }
256   }
257
258   /**
259    * Constructs and executes the hmmbuild command as a separate process
260    * 
261    * @param sequencesFile
262    *          the alignment from which the HMM is built
263    * @param hmmFile
264    *          the output file to which the HMM is written
265    * @param group
266    *          alignment or group for which the hmm is generated
267    * 
268    * @return
269    * @throws IOException
270    */
271   private boolean runCommand(File sequencesFile, File hmmFile,
272           AnnotatedCollectionI group) throws IOException
273   {
274     String cmd = getCommandPath(HMMBUILD);
275     if (cmd == null)
276     {
277       return false; // executable not found
278     }
279     List<String> args = new ArrayList<>();
280     args.add(cmd);
281
282     /*
283      * HMM name (will be given to consensus sequence) is
284      * - as specified by an input parameter if set
285      * - else group name with _HMM appended (if for a group)
286      * - else align frame title with _HMM appended (if title is not too long)
287      * - else "Alignment_HMM" 
288      */
289     String name = "";
290
291     if (params != null)
292     {
293       for (ArgumentI arg : params)
294       {
295         String argName = arg.getName();
296         switch (argName)
297         {
298         case "HMM Name":
299           name = arg.getValue().trim();
300           break;
301         case "Use Reference Annotation":
302           args.add("--hand");
303           break;
304         }
305       }
306     }
307
308     if (group instanceof SequenceGroup)
309     {
310       name = ((SequenceGroup) group).getName() + "_HMM";
311     }
312
313     if ("".equals(name))
314     {
315       if (af != null && af.getTitle().length() < 15)
316       {
317         name = af.getTitle();
318       }
319       else
320       {
321         name = "Alignment_HMM";
322       }
323     }
324
325     args.add("-n");
326     args.add(name.replace(' ', '_'));
327     if (!alignment.isNucleotide())
328     {
329       args.add(ARG_AMINO); // TODO check for rna
330     }
331     else
332     {
333       args.add(ARG_DNA);
334     }
335
336     args.add(getFilePath(hmmFile));
337     args.add(getFilePath(sequencesFile));
338
339     return runCommand(args);
340   }
341
342   /**
343    * Imports the .hmm file produced by hmmbuild, and inserts the HMM consensus
344    * sequence (with attached HMM profile) as the first sequence in the alignment
345    * or group for which it was generated
346    * 
347    * @param hmmFile
348    * @param ac
349    *          (optional) the group for which the hmm was generated
350    * @throws IOException
351    */
352   private void importData(File hmmFile, AnnotatedCollectionI ac)
353           throws IOException
354   {
355     if (hmmFile.length() == 0L)
356     {
357       Cache.log.error("Error: hmmbuild produced empty hmm file");
358       return;
359     }
360
361     HMMFile file = new HMMFile(
362             new FileParse(hmmFile.getAbsolutePath(), DataSourceType.FILE));
363     SequenceI hmmSeq = file.getHMM().getConsensusSequence();
364
365     if (hmmSeq == null)
366     {
367       // hmmbuild failure not detected earlier
368       return;
369     }
370
371     if (ac instanceof SequenceGroup)
372     {
373       SequenceGroup grp = (SequenceGroup) ac;
374       char gapChar = alignment.getGapCharacter();
375       hmmSeq.insertCharAt(0, ac.getStartRes(), gapChar);
376       hmmSeq.insertCharAt(ac.getEndRes() + 1,
377               alignment.getWidth() - ac.getEndRes() - 1, gapChar);
378       SequenceI topSeq = grp.getSequencesInOrder(alignment)[0];
379       int topIndex = alignment.findIndex(topSeq);
380       alignment.insertSequenceAt(topIndex, hmmSeq);
381       ac.setSeqrep(hmmSeq);
382       grp.addSequence(hmmSeq, false);
383     }
384     else
385     {
386       alignment.insertSequenceAt(0, hmmSeq);
387     }
388   }
389 }