JAL-3285 change method declaration in AAFrequency to match develop
[jalview.git] / src / jalview / analysis / AAFrequency.java
index cc4f8f4..1fef08e 100755 (executable)
@@ -50,31 +50,12 @@ import java.util.List;
  * This class is used extensively in calculating alignment colourschemes that
  * depend on the amount of conservation in each alignment column.
  * 
- * @author $author$
- * @version $Revision$
  */
 public class AAFrequency
 {
-  public static final String PROFILE = "P";
-
-  private static final String AMINO = "amino";
-
-  private static final String DNA = "DNA";
-
-  private static final String RNA = "RNA";
-
-  /*
-   * Quick look-up of String value of char 'A' to 'Z'
-   */
-  private static final String[] CHARS = new String['Z' - 'A' + 1];
+  private static final double LOG2 = Math.log(2);
 
-  static
-  {
-    for (char c = 'A'; c <= 'Z'; c++)
-    {
-      CHARS[c - 'A'] = String.valueOf(c);
-    }
-  }
+  public static final String PROFILE = "P";
 
   public static final ProfilesI calculate(List<SequenceI> list, int start,
           int end)
@@ -109,8 +90,6 @@ public class AAFrequency
     }
   }
 
-
-
   /**
    * Calculate the consensus symbol(s) for each column in the given range.
    * 
@@ -161,10 +140,9 @@ public class AAFrequency
                   "WARNING: Consensus skipping null sequence - possible race condition.");
           continue;
         }
-        char[] seq = sequences[row].getSequence();
-        if (seq.length > column)
+        if (sequences[row].getLength() > column)
         {
-          char c = seq[column];
+          char c = sequences[row].getCharAt(column);
           residueCounts.add(c);
           if (Comparison.isNucleotide(c))
           {
@@ -215,23 +193,22 @@ public class AAFrequency
    *          The alignment column on which the first profile is based.
    * @param end
    *          The alignment column on which the last profile is based.
-   * @param saveFullProfile
-   *          Flag for saving the counts for each profile
    * @param removeBelowBackground
-   *          Flag for removing any characters with a match emission probability
-   *          less than its background frequency
+   *          if true, symbols with a match emission probability less than
+   *          background frequency are ignored
    * @return
    */
   public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
-          int width, int start, int end, boolean saveFullProfile,
-          boolean removeBelowBackground, boolean infoLetterHeight)
+          int width, int start, int end, boolean removeBelowBackground,
+          boolean infoLetterHeight)
   {
     ProfileI[] result = new ProfileI[width];
-    int symbolCount = hmm.getNumberOfSymbols();
+    char[] symbols = hmm.getSymbols().toCharArray();
+    int symbolCount = symbols.length;
     for (int column = start; column < end; column++)
     {
       ResidueCount counts = new ResidueCount();
-      for (char symbol : hmm.getSymbols())
+      for (char symbol : symbols)
       {
         int value = getAnalogueCount(hmm, column, symbol,
                 removeBelowBackground, infoLetterHeight);
@@ -242,11 +219,7 @@ public class AAFrequency
       int gapCount = counts.getGapCount();
       ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
               maxResidue);
-
-      if (saveFullProfile)
-      {
-        profile.setCounts(counts);
-      }
+      profile.setCounts(counts);
 
       result[column] = profile;
     }
@@ -365,20 +338,16 @@ public class AAFrequency
    * @param endCol
    *          end column (exclusive)
    * @param ignoreGaps
-   *          if true, normalise residue percentages 
+   *          if true, normalise residue percentages
    * @param showSequenceLogo
    *          if true include all information symbols, else just show modal
    *          residue
-   * @param nseq
-   *          number of sequences
    */
   public static float completeInformation(AlignmentAnnotation information,
-          ProfilesI profiles, int startCol, int endCol, long nseq,
-          Float currentMax)
+          ProfilesI profiles, int startCol, int endCol)
   {
     // long now = System.currentTimeMillis();
-    if (information == null || information.annotations == null
-            || information.annotations.length < endCol)
+    if (information == null || information.annotations == null)
     {
       /*
        * called with a bad alignment annotation row 
@@ -387,56 +356,48 @@ public class AAFrequency
       return 0;
     }
 
-    Float max = 0f;
+    float max = 0f;
+    SequenceI hmmSeq = information.sequenceRef;
 
-    for (int i = startCol; i < endCol; i++)
+    int seqLength = hmmSeq.getLength();
+    if (information.annotations.length < seqLength)
     {
-      ProfileI profile = profiles.get(i);
-      if (profile == null)
+      return 0;
+    }
+
+    HiddenMarkovModel hmm = hmmSeq.getHMM();
+
+    for (int column = startCol; column < endCol; column++)
+    {
+      if (column >= seqLength)
       {
-        /*
-         * happens if sequences calculated over were 
-         * shorter than alignment width
-         */
-        information.annotations[i] = null;
-        return 0;
+        // hmm consensus sequence is shorter than the alignment
+        break;
       }
-
-      HiddenMarkovModel hmm;
-      
-      SequenceI hmmSeq = information.sequenceRef;
-      
-      hmm = hmmSeq.getHMM();
       
-      Float value = getInformationContent(i, hmm);
-
-      if (value > max)
+      float value = hmm.getInformationContent(column);
+      boolean isNaN = Float.isNaN(value);
+      if (!isNaN)
       {
-        max = value;
+        max = Math.max(max, value);
       }
 
-      String description = value + " bits";
-      information.annotations[i] = new Annotation(
-              Character.toString(Character
-                      .toUpperCase(hmm.getConsensusAtAlignColumn(i))),
+      String description = isNaN ? null
+              : String.format("%.4f bits", value);
+      information.annotations[column] = new Annotation(
+              Character.toString(
+                      Character.toUpperCase(hmmSeq.getCharAt(column))),
               description, ' ', value);
     }
-    if (max > currentMax)
-    {
-      information.graphMax = max;
-      return max;
-    }
-    else
-    {
-      information.graphMax = currentMax;
-      return currentMax;
-    }
+
+    information.graphMax = max;
+    return max;
   }
 
   /**
-   * Derive the gap count annotation row.
+   * Derive the occupancy count annotation
    * 
-   * @param gaprow
+   * @param occupancy
    *          the annotation row to add annotations to
    * @param profiles
    *          the source consensus data
@@ -445,11 +406,11 @@ public class AAFrequency
    * @param endCol
    *          end column (exclusive)
    */
