3 import jalview.datamodel.HMMNode;
4 import jalview.datamodel.HiddenMarkovModel;
5 import jalview.datamodel.SequenceI;
7 import java.io.BufferedReader;
8 import java.io.FileNotFoundException;
9 import java.io.IOException;
10 import java.io.PrintWriter;
11 import java.io.UnsupportedEncodingException;
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Scanner;
18 * Adds capability to read in and write out HMMER3 files. Currently only supports HMMER3/f.
24 public class HMMFile extends AlignFile
25 implements AlignmentFileReaderI, AlignmentFileWriterI
27 // HMM to store file data
28 private HiddenMarkovModel hmm = new HiddenMarkovModel();
33 // number of possible transitions
34 private final int NUMBER_OF_TRANSITIONS = 7;
36 private final String NEW_LINE = "\n";
41 //number of symbols in the alphabet used in the hidden Markov model
44 private final String SPACE = " ";
46 private final String COMPO = "COMPO";
48 private final String EMPTY = "";
50 //This is a line that needs to be added to each HMMER£ file. It is purely for readability.
51 private static final String TRANSITIONTYPELINE = "m->m m->i m->d i->m i->i d->m d->d";
54 * Constructor for HMMFile
58 public HMMFile(FileParse source) throws IOException
64 * Default constructor, do not use!
72 * Returns the HMM produced by reading in a HMMER3 file.
76 public HiddenMarkovModel getHMM()
82 * Sets the HMM used in this file.
86 public void setHMM(HiddenMarkovModel model)
92 * Gets the name of the hidden Markov model.
96 public String getName()
102 * Reads the data from HMM file into the HMM field on this object.
104 * @throws IOException
107 public void parse() throws IOException
109 parseFileProperties(dataIn);
114 * Reads the data from HMM file into the HMM field on this object.
116 * @throws IOException
119 public void parse(BufferedReader br) throws IOException
121 parseFileProperties(br);
128 * Imports the file properties from a HMMER3 file.
131 * The buffered reader used to read in the file.
132 * @throws IOException
134 void parseFileProperties(BufferedReader input) throws IOException
136 boolean readingFile = true;
137 fileHeader = input.readLine();
138 String line = input.readLine();
143 Scanner parser = new Scanner(line);
144 String next = parser.next();
145 if ("HMM".equals(next)) // indicates start of HMM data (end of file
149 hmm.fillSymbols(parser);
150 numberOfSymbols = hmm.getNumberOfSymbols();
152 else if ("STATS".equals(next))
158 value = parser.next() + SPACE + SPACE + parser.next();
159 hmm.addFileProperty(key, value);
164 String value = parser.next();
165 while (parser.hasNext())
167 value = value + SPACE + parser.next();
169 hmm.addFileProperty(key, value);
173 line = input.readLine();
183 * Parses the model data from the HMMER3 file
186 * The buffered reader used to read the file.
187 * @throws IOException
189 void parseModel(BufferedReader input) throws IOException
191 for (int i = 0; i < hmm.getLength() + 1; i++)
193 hmm.getNodes().add(new HMMNode());
196 line = input.readLine();
197 Scanner matchReader = new Scanner(line);
198 next = matchReader.next();
199 if (next.equals(COMPO) || i > 0)
201 // stores match emission line in list
202 List<Double> matches = new ArrayList<>();
203 matches = fillList(matchReader, numberOfSymbols);
204 hmm.getNodes().get(i).setMatchEmissions(matches);
207 parseAnnotations(matchReader, i);
211 // stores insert emission line in list
212 line = input.readLine();
213 Scanner insertReader = new Scanner(line);
214 List<Double> inserts = new ArrayList<>();
215 inserts = fillList(insertReader, numberOfSymbols);
216 hmm.getNodes().get(i).setInsertEmissions(inserts);
217 insertReader.close();
219 // stores state transition line in list
220 line = input.readLine();
221 Scanner transitionReader = new Scanner(line);
222 List<Double> transitions = new ArrayList<>();
223 transitions = fillList(transitionReader, NUMBER_OF_TRANSITIONS);
224 hmm.getNodes().get(i).setStateTransitions(transitions);
225 transitionReader.close();
231 * Parses the annotations on the match emission line.
234 * The scanner which is processing match emission line.
236 * The index of node which is being scanned.
238 void parseAnnotations(Scanner scanner, int index)
240 if (hmm.mapIsActive())
243 column = scanner.nextInt();
244 hmm.getNodes().get(index).setAlignmentColumn(column);
245 hmm.getNodeLookup().put(column, index);
253 consensusR = charValue(scanner.next());
254 hmm.getNodes().get(index).setConsensusResidue(consensusR);
257 reference = charValue(scanner.next());
258 hmm.getNodes().get(index).setReferenceAnnotation(reference);
262 value = charValue(scanner.next());
263 hmm.getNodes().get(index).setMaskValue(value);
266 consensusS = charValue(scanner.next());
267 hmm.getNodes().get(index).setConsensusStructure(consensusS);
272 * Fills a list of doubles based on an input line.
275 * The scanner for the line containing the data to be transferred to
277 * @param numberOfElements
278 * The number of elements in the list to be filled.
279 * @return filled list Returns the list of doubles.
281 static List<Double> fillList(Scanner input,
282 int numberOfElements)
284 List<Double> list = new ArrayList<>();
285 for (int i = 0; i < numberOfElements; i++)
288 String next = input.next();
289 if (next.contains("*")) // state transitions to or from delete states
290 // occasionally have values of -infinity. These
291 // values are represented by an * in the .hmm
294 list.add(Double.NEGATIVE_INFINITY);
298 double prob = Double.valueOf(next);
299 prob = Math.pow(Math.E, -prob);
308 * Writes a HMM to a file/
310 * @param exportLocation
311 * Filename, URL or Pasted String to write to.
312 * @throws FileNotFoundException
313 * @throws UnsupportedEncodingException
317 public void exportFile(String exportLocation) throws IOException
319 StringBuilder file = new StringBuilder();
320 appendFileProperties(file);
324 PrintWriter output = new PrintWriter(exportLocation);
331 * Returns a string to be added to the StringBuilder containing the entire
334 * @param initialColumnSeparation
335 * The initial whitespace separation between the left side of the
336 * file and first character.
337 * @param columnSeparation
338 * The separation between subsequent data entries.
340 * The list fo data to be added to the String.
343 String addData(int initialColumnSeparation,
344 int columnSeparation, List<String> data)
348 for (String value : data)
352 line += String.format("%" + initialColumnSeparation + "s", value);
356 line += String.format("%" + columnSeparation + "s", value);
364 * Converts list of characters into a list of Strings.
367 * @return Returns the list of Strings.
369 List<String> charListToStringList(List<Character> list)
371 List<String> strList = new ArrayList<>();
372 for (char value : list)
374 String strValue = Character.toString(value);
375 strList.add(strValue);
381 * Converts a list of doubles into a list of Strings, rounded to the nearest
385 * @param noOfDecimals
388 List<String> doubleListToStringList(List<Double> list)
390 List<String> strList = new ArrayList<>();
391 for (double value : list)
396 strValue = String.format("%.5f", value);
399 else if (value == -0.00000d)
401 strValue = "0.00000";
408 strList.add(strValue);
414 * Converts a primitive array of Strings to a list of Strings.
419 List<String> stringArrayToStringList(String[] array)
421 List<String> list = new ArrayList<>();
422 for (String value : array)
431 * Appends the hidden Markov model data to the StringBuilder containing the
435 * The StringBuilder containing the output.
437 void appendModel(StringBuilder file)
439 String symbolLine = "HMM";
440 List<Character> charSymbols = hmm.getSymbols();
441 List<String> strSymbols;
442 strSymbols = charListToStringList(charSymbols);
443 symbolLine += addData(11, 9, strSymbols);
444 file.append(symbolLine + NEW_LINE);
445 file.append(TRANSITIONTYPELINE + NEW_LINE);
447 int length = hmm.getLength();
449 for (int node = 0; node <= length; node++)
454 matchLine = String.format("%7s", "COMPO");
458 matchLine = String.format("%7s", node);
461 List<String> strMatches;
462 List<Double> doubleMatches;
463 doubleMatches = hmm.getNode(node).getMatchEmissions();
464 convertListToLogSpace(doubleMatches);
465 strMatches = doubleListToStringList(doubleMatches);
466 matchLine += addData(10, 9, strMatches);
471 matchLine += SPACE + hmm.getNodeAlignmentColumn(node);
472 matchLine += SPACE + hmm.getConsensusResidue(node);
473 matchLine += SPACE + hmm.getReferenceAnnotation(node);
474 matchLine += SPACE + hmm.getMaskedValue(node);
475 matchLine += SPACE + hmm.getConsensusStructure(node);
479 file.append(matchLine + NEW_LINE);
481 String insertLine = EMPTY;
482 List<String> strInserts;
483 List<Double> doubleInserts;
484 doubleInserts = hmm.getNode(node).getInsertEmissions();
485 convertListToLogSpace(doubleInserts);
486 strInserts = doubleListToStringList(doubleInserts);
487 insertLine += addData(17, 9, strInserts);
489 file.append(insertLine + NEW_LINE);
491 String transitionLine = EMPTY;
492 List<String> strTransitions;
493 List<Double> doubleTransitions;
494 doubleTransitions = hmm.getNode(node).getStateTransitions();
495 convertListToLogSpace(doubleTransitions);
496 strTransitions = doubleListToStringList(doubleTransitions);
497 transitionLine += addData(17, 9, strTransitions);
499 file.append(transitionLine + NEW_LINE);
504 * Appends the hidden Markov model file properties to the StringBuilder
505 * containing the output
508 * The StringBuilder containing the output.
510 void appendFileProperties(StringBuilder file)
514 file.append(fileHeader + NEW_LINE);
516 line = String.format("%-5s %1s", "NAME", hmm.getName());
517 file.append((line + NEW_LINE));
519 if (hmm.getAccessionNumber() != null)
521 line = String.format("%-5s %1s", "ACC", hmm.getAccessionNumber());
522 file.append((line + NEW_LINE));
525 if (hmm.getDescription() != null)
527 line = String.format("%-5s %1s", "DESC", hmm.getDescription());
528 file.append((line + NEW_LINE));
530 line = String.format("%-5s %1s", "LENG", hmm.getLength());
531 file.append((line + NEW_LINE));
533 if (hmm.getMaxInstanceLength() != null)
535 line = String.format("%-5s %1s", "MAXL", hmm.getMaxInstanceLength());
536 file.append((line + NEW_LINE));
538 line = String.format("%-5s %1s", "ALPH", hmm.getAlphabetType());
539 file.append((line + NEW_LINE));
544 status = hmm.referenceAnnotationIsActive();
545 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
546 line = String.format("%-5s %1s", "RF",
548 file.append((line + NEW_LINE));
550 status = hmm.maskValueIsActive();
551 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
552 line = String.format("%-5s %1s", "MM",
554 file.append((line + NEW_LINE));
556 status = hmm.consensusResidueIsActive();
557 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
558 line = String.format("%-5s %1s", "CONS",
560 file.append((line + NEW_LINE));
562 status = hmm.consensusStructureIsActive();
563 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
564 line = String.format("%-5s %1s", "CS",
566 file.append((line + NEW_LINE));
568 status = hmm.mapIsActive();
569 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
570 line = String.format("%-5s %1s", "MAP",
572 file.append((line + NEW_LINE));
575 if (hmm.getDate() != null)
577 line = String.format("%-5s %1s", "DATE", hmm.getDate());
578 file.append((line + NEW_LINE));
580 if (hmm.getNumberOfSequences() != null)
582 line = String.format("%-5s %1s", "NSEQ", hmm.getNumberOfSequences());
583 file.append((line + NEW_LINE));
585 if (hmm.getEffectiveNumberOfSequences() != null)
587 line = String.format("%-5s %1s", "EFFN",
588 hmm.getEffectiveNumberOfSequences());
589 file.append((line + NEW_LINE));
591 if (hmm.getCheckSum() != null)
593 line = String.format("%-5s %1s", "CKSUM", hmm.getCheckSum());
594 file.append((line + NEW_LINE));
596 if (hmm.getGatheringThreshold() != null)
598 line = String.format("%-5s %1s", "GA", hmm.getGatheringThreshold());
599 file.append((line + NEW_LINE));
602 if (hmm.getTrustedCutoff() != null)
604 line = String.format("%-5s %1s", "TC", hmm.getTrustedCutoff());
605 file.append((line + NEW_LINE));
607 if (hmm.getNoiseCutoff() != null)
609 line = String.format("%-5s %1s", "NC", hmm.getNoiseCutoff());
610 file.append((line + NEW_LINE));
612 if (hmm.getMSV() != null)
614 line = String.format("%-19s %18s", "STATS LOCAL MSV", hmm.getMSV());
615 file.append((line + NEW_LINE));
617 line = String.format("%-19s %18s", "STATS LOCAL VITERBI",
619 file.append((line + NEW_LINE));
621 line = String.format("%-19s %18s", "STATS LOCAL FORWARD",
623 file.append((line + NEW_LINE));
629 * Returns the char value of a single lettered String.
634 char charValue(String string)
637 character = string.charAt(0);
643 public String print(SequenceI[] seqs, boolean jvsuffix)
650 * Converts the probabilities contained in a list into log space.
654 void convertListToLogSpace(List<Double> list)
657 for (int i = 0; i < list.size(); i++)
659 double prob = list.get(i);
660 double logProb = -1 * Math.log(prob);
662 list.set(i, logProb);