JAL-2629 add basic parameter adjustment to hmmsearch/align
[jalview.git] / src / jalview / hmmer / HMMAlignThread.java
index 2674c8c..532271b 100644 (file)
@@ -10,12 +10,14 @@ import jalview.datamodel.HiddenMarkovModel;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
 import jalview.gui.Preferences;
 import jalview.gui.SplitFrame;
 import jalview.io.DataSourceType;
 import jalview.io.StockholmFile;
 import jalview.util.MessageManager;
 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
+import jalview.ws.params.ArgumentI;
 
 import java.io.File;
 import java.io.IOException;
@@ -33,6 +35,9 @@ public class HMMAlignThread implements Runnable
    */
   protected FeatureRendererSettings featureSettings = null;
 
+  /**
+   * Object containing frequently used commands.
+   */
   HMMERCommands cmds = new HMMERCommands();
 
   AlignFrame af;
@@ -47,6 +52,8 @@ public class HMMAlignThread implements Runnable
 
   HiddenMarkovModel hmm;
 
+  List<ArgumentI> args;
+
   boolean newFrame;
 
   long barID;
@@ -63,7 +70,15 @@ public class HMMAlignThread implements Runnable
 
   SequenceI[][] allResults;
 
-  public HMMAlignThread(AlignFrame af, boolean createNewFrame)
+  /**
+   * Constructor for the HMMAlignThread. If create new frame is set to true, a
+   * new frame will be created.
+   * 
+   * @param af
+   * @param createNewFrame
+   */
+  public HMMAlignThread(AlignFrame af, boolean createNewFrame,
+          List<ArgumentI> args)
   {
     this.af = af;
     alignment = af.getViewport().getAlignment();
@@ -71,63 +86,74 @@ public class HMMAlignThread implements Runnable
     {
       dataset = alignment.getDataset();
     }
-    hmm = alignment.getSequenceAt(0).getHMM();
     newFrame = createNewFrame;
     featureSettings = af.getFeatureRenderer().getSettings();
+    this.args = args;
   }
 
