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);
116 * Imports the file properties from a HMMER3 file.
119 * The buffered reader used to read in the file.
120 * @throws IOException
122 void parseFileProperties(BufferedReader input) throws IOException
124 boolean readingFile = true;
125 fileHeader = input.readLine();
126 String line = input.readLine();
131 Scanner parser = new Scanner(line);
132 String next = parser.next();
133 if ("HMM".equals(next)) // indicates start of HMM data (end of file
137 hmm.fillSymbols(parser);
138 numberOfSymbols = hmm.getNumberOfSymbols();
140 else if ("STATS".equals(next))
146 value = parser.next() + SPACE + SPACE + parser.next();
147 hmm.addFileProperty(key, value);
152 String value = parser.next();
153 while (parser.hasNext())
155 value = value + SPACE + parser.next();
157 hmm.addFileProperty(key, value);
161 line = input.readLine();
171 * Parses the model data from the HMMER3 file
174 * The buffered reader used to read the file.
175 * @throws IOException
177 void parseModel(BufferedReader input) throws IOException
179 for (int i = 0; i < hmm.getLength() + 1; i++)
181 hmm.getNodes().add(new HMMNode());
184 line = input.readLine();
185 Scanner matchReader = new Scanner(line);
186 next = matchReader.next();
187 if (next.equals(COMPO) || i > 0)
189 // stores match emission line in list
190 List<Double> matches = new ArrayList<>();
191 matches = fillList(matchReader, numberOfSymbols);
192 hmm.getNodes().get(i).setMatchEmissions(matches);
195 parseAnnotations(matchReader, i);
199 // stores insert emission line in list
200 line = input.readLine();
201 Scanner insertReader = new Scanner(line);
202 List<Double> inserts = new ArrayList<>();
203 inserts = fillList(insertReader, numberOfSymbols);
204 hmm.getNodes().get(i).setInsertEmissions(inserts);
205 insertReader.close();
207 // stores state transition line in list
208 line = input.readLine();
209 Scanner transitionReader = new Scanner(line);
210 List<Double> transitions = new ArrayList<>();
211 transitions = fillList(transitionReader, NUMBER_OF_TRANSITIONS);
212 hmm.getNodes().get(i).setStateTransitions(transitions);
213 transitionReader.close();
219 * Parses the annotations on the match emission line.
222 * The scanner which is processing match emission line.
224 * The index of node which is being scanned.
226 void parseAnnotations(Scanner scanner, int index)
228 if (hmm.mapIsActive())
231 column = scanner.nextInt();
232 hmm.getNodes().get(index).setAlignmentColumn(column);
233 hmm.getNodeLookup().put(column, index);
241 consensusR = charValue(scanner.next());
242 hmm.getNodes().get(index).setConsensusResidue(consensusR);
245 reference = charValue(scanner.next());
246 hmm.getNodes().get(index).setReferenceAnnotation(reference);
250 value = charValue(scanner.next());
251 hmm.getNodes().get(index).setMaskValue(value);
254 consensusS = charValue(scanner.next());
255 hmm.getNodes().get(index).setConsensusStructure(consensusS);
260 * Fills a list of doubles based on an input line.
263 * The scanner for the line containing the data to be transferred to
265 * @param numberOfElements
266 * The number of elements in the list to be filled.
267 * @return filled list Returns the list of doubles.
269 static List<Double> fillList(Scanner input,
270 int numberOfElements)
272 List<Double> list = new ArrayList<>();
273 for (int i = 0; i < numberOfElements; i++)
276 String next = input.next();
277 if (next.contains("*")) // state transitions to or from delete states
278 // occasionally have values of -infinity. These
279 // values are represented by an * in the .hmm
282 list.add(Double.NEGATIVE_INFINITY);
286 double prob = Double.valueOf(next);
287 prob = Math.pow(Math.E, -prob);
296 * Writes a HMM to a file/
298 * @param exportLocation
299 * Filename, URL or Pasted String to write to.
300 * @throws FileNotFoundException
301 * @throws UnsupportedEncodingException
305 public void exportFile(String exportLocation) throws IOException
307 StringBuilder file = new StringBuilder();
308 appendFileProperties(file);
312 PrintWriter output = new PrintWriter(exportLocation);
319 * Returns a string to be added to the StringBuilder containing the entire
322 * @param initialColumnSeparation
323 * The initial whitespace separation between the left side of the
324 * file and first character.
325 * @param columnSeparation
326 * The separation between subsequent data entries.
328 * The list fo data to be added to the String.
331 String addData(int initialColumnSeparation,
332 int columnSeparation, List<String> data)
336 for (String value : data)
340 line += String.format("%" + initialColumnSeparation + "s", value);
344 line += String.format("%" + columnSeparation + "s", value);
352 * Converts list of characters into a list of Strings.
355 * @return Returns the list of Strings.
357 List<String> charListToStringList(List<Character> list)
359 List<String> strList = new ArrayList<>();
360 for (char value : list)
362 String strValue = Character.toString(value);
363 strList.add(strValue);
369 * Converts a list of doubles into a list of Strings, rounded to the nearest
373 * @param noOfDecimals
376 List<String> doubleListToStringList(List<Double> list)
378 List<String> strList = new ArrayList<>();
379 for (double value : list)
384 strValue = String.format("%.5f", value);
387 else if (value == -0.00000d)
389 strValue = "0.00000";
396 strList.add(strValue);
402 * Converts a primitive array of Strings to a list of Strings.
407 List<String> stringArrayToStringList(String[] array)
409 List<String> list = new ArrayList<>();
410 for (String value : array)
419 * Appends the hidden Markov model data to the StringBuilder containing the
423 * The StringBuilder containing the output.
425 void appendModel(StringBuilder file)
427 String symbolLine = "HMM";
428 List<Character> charSymbols = hmm.getSymbols();
429 List<String> strSymbols;
430 strSymbols = charListToStringList(charSymbols);
431 symbolLine += addData(11, 9, strSymbols);
432 file.append(symbolLine + NEW_LINE);
433 file.append(TRANSITIONTYPELINE + NEW_LINE);
435 int length = hmm.getLength();
437 for (int node = 0; node <= length; node++)
442 matchLine = String.format("%7s", "COMPO");
446 matchLine = String.format("%7s", node);
449 List<String> strMatches;
450 List<Double> doubleMatches;
451 doubleMatches = hmm.getNode(node).getMatchEmissions();
452 convertListToLogSpace(doubleMatches);
453 strMatches = doubleListToStringList(doubleMatches);
454 matchLine += addData(10, 9, strMatches);
459 matchLine += SPACE + hmm.getNodeAlignmentColumn(node);
460 matchLine += SPACE + hmm.getConsensusResidue(node);
461 matchLine += SPACE + hmm.getReferenceAnnotation(node);
462 matchLine += SPACE + hmm.getMaskedValue(node);
463 matchLine += SPACE + hmm.getConsensusStructure(node);
467 file.append(matchLine + NEW_LINE);
469 String insertLine = EMPTY;
470 List<String> strInserts;
471 List<Double> doubleInserts;
472 doubleInserts = hmm.getNode(node).getInsertEmissions();
473 convertListToLogSpace(doubleInserts);
474 strInserts = doubleListToStringList(doubleInserts);
475 insertLine += addData(17, 9, strInserts);
477 file.append(insertLine + NEW_LINE);
479 String transitionLine = EMPTY;
480 List<String> strTransitions;
481 List<Double> doubleTransitions;
482 doubleTransitions = hmm.getNode(node).getStateTransitions();
483 convertListToLogSpace(doubleTransitions);
484 strTransitions = doubleListToStringList(doubleTransitions);
485 transitionLine += addData(17, 9, strTransitions);
487 file.append(transitionLine + NEW_LINE);
492 * Appends the hidden Markov model file properties to the StringBuilder
493 * containing the output
496 * The StringBuilder containing the output.
498 void appendFileProperties(StringBuilder file)
502 file.append(fileHeader + NEW_LINE);
504 line = String.format("%-5s %1s", "NAME", hmm.getName());
505 file.append((line + NEW_LINE));
507 if (hmm.getAccessionNumber() != null)
509 line = String.format("%-5s %1s", "ACC", hmm.getAccessionNumber());
510 file.append((line + NEW_LINE));
513 if (hmm.getDescription() != null)
515 line = String.format("%-5s %1s", "DESC", hmm.getDescription());
516 file.append((line + NEW_LINE));
518 line = String.format("%-5s %1s", "LENG", hmm.getLength());
519 file.append((line + NEW_LINE));
521 if (hmm.getMaxInstanceLength() != null)
523 line = String.format("%-5s %1s", "MAXL", hmm.getMaxInstanceLength());
524 file.append((line + NEW_LINE));
526 line = String.format("%-5s %1s", "ALPH", hmm.getAlphabetType());
527 file.append((line + NEW_LINE));
532 status = hmm.referenceAnnotationIsActive();
533 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
534 line = String.format("%-5s %1s", "RF",
536 file.append((line + NEW_LINE));
538 status = hmm.maskValueIsActive();
539 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
540 line = String.format("%-5s %1s", "MM",
542 file.append((line + NEW_LINE));
544 status = hmm.consensusResidueIsActive();
545 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
546 line = String.format("%-5s %1s", "CONS",
548 file.append((line + NEW_LINE));
550 status = hmm.consensusStructureIsActive();
551 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
552 line = String.format("%-5s %1s", "CS",
554 file.append((line + NEW_LINE));
556 status = hmm.mapIsActive();
557 statusStr = HiddenMarkovModel.findStringFromBoolean(status);
558 line = String.format("%-5s %1s", "MAP",
560 file.append((line + NEW_LINE));
563 if (hmm.getDate() != null)
565 line = String.format("%-5s %1s", "DATE", hmm.getDate());
566 file.append((line + NEW_LINE));
568 if (hmm.getNumberOfSequences() != null)
570 line = String.format("%-5s %1s", "NSEQ", hmm.getNumberOfSequences());
571 file.append((line + NEW_LINE));
573 if (hmm.getEffectiveNumberOfSequences() != null)
575 line = String.format("%-5s %1s", "EFFN",
576 hmm.getEffectiveNumberOfSequences());
577 file.append((line + NEW_LINE));
579 if (hmm.getCheckSum() != null)
581 line = String.format("%-5s %1s", "CKSUM", hmm.getCheckSum());
582 file.append((line + NEW_LINE));
584 if (hmm.getGatheringThreshold() != null)
586 line = String.format("%-5s %1s", "GA", hmm.getGatheringThreshold());
587 file.append((line + NEW_LINE));
590 if (hmm.getTrustedCutoff() != null)
592 line = String.format("%-5s %1s", "TC", hmm.getTrustedCutoff());
593 file.append((line + NEW_LINE));
595 if (hmm.getNoiseCutoff() != null)
597 line = String.format("%-5s %1s", "NC", hmm.getNoiseCutoff());
598 file.append((line + NEW_LINE));
600 if (hmm.getMSV() != null)
602 line = String.format("%-19s %18s", "STATS LOCAL MSV", hmm.getMSV());
603 file.append((line + NEW_LINE));
605 line = String.format("%-19s %18s", "STATS LOCAL VITERBI",
607 file.append((line + NEW_LINE));
609 line = String.format("%-19s %18s", "STATS LOCAL FORWARD",
611 file.append((line + NEW_LINE));
617 * Returns the char value of a single lettered String.
622 char charValue(String string)
625 character = string.charAt(0);
631 public String print(SequenceI[] seqs, boolean jvsuffix)
638 * Converts the probabilities contained in a list into log space.
642 void convertListToLogSpace(List<Double> list)
645 for (int i = 0; i < list.size(); i++)
647 double prob = list.get(i);
648 double logProb = -1 * Math.log(prob);
650 list.set(i, logProb);