JAL-2629 storage and lifecycle of alignment/group HMM annotations revised
[jalview.git] / src / jalview / hmmer / HMMAlign.java
1 package jalview.hmmer;
2
3 import jalview.analysis.AlignmentSorter;
4 import jalview.datamodel.Alignment;
5 import jalview.datamodel.AlignmentI;
6 import jalview.datamodel.AlignmentOrder;
7 import jalview.datamodel.AlignmentView;
8 import jalview.datamodel.HiddenColumns;
9 import jalview.datamodel.HiddenMarkovModel;
10 import jalview.datamodel.SequenceI;
11 import jalview.gui.AlignFrame;
12 import jalview.gui.Desktop;
13 import jalview.gui.JvOptionPane;
14 import jalview.gui.SplitFrame;
15 import jalview.io.DataSourceType;
16 import jalview.io.StockholmFile;
17 import jalview.util.MessageManager;
18 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
19 import jalview.ws.params.ArgumentI;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Hashtable;
25 import java.util.List;
26
27 import javax.swing.JInternalFrame;
28
29 public class HMMAlign extends HmmerCommand
30 {
31   static final String HMMALIGN = "hmmalign";
32
33   static final String ARG_TRIM = "--trim";
34
35   private final AlignmentI dataset;
36
37   private AlignmentView msa;
38
39   /**
40    * Constructor for the HMMAlignThread
41    * 
42    * @param af
43    * @param args
44    */
45   public HMMAlign(AlignFrame af, List<ArgumentI> args)
46   {
47     super(af, args);
48     if (alignment.getDataset() != null)
49     {
50       dataset = alignment.getDataset();
51     }
52     else
53     {
54       dataset = null;
55     }
56   }
57
58   /**
59    * Runs the HMMAlignThread: the data on the alignment or group is exported,
60    * then the command is executed in the command line and then the data is
61    * imported and displayed in a new frame (if true). The command is executed
62    * for each segment of the alignment. Call this method directly to execute
63    * synchronously, or via start() in a new Thread for asynchronously.
64    */
65   @Override
66   public void run()
67   {
68     HiddenMarkovModel hmm = af.getSelectedHMM();
69     if (hmm == null)
70     {
71       System.err.println("Can't run hmmalign as no HMM profile selected");
72       return;
73     }
74
75     long msgId = System.currentTimeMillis();
76     af.setProgressBar(MessageManager.getString("status.running_hmmalign"),
77             msgId);
78     prepareAlignment();
79     SequenceI[][] subAlignments = msa.getVisibleContigs('-');
80
81     List<AlignmentOrder> allOrders = new ArrayList<>();
82
83     SequenceI[][] allResults = new SequenceI[subAlignments.length][];
84     int job = 0;
85     for (SequenceI[] seqs : subAlignments)
86     {
87       Hashtable sequencesHash = stashSequences(seqs);
88       try
89       {
90         File modelFile = createTempFile("hmm", ".hmm");
91         File alignmentFile = createTempFile("output", ".sto");
92         File resultFile = createTempFile("input", ".sto");
93
94         exportStockholm(seqs, alignmentFile.getAbsoluteFile(), null);
95         exportHmm(hmm, modelFile.getAbsoluteFile());
96
97         boolean ran = runCommand(modelFile, alignmentFile, resultFile);
98         if (!ran)
99         {
100           JvOptionPane.showInternalMessageDialog(af,
101                   MessageManager.getString("warn.hmmalign_failed"));
102           return;
103         }
104
105         SequenceI[] result = importData(resultFile, allOrders);
106         recoverSequences(sequencesHash, result);
107         allResults[job] = result;
108         modelFile.delete();
109         alignmentFile.delete();
110         resultFile.delete();
111       } catch (IOException e)
112       {
113         e.printStackTrace();
114       }
115       job++;
116     }
117
118     displayResults(allResults, allOrders);
119
120     af.setProgressBar("", msgId);
121   }
122
123   /**
124    * Executes the hmmalign command and returns true if successful, false if an
125    * error is detected
126    * 
127    * @param modelFile
128    *          the HMM to align to
129    * @param alignmentFile
130    *          the sequences to align
131    * @param resultFile
132    *          the file to hold the results of alignment
133    * @return
134    * @throws IOException
135    */
136   private boolean runCommand(File modelFile, File alignmentFile,
137           File resultFile)
138           throws IOException
139   {
140     String command = getCommandPath(HMMALIGN);
141     if (command == null)
142     {
143       return false;
144     }
145     List<String> args = new ArrayList<>();
146     args.add(command);
147
148     if (params != null)
149     {
150       for (ArgumentI arg : params)
151       {
152         String name = arg.getName();
153         if (MessageManager.getString("label.trim_termini").equals(name))
154         {
155           args.add(ARG_TRIM);
156         }
157       }
158     }
159     args.add("-o");
160     args.add(resultFile.getAbsolutePath());
161     args.add(modelFile.getAbsolutePath());
162     args.add(alignmentFile.getAbsolutePath());
163     
164     return runCommand(args);
165   }
166
167   /**
168    * Imports the data from the file holding the output of hmmalign
169    * 
170    * @param resultFile
171    * @param allOrders
172    *          a list of alignment orders to add to
173    * 
174    * @return
175    * @throws IOException
176    */
177   private SequenceI[] importData(File resultFile,
178           List<AlignmentOrder> allOrders) throws IOException
179   {
180     StockholmFile file = new StockholmFile(resultFile.getAbsolutePath(),
181             DataSourceType.FILE);
182     SequenceI[] result = file.getSeqsAsArray();
183     AlignmentOrder msaorder = new AlignmentOrder(result);
184     AlignmentSorter.recoverOrder(result);
185     allOrders.add(msaorder);
186
187     return result;
188   }
189
190   /**
191    * Gathers the sequences in preparation for the alignment.
192    */
193   private void prepareAlignment()
194   {
195     msa = af.gatherSequencesForAlignment();
196   }
197
198   /**
199    * Displays the results of all 'jobs' in a new frame
200    * 
201    * @param allResults
202    * 
203    * @param allOrders
204    */
205   private void displayResults(SequenceI[][] allResults,
206           List<AlignmentOrder> allOrders)
207   {
208     AlignmentOrder[] arrOrders = allOrders
209             .toArray(new AlignmentOrder[allOrders.size()]);
210     Object[] newview = msa.getUpdatedView(allResults, arrOrders, '-');
211     SequenceI[] seqs = (SequenceI[]) newview[0];
212     HiddenColumns hidden = (HiddenColumns) newview[1];
213     Alignment al = new Alignment(seqs);
214     al.setProperty("Alignment Program", "hmmalign");
215     if (dataset != null)
216     {
217       al.setDataset(dataset);
218     }
219
220     displayInNewFrame(al, allOrders, hidden);
221   }
222
223   /**
224    * Displays the results in a new frame
225    * 
226    * @param al
227    *          The alignment containing the results
228    * @param alorders
229    *          The order of the sequences in the alignment on which the jobs were
230    *          run
231    * @param hidden
232    *          Hidden columns in the previous alignment
233    */
234   private void displayInNewFrame(AlignmentI al,
235           List<AlignmentOrder> alorders, HiddenColumns hidden)
236   {
237     AlignFrame alignFrame = new AlignFrame(al, hidden, AlignFrame.DEFAULT_WIDTH,
238             AlignFrame.DEFAULT_HEIGHT);
239
240     FeatureRendererSettings featureSettings = af.getFeatureRenderer()
241             .getSettings();
242     // initialise with same renderer settings as in parent alignframe.
243     alignFrame.getFeatureRenderer().transferSettings(featureSettings);
244
245     addSortByMenuItems(alignFrame, alorders);
246
247     // TODO: refactor retrieve and show as new splitFrame as Desktop method
248
249     /*
250      * If alignment was requested from one half of a SplitFrame, show in a
251      * SplitFrame with the other pane similarly aligned.
252      */
253     AlignFrame requestedBy = this.af;
254     if (requestedBy != null && requestedBy.getSplitViewContainer() != null
255             && requestedBy.getSplitViewContainer()
256                     .getComplement(requestedBy) != null)
257     {
258       AlignmentI complement = requestedBy.getSplitViewContainer()
259               .getComplement(requestedBy);
260       String complementTitle = requestedBy.getSplitViewContainer()
261               .getComplementTitle(requestedBy);
262       // becomes null if the alignment window was closed before the alignment
263       // job finished.
264       AlignmentI copyComplement = new Alignment(complement);
265       // todo should this be done by copy constructor?
266       copyComplement.setGapCharacter(complement.getGapCharacter());
267       // share the same dataset (and the mappings it holds)
268       copyComplement.setDataset(complement.getDataset());
269       copyComplement.alignAs(al);
270       if (copyComplement.getHeight() > 0)
271       {
272         alignFrame.setTitle(this.af.getTitle());
273         AlignFrame af2 = new AlignFrame(copyComplement,
274                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
275         af2.setTitle(complementTitle);
276         String linkedTitle = MessageManager
277                 .getString("label.linked_view_title");
278         JInternalFrame splitFrame = new SplitFrame(
279                 al.isNucleotide() ? alignFrame : af2, al.isNucleotide() ? af2 : alignFrame);
280         Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
281         return;
282       }
283     }
284
285     /*
286      * Not from SplitFrame, or failed to created a complementary alignment
287      */
288     Desktop.addInternalFrame(alignFrame, alignFrame.getTitle(), AlignFrame.DEFAULT_WIDTH,
289             AlignFrame.DEFAULT_HEIGHT);
290   }
291
292   /**
293    * Adds sort order options to the AlignFrame menus
294    * 
295    * @param alignFrame
296    * @param alorders
297    */
298   protected void addSortByMenuItems(AlignFrame alignFrame,
299           List<AlignmentOrder> alorders)
300   {
301     // update orders
302     if (alorders.size() == 1)
303     {
304       alignFrame.addSortByOrderMenuItem("hmmalign" + " Ordering", alorders.get(0));
305     }
306     else
307     {
308       // construct a non-redundant ordering set
309       List<String> names = new ArrayList<>();
310       for (int i = 0, l = alorders.size(); i < l; i++)
311       {
312         String orderName = " Region " + i;
313         int j = i + 1;
314
315         while (j < l)
316         {
317           if (alorders.get(i).equals(alorders.get(j)))
318           {
319             alorders.remove(j);
320             l--;
321             orderName += "," + j;
322           }
323           else
324           {
325             j++;
326           }
327         }
328
329         if (i == 0 && j == 1)
330         {
331           names.add("");
332         }
333         else
334         {
335           names.add(orderName);
336         }
337       }
338       for (int i = 0, l = alorders.size(); i < l; i++)
339       {
340         alignFrame.addSortByOrderMenuItem("hmmalign" + (names.get(i)) + " Ordering",
341                 alorders.get(i));
342       }
343     }
344   }
345 }