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()
85 * Copy constructor given a new aligned sequence with which to associate the
91 public HiddenMarkovModel(HiddenMarkovModel hmm, SequenceI sq)
94 this.fileProperties = new HashMap<>(hmm.fileProperties);
95 this.alphabet = hmm.alphabet;
96 this.nodes = new ArrayList<>(hmm.nodes);
97 this.symbolIndexLookup = hmm.symbolIndexLookup;
98 this.fileHeader = new String(hmm.fileHeader);
100 if (sq.getDatasetSequence() == hmm.mapToHmmConsensus.getTo())
102 // same dataset sequence e.g. after realigning search results
103 this.mapToHmmConsensus = hmm.mapToHmmConsensus;
107 // different dataset sequence e.g. after loading HMM from project
108 this.mapToHmmConsensus = new Mapping(sq.getDatasetSequence(),
109 hmm.mapToHmmConsensus.getMap());
114 * Returns the information content at a specified column, calculated as the
115 * sum (over possible symbols) of the log ratio
118 * log(emission probability / background probability) / log(2)
122 * column position (base 0)
125 public float getInformationContent(int column)
127 float informationContent = 0f;
129 for (char symbol : getSymbols().toCharArray())
131 float freq = ResidueProperties.backgroundFrequencies
132 .get(getAlphabetType()).get(symbol);
133 float prob = (float) getMatchEmissionProbability(column, symbol);
134 informationContent += prob * Math.log(prob / freq);
137 informationContent = informationContent / (float) LOG2;
139 return informationContent;
143 * Gets the file header of the .hmm file this model came from
147 public String getFileHeader()
153 * Sets the file header of this model.
157 public void setFileHeader(String header)
163 * Returns the symbols used in this hidden Markov model
167 public String getSymbols()
173 * Gets the node in the hidden Markov model at the specified position.
176 * The index of the node requested. Node 0 optionally contains the
177 * average match emission probabilities across the entire model, and
178 * always contains the insert emission probabilities and state
179 * transition probabilities for the begin node. Node 1 contains the
180 * first node in the HMM that can correspond to a column in the
184 public HMMNode getNode(int nodeIndex)
186 return nodes.get(nodeIndex);
190 * Returns the name of the sequence alignment on which the HMM is based.
194 public String getName()
196 return fileProperties.get(HMMFile.NAME);
200 * Answers the string value of the property (parsed from an HMM file) for the
201 * given key, or null if the property is not present
206 public String getProperty(String key)
208 return fileProperties.get(key);
212 * Answers true if the property with the given key is present with a value of
213 * "yes" (not case-sensitive), else false
218 public boolean getBooleanProperty(String key)
220 return YES.equalsIgnoreCase(fileProperties.get(key));
224 * Returns the length of the hidden Markov model. The value returned is the
225 * LENG property if specified, else the number of nodes, excluding the begin
226 * node (which should be the same thing).
230 public int getLength()
232 if (fileProperties.get(HMMFile.LENGTH) == null)
234 return nodes.size() - 1; // not counting BEGIN node
236 return Integer.parseInt(fileProperties.get(HMMFile.LENGTH));
240 * Returns the value of mandatory property "ALPH" - "amino", "DNA", "RNA" are
241 * the options. Other alphabets may be added.
245 public String getAlphabetType()
247 return fileProperties.get(HMMFile.ALPHABET);
251 * Sets the model alphabet to the symbols in the given string (ignoring any
252 * whitespace), and returns the number of symbols
256 public int setAlphabet(String symbols)
258 String trimmed = symbols.toUpperCase().replaceAll("\\s", "");
259 int count = trimmed.length();
261 symbolIndexLookup = new int['Z' - 'A' + 1];
262 Arrays.fill(symbolIndexLookup, -1);
266 * save the symbols in order, and a quick lookup of symbol position
268 for (short i = 0; i < count; i++)
270 char symbol = trimmed.charAt(i);
271 if (symbol >= 'A' && symbol <= 'Z'
272 && symbolIndexLookup[symbol - 'A'] == -1)
274 symbolIndexLookup[symbol - 'A'] = i;
280 "Unexpected or duplicated character in HMM ALPHabet: "
285 return count - ignored;
289 * Answers the node of the model corresponding to an aligned column position
290 * (0...), or null if there is no such node
295 HMMNode getNodeForColumn(int column)
298 * if the hmm consensus is gapped at the column,
299 * there is no corresponding node
301 if (Comparison.isGap(hmmSeq.getCharAt(column)))
307 * find the node (if any) that is mapped to the
308 * consensus sequence residue position at the column
310 int seqPos = hmmSeq.findPosition(column);
311 int[] nodeNo = mapToHmmConsensus.getMap().locateInFrom(seqPos, seqPos);
314 return getNode(nodeNo[0]);
320 * Gets the match emission probability for a given symbol at a column in the
324 * The index of the alignment column, starting at index 0. Index 0
325 * usually corresponds to index 1 in the HMM.
327 * The symbol for which the desired probability is being requested.
331 public double getMatchEmissionProbability(int alignColumn, char symbol)
333 HMMNode node = getNodeForColumn(alignColumn);
334 int symbolIndex = getSymbolIndex(symbol);
335 if (node != null && symbolIndex != -1)
337 return node.getMatchEmission(symbolIndex);
343 * Gets the insert emission probability for a given symbol at a column in the
347 * The index of the alignment column, starting at index 0. Index 0
348 * usually corresponds to index 1 in the HMM.
350 * The symbol for which the desired probability is being requested.
354 public double getInsertEmissionProbability(int alignColumn, char symbol)
356 HMMNode node = getNodeForColumn(alignColumn);
357 int symbolIndex = getSymbolIndex(symbol);
358 if (node != null && symbolIndex != -1)
360 return node.getInsertEmission(symbolIndex);
366 * Gets the state transition probability for a given symbol at a column in the
370 * The index of the alignment column, starting at index 0. Index 0
371 * usually corresponds to index 1 in the HMM.
373 * The symbol for which the desired probability is being requested.
377 public double getStateTransitionProbability(int alignColumn,
380 HMMNode node = getNodeForColumn(alignColumn);
383 return node.getStateTransition(transition);
389 * Returns the sequence position linked to the node at the given index. This
390 * corresponds to an aligned column position (counting from 1).
393 * The index of the node, starting from index 1. Index 0 is the begin
394 * node, which does not correspond to a column in the alignment.
397 public int getNodeMapPosition(int nodeIndex)
399 return nodes.get(nodeIndex).getResidueNumber();
403 * Returns the consensus residue at the specified node.
406 * The index of the specified node.
409 public char getConsensusResidue(int nodeIndex)
411 char value = nodes.get(nodeIndex).getConsensusResidue();
416 * Returns the reference annotation at the specified node.
419 * The index of the specified node.
422 public char getReferenceAnnotation(int nodeIndex)
424 char value = nodes.get(nodeIndex).getReferenceAnnotation();
429 * Returns the mask value at the specified node.
432 * The index of the specified node.
435 public char getMaskedValue(int nodeIndex)
437 char value = nodes.get(nodeIndex).getMaskValue();
442 * Returns the consensus structure at the specified node.
445 * The index of the specified node.
448 public char getConsensusStructure(int nodeIndex)
450 char value = nodes.get(nodeIndex).getConsensusStructure();
455 * Sets a property read from an HMM file
460 public void setProperty(String key, String value)
462 fileProperties.put(key, value);
466 * Temporary implementation, should not be used.
470 public String getViterbi()
473 value = fileProperties.get(HMMFile.VITERBI);
478 * Temporary implementation, should not be used.
482 public String getMSV()
485 value = fileProperties.get(HMMFile.MSV);
490 * Temporary implementation, should not be used.
494 public String getForward()
497 value = fileProperties.get(HMMFile.FORWARD);
502 * Constructs the consensus sequence based on the most probable symbol at each
503 * position. Gap characters are inserted for discontinuities in the node map
504 * numbering (if provided), else an ungapped sequence is generated.
506 * A mapping between the HMM nodes and residue positions of the sequence is
507 * also built and saved.
511 void buildConsensusSequence()
513 List<int[]> toResidues = new ArrayList<>();
516 * if the HMM provided a map to sequence, use those start/end values,
517 * else just treat it as for a contiguous sequence numbered from 1
519 boolean hasMap = getBooleanProperty(HMMFile.MAP);
520 int start = hasMap ? getNode(1).getResidueNumber() : 1;
521 int endResNo = hasMap ? getNode(nodes.size() - 1).getResidueNumber()
522 : (start + getLength() - 1);
523 char[] sequence = new char[endResNo - start + 1];
525 int lastResNo = start - 1;
529 for (int nodeNo = 1; nodeNo < nodes.size(); nodeNo++)
531 HMMNode node = nodes.get(nodeNo);
532 final int resNo = hasMap ? node.getResidueNumber() : lastResNo + 1;
535 * insert gaps if map numbering is not continuous
537 while (resNo > lastResNo + 1)
539 sequence[seqOffset++] = '-';
543 char consensusResidue = node.getConsensusResidue();
544 if (GAP_DASH == consensusResidue)
547 * no residue annotation in HMM - scan for the symbol
548 * with the highest match emission probability
550 int symbolIndex = node.getMaxMatchEmissionIndex();
551 consensusResidue = alphabet.charAt(symbolIndex);
552 if (node.getMatchEmission(symbolIndex) < 0.5D)
554 // follow convention of lower case if match emission prob < 0.5
555 consensusResidue = Character.toLowerCase(consensusResidue);
558 sequence[seqOffset++] = consensusResidue;
562 Sequence seq = new Sequence(getName(), sequence, start,
563 lastResNo - gapCount);
564 seq.createDatasetSequence();
569 * construct and store Mapping of nodes to residues
570 * note as constructed this is just an identity mapping,
571 * but it allows for greater flexibility in future
573 List<int[]> fromNodes = new ArrayList<>();
574 fromNodes.add(new int[] { 1, getLength() });
575 toResidues.add(new int[] { seq.getStart(), seq.getEnd() });
576 MapList mapList = new MapList(fromNodes, toResidues, 1, 1);
577 mapToHmmConsensus = new Mapping(seq.getDatasetSequence(), mapList);
582 * Answers the aligned consensus sequence for the profile. Note this will
583 * return null if called before <code>setNodes</code> has been called.
587 public SequenceI getConsensusSequence()
593 * Answers the index position (0...) of the given symbol, or -1 if not a valid
594 * symbol for this HMM
599 private int getSymbolIndex(char symbol)
602 * symbolIndexLookup holds the index for 'A' to 'Z'
604 char c = Character.toUpperCase(symbol);
605 if ('A' <= c && c <= 'Z')
607 return symbolIndexLookup[c - 'A'];
613 * Sets the nodes of this HMM, and also extracts the HMM consensus sequence
614 * and a mapping between node numbers and sequence positions
618 public void setNodes(List<HMMNode> nodeList)
621 if (nodes.size() > 1)
623 buildConsensusSequence();
628 * Sets the aligned consensus sequence this HMM is the model for
632 public void setHmmSeq(SequenceI hmmSeq)
634 this.hmmSeq = hmmSeq;