-  public static void completeGapAnnot(AlignmentAnnotation gaprow,
+  public static void completeGapAnnot(AlignmentAnnotation occupancy,
           ProfilesI profiles, int startCol, int endCol, long nseq)
   {
-    if (gaprow == null || gaprow.annotations == null
-            || gaprow.annotations.length < endCol)
+    if (occupancy == null || occupancy.annotations == null
+            || occupancy.annotations.length < endCol)
     {
       /*
        * called with a bad alignment annotation row 
@@ -458,8 +419,8 @@ public class AAFrequency
       return;
     }
     // always set ranges again
-    gaprow.graphMax = nseq;
-    gaprow.graphMin = 0;
+    occupancy.graphMax = nseq;
+    occupancy.graphMin = 0;
     double scale = 0.8 / nseq;
     for (int i = startCol; i < endCol; i++)
     {
@@ -470,7 +431,7 @@ public class AAFrequency
          * happens if sequences calculated over were 
          * shorter than alignment width
          */
-        gaprow.annotations[i] = null;
+        occupancy.annotations[i] = null;
         return;
       }
 
@@ -478,7 +439,8 @@ public class AAFrequency
 
       String description = "" + gapped;
 
-      gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
+      occupancy.annotations[i] = new Annotation("", description, '\0',
+              gapped,
               jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
                       (float) scale * gapped));
     }
