1 package jalview.datamodel;
3 import jalview.io.HMMFile;
4 import jalview.schemes.ResidueProperties;
5 import jalview.util.Comparison;
6 import jalview.util.MapList;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.HashMap;
11 import java.util.List;
15 * Data structure which stores a hidden Markov model
20 public class HiddenMarkovModel
22 private static final char GAP_DASH = '-';
24 public final static String YES = "yes";
26 public final static String NO = "no";
28 public static final int MATCHTOMATCH = 0;
30 public static final int MATCHTOINSERT = 1;
32 public static final int MATCHTODELETE = 2;
34 public static final int INSERTTOMATCH = 3;
36 public static final int INSERTTOINSERT = 4;
38 public static final int DELETETOMATCH = 5;
40 public static final int DELETETODELETE = 6;
42 private static final double LOG2 = Math.log(2);
45 * properties read from HMM file header lines
47 private Map<String, String> fileProperties = new HashMap<>();
49 private String fileHeader;
52 * the symbols used in this model e.g. "ACGT"
54 private String alphabet;
57 * symbol lookup index into the alphabet for 'A' to 'Z'
59 private int[] symbolIndexLookup = new int['Z' - 'A' + 1];
62 * Nodes in the model. The begin node is at index 0, and contains
63 * average emission probabilities for each symbol.
65 private List<HMMNode> nodes = new ArrayList<>();
68 * the aligned HMM consensus sequence extracted from the HMM profile
70 private SequenceI hmmSeq;
73 * mapping from HMM nodes to residues of the hmm consensus sequence
75 private Mapping mapToHmmConsensus;
80 public HiddenMarkovModel()
89 public HiddenMarkovModel(HiddenMarkovModel hmm)
92 this.fileProperties = new HashMap<>(hmm.fileProperties);
93 this.alphabet = hmm.alphabet;
94 this.nodes = new ArrayList<>(hmm.nodes);
95 this.symbolIndexLookup = hmm.symbolIndexLookup;
96 this.fileHeader = new String(hmm.fileHeader);
100 * Returns the information content at a specified column, calculated as the
101 * sum (over possible symbols) of the log ratio
104 * log(emission probability / background probability) / log(2)
108 * column position (base 0)
111 public float getInformationContent(int column)
113 float informationContent = 0f;
115 for (char symbol : getSymbols().toCharArray())
117 float freq = ResidueProperties.backgroundFrequencies
118 .get(getAlphabetType()).get(symbol);
119 float prob = (float) getMatchEmissionProbability(column, symbol);
120 informationContent += prob * Math.log(prob / freq);
123 informationContent = informationContent / (float) LOG2;
125 return informationContent;
129 * Gets the file header of the .hmm file this model came from
133 public String getFileHeader()
139 * Sets the file header of this model.
143 public void setFileHeader(String header)
149 * Returns the symbols used in this hidden Markov model
153 public String getSymbols()
159 * Gets the node in the hidden Markov model at the specified position.
162 * The index of the node requested. Node 0 optionally contains the
163 * average match emission probabilities across the entire model, and
164 * always contains the insert emission probabilities and state
165 * transition probabilities for the begin node. Node 1 contains the
166 * first node in the HMM that can correspond to a column in the
170 public HMMNode getNode(int nodeIndex)
172 return nodes.get(nodeIndex);
176 * Returns the name of the sequence alignment on which the HMM is based.
180 public String getName()
182 return fileProperties.get(HMMFile.NAME);
186 * Answers the string value of the property (parsed from an HMM file) for the
187 * given key, or null if the property is not present
192 public String getProperty(String key)
194 return fileProperties.get(key);
198 * Answers true if the property with the given key is present with a value of
199 * "yes" (not case-sensitive), else false
204 public boolean getBooleanProperty(String key)
206 return YES.equalsIgnoreCase(fileProperties.get(key));
210 * Returns the length of the hidden Markov model. The value returned is the
211 * LENG property if specified, else the number of nodes, excluding the begin
212 * node (which should be the same thing).
216 public int getLength()
218 if (fileProperties.get(HMMFile.LENGTH) == null)
220 return nodes.size() - 1; // not counting BEGIN node
222 return Integer.parseInt(fileProperties.get(HMMFile.LENGTH));
226 * Returns the value of mandatory property "ALPH" - "amino", "DNA", "RNA" are
227 * the options. Other alphabets may be added.
231 public String getAlphabetType()
233 return fileProperties.get(HMMFile.ALPHABET);
237 * Sets the model alphabet to the symbols in the given string (ignoring any
238 * whitespace), and returns the number of symbols
242 public int setAlphabet(String symbols)
244 String trimmed = symbols.toUpperCase().replaceAll("\\s", "");
245 int count = trimmed.length();
247 symbolIndexLookup = new int['Z' - 'A' + 1];
248 Arrays.fill(symbolIndexLookup, -1);
252 * save the symbols in order, and a quick lookup of symbol position
254 for (short i = 0; i < count; i++)
256 char symbol = trimmed.charAt(i);
257 if (symbol >= 'A' && symbol <= 'Z'
258 && symbolIndexLookup[symbol - 'A'] == -1)
260 symbolIndexLookup[symbol - 'A'] = i;
266 "Unexpected or duplicated character in HMM ALPHabet: "
271 return count - ignored;
275 * Answers the node of the model corresponding to an aligned column position
276 * (0...), or null if there is no such node
281 HMMNode getNodeForColumn(int column)
284 * if the hmm consensus is gapped at the column,
285 * there is no corresponding node
287 if (Comparison.isGap(hmmSeq.getCharAt(column)))
293 * find the node (if any) that is mapped to the
294 * consensus sequence residue position at the column
296 int seqPos = hmmSeq.findPosition(column);
297 int[] nodeNo = mapToHmmConsensus.getMap().locateInFrom(seqPos, seqPos);
300 return getNode(nodeNo[0]);
306 * Gets the match emission probability for a given symbol at a column in the
310 * The index of the alignment column, starting at index 0. Index 0
311 * usually corresponds to index 1 in the HMM.
313 * The symbol for which the desired probability is being requested.
317 public double getMatchEmissionProbability(int alignColumn, char symbol)
319 HMMNode node = getNodeForColumn(alignColumn);
320 int symbolIndex = getSymbolIndex(symbol);
321 if (node != null && symbolIndex != -1)
323 return node.getMatchEmission(symbolIndex);
329 * Gets the insert emission probability for a given symbol at a column in the
333 * The index of the alignment column, starting at index 0. Index 0
334 * usually corresponds to index 1 in the HMM.
336 * The symbol for which the desired probability is being requested.
340 public double getInsertEmissionProbability(int alignColumn, char symbol)
342 HMMNode node = getNodeForColumn(alignColumn);
343 int symbolIndex = getSymbolIndex(symbol);
344 if (node != null && symbolIndex != -1)
346 return node.getInsertEmission(symbolIndex);
352 * Gets the state transition probability for a given symbol at a column in the
356 * The index of the alignment column, starting at index 0. Index 0
357 * usually corresponds to index 1 in the HMM.
359 * The symbol for which the desired probability is being requested.
363 public double getStateTransitionProbability(int alignColumn,
366 HMMNode node = getNodeForColumn(alignColumn);
369 return node.getStateTransition(transition);
375 * Returns the sequence position linked to the node at the given index. This
376 * corresponds to an aligned column position (counting from 1).
379 * The index of the node, starting from index 1. Index 0 is the begin
380 * node, which does not correspond to a column in the alignment.
383 public int getNodeMapPosition(int nodeIndex)
385 return nodes.get(nodeIndex).getResidueNumber();
389 * Returns the consensus residue at the specified node.
392 * The index of the specified node.
395 public char getConsensusResidue(int nodeIndex)
397 char value = nodes.get(nodeIndex).getConsensusResidue();
402 * Returns the reference annotation at the specified node.
405 * The index of the specified node.
408 public char getReferenceAnnotation(int nodeIndex)
410 char value = nodes.get(nodeIndex).getReferenceAnnotation();
415 * Returns the mask value at the specified node.
418 * The index of the specified node.
421 public char getMaskedValue(int nodeIndex)
423 char value = nodes.get(nodeIndex).getMaskValue();
428 * Returns the consensus structure at the specified node.
431 * The index of the specified node.
434 public char getConsensusStructure(int nodeIndex)
436 char value = nodes.get(nodeIndex).getConsensusStructure();
441 * Sets a property read from an HMM file
446 public void setProperty(String key, String value)
448 fileProperties.put(key, value);
452 * Temporary implementation, should not be used.
456 public String getViterbi()
459 value = fileProperties.get(HMMFile.VITERBI);
464 * Temporary implementation, should not be used.
468 public String getMSV()
471 value = fileProperties.get(HMMFile.MSV);
476 * Temporary implementation, should not be used.
480 public String getForward()
483 value = fileProperties.get(HMMFile.FORWARD);
488 * Constructs the consensus sequence based on the most probable symbol at each
489 * position. Gap characters are inserted for discontinuities in the node map
490 * numbering (if provided), else an ungapped sequence is generated.
492 * A mapping between the HMM nodes and residue positions of the sequence is
493 * also built and saved.
497 void buildConsensusSequence()
499 List<int[]> toResidues = new ArrayList<>();
502 * if the HMM provided a map to sequence, use those start/end values,
503 * else just treat it as for a contiguous sequence numbered from 1
505 boolean hasMap = getBooleanProperty(HMMFile.MAP);
506 int start = hasMap ? getNode(1).getResidueNumber() : 1;
507 int endResNo = hasMap ? getNode(nodes.size() - 1).getResidueNumber()
508 : (start + getLength() - 1);
509 char[] sequence = new char[endResNo - start + 1];
511 int lastResNo = start - 1;
515 for (int nodeNo = 1; nodeNo < nodes.size(); nodeNo++)
517 HMMNode node = nodes.get(nodeNo);
518 final int resNo = hasMap ? node.getResidueNumber() : lastResNo + 1;
521 * insert gaps if map numbering is not continuous
523 while (resNo > lastResNo + 1)
525 sequence[seqOffset++] = '-';
529 char consensusResidue = node.getConsensusResidue();
530 if (GAP_DASH == consensusResidue)
533 * no residue annotation in HMM - scan for the symbol
534 * with the highest match emission probability
536 int symbolIndex = node.getMaxMatchEmissionIndex();
537 consensusResidue = alphabet.charAt(symbolIndex);
538 if (node.getMatchEmission(symbolIndex) < 0.5D)
540 // follow convention of lower case if match emission prob < 0.5
541 consensusResidue = Character.toLowerCase(consensusResidue);
544 sequence[seqOffset++] = consensusResidue;
548 Sequence seq = new Sequence(getName(), sequence, start,
549 lastResNo - gapCount);
550 seq.createDatasetSequence();
552 seq.setIsHMMConsensusSequence(true);
557 * construct and store Mapping of nodes to residues
558 * note as constructed this is just an identity mapping,
559 * but it allows for greater flexibility in future
561 List<int[]> fromNodes = new ArrayList<>();
562 fromNodes.add(new int[] { 1, getLength() });
563 toResidues.add(new int[] { seq.getStart(), seq.getEnd() });
564 MapList mapList = new MapList(fromNodes, toResidues, 1, 1);
565 mapToHmmConsensus = new Mapping(seq.getDatasetSequence(), mapList);
570 * Answers the aligned consensus sequence for the profile. Note this will
571 * return null if called before <code>setNodes</code> has been called.
575 public SequenceI getConsensusSequence()
581 * Answers the index position (0...) of the given symbol, or -1 if not a valid
582 * symbol for this HMM
587 private int getSymbolIndex(char symbol)
590 * symbolIndexLookup holds the index for 'A' to 'Z'
592 char c = Character.toUpperCase(symbol);
593 if ('A' <= c && c <= 'Z')
595 return symbolIndexLookup[c - 'A'];
601 * Sets the nodes of this HMM, and also extracts the HMM consensus sequence
602 * and a mapping between node numbers and sequence positions
606 public void setNodes(List<HMMNode> nodeList)
609 if (nodes.size() > 1)
611 buildConsensusSequence();