9d6066d9082bc46281391d9e185083a658c65628
[jalview.git] / src / jalview / util / HMMProbabilityDistributionAnalyser.java
1 package jalview.util;
2
3 import jalview.datamodel.HiddenMarkovModel;
4 import jalview.datamodel.SequenceI;
5 import jalview.io.DataSourceType;
6 import jalview.io.FileParse;
7 import jalview.io.HMMFile;
8 import jalview.io.StockholmFile;
9 import jalview.schemes.ResidueProperties;
10
11 import java.io.BufferedReader;
12 import java.io.File;
13 import java.io.FileNotFoundException;
14 import java.io.FileReader;
15 import java.io.IOException;
16 import java.io.PrintWriter;
17 import java.util.ArrayList;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Scanner;
22 import java.util.Vector;
23
24 public class HMMProbabilityDistributionAnalyser
25 {
26
27   Vector<SequenceI> sequences;
28
29   HiddenMarkovModel hmm;
30
31   List<ArrayList<Double>> raw = new ArrayList<>();
32
33   Map<String, Double> binned = new HashMap<>();
34
35   final static String FAMILIES = "C:/Users/TZVanaalten/Pfam-A.full";
36
37   final static String HMMS = "H:/Desktop/PFAM/HMMs/Pfam-A.hmm";
38
39   final static String RAW = "/Raw.csv";
40
41   final static String BINNED = "/Binned.csv";
42
43   final static double SCALE = 100000;
44
45   int currentFilePosition = 0;
46
47   final static String NL = "\n";
48
49   String currentFolder;
50
51   public void setFolder(String path)
52   {
53     currentFolder = path;
54   }
55
56   public void moveToFile(int index, BufferedReader br) throws IOException
57   {
58     for (int i = 0; i < index; i++)
59     {
60       String line = br.readLine();
61       while (!"//".equals(line))
62       {
63         line = br.readLine();
64       }
65     }
66
67   }
68   /**
69    * Analyses probability data
70    * 
71    * @param args
72    * @throws IOException
73    */
74   public void run(int increments) throws IOException
75   {
76
77     readPreviousData(currentFolder);
78
79     BufferedReader posReader = new BufferedReader(
80             new FileReader(currentFolder + "/CurrentPosition.txt"));
81     String line = posReader.readLine();
82     posReader.close();
83     currentFilePosition = Integer.parseInt(line);
84
85     BufferedReader inputSTO = new BufferedReader(
86             new FileReader(FAMILIES));
87     BufferedReader inputHMM = new BufferedReader(
88             new FileReader(HMMS));
89
90     moveToFile(currentFilePosition, inputHMM);
91     moveToFile(currentFilePosition, inputSTO);
92
93     int filesRead = 0;
94     while (filesRead < increments)
95     {
96       FileParse parserSTO = new FileParse(inputSTO, "",
97               DataSourceType.FILE);
98       readStockholm(parserSTO);
99
100       FileParse parserHMM = new FileParse(inputHMM, "",
101               DataSourceType.FILE);
102       readHMM(parserHMM);
103
104       if (hmm.getAlphabetType().equals("amino"))
105       {
106         int count = countValidResidues();
107         processData(count);
108         filesRead++;
109       }
110       currentFilePosition++;
111     }
112
113     PrintWriter p = new PrintWriter(
114             new File(currentFolder + "/CurrentPosition"));
115     p.print(currentFilePosition);
116     p.close();
117     exportData(currentFolder);
118     raw.clear();
119     binned.clear();
120
121   }
122
123   public void readPreviousData(String source) throws IOException
124   {
125     readBinned(source);
126     readRaw(source);
127   }
128
129   public void readBinned(String source) throws IOException
130   {
131     BufferedReader input = new BufferedReader(
132             new FileReader(source + BINNED));
133     String line = input.readLine();
134     while (!("".equals(line) || line == null))
135     {
136       binned = new HashMap<>();
137       Scanner scanner = new Scanner(line);
138       scanner.useDelimiter(",");
139       binned.put(scanner.next(), scanner.nextDouble());
140       scanner.close();
141       line = input.readLine();
142     }
143
144     input.close();
145   }
146
147   public void readRaw(String source) throws IOException
148   {
149     BufferedReader input = new BufferedReader(new FileReader(source + RAW));
150     String line = input.readLine();
151     if (line == null)
152     {
153       input.close();
154       return;
155     }
156     Scanner numberScanner = new Scanner(line);
157     numberScanner.useDelimiter(",");
158     raw = new ArrayList<>();
159     while (numberScanner.hasNext())
160     {
161       numberScanner.next();
162       raw.add(new ArrayList<Double>());
163     }
164     numberScanner.close();
165
166     line = input.readLine();
167     while (!("".equals(line) || line == null))
168     {
169       Scanner scanner = new Scanner(line);
170       scanner.useDelimiter(",");
171
172       int i = 0;
173       while (scanner.hasNext())
174       {
175         String value;
176         value = scanner.next();
177         if (!value.equals("EMPTY"))
178         {
179           raw.get(i).add(Double.parseDouble(value));
180         }
181
182         i++;
183       }
184       scanner.close();
185       line = input.readLine();
186     }
187
188     input.close();
189   }
190
191   public int countValidResidues()
192   {
193     int count = 0;
194
195     for (int width = 0; width < sequences.size(); width++)
196     {
197       for (int length = 1; length < hmm.getLength(); length++)
198       {
199         char symbol;
200         int alignPos;
201         alignPos = hmm.getNodeAlignmentColumn(length);
202
203         symbol = sequences.get(width).getCharAt(alignPos);
204         if (ResidueProperties.aminoBackgroundFrequencies
205                 .containsKey(symbol))
206         {
207           count++;
208         }
209       }
210     }
211
212     return count;
213   }
214
215   public void processData(int count)
216   {
217
218     raw.add(new ArrayList<Double>());
219     int rawPos = raw.size() - 1;
220     for (int width = 0; width < sequences.size(); width++)
221     {
222       for (int length = 1; length < hmm.getLength(); length++)
223       {
224         char symbol;
225         int alignPos;
226         alignPos = hmm.getNodeAlignmentColumn(length);
227
228         symbol = sequences.get(width).getCharAt(alignPos);
229         if (ResidueProperties.aminoBackgroundFrequencies
230                 .containsKey(symbol))
231         {
232
233           Double prob;
234           Float bfreq;
235           Double llr;
236           prob = hmm.getMatchEmissionProbability(alignPos, symbol);
237           bfreq = ResidueProperties.aminoBackgroundFrequencies.get(symbol);
238           llr = Math.log(prob / bfreq);
239           raw.get(rawPos).add(llr);
240           String output;
241           output = String.format("%.1f", llr);
242           if ("-0.0".equals(output))
243           {
244             output = "0.0";
245           }
246           if (binned.containsKey(output))
247           {
248             double prev = binned.get(output);
249             prev += (SCALE / count);
250             binned.put(output, prev);
251
252           }
253           else
254           {
255             binned.put(output, SCALE / count);
256           }
257         }
258       }
259     }
260   }
261
262
263   public void readStockholm(FileParse source) throws IOException
264   {
265     StockholmFile file = new StockholmFile(source);
266     file.parse();
267     sequences = file.getSeqs();
268   }
269
270   public void readHMM(FileParse source) throws IOException
271   {
272
273     HMMFile file = new HMMFile(source);
274     file.parse();
275     hmm = file.getHMM();
276
277   }
278
279   public void exportData(String location) throws FileNotFoundException
280   {
281     PrintWriter writerBin = new PrintWriter(new File(location + BINNED));
282     for (Map.Entry<String, Double> entry : binned.entrySet())
283     {
284       writerBin.println(entry.getKey() + "," + entry.getValue());
285     }
286     writerBin.close();
287
288     PrintWriter writerRaw = new PrintWriter(new File(location + RAW));
289
290     StringBuilder identifier = new StringBuilder();
291
292     for (int i = 1; i < raw.size() + 1; i++)
293     {
294       identifier.append("Fam " + i + ",");
295     }
296
297     writerRaw.println(identifier);
298
299     boolean rowIsEmpty = false;
300     int row = 0;
301     while (!rowIsEmpty)
302     {
303       rowIsEmpty = true;
304       StringBuilder string = new StringBuilder();
305       for (int column = 0; column < raw.size(); column++)
306       {
307         if (raw.get(column).size() <= row)
308         {
309           string.append("EMPTY,");
310         }
311         else
312         {
313           string.append(raw.get(column).get(row) + ",");
314           rowIsEmpty = false;
315         }
316       }
317       row++;
318       writerRaw.println(string);
319     }
320     writerRaw.close();
321
322   }
323
324   public void printFam(int index) throws IOException
325   {
326     BufferedReader br = new BufferedReader(new FileReader(FAMILIES));
327
328     moveToFile(index, br);
329
330     String line = br.readLine();
331
332     while (!"//".equals(line))
333     {
334       System.out.println(line);
335       line = br.readLine();
336     }
337     System.out.println(line);
338     br.close();
339
340   }
341
342   public void printHMM(int index) throws IOException
343   {
344     BufferedReader br = new BufferedReader(new FileReader(HMMS));
345
346     moveToFile(index, br);
347
348     String line = br.readLine();
349
350     while (!"//".equals(line))
351     {
352       System.out.println(line);
353       line = br.readLine();
354     }
355     System.out.println(line);
356     br.close();
357
358   }
359
360   public void printFamToFile(int index) throws IOException
361   {
362     String name;
363
364     BufferedReader nameFinder = new BufferedReader(
365             new FileReader(FAMILIES));
366
367     moveToFile(index, nameFinder);
368
369     nameFinder.readLine();
370
371     Scanner scanner = new Scanner(nameFinder.readLine());
372     scanner.next();
373     scanner.next();
374     name = scanner.next();
375     scanner.close();
376
377     BufferedReader br = new BufferedReader(new FileReader(FAMILIES));
378
379     moveToFile(index, br);
380
381     String line = br.readLine();
382     PrintWriter writer = new PrintWriter(
383             currentFolder + "/" + name + ".sto");
384     while (!"//".equals(line))
385     {
386       writer.println(line);
387       line = br.readLine();
388     }
389     writer.println(line);
390     writer.close();
391     br.close();
392
393   }
394
395   public void printHMMToFile(int index) throws IOException
396   {
397
398     String name;
399
400     BufferedReader nameFinder = new BufferedReader(new FileReader(HMMS));
401
402     moveToFile(index, nameFinder);
403
404     nameFinder.readLine();
405
406     Scanner scanner = new Scanner(nameFinder.readLine());
407     name = scanner.next();
408     name = scanner.next();
409     scanner.close();
410
411     BufferedReader br = new BufferedReader(new FileReader(HMMS));
412
413     moveToFile(index, br);
414
415     String line = br.readLine();
416
417     PrintWriter writer = new PrintWriter(
418             currentFolder + "/" + name + ".hmm");
419     while (!"//".equals(line))
420     {
421       writer.println(line);
422       line = br.readLine();
423     }
424     writer.println(line);
425     writer.close();
426     br.close();
427
428   }
429   
430   public void clear() throws FileNotFoundException
431   {
432     PrintWriter pos = new PrintWriter(
433             currentFolder + "/CurrentPosition.txt");
434     pos.println("0");
435     
436     PrintWriter raw = new PrintWriter(currentFolder + RAW);
437     
438     PrintWriter bin = new PrintWriter(currentFolder + BINNED);
439     
440     pos.close();
441     bin.close();
442     raw.close();
443   }
444
445 }