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