Merge branch 'alpha/JAL-3362_Jalview_212_alpha' into alpha/merge_212_JalviewJS_2112
[jalview.git] / src / jalview / io / HMMFile.java
index 764db7f..2fce4cc 100644 (file)
 package jalview.io;
 
-import jalview.datamodel.EValueStatistic;
+import jalview.api.AlignExportSettingsI;
+import jalview.api.AlignmentViewPanel;
+import jalview.datamodel.HMMNode;
 import jalview.datamodel.HiddenMarkovModel;
+import jalview.datamodel.SequenceI;
 
 import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 import java.util.Scanner;
 
+
 /**
- * reads in and writes out a HMMER standard file
+ * Adds capability to read in and write out HMMER3 files. .
  * 
  * 
  * @author TZVanaalten
  *
  */
-public class HMMFile extends FileParse
+public class HMMFile extends AlignFile
+        implements AlignmentFileReaderI, AlignmentFileWriterI
 {
-  // HMM to store file data
-  HiddenMarkovModel hmm = new HiddenMarkovModel();
+  private static final String TERMINATOR = "//";
+
+  /*
+   * keys to data in HMM file, used to store as properties of the HiddenMarkovModel
+   */
+  public static final String HMM = "HMM";
+
+  public static final String NAME = "NAME";
+
+  public static final String ACCESSION_NUMBER = "ACC";
+
+  public static final String DESCRIPTION = "DESC";
+
+  public static final String LENGTH = "LENG";
+
+  public static final String MAX_LENGTH = "MAXL";
+
+  public static final String ALPHABET = "ALPH";
+
+  public static final String DATE = "DATE";
+
+  public static final String COMMAND_LOG = "COM";
+
+  public static final String NUMBER_OF_SEQUENCES = "NSEQ";
+
+  public static final String EFF_NUMBER_OF_SEQUENCES = "EFFN";
+
+  public static final String CHECK_SUM = "CKSUM";
+
+  public static final String STATISTICS = "STATS";
+
+  public static final String COMPO = "COMPO";
+
+  public static final String GATHERING_THRESHOLD = "GA";
+
+  public static final String TRUSTED_CUTOFF = "TC";
+
+  public static final String NOISE_CUTOFF = "NC";
+
+  public static final String VITERBI = "VITERBI";
+
+  public static final String MSV = "MSV";
+
+  public static final String FORWARD = "FORWARD";
+
+  public static final String MAP = "MAP";
+
+  public static final String REFERENCE_ANNOTATION = "RF";
+
+  public static final String CONSENSUS_RESIDUE = "CONS";
+
+  public static final String CONSENSUS_STRUCTURE = "CS";
+
+  public static final String MASKED_VALUE = "MM";
 
-  // Source of file
-  String dataObject;
+  private static final String ALPH_AMINO = "amino";
 
-  // number of symbols
-  int numberOfSymbols;
+  private static final String ALPH_DNA = "DNA";
 
-  // number of possible transitions
-  final int NUMBER_OF_TRANSITIONS = 7;
+  private static final String ALPH_RNA = "RNA";
 
-  // file header
-  String fileHeader;
+  private static final String ALPHABET_AMINO = "ACDEFGHIKLMNPQRSTVWY";
+
+  private static final String ALPHABET_DNA = "ACGT";
+
+  private static final String ALPHABET_RNA = "ACGU";
+
+  private static final int NUMBER_OF_TRANSITIONS = 7;
+
+  private static final String SPACE = " ";
+
+  /*
+   * optional guide line added to an output HMMER file, purely for readability
+   */
+  private static final String TRANSITIONTYPELINE = "            m->m     m->i     m->d     i->m     i->i     d->m     d->d";
+
+  private static String NL = System.lineSeparator();
+
+  private HiddenMarkovModel hmm;
+
+  // number of symbols in the alphabet used in the hidden Markov model
+  private int numberOfSymbols;
 
   /**
-   * Constructor which contains model to be filled or exported
+   * Constructor that parses immediately
    * 
-   * @param dataSource
-   *          Filename, URL or Pasted String to read from
+   * @param inFile
+   * @param type
+   * @throws IOException
    */
-  public HMMFile(String dataSource)
+  public HMMFile(String inFile, DataSourceType type) throws IOException
   {
-    dataObject = dataSource;
+    super(inFile, type);
   }
 
   /**
-   * reads data from HMM file
+   * Constructor that parses immediately
    * 
+   * @param source
    * @throws IOException
    */
-  public void parse() throws IOException
+  public HMMFile(FileParse source) throws IOException
+  {
+    super(source);
+  }
+
+  /**
+   * Default constructor
+   */
+  public HMMFile()
   {
-    File file = new File(dataObject);
-    FileReader fr = new FileReader(file);
-    BufferedReader br = new BufferedReader(fr);
-    parseFileProperties(br);
-    parseModel(br);
+  }
 
+  /**
+   * Constructor for HMMFile used for exporting
+   * 
+   * @param hmm
+   */
+  public HMMFile(HiddenMarkovModel markov)
+  {
+    hmm = markov;
+  }
+
+  /**
+   * Returns the HMM produced by parsing a HMMER3 file
+   * 
+   * @return
+   */
+  public HiddenMarkovModel getHMM()
+  {
+    return hmm;
   }
 
   /**
-   * imports file properties from hmm file
+   * Gets the name of the hidden Markov model
+   * 
+   * @return
+   */
+  public String getName()
+  {
+    return hmm.getName();
+  }
+
+  /**
+   * Reads the data from HMM file into the HMM model
+   */
+  @Override
+  public void parse()
+  {
+    try
+    {
+      hmm = new HiddenMarkovModel();
+      parseHeaderLines(dataIn);
+      parseModel(dataIn);
+    } catch (Exception e)
+    {
+      e.printStackTrace();
+    }
+  }
+
+  /**
+   * Reads the header properties from a HMMER3 file and saves them in the
+   * HiddeMarkovModel. This method exits after reading the next line after the
+   * HMM line.
    * 
    * @param input
-   *          buffered reader used to read in file
    * @throws IOException
    */
-  public void parseFileProperties(BufferedReader input) throws IOException
+  void parseHeaderLines(BufferedReader input) throws IOException
   {
-    boolean readingFile = true;
-    fileHeader = input.readLine();
+    boolean readingHeaders = true;
+    hmm.setFileHeader(input.readLine());
     String line = input.readLine();
-    while (readingFile)
+    while (readingHeaders && line != null)
     {
-      if (line != null)
+      Scanner parser = new Scanner(line);
+      String next = parser.next();
+      if (ALPHABET.equals(next))
       {
-        Scanner parser = new Scanner(line);
-        String next = parser.next();
-        if ("HMM".equals(next)) // indicates start of HMM data (end of file
-                              // properties)
-        {
-          readingFile = false;
-          hmm.fillSymbols(line);
-          numberOfSymbols = hmm.getSymbols().size();
-        }
-        else if ("STATS".equals(next)) // reads e-value stats into separate
-                                       // field
-                                     // on HMM object
-        {
-          readStats(parser);
-        }
-        else if ("GA".equals(next) || "TC".equals(next)
-                || "NC".equals(next)) // reads
-                                                                            // pfam
-                                                                            // data
-                                                                            // into
-                                                                            // separate
-                                                                            // field
-                                                                            // on
-                                                                            // HMM
-                                                                            // object
-        {
-          Double[] data = new Double[2];
-          data[0] = parser.nextDouble();
-          data[1] = parser.nextDouble();
-          hmm.setPFAMData(next, data);
-        }
-        else
+        String alphabetType = parser.next();
+        hmm.setProperty(ALPHABET, alphabetType);
+        String alphabet = ALPH_DNA.equalsIgnoreCase(alphabetType)
+                ? ALPHABET_DNA
+                : (ALPH_RNA.equalsIgnoreCase(alphabetType) ? ALPHABET_RNA
+                        : ALPHABET_AMINO);
+        numberOfSymbols = hmm.setAlphabet(alphabet);
+      }
+      else if (HMM.equals(next))
+      {
+        readingHeaders = false;
+        String symbols = line.substring(line.indexOf(HMM) + HMM.length());
+        numberOfSymbols = hmm.setAlphabet(symbols);
+      }
+      else if (STATISTICS.equals(next))
+      {
+        parser.next();
+        String key;
+        String value;
+        key = parser.next();
+        value = parser.next() + SPACE + SPACE + parser.next();
+        hmm.setProperty(key, value);
+      }
+      else
+      {
+        String key = next;
+        String value = parser.next();
+        while (parser.hasNext())
         {
-          String key = next;
-          String value = parser.next();
-          while (parser.hasNext())
-          {
-            value = value + " " + parser.next();
-          }
-          hmm.put(key, value);
+          value = value + SPACE + parser.next();
         }
-        parser.close();
+        hmm.setProperty(key, value);
       }
+      parser.close();
       line = input.readLine();
-      if (line == null)
-      {
-        readingFile = false;
-      }
     }
-
   }
 
   /**
-   * creates a new EValueStatistic object to store stats
-   * 
-   * @param parser
-   *          Scanner which contains data for STATS line
+   * Parses the model data from the HMMER3 file. The input buffer should be
+   * positioned at the (optional) COMPO line if there is one, else at the insert
+   * emissions line for the BEGIN node of the model.
    * 
+   * @param input
+   * @throws IOException
    */
-  public void readStats(Scanner parser)
+  void parseModel(BufferedReader input) throws IOException
   {
-    if (parser.hasNext())
+    /*
+     * specification says there must always be an HMM header (already read)
+     * and one more header (guide headings) which is skipped here
+     */
+    int nodeNo = 0;
+    String line = input.readLine();
+    List<HMMNode> nodes = new ArrayList<>();
+
+    while (line != null && !TERMINATOR.equals(line))
     {
-    String name;
-    double slope;
-    double location;
-    String configuration;
-
-    configuration = parser.next();
-    name = parser.next();
-    slope = parser.nextDouble();
-    location = parser.nextDouble();
-    hmm.addStatistic(name,
-            new EValueStatistic(configuration, slope, location));
+      HMMNode node = new HMMNode();
+      nodes.add(node);
+      Scanner scanner = new Scanner(line);
+      String next = scanner.next();
+
+      /*
+       * expect COMPO (optional) for average match emissions
+       * or a node number followed by node's match emissions
+       */
+      if (COMPO.equals(next) || nodeNo > 0)
+      {
+        /*
+         * parse match emissions
+         */
+        double[] matches = parseDoubles(scanner, numberOfSymbols);
+        node.setMatchEmissions(matches);
+        if (!COMPO.equals(next))
+        {
+          int resNo = parseAnnotations(scanner, node);
+          if (resNo == 0)
+          {
+            /*
+             * no MAP annotation provided, just number off from 0 (begin node)
+             */
+            resNo = nodeNo;
+          }
+          node.setResidueNumber(resNo);
+        }
+        line = input.readLine();
+      }
+      scanner.close();
+
+      /*
+       * parse insert emissions
+       */
+      scanner = new Scanner(line);
+      double[] inserts = parseDoubles(scanner, numberOfSymbols);
+      node.setInsertEmissions(inserts);
+      scanner.close();
+
+      /*
+       * parse state transitions
+       */
+      line = input.readLine();
+      scanner = new Scanner(line);
+      double[] transitions = parseDoubles(scanner,
+              NUMBER_OF_TRANSITIONS);
+      node.setStateTransitions(transitions);
+      scanner.close();
+      line = input.readLine();
+
+      nodeNo++;
     }
+
+    hmm.setNodes(nodes);
   }
 
   /**
-   * parses the model data from the hmm file
+   * Parses the annotations on the match emission line and add them to the node.
+   * (See p109 of the HMMER User Guide (V3.1b2) for the specification.) Returns
+   * the residue position that the node maps to, if provided, else zero.
    * 
-   * @param input
-   *          buffered reader used to read file
-   * @throws IOException
+   * @param scanner
+   * @param node
    */
-  public void parseModel(BufferedReader input) throws IOException
+  int parseAnnotations(Scanner scanner, HMMNode node)
   {
+    int mapTo = 0;
 
-    String line = input.readLine();
-    Scanner scanner = new Scanner(line);
-    String next = scanner.next();
-    if ("COMPO".equals(next)) // checks to and stores COMPO data if present
+    /*
+     * map from hmm node to sequence position, if provided
+     */
+    if (scanner.hasNext())
     {
-      for (int i = 0; i < numberOfSymbols; i++)
-
+      String value = scanner.next();
+      if (!"-".equals(value))
       {
-        hmm.getAverageMatchStateEmissionProbabilities()
-                .add(scanner.nextDouble());
+        try
+        {
+          mapTo = Integer.parseInt(value);
+          node.setResidueNumber(mapTo);
+        } catch (NumberFormatException e)
+        {
+          // ignore
+        }
       }
     }
-    scanner.close();
-    parseBeginNodeData(input);
-    for (int i = 0; i < hmm.getLength(); i++)
+
+    /*
+     * hmm consensus residue if provided, else '-'
+     */
+    if (scanner.hasNext())
+    {
+      node.setConsensusResidue(scanner.next().charAt(0));
+    }
+
+    /*
+     * RF reference annotation, if provided, else '-'
+     */
+    if (scanner.hasNext())
     {
-      Scanner matchReader = new Scanner(input.readLine());
-      matchReader.nextInt(); // skips number indicating position in HMM
-      hmm.getMatchEmissions()
-              .add(fillList(matchReader, numberOfSymbols));
-      parseAnnotations(matchReader, i);
-      matchReader.close();
-      Scanner insertReader = new Scanner(input.readLine());
-      hmm.getInsertEmissions().add(fillList(insertReader, numberOfSymbols));
-      insertReader.close();
-      Scanner transitionReader = new Scanner(input.readLine());
-      hmm.getStateTransitions()
-              .add(fillList(transitionReader, NUMBER_OF_TRANSITIONS));
-      transitionReader.close();
+      node.setReferenceAnnotation(scanner.next().charAt(0));
     }
 
+    /*
+     * 'm' for masked position, if provided, else '-'
+     */
+    if (scanner.hasNext())
+    {
+      node.setMaskValue(scanner.next().charAt(0));
+    }
+
+    /*
+     * structure consensus symbol, if provided, else '-'
+     */
+    if (scanner.hasNext())
+    {
+      node.setConsensusStructure(scanner.next().charAt(0));
+    }
+
+    return mapTo;
   }
 
   /**
-   * parses the begin state transitions and insert 0 emissions
+   * Fills an array of doubles parsed from an input line
    * 
    * @param input
-   *          buffered reader used to read model
-   * @param currentline
-   *          string contain all data on current line of buffered reader
+   * @param numberOfElements
+   * @return
    * @throws IOException
    */
-
-  public void parseBeginNodeData(BufferedReader input)
-          throws IOException
+  static double[] parseDoubles(Scanner input,
+          int numberOfElements) throws IOException
   {
-    Scanner scanner = new Scanner(input.readLine());
-    hmm.setInsertZeroEmissions(fillList(scanner, hmm.getSymbols().size()));
-    scanner.close();
-    Scanner scannerTransitions = new Scanner(input.readLine());
-    hmm.setBeginStateTransitions(
-            fillList(scannerTransitions, NUMBER_OF_TRANSITIONS));
-    scannerTransitions.close();
+    double[] values = new double[numberOfElements];
+    for (int i = 0; i < numberOfElements; i++)
+    {
+      if (!input.hasNext())
+      {
+        throw new IOException("Incomplete data");
+      }
+      String next = input.next();
+      if (next.contains("*"))
+      {
+        values[i] = Double.NEGATIVE_INFINITY;
+      }
+      else
+      {
+        double prob = Double.valueOf(next);
+        prob = Math.pow(Math.E, -prob);
+        values[i] = prob;
+      }
+    }
+    return values;
   }
 
   /**
-   * parses annotations on match emission line
+   * Returns a string to be added to the StringBuilder containing the entire
+   * output String.
    * 
-   * @param scanner
-   *          scanner which is processing match emission line
-   * @param index
-   *          index of node which is beign scanned
+   * @param initialColumnSeparation
+   *          The initial whitespace separation between the left side of the
+   *          file and first character.
+   * @param columnSeparation
+   *          The separation between subsequent data entries.
+   * @param data
+   *          The list of data to be added to the String.
+   * @return
    */
-  public void parseAnnotations(Scanner scanner, int index)
+  String addData(int initialColumnSeparation,
+          int columnSeparation, List<String> data)
   {
-    if (hmm.getMapAnnotationFlag())
-    {
-      hmm.getAlignmentColumnIndexes().add(scanner.nextInt());
-    }
-    else
+    String line = "";
+    boolean first = true;
+    for (String value : data)
     {
-      scanner.next();
+      int sep = first ? initialColumnSeparation : columnSeparation;
+      line += String.format("%" + sep + "s", value);
+      first = false;
     }
-    hmm.getAnnotations().add(new HashMap<String, Character>());
-    hmm.getAnnotations().get(index).put("CONS", scanner.next().charAt(0));
-    hmm.getAnnotations().get(index).put("RF", scanner.next().charAt(0));
-    hmm.getAnnotations().get(index).put("MM", scanner.next().charAt(0));
-    hmm.getAnnotations().get(index).put("CS", scanner.next().charAt(0));
+    return line;
   }
+
   /**
+   * Converts list of characters into a list of Strings.
    * 
-   * @param transition
-   *          type of transition occuring
-   * @return index value representing position along stateTransition array.
+   * @param list
+   * @return Returns the list of Strings.
    */
-  public Integer getTransitionType(String transition)
+  List<String> charListToStringList(List<Character> list)
   {
-    Integer index;
-    switch (transition)
+    List<String> strList = new ArrayList<>();
+    for (char value : list)
     {
-    case "mm":
-      index = 0;
-      break;
-    case "mi":
-      index = 1;
-      break;
-    case "md":
-      index = 2;
-      break;
-    case "im":
-      index = 3;
-      break;
-    case "ii":
-      index = 4;
-      break;
-    case "dm":
-      index = 5;
-      break;
-    case "dd":
-      index = 6;
-      break;
-    default:
-      index = null;
+      String strValue = Character.toString(value);
+      strList.add(strValue);
     }
-    return index;
+    return strList;
   }
 
   /**
+   * Converts an array of doubles into a list of Strings, rounded to the nearest
+   * 5th decimal place
    * 
-   * @param input
-   *          scanner for line containing data to be transferred to list
-   * @param numberOfElements
-   *          number of elements in the list to be filled
-   * @return filled list
+   * @param doubles
+   * @param noOfDecimals
+   * @return
    */
-  public static List<Double> fillList(Scanner input,
-          int numberOfElements)
+  List<String> doublesToStringList(double[] doubles)
   {
-    List<Double> list = new ArrayList<>();
-    String next;
-    for (int i = 0; i < numberOfElements; i++)
+    List<String> strList = new ArrayList<>();
+    for (double value : doubles)
     {
-      next = input.next();
-      if (next.contains("*")) // state transitions to or from delete states
-                              // occasionally have values of -infinity. These
-                              // values are represented by an * in the .hmm
-                              // file, and by a null value in the
-                              // HiddenMarkovModel class
+      String strValue;
+      if (value > 0)
+      {
+        strValue = String.format("%.5f", value);
+      }
+      else if (value == -0.00000d)
       {
-        list.add(null);
+        strValue = "0.00000";
       }
       else
       {
-        list.add(Double.valueOf(next));
+        strValue = "*";
       }
+      strList.add(strValue);
     }
-    return list;
+    return strList;
   }
 
   /**
-   * writes a HiddenMarkovModel to a file. Needs mode work to make file more
-   * readable for humans (align columns)
+   * Appends model data in string format to the string builder
    * 
-   * @param exportLocation
-   *          Filename, URL or Pasted String to write to
-   * @throws FileNotFoundException
-   * @throws UnsupportedEncodingException
+   * @param output
    */
-  public void exportFile(String exportLocation)
-          throws FileNotFoundException, UnsupportedEncodingException
+  void appendModelAsString(StringBuilder output)
   {
-    PrintWriter writer = new PrintWriter(exportLocation, "UTF-8");
-    writer.println(fileHeader);
-    for (Map.Entry<String, String> entry : hmm.getFileProperties()
-            .entrySet())
+    output.append(HMM).append("  ");
+    String charSymbols = hmm.getSymbols();
+    for (char c : charSymbols.toCharArray())
     {
-      writer.println(entry.getKey() + " " + entry.getValue());
+      output.append(String.format("%9s", c));
     }
-    writer.println(
-            "HMM" + " " + convertCharListToString(hmm.getSymbols()));
-    writer.println("m->m m->i m->d i->m i->i d->m d->d");
-    if (false == hmm.getAverageMatchStateEmissionProbabilities().isEmpty())
+    output.append(NL).append(TRANSITIONTYPELINE);
+
+    int length = hmm.getLength();
+
+    for (int nodeNo = 0; nodeNo <= length; nodeNo++)
     {
-      writer.println("COMPO" + " " + convertDoubleListToString(
-              hmm.getAverageMatchStateEmissionProbabilities()));
+      String matchLine = String.format("%7s",
+              nodeNo == 0 ? COMPO : Integer.toString(nodeNo));
+
+      double[] doubleMatches = convertToLogSpace(
+              hmm.getNode(nodeNo).getMatchEmissions());
+      List<String> strMatches = doublesToStringList(doubleMatches);
+      matchLine += addData(10, 9, strMatches);
+
+      if (nodeNo != 0)
+      {
+        matchLine += SPACE + (hmm.getNodeMapPosition(nodeNo));
+        matchLine += SPACE + hmm.getConsensusResidue(nodeNo);
+        matchLine += SPACE + hmm.getReferenceAnnotation(nodeNo);
+        if (hmm.getFileHeader().contains("HMMER3/f"))
+        {
+          matchLine += SPACE + hmm.getMaskedValue(nodeNo);
+          matchLine += SPACE + hmm.getConsensusStructure(nodeNo);
+        }
+      }
+
+      output.append(NL).append(matchLine);
+      
+      String insertLine = "";
+
+      double[] doubleInserts = convertToLogSpace(
+              hmm.getNode(nodeNo).getInsertEmissions());
+      List<String> strInserts = doublesToStringList(doubleInserts);
+      insertLine += addData(17, 9, strInserts);
+
+      output.append(NL).append(insertLine);
+
+      String transitionLine = "";
+      double[] doubleTransitions = convertToLogSpace(
+              hmm.getNode(nodeNo).getStateTransitions());
+      List<String> strTransitions = doublesToStringList(
+              doubleTransitions);
+      transitionLine += addData(17, 9, strTransitions);
+
+      output.append(NL).append(transitionLine);
     }
-    writer.println(convertDoubleListToString(hmm.getInsertZeroEmissions()));
-    writer.println(
-            convertDoubleListToString(hmm.getBeginStateTransitions()));
+  }
 
-    for (Integer i = 0; i < hmm.getLength(); i++)
+  /**
+   * Appends formatted HMM file properties to the string builder
+   * 
+   * @param output
+   */
+  void appendProperties(StringBuilder output)
+  {
+    output.append(hmm.getFileHeader());
+
+    String format = "%n%-5s %1s";
+    appendProperty(output, format, NAME);
+    appendProperty(output, format, ACCESSION_NUMBER);
+    appendProperty(output, format, DESCRIPTION);
+    appendProperty(output, format, LENGTH);
+    appendProperty(output, format, MAX_LENGTH);
+    appendProperty(output, format, ALPHABET);
+    appendBooleanProperty(output, format, REFERENCE_ANNOTATION);
+    appendBooleanProperty(output, format, MASKED_VALUE);
+    appendBooleanProperty(output, format, CONSENSUS_RESIDUE);
+    appendBooleanProperty(output, format, CONSENSUS_STRUCTURE);
+    appendBooleanProperty(output, format, MAP);
+    appendProperty(output, format, DATE);
+    appendProperty(output, format, NUMBER_OF_SEQUENCES);
+    appendProperty(output, format, EFF_NUMBER_OF_SEQUENCES);
+    appendProperty(output, format, CHECK_SUM);
+    appendProperty(output, format, GATHERING_THRESHOLD);
+    appendProperty(output, format, TRUSTED_CUTOFF);
+    appendProperty(output, format, NOISE_CUTOFF);
+
+    if (hmm.getMSV() != null)
     {
-      String matchEmissionLine = i.toString() + " "; // adds node index
-      matchEmissionLine += convertDoubleListToString(
-              hmm.getMatchEmissions().get(i)); // adds match emissions
-      matchEmissionLine += " "
-              + hmm.getAlignmentColumnIndexes().get(i).toString(); // adds MAP
-                                                                   // annotation
-      matchEmissionLine += " "
-              + hmm.getAnnotations().get(i).get("CONS").toString(); // adds CONS
-                                                                    // annotation
-      matchEmissionLine += " "
-              + hmm.getAnnotations().get(i).get("RF").toString(); // adds RF
-                                                                  // annotation
-      matchEmissionLine += " "
-              + hmm.getAnnotations().get(i).get("MM").toString(); // adds MM
-                                                                  // annotation
-      matchEmissionLine += " "
-              + hmm.getAnnotations().get(i).get("CS").toString(); // adds CS
-                                                                  // annotation
-      writer.println(matchEmissionLine);
-
-      writer.println(
-              convertDoubleListToString(hmm.getInsertEmissions().get(i)));
-      writer.println(
-              convertDoubleListToString(hmm.getStateTransitions().get(i)));
+      format = "%n%-19s %18s";
+      output.append(String.format(format, "STATS LOCAL MSV", hmm.getMSV()));
+
+      output.append(String.format(format, "STATS LOCAL VITERBI",
+              hmm.getViterbi()));
+
+      output.append(String.format(format, "STATS LOCAL FORWARD",
+              hmm.getForward()));
     }
-    writer.println("//");
+  }
 
-    writer.close();
+  /**
+   * Appends 'yes' or 'no' for the given property, according to whether or not
+   * it is set in the HMM
+   * 
+   * @param output
+   * @param format
+   * @param propertyName
+   */
+  private void appendBooleanProperty(StringBuilder output, String format,
+          String propertyName)
+  {
+    boolean set = hmm.getBooleanProperty(propertyName);
+    output.append(String.format(format, propertyName,
+            set ? HiddenMarkovModel.YES : HiddenMarkovModel.NO));
   }
 
   /**
-   * converts an list of characters to a string with items separated by spaces
+   * Appends the value of the given property to the output, if not null
    * 
-   * @param list
-   *          character list to be converted
-   * @return string value of char list
+   * @param output
+   * @param format
+   * @param propertyName
    */
-  public String convertCharListToString(List<Character> list)
+  private void appendProperty(StringBuilder output, String format,
+          String propertyName)
   {
-    String string = "";
-    for (Character item : list)
+    String value = hmm.getProperty(propertyName);
+    if (value != null)
     {
-      string = string + item.toString() + " ";
+      output.append(String.format(format, propertyName, value));
     }
+  }
 
-    return string;
+  @Override
+  public String print(SequenceI[] sequences, boolean jvsuffix)
+  {
+    if (sequences[0].getHMM() != null)
+    {
+      hmm = sequences[0].getHMM();
+    }
+    return print();
   }
-  
+
   /**
-   * converts an list of doubles to a string with items separated by spaces
+   * Prints the .hmm file to a String.
    * 
-   * @param list
-   *          double list to be converted
-   * @return string value of double list
+   * @return
    */
-  public String convertDoubleListToString(List<Double> list)
+  public String print()
   {
-    String string = "";
-    for (Double item : list)
+    StringBuilder output = new StringBuilder();
+    appendProperties(output);
+    output.append(NL);
+    appendModelAsString(output);
+    output.append(NL).append(TERMINATOR).append(NL);
+    return output.toString();
+  }
+
+  /**
+   * Converts the probabilities contained in an array into log space
+   * 
+   * @param ds
+   */
+  double[] convertToLogSpace(double[] ds)
+  {
+    double[] converted = new double[ds.length];
+    for (int i = 0; i < ds.length; i++)
     {
-      if (item != null)
-      {
-        string = string + item.toString() + " ";
-      }
-      else
-      {
-        string = string + "*" + " ";
-      }
+      double prob = ds[i];
+      double logProb = -1 * Math.log(prob);
 
+      converted[i] = logProb;
     }
+    return converted;
+  }
+
+  /**
+   * Returns the HMM sequence produced by reading a .hmm file.
+   */
+  @Override
+  public SequenceI[] getSeqsAsArray()
+  {
+    SequenceI hmmSeq = hmm.getConsensusSequence();
+    SequenceI[] seq = new SequenceI[1];
+    seq[0] = hmmSeq;
+    return seq;
+  }
+
+  @Override
+  public void setNewlineString(String newLine)
+  {
+    NL = newLine;
+  }
+
+  @Override
+  public void setExportSettings(AlignExportSettingsI exportSettings)
+  {
 
-    return string;
   }
+
+  @Override
+  public void configureForView(AlignmentViewPanel viewpanel)
+  {
+
+  }
+
+  @Override
+  public boolean hasWarningMessage()
+  {
+    return false;
+  }
+
+  @Override
+  public String getWarningMessage()
+  {
+    return "warning message";
+  }
+
 }