fb6c38e49eb0d64a80f7f37481d5e0795c4bc30a
[jalview.git] / src / jalview / hmmer / HMMAlignThread.java
1 package jalview.hmmer;
2
3 import jalview.bin.Cache;
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.Preferences;
15 import jalview.gui.SplitFrame;
16 import jalview.io.DataSourceType;
17 import jalview.io.StockholmFile;
18 import jalview.util.MessageManager;
19 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26
27 import javax.swing.JInternalFrame;
28 import javax.swing.JOptionPane;
29
30 public class HMMAlignThread implements Runnable
31 {
32
33   /**
34    * feature settings from view that job was associated with
35    */
36   protected FeatureRendererSettings featureSettings = null;
37
38   HMMERCommands cmds = new HMMERCommands();
39
40   AlignFrame af;
41
42   AlignmentI alignment;
43
44   AlignmentI dataset;
45
46   List<AlignmentOrder> orders;
47
48   AlignmentView msa;
49
50   HiddenMarkovModel hmm;
51
52   boolean newFrame;
53
54   long barID;
55
56   Map<Integer, SequenceI> hmmSeqs;
57
58   File hmmTemp = null;
59
60   File outTemp = null;
61
62   File inputTemp = null;
63
64   List<AlignmentOrder> allOrders;
65
66   SequenceI[][] allResults;
67
68   public HMMAlignThread(AlignFrame af, boolean createNewFrame)
69   {
70     this.af = af;
71     alignment = af.getViewport().getAlignment();
72     if (alignment.getDataset() != null)
73     {
74       dataset = alignment.getDataset();
75     }
76     newFrame = createNewFrame;
77     featureSettings = af.getFeatureRenderer().getSettings();
78   }
79
80   @Override
81   public void run()
82   {
83     if (af.getSelectedHMM() == null)
84     {
85       JOptionPane.showMessageDialog(af,
86               MessageManager.getString("warn.no_selected_hmm"));
87       return;
88     }
89     else
90     {
91       hmm = af.getSelectedHMM();
92     }
93     barID = System.currentTimeMillis();
94     af.setProgressBar(MessageManager.getString("status.running_hmmalign"),
95             barID);
96     cmds.HMMERFOLDER = Cache.getProperty(Preferences.HMMER_PATH);
97
98     // if (!alignment.isAligned())
99     // {
100     // alignment.padGaps();
101     // }
102     prepareAlignment();
103     SequenceI[][] subAlignments = msa.getVisibleContigs('-');
104     allOrders = new ArrayList<>();
105     allResults = new SequenceI[subAlignments.length][];
106     int job = 0;
107     for (SequenceI[] seqs : subAlignments)
108     {
109       cmds.uniquifySequences(seqs);
110       try
111       {
112         createTemporaryFiles();
113       } catch (IOException e2)
114       {
115         e2.printStackTrace();
116       }
117       try
118       {
119         cmds.exportData(seqs, outTemp.getAbsoluteFile(), hmm,
120                 hmmTemp.getAbsoluteFile());
121       } catch (IOException e1)
122       {
123         e1.printStackTrace();
124       }
125       try
126       {
127         boolean ran = runCommand();
128         if (!ran)
129         {
130           JvOptionPane.showInternalMessageDialog(af,
131                   MessageManager.getString("warn.hmmalign_failed"));
132           return;
133         }
134       } catch (IOException | InterruptedException e)
135       {
136         e.printStackTrace();
137       }
138       try
139       {
140         importData(job);
141       } catch (IOException | InterruptedException e)
142       {
143         // TODO Auto-generated catch block
144         e.printStackTrace();
145       }
146       job++;
147     }
148
149     displayResults(newFrame);
150
151     af.setProgressBar(MessageManager.getString("status.running_hmmalign"),
152             barID);
153
154   }
155
156   private void createTemporaryFiles() throws IOException
157   {
158     hmmTemp = File.createTempFile("hmm", ".hmm");
159     hmmTemp.deleteOnExit();
160     outTemp = File.createTempFile("output", ".sto");
161     outTemp.deleteOnExit();
162     inputTemp = File.createTempFile("input", ".sto");
163     inputTemp.deleteOnExit();
164   }
165
166   private boolean runCommand() throws IOException, InterruptedException
167   {
168     File file = new File(cmds.HMMERFOLDER + "/hmmalign");
169     if (!file.canExecute())
170     {
171       file = new File(cmds.HMMERFOLDER + "/hmmalign.exe");
172       {
173         if (!file.canExecute())
174         {
175           return false;
176         }
177       }
178     }
179     String command = cmds.HMMERFOLDER + cmds.HMMALIGN;
180     String version = Cache.getProperty("HMMER_VERSION");
181     if (!"3.1b2".equals(version))
182     {
183       command += cmds.ALLCOL;
184     }
185     boolean trim = true;
186     String bool = Cache.getProperty("TRIM_TERMINI");
187     if ("false".equals(bool))
188     {
189       trim = false;
190     }
191     if (trim)
192     {
193       command += cmds.TRIM;
194     }
195     command += " -o " + inputTemp.getAbsolutePath() + cmds.SPACE
196             + hmmTemp.getAbsolutePath() + cmds.SPACE
197             + outTemp.getAbsolutePath();
198     return cmds.runCommand(command);
199   }
200
201   private void importData(int index)
202           throws IOException, InterruptedException
203   {
204     StockholmFile file = new StockholmFile(inputTemp.getAbsolutePath(),
205             DataSourceType.FILE);
206     SequenceI[] result = file.getSeqsAsArray();
207     AlignmentOrder msaorder = new AlignmentOrder(result);
208     jalview.analysis.AlignmentSorter.recoverOrder(result);
209     jalview.analysis.SeqsetUtils.deuniquify(cmds.hash, result);
210     allOrders.add(msaorder);
211     allResults[index] = result;
212     hmmTemp.delete();
213     outTemp.delete();
214     inputTemp.delete();
215   }
216
217   private void prepareAlignment()
218   {
219     // hmmSeqs = alignment.getHMMConsensusSequences(true);
220     msa = af.gatherSequencesForAlignment();
221   }
222
223   private void displayResults(boolean newFrame)
224   {
225     AlignmentOrder[] arrOrders = allOrders
226             .toArray(new AlignmentOrder[allOrders.size()]);
227     Object[] newview = msa.getUpdatedView(allResults,
228             arrOrders, '-');
229     SequenceI[] alignment = (SequenceI[]) newview[0];
230     HiddenColumns hidden = (HiddenColumns) newview[1];
231     Alignment al = new Alignment(alignment);
232     al.setProperty("Alignment Program", "hmmalign");
233     if (dataset != null)
234     {
235       al.setDataset(dataset);
236     }
237
238     if (newFrame)
239     {
240       displayInNewFrame(al, allOrders, hidden);
241     }
242   }
243
244   private void displayInNewFrame(AlignmentI al,
245           List<AlignmentOrder> alorders, HiddenColumns hidden)
246   {
247     AlignFrame af = new AlignFrame(al, hidden, AlignFrame.DEFAULT_WIDTH,
248             AlignFrame.DEFAULT_HEIGHT);
249
250     // initialise with same renderer settings as in parent alignframe.
251     af.getFeatureRenderer().transferSettings(this.featureSettings);
252
253     if (allOrders.size() > 0)
254     {
255       addSortByMenuItems(af, allOrders);
256     }
257
258     // TODO: refactor retrieve and show as new splitFrame as Desktop method
259
260     /*
261      * If alignment was requested from one half of a SplitFrame, show in a
262      * SplitFrame with the other pane similarly aligned.
263      */
264     AlignFrame requestedBy = this.af;
265     if (requestedBy != null && requestedBy.getSplitViewContainer() != null
266             && requestedBy.getSplitViewContainer()
267                     .getComplement(requestedBy) != null)
268     {
269       AlignmentI complement = requestedBy.getSplitViewContainer()
270               .getComplement(requestedBy);
271       String complementTitle = requestedBy.getSplitViewContainer()
272               .getComplementTitle(requestedBy);
273       // becomes null if the alignment window was closed before the alignment
274       // job finished.
275       AlignmentI copyComplement = new Alignment(complement);
276       // todo should this be done by copy constructor?
277       copyComplement.setGapCharacter(complement.getGapCharacter());
278       // share the same dataset (and the mappings it holds)
279       copyComplement.setDataset(complement.getDataset());
280       copyComplement.alignAs(al);
281       if (copyComplement.getHeight() > 0)
282       {
283         af.setTitle(this.af.getTitle());
284         AlignFrame af2 = new AlignFrame(copyComplement,
285                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
286         af2.setTitle(complementTitle);
287         String linkedTitle = MessageManager
288                 .getString("label.linked_view_title");
289         JInternalFrame splitFrame = new SplitFrame(
290                 al.isNucleotide() ? af : af2, al.isNucleotide() ? af2 : af);
291         Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
292         return;
293       }
294     }
295
296     /*
297      * Not from SplitFrame, or failed to created a complementary alignment
298      */
299     Desktop.addInternalFrame(af, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
300             AlignFrame.DEFAULT_HEIGHT);
301   }
302
303   /**
304    * Add sort order options to the AlignFrame menus.
305    * 
306    * @param af
307    * @param alorders
308    */
309   protected void addSortByMenuItems(AlignFrame af,
310           List<AlignmentOrder> alorders)
311   {
312     // update orders
313     if (alorders.size() == 1)
314     {
315       af.addSortByOrderMenuItem("hmmalign" + " Ordering", alorders.get(0));
316     }
317     else
318     {
319       // construct a non-redundant ordering set
320       List<String> names = new ArrayList<>();
321       for (int i = 0, l = alorders.size(); i < l; i++)
322       {
323         String orderName = " Region " + i;
324         int j = i + 1;
325
326         while (j < l)
327         {
328           if (alorders.get(i).equals(alorders.get(j)))
329           {
330             alorders.remove(j);
331             l--;
332             orderName += "," + j;
333           }
334           else
335           {
336             j++;
337           }
338         }
339
340         if (i == 0 && j == 1)
341         {
342           names.add("");
343         }
344         else
345         {
346           names.add(orderName);
347         }
348       }
349       for (int i = 0, l = alorders.size(); i < l; i++)
350       {
351         af.addSortByOrderMenuItem("hmmalign" + (names.get(i)) + " Ordering",
352                 alorders.get(i));
353       }
354     }
355   }
356
357   }
358
359