+  /**
+   * Runs the HMMAlignThread: the data on the alignment or group is exported,
+   * then the command is executed in the command line and then the data is
+   * imported and displayed in a new frame (if true). The command is executed
+   * for each segemtn of the alignment.
+   */
   @Override
   public void run()
   {
+
+    hmm = af.getSelectedHMM();
+
     barID = System.currentTimeMillis();
-    af.setProgressBar(MessageManager.getString("status.running_hmmbuild"),
+    af.setProgressBar(MessageManager.getString("status.running_hmmalign"),
             barID);
     cmds.HMMERFOLDER = Cache.getProperty(Preferences.HMMER_PATH);
-
-    // if (!alignment.isAligned())
-    // {
-    // alignment.padGaps();
-    // }
-    prepareAlignment();
-    SequenceI[][] subAlignments = msa.getVisibleContigs('-');
-    allOrders = new ArrayList<>();
-    allResults = new SequenceI[subAlignments.length][];
-    int job = 0;
-    for (SequenceI[] seqs : subAlignments)
-    {
-      cmds.uniquifySequences(seqs);
-      try
-      {
-        createTemporaryFiles();
-      } catch (IOException e2)
-      {
-        e2.printStackTrace();
-      }
-      try
-      {
-        cmds.exportData(seqs, outTemp.getAbsoluteFile(), hmm,
-                hmmTemp.getAbsoluteFile());
-      } catch (IOException e1)
-      {
-        e1.printStackTrace();
-      }
-      try
-      {
-        runCommand();
-      } catch (IOException | InterruptedException e)
-      {
-        e.printStackTrace();
-      }
-      try
-      {
-        importData(job);
-      } catch (IOException | InterruptedException e)
+      prepareAlignment();
+      SequenceI[][] subAlignments = msa.getVisibleContigs('-');
+      allOrders = new ArrayList<>();
+      allResults = new SequenceI[subAlignments.length][];
+      int job = 0;
+      for (SequenceI[] seqs : subAlignments)
       {
-        // TODO Auto-generated catch block
-        e.printStackTrace();
+        cmds.uniquifySequences(seqs);
+        try
+        {
+          createTemporaryFiles();
+        } catch (IOException e2)
+        {
+          e2.printStackTrace();
+        }
+        try
+        {
+          cmds.exportData(seqs, outTemp.getAbsoluteFile(), hmm,
+                  hmmTemp.getAbsoluteFile());
+        } catch (IOException e1)
+        {
+          e1.printStackTrace();
+        }
+        try
+        {
+          boolean ran = runCommand();
+          if (!ran)
+          {
+            JvOptionPane.showInternalMessageDialog(af,
+                    MessageManager.getString("warn.hmmalign_failed"));
+            return;
+          }
+        } catch (IOException | InterruptedException e)
+        {
+          e.printStackTrace();
+        }
+        try
+        {
+          importData(job);
+        } catch (IOException | InterruptedException e)
+        {
+          // TODO Auto-generated catch block
+          e.printStackTrace();
+        }
+        job++;
       }
-      job++;
-    }
+
 
     displayResults(newFrame);
 
@@ -136,29 +162,80 @@ public class HMMAlignThread implements Runnable
 
   }
 
+  /**
+   * Creates temporary files for exporting and importing the data.
+   * 
+   * @throws IOException
+   */
   private void createTemporaryFiles() throws IOException
   {
-    hmmTemp = File.createTempFile("hmm", ".hmm");
-    hmmTemp.deleteOnExit();
-    outTemp = File.createTempFile("output", ".sto");
-    outTemp.deleteOnExit();
+    if (hmmTemp == null)
+    {
+      hmmTemp = File.createTempFile("hmm", ".hmm");
+      hmmTemp.deleteOnExit();
+    }
+    if (outTemp == null)
+    {
+      outTemp = File.createTempFile("output", ".sto");
+      outTemp.deleteOnExit();
+    }
     inputTemp = File.createTempFile("input", ".sto");
     inputTemp.deleteOnExit();
   }
 
-  private void runCommand() throws IOException, InterruptedException
+  /**
+   * Executes the hmmalign command in the command line.
+   * 
+   * @return
+   * @throws IOException
+   * @throws InterruptedException
+   */
+  private boolean runCommand() throws IOException, InterruptedException
   {
+    File file = new File(cmds.HMMERFOLDER + "/hmmalign");
+    if (!file.canExecute())
+    {
+      file = new File(cmds.HMMERFOLDER + "/hmmalign.exe");
+      {
+        if (!file.canExecute())
+        {
+          return false;
+        }
+      }
+    }
     String command = cmds.HMMERFOLDER + cmds.HMMALIGN;
-    if (!hmm.getFileHeader().contains("HMMER3/f"))
+    String version = Cache.getProperty("HMMER_VERSION");
+    if (!"3.1b2".equals(version))
     {
       command += cmds.ALLCOL;
     }
-    command += cmds.TRIM + " -o" + inputTemp.getAbsolutePath() + cmds.SPACE
+    if (args != null)
+    {
+      for (ArgumentI arg : args)
+      {
+        String name = arg.getName();
+        switch (name)
+        {
+        case "Trim Non-Matching Termini":
+          command += "--trim";
+        }
+      }
+    }
+    command += " -o " + inputTemp.getAbsolutePath() + cmds.SPACE
             + hmmTemp.getAbsolutePath() + cmds.SPACE
             + outTemp.getAbsolutePath();
-    cmds.runCommand(command);
+    return cmds.runCommand(command);
   }
 
+  /**
+   * Imports the data from the temporary file to which the output of hmmalign is
+   * directed. this is used for an internal job.
+   * 
+   * @param index
+   *          The index of the 'job' (or region of an alignment).
+   * @throws IOException
+   * @throws InterruptedException
+   */
   private void importData(int index)
           throws IOException, InterruptedException
   {
@@ -166,68 +243,29 @@ public class HMMAlignThread implements Runnable
             DataSourceType.FILE);
     SequenceI[] result = file.getSeqsAsArray();
     AlignmentOrder msaorder = new AlignmentOrder(result);
-    // always recover the order - makes parseResult()'s life easier.
     jalview.analysis.AlignmentSorter.recoverOrder(result);
     jalview.analysis.SeqsetUtils.deuniquify(cmds.hash, result);
     allOrders.add(msaorder);
     allResults[index] = result;
-
-    /*
-    if (newFrame)
-    {
-      FileLoader loader = new FileLoader();
-      AlignFrame aFrame = new AlignFrame(new Alignment(new SequenceI[1]),
-              AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
-      Desktop.addInternalFrame(aFrame, aFrame.getTitle(),
-              AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
-      aFrame.setTitle(
-              af.getName() + "Aligned to " + hmm.getName() + "'s HMM");
-      af.getViewport().setAlignment(null);
-    
-      aFrame.loadJalviewDataFile(inputTemp.getAbsolutePath(),
-              DataSourceType.FILE, FileFormat.Stockholm, null);
-    
-    
-    
-      Map<Integer, SequenceI> copy = new HashMap<>(
-              hmmSeqs);
-      addSeqs(aFrame, copy);
-      SequenceI seq = aFrame.getViewport().getAlignment()
-              .getSequenceAt(0);
-      seq.getHMM().mapToReferenceAnnotation(aFrame, seq);
-      addSeqs(af, hmmSeqs);
-    }
-    else
-    {
-      af.getViewport().getAlignment().getSequences().clear();
-      af.setIsRecurring(true);
-      af.loadJalviewDataFile(inputTemp.getAbsolutePath(),
-              DataSourceType.FILE, FileFormat.Stockholm, null);
-      af.setIsRecurring(false);
-      addSeqs(af, hmmSeqs);
-    }
-    */
     hmmTemp.delete();
     outTemp.delete();
     inputTemp.delete();
   }
 
