1 package jalview.datamodel;
3 import jalview.schemes.ResidueProperties;
5 import java.util.ArrayList;
6 import java.util.HashMap;
9 import java.util.Scanner;
12 * Data structure which stores a hidden Markov model. Currently contains file
13 * properties as well, not sure whether these should be transferred to the
19 public class HiddenMarkovModel
23 // Stores file properties. Do not directly access this field as it contains
24 // only string value - use the getter methods. For example, to find the length
25 // of theHMM, use getModelLength()to return an int value
26 Map<String, String> fileProperties = new HashMap<>();
28 // contains all of the symbols used in this model. The index of each symbol
29 // represents its lookup value
30 List<Character> symbols = new ArrayList<>();
32 // contains information for each node in the model. The begin node is at index
33 // 0. Node 0 contains average emission probabilities for each symbol
34 List<HMMNode> nodes = new ArrayList<>();
36 // contains the HMM node for each alignment column
37 Map<Integer, Integer> nodeLookup = new HashMap<>();
39 // contains the symbol index for each symbol
40 Map<Character, Integer> symbolIndexLookup = new HashMap<>();
42 final static String YES = "yes";
44 final static String NO = "no";
48 // keys for file properties hashmap
49 private final String NAME = "NAME";
51 private final String ACCESSION_NUMBER = "ACC";
53 private final String DESCRIPTION = "DESC";
55 private final String LENGTH = "LENG";
57 private final String MAX_LENGTH = "MAXL";
59 private final String ALPHABET = "ALPH";
61 private final String DATE = "DATE";
63 private final String COMMAND_LOG = "COM";
65 private final String NUMBER_OF_SEQUENCES = "NSEQ";
67 private final String EFF_NUMBER_OF_SEQUENCES = "EFFN";
69 private final String CHECK_SUM = "CKSUM";
71 private final String GATHERING_THRESHOLDS = "GA";
73 private final String TRUSTED_CUTOFFS = "TC";
75 private final String NOISE_CUTOFFS = "NC";
77 private final String STATISTICS = "STATS";
79 private final String COMPO = "COMPO";
81 private final String GATHERING_THRESHOLD = "GA";
83 private final String TRUSTED_CUTOFF = "TC";
85 private final String NOISE_CUTOFF = "NC";
87 private final String VITERBI = "VITERBI";
89 private final String MSV = "MSV";
91 private final String FORWARD = "FORWARD";
93 private final String MAP = "MAP";
95 private final String REFERENCE_ANNOTATION = "RF";
97 private final String CONSENSUS_RESIDUE = "CONS";
99 private final String CONSENSUS_STRUCTURE = "CS";
101 private final String MASKED_VALUE = "MM";
103 public static final int MATCHTOMATCH = 0;
105 public static final int MATCHTOINSERT = 1;
107 public static final int MATCHTODELETE = 2;
109 public static final int INSERTTOMATCH = 3;
111 public static final int INSERTTOINSERT = 4;
113 public static final int DELETETOMATCH = 5;
115 public static final int DELETETODELETE = 6;
118 * Returns the map containing the matches between nodes and alignment column
124 public Map<Integer, Integer> getNodeLookup()
130 * Returns the list of symbols used in this hidden Markov model.
134 public List<Character> getSymbols()
140 * Returns the file properties.
144 public Map<String, String> getFileProperties()
146 return fileProperties;
150 * Gets the node in the hidden Markov model at the specified position.
153 * The index of the node requested. Node 0 optionally contains the
154 * average match emission probabilities across the entire model, and
155 * always contains the insert emission probabilities and state
156 * transition probabilities for the begin node. Node 1 contains the
157 * first node in the HMM that can correspond to a column in the
161 public HMMNode getNode(int nodeIndex)
163 return getNodes().get(nodeIndex);
167 * Sets the list of symbols used in the hidden Markov model to the list
171 * The list of symbols to which the current list is to be changed.
174 public void setSymbols(List<Character> symbolsL)
176 this.symbols = symbolsL;
180 * Returns the name of the sequence alignment on which the HMM is based.
184 public String getName()
186 return fileProperties.get(NAME);
190 * Returns the accession number.
193 public String getAccessionNumber()
195 return fileProperties.get(ACCESSION_NUMBER);
199 * Returns a description of the sequence alignment on which the hidden Markov
204 public String getDescription()
206 return fileProperties.get(DESCRIPTION);
210 * Returns the length of the hidden Markov model.
214 public Integer getLength()
216 if (fileProperties.get(LENGTH) == null)
220 return Integer.parseInt(fileProperties.get(LENGTH));
224 * Returns the max instance length within the hidden Markov model.
228 public Integer getMaxInstanceLength()
230 if (fileProperties.get(MAX_LENGTH) == null)
234 return Integer.parseInt(fileProperties.get(MAX_LENGTH));
238 * Returns the type of symbol alphabet - "amino", "DNA", "RNA" are the
239 * options. Other alphabets may be added.
243 public String getAlphabetType()
245 return fileProperties.get(ALPHABET);
249 * Returns the date as a String.
253 public String getDate()
255 return fileProperties.get(DATE);
259 * Returns the command line log.
263 public String getCommandLineLog()
265 return fileProperties.get(COMMAND_LOG);
269 * Returns the number of sequences on which the HMM was trained.
273 public Integer getNumberOfSequences()
275 if (fileProperties.get(NUMBER_OF_SEQUENCES) == null)
279 return Integer.parseInt(fileProperties.get(NUMBER_OF_SEQUENCES));
283 * Returns the effective number of sequences on which the HMM was based.
287 public Double getEffectiveNumberOfSequences()
289 if (fileProperties.get(LENGTH) == null)
293 return Double.parseDouble(fileProperties.get(EFF_NUMBER_OF_SEQUENCES));
297 * Returns the checksum.
301 public Long getCheckSum()
303 if (fileProperties.get(LENGTH) == null)
307 return Long.parseLong(fileProperties.get(CHECK_SUM));
311 * Returns the list of nodes in this HMM.
315 public List<HMMNode> getNodes()
321 * Sets the list of nodes in this HMM to the given list.
324 * The list of nodes to which the current list of nodes is being
327 public void setNodes(List<HMMNode> nodes)
333 * Gets the match emission probability for a given symbol at a column in the
337 * The index of the alignment column, starting at index 0. Index 0
338 * usually corresponds to index 1 in the HMM.
340 * The symbol for which the desired probability is being requested.
344 public Double getMatchEmissionProbability(int alignColumn, char symbol)
349 if (!symbolIndexLookup.containsKey(symbol))
353 symbolIndex = symbolIndexLookup.get(symbol);
354 if (nodeLookup.containsKey(alignColumn + 1))
356 nodeIndex = nodeLookup.get(alignColumn + 1);
357 probability = getNode(nodeIndex).getMatchEmissions().get(symbolIndex);
368 * Gets the insert emission probability for a given symbol at a column in the
372 * The index of the alignment column, starting at index 0. Index 0
373 * usually corresponds to index 1 in the HMM.
375 * The symbol for which the desired probability is being requested.
379 public Double getInsertEmissionProbability(int alignColumn, char symbol)
384 if (!symbolIndexLookup.containsKey(symbol))
388 symbolIndex = symbolIndexLookup.get(symbol);
389 if (nodeLookup.containsKey(alignColumn + 1))
391 nodeIndex = nodeLookup.get(alignColumn + 1);
392 probability = getNode(nodeIndex).getInsertEmissions()
404 * Gets the state transition probability for a given symbol at a column in the
408 * The index of the alignment column, starting at index 0. Index 0
409 * usually corresponds to index 1 in the HMM.
411 * The symbol for which the desired probability is being requested.
415 public Double getStateTransitionProbability(int alignColumn,
421 if (nodeLookup.containsKey(alignColumn + 1))
423 nodeIndex = nodeLookup.get(alignColumn + 1);
424 probability = getNode(nodeIndex).getStateTransitions()
436 * Returns the alignment column linked to the node at the given index.
439 * The index of the node, starting from index 1. Index 0 is the begin
440 * node, which does not correspond to a column in the alignment.
443 public Integer getNodeAlignmentColumn(int nodeIndex)
445 Integer value = nodes.get(nodeIndex).getAlignmentColumn();
450 * Returns the consensus residue at the specified node.
453 * The index of the specified node.
456 public char getConsensusResidue(int nodeIndex)
458 char value = nodes.get(nodeIndex).getConsensusResidue();
463 * Returns the consensus at a given alignment column.
466 * The index of the column in the alignment for which the consensus
467 * is desired. The list of columns starts at index 0.
470 public char getConsensusAtAlignColumn(int columnIndex)
472 char mostLikely = '-';
473 if (consensusResidueIsActive())
476 Integer index = findNodeIndex(columnIndex);
481 mostLikely = getNodes().get(index).getConsensusResidue();
486 double highestProb = 0;
487 for (char character : symbols)
489 Double prob = getMatchEmissionProbability(columnIndex, character);
490 if (prob > highestProb)
493 mostLikely = character;
502 * Returns the reference annotation at the specified node.
505 * The index of the specified node.
508 public char getReferenceAnnotation(int nodeIndex)
510 char value = nodes.get(nodeIndex).getReferenceAnnotation();
515 * Returns the mask value at the specified node.
518 * The index of the specified node.
521 public char getMaskedValue(int nodeIndex)
523 char value = nodes.get(nodeIndex).getMaskValue();
528 * Returns the consensus structure at the specified node.
531 * The index of the specified node.
534 public char getConsensusStructure(int nodeIndex)
536 char value = nodes.get(nodeIndex).getConsensusStructure();
541 * Returns the average match emission probability for a given symbol
544 * The index of the symbol.
548 public double getAverageMatchEmission(int symbolIndex)
550 double value = nodes.get(0).getMatchEmissions().get(symbolIndex);
555 * Returns the number of symbols in the alphabet used in this HMM.
559 public int getNumberOfSymbols()
561 return numberOfSymbols;
565 * Fills symbol array and whilst doing so, updates the value of the number of
569 * The scanner scanning the symbol line in the file.
571 public void fillSymbols(Scanner parser)
574 while (parser.hasNext())
576 String strSymbol = parser.next();
577 char[] symbol = strSymbol.toCharArray();
578 symbols.add(symbol[0]);
579 symbolIndexLookup.put(symbol[0], i);
582 numberOfSymbols = symbols.size();
586 * Adds a file property.
591 public void addFileProperty(String key, String value)
593 fileProperties.put(key, value);
597 * Returns a boolean indicating whether the reference annotation is active.
601 public boolean referenceAnnotationIsActive()
604 status = fileProperties.get(REFERENCE_ANNOTATION);
622 * Returns a boolean indicating whether the mask value annotation is active.
626 public boolean maskValueIsActive()
629 status = fileProperties.get(MASKED_VALUE);
647 * Returns a boolean indicating whether the consensus residue annotation is
652 public boolean consensusResidueIsActive()
655 status = fileProperties.get(CONSENSUS_RESIDUE);
673 * Returns a boolean indicating whether the consensus structure annotation is
678 public boolean consensusStructureIsActive()
681 status = fileProperties.get(CONSENSUS_STRUCTURE);
699 * Returns a boolean indicating whether the MAP annotation is active.
703 public boolean mapIsActive()
706 status = fileProperties.get(MAP);
724 * Sets the alignment column of the specified node.
731 public void setAlignmentColumn(int nodeIndex, int column)
733 nodes.get(nodeIndex).setAlignmentColumn(column);
737 * Sets the reference annotation at a given node.
742 public void setReferenceAnnotation(int nodeIndex, char value)
744 nodes.get(nodeIndex).setReferenceAnnotation(value);
748 * Sets the consensus residue at a given node.
753 public void setConsensusResidue(int nodeIndex, char value)
755 nodes.get(nodeIndex).setConsensusResidue(value);
759 * Sets the consensus structure at a given node.
764 public void setConsensusStructure(int nodeIndex, char value)
766 nodes.get(nodeIndex).setConsensusStructure(value);
770 * Sets the mask value at a given node.
775 public void setMaskValue(int nodeIndex, char value)
777 nodes.get(nodeIndex).setMaskValue(value);
781 * Temporary implementation, should not be used.
785 public String getGatheringThreshold()
788 value = fileProperties.get("GA");
793 * Temporary implementation, should not be used.
797 public String getNoiseCutoff()
800 value = fileProperties.get("NC");
805 * Temporary implementation, should not be used.
809 public String getTrustedCutoff()
812 value = fileProperties.get("TC");
817 * Temporary implementation, should not be used.
821 public String getViterbi()
824 value = fileProperties.get(VITERBI);
829 * Temporary implementation, should not be used.
833 public String getMSV()
836 value = fileProperties.get(MSV);
841 * Temporary implementation, should not be used.
845 public String getForward()
848 value = fileProperties.get(FORWARD);
853 * Sets the activation status of the MAP annotation.
857 public void setMAPStatus(boolean status)
859 fileProperties.put(MAP, status ? YES : NO);
863 * Sets the activation status of the reference annotation.
867 public void setReferenceAnnotationStatus(boolean status)
869 fileProperties.put(REFERENCE_ANNOTATION, status ? YES : NO);
873 * Sets the activation status of the mask value annotation.
877 public void setMaskedValueStatus(boolean status)
879 fileProperties.put(MASKED_VALUE, status ? YES : NO);
883 * Sets the activation status of the consensus residue annotation.
887 public void setConsensusResidueStatus(boolean status)
889 fileProperties.put(CONSENSUS_RESIDUE, status ? YES : NO);
893 * Sets the activation status of the consensus structure annotation.
897 public void setConsensusStructureStatus(boolean status)
899 fileProperties.put(CONSENSUS_STRUCTURE, status ? YES : NO);
903 * Finds the index of the node in a hidden Markov model based on the column in
906 * @param alignmentColumn
907 * The index of the column in the alignment, with the indexes
911 public Integer findNodeIndex(int alignmentColumn)
914 index = nodeLookup.get(alignmentColumn + 1);
919 * Finds the String values of a boolean. "yes" for true and "no" for false.
924 public static String findStringFromBoolean(boolean value)
937 * Creates the HMM Logo alignment annotation, and populates it with
938 * information content data.
940 * @return The alignment annotation.
942 public AlignmentAnnotation createAnnotation(int length)
944 Annotation[] annotations = new Annotation[length];
946 for (int alignPos = 0; alignPos < length; alignPos++)
948 Float content = getInformationContent(alignPos);
956 cons = getConsensusAtAlignColumn(alignPos);
958 cons = Character.toUpperCase(cons);
960 String description = String.format("%.3f", content);
961 description += " bits";
962 annotations[alignPos] = new Annotation(cons.toString(), description,
967 AlignmentAnnotation annotation = new AlignmentAnnotation(
968 "Information Content",
969 "The information content of each column, measured in bits",
971 0f, max, AlignmentAnnotation.BAR_GRAPH);
972 annotation.setHMM(this);
977 * Returns the information content at a specified column.
980 * Index of the column, starting from 0.
983 public float getInformationContent(int column)
985 float informationContent = 0f;
987 for (char symbol : symbols)
990 if ("amino".equals(getAlphabetType()))
992 freq = ResidueProperties.aminoBackgroundFrequencies.get(symbol);
994 if ("DNA".equals(getAlphabetType()))
996 freq = ResidueProperties.dnaBackgroundFrequencies.get(symbol);
998 if ("RNA".equals(getAlphabetType()))
1000 freq = ResidueProperties.rnaBackgroundFrequencies
1003 Double hmmProb = getMatchEmissionProbability(column, symbol);
1004 float prob = hmmProb.floatValue();
1005 informationContent += prob * (Math.log(prob / freq) / Math.log(2));
1009 return informationContent;
1013 * Returns the consensus sequence based on the most probable symbol at each
1014 * position. The sequence is adjusted to match the length of the existing
1015 * sequence alignment. Gap characters are used as padding.
1018 * The length of the longest sequence in the existing alignment.
1021 public Sequence getConsensusSequence(int length)
1026 start = getNodeAlignmentColumn(1);
1027 modelLength = getLength();
1028 end = getNodeAlignmentColumn(modelLength);
1029 char[] sequence = new char[length];
1030 for (int index = 0; index < length; index++)
1032 Character character;
1034 character = getConsensusAtAlignColumn(index);
1036 if (character == null || character == '-')
1038 sequence[index] = '-';
1042 sequence[index] = Character.toUpperCase(character);
1047 Sequence seq = new Sequence("HMM CONSENSUS", sequence, start, end);
1053 * Maps the nodes of the hidden Markov model to the reference annotation.
1055 public void mapToReferenceAnnotation(AlignmentAnnotation alAnnotation)
1057 Annotation[] annots = alAnnotation.annotations;
1060 for (int col = 0; col < annots.length; col++)
1062 String character = annots[col].displayCharacter;
1063 if ("x".equals(character) || "X".equals(character))
1066 if (nodeIndex < nodes.size())
1068 nodes.get(nodeIndex).setAlignmentColumn(col + 1);
1069 nodeLookup.put(col + 1, nodeIndex);
1074 "The reference annotation contains more consensus columns than the hidden Markov model");
1080 nodeLookup.remove(col + 1);
1087 public AlignmentI initPlaceholder(AlignmentI alignment)
1089 int length = alignment.getWidth();
1090 Sequence consensus = getConsensusSequence(length);
1091 consensus.setHMM(this);
1092 SequenceI[] consensusArr = new Sequence[] { consensus };
1093 AlignmentI newAlignment = new Alignment(consensusArr);
1094 newAlignment.append(alignment);
1095 return newAlignment;