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";
38 //number of symbols in the alphabet used in the hidden Markov model
41 private final String SPACE = " ";
43 private final String COMPO = "COMPO";
45 private final String EMPTY = "";
47 //This is a line that needs to be added to each HMMER£ file. It is purely for readability.
48 private static final String TRANSITIONTYPELINE = "m->m m->i m->d i->m i->i d->m d->d";
51 * Constructor for HMMFile
55 public HMMFile(FileParse source) throws IOException
61 * Default constructor, do not use!
69 * Constructor for HMMFile used for exporting.
72 * @param exportImmediately
74 public HMMFile(HiddenMarkovModel markov)
80 * Returns the HMM produced by reading in a HMMER3 file.
84 public HiddenMarkovModel getHMM()
90 * Sets the HMM used in this file.
94 public void setHMM(HiddenMarkovModel model)
100 * Gets the name of the hidden Markov model.
104 public String getName()
106 return hmm.getName();
110 * Reads the data from HMM file into the HMM field on this object.
112 * @throws IOException
115 public void parse() throws IOException
117 parseFileProperties(dataIn);
122 * Reads the data from HMM file into the HMM field on this object.
124 * @throws IOException
127 public void parse(BufferedReader br) throws IOException
129 parseFileProperties(br);
136 * Imports the file properties from a HMMER3 file.
139 * The buffered reader used to read in the file.
140 * @throws IOException
142 void parseFileProperties(BufferedReader input) throws IOException
144 boolean readingFile = true;
145 hmm.setFileHeader(input.readLine());
146 String line = input.readLine();
151 Scanner parser = new Scanner(line);
152 String next = parser.next();
153 if ("HMM".equals(next)) // indicates start of HMM data (end of file
157 hmm.fillSymbols(parser);
158 numberOfSymbols = hmm.getNumberOfSymbols();
160 else if ("STATS".equals(next))
166 value = parser.next() + SPACE + SPACE + parser.next();
167 hmm.addFileProperty(key, value);
172 String value = parser.next();
173 while (parser.hasNext())
175 value = value + SPACE + parser.next();
177 hmm.addFileProperty(key, value);
181 line = input.readLine();
191 * Parses the model data from the HMMER3 file
194 * The buffered reader used to read the file.
195 * @throws IOException
197 void parseModel(BufferedReader input) throws IOException
199 String line = input.readLine();
201 while (!"//".equals(line))
203 hmm.getNodes().add(new HMMNode());
205 Scanner matchReader = new Scanner(line);
206 next = matchReader.next();
207 if (next.equals(COMPO) || node > 0)
209 // stores match emission line in list
210 List<Double> matches = new ArrayList<>();
211 matches = fillList(matchReader, numberOfSymbols);
212 hmm.getNodes().get(node).setMatchEmissions(matches);
215 parseAnnotations(matchReader, node);
219 // stores insert emission line in list
220 line = input.readLine();
221 Scanner insertReader = new Scanner(line);
222 List<Double> inserts = new ArrayList<>();
223 inserts = fillList(insertReader, numberOfSymbols);
224 hmm.getNodes().get(node).setInsertEmissions(inserts);
225 insertReader.close();
227 // stores state transition line in list
228 line = input.readLine();
229 Scanner transitionReader = new Scanner(line);
230 List<Double> transitions = new ArrayList<>();
231 transitions = fillList(transitionReader, NUMBER_OF_TRANSITIONS);
232 hmm.getNodes().get(node).setStateTransitions(transitions);
233 transitionReader.close();
234 line = input.readLine();
241 * Parses the annotations on the match emission line.
244 * The scanner which is processing match emission line.
246 * The index of node which is being scanned.
248 void parseAnnotations(Scanner scanner, int index)
250 if (hmm.mapIsActive())
253 column = scanner.nextInt();
254 hmm.getNodes().get(index).setAlignmentColumn(column);
255 hmm.getNodeLookup().put(column, index);
262 if (scanner.hasNext())
265 consensusR = charValue(scanner.next());
266 hmm.getNodes().get(index).setConsensusResidue(consensusR);
269 if (scanner.hasNext())
272 reference = charValue(scanner.next());
273 hmm.getNodes().get(index).setReferenceAnnotation(reference);
276 if (scanner.hasNext())
279 value = charValue(scanner.next());
280 hmm.getNodes().get(index).setMaskValue(value);
282 if (scanner.hasNext())
285 consensusS = charValue(scanner.next());
286 hmm.getNodes().get(index).setConsensusStructure(consensusS);
293 * Fills a list of doubles based on an input line.
296 * The scanner for the line containing the data to be transferred to
298 * @param numberOfElements
299 * The number of elements in the list to be filled.
300 * @return filled list Returns the list of doubles.
302 static List<Double> fillList(Scanner input,
303 int numberOfElements)
305 List<Double> list = new ArrayList<>();
306 for (int i = 0; i < numberOfElements; i++)
309 String next = input.next();
310 if (next.contains("*")) // state transitions to or from delete states
311 // occasionally have values of -infinity. These
312 // values are represented by an * in the .hmm
315 list.add(Double.NEGATIVE_INFINITY);
319 double prob = Double.valueOf(next);
320 prob = Math.pow(Math.E, -prob);
329 * Writes a HMM to a file/
331 * @param exportLocation
332 * Filename, URL or Pasted String to write to.
333 * @throws FileNotFoundException
334 * @throws UnsupportedEncodingException
338 public void exportFile(String exportLocation) throws IOException
340 PrintWriter writer = new PrintWriter(exportLocation);
341 appendFileProperties(writer);
343 writer.println("//");
350 * Returns a string to be added to the StringBuilder containing the entire
353 * @param initialColumnSeparation
354 * The initial whitespace separation between the left side of the
355 * file and first character.
356 * @param columnSeparation
357 * The separation between subsequent data entries.
359 * The list fo data to be added to the String.
362 String addData(int initialColumnSeparation,
363 int columnSeparation, List<String> data)
367 for (String value : data)
371 line += String.format("%" + initialColumnSeparation + "s", value);
375 line += String.format("%" + columnSeparation + "s", value);
383 * Converts list of characters into a list of Strings.
386 * @return Returns the list of Strings.
388 List<String> charListToStringList(List<Character> list)
390 List<String> strList = new ArrayList<>();
391 for (char value : list)
393 String strValue = Character.toString(value);
394 strList.add(strValue);
400 * Converts a list of doubles into a list of Strings, rounded to the nearest
404 * @param noOfDecimals
407 List<String> doubleListToStringList(List<Double> list)
409 List<String> strList = new ArrayList<>();
410 for (double value : list)
415 strValue = String.format("%.5f", value);
418 else if (value == -0.00000d)
420 strValue = "0.00000";
427 strList.add(strValue);
433 * Converts a primitive array of Strings to a list of Strings.
438 List<String> stringArrayToStringList(String[] array)
440 List<String> list = new ArrayList<>();
441 for (String value : array)
450 * Appends the hidden Markov model data to the StringBuilder containing the
454 * The StringBuilder containing the output.
456 void appendModel(PrintWriter writer)
458 String symbolLine = "HMM";
459 List<Character> charSymbols = hmm.getSymbols();
460 List<String> strSymbols;
461 strSymbols = charListToStringList(charSymbols);
462 symbolLine += addData(11, 9, strSymbols);
463 writer.println(symbolLine);
464 writer.println(TRANSITIONTYPELINE);
466 int length = hmm.getLength();
468 for (int node = 0; node <= length; node++)
473 matchLine = String.format("%7s", "COMPO");
477 matchLine = String.format("%7s", node);
480 List<String> strMatches;
481 List<Double> doubleMatches;
482 doubleMatches = convertListToLogSpace(
483 hmm.getNode(node).getMatchEmissions());
484 strMatches = doubleListToStringList(doubleMatches);
485 matchLine += addData(10, 9, strMatches);
490 matchLine += SPACE + (hmm.getNodeAlignmentColumn(node) + 1);
491 matchLine += SPACE + hmm.getConsensusResidue(node);
492 matchLine += SPACE + hmm.getReferenceAnnotation(node);
493 if (hmm.getFileHeader().contains("HMMER3/f"))
495 matchLine += SPACE + hmm.getMaskedValue(node);
496 matchLine += SPACE + hmm.getConsensusStructure(node);
501 writer.println(matchLine);
503 String insertLine = EMPTY;
504 List<String> strInserts;
505 List<Double> doubleInserts;
506 doubleInserts = convertListToLogSpace(
507 hmm.getNode(node).getInsertEmissions());
508 strInserts = doubleListToStringList(doubleInserts);
509 insertLine += addData(17, 9, strInserts);
511 writer.println(insertLine);
513 String transitionLine = EMPTY;
514 List<String> strTransitions;
515 List<Double> doubleTransitions;
516 doubleTransitions = convertListToLogSpace(
517 hmm.getNode(node).getStateTransitions());
518 strTransitions = doubleListToStringList(doubleTransitions);
519 transitionLine += addData(17, 9, strTransitions);
521 writer.println(transitionLine);
526 * Appends the hidden Markov model file properties to the StringBuilder
527 * containing the output
530 * The StringBuilder containing the output.
532 void appendFileProperties(PrintWriter writer)
536 writer.println(hmm.getFileHeader());
538 line = String.format("%-5s %1s", "NAME", hmm.getName());
539 writer.println((line));
541 if (hmm.getAccessionNumber() != null)
543 line = String.format("%-5s %1s", "ACC", hmm.getAccessionNumber());
544 writer.println((line));
547 if (hmm.getDescription() != null)
549 line = String.format("%-5s %1s", "DESC", hmm.getDescription());
550 writer.println((line));
552 line = String.format("%-5s %1s", "LENG", hmm.getLength());
553 writer.println((line));
555 if (hmm.getMaxInstanceLength() != null)
557 line = String.format("%-5s %1s", "MAXL", hmm.getMaxInstanceLength());
558 writer.println((line));
560 line = String.format("%-5s %1s", "ALPH", hmm.getAlphabetType());
561 writer.println((line));
566 status = hmm.referenceAnnotationIsActive();
567 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
568 line = String.format("%-5s %1s", "RF",
570 writer.println((line));
572 status = hmm.maskValueIsActive();
573 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
574 line = String.format("%-5s %1s", "MM",
576 writer.println((line));
578 status = hmm.consensusResidueIsActive();
579 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
580 line = String.format("%-5s %1s", "CONS",
582 writer.println((line));
584 status = hmm.consensusStructureIsActive();
585 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
586 line = String.format("%-5s %1s", "CS",
588 writer.println((line));
590 status = hmm.mapIsActive();
591 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
592 line = String.format("%-5s %1s", "MAP",
594 writer.println((line));
597 if (hmm.getDate() != null)
599 line = String.format("%-5s %1s", "DATE", hmm.getDate());
600 writer.println((line));
602 if (hmm.getNumberOfSequences() != null)
604 line = String.format("%-5s %1s", "NSEQ", hmm.getNumberOfSequences());
605 writer.println((line));
607 if (hmm.getEffectiveNumberOfSequences() != null)
609 line = String.format("%-5s %1s", "EFFN",
610 hmm.getEffectiveNumberOfSequences());
611 writer.println((line));
613 if (hmm.getCheckSum() != null)
615 line = String.format("%-5s %1s", "CKSUM", hmm.getCheckSum());
616 writer.println((line));
618 if (hmm.getGatheringThreshold() != null)
620 line = String.format("%-5s %1s", "GA", hmm.getGatheringThreshold());
621 writer.println((line));
624 if (hmm.getTrustedCutoff() != null)
626 line = String.format("%-5s %1s", "TC", hmm.getTrustedCutoff());
627 writer.println((line));
629 if (hmm.getNoiseCutoff() != null)
631 line = String.format("%-5s %1s", "NC", hmm.getNoiseCutoff());
632 writer.println((line));
634 if (hmm.getMSV() != null)
636 line = String.format("%-19s %18s", "STATS LOCAL MSV", hmm.getMSV());
637 writer.println((line));
639 line = String.format("%-19s %18s", "STATS LOCAL VITERBI",
641 writer.println((line));
643 line = String.format("%-19s %18s", "STATS LOCAL FORWARD",
645 writer.println((line));
651 * Returns the char value of a single lettered String.
656 char charValue(String string)
659 character = string.charAt(0);
665 public String print(SequenceI[] seqs, boolean jvsuffix)
672 * Converts the probabilities contained in a list into log space.
676 List<Double> convertListToLogSpace(List<Double> list)
679 List<Double> convertedList = new ArrayList<>();
680 for (int i = 0; i < list.size(); i++)
682 double prob = list.get(i);
683 double logProb = -1 * Math.log(prob);
685 convertedList.add(logProb);
687 return convertedList;