Merge branch 'develop' into features/mchmmer
[jalview.git] / src / jalview / analysis / AAFrequency.java
index e4f2dfa..85a9bb0 100755 (executable)
@@ -24,6 +24,7 @@ import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.Annotation;
+import jalview.datamodel.HiddenMarkovModel;
 import jalview.datamodel.Profile;
 import jalview.datamodel.ProfileI;
 import jalview.datamodel.Profiles;
@@ -32,6 +33,7 @@ import jalview.datamodel.ResidueCount;
 import jalview.datamodel.ResidueCount.SymbolCounts;
 import jalview.datamodel.SequenceI;
 import jalview.ext.android.SparseIntArray;
+import jalview.schemes.ResidueProperties;
 import jalview.util.Comparison;
 import jalview.util.Format;
 import jalview.util.MappingUtils;
@@ -55,6 +57,12 @@ 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'
    */
@@ -101,6 +109,8 @@ public class AAFrequency
     }
   }
 
+
+
   /**
    * Calculate the consensus symbol(s) for each column in the given range.
    * 
@@ -192,6 +202,57 @@ public class AAFrequency
   }
 
   /**
+   * Returns the full set of profiles for a hidden Markov model. The underlying
+   * data is the raw probabilities of a residue being emitted at each node,
+   * however the profiles returned by this function contain the percentage
+   * chance of a residue emission.
+   * 
+   * @param hmm
+   * @param width
+   *          The width of the Profile array (Profiles) to be returned.
+   * @param start
+   *          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
+   * @return
+   */
+  public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
+          int width, int start, int end, boolean saveFullProfile,
+          boolean removeBelowBackground, boolean infoLetterHeight)
+  {
+    ProfileI[] result = new ProfileI[width];
+    int symbolCount = hmm.getNumberOfSymbols();
+    for (int column = start; column < end; column++)
+    {
+      ResidueCount counts = new ResidueCount();
+      for (char symbol : hmm.getSymbols())
+      {
+        int value = getAnalogueCount(hmm, column, symbol,
+                removeBelowBackground, infoLetterHeight);
+        counts.put(symbol, value);
+      }
+      int maxCount = counts.getModalCount();
+      String maxResidue = counts.getResiduesForCount(maxCount);
+      int gapCount = counts.getGapCount();
+      ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
+              maxResidue);
+
+      if (saveFullProfile)
+      {
+        profile.setCounts(counts);
+      }
+
+      result[column] = profile;
+    }
+    return new Profiles(result);
+  }
+
+  /**
    * Make an estimate of the profile size we are going to compute i.e. how many
    * different characters may be present in it. Overestimating has a cost of
    * using more memory than necessary. Underestimating has a cost of needing to
@@ -289,6 +350,89 @@ public class AAFrequency
   }
 
   /**
+   * Derive the information annotations to be added to the alignment for
+   * display. This does not recompute the raw data, but may be called on a
+   * change in display options, such as 'ignore below background frequency',
+   * which may in turn result in a change in the derived values.
+   * 
+   * @param information
+   *          the annotation row to add annotations to
+   * @param profiles
+   *          the source information data
+   * @param startCol
+   *          start column (inclusive)
+   * @param endCol
+   *          end column (exclusive)
+   * @param ignoreGaps
+   *          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)
+  {
+    // long now = System.currentTimeMillis();
+    if (information == null || information.annotations == null
+            || information.annotations.length < endCol)
+    {
+      /*
+       * called with a bad alignment annotation row 
+       * wait for it to be initialised properly
+       */
+      return 0;
+    }
+
+    Float max = 0f;
+
+    for (int i = startCol; i < endCol; i++)
+    {
+      ProfileI profile = profiles.get(i);
+      if (profile == null)
+      {
+        /*
+         * happens if sequences calculated over were 
+         * shorter than alignment width
+         */
+        information.annotations[i] = null;
+        return 0;
+      }
+
+      HiddenMarkovModel hmm;
+      
+      SequenceI hmmSeq = information.sequenceRef;
+      
+      hmm = hmmSeq.getHMM();
+      
+      Float value = getInformationContent(i, hmm);
+
+      if (value > max)
+      {
+        max = value;
+      }
+
+      String description = value + " bits";
+      information.annotations[i] = new Annotation(
+              Character.toString(Character
+                      .toUpperCase(hmm.getConsensusAtAlignColumn(i))),
+              description, ' ', value);
+    }
+    if (max > currentMax)
+    {
+      information.graphMax = max;
+      return max;
+    }
+    else
+    {
+      information.graphMax = currentMax;
+      return currentMax;
+    }
+  }
+
+  /**
    * Derive the gap count annotation row.
    * 
    * @param gaprow
@@ -449,6 +593,7 @@ public class AAFrequency
     return result;
   }
 
+
   /**
    * Extract a sorted extract of cDNA codon profile data. The returned array
    * contains
@@ -531,7 +676,7 @@ public class AAFrequency
     for (int col = 0; col < cols; col++)
     {
       // todo would prefer a Java bean for consensus data
-      Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
+      Hashtable<String, int[]> columnHash = new Hashtable<>();
       // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
       int[] codonCounts = new int[66];
       codonCounts[0] = alignment.getSequences().size();
@@ -718,4 +863,135 @@ public class AAFrequency
     }
     return scale;
   }
+
+  /**
+   * Returns the information content at a specified column.
+   * 
+   * @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
+   * 
+   * @param aa
+   *          Alignment annotation for which the profile is being calculated.
+   * @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.
+   * @return
+   */
+  public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
+          boolean removeBelowBackground, boolean infoHeight)
+  {
+
+    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;
+
+      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;
+      }
+
+      QuickSort.sort(values, symbols);
+
+      int[] profile = new int[3 + size * 2];
+
+      profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
+      profile[1] = size;
+      profile[2] = 100;
+
+      if (totalCount != 0)
+      {
+        int arrayPos = 3;
+        for (int k = size - 1; k >= 0; k--)
+        {
+          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;
+        }
+      }
+      return profile;
+    }
+    return null;
+  }
+
+  /**
+   * Converts the emission probability of a residue at a column in the alignment
+   * to a 'count' to allow for processing by the annotation renderer.
+   * 
+   * @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
+   * @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
+            .get(hmm.getAlphabetType()).get(symbol);
+    if (value < freq && removeBelowBackground)
+    {
+      return 0;
+    }
+
+    if (infoHeight)
+    {
+      value = value * (Math.log(value / freq) / Math.log(2));
+    }
+
+    value = value * 10000;
+    return Math.round(value.floatValue());
+  }
 }