Debian Codegraph @

edu/mit/compbio/ChromHMM/NestedEliminateInitialize.java

raw symbols SCIP
1 /**
2 * ChromHMM - automating chromatin state discovery and characterization
3 * Copyright (C) 2008-2012 Massachusetts Institute of Technology
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 **/
18 package edu.mit.compbio.ChromHMM;
19
20 import java.io.*;
21 import java.util.*;
22
23 public class NestedEliminateInitialize
24 {
25
26 /**
27 * Implements a procedure to generate a nested initialization based on state pruning
28 * The ChromHMM code was written by Jason Ernst
29 */
30
31 /**
32 * This is used to generate a set of nested models by pruning states from a high scoring model. This can be used as one heuristic to initialize model parameters
33 * to get a roughly comparable set of models across different number of states while biasing the learning procedure to avoid redundant or non-representative states.
34 * States are greedily pruned from the highest scoring model. The criteria to a prune a state is that it has the least impact on the total distance to the nearest
35 * remaining state for all the states in other models. If there is only one model, then distance to other states in that model are considered. By default euclidean
36 * distance for emission parameters is used, but there is an option to use the total correlation instead.
37 * szinputdir is the name of the directory containing model files to eliminate. Only files with prefix 'model_' in the directory are used.
38 * szoutput dir is the name of the output directory where the eliminated model files will go
39 * beuclid is true if euclidean distance should be used
40 */
41 public static void nestedEliminateInitialize(String szinputdir, String szoutputdir,boolean beuclid) throws IOException
42 {
43 int numcols = 0;
44 int nummodels = 0;
45
46 File inputdir = new File(szinputdir);
47 if (!inputdir.exists())
48 {
49 throw new IllegalArgumentException(szinputdir+" was not found!");
50 }
51
52 String[] files = inputdir.list();
53
54 double dbestlikelihood = Double.NEGATIVE_INFINITY;
55 String szmainfile="";
56
57 int nbestnumstates=-1;
58 int nbestmodel=-1;
59 char chbestorder='0';
60
61 HashMap hmNameToID = new HashMap();
62 boolean bfound = false;
63
64 for (int nfile = 0; nfile < files.length; nfile++)
65 {
66 //goes through all the files counting how many begin with model_
67 //also for the first found determines the number of marks
68 //and a mapping from marks to IDs
69
70 if ((files[nfile].startsWith("model_"))&&(!(new File(files[nfile])).isHidden()))
71 {
72 if (!bfound)
73 {
74 BufferedReader brfile = Util.getBufferedReader(szinputdir+"/"+files[nfile]);
75 String szLine;
76 numcols = 0;
77
78 while ((szLine = brfile.readLine())!= null)
79 {
80 if (szLine.startsWith("emission"))
81 {
82 StringTokenizer stemiss = new StringTokenizer(szLine,"\t");
83 stemiss.nextToken().trim();
84 stemiss.nextToken().trim();
85 stemiss.nextToken().trim();
86 String szmark = stemiss.nextToken().trim();
87
88 Object objInt = hmNameToID.get(szmark);
89 if (objInt ==null)
90 {
91 hmNameToID.put(szmark, Integer.valueOf(numcols));
92 numcols++;
93 }
94 }
95 }
96 brfile.close();
97 bfound = true;
98 }
99 nummodels++;
100 }
101 }
102
103 if (nummodels < 1)
104 {
105 throw new IllegalArgumentException("No models found in directory "+szinputdir);
106 }
107
108 double[][][] modelemissions = new double[nummodels][][];
109 int nmodel = 0;
110
111 for (int nfile = 0; nfile < files.length; nfile++)
112 {
113 //going through all the model files and loading in the emission parameters
114 //also recording the model with the best score
115
116 if ((files[nfile].startsWith("model_"))&&(!(new File(files[nfile])).isHidden()))
117 {
118 //assuming file
119 String szfile = files[nfile];
120
121 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+szfile);
122
123 String szheader = br.readLine();
124 if (szheader == null)
125 throw new IllegalArgumentException(szinputdir+"/"+szfile+" is empty!");
126 StringTokenizer stheader = new StringTokenizer(szheader,"\t ");
127 int numstates = Integer.parseInt(stheader.nextToken());
128 stheader.nextToken();
129 char chorder = stheader.nextToken().charAt(0); //order type
130 double dcurrlikelihood = Double.parseDouble(stheader.nextToken());
131
132 String szLine;
133 StringTokenizer st;
134
135 modelemissions[nmodel] = new double[numstates][numcols];
136 int ncount = 0;
137 while ((szLine = br.readLine())!=null)
138 {
139
140 if (szLine.startsWith("emissionprobs"))
141 {
142 st = new StringTokenizer(szLine,"\t");
143 st.nextToken().trim();
144 int nstate = Integer.parseInt(st.nextToken().trim())-1;
145 st.nextToken().trim();
146 String szmark = st.nextToken().trim();
147 Integer intMark = (Integer) hmNameToID.get(szmark);
148 int nmark = -1;
149 if (intMark == null)
150 {
151 throw new IllegalArgumentException(szmark+" not found in "+files[nfile]);
152 }
153 else
154 {
155 nmark = ((Integer) intMark).intValue();
156 }
157 String szbucket = st.nextToken().trim();
158 if (szbucket.equals("1"))
159 {
160 modelemissions[nmodel][nstate][nmark] = Double.parseDouble(st.nextToken().trim());
161 ncount++;
162 }
163 }
164 }
165 br.close();
166
167 if (ncount != (numstates*numcols))
168 {
169 throw new IllegalArgumentException(files[nfile]+" had "+ncount+" emission values while expecting "+(numstates*numcols));
170 }
171
172 if (dcurrlikelihood > dbestlikelihood)
173 {
174 dbestlikelihood = dcurrlikelihood;
175 nbestmodel = nmodel;
176 nbestnumstates = numstates;
177 chbestorder = chorder;
178 szmainfile = files[nfile];
179 }
180
181 nmodel++;
182 }
183 }
184
185 //storing the parameters for the best model
186 double[] bestprobinit = new double[nbestnumstates];
187 double[][] besttransitionprobs = new double[nbestnumstates][nbestnumstates];
188 ArrayList[] emissionsline = new ArrayList[nbestnumstates];
189
190 BufferedReader brfile = Util.getBufferedReader(szinputdir+"/"+szmainfile);
191 brfile.readLine();
192 for (int ni = 0; ni < bestprobinit.length; ni++)
193 {
194 String szinitline = brfile.readLine();
195 if (szinitline == null)
196 {
197 throw new IllegalArgumentException(szinputdir+"/"+szmainfile+" is missing lines!");
198 }
199 StringTokenizer st = new StringTokenizer(szinitline,"\t");
200 st.nextToken().trim();
201 st.nextToken().trim();
202 bestprobinit[ni] = Double.parseDouble(st.nextToken().trim());
203 }
204
205 for (int ni = 0; ni < nbestnumstates; ni++)
206 {
207 for (int nj = 0; nj < nbestnumstates; nj++)
208 {
209 String sztransitionline = brfile.readLine();
210 if (sztransitionline == null)
211 {
212 throw new IllegalArgumentException(szinputdir+"/"+szmainfile+" is missing lines!");
213 }
214 StringTokenizer st = new StringTokenizer(sztransitionline,"\t");
215 st.nextToken().trim();
216 st.nextToken().trim();
217 st.nextToken().trim();
218 besttransitionprobs[ni][nj] = Double.parseDouble(st.nextToken().trim());
219 }
220 }
221
222 for (int ni = 0; ni < nbestnumstates; ni++)
223 {
224 emissionsline[ni] = new ArrayList();
225 }
226
227 String szLine;
228 while ((szLine = brfile.readLine())!=null)
229 {
230 StringTokenizer st = new StringTokenizer(szLine,"\t");
231 st.nextToken().trim();
232 int nj = Integer.parseInt(st.nextToken().trim())-1;
233 emissionsline[nj].add(st.nextToken().trim()+"\t"+st.nextToken().trim()+"\t"+st.nextToken().trim()+"\t"+st.nextToken().trim());
234 }
235 brfile.close();
236
237
238 //double dmaxcorrouterouter = -Integer.MAX_VALUE;
239 int nstatesleft = nbestnumstates;
240 boolean[] elim = new boolean[nbestnumstates];
241 double[][] modelemissions_nbestmodel = modelemissions[nbestmodel];
242
243 while (nstatesleft > 2)
244 {
245 //while there are more than 2 states in the model
246
247 int nmaxelimstate = -1;
248 double dmaxtotsum = -Double.MAX_VALUE;
249 for (int nelimstate = 0; nelimstate < elim.length; nelimstate++)
250 {
251 //will consider eliminating each state to see effect on total representation
252 if (!elim[nelimstate])
253 {
254 elim[nelimstate] = true;
255 double dtotsum =0;
256 for (int nc = 0; nc < modelemissions.length; nc++)
257 {
258 //will iterate through each sampled models
259
260 if ((nbestmodel != nc)||(modelemissions.length==1))
261 {
262 //going through each state in the other sampled modes
263 for (int nd = 0; nd < modelemissions[nc].length; nd++)
264 {
265 double dmaxagreeval =-Integer.MAX_VALUE;
266 double[] modelemissions_ncnd = modelemissions[nc][nd];
267 //comparing to each state in the best model not eliminated
268 for (int nb = 0; nb < modelemissions_nbestmodel.length; nb++)
269 {
270 if (!elim[nb])
271 {
272 //state has not been elminiated
273 double dagreeval;
274 if (beuclid)
275 {
276 dagreeval = -Util.euclid(modelemissions_nbestmodel[nb],modelemissions_ncnd);
277 }
278 else
279 {
280 dagreeval = Util.correlation(modelemissions_nbestmodel[nb],modelemissions_ncnd);
281 }
282
283 if (dagreeval > dmaxagreeval)
284 {
285 //this is the closest state found so far
286 dmaxagreeval = dagreeval;
287 }
288 }
289 }
290 //add to the total distance for this emission vector the closest distance
291 dtotsum += dmaxagreeval;
292 }
293 }
294 }
295
296 //the elimination of this state was temporary
297 elim[nelimstate] = false;
298 if (dtotsum > dmaxtotsum)
299 {
300 dmaxtotsum = dtotsum;
301 nmaxelimstate = nelimstate;
302 }
303 }
304 }
305
306 if (ChromHMM.BVERBOSE)
307 {
308 System.out.println("****\t"+nstatesleft+"\t"+nmaxelimstate+"\t"+dmaxtotsum);
309 }
310 elim[nmaxelimstate] = true;
311 nstatesleft--;
312 //nmaxelim state is the state to eliminate
313
314 PrintWriter pw = new PrintWriter(szoutputdir+"/elim_"+nstatesleft+"_"+szmainfile);
315 String szLinein;
316
317 int nelim = nstatesleft;
318 pw.println(nelim+"\t"+numcols+"\t"+chbestorder);
319
320 //readjusting the inital probabilities
321 //uniformly assign the initial probabilities of eliminated states
322 int nj = 0;
323 double dextra = 0;
324 double[] probinit = new double[nelim];
325 for (int ni = 0; ni < elim.length; ni++)
326 {
327 if (!elim[ni])
328 {
329 probinit[nj] = bestprobinit[ni];
330 nj++;
331 }
332 else
333 {
334 dextra += bestprobinit[ni];
335 }
336 }
337
338 dextra= dextra/nelim;
339 nj = 0;
340 for (int ni = 0; ni < elim.length; ni++)
341 {
342 if (!elim[ni])
343 {
344 pw.println("probinit\t"+(nj+1)+"\t"+(probinit[nj]+dextra));
345 nj++;
346 }
347 }
348
349 //readjusting the transition probabilities
350 int nk = 0;
351 for (int na = 0; na < elim.length; na++)
352 {
353 if (!elim[na])
354 {
355 nj = 0;
356 dextra = 0;
357 double[] transitionprob = new double[nelim];
358 for (int ni = 0; ni < elim.length; ni++)
359 {
360 if (!elim[ni])
361 {
362 transitionprob[nj] = besttransitionprobs[na][ni];
363 nj++;
364 }
365 else
366 {
367 dextra += besttransitionprobs[na][ni];
368 }
369 }
370
371 dextra= dextra/nelim;
372 nj = 0;
373 for (int ni = 0; ni < elim.length; ni++)
374 {
375 if (!elim[ni])
376 {
377 pw.println("transitionprobs\t"+(nk+1)+"\t"+(nj+1)+"\t"+(transitionprob[nj]+dextra));
378 nj++;
379 }
380 }
381 nk++;
382 }
383 }
384
385 //outputing emission parameters for those states which have not been eliminated
386 nk = 0;
387 for (int na = 0; na < elim.length; na++)
388 {
389 if (!elim[na])
390 {
391 int numlines = emissionsline[na].size();
392 for (int ni = 0; ni < numlines; ni++)
393 {
394 pw.println("emissionprobs\t"+(nk+1)+"\t"+emissionsline[na].get(ni));
395 }
396 nk++;
397 }
398 }
399 pw.close();
400 }
401 }
402 }