@@ -866,121 +828,104 @@ public class AAFrequency
   }
 
   /**
-   * Returns the information content at a specified column.
+   * Returns the sorted HMM profile for the given column of the alignment. The
+   * returned array contains
    * 
-   * @param column
-   *          Index of the column, starting from 0.
-   * @return
-   */
-  public static float getInformationContent(int column,
-          HiddenMarkovModel hmm)
-  {
-    float informationContent = 0f;
-
-    for (char symbol : hmm.getSymbols())
-    {
-      float freq = 0f;
-      freq = ResidueProperties.backgroundFrequencies
-              .get(hmm.getAlphabetType()).get(symbol);
-      Double hmmProb = hmm.getMatchEmissionProbability(column, symbol);
-      float prob = hmmProb.floatValue();
-      informationContent += prob * (Math.log(prob / freq) / Math.log(2));
-
-    }
-
-    return informationContent;
-  }
-
-  /**
-   * Produces a HMM profile for a column in an alignment
+   * <pre>
+   *    [profileType=0, numberOfValues, 100, charValue1, percentage1, charValue2, percentage2, ...]
+   * in descending order of percentage value
+   * </pre>
    * 
-   * @param aa
-   *          Alignment annotation for which the profile is being calculated.
+   * @param hmm
    * @param column
-   *          Column in the alignment the profile is being made for.
    * @param removeBelowBackground
-   *          Boolean indicating whether to ignore residues with probabilities
-   *          less than their background frequencies.
+   *          if true, ignores residues with probability less than their
+   *          background frequency
+   * @param infoHeight
+   *          if true, uses the log ratio 'information' measure to scale the
+   *          value
    * @return
    */
   public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
           boolean removeBelowBackground, boolean infoHeight)
   {
-
-    if (hmm != null)
+    if (hmm == null)
     {
-      int size = hmm.getNumberOfSymbols();
-      char symbols[] = new char[size];
-      int values[] = new int[size];
-      List<Character> charList = hmm.getSymbols();
-      Integer totalCount = 0;
+      return null;
+    }
+    String alphabet = hmm.getSymbols();
+    int size = alphabet.length();
+    char symbols[] = new char[size];
+    int values[] = new int[size];
+    int totalCount = 0;
 
-      for (int i = 0; i < size; i++)
-      {
-        char symbol = charList.get(i);
-        symbols[i] = symbol;
-        int value = getAnalogueCount(hmm, column, symbol,
-                removeBelowBackground, infoHeight);
-        values[i] = value;
-        totalCount += value;
-      }
+    for (int i = 0; i < size; i++)
+    {
+      char symbol = alphabet.charAt(i);
+      symbols[i] = symbol;
+      int value = getAnalogueCount(hmm, column, symbol,
+              removeBelowBackground, infoHeight);
+      values[i] = value;
+      totalCount += value;
+    }
 
-      QuickSort.sort(values, symbols);
+    /*
+     * sort symbols by increasing emission probability
+     */
+    QuickSort.sort(values, symbols);
 
-      int[] profile = new int[3 + size * 2];
+    int[] profile = new int[3 + size * 2];
 
-      profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
-      profile[1] = size;
-      profile[2] = 100;
+    profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
+    profile[1] = size;
+    profile[2] = 100;
 
-      if (totalCount != 0)
+    /*
+     * order symbol/count profile by decreasing emission probability
+     */
+    if (totalCount != 0)
+    {
+      int arrayPos = 3;
+      for (int k = size - 1; k >= 0; k--)
       {
-        int arrayPos = 3;
-        for (int k = size - 1; k >= 0; k--)
+        Float percentage;
+        int value = values[k];
+        if (removeBelowBackground)
         {
-          Float percentage;
-          Integer value = values[k];
-          if (removeBelowBackground)
-          {
-            percentage = (value.floatValue() / totalCount.floatValue())
-                    * 100;
-          }
-          else
-          {
-            percentage = value.floatValue() / 100f;
-          }
-          int intPercent = Math.round(percentage);
-          profile[arrayPos] = symbols[k];
-          profile[arrayPos + 1] = intPercent;
-          arrayPos += 2;
+          percentage = ((float) value) / totalCount * 100f;
+        }
+        else
+        {
+          percentage = value / 100f;
         }
+        int intPercent = Math.round(percentage);
+        profile[arrayPos] = symbols[k];
+        profile[arrayPos + 1] = intPercent;
+        arrayPos += 2;
       }
-      return profile;
     }
-    return null;
+    return profile;
   }
 
   /**
    * Converts the emission probability of a residue at a column in the alignment
-   * to a 'count' to allow for processing by the annotation renderer.
+   * to a 'count', suitable for rendering as an annotation value
    * 
    * @param hmm
    * @param column
-   * @param removeBelowBackground
-   *          When true, this method returns 0 for any symbols with a match
-   *          emission probability less than the background frequency.
    * @param symbol
+   * @param removeBelowBackground
+   *          if true, returns 0 for any symbol with a match emission
+   *          probability less than the background frequency
+   * @infoHeight if true, uses the log ratio 'information content' to scale the
+   *             value
    * @return
    */
   static int getAnalogueCount(HiddenMarkovModel hmm, int column,
           char symbol, boolean removeBelowBackground, boolean infoHeight)
   {
-    Double value;
-
-    value = hmm.getMatchEmissionProbability(column, symbol);
-    double freq;
-
-    freq = ResidueProperties.backgroundFrequencies
+    double value = hmm.getMatchEmissionProbability(column, symbol);
+    double freq = ResidueProperties.backgroundFrequencies
             .get(hmm.getAlphabetType()).get(symbol);
     if (value < freq && removeBelowBackground)
     {
@@ -989,10 +934,10 @@ public class AAFrequency
 
     if (infoHeight)
     {
-      value = value * (Math.log(value / freq) / Math.log(2));
+      value = value * (Math.log(value / freq) / LOG2);
     }
 
-    value = value * 10000;
-    return Math.round(value.floatValue());
+    value = value * 10000d;
+    return Math.round((float) value);
   }
 }