3 import jalview.datamodel.HMMNode;
4 import jalview.datamodel.HiddenMarkovModel;
5 import jalview.datamodel.SequenceI;
7 import java.io.BufferedReader;
9 import java.io.FileNotFoundException;
10 import java.io.IOException;
11 import java.io.PrintWriter;
12 import java.io.UnsupportedEncodingException;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Scanner;
19 * Adds capability to read in and write out HMMER3 files. Currently only supports HMMER3/f.
25 public class HMMFile extends AlignFile
26 implements AlignmentFileReaderI, AlignmentFileWriterI
28 // HMM to store file data
29 private HiddenMarkovModel hmm = new HiddenMarkovModel();
31 // number of possible transitions
32 private final int NUMBER_OF_TRANSITIONS = 7;
34 private final String NEW_LINE = "\n";
36 //number of symbols in the alphabet used in the hidden Markov model
39 private final String SPACE = " ";
41 private final String COMPO = "COMPO";
43 private final String EMPTY = "";
45 //This is a line that needs to be added to each HMMER� file. It is purely for readability.
46 private static final String TRANSITIONTYPELINE = "m->m m->i m->d i->m i->i d->m d->d";
49 * Constructor for HMMFile, parses immediately
54 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 - 1);
255 hmm.getNodeLookup().put(column - 1, 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 * Writes a HMM to a file/
352 * @param exportLocation
353 * Filename, URL or Pasted String to write to.
354 * @throws FileNotFoundException
355 * @throws UnsupportedEncodingException
359 public void exportFile(File exportLocation) throws IOException
361 PrintWriter writer = new PrintWriter(exportLocation);
362 appendFileProperties(writer);
364 writer.println("//");
371 * Returns a string to be added to the StringBuilder containing the entire
374 * @param initialColumnSeparation
375 * The initial whitespace separation between the left side of the
376 * file and first character.
377 * @param columnSeparation
378 * The separation between subsequent data entries.
380 * The list fo data to be added to the String.
383 String addData(int initialColumnSeparation,
384 int columnSeparation, List<String> data)
388 for (String value : data)
392 line += String.format("%" + initialColumnSeparation + "s", value);
396 line += String.format("%" + columnSeparation + "s", value);
404 * Converts list of characters into a list of Strings.
407 * @return Returns the list of Strings.
409 List<String> charListToStringList(List<Character> list)
411 List<String> strList = new ArrayList<>();
412 for (char value : list)
414 String strValue = Character.toString(value);
415 strList.add(strValue);
421 * Converts a list of doubles into a list of Strings, rounded to the nearest
425 * @param noOfDecimals
428 List<String> doubleListToStringList(List<Double> list)
430 List<String> strList = new ArrayList<>();
431 for (double value : list)
436 strValue = String.format("%.5f", value);
439 else if (value == -0.00000d)
441 strValue = "0.00000";
448 strList.add(strValue);
454 * Converts a primitive array of Strings to a list of Strings.
459 List<String> stringArrayToStringList(String[] array)
461 List<String> list = new ArrayList<>();
462 for (String value : array)
471 * Appends the hidden Markov model data to the StringBuilder containing the
475 * The StringBuilder containing the output.
477 void appendModel(PrintWriter writer)
479 String symbolLine = "HMM";
480 List<Character> charSymbols = hmm.getSymbols();
481 List<String> strSymbols;
482 strSymbols = charListToStringList(charSymbols);
483 symbolLine += addData(11, 9, strSymbols);
484 writer.println(symbolLine);
485 writer.println(TRANSITIONTYPELINE);
487 int length = hmm.getLength();
489 for (int node = 0; node <= length; node++)
494 matchLine = String.format("%7s", "COMPO");
498 matchLine = String.format("%7s", node);
501 List<String> strMatches;
502 List<Double> doubleMatches;
503 doubleMatches = convertListToLogSpace(
504 hmm.getNode(node).getMatchEmissions());
505 strMatches = doubleListToStringList(doubleMatches);
506 matchLine += addData(10, 9, strMatches);
511 matchLine += SPACE + (hmm.getNodeAlignmentColumn(node) + 1);
512 matchLine += SPACE + hmm.getConsensusResidue(node);
513 matchLine += SPACE + hmm.getReferenceAnnotation(node);
514 if (hmm.getFileHeader().contains("HMMER3/f"))
516 matchLine += SPACE + hmm.getMaskedValue(node);
517 matchLine += SPACE + hmm.getConsensusStructure(node);
522 writer.println(matchLine);
524 String insertLine = EMPTY;
525 List<String> strInserts;
526 List<Double> doubleInserts;
527 doubleInserts = convertListToLogSpace(
528 hmm.getNode(node).getInsertEmissions());
529 strInserts = doubleListToStringList(doubleInserts);
530 insertLine += addData(17, 9, strInserts);
532 writer.println(insertLine);
534 String transitionLine = EMPTY;
535 List<String> strTransitions;
536 List<Double> doubleTransitions;
537 doubleTransitions = convertListToLogSpace(
538 hmm.getNode(node).getStateTransitions());
539 strTransitions = doubleListToStringList(doubleTransitions);
540 transitionLine += addData(17, 9, strTransitions);
542 writer.println(transitionLine);
547 * Appends the hidden Markov model file properties to the StringBuilder
548 * containing the output
551 * The StringBuilder containing the output.
553 void appendFileProperties(PrintWriter writer)
557 writer.println(hmm.getFileHeader());
559 line = String.format("%-5s %1s", "NAME", hmm.getName());
560 writer.println((line));
562 if (hmm.getAccessionNumber() != null)
564 line = String.format("%-5s %1s", "ACC", hmm.getAccessionNumber());
565 writer.println((line));
568 if (hmm.getDescription() != null)
570 line = String.format("%-5s %1s", "DESC", hmm.getDescription());
571 writer.println((line));
573 line = String.format("%-5s %1s", "LENG", hmm.getLength());
574 writer.println((line));
576 if (hmm.getMaxInstanceLength() != null)
578 line = String.format("%-5s %1s", "MAXL", hmm.getMaxInstanceLength());
579 writer.println((line));
581 line = String.format("%-5s %1s", "ALPH", hmm.getAlphabetType());
582 writer.println((line));
587 status = hmm.referenceAnnotationIsActive();
588 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
589 line = String.format("%-5s %1s", "RF",
591 writer.println((line));
593 status = hmm.maskValueIsActive();
594 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
595 line = String.format("%-5s %1s", "MM",
597 writer.println((line));
599 status = hmm.consensusResidueIsActive();
600 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
601 line = String.format("%-5s %1s", "CONS",
603 writer.println((line));
605 status = hmm.consensusStructureIsActive();
606 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
607 line = String.format("%-5s %1s", "CS",
609 writer.println((line));
611 status = hmm.mapIsActive();
612 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
613 line = String.format("%-5s %1s", "MAP",
615 writer.println((line));
618 if (hmm.getDate() != null)
620 line = String.format("%-5s %1s", "DATE", hmm.getDate());
621 writer.println((line));
623 if (hmm.getNumberOfSequences() != null)
625 line = String.format("%-5s %1s", "NSEQ", hmm.getNumberOfSequences());
626 writer.println((line));
628 if (hmm.getEffectiveNumberOfSequences() != null)
630 line = String.format("%-5s %1s", "EFFN",
631 hmm.getEffectiveNumberOfSequences());
632 writer.println((line));
634 if (hmm.getCheckSum() != null)
636 line = String.format("%-5s %1s", "CKSUM", hmm.getCheckSum());
637 writer.println((line));
639 if (hmm.getGatheringThreshold() != null)
641 line = String.format("%-5s %1s", "GA", hmm.getGatheringThreshold());
642 writer.println((line));
645 if (hmm.getTrustedCutoff() != null)
647 line = String.format("%-5s %1s", "TC", hmm.getTrustedCutoff());
648 writer.println((line));
650 if (hmm.getNoiseCutoff() != null)
652 line = String.format("%-5s %1s", "NC", hmm.getNoiseCutoff());
653 writer.println((line));
655 if (hmm.getMSV() != null)
657 line = String.format("%-19s %18s", "STATS LOCAL MSV", hmm.getMSV());
658 writer.println((line));
660 line = String.format("%-19s %18s", "STATS LOCAL VITERBI",
662 writer.println((line));
664 line = String.format("%-19s %18s", "STATS LOCAL FORWARD",
666 writer.println((line));
672 * Returns the char value of a single lettered String.
677 char charValue(String string)
680 character = string.charAt(0);
686 public String print(SequenceI[] seqs, boolean jvsuffix)
693 * Converts the probabilities contained in a list into log space.
697 List<Double> convertListToLogSpace(List<Double> list)
700 List<Double> convertedList = new ArrayList<>();
701 for (int i = 0; i < list.size(); i++)
703 double prob = list.get(i);
704 double logProb = -1 * Math.log(prob);
706 convertedList.add(logProb);
708 return convertedList;