-  private void addSeqs(AlignFrame alignFrame, Map<Integer, SequenceI> map)
-  {
-    for (Map.Entry<Integer, SequenceI> entry : map.entrySet())
-    {
-      SequenceI seq = entry.getValue();
-      Integer pos = entry.getKey();
-      cmds.addHMMConsensusSequence(alignFrame, seq, pos);
-    }
-  }
-
+  /**
+   * Gathers the sequences in preparation for the alignment.
+   */
   private void prepareAlignment()
   {
     // hmmSeqs = alignment.getHMMConsensusSequences(true);
     msa = af.gatherSequencesForAlignment();
   }
 
+  /**
+   * Displays the results of all 'jobs'.
+   * 
+   * @param newFrame
+   */
   private void displayResults(boolean newFrame)
   {
     AlignmentOrder[] arrOrders = allOrders
@@ -249,6 +287,17 @@ public class HMMAlignThread implements Runnable
     }
   }
 
+  /**
+   * Displays the results in a new frame.
+   * 
+   * @param al
+   *          The alignment containing the results.
+   * @param alorders
+   *          The order of the sequences in the alignment on which the jobs were
+   *          run.
+   * @param hidden
+   *          Hidden columns in the previous alignment.
+   */
   private void displayInNewFrame(AlignmentI al,
           List<AlignmentOrder> alorders, HiddenColumns hidden)
   {
@@ -362,6 +411,25 @@ public class HMMAlignThread implements Runnable
     }
   }
 
+  /**
+   * Runs hmmalign, and waits for the results to be imported before continuing
+   */
+  public void hmmalignWaitTillComplete()
+  {
+    Thread loader = new Thread(this);
+    loader.start();
+
+    while (loader.isAlive())
+    {
+      try
+      {
+        Thread.sleep(500);
+      } catch (Exception ex)
+      {
+      }
+    }
+
+  }
   }