Debian Codegraph @

edu/mit/compbio/ChromHMM/StateAnalysis.java

raw symbols SCIP
1
2 /**
3 * ChromHMM - automating chromatin state discovery and characterization
4 * Copyright (C) 2008-2012 Massachusetts Institute of Technology
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 **/
19 package edu.mit.compbio.ChromHMM;
20
21 import java.io.*;
22 import java.util.*;
23 import java.text.*;
24 import java.awt.*;
25 import org.tc33.jheatchart.HeatChart;
26
27
28 /**
29 * This class supports post analysis for the ChromHMM segmentations
30 * The ChromHMM code was written by Jason Ernst
31 */
32 public class StateAnalysis
33 {
34
35 /**
36 * If total fraction for an annotation is below this an error message is triggered
37 * that there was no state assigment matches
38 */
39 static double EPSILONOVERLAP = 0.00000001;
40
41 /**
42 * Limit on how significant p-value should be reported in OverlapEnrichment
43 */
44 static double PVALLOG10CUTOFF = 300;
45
46
47 /**
48 * Variable indicating if found a duplicate state assignment to prevent printing warning more than once
49 */
50 static boolean bfounddup = false;
51
52 /**
53 * A record for storing a segmentation
54 */
55 static class SegmentRec
56 {
57 String szchrom; // the chromosome
58 int nbegin; //coordinate of start of the segmentation
59 int nend; //coordinate of the end of the segmentation
60 short slabel; //the segmentationlabel
61
62 SegmentRec(String szchrom, int nbegin, int nend,short slabel)
63 {
64 this.szchrom = szchrom;
65 this.nbegin =nbegin;
66 this.nend = nend;
67 this.slabel = slabel;
68 }
69
70 }
71
72 ////////////////////////////////////////////////////////////////////////////////
73
74 /**
75 * Stores all the emission parameters for a model
76 * corresponding to szfilename and also explicitly the number of states
77 */
78 static class RecEmissionFile
79 {
80 String szfilename;
81 int numstates;
82 double[][] emissionparams;
83 }
84
85
86
87 /////////////////////////////////////////////////////////////////////////////////////////
88 /**
89 * Compares two emission files and orders them so the one with fewer states comes first
90 * and if there is a tie then by the file name
91 */
92 public static class RecEmissionFileCompare implements Comparator, Serializable
93 {
94 public int compare(Object o1, Object o2)
95 {
96 RecEmissionFile r1 = (RecEmissionFile) o1;
97 RecEmissionFile r2 = (RecEmissionFile) o2;
98 if (r1.numstates < r2.numstates)
99 {
100 return -1;
101 }
102 else if (r1.numstates > r2.numstates)
103 {
104 return 1;
105 }
106 else
107 {
108 return (r1.szfilename.compareTo(r2.szfilename));
109 }
110 }
111 }
112
113
114 //////////////////////////////////////////////////////////////////////////////////////////////////////////
115
116 public static class Interval
117 {
118 int nstart;
119 int nend;
120
121 Interval(int nstart, int nend)
122 {
123 this.nstart = nstart;
124 this.nend = nend;
125 }
126 }
127
128 //////////////////////////////////////////////////////////////////////////////////////////////////////////
129
130 public static class IntervalCompare implements Comparator, Serializable
131 {
132 public int compare(Object o1, Object o2)
133 {
134 Interval i1 = (Interval) o1;
135 Interval i2 = (Interval) o2;
136
137 if (i1.nstart < i2.nstart)
138 {
139 return -1;
140 }
141 else if (i1.nstart > i2.nstart)
142 {
143 return 1;
144 }
145 else if (i1.nend < i2.nend)
146 {
147 return -1;
148 }
149 else if (i1.nend > i2.nend)
150 {
151 return 1;
152 }
153 else
154 {
155 return 0;
156 }
157 }
158 }
159
160 /////////////////////////////////////////////////////////////////////////////////////////////////////////
161
162
163
164 static void makeEnrichmentHeatMap(double[][] heatmapfold, String[] xlabels, String[] ylabels,String szoutfileprefix,Color theColor,
165 String sztitle,String szxaxis,String szyaxis) throws IOException
166 {
167 HeatChart map = new HeatChart(heatmapfold);
168
169 map.setTitle(sztitle);
170 map.setXAxisLabel(szxaxis);
171 map.setYAxisLabel(szyaxis);
172
173 map.setChartMargin(100);
174 map.setXValues(xlabels);
175 map.setYValues(ylabels);
176 map.setHighValueColour(theColor);
177 map.setAxisValuesFont(new Font("SansSerif",0,20));
178 map.setAxisLabelsFont(new Font("SansSerif",0,22));
179 map.setTitleFont(new Font("SansSerif",0,24));
180 map.saveToFile(new File(szoutfileprefix+".png"));
181 Util.printImageToSVG(map, szoutfileprefix+".svg");
182 System.out.println("Writing to file "+szoutfileprefix+".png");
183 System.out.println("Writing to file "+szoutfileprefix+".svg");
184 }
185
186 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
187 /**
188 *
189 * Computes an enrichment based on a set of posterior files
190 * szposteriordir - the directory with the posterior files to compute enrichments for
191 * szcell - the cell type for which to compute the enrichment
192 * szinputcoorddir - the directory containing the coordinates for enrichment
193 * szinputcoordlist - if non-null only computes enrichments for file names in the specified
194 * noffsetleft - the amount that should be subtracted from the left coordinate so it is 0-based inclusive
195 * noffsetright - the amount that should be subtracted from the right coordinate so it is 0-based inclusive
196 * nbinsize - the binsize used in the segmentation
197 * bcenter - if true only uses the center of the interval for determining enrichments
198 * bunique - only counts a bin once, this is not applicable if bbaseres is true or busesignal is true
199 * busesignal - if true then uses signal information about the interval if available
200 * szcolfields - comma delimited list of the 0-based columns of chromosome,start,end, and if busesignal is true the signal column
201 * bbaseres - if true gives enrichment at the base resolution opposed to the bin resolution
202 * szoutfile - the file to which to output the
203 * bcolscaleheat - if true scales the heatmap individual for each column otherwise uses the same for all columns
204 * theColor - theColor to use for the heatmap
205
206 * default is chromsome is field 1, start is field 2, end is field 3, and amount is field 4
207 * if szcolfields is non-null reads chrom, start, end, signal if busesignal field is true
208 *
209 */
210 public static void enrichmentPosterior(String szposteriordir,String szcell,String szinputcoorddir, String szinputcoordlist,
211 int noffsetleft, int noffsetright, int nbinsize,
212 boolean bcenter,boolean bunique, boolean busesignal,String szcolfields,boolean bbaseres,
213 String szoutfile,boolean bcolscaleheat, Color theColor,String sztitle,
214 String szlabelmapping, boolean bprintimage, boolean blogpvals) throws IOException
215 {
216
217 String szLine;
218 char chorder='0';
219
220 if (busesignal)
221 {
222 bunique = false;
223 }
224
225 File posteriordir = new File(szposteriordir);
226 if (!posteriordir.exists())
227 {
228 throw new IllegalArgumentException(szposteriordir+" was not found!");
229 }
230
231 String[] posteriorfiles = posteriordir.list();
232
233 int numposteriorstates = 0;
234
235 int nfirstindex=0;
236 boolean bfirst = true;
237
238
239 String[] files;
240
241 if (szinputcoordlist == null)
242 {
243 File dir = new File(szinputcoorddir);
244
245 if (dir.isDirectory())
246 {
247 //files = dir.list();
248
249 //added in v1.11 to skip hidden
250 String[] filesWithHidden = dir.list();
251 int nnonhiddencount = 0;
252 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
253 {
254 if (!(new File(filesWithHidden[nfile])).isHidden())
255 {
256 nnonhiddencount++;
257 }
258 }
259
260 int nactualindex = 0;
261 files = new String[nnonhiddencount];// dir.list();
262 if (nnonhiddencount == 0)
263 {
264 throw new IllegalArgumentException("No files found in "+szinputcoorddir);
265 }
266
267 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
268 {
269 if (!(new File(filesWithHidden[nfile])).isHidden())
270 {
271 files[nactualindex] = filesWithHidden[nfile];
272 nactualindex++;
273 }
274 }
275
276 Arrays.sort(files);
277 szinputcoorddir += "/";
278 }
279 else
280 {
281 files = new String[1];
282 files[0] = szinputcoorddir;
283 szinputcoorddir = "";
284 }
285 }
286 else
287 {
288 szinputcoorddir += "/";
289 //loads in the input coords list
290 BufferedReader brfiles = Util.getBufferedReader(szinputcoordlist);
291
292 ArrayList alfiles = new ArrayList();
293 while ((szLine = brfiles.readLine())!=null)
294 {
295 alfiles.add(szLine);
296 }
297 brfiles.close();
298 files = new String[alfiles.size()];
299 for (int nfile = 0; nfile < files.length; nfile++)
300 {
301 files[nfile] = (String) alfiles.get(nfile);
302 }
303 }
304
305
306 double dsumlabel = 0;
307 double[] tallylabel = null;
308 double[][] tallyoverlaplabel = null;
309 double[] dsumoverlaplabel = new double[files.length];
310
311 boolean bposteriorfound = false;
312
313 for (int nfile = 0; nfile < posteriorfiles.length; nfile++)
314 {
315 String szposteriorfiles_nfile = posteriorfiles[nfile];
316
317 //going through the posterior files
318 if ((szposteriorfiles_nfile.contains("_posterior"))&&(!(new File(szposteriorfiles_nfile)).isHidden()))
319 {
320
321 BufferedReader brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
322 String szHeader = brposterior.readLine();
323 if (szHeader == null)
324 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" is empty!");
325 StringTokenizer st =new StringTokenizer(szHeader,"\t");
326 String szcurrcell = st.nextToken().trim();
327 if ((!szcurrcell.equals(szcell))&&(!szcell.equals("")))
328 {
329 brposterior.close();
330 }
331 else
332 {
333 bposteriorfound = true;
334 String szchrom = st.nextToken().trim();
335
336 int numlines = 0;
337 szLine = brposterior.readLine();
338 if (szLine == null)
339 {
340 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" is missing lines!");
341 }
342 st = new StringTokenizer(szLine,"\t");
343 int numcurrstates = st.countTokens();
344 if (bfirst)
345 {
346 chorder = st.nextToken().trim().charAt(0);
347 bfirst = false;
348 nfirstindex = nfile;
349 numposteriorstates = numcurrstates;
350 tallylabel = new double[numposteriorstates];
351 tallyoverlaplabel = new double[files.length][numposteriorstates];
352 }
353 else if (numposteriorstates != numcurrstates)
354 {
355 throw new IllegalArgumentException("Number of states "+numcurrstates+" in "+szposteriorfiles_nfile+
356 " does not match number of states "+numposteriorstates+" in "+posteriorfiles[nfirstindex]);
357 }
358
359 while ((szLine = brposterior.readLine())!=null)
360 {
361 numlines++;
362 }
363 brposterior.close();
364
365 //now know the number of states and lines for the posterior file
366 float[][] posterior = new float[numlines][numposteriorstates];
367
368 //loading in the posterior data and tallying how frequently each state has occured
369 brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
370 brposterior.readLine();
371 brposterior.readLine();
372 int nline = 0;
373 while ((szLine = brposterior.readLine())!=null)
374 {
375 st = new StringTokenizer(szLine,"\t");
376 float[] posterior_nline = posterior[nline];
377 for (int nstate = 0; nstate < numposteriorstates; nstate++)
378 {
379 float fval = Float.parseFloat(st.nextToken().trim());
380 posterior_nline[nstate] = fval;
381 tallylabel[nstate] += fval;
382 }
383 nline++;
384 }
385 brposterior.close();
386
387 for (int ncoordfile = 0; ncoordfile < files.length; ncoordfile++)
388 {
389 double[] tallyoverlaplabel_ncoordfile = tallyoverlaplabel[ncoordfile];
390
391 int nchromindex = 0;
392 int nstartindex = 1;
393 int nendindex = 2;
394 int nsignalindex = 3;
395
396 if (szcolfields != null)
397 {
398 //gets the start and end coordinates
399 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
400 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
401 nstartindex = Integer.parseInt(stcolfields.nextToken().trim());
402 nendindex = Integer.parseInt(stcolfields.nextToken().trim());
403
404 if (busesignal)
405 {
406 nsignalindex = Integer.parseInt(stcolfields.nextToken().trim());
407 }
408 }
409
410 BufferedReader brcoords = Util.getBufferedReader(szinputcoorddir+files[ncoordfile]);
411
412 if (bunique)
413 {
414 ArrayList alrecs = new ArrayList();
415 while ((szLine = brcoords.readLine())!=null)
416 {
417 if (szLine.trim().equals("")) continue;
418 String[] szLineA = szLine.split("\\s+");
419 if (nchromindex >= szLineA.length)
420 {
421 throw new IllegalArgumentException(nchromindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[ncoordfile]);
422 }
423 String szreadchrom = szLineA[nchromindex];
424
425 if (szreadchrom.equals(szchrom))
426 {
427 //removed in v1.27 appears to be a dead store
428 //String szcurrchrom = szLineA[nchromindex];
429 if (nstartindex >= szLineA.length)
430 {
431 throw new IllegalArgumentException(nstartindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[ncoordfile]);
432 }
433
434 if (nendindex >= szLineA.length)
435 {
436 throw new IllegalArgumentException(nendindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[ncoordfile]);
437 }
438
439 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
440 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
441 if (bcenter)
442 {
443 nbeginactual = (nbeginactual+nendactual)/2;
444 nendactual = nbeginactual;
445 }
446 alrecs.add(new Interval(nbeginactual,nendactual));
447 }
448 }
449
450 Object[] alrecA = alrecs.toArray();
451 Arrays.sort(alrecA,new IntervalCompare());
452
453 boolean bclosed = true;
454 int nintervalstart = -1;
455 int nintervalend = -1;
456 boolean bdone = false;
457
458 for (int nindex = 0; ((nindex <= alrecA.length)&&(alrecA.length>0)); nindex++)
459 {
460 int ncurrstart=-1;
461 int ncurrend=-1;
462
463 if (nindex == alrecA.length)
464 {
465 bdone = true;
466 }
467 else
468 {
469 ncurrstart = ((Interval) alrecA[nindex]).nstart;
470 ncurrend = ((Interval) alrecA[nindex]).nend;
471 if (nindex == 0)
472 {
473 nintervalstart = ncurrstart;
474 nintervalend = ncurrend;
475 }
476 else if (ncurrstart <= nintervalend)
477 {
478 //this read is still in the active interval
479 //extending the current active interval interval
480 if (ncurrend > nintervalend)
481 {
482 nintervalend = ncurrend;
483 }
484 }
485 else
486 {
487 //just finished the current active interval
488 bdone = true;
489 }
490 }
491
492 if (bdone)
493 {
494 int nbegin = nintervalstart/nbinsize;
495 int nend = nintervalend/nbinsize;
496
497 if (nbegin < 0)
498 {
499 nbegin = 0;
500 }
501
502 if (nend >= posterior.length)
503 {
504 nend = posterior.length - 1;
505 }
506
507 for (int nbin = nbegin; nbin <= nend; nbin++)
508 {
509 float[] posterior_nbin = posterior[nbin];
510 for (int nstate = 0; nstate < numposteriorstates; nstate++)
511 {
512 tallyoverlaplabel_ncoordfile[nstate] += posterior_nbin[nstate];
513 }
514 }
515
516 if (bbaseres)
517 {
518 //dbeginfrac represents the fraction of bases the nbegin interval
519 //which came after the actual nbeginactual
520 double dbeginfrac = (nintervalstart - nbegin*nbinsize)/(double) nbinsize;
521
522 //dendfrac represents the fraction of bases after the end position in the interval
523 double dendfrac = ((nend+1)*nbinsize-nintervalend-1)/(double) nbinsize;
524
525 if ((nbegin < posterior.length)&&(dbeginfrac>0))
526 {
527 //only removing if it would of made it into the actual posterior counts
528 float[] posterior_nbegin = posterior[nbegin];
529 for (int nstate = 0; nstate < numposteriorstates; nstate++)
530 {
531 tallyoverlaplabel_ncoordfile[nstate]-=dbeginfrac*posterior_nbegin[nstate];
532 }
533 }
534
535 if ((nend < posterior.length)&&(dendfrac >0))
536 {
537 //only removing if it would of made it into the actual posterior counts
538 float[] posterior_nend = posterior[nend];
539 for (int nstate = 0; nstate < numposteriorstates; nstate++)
540 {
541 tallyoverlaplabel_ncoordfile[nstate]-=dendfrac*posterior_nend[nstate];
542 }
543 }
544 nintervalstart = ncurrstart;
545 nintervalend = ncurrend;
546 bdone = false;
547 }
548 }
549 }
550 }
551 else
552 {
553 while ((szLine = brcoords.readLine())!=null)
554 {
555 if (szLine.trim().equals("")) continue;
556 String[] szLineA = szLine.split("\\s+");
557 String szreadchrom = szLineA[nchromindex];
558 if (szreadchrom.equals(szchrom))
559 {
560 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
561 int nbegin = nbeginactual/nbinsize;
562
563 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
564 int nend = nendactual/nbinsize;
565
566 double damount;
567 if ((busesignal)&&(nsignalindex < szLineA.length))
568 {
569 damount = Double.parseDouble(szLineA[nsignalindex]);
570
571 if (damount < 0)
572 {
573 throw new IllegalArgumentException("A negative weight of "+damount+" was found in "+szinputcoorddir+files[nfile]+
574 " but weights are assumed to be non-negative");
575 }
576 }
577 else
578 {
579 //update in v1.26
580 damount = 1.0/(double) (nbinsize);
581 }
582
583 if (bcenter)
584 {
585 int ncenter = (nbeginactual+nendactual)/(2*nbinsize);
586 if (ncenter < posterior.length)
587 {
588 float[] posterior_ncenter = posterior[ncenter];
589
590 //allowing duplicates
591 for (int nstate = 0; nstate < numposteriorstates; nstate++)
592 {
593 tallyoverlaplabel_ncoordfile[nstate]+=damount*posterior_ncenter[nstate];
594 }
595 }
596 }
597 else
598 {
599 //allowing duplicate counts
600 if (nbegin < 0)
601 {
602 nbegin = 0;
603 }
604
605 if (nend >= posterior.length)
606 {
607 nend = posterior.length - 1;
608 }
609
610 for (int nindex = nbegin; nindex <= nend; nindex++)
611 {
612 float[] posterior_nindex = posterior[nindex];
613 for (int nstate = 0; nstate < numposteriorstates; nstate++)
614 {
615 tallyoverlaplabel_ncoordfile[nstate]+=damount*posterior_nindex[nstate];
616 }
617 }
618
619 if (bbaseres)
620 {
621 //the fractions of the begin and end intervals not actually included
622 double dbeginfrac = (nbeginactual - nbegin*nbinsize)/(double) nbinsize;
623 double dendfrac = ((nend+1)*nbinsize-nendactual-1)/(double) nbinsize;
624
625 if ((nbegin< posterior.length)&&(dbeginfrac>0))
626 {
627 //only removing if it would of made it into the actual posterior counts
628 float[] posterior_nbegin = posterior[nbegin];
629 for (int nstate = 0; nstate < numposteriorstates; nstate++)
630 {
631 tallyoverlaplabel_ncoordfile[nstate]-=damount*dbeginfrac*posterior_nbegin[nstate];
632 }
633 }
634
635 if ((nend < posterior.length)&&(dendfrac>0))
636 {
637 //only removing if it would of made it into the actual posterior counts
638 float[] posterior_nend = posterior[nend];
639 for (int nstate = 0; nstate < numposteriorstates; nstate++)
640 {
641 tallyoverlaplabel_ncoordfile[nstate]-=damount*dendfrac*posterior_nend[nstate];
642 }
643 }
644 }
645 }
646 }
647 }
648 }
649 brcoords.close();
650 }
651 }
652 }
653 }
654
655 if (!bposteriorfound)
656 {
657 throw new IllegalArgumentException("no posterior file found for cell type "+szcell);
658 }
659
660 for (int nfile = 0; nfile < dsumoverlaplabel.length; nfile++)
661 {
662 double[] tallyoverlaplabel_nfile = tallyoverlaplabel[nfile];
663 for (int nindex = 0; nindex < tallyoverlaplabel_nfile.length; nindex++)
664 {
665 dsumoverlaplabel[nfile] += tallyoverlaplabel_nfile[nindex];
666 }
667
668 if (dsumoverlaplabel[nfile] < EPSILONOVERLAP) //0.00000001)
669 {
670 throw new IllegalArgumentException("Coordinates in "+files[nfile]+" not assigned to any state. Check if chromosome naming in "+files[nfile]+
671 " match those in the posterior files.");
672 }
673 }
674
675
676
677 outputenrichment(szoutfile, files,tallyoverlaplabel, tallylabel, dsumoverlaplabel,theColor,bcolscaleheat,ChromHMM.convertCharOrderToStringOrder(chorder),
678 sztitle,1,szlabelmapping,chorder, bprintimage,false, null,bcenter&&blogpvals,!bunique,nbinsize);
679
680 }
681
682 /////////////////////////////////////////////////////////////////////////////////////////////////////////
683
684 /**
685 * Computes an enrichment based on a hard segmentation
686 * szinputsegment - the file with the segmentation
687 * szinputcoorddir - the directory containing the coordinates for enrichment
688 * szinputcoordlist - if non-null only computes enrichments for file names in the specified
689 * noffsetleft - the amount that should be subtracted from the left coordinate so it is 0-based inclusive
690 * noffsetright - the amount that should be subtracted from the right coordinate so it is 0-based inclusive
691 * nbinsize - the binsize used in the segmentation
692 * bcenter - if true only uses the center of the interval for determining enrichments
693 * bunique - only counts a bin once, this is not applicable if bbaseres is true or busesignal is true
694 * busesignal - if true then uses signal information about the interval if available
695 * szcolfields - comma delimited list of the 0-based columns of chromosme,start,end, and if busesignal is true the signal column
696 * bbaseres - if true gives enrichment at the base resolution opposed to the bin resolution
697 * szoutfile - the file to which to output the
698 * bcolscaleheat - if true scales the heatmap individual for each column otherwise uses the same for all columns
699 * theColor - theColor to use for the heatmap
700 */
701 public static void enrichmentMax(String szinputsegment,String szinputcoorddir,String szinputcoordlist,
702 int noffsetleft, int noffsetright,
703 int nbinsize, boolean bcenter,boolean bunique, boolean busesignal,String szcolfields,
704 boolean bbaseres, String szoutfile,boolean bcolscaleheat,Color theColor,String sztitle,
705 String szlabelmapping, boolean bprintimage,
706 boolean bstringlabels, boolean bbrowser, boolean blogpvals) throws IOException
707 {
708 //usual high memory
709 ArrayList alsegments = new ArrayList(); //stores all the segments
710 ArrayList alchromindex = new ArrayList(); //stores the index of the chromosome
711
712 if (busesignal)
713 {
714 bunique = false;
715 }
716
717 String szLine;
718 HashMap hmchromMax = new HashMap(); //maps chromosome to the maximum index
719 HashMap hmchromToIndex = new HashMap(); //maps chromosome to an index
720 HashMap hmLabelToIndex = new HashMap(); //maps label to an index
721 HashMap hmIndexToLabel = new HashMap(); //maps index string to label
722 int nmaxlabel=0; // the maximum label found
723 String szlabel="";
724 //reads in the segmentation recording maximum position for each chromosome and
725 //maximum label
726 boolean busedunderscore = false;
727 BufferedReader brinputsegment = Util.getBufferedReader(szinputsegment);
728 while ((szLine = brinputsegment.readLine())!=null)
729 {
730 //added v1.24
731 if (bbrowser)
732 {
733 if ((szLine.toLowerCase(Locale.ENGLISH).startsWith("browser"))||(szLine.toLowerCase(Locale.ENGLISH).startsWith("track")))
734 {
735 continue;
736 }
737 }
738
739 StringTokenizer st;
740
741 if (bstringlabels)
742 {
743 st = new StringTokenizer(szLine,"\t");
744 }
745 else
746 {
747 st = new StringTokenizer(szLine,"\t ");
748 }
749
750 //added in v1.24
751 int numtokens = st.countTokens();
752 if (numtokens == 0)
753 {
754 //skip blank lines
755 continue;
756 }
757 else if (numtokens < 4)
758 {
759 throw new IllegalArgumentException("Line "+szLine+" in "+szinputsegment+" only had "+numtokens+" token(s). Expecting at least 4");
760 }
761
762 String szchrom = st.nextToken().trim();
763 int nbegincoord = Integer.parseInt(st.nextToken().trim());
764 int nendcoord = Integer.parseInt(st.nextToken().trim());
765 if (nbegincoord % nbinsize != 0)
766 {
767 throw new IllegalArgumentException("Binsize of "+nbinsize+" does not agree with coordinates in input segment "+szLine+". -b binsize should match parameter value to LearnModel or "+
768 "MakeSegmentation used to produce segmentation. If segmentation is derived from a lift over from another assembly, then the '-b 1' option should be used");
769 }
770 int nbegin = nbegincoord/nbinsize;
771 int nend = (nendcoord-1)/nbinsize;
772 szlabel = st.nextToken().trim();
773
774 short slabel = -1;
775 if (bstringlabels)
776 {
777 int nunderscoreindex = szlabel.indexOf("_");
778
779 if (nunderscoreindex >=0)
780 {
781 String szprefix = szlabel.substring(0,nunderscoreindex);
782
783 try
784 {
785 slabel = (short) (Short.parseShort(szprefix));
786 if (slabel > nmaxlabel)
787 {
788 nmaxlabel = slabel;
789 }
790 busedunderscore = true;
791 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
792 hmIndexToLabel.put(""+slabel, szlabel);
793 }
794 catch (NumberFormatException ex)
795 {
796 try
797 {
798 slabel = (short) (Short.parseShort(szprefix.substring(1)));
799 if (slabel > nmaxlabel)
800 {
801 nmaxlabel = slabel;
802 }
803 busedunderscore = true;
804 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
805 hmIndexToLabel.put(""+slabel, szlabel);
806 }
807 catch (NumberFormatException ex2)
808 {
809 if (busedunderscore)
810 {
811 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
812 }
813 }
814 }
815 }
816
817 if (!busedunderscore)
818 {
819 //handle string labels
820 Short objshort = ((Short) hmLabelToIndex.get(szlabel));
821
822 if (objshort == null)
823 {
824 nmaxlabel = hmLabelToIndex.size()+1;
825 slabel = (short) nmaxlabel;
826 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
827 hmIndexToLabel.put(""+nmaxlabel, szlabel);
828 }
829 else
830 {
831 slabel = ((Short) objshort).shortValue();
832 }
833 }
834 alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
835 }
836 else
837 {
838 try
839 {
840 slabel = (short) (Short.parseShort(szlabel));
841 }
842 catch (NumberFormatException ex)
843 {
844 try
845 {
846 slabel = (short) (Short.parseShort(szlabel.substring(1)));
847 }
848 catch (NumberFormatException ex2)
849 {
850 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
851 }
852 }
853
854 alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
855 if (slabel > nmaxlabel)
856 {
857 nmaxlabel = slabel;
858 }
859 }
860
861 Integer objMax = (Integer) hmchromMax.get(szchrom);
862 if (objMax == null)
863 {
864 hmchromMax.put(szchrom,Integer.valueOf(nend));
865 hmchromToIndex.put(szchrom, Integer.valueOf(hmchromToIndex.size()));
866 alchromindex.add(szchrom);
867 }
868 else
869 {
870 int ncurrmax = objMax.intValue();
871 if (ncurrmax < nend)
872 {
873 hmchromMax.put(szchrom, Integer.valueOf(nend));
874 }
875 }
876 }
877 brinputsegment.close();
878
879 int numchroms = alchromindex.size();
880 short[][] labels = new short[numchroms][]; //stores the hard label assignments
881
882 for (int nchrom = 0; nchrom < numchroms; nchrom++)
883 {
884 int nsize = ((Integer) hmchromMax.get(alchromindex.get(nchrom))).intValue()+1;
885 labels[nchrom] = new short[nsize];
886 short[] labels_nchrom = labels[nchrom];
887 //sets to -1 so missing segments not counted as label 0
888 for (int npos = 0; npos < nsize; npos++)
889 {
890 labels_nchrom[npos] = -1;
891 }
892
893 }
894
895 double[] tallylabel = new double[nmaxlabel+1];
896
897 int numlines = alsegments.size();
898
899 for (int nindex = 0; nindex < numlines; nindex++)
900 {
901 SegmentRec theSegmentRec = (SegmentRec) alsegments.get(nindex);
902 int nbegin = theSegmentRec.nbegin;
903 int nend = theSegmentRec.nend;
904 short slabel = theSegmentRec.slabel;
905 int nchrom = ((Integer) hmchromToIndex.get(theSegmentRec.szchrom)).intValue();
906 short[] labels_nchrom = labels[nchrom];
907 //stores each label position in the genome
908 for (int npos = nbegin; npos <= nend; npos++)
909 {
910 if ((!StateAnalysis.bfounddup) &&(labels_nchrom[npos] >= 0)&&(labels_nchrom[npos]!=slabel))
911 {
912 StateAnalysis.bfounddup = true;
913 System.out.println("WARNING: found the same position assigned to multiple states. First example found: "+theSegmentRec.szchrom+
914 ":"+(npos*nbinsize+1)+". Will use the last occurrence in file.");
915
916 }
917 labels_nchrom[npos] = slabel;
918 tallylabel[slabel]++;
919 }
920 }
921
922
923 String[] files;
924
925 if (szinputcoordlist == null)
926 {
927 File dir = new File(szinputcoorddir);
928 //we don't have a specific list of files to include
929 //will use all files in the directory
930 if (dir.isDirectory())
931 {
932 //throw new IllegalArgumentException(szinputcoorddir+" is not a directory!");
933 //added in v1.11 to skip hidden files
934 String[] filesWithHidden = dir.list();
935 int nnonhiddencount = 0;
936 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
937 {
938 if (!(new File(filesWithHidden[nfile])).isHidden())
939 {
940 nnonhiddencount++;
941 }
942 }
943
944 int nactualindex = 0;
945 files = new String[nnonhiddencount];// dir.list();
946 if (nnonhiddencount == 0)
947 {
948 throw new IllegalArgumentException("No files found in "+szinputcoorddir);
949 }
950
951 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
952 {
953 if (!(new File(filesWithHidden[nfile])).isHidden())
954 {
955 files[nactualindex] = filesWithHidden[nfile];
956 nactualindex++;
957 }
958 }
959 Arrays.sort(files);
960 szinputcoorddir += "/";
961 }
962 else
963 {
964 files = new String[1];
965 files[0] = szinputcoorddir;
966 szinputcoorddir = "";
967 }
968 }
969 else
970 {
971 szinputcoorddir += "/";
972 //store in files all file names given in szinputcoordlist
973 BufferedReader brfiles = Util.getBufferedReader(szinputcoordlist);
974 ArrayList alfiles = new ArrayList();
975 while ((szLine = brfiles.readLine())!=null)
976 {
977 alfiles.add(szLine);
978 }
979 brfiles.close();
980 files = new String[alfiles.size()];
981 for (int nfile = 0; nfile < files.length; nfile++)
982 {
983 files[nfile] = (String) alfiles.get(nfile);
984 }
985 }
986
987 //for each enrichment category and state label gives a count of how often
988 //overlapped by a segment optionally with signal
989 double[][] tallyoverlaplabel = new double[files.length][nmaxlabel+1];
990 double[] dsumoverlaplabel = new double[files.length];
991
992 for (int nfile = 0; nfile < files.length; nfile++)
993 {
994 double[] tallyoverlaplabel_nfile = tallyoverlaplabel[nfile];
995
996 int nchromindex = 0;
997 int nstartindex = 1;
998 int nendindex = 2;
999 int nsignalindex = 3;
1000
1001 if (szcolfields != null)
1002 {
1003 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
1004 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
1005 nstartindex = Integer.parseInt(stcolfields.nextToken().trim());
1006 nendindex = Integer.parseInt(stcolfields.nextToken().trim());
1007
1008 if (busesignal)
1009 {
1010 nsignalindex = Integer.parseInt(stcolfields.nextToken().trim());
1011 }
1012 }
1013
1014
1015 if (bunique)
1016 {
1017 Iterator itrChroms = hmchromToIndex.entrySet().iterator();
1018 while (itrChroms.hasNext())
1019 {
1020 Map.Entry pairs = (Map.Entry) itrChroms.next();
1021 String szchrom =(String) pairs.getKey();
1022 int nchrom = ((Integer) pairs.getValue()).intValue();
1023 short[] labels_nchrom = labels[nchrom];
1024
1025 //reading in the coordinates to overlap with
1026 BufferedReader brcoords = Util.getBufferedReader(szinputcoorddir +files[nfile]);
1027
1028 ArrayList alrecs = new ArrayList();
1029 while ((szLine = brcoords.readLine())!=null)
1030 {
1031 if (szLine.trim().equals("")) continue;
1032 String[] szLineA = szLine.split("\\s+");
1033
1034 if (nchromindex >= szLineA.length)
1035 {
1036 throw new IllegalArgumentException(nchromindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1037 }
1038
1039 String szcurrchrom = szLineA[nchromindex];
1040 if (szchrom.equals(szcurrchrom))
1041 {
1042 if (nstartindex >= szLineA.length)
1043 {
1044 throw new IllegalArgumentException(nstartindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1045 }
1046
1047 if (nendindex >= szLineA.length)
1048 {
1049 throw new IllegalArgumentException(nendindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1050 }
1051
1052
1053 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
1054 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
1055 if (bcenter)
1056 {
1057 nbeginactual = (nbeginactual+nendactual)/2;
1058 nendactual = nbeginactual;
1059 }
1060 alrecs.add(new Interval(nbeginactual,nendactual));
1061 }
1062 }
1063 brcoords.close();
1064
1065 Object[] alrecA = alrecs.toArray();
1066 Arrays.sort(alrecA,new IntervalCompare());
1067
1068 boolean bclosed = true;
1069 int nintervalstart = -1;
1070 int nintervalend = -1;
1071 boolean bdone = false;
1072
1073 for (int nindex = 0; (nindex <= alrecA.length&&(alrecA.length>0)); nindex++)
1074 {
1075 int ncurrstart=-1;
1076 int ncurrend=-1;
1077
1078
1079 if (nindex == alrecA.length)
1080 {
1081 bdone = true;
1082 }
1083 else
1084 {
1085 ncurrstart = ((Interval) alrecA[nindex]).nstart;
1086 ncurrend = ((Interval) alrecA[nindex]).nend;
1087 if (nindex == 0)
1088 {
1089 nintervalstart = ncurrstart;
1090 nintervalend = ncurrend;
1091 }
1092 else if (ncurrstart <= nintervalend)
1093 {
1094 //this read is still in the active interval
1095 //extending the current active interval
1096 if (ncurrend > nintervalend)
1097 {
1098 nintervalend = ncurrend;
1099 }
1100 }
1101 else
1102 {
1103 //just finished the current active interval
1104 bdone = true;
1105 }
1106 }
1107
1108 if (bdone)
1109 {
1110 int nbegin = nintervalstart/nbinsize;
1111 int nend = nintervalend/nbinsize;
1112
1113 if (nbegin < 0)
1114 {
1115 nbegin = 0;
1116 }
1117
1118 if (nend >= labels_nchrom.length)
1119 {
1120 nend = labels_nchrom.length - 1;
1121 }
1122
1123 for (int nbin = nbegin; nbin <= nend; nbin++)
1124 {
1125 if (labels_nchrom[nbin]>=0)
1126 {
1127 tallyoverlaplabel_nfile[labels_nchrom[nbin]]++;
1128 }
1129 }
1130
1131 if (bbaseres)
1132 {
1133 //dbeginfrac represents the fraction of bases the nbegin interval
1134 //which came after the actual nbeginactual
1135 double dbeginfrac = (nintervalstart - nbegin*nbinsize)/(double) nbinsize;
1136
1137 //dendfrac represents the fraction of bases after the end position in the interval
1138 double dendfrac = ((nend+1)*nbinsize-nintervalend-1)/(double) nbinsize;
1139
1140 if ((nbegin < labels_nchrom.length)&&(labels_nchrom[nbegin]>=0)&&(dbeginfrac>0))
1141 {
1142
1143 //only counted the bases if nbegin was less than labels_nchrom.length
1144 tallyoverlaplabel_nfile[labels_nchrom[nbegin]]-=dbeginfrac;
1145 }
1146
1147 if ((nend < labels_nchrom.length)&&(labels_nchrom[nend]>=0)&&(dendfrac>0))
1148 {
1149 //only counted the bases if nend was less than labels_nchrom.length
1150 tallyoverlaplabel_nfile[labels_nchrom[nend]]-=dendfrac;
1151 }
1152 }
1153
1154 nintervalstart = ncurrstart;
1155 nintervalend = ncurrend;
1156 bdone = false;
1157 }
1158 }
1159 }
1160 }
1161 else
1162 {
1163 BufferedReader brcoords = Util.getBufferedReader(szinputcoorddir +files[nfile]);
1164
1165 while ((szLine = brcoords.readLine())!=null)
1166 {
1167 if (szLine.trim().equals("")) continue;
1168 String[] szLineA = szLine.split("\\s+");
1169
1170
1171 if (nchromindex >= szLineA.length)
1172 {
1173 throw new IllegalArgumentException(nchromindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1174 }
1175
1176 if (nstartindex >= szLineA.length)
1177 {
1178 throw new IllegalArgumentException(nstartindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1179 }
1180
1181 if (nendindex >= szLineA.length)
1182 {
1183 throw new IllegalArgumentException(nendindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1184 }
1185
1186 String szchrom = szLineA[nchromindex];
1187 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
1188 int nbegin = nbeginactual/nbinsize;
1189
1190 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
1191 int nend = nendactual/nbinsize;
1192
1193 double damount;
1194 if ((busesignal)&&(nsignalindex < szLineA.length))
1195 {
1196 if (nsignalindex >= szLineA.length)
1197 {
1198 throw new IllegalArgumentException(nsignalindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1199 }
1200 damount = Double.parseDouble(szLineA[nsignalindex]);
1201 if (damount < 0)
1202 {
1203 throw new IllegalArgumentException("A negative weight of "+damount+" was found in "+szinputcoorddir+files[nfile]+
1204 " but weights are assumed to be non-negative");
1205 }
1206 }
1207 else
1208 {
1209 //fix in v1.26
1210 damount = 1.0/(double) (nbinsize);
1211 }
1212
1213 Integer objChrom = (Integer) hmchromToIndex.get(szchrom);
1214 if (objChrom != null)
1215 {
1216 //we have the chromosome corresponding to this read
1217 int nchrom = objChrom.intValue();
1218 short[] labels_nchrom = labels[nchrom];
1219
1220 if (bcenter)
1221 {
1222 //using the center position of the interval only
1223 int ncenter = (nbeginactual+nendactual)/(2*nbinsize);
1224 if ((ncenter < labels_nchrom.length)&&(labels_nchrom[ncenter]>=0))
1225 {
1226 tallyoverlaplabel_nfile[labels_nchrom[ncenter]]+=damount;
1227 }
1228 }
1229 else
1230 {
1231
1232 if (nbegin < 0)
1233 {
1234 nbegin = 0;
1235 }
1236
1237 //using the full interval range
1238 //no requirement on uniqueness
1239 if (nend >= labels_nchrom.length)
1240 {
1241 nend = labels_nchrom.length - 1;
1242 }
1243
1244
1245 for (int nindex = nbegin; nindex <= nend; nindex++)
1246 {
1247 if (labels_nchrom[nindex]>=0)
1248 {
1249 //increment overlap tally not checking for uniqueness
1250 tallyoverlaplabel_nfile[labels_nchrom[nindex]]+=damount;
1251 }
1252 }
1253
1254 if (bbaseres)
1255 {
1256 //dbeginfrac represents the fraction of bases the nbegin interval
1257 //which came after the actual nbeginactual
1258 double dbeginfrac = (nbeginactual - nbegin*nbinsize)/(double) nbinsize;
1259
1260 //dendfrac represents the fraction of bases after the end position in the interval
1261 double dendfrac = ((nend+1)*nbinsize-nendactual-1)/(double) nbinsize;
1262
1263 if ((nbegin < labels_nchrom.length)&&(labels_nchrom[nbegin]>=0)&&(dbeginfrac>0))
1264 {
1265 //only counted the bases if nbegin was less than labels_nchrom.length
1266 tallyoverlaplabel_nfile[labels_nchrom[nbegin]]-=damount*dbeginfrac;
1267 }
1268
1269 if ((nend < labels_nchrom.length)&&(labels_nchrom[nend]>=0)&&(dendfrac>0))
1270 {
1271 //only counted the bases if nend was less than labels_nchrom.length
1272 tallyoverlaplabel_nfile[labels_nchrom[nend]]-=damount*dendfrac;
1273 }
1274 }
1275 }
1276 }
1277 }
1278 brcoords.close();
1279 }
1280
1281 for (int nindex = 0; nindex < tallyoverlaplabel_nfile.length; nindex++)
1282 {
1283 dsumoverlaplabel[nfile] += tallyoverlaplabel_nfile[nindex];
1284 }
1285
1286 if (dsumoverlaplabel[nfile] < EPSILONOVERLAP) //0.00000001)
1287 {
1288 throw new IllegalArgumentException("Coordinates in "+files[nfile]+" not assigned to any state. Check if chromosome naming in "+files[nfile]+
1289 " match those in the segmentation file.");
1290 }
1291 }
1292
1293 outputenrichment(szoutfile, files,tallyoverlaplabel, tallylabel, dsumoverlaplabel,theColor,
1294 bcolscaleheat,ChromHMM.convertCharOrderToStringOrder(szlabel.charAt(0)),sztitle,0,szlabelmapping,szlabel.charAt(0), bprintimage,
1295 bstringlabels, hmIndexToLabel, bcenter&&blogpvals, !bunique, nbinsize);
1296 }
1297
1298
1299 //////////////////////////////////////////////////////////////////////////////////////
1300
1301
1302
1303 /**
1304 * Computes an enrichment based on a hard segmentation
1305 * szinputsegment - the file with the segmentation
1306 * szinputcoorddir - the directory containing the coordinates for enrichment
1307 * szinputcoordlist - if non-null only computes enrichments for file names in the specified
1308 * noffsetleft - the amount that should be subtracted from the left coordinate so it is 0-based inclusive
1309 * noffsetright - the amount that should be subtracted from the right coordinate so it is 0-based inclusive
1310 * nbinsize - the binsize used in the segmentation
1311 * bcenter - if true only uses the center of the interval for determining enrichments
1312 * bunique - only counts a bin once, this is not applicable if bbaseres is true or busesignal is true
1313 * busesignal - if true then uses signal information about the interval if available
1314 * szcolfields - comma delimited list of the 0-based columns of chromosme,start,end, and if busesignal is true the signal column
1315 * bbaseres - if true gives enrichment at the base resolution opposed to the bin resolution
1316 * szoutfile - the file to which to output the
1317 * bcolscaleheat - if true scales the heatmap individual for each column otherwise uses the same for all columns
1318 * theColor - theColor to use for the heatmap
1319 */
1320 //this is lowmem
1321 public static void enrichmentMaxLowMem(String szinputsegment,String szinputcoorddir,String szinputcoordlist,
1322 int noffsetleft, int noffsetright,
1323 int nbinsize, boolean bcenter,boolean bunique, boolean busesignal,String szcolfields,
1324 boolean bbaseres, String szoutfile,boolean bcolscaleheat,Color theColor,String sztitle,
1325 String szlabelmapping, boolean bprintimage,
1326 boolean bstringlabels, boolean bbrowser, boolean blogpvals) throws IOException
1327 {
1328
1329
1330 //for each enrichment category and state label gives a count of how often
1331 //overlapped by a segment optionally with signal
1332
1333 String szLine;
1334 String[] files;
1335
1336 if (szinputcoordlist == null)
1337 {
1338 File dir = new File(szinputcoorddir);
1339 //we don't have a specific list of files to include
1340 //will use all files in the directory
1341 if (dir.isDirectory())
1342 {
1343 //throw new IllegalArgumentException(szinputcoorddir+" is not a directory!");
1344 //added in v1.11 to skip hidden files
1345 String[] filesWithHidden = dir.list();
1346 int nnonhiddencount = 0;
1347 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
1348 {
1349 if (!(new File(filesWithHidden[nfile])).isHidden())
1350 {
1351 nnonhiddencount++;
1352 }
1353 }
1354
1355 int nactualindex = 0;
1356 files = new String[nnonhiddencount];// dir.list();
1357 if (nnonhiddencount == 0)
1358 {
1359 throw new IllegalArgumentException("No files found in "+szinputcoorddir);
1360 }
1361
1362 for (int nfile = 0; nfile < filesWithHidden.length; nfile++)
1363 {
1364 if (!(new File(filesWithHidden[nfile])).isHidden())
1365 {
1366 files[nactualindex] = filesWithHidden[nfile];
1367 nactualindex++;
1368 }
1369 }
1370 Arrays.sort(files);
1371 szinputcoorddir += "/";
1372 }
1373 else
1374 {
1375 files = new String[1];
1376 files[0] = szinputcoorddir;
1377 szinputcoorddir = "";
1378 }
1379 }
1380 else
1381 {
1382 szinputcoorddir += "/";
1383 //store in files all file names given in szinputcoordlist
1384 BufferedReader brfiles = Util.getBufferedReader(szinputcoordlist);
1385 ArrayList alfiles = new ArrayList();
1386 while ((szLine = brfiles.readLine())!=null)
1387 {
1388 alfiles.add(szLine);
1389 }
1390 brfiles.close();
1391 files = new String[alfiles.size()];
1392 for (int nfile = 0; nfile < files.length; nfile++)
1393 {
1394 files[nfile] = (String) alfiles.get(nfile);
1395 }
1396 }
1397
1398 ArrayList alchromindex = new ArrayList(); //stores the index of the chromosome
1399
1400 if (busesignal)
1401 {
1402 bunique = false;
1403 }
1404
1405 HashMap hmchromMax = new HashMap(); //maps chromosome to the maximum index
1406 HashMap hmchromToIndex = new HashMap(); //maps chromosome to an index
1407 HashMap hmLabelToIndex = new HashMap(); //maps label to an index
1408 HashMap hmIndexToLabel = new HashMap(); //maps index string to label
1409 int nmaxlabel=0; // the maximum label found
1410 String szlabel="";
1411 boolean busedunderscore = false;
1412 //reads in the segmentation recording maximum position for each chromosome and
1413 //maximum label
1414 BufferedReader brinputsegment = Util.getBufferedReader(szinputsegment);
1415 while ((szLine = brinputsegment.readLine())!=null)
1416 {
1417
1418 //added v1.24
1419 if (bbrowser)
1420 {
1421 if ((szLine.toLowerCase(Locale.ENGLISH).startsWith("browser"))||(szLine.toLowerCase(Locale.ENGLISH).startsWith("track")))
1422 {
1423 continue;
1424 }
1425 }
1426
1427 StringTokenizer st;
1428 if (bstringlabels)
1429 {
1430 st = new StringTokenizer(szLine,"\t");
1431 }
1432 else
1433 {
1434 st = new StringTokenizer(szLine,"\t ");
1435 }
1436
1437 //added in v1.24
1438 int numtokens = st.countTokens();
1439 if (numtokens == 0)
1440 {
1441 //skip blank lines
1442 continue;
1443 }
1444 else if (numtokens < 4)
1445 {
1446 throw new IllegalArgumentException("Line "+szLine+" in "+szinputsegment+" only had "+numtokens+" token(s). Expecting at least 4");
1447 }
1448
1449 String szchrom = st.nextToken().trim();
1450 int nbegincoord = Integer.parseInt(st.nextToken().trim());
1451 int nendcoord = Integer.parseInt(st.nextToken().trim());
1452 if (nbegincoord % nbinsize != 0)
1453 {
1454 throw new IllegalArgumentException("Binsize of "+nbinsize+" does not agree with coordinates in input segment "+szLine+". -b binsize should match parameter value to LearnModel or "+
1455 "MakeSegmentation used to produce segmentation. If segmentation is derived from a lift over from another assembly, then the '-b 1' option should be used");
1456 }
1457 //int nbegin = nbegincoord/nbinsize;
1458 int nend = (nendcoord-1)/nbinsize;
1459 szlabel = st.nextToken().trim();
1460 short slabel;
1461
1462
1463 if (bstringlabels)
1464 {
1465
1466 int nunderscoreindex = szlabel.indexOf("_");
1467
1468 if (nunderscoreindex >=0)
1469 {
1470 String szprefix = szlabel.substring(0,nunderscoreindex);
1471
1472 try
1473 {
1474 slabel = (short) (Short.parseShort(szprefix));
1475 if (slabel > nmaxlabel)
1476 {
1477 nmaxlabel = slabel;
1478 }
1479 busedunderscore = true;
1480 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
1481 hmIndexToLabel.put(""+slabel, szlabel);
1482 }
1483 catch (NumberFormatException ex)
1484 {
1485 try
1486 {
1487 slabel = (short) (Short.parseShort(szprefix.substring(1)));
1488 if (slabel > nmaxlabel)
1489 {
1490 nmaxlabel = slabel;
1491 }
1492 busedunderscore = true;
1493 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
1494 hmIndexToLabel.put(""+slabel, szlabel);
1495 }
1496 catch (NumberFormatException ex2)
1497 {
1498 if (busedunderscore)
1499 {
1500 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
1501 }
1502 }
1503 }
1504 }
1505
1506 if (!busedunderscore)
1507 {
1508 //handle string labels
1509 Short objshort = (Short) hmLabelToIndex.get(szlabel);
1510
1511 if (objshort == null)
1512 {
1513 nmaxlabel = hmLabelToIndex.size()+1;
1514 slabel = (short) nmaxlabel;
1515 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
1516 hmIndexToLabel.put(""+nmaxlabel, szlabel);
1517 }
1518 //else
1519 //{
1520 // slabel = ((Short) objshort).shortValue();
1521 //}
1522 }
1523 }
1524 else
1525 {
1526 try
1527 {
1528 slabel = (short) (Short.parseShort(szlabel));
1529 }
1530 catch (NumberFormatException ex)
1531 {
1532 try
1533 {
1534 slabel = (short) (Short.parseShort(szlabel.substring(1)));
1535 }
1536 catch (NumberFormatException ex2)
1537 {
1538 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
1539 }
1540 }
1541
1542 //alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
1543 if (slabel > nmaxlabel)
1544 {
1545 nmaxlabel = slabel;
1546 }
1547 }
1548
1549 Integer objMax = (Integer) hmchromMax.get(szchrom);
1550 if (objMax == null)
1551 {
1552 //System.out.println("on chrom "+szchrom);
1553 hmchromMax.put(szchrom,Integer.valueOf(nend));
1554 hmchromToIndex.put(szchrom, Integer.valueOf(hmchromToIndex.size()));
1555 alchromindex.add(szchrom);
1556 }
1557 else
1558 {
1559 int ncurrmax = objMax.intValue();
1560 if (ncurrmax < nend)
1561 {
1562 hmchromMax.put(szchrom, Integer.valueOf(nend));
1563 }
1564 }
1565 }
1566 brinputsegment.close();
1567
1568 double[][] tallyoverlaplabel = new double[files.length][nmaxlabel+1];
1569 double[] dsumoverlaplabel = new double[files.length];
1570 double[] tallylabel = new double[nmaxlabel+1];
1571
1572 int numchroms = alchromindex.size();
1573
1574 for (int nchrom = 0; nchrom < numchroms; nchrom++)
1575 {
1576 //ArrayList alsegments = new ArrayList(); //stores all the segments
1577 String szchromwant = (String) alchromindex.get(nchrom);
1578 //System.out.println("processing "+szchromwant);
1579 int nsize = ((Integer) hmchromMax.get(szchromwant)).intValue()+1;
1580 short[] labels = new short[nsize]; //stores the hard label assignments
1581
1582 //sets to -1 so missing segments not counted as label 0
1583 for (int npos = 0; npos < nsize; npos++)
1584 {
1585 labels[npos] = -1;
1586 }
1587
1588 brinputsegment = Util.getBufferedReader(szinputsegment);
1589 while ((szLine = brinputsegment.readLine())!=null)
1590 {
1591 StringTokenizer st;
1592 if (bstringlabels)
1593 {
1594 st = new StringTokenizer(szLine,"\t");
1595 }
1596 else
1597 {
1598 st = new StringTokenizer(szLine,"\t ");
1599 }
1600
1601 String szchrom = st.nextToken().trim();
1602 if (!szchrom.equals(szchromwant))
1603 continue;
1604
1605 int nbegincoord = Integer.parseInt(st.nextToken().trim());
1606 int nendcoord = Integer.parseInt(st.nextToken().trim());
1607
1608 //if (nbegincoord % nbinsize != 0)
1609 // {
1610 // throw new IllegalArgumentException("Binsize of "+nbinsize+" does not agree with input segment "+szLine);
1611 //}
1612 int nbegin = nbegincoord/nbinsize;
1613 int nend = (nendcoord-1)/nbinsize;
1614 szlabel = st.nextToken().trim();
1615 short slabel = -1;
1616
1617 if (bstringlabels)
1618 {
1619 int nunderscoreindex = szlabel.indexOf("_");
1620
1621 if (nunderscoreindex >=0)
1622 {
1623 String szprefix = szlabel.substring(0,nunderscoreindex);
1624
1625 try
1626 {
1627 slabel = (short) (Short.parseShort(szprefix));
1628 busedunderscore = true;
1629 }
1630 catch (NumberFormatException ex)
1631 {
1632 try
1633 {
1634 slabel = (short) (Short.parseShort(szprefix.substring(1)));
1635 busedunderscore = true;
1636 }
1637 catch (NumberFormatException ex2)
1638 {
1639 if (busedunderscore)
1640 {
1641 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
1642 }
1643 }
1644 }
1645 }
1646
1647 if (!busedunderscore)
1648 {
1649 //handle string labels
1650 Short objshort = (Short) hmLabelToIndex.get(szlabel);
1651 slabel = ((Short) objshort).shortValue();
1652 }
1653 }
1654 else
1655 {
1656 try
1657 {
1658 slabel = (short) (Short.parseShort(szlabel));
1659 }
1660 catch (NumberFormatException ex)
1661 {
1662 try
1663 {
1664 slabel = (short) (Short.parseShort(szlabel.substring(1)));
1665 }
1666 catch (NumberFormatException ex2)
1667 {
1668 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
1669 }
1670 }
1671 }
1672
1673 if (nbegin < 0)
1674 {
1675 nbegin = 0;
1676 }
1677
1678 if (nend >= labels.length)
1679 {
1680 nend = labels.length - 1;
1681 }
1682
1683 //SegmentRec theSegmentRec = (SegmentRec) alsegments.get(nindex);
1684 //int nbegin = theSegmentRec.nbegin;
1685 //int nend = theSegmentRec.nend;
1686 //short slabel = theSegmentRec.slabel;
1687 //int nchrom = ((Integer) hmchromToIndex.get(theSegmentRec.szchrom)).intValue();
1688 //short[] labels_nchrom = labels[nchrom];
1689 //stores each label position in the genome
1690 for (int npos = nbegin; npos <= nend; npos++)
1691 {
1692 if ((!StateAnalysis.bfounddup) &&(labels[npos] >= 0)&&(labels[npos]!=slabel))
1693 {
1694 StateAnalysis.bfounddup = true;
1695 System.out.println("WARNING: found the same position assigned to multiple states. First example found: "+szchrom+
1696 ":"+(npos*nbinsize+1)+". Will use the last occurrence in file.");
1697
1698 }
1699 labels[npos] = slabel;
1700 //tallylabel[slabel]++;
1701 }
1702 tallylabel[slabel] += (nend-nbegin)+1;
1703 }
1704
1705
1706 for (int nfile = 0; nfile < files.length; nfile++)
1707 {
1708 double[] tallyoverlaplabel_nfile = tallyoverlaplabel[nfile];
1709
1710 int nchromindex = 0;
1711 int nstartindex = 1;
1712 int nendindex = 2;
1713 int nsignalindex = 3;
1714
1715 if (szcolfields != null)
1716 {
1717 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
1718 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
1719 nstartindex = Integer.parseInt(stcolfields.nextToken().trim());
1720 nendindex = Integer.parseInt(stcolfields.nextToken().trim());
1721
1722 if (busesignal)
1723 {
1724 nsignalindex = Integer.parseInt(stcolfields.nextToken().trim());
1725 }
1726 }
1727
1728
1729 if (bunique)
1730 {
1731 //Iterator itrChroms = hmchromToIndex.entrySet().iterator();
1732 //while (itrChroms.hasNext())
1733 //{
1734 //Map.Entry pairs = (Map.Entry) itrChroms.next();
1735 //String szchrom =(String) pairs.getKey();
1736 //int nchrom = ((Integer) pairs.getValue()).intValue();
1737 //short[] labels_nchrom = labels[nchrom];
1738
1739 //reading in the coordinates to overlap with
1740 BufferedReader brcoords = Util.getBufferedReader(szinputcoorddir +files[nfile]);
1741
1742 ArrayList alrecs = new ArrayList();
1743 while ((szLine = brcoords.readLine())!=null)
1744 {
1745 if (szLine.trim().equals("")) continue;
1746 String[] szLineA = szLine.split("\\s+");
1747
1748 if (nchromindex >= szLineA.length)
1749 {
1750 throw new IllegalArgumentException(nchromindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1751 }
1752
1753 String szcurrchrom = szLineA[nchromindex];
1754 if (szchromwant.equals(szcurrchrom))
1755 {
1756 if (nstartindex >= szLineA.length)
1757 {
1758 throw new IllegalArgumentException(nstartindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1759 }
1760
1761 if (nendindex >= szLineA.length)
1762 {
1763 throw new IllegalArgumentException(nendindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1764 }
1765
1766 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
1767 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
1768 if (bcenter)
1769 {
1770 nbeginactual = (nbeginactual+nendactual)/2;
1771 nendactual = nbeginactual;
1772 }
1773 alrecs.add(new Interval(nbeginactual,nendactual));
1774 }
1775 }
1776 brcoords.close();
1777
1778 Object[] alrecA = alrecs.toArray();
1779 Arrays.sort(alrecA,new IntervalCompare());
1780
1781 boolean bclosed = true;
1782 int nintervalstart = -1;
1783 int nintervalend = -1;
1784 boolean bdone = false;
1785
1786 for (int nindex = 0; (nindex <= alrecA.length&&(alrecA.length>0)); nindex++)
1787 {
1788 int ncurrstart = -1;
1789 int ncurrend = -1;
1790
1791 if (nindex == alrecA.length)
1792 {
1793 bdone = true;
1794 }
1795 else
1796 {
1797 ncurrstart = ((Interval) alrecA[nindex]).nstart;
1798 ncurrend = ((Interval) alrecA[nindex]).nend;
1799 if (nindex == 0)
1800 {
1801 nintervalstart = ncurrstart;
1802 nintervalend = ncurrend;
1803 }
1804 else if (ncurrstart <= nintervalend)
1805 {
1806 //this read is still in the active interval
1807 //extending the current active interval
1808 if (ncurrend > nintervalend)
1809 {
1810 nintervalend = ncurrend;
1811 }
1812 }
1813 else
1814 {
1815 //just finished the current active interval
1816 bdone = true;
1817 }
1818 }
1819
1820 if (bdone)
1821 {
1822 int nbegin = nintervalstart/nbinsize;
1823 int nend = nintervalend/nbinsize;
1824
1825 if (nbegin < 0)
1826 {
1827 nbegin = 0;
1828 }
1829
1830 if (nend >= labels.length)
1831 {
1832 nend = labels.length - 1;
1833 }
1834
1835 for (int nbin = nbegin; nbin <= nend; nbin++)
1836 {
1837 if (labels[nbin]>=0)
1838 {
1839 tallyoverlaplabel_nfile[labels[nbin]]++;
1840 }
1841 }
1842
1843 if (bbaseres)
1844 {
1845 //dbeginfrac represents the fraction of bases the nbegin interval
1846 //which came after the actual nbeginactual
1847 double dbeginfrac = (nintervalstart - nbegin*nbinsize)/(double) nbinsize;
1848
1849 //dendfrac represents the fraction of bases after the end position in the interval
1850 double dendfrac = ((nend+1)*nbinsize-nintervalend-1)/(double) nbinsize;
1851
1852 if ((nbegin < labels.length)&&(labels[nbegin]>=0)&&(dbeginfrac>0))
1853 {
1854 //only counted the bases if nbegin was less than labels.length
1855 tallyoverlaplabel_nfile[labels[nbegin]]-=dbeginfrac;
1856 }
1857
1858 if ((nend < labels.length)&&(labels[nend]>=0)&&(dendfrac>0))
1859 {
1860 //only counted the bases if nend was less than labels.length
1861 tallyoverlaplabel_nfile[labels[nend]]-=dendfrac;
1862 }
1863 }
1864
1865 nintervalstart = ncurrstart;
1866 nintervalend = ncurrend;
1867 bdone = false;
1868 }
1869 }
1870 //}
1871 }
1872 else
1873 {
1874 BufferedReader brcoords = Util.getBufferedReader(szinputcoorddir +files[nfile]);
1875
1876 while ((szLine = brcoords.readLine())!=null)
1877 {
1878 if (szLine.trim().equals("")) continue;
1879 String[] szLineA = szLine.split("\\s+");
1880
1881 if (nchromindex >= szLineA.length)
1882 {
1883 throw new IllegalArgumentException(nchromindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1884 }
1885
1886 String szchrom = szLineA[nchromindex];
1887 if (!szchromwant.equals(szchrom))
1888 continue;
1889
1890 if (nstartindex >= szLineA.length)
1891 {
1892 throw new IllegalArgumentException(nstartindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1893 }
1894
1895 if (nendindex >= szLineA.length)
1896 {
1897 throw new IllegalArgumentException(nendindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1898 }
1899
1900 int nbeginactual =Integer.parseInt(szLineA[nstartindex])-noffsetleft;
1901 int nbegin = nbeginactual/nbinsize;
1902
1903 int nendactual =Integer.parseInt(szLineA[nendindex])-noffsetright;
1904 int nend = nendactual/nbinsize;
1905
1906 double damount;
1907 if ((busesignal)&&(nsignalindex < szLineA.length))
1908 {
1909 if (nsignalindex >= szLineA.length)
1910 {
1911 throw new IllegalArgumentException(nsignalindex+" is an invalid column index for line "+szLine+" in "+szinputcoorddir+files[nfile]);
1912 }
1913 damount = Double.parseDouble(szLineA[nsignalindex]);
1914
1915 if (damount < 0)
1916 {
1917 throw new IllegalArgumentException("A negative weight of "+damount+" was found in "+szinputcoorddir+files[nfile]+
1918 " but weights are assumed to be non-negative");
1919 }
1920 }
1921 else
1922 {
1923 //fix in v1.26
1924 damount = 1.0/(double)nbinsize;
1925 }
1926
1927 //Integer objChrom = (Integer) hmchromToIndex.get(szchrom);
1928 //if (objChrom != null)
1929 //{
1930 //we have the chromosome corresponding to this read
1931 //int nchrom = objChrom.intValue();
1932 //short[] labels_nchrom = labels[nchrom];
1933
1934 if (bcenter)
1935 {
1936 //using the center position of the interval only
1937 int ncenter = (nbeginactual+nendactual)/(2*nbinsize);
1938 if ((ncenter < labels.length)&&(labels[ncenter]>=0))
1939 {
1940 tallyoverlaplabel_nfile[labels[ncenter]]+=damount;
1941 }
1942 }
1943 else
1944 {
1945 if (nbegin < 0)
1946 {
1947 nbegin = 0;
1948 }
1949 //using the full interval range
1950 //no requirement on uniqueness
1951 if (nend >= labels.length)
1952 {
1953 nend = labels.length - 1;
1954 }
1955
1956 for (int nindex = nbegin; nindex <= nend; nindex++)
1957 {
1958 if (labels[nindex]>=0)
1959 {
1960 //increment overlap tally not checking for uniqueness
1961 tallyoverlaplabel_nfile[labels[nindex]]+=damount;
1962 }
1963 }
1964
1965 if (bbaseres)
1966 {
1967 //dbeginfrac represents the fraction of bases the nbegin interval
1968 //which came after the actual nbeginactual
1969 double dbeginfrac = (nbeginactual - nbegin*nbinsize)/(double) nbinsize;
1970
1971 //dendfrac represents the fraction of bases after the end position in the interval
1972 double dendfrac = ((nend+1)*nbinsize-nendactual-1)/(double) nbinsize;
1973
1974 if ((nbegin < labels.length)&&(labels[nbegin]>=0)&&(dbeginfrac>0))
1975 {
1976 //only counted the bases if nbegin was less than labels.length
1977 tallyoverlaplabel_nfile[labels[nbegin]]-=damount*dbeginfrac;
1978 }
1979
1980 if ((nend < labels.length)&&(labels[nend]>=0)&&(dendfrac>0))
1981 {
1982 //only counted the bases if nend was less than labels.length
1983 tallyoverlaplabel_nfile[labels[nend]]-=damount*dendfrac;
1984 }
1985 }
1986 }
1987 }
1988 brcoords.close();
1989 }
1990 }
1991 }
1992
1993
1994 for (int nfile = 0; nfile < files.length; nfile++)
1995 {
1996 double[] tallyoverlaplabel_nfile = tallyoverlaplabel[nfile];
1997
1998 for (int nindex = 0; nindex < tallyoverlaplabel_nfile.length; nindex++)
1999 {
2000 dsumoverlaplabel[nfile] += tallyoverlaplabel_nfile[nindex];
2001 }
2002
2003 if (dsumoverlaplabel[nfile] < EPSILONOVERLAP) // 0.00000001)
2004 {
2005 throw new IllegalArgumentException("Coordinates in "+files[nfile]+" not assigned to any state. Check if chromosome naming in "+files[nfile]+
2006 " match those in the segmentation file.");
2007 }
2008 }
2009
2010 outputenrichment(szoutfile, files,tallyoverlaplabel, tallylabel, dsumoverlaplabel,theColor,
2011 bcolscaleheat,ChromHMM.convertCharOrderToStringOrder(szlabel.charAt(0)),sztitle,0,szlabelmapping,szlabel.charAt(0), bprintimage, bstringlabels, hmIndexToLabel, bcenter&&blogpvals, !bunique,nbinsize);
2012 }
2013
2014
2015
2016
2017
2018 /////////////////////////////////////////////////////////////////
2019 /**
2020 * Loads contents of szlabelmapping into a HashMap
2021 */
2022 private static HashMap makeLabelMapping(String szlabelmapping) throws IOException
2023 {
2024 HashMap hmlabelExtend = new HashMap();
2025 if (szlabelmapping != null)
2026 {
2027 BufferedReader bridlabel = Util.getBufferedReader(szlabelmapping);
2028 String szLine;
2029
2030 //Loading in a mapping from state ID to a label description
2031
2032 while ((szLine = bridlabel.readLine())!=null)
2033 {
2034 StringTokenizer st = new StringTokenizer(szLine,"\t");
2035 String szID = st.nextToken().trim();
2036 String szLabelExtend = st.nextToken().trim();
2037 hmlabelExtend.put(szID,szLabelExtend);
2038 }
2039 bridlabel.close();
2040 }
2041
2042 return hmlabelExtend;
2043 }
2044
2045 ////////////////////////////////////////////////////////////////////////////////////////////////
2046 /**
2047 * Prints the enrichment to a text file and heatmap for the enrichment tallies
2048 */
2049 private static void outputenrichment(String szoutfile,String[] files,double[][] tallyoverlaplabel,
2050 double[] tallylabel, double[] dsumoverlaplabel,Color theColor,
2051 boolean bcolscaleheat,String szstateorder,String sztitle, int noffset,
2052 String szlabelmapping,char chorder, boolean bprintimage,
2053 boolean bstringlabels, HashMap hmIndexToLabel,
2054 boolean blogpvals, boolean bbinomial,int nbinsize) throws IOException
2055 {
2056
2057 HashMap hmlabelExtend = makeLabelMapping(szlabelmapping);
2058
2059 double dsumlabel = 0;
2060 for (int ni = 0; ni < tallylabel.length; ni++)
2061 {
2062 dsumlabel += tallylabel[ni];
2063 }
2064
2065 NumberFormat nf5 = NumberFormat.getInstance();
2066 nf5.setMaximumFractionDigits(5);
2067 nf5.setGroupingUsed(false);
2068 nf5.setMinimumFractionDigits(5);
2069
2070 NumberFormat nf10 = NumberFormat.getInstance();
2071 nf10.setMaximumFractionDigits(10);
2072 nf10.setGroupingUsed(false);
2073 nf10.setMinimumFractionDigits(10);
2074
2075 System.out.println("Writing to file "+szoutfile+".txt");
2076 PrintWriter pw = new PrintWriter(new FileWriter(szoutfile+".txt"));
2077
2078
2079 //added v1.26
2080 PrintWriter pwlogpval = null;
2081 if (blogpvals)
2082 {
2083 System.out.println("Writing to file "+szoutfile+"_log10pvals.txt");
2084 pwlogpval = new PrintWriter(new FileWriter(szoutfile+"_log10pvals.txt"));
2085 }
2086
2087 //added v1.26
2088 if (bcolscaleheat)
2089 {
2090 pw.print("State ("+szstateorder+" order)\tGenome %");
2091
2092 if (blogpvals)
2093 {
2094 pwlogpval.print("State ("+szstateorder+" order)\tGenome %");
2095 }
2096 }
2097 else
2098 {
2099 pw.print("State ("+szstateorder+" order)");
2100
2101 if (blogpvals)
2102 {
2103 pwlogpval.print("State ("+szstateorder+" order)");
2104 }
2105 }
2106
2107 for (int nfile = 0; nfile < files.length; nfile++)
2108 {
2109 pw.print("\t"+files[nfile]);
2110 }
2111 pw.println();
2112
2113 if (blogpvals)
2114 {
2115 for (int nfile = 0; nfile < files.length; nfile++)
2116 {
2117 pwlogpval.print("\t"+files[nfile]);
2118 }
2119 pwlogpval.println();
2120 }
2121
2122
2123 double[][] heatmapfold;
2124
2125
2126 if (bcolscaleheat)
2127 {
2128 heatmapfold = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length+1];
2129 }
2130 else
2131 {
2132 heatmapfold = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length];
2133 }
2134
2135 double[][] heatmaplogpval = null;
2136 if (blogpvals)
2137 {
2138 if (bcolscaleheat)
2139 {
2140 heatmaplogpval = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length+1];
2141 }
2142 else
2143 {
2144 heatmaplogpval = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length];
2145 }
2146 }
2147
2148 int numelim = 0;
2149
2150 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
2151 {
2152 if (tallylabel[nstate] > 0)
2153 {
2154 if (bstringlabels)
2155 {
2156 pw.print(hmIndexToLabel.get(""+nstate));
2157
2158 if (blogpvals)
2159 {
2160 pwlogpval.print(hmIndexToLabel.get(""+nstate));
2161 }
2162 }
2163 else
2164 {
2165 pw.print(nstate+noffset);
2166 if (blogpvals)
2167 {
2168 pwlogpval.print(nstate+noffset);
2169 }
2170 String szsuffix;
2171
2172 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(nstate+noffset)))!=null)
2173 {
2174 pw.print("_"+szsuffix);
2175
2176 if (blogpvals)
2177 {
2178 pwlogpval.print("_"+szsuffix);
2179 }
2180 }
2181 }
2182
2183 if (bcolscaleheat)
2184 {
2185 //only include genome % if scaling by column
2186 heatmapfold[nstate][0] =100*(tallylabel[nstate]/dsumlabel); //first column is heatmap
2187 pw.print("\t"+nf5.format(heatmapfold[nstate][0]));
2188
2189 if (blogpvals)
2190 {
2191 heatmaplogpval[nstate][0] = 100*(tallylabel[nstate]/dsumlabel);
2192 pwlogpval.print("\t"+nf5.format(heatmaplogpval[nstate][0]));
2193 }
2194 }
2195 for (int nfile = 0; nfile < tallyoverlaplabel.length; nfile++)
2196 {
2197 //numerator is fraction of total of category in state while denominator is total fraction state is
2198 double dfold = (tallyoverlaplabel[nfile][nstate]/dsumoverlaplabel[nfile])/
2199 (tallylabel[nstate]/dsumlabel);
2200 if (bcolscaleheat)
2201 {
2202 heatmapfold[nstate][nfile+1] = dfold;
2203 }
2204 else
2205 {
2206 heatmapfold[nstate][nfile] = dfold;
2207 }
2208
2209 pw.print("\t"+nf5.format(dfold));
2210
2211 if (blogpvals)
2212 {
2213 double dlogpval;
2214 if (bbinomial)
2215 {
2216 dlogpval = -Math.log(binomialtail(Math.round(tallyoverlaplabel[nfile][nstate]*nbinsize-1),
2217 Math.round(dsumoverlaplabel[nfile]*nbinsize),
2218 tallylabel[nstate]/dsumlabel))/Math.log(10);
2219
2220 }
2221 else
2222 {
2223
2224 dlogpval = -Math.log(hypergeometrictail(Math.round(tallyoverlaplabel[nfile][nstate]*nbinsize-1),
2225 Math.round(tallylabel[nstate]*nbinsize),
2226 Math.round((dsumlabel- tallylabel[nstate])*nbinsize),
2227 Math.round(dsumoverlaplabel[nfile]*nbinsize)))/Math.log(10);
2228 }
2229
2230 if (dlogpval > PVALLOG10CUTOFF)
2231 {
2232 dlogpval = PVALLOG10CUTOFF;
2233 }
2234 else if (dlogpval == -0)
2235 {
2236 dlogpval = 0;
2237 }
2238
2239 if (bcolscaleheat)
2240 {
2241 heatmaplogpval[nstate][nfile+1] = dlogpval;
2242 }
2243 else
2244 {
2245 heatmaplogpval[nstate][nfile] = dlogpval;
2246 }
2247
2248 pwlogpval.print("\t"+nf5.format(dlogpval));
2249 }
2250
2251 }
2252 pw.println();
2253
2254 if (blogpvals)
2255 {
2256 pwlogpval.println();
2257 }
2258 }
2259 else
2260 {
2261 numelim++;
2262 }
2263 }
2264
2265 //added v1.26
2266 if (bcolscaleheat)
2267 {
2268 pw.print("Base\t100");
2269 }
2270 else
2271 {
2272 pw.print("Base");
2273 }
2274
2275 for (int nfile = 0; nfile < tallyoverlaplabel.length; nfile++)
2276 {
2277 pw.print("\t"+nf10.format(100*(dsumoverlaplabel[nfile]/dsumlabel)));
2278 }
2279
2280 pw.println();
2281 pw.close();
2282
2283
2284
2285 if (blogpvals)
2286 {
2287 //added v1.26
2288 if (bcolscaleheat)
2289 {
2290 pwlogpval.print("Base\t100");
2291 }
2292 else
2293 {
2294 pwlogpval.print("Base");
2295 }
2296
2297 for (int nfile = 0; nfile < tallyoverlaplabel.length; nfile++)
2298 {
2299 pwlogpval.print("\t"+nf10.format(100*(dsumoverlaplabel[nfile]/dsumlabel)));
2300 }
2301
2302 pwlogpval.println();
2303 pwlogpval.close();
2304 }
2305
2306 String[] rowlabels;// = new String[tallyoverlaplabel[0].length];
2307 if (numelim > 0)
2308 {
2309 double[][] heatmapreduce = new double[heatmapfold.length-numelim][heatmapfold[0].length];
2310
2311 double[][] heatmapreducelogpval = null;
2312 if (blogpvals)
2313 {
2314 heatmapreducelogpval = new double[heatmaplogpval.length-numelim][heatmaplogpval[0].length];
2315 }
2316 rowlabels = new String[heatmapreduce.length];
2317 int nkeepindex = 0;
2318 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
2319 {
2320 if (tallylabel[nstate] > 0)
2321 {
2322 for (int ncol = 0; ncol < heatmapfold[nstate].length; ncol++)
2323 {
2324 heatmapreduce[nkeepindex][ncol] = heatmapfold[nstate][ncol];
2325
2326 if (blogpvals)
2327 {
2328 heatmapreducelogpval[nkeepindex][ncol] = heatmaplogpval[nstate][ncol];
2329 }
2330 }
2331
2332 if (bstringlabels)
2333 {
2334 rowlabels[nkeepindex] = (String) hmIndexToLabel.get(""+nstate);
2335 }
2336 else
2337 {
2338 rowlabels[nkeepindex] = ""+(nstate+noffset);
2339 }
2340 nkeepindex++;
2341 }
2342 }
2343 heatmapfold = heatmapreduce;
2344 }
2345 else
2346 {
2347 rowlabels = new String[tallyoverlaplabel[0].length];
2348 if (bstringlabels)
2349 {
2350 for (int ni = 0; ni < rowlabels.length; ni++)
2351 {
2352 rowlabels[ni] = (String) hmIndexToLabel.get(""+ni);
2353 }
2354 }
2355 else
2356 {
2357 for (int ni = 0; ni < rowlabels.length; ni++)
2358 {
2359 rowlabels[ni] = ""+(ni+noffset);
2360 }
2361 }
2362 }
2363
2364
2365 if (!bstringlabels)
2366 {
2367 for (int ni = 0; ni < rowlabels.length; ni++)
2368 {
2369 String szsuffix;
2370 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+rowlabels[ni]))!=null)
2371 {
2372 rowlabels[ni] = rowlabels[ni]+"_"+szsuffix;
2373 }
2374 }
2375 }
2376
2377 if (bcolscaleheat)
2378 {
2379 for (int nfile = 0; nfile < heatmapfold[0].length; nfile++)
2380 {
2381 double dmaxval = Double.NEGATIVE_INFINITY;
2382 double dminval = Double.POSITIVE_INFINITY;
2383
2384 for (int nstate = 0; nstate < heatmapfold.length; nstate++)
2385 {
2386 if (heatmapfold[nstate][nfile] > dmaxval)
2387 {
2388 dmaxval = heatmapfold[nstate][nfile];
2389 }
2390
2391 if (heatmapfold[nstate][nfile] < dminval)
2392 {
2393 dminval = heatmapfold[nstate][nfile];
2394 }
2395 }
2396
2397 for (int nstate = 0; nstate < heatmapfold.length; nstate++)
2398 {
2399 heatmapfold[nstate][nfile] =(heatmapfold[nstate][nfile]-dminval)/dmaxval;
2400 }
2401 }
2402
2403 if (blogpvals)
2404 {
2405 for (int nfile = 0; nfile < heatmaplogpval[0].length; nfile++)
2406 {
2407 double dmaxval = Double.NEGATIVE_INFINITY;
2408 double dminval = Double.POSITIVE_INFINITY;
2409
2410 for (int nstate = 0; nstate < heatmaplogpval.length; nstate++)
2411 {
2412 if (heatmaplogpval[nstate][nfile] > dmaxval)
2413 {
2414 dmaxval = heatmaplogpval[nstate][nfile];
2415 }
2416
2417 if (heatmaplogpval[nstate][nfile] < dminval)
2418 {
2419 dminval = heatmaplogpval[nstate][nfile];
2420 }
2421 }
2422
2423 for (int nstate = 0; nstate < heatmaplogpval.length; nstate++)
2424 {
2425 heatmaplogpval[nstate][nfile] =(heatmaplogpval[nstate][nfile]-dminval)/dmaxval;
2426 }
2427 }
2428 }
2429 }
2430
2431 String[] collabels = new String[heatmapfold[0].length];
2432 if (bcolscaleheat)
2433 {
2434 collabels[0] = "Genome %";
2435 }
2436
2437 for (int ni = 0; ni < files.length; ni++)
2438 {
2439 int nfirstindex = files[ni].indexOf('.');
2440 if (nfirstindex == -1)
2441 {
2442 if (bcolscaleheat)
2443 {
2444 collabels[ni+1] = files[ni];
2445 }
2446 else
2447 {
2448 collabels[ni] = files[ni];
2449 }
2450 }
2451 else
2452 {
2453 String szsub = files[ni].substring(0,nfirstindex);
2454
2455 if (bcolscaleheat)
2456 {
2457 collabels[ni+1] = szsub;
2458 }
2459 else
2460 {
2461 collabels[ni] = szsub;
2462 }
2463 }
2464 }
2465
2466
2467 if (bprintimage)
2468 {
2469 makeEnrichmentHeatMap(heatmapfold, collabels, rowlabels,szoutfile,theColor,sztitle,
2470 "Category","State ("+szstateorder+" order)");
2471
2472 if (blogpvals)
2473 {
2474 makeEnrichmentHeatMap(heatmaplogpval, collabels, rowlabels,szoutfile+"_log10pvals",theColor,sztitle,
2475 "Category","State ("+szstateorder+" order)");
2476 }
2477 }
2478 }
2479
2480 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2481 /**
2482 *this hashtable caches previously computed binomial coefficient values so they do not need to be recomputed
2483 */
2484 public static Hashtable htbinom =new Hashtable();
2485
2486 /**
2487 * Code based on STEM/DREM code I (Jason Ernst) previously wrote
2488 *Returns the log of the binomial coefficient N choose ni
2489 */
2490 public static double logbinomcoeff(long ni, long N)
2491 {
2492 String sz = ni+";"+N;
2493 Double dobj = (Double) htbinom.get(sz);
2494 double dsum;
2495
2496 if (dobj != null)
2497 {
2498 dsum = ((Double) dobj).doubleValue();
2499 }
2500 else
2501 {
2502 dsum = 0;
2503 long dmax = Math.max(ni,N-ni);
2504 long dmin = Math.min(ni,N-ni);
2505
2506 //the log of the part of the numerator not cancelled by
2507 //the larger factorial in the denominator
2508 for (long nj = dmax+1; nj <=N; nj++)
2509 {
2510 dsum += Math.log(nj);
2511 }
2512
2513 //subtract off the log of the denominator of the smaller term
2514 for (long nj = 2; nj <=dmin; nj++)
2515 {
2516 dsum -= Math.log(nj);
2517 }
2518 //store it
2519 htbinom.put(sz,new Double(dsum));
2520 }
2521
2522 return dsum;
2523 }
2524
2525
2526 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2527
2528
2529 /**
2530 * Code based on STEM/DREM code I (Jason Ernst) previously wrote
2531 * Computes the probability of seeing more than nx successes in nN trials
2532 * where the probability of a success is dp.
2533 */
2534 public static double binomialtail(long nx,long nN, double dp)
2535 {
2536 if (nx > nN)
2537 {
2538 return 0;
2539 }
2540 else if ((nx < 0)||(dp<=0)||(dp>=1))
2541 {
2542 return 1;
2543 }
2544
2545 nx++;
2546 double dterm = logbinomcoeff(nx, nN);
2547 double dpv1 = Math.log(dp);
2548 double dpv2 = Math.log(1-dp);
2549
2550 dterm += nx*dpv1+(nN-nx)*dpv2;
2551
2552 double dlogprob = dterm;
2553 double dpdiff = dpv1-dpv2;
2554 double dprob;
2555 for (long ni = nx+1; ni <= nN; ni++)
2556 {
2557 //N!/(ni!(N-ni)!)
2558 //N!/((ni-1)!(N-ni+1)!)
2559 dterm += Math.log(nN-ni+1) - Math.log(ni) + dpdiff;
2560
2561 if (dterm >= dlogprob)
2562 {
2563 dlogprob = dterm + Math.log(1+Math.pow(Math.E,dlogprob-dterm));
2564 }
2565 else
2566 {
2567 dlogprob = dlogprob + Math.log(1+Math.pow(Math.E,dterm-dlogprob));
2568 }
2569 }
2570 dprob = Math.pow(Math.E,dlogprob);
2571
2572 if (dprob <= 0)
2573 {
2574 return 0;
2575 }
2576 else if (dprob >= 1)
2577 {
2578 return 1;
2579 }
2580 else
2581 {
2582 return dprob;
2583 }
2584 }
2585
2586
2587
2588 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2589
2590 /**
2591 * Code based on STEM/DREM code I (Jason Ernst) previously wrote
2592 * Returns the probability of seeing more than nx objects of type A, when there are nA objects of type A
2593 * nB objects of type B, and nm objects total drawn
2594 * This can be used to compute a more accurate p-values than a 1-cumulative probability calculation
2595 */
2596 public static double hypergeometrictail(long nx, long nA, long nB, long nm)
2597 {
2598 if (nx < 0)
2599 {
2600 return 1;
2601 }
2602
2603 double dprob = 0;
2604
2605
2606 long nminx = Math.max(nx+1,0); //the first element to the right of x or 0
2607 long nmaxx = Math.min(nA,nm); //the max of type A there can be
2608
2609 if (nminx > nmaxx)
2610 {
2611 //if nx approaches infinity tail should be 0
2612 return 0;
2613 }
2614
2615 double dsum = -logbinomcoeff(nm, nA + nB)+ logbinomcoeff(nminx, nA)
2616 + logbinomcoeff(nm-nminx, nB);
2617
2618 double dlogprob=dsum;
2619 for (long ni = nminx+1; ni <= nmaxx; ni++)
2620 {
2621 //computing the increase in probability mass
2622 //numerator has nA!/(ni!(nA-ni)!) * nB!/((nm-ni)!(nB-nm+ni)!)
2623 //denominator has (nA+nB)!/(nm!(nA+nB-nm)!)
2624
2625 //numerator has nA!/((ni-1)!(nA-ni+1)!) * nB!/((nm-ni+1)!(nB-nm+ni-1)!)
2626 //denominator has (nA+nB)!/(nm!(nA+nB-nm)!)
2627
2628 //cancelling gives
2629 //1/(ni!(nA-ni)!) * 1/((nm-ni)!(nB-nm+ni)!) over
2630 //1/((ni-1)!(nA-ni+1)!) * 1/((nm-ni+1)!(nB-nm+ni-1)!)
2631 dsum += Math.log(nA-ni+1)-Math.log(nB-nm+ni)
2632 + Math.log(nm-ni+1)-Math.log(ni);
2633
2634
2635 //log(a+b+c+d+e)
2636 //log(e) + log(a+b+c+d+e) - log(e)
2637 //log(e) + log((a+b+c+d+e)/e)
2638 //log(e) + log(1+(a+b+c+d)/e)
2639 //log(e) + log(1+Math.exp(log(a+b+c+d)-log(e)))
2640
2641 if (dsum >= dlogprob)
2642 {
2643 dlogprob = dsum + Math.log(1+Math.pow(Math.E,dlogprob-dsum));
2644 }
2645 else
2646 {
2647 dlogprob = dlogprob + Math.log(1+Math.pow(Math.E,dsum-dlogprob));
2648 }
2649 }
2650
2651 dprob = Math.pow(Math.E,dlogprob);
2652
2653
2654 if (dprob <= 0)
2655 {
2656 return 0;
2657 }
2658 else if (dprob >= 1)
2659 {
2660 return 1;
2661 }
2662 else
2663 {
2664 return dprob;
2665 }
2666 }
2667
2668 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2669 /**
2670 * Record have the index of the chromsome, coordinate position, strand, and signal
2671 */
2672 private static class RecAnchorIndex
2673 {
2674 int nchromindex;
2675 int npositionindex;
2676 int nstrandindex;
2677 int nsignalindex;
2678
2679 RecAnchorIndex(int nchromindex, int npositionindex, int nstrandindex, int nsignalindex)
2680 {
2681 this.nchromindex = nchromindex;
2682 this.npositionindex = npositionindex;
2683 this.nstrandindex = nstrandindex;
2684 this.nsignalindex = nsignalindex;
2685 }
2686 }
2687
2688 /**
2689 * Returns a Record of the indicies as determined by the contents of szcolfields, busestrand, and busesignal
2690 * of the chromosome, coordinate, strand and signal positions
2691 */
2692 private static RecAnchorIndex getAnchorIndex(String szcolfields, boolean busestrand, boolean busesignal)
2693 {
2694 int nchromindex=0;
2695 int npositionindex=1;
2696 int nstrandindex=2;
2697 int nsignalindex=3;
2698
2699 if (busestrand && busesignal)
2700 {
2701 if (szcolfields != null)
2702 {
2703 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
2704 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
2705 npositionindex = Integer.parseInt(stcolfields.nextToken().trim());
2706 nstrandindex = Integer.parseInt(stcolfields.nextToken().trim());
2707 nsignalindex = Integer.parseInt(stcolfields.nextToken().trim());
2708 }
2709 }
2710 else if (busestrand && !busesignal)
2711 {
2712 if (szcolfields != null)
2713 {
2714 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
2715 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
2716 npositionindex = Integer.parseInt(stcolfields.nextToken().trim());
2717 nstrandindex = Integer.parseInt(stcolfields.nextToken().trim());
2718 }
2719 }
2720 else if (!busestrand && busesignal)
2721 {
2722 if (szcolfields != null)
2723 {
2724 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
2725 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
2726 npositionindex = Integer.parseInt(stcolfields.nextToken().trim());
2727 nsignalindex = Integer.parseInt(stcolfields.nextToken().trim());
2728 }
2729 else //if (szcolfields == null)
2730 {
2731 nsignalindex = 2;
2732 }
2733 }
2734 else //both are off
2735 {
2736 if (szcolfields != null)
2737 {
2738 StringTokenizer stcolfields = new StringTokenizer(szcolfields,",");
2739 nchromindex = Integer.parseInt(stcolfields.nextToken().trim());
2740 npositionindex = Integer.parseInt(stcolfields.nextToken().trim());
2741 }
2742 }
2743
2744 return new RecAnchorIndex(nchromindex, npositionindex, nstrandindex, nsignalindex);
2745 }
2746
2747
2748 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2749
2750
2751
2752 /**
2753 * Outputs a neighborhood enrichment based on a given hard segmentation
2754 * szinputsegmentation - is the input segmentation ; assumes segments are non-negative integers
2755 * szanchorpositions - is a file with the coordinates of the anchor positions
2756 * nbinsize - the binsize used in the segmentation, this ensures any position at this bin size
2757 * numleft - the number of intervals to the left of the anchor position to display the heatmap for
2758 * numright - the number of intervals to the right of the anchor position to display the heatmap for
2759 * nspacing - the frequency at which to display enrichments
2760 * noffsetanchor - the amount that should be substract so the anchor coordinates are 0 based
2761 * busestrand - true if strand orientation associated with the position is given
2762 * busesignal - true if signal associated with the data file should be used
2763 * szcolfields - a comma list of the 0-based index of
2764 * if (busestrand and busesignal) chromosome,pos,strand,signal default is 0,1,2,3
2765 * if (busestrand and not busesignal) chromosome,pos,strand default is 0,1,2
2766 * if (not busestrand and busesignal) chromosome,pos,signal default is 0,1,2
2767 * if (not busestrand not busesignal) chromosome,pos default is 0,1
2768 * szoutfile - the name of the text file for which the enrichments should be displayed
2769 * heatmaps are written to the same place with the extensions '.png' and '.svg'
2770 * theColor - theColor to use for the heatmap program
2771 */
2772 //low mem
2773 public static void neighborhoodMaxLowMem(String szinputsegmentation,String szanchorpositions,
2774 int nbinsize, int numleft, int numright, int nspacing,
2775 boolean busestrand, boolean busesignal, String szcolfields,
2776 int noffsetanchor, String szoutfile,Color theColor,
2777 String sztitle,String szlabelmapping, boolean bprintimage,
2778 boolean bstringlabels, boolean bbrowser) throws IOException
2779 {
2780
2781 //v1.26
2782 int nminnumcols =3;
2783 if (busestrand && busesignal)
2784 {
2785 nminnumcols = 4;
2786 }
2787 else if (!busestrand && !busesignal)
2788 {
2789 nminnumcols = 2;
2790 }
2791
2792 boolean bchrommatch = false;//added in 1.23 to check for chromosome matches
2793 //an array of chromosome names
2794 ArrayList alchromindex = new ArrayList();
2795
2796 String szLine;
2797
2798 //stores the largest index value for each chromosome
2799 HashMap hmchromMax = new HashMap();
2800
2801 //maps chromosome names to index values
2802 HashMap hmchromToIndex = new HashMap();
2803 HashMap hmLabelToIndex = new HashMap(); //maps label to an index
2804 HashMap hmIndexToLabel = new HashMap(); //maps index string to label
2805 //stores the maximum integer label value
2806 int nmaxlabel=0;
2807 String szlabel ="";
2808 BufferedReader brinputsegment = Util.getBufferedReader(szinputsegmentation);
2809
2810 boolean busedunderscore = false;
2811 //the number of additional intervals to the left and right to include
2812
2813 //the center anchor position
2814 int numintervals = 1+numleft+numright;
2815
2816
2817 //this loops reads in the segmentation
2818 while ((szLine = brinputsegment.readLine())!=null)
2819 {
2820 //added v1.24
2821 if (bbrowser)
2822 {
2823 if ((szLine.toLowerCase(Locale.ENGLISH).startsWith("browser"))||(szLine.toLowerCase(Locale.ENGLISH).startsWith("track")))
2824 {
2825 continue;
2826 }
2827 }
2828
2829 StringTokenizer st;
2830 if (bstringlabels)
2831 {
2832 st = new StringTokenizer(szLine,"\t");
2833 }
2834 else
2835 {
2836 st = new StringTokenizer(szLine,"\t ");
2837 }
2838
2839 //added in v1.24
2840 int numtokens = st.countTokens();
2841 if (numtokens == 0)
2842 {
2843 //skip blank lines
2844 continue;
2845 }
2846 else if (numtokens < 4)
2847 {
2848 throw new IllegalArgumentException("Line "+szLine+" in "+szinputsegmentation+" only had "+numtokens+" token(s). Expecting at least 4");
2849 }
2850
2851 String szchrom = st.nextToken().trim();
2852 //assumes segments are in standard bed format which to get to
2853 //0-based inclusive requires substract 1 from the end
2854 //int nbegin = Integer.parseInt(st.nextToken().trim())/nbinsize;
2855 st.nextToken().trim();
2856 int nend = (Integer.parseInt(st.nextToken().trim())-1)/nbinsize;
2857 szlabel = st.nextToken().trim();
2858 short slabel;
2859
2860 if (bstringlabels)
2861 {
2862 int nunderscoreindex = szlabel.indexOf("_");
2863
2864 if (nunderscoreindex >=0)
2865 {
2866 String szprefix = szlabel.substring(0,nunderscoreindex);
2867
2868 try
2869 {
2870 slabel = (short) (Short.parseShort(szprefix));
2871 if (slabel > nmaxlabel)
2872 {
2873 nmaxlabel = slabel;
2874 }
2875 busedunderscore = true;
2876 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
2877 hmIndexToLabel.put(""+slabel, szlabel);
2878 }
2879 catch (NumberFormatException ex)
2880 {
2881 try
2882 {
2883 slabel = (short) (Short.parseShort(szprefix.substring(1)));
2884 if (slabel > nmaxlabel)
2885 {
2886 nmaxlabel = slabel;
2887 }
2888 busedunderscore = true;
2889 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
2890 hmIndexToLabel.put(""+slabel, szlabel);
2891 }
2892 catch (NumberFormatException ex2)
2893 {
2894 if (busedunderscore)
2895 {
2896 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
2897 }
2898 }
2899 }
2900 }
2901
2902 if (!busedunderscore)
2903 {
2904 //handle string labels
2905 Short objshort = (Short) hmLabelToIndex.get(szlabel);
2906
2907 if (objshort == null)
2908 {
2909 nmaxlabel = hmLabelToIndex.size()+1;
2910 slabel = (short) nmaxlabel;
2911 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
2912 hmIndexToLabel.put(""+nmaxlabel, szlabel);
2913 }
2914 }
2915 }
2916 else
2917 {
2918 try
2919 {
2920 slabel = (short) (Short.parseShort(szlabel));
2921 }
2922 catch (NumberFormatException ex)
2923 {
2924 try
2925 {
2926 slabel = (short) (Short.parseShort(szlabel.substring(1)));
2927 }
2928 catch (NumberFormatException ex2)
2929 {
2930 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
2931 }
2932 }
2933
2934 //alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
2935
2936 if (slabel > nmaxlabel)
2937 {
2938 nmaxlabel = slabel;
2939 }
2940 }
2941
2942 Integer objMax = (Integer) hmchromMax.get(szchrom);
2943 if (objMax == null)
2944 {
2945 //System.out.println("on chrom "+szchrom);
2946 hmchromMax.put(szchrom,Integer.valueOf(nend));
2947 hmchromToIndex.put(szchrom, Integer.valueOf(hmchromToIndex.size()));
2948 alchromindex.add(szchrom);
2949 }
2950 else
2951 {
2952 int ncurrmax = objMax.intValue();
2953 if (ncurrmax < nend)
2954 {
2955 hmchromMax.put(szchrom, Integer.valueOf(nend));
2956 }
2957 }
2958 }
2959 brinputsegment.close();
2960
2961 //stores a tally for each position relative to an anchor how frequently the label was observed
2962 double[][] tallyoverlaplabel = new double[numintervals][nmaxlabel+1];
2963
2964 //stores a tally for the total signal associated with each anchor position
2965 double[] dsumoverlaplabel = new double[numintervals];
2966
2967 //a tally on how frequently each label occurs
2968 double[] tallylabel = new double[nmaxlabel+1];
2969
2970
2971 int numchroms = alchromindex.size();
2972
2973 //short[][] labels = new short[numchroms][];
2974
2975 //allocates space store all the segment labels for each chromosome
2976 for (int nchrom = 0; nchrom < numchroms; nchrom++)
2977 {
2978 //stores all the segments in the data
2979 //ArrayList alsegments = new ArrayList();
2980 brinputsegment = Util.getBufferedReader(szinputsegmentation);
2981 String szchromwant = (String) alchromindex.get(nchrom);
2982 //System.out.println("processing "+szchromwant);
2983 int nsize = ((Integer) hmchromMax.get(alchromindex.get(nchrom))).intValue()+1;
2984 short[] labels = new short[nsize];
2985 //this loops reads in the segmentation
2986
2987
2988 //short[] labels_nchrom = labels[nchrom];
2989 for (int npos = 0; npos < nsize; npos++)
2990 {
2991 labels[npos] = -1;
2992 }
2993
2994 while ((szLine = brinputsegment.readLine())!=null)
2995 {
2996 //int numlines = alsegments.size();
2997 StringTokenizer st;
2998 if (bstringlabels)
2999 {
3000 st = new StringTokenizer(szLine,"\t");
3001 }
3002 else
3003 {
3004 st = new StringTokenizer(szLine,"\t ");
3005 }
3006
3007 String szchrom = st.nextToken().trim();
3008 if (!szchromwant.equals(szchrom))
3009 continue;
3010
3011 bchrommatch = true;
3012 //assumes segments are in standard bed format which to get to
3013 //0-based inclusive requires substract 1 from the end
3014 int nbegin = Integer.parseInt(st.nextToken().trim())/nbinsize;
3015 int nend = (Integer.parseInt(st.nextToken().trim())-1)/nbinsize;
3016 szlabel = st.nextToken().trim();
3017 short slabel = -1;
3018
3019 if (bstringlabels)
3020 {
3021 int nunderscoreindex = szlabel.indexOf("_");
3022
3023 if (nunderscoreindex >=0)
3024 {
3025 String szprefix = szlabel.substring(0,nunderscoreindex);
3026
3027 try
3028 {
3029 slabel = (short) (Short.parseShort(szprefix));
3030 busedunderscore = true;
3031 }
3032 catch (NumberFormatException ex)
3033 {
3034 try
3035 {
3036 slabel = (short) (Short.parseShort(szprefix.substring(1)));
3037 busedunderscore = true;
3038 }
3039 catch (NumberFormatException ex2)
3040 {
3041 if (busedunderscore)
3042 {
3043 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
3044 }
3045 }
3046 }
3047 }
3048
3049 if (!busedunderscore)
3050 {
3051 //handle string labels
3052 Short objshort = (Short) hmLabelToIndex.get(szlabel);
3053 slabel = ((Short) objshort).shortValue();
3054 }
3055 }
3056 else
3057 {
3058 try
3059 {
3060 slabel = (short) (Short.parseShort(szlabel));
3061 }
3062 catch (NumberFormatException ex)
3063 {
3064 try
3065 {
3066 slabel = (short) (Short.parseShort(szlabel.substring(1)));
3067 }
3068 catch (NumberFormatException ex2)
3069 {
3070 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
3071 }
3072 }
3073 }
3074
3075 //this loop stores into labels the full segmentation
3076 //and a count of how often each label occurs
3077 //for (int nindex = 0; nindex < numlines; nindex++)
3078 //{
3079 //SegmentRec theSegmentRec = (SegmentRec) alsegments.get(nindex);
3080 //int nchrom = ((Integer) hmchromToIndex.get(theSegmentRec.szchrom)).intValue();
3081 //short[] labels_nchrom = labels[nchrom];
3082 //int nbegin = theSegmentRec.nbegin;
3083 //int nend = theSegmentRec.nend;
3084 //short slabel = theSegmentRec.slabel;
3085 for (int npos = nbegin; npos <= nend; npos++)
3086 {
3087 if ((!StateAnalysis.bfounddup) &&(labels[npos] >= 0)&&(labels[npos]!=slabel))
3088 {
3089 StateAnalysis.bfounddup = true;
3090 System.out.println("WARNING: found the same position assigned to multiple states. First example found: "+szchrom+
3091 ":"+(npos*nbinsize+1)+". Will use the last occurrence in file.");
3092
3093 }
3094 labels[npos] = slabel;
3095 }
3096
3097 if (slabel >= 0)
3098 {
3099 tallylabel[slabel]+=(nend-nbegin)+1;
3100 }
3101 }
3102 brinputsegment.close();
3103
3104
3105 RecAnchorIndex theAnchorIndex = getAnchorIndex(szcolfields, busestrand, busesignal);
3106
3107 //reads in the anchor position
3108 BufferedReader brcoords = Util.getBufferedReader(szanchorpositions);
3109 while ((szLine = brcoords.readLine())!=null)
3110 {
3111 if (szLine.trim().equals("")) continue;
3112 String[] szLineA = szLine.split("\\s+");
3113
3114 if (szLineA.length < nminnumcols)
3115 {
3116 //v1.26
3117 throw new IllegalArgumentException("Line: "+szLine +" in "+szanchorpositions+" has "+szLineA.length+" columns while expecting "+nminnumcols);
3118 }
3119
3120 String szchrom = szLineA[theAnchorIndex.nchromindex];
3121 if (!szchrom.equals(szchromwant))
3122 continue;
3123
3124 int nanchor = (Integer.parseInt(szLineA[theAnchorIndex.npositionindex])-noffsetanchor);
3125 boolean bposstrand = true;
3126 if (busestrand)
3127 {
3128 String szstrand = szLineA[theAnchorIndex.nstrandindex];
3129 if (szstrand.equals("+"))
3130 {
3131 bposstrand = true;
3132 }
3133 else if (szstrand.equals("-"))
3134 {
3135 bposstrand = false;
3136 }
3137 else
3138 {
3139 throw new IllegalArgumentException(szstrand +" is an invalid strand. Strand should be '+' or '-'");
3140 }
3141 }
3142
3143 double damount;
3144
3145 if ((busesignal)&&(theAnchorIndex.nsignalindex< szLineA.length))
3146 {
3147 damount = Double.parseDouble(szLineA[theAnchorIndex.nsignalindex]);
3148 }
3149 else
3150 {
3151 damount = 1;
3152 }
3153
3154 //updates the tallys for the given anchor position
3155 //Integer objChrom = (Integer) hmchromToIndex.get(szchrom);
3156 //if (objChrom != null)
3157 //{
3158 // int nchrom = objChrom.intValue();
3159 //short[] labels_nchrom = labels[nchrom];
3160
3161 if (bposstrand)
3162 {
3163 int ntallyindex = 0;
3164 for(int noffset= -numleft; noffset <= numright; noffset++)
3165 {
3166 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3167
3168 if ((nposindex >=0)&&(nposindex < labels.length)&&(labels[nposindex]>=0))
3169 {
3170 tallyoverlaplabel[ntallyindex][labels[nposindex]] += damount;
3171 }
3172 ntallyindex++;
3173 }
3174 }
3175 else
3176 {
3177 int ntallyindex = 0;
3178 for(int noffset= numright; noffset >= -numleft; noffset--)
3179 {
3180 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3181
3182 if ((nposindex >=0)&&(nposindex < labels.length)&&(labels[nposindex]>=0))
3183 {
3184 tallyoverlaplabel[ntallyindex][labels[nposindex]]+=damount;
3185 }
3186 ntallyindex++;
3187 }
3188 //}
3189 }
3190 }
3191 brcoords.close();
3192 }
3193
3194 if (!bchrommatch)
3195 {
3196 throw new IllegalArgumentException("No chromosome name matches found between "+szanchorpositions+
3197 " and those in the segmentation file.");
3198 }
3199
3200 outputneighborhood(tallyoverlaplabel,tallylabel,dsumoverlaplabel,szoutfile,nspacing,numright,
3201 numleft,theColor,ChromHMM.convertCharOrderToStringOrder(szlabel.charAt(0)),sztitle,0,
3202 szlabelmapping,szlabel.charAt(0), bprintimage, bstringlabels, hmIndexToLabel);
3203 }
3204
3205
3206 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3207
3208 /**
3209 * Outputs a neighborhood enrichment based on a given hard segmentation
3210 * szinputsegmentation - is the input segmentation ; assumes segments are non-negative integers
3211 * szanchorpositions - is a file with the coordinates of the anchor positions
3212 * nbinsize - the binsize used in the segmentation, this ensures any position at this bin size
3213 * numleft - the number of intervals to the left of the anchor position to display the heatmap for
3214 * numright - the number of intervals to the right of the anchor position to display the heatmap for
3215 * nspacing - the frequency at which to display enrichments
3216 * noffsetanchor - the amount that should be substract so the anchor coordinates are 0 based
3217 * busestrand - true if strand orientation associated with the position is given
3218 * busesignal - true if signal associated with the data file should be used
3219 * szcolfields - a comma list of the 0-based index of
3220 * if (busestrand and busesignal) chromosome,pos,strand,signal default is 0,1,2,3
3221 * if (busestrand and not busesignal) chromosome,pos,strand default is 0,1,2
3222 * if (not busestrand and busesignal) chromosome,pos,signal default is 0,1,2
3223 * if (not busestrand not busesignal) chromosome,pos default is 0,1
3224 * szoutfile - the name of the text file for which the enrichments should be displayed
3225 * heatmaps are written to the same place with the extensions '.png' and '.svg'
3226 * theColor - theColor to use for the heatmap program
3227 */
3228 public static void neighborhoodMax(String szinputsegmentation,String szanchorpositions,
3229 int nbinsize, int numleft, int numright, int nspacing,
3230 boolean busestrand, boolean busesignal, String szcolfields,
3231 int noffsetanchor, String szoutfile,Color theColor,
3232 String sztitle,String szlabelmapping, boolean bprintimage,
3233 boolean bstringlabels, boolean bbrowser) throws IOException
3234 {
3235 //v1.26
3236 int nminnumcols =3;
3237 if (busestrand && busesignal)
3238 {
3239 nminnumcols = 4;
3240 }
3241 else if (!busestrand && !busesignal)
3242 {
3243 nminnumcols = 2;
3244 }
3245
3246 //highmem
3247 boolean bchrommatch = false;//added in 1.23 to check for chromosome matches
3248 //stores all the segments in the data
3249 ArrayList alsegments = new ArrayList();
3250
3251 //an array of chromosome names
3252 ArrayList alchromindex = new ArrayList();
3253
3254 String szLine;
3255
3256 //stores the largest index value for each chromosome
3257 HashMap hmchromMax = new HashMap();
3258
3259 //maps chromosome names to index values
3260 HashMap hmchromToIndex = new HashMap();
3261
3262 HashMap hmLabelToIndex = new HashMap(); //maps label to an index
3263 HashMap hmIndexToLabel = new HashMap(); //maps index string to label
3264
3265 //stores the maximum integer label value
3266 int nmaxlabel=0;
3267 String szlabel ="";
3268 boolean busedunderscore = false;
3269 BufferedReader brinputsegment = Util.getBufferedReader(szinputsegmentation);
3270
3271 //this loops reads in the segmentation
3272 while ((szLine = brinputsegment.readLine())!=null)
3273 {
3274 //added v1.24
3275 if (bbrowser)
3276 {
3277 if ((szLine.toLowerCase(Locale.ENGLISH).startsWith("browser"))||(szLine.toLowerCase(Locale.ENGLISH).startsWith("track")))
3278 {
3279 continue;
3280 }
3281 }
3282
3283 StringTokenizer st;
3284 if (bstringlabels)
3285 {
3286 st = new StringTokenizer(szLine,"\t");
3287 }
3288 else
3289 {
3290 st = new StringTokenizer(szLine,"\t ");
3291 }
3292
3293 //added in v1.24
3294 int numtokens = st.countTokens();
3295 if (numtokens == 0)
3296 {
3297 //skip blank lines
3298 continue;
3299 }
3300 else if (numtokens < 4)
3301 {
3302 throw new IllegalArgumentException("Line "+szLine+" in "+szinputsegmentation+" only had "+numtokens+" token(s). Expecting at least 4");
3303 }
3304
3305 String szchrom = st.nextToken().trim();
3306 //assumes segments are in standard bed format which to get to
3307 //0-based inclusive requires substract 1 from the end
3308 int nbegin = Integer.parseInt(st.nextToken().trim())/nbinsize;
3309 int nend = (Integer.parseInt(st.nextToken().trim())-1)/nbinsize;
3310 szlabel = st.nextToken().trim();
3311 short slabel = -1;
3312
3313 if (bstringlabels)
3314 {
3315 int nunderscoreindex = szlabel.indexOf("_");
3316
3317 if (nunderscoreindex >=0)
3318 {
3319 String szprefix = szlabel.substring(0,nunderscoreindex);
3320
3321 try
3322 {
3323 slabel = (short) (Short.parseShort(szprefix));
3324 if (slabel > nmaxlabel)
3325 {
3326 nmaxlabel = slabel;
3327 }
3328 busedunderscore = true;
3329 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
3330 hmIndexToLabel.put(""+slabel, szlabel);
3331 }
3332 catch (NumberFormatException ex)
3333 {
3334 try
3335 {
3336 slabel = (short) (Short.parseShort(szprefix.substring(1)));
3337 if (slabel > nmaxlabel)
3338 {
3339 nmaxlabel = slabel;
3340 }
3341 busedunderscore = true;
3342 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
3343 hmIndexToLabel.put(""+slabel, szlabel);
3344 }
3345 catch (NumberFormatException ex2)
3346 {
3347 if (busedunderscore)
3348 {
3349 throw new IllegalArgumentException("Not a valid ID before '_' in "+szlabel+", while valid ID found for other entries");
3350 }
3351 }
3352 }
3353 }
3354
3355 if (!busedunderscore)
3356 {
3357 //handle string labels
3358 Short objshort = (Short) hmLabelToIndex.get(szlabel);
3359
3360 if (objshort == null)
3361 {
3362 nmaxlabel = hmLabelToIndex.size()+1;
3363 slabel = (short) nmaxlabel;
3364 hmLabelToIndex.put(szlabel, Short.valueOf(slabel));
3365 hmIndexToLabel.put(""+nmaxlabel, szlabel);
3366 }
3367 else
3368 {
3369 slabel = ((Short) objshort).shortValue();
3370 }
3371 }
3372 alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
3373 }
3374 else
3375 {
3376 try
3377 {
3378 slabel = (short) (Short.parseShort(szlabel));
3379 }
3380 catch (NumberFormatException ex)
3381 {
3382 try
3383 {
3384 slabel = (short) (Short.parseShort(szlabel.substring(1)));
3385 }
3386 catch (NumberFormatException ex2)
3387 {
3388 throw new IllegalArgumentException("In fourth column neither state number or ID found in segmentation file. Use '-labels' option to run overlap enrichment treating fourth column as labels");
3389 }
3390 }
3391
3392 alsegments.add(new SegmentRec(szchrom,nbegin,nend,slabel));
3393
3394 if (slabel > nmaxlabel)
3395 {
3396 nmaxlabel = slabel;
3397 }
3398 }
3399
3400 Integer objMax = (Integer) hmchromMax.get(szchrom);
3401 if (objMax == null)
3402 {
3403 hmchromMax.put(szchrom,Integer.valueOf(nend));
3404 hmchromToIndex.put(szchrom, Integer.valueOf(hmchromToIndex.size()));
3405 alchromindex.add(szchrom);
3406 }
3407 else
3408 {
3409 int ncurrmax = objMax.intValue();
3410 if (ncurrmax < nend)
3411 {
3412 hmchromMax.put(szchrom, Integer.valueOf(nend));
3413 }
3414 }
3415 }
3416 brinputsegment.close();
3417
3418 int numchroms = alchromindex.size();
3419 short[][] labels = new short[numchroms][];
3420 //allocates space store all the segment labels for each chromosome
3421 for (int nchrom = 0; nchrom < numchroms; nchrom++)
3422 {
3423 int nsize = ((Integer) hmchromMax.get(alchromindex.get(nchrom))).intValue()+1;
3424 labels[nchrom] = new short[nsize];
3425 short[] labels_nchrom = labels[nchrom];
3426 for (int npos = 0; npos < nsize; npos++)
3427 {
3428 labels_nchrom[npos] = -1;
3429 }
3430 }
3431
3432 //a tally on how frequently each label occurs
3433 double[] tallylabel = new double[nmaxlabel+1];
3434
3435 int numlines = alsegments.size();
3436
3437 //this loop stores into labels the full segmentation
3438 //and a count of how often each label occurs
3439 for (int nindex = 0; nindex < numlines; nindex++)
3440 {
3441 SegmentRec theSegmentRec = (SegmentRec) alsegments.get(nindex);
3442 int nchrom = ((Integer) hmchromToIndex.get(theSegmentRec.szchrom)).intValue();
3443 short[] labels_nchrom = labels[nchrom];
3444 int nbegin = theSegmentRec.nbegin;
3445 int nend = theSegmentRec.nend;
3446 short slabel = theSegmentRec.slabel;
3447 for (int npos = nbegin; npos <= nend; npos++)
3448 {
3449 if ((!StateAnalysis.bfounddup) &&(labels_nchrom[npos] >= 0)&&(labels_nchrom[npos]!=slabel))
3450 {
3451 StateAnalysis.bfounddup = true;
3452 System.out.println("WARNING: found the same position assigned to multiple states. First example found: "+theSegmentRec.szchrom+
3453 ":"+(npos*nbinsize+1)+". Will use the last occurrence in file.");
3454
3455 }
3456 labels_nchrom[npos] = slabel;
3457 if (slabel >= 0)
3458 {
3459 tallylabel[slabel]++;
3460 }
3461 }
3462 }
3463
3464 //the number of additional intervals to the left and right to include
3465
3466 //the center anchor position
3467 int numintervals = 1+numleft+numright;
3468
3469 //stores a tally for each position relative to an anchor how frequently the label was observed
3470 double[][] tallyoverlaplabel = new double[numintervals][nmaxlabel+1];
3471
3472 //stores a tally for the total signal associated with each anchor position
3473 double[] dsumoverlaplabel = new double[numintervals];
3474
3475 RecAnchorIndex theAnchorIndex = getAnchorIndex(szcolfields, busestrand, busesignal);
3476
3477 //reads in the anchor position
3478 BufferedReader brcoords = Util.getBufferedReader(szanchorpositions);
3479 while ((szLine = brcoords.readLine())!=null)
3480 {
3481 if (szLine.trim().equals("")) continue;
3482 String[] szLineA = szLine.split("\\s+");
3483
3484 if (szLineA.length < nminnumcols)
3485 {
3486 //v1.26
3487 throw new IllegalArgumentException("Line: "+szLine +" in "+szanchorpositions+" has "+szLineA.length+" columns while expecting "+nminnumcols);
3488 }
3489
3490 String szchrom = szLineA[theAnchorIndex.nchromindex];
3491 int nanchor = (Integer.parseInt(szLineA[theAnchorIndex.npositionindex])-noffsetanchor);
3492 boolean bposstrand = true;
3493 if (busestrand)
3494 {
3495 String szstrand = szLineA[theAnchorIndex.nstrandindex];
3496 if (szstrand.equals("+"))
3497 {
3498 bposstrand = true;
3499 }
3500 else if (szstrand.equals("-"))
3501 {
3502 bposstrand = false;
3503 }
3504 else
3505 {
3506 throw new IllegalArgumentException(szstrand +" is an invalid strand. Strand should be '+' or '-'");
3507 }
3508 }
3509
3510 double damount;
3511
3512 if ((busesignal)&&(theAnchorIndex.nsignalindex< szLineA.length))
3513 {
3514 damount = Double.parseDouble(szLineA[theAnchorIndex.nsignalindex]);
3515 }
3516 else
3517 {
3518 damount = 1;
3519 }
3520
3521 //updates the tallys for the given anchor position
3522 Integer objChrom = (Integer) hmchromToIndex.get(szchrom);
3523 if (objChrom != null)
3524 {
3525 int nchrom = objChrom.intValue();
3526 short[] labels_nchrom = labels[nchrom];
3527 bchrommatch = true;
3528
3529 if (bposstrand)
3530 {
3531 int ntallyindex = 0;
3532 for(int noffset= -numleft; noffset <= numright; noffset++)
3533 {
3534 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3535
3536 if ((nposindex >=0)&&(nposindex < labels_nchrom.length)&&(labels_nchrom[nposindex]>=0))
3537 {
3538 tallyoverlaplabel[ntallyindex][labels_nchrom[nposindex]] += damount;
3539 }
3540 ntallyindex++;
3541 }
3542 }
3543 else
3544 {
3545 int ntallyindex = 0;
3546 for(int noffset= numright; noffset >= -numleft; noffset--)
3547 {
3548 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3549
3550 if ((nposindex >=0)&&(nposindex < labels_nchrom.length)&&(labels_nchrom[nposindex]>=0))
3551 {
3552 tallyoverlaplabel[ntallyindex][labels_nchrom[nposindex]]+=damount;
3553 }
3554 ntallyindex++;
3555 }
3556 }
3557 }
3558 }
3559 brcoords.close();
3560
3561
3562 if (!bchrommatch)
3563 {
3564 throw new IllegalArgumentException("No chromosome name matches found between "+szanchorpositions+
3565 " and those in the segmentation file.");
3566 }
3567
3568 outputneighborhood(tallyoverlaplabel,tallylabel,dsumoverlaplabel,szoutfile,nspacing,numright,
3569 numleft,theColor,ChromHMM.convertCharOrderToStringOrder(szlabel.charAt(0)),sztitle,0,
3570 szlabelmapping,szlabel.charAt(0),bprintimage, bstringlabels, hmIndexToLabel);
3571 }
3572
3573
3574 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3575
3576 /**
3577 * Outputs a signal enrichment agreggation
3578 * szinputsegmentation - szposteriordir the directory with the posterior files
3579 * szcell - the cell type to use for the neighborhood enrichments
3580 * szanchorpositions - is a file with the coordinates of the anchor positions
3581 * nbinsize - the binsize used in the segmentation, this ensures any position at this bin size
3582 * numleft - the number of intervals to the left of the anchor position to display the heatmap for
3583 * numright - the number of intervals to the right of the anchor position to display the heatmap for
3584 * nspacing - the frequency at which to display enrichments
3585 * noffsetanchor - the amount that should be substract so the anchor coordinates are 0 based
3586 * busestrand - true if strand orientation associated with the position is given
3587 * busesignal - true if signal associated with the data file should be used
3588 * szcolfields - a comma list of the 0-based index of
3589 * if (busestrand and busesignal) chromosome,pos,strand,signal default is 0,1,2,3
3590 * if (busestrand and not busesignal) chromosome,pos,strand default is 0,1,2
3591 * if (not busestrand and busesignal) chromosome,pos,signal default is 0,1,2
3592 * if (not busestrand not busesignal) chromosome,pos default is 0,1
3593 * szoutfile - the name of the text file for which the enrichments should be displayed
3594 * a heatmap is written to the same place with the extensions '.png' and '.svg'
3595 * theColor - theColor to use for the heatmap program
3596 */
3597 public static void neighborhoodSignal(String szposteriordir,String szcell,String szanchorpositions, int nbinsize, int numleft, int numright, int nspacing,
3598 boolean busestrand, boolean busesignal,String szcolfields, int noffsetanchor,
3599 String szoutfile,Color theColor,String sztitle,String szlabelmapping, boolean bprintimage) throws IOException
3600 {
3601 //v1.26
3602 int nminnumcols =3;
3603 if (busestrand && busesignal)
3604 {
3605 nminnumcols = 4;
3606 }
3607 else if (!busestrand && !busesignal)
3608 {
3609 nminnumcols = 2;
3610 }
3611
3612 boolean bchrommatch = false;//added in 1.23 to check for chromosome matches
3613 //posterior here is really signal just using equivalent variable names
3614 //list of possible posterior files
3615 File posteriordir = new File(szposteriordir);
3616 if (!posteriordir.exists())
3617 {
3618 throw new IllegalArgumentException(szposteriordir+" was not found!");
3619 }
3620 String[] posteriorfiles = posteriordir.list();
3621
3622 String szLine;
3623 int numlocs = 0;
3624
3625 int numposteriorstates = 0;
3626 char chorder= '0';//just need to initalize it to something
3627 int nfirstindex = 0; //the index of the first file found
3628 boolean bfirst = true;
3629
3630 int numintervals = 1+numleft+numright; //total number of intervals
3631
3632 double[][] tallyoverlaplabel = null; //tally of the overlap of each interval and state
3633 double[] tallylabel = null; //tally of the overlap of each interval
3634
3635 double[] dsumoverlaplabel = new double[numintervals];
3636 String szmarknames="";
3637 boolean bposteriorfound = false;
3638 for (int nfile = 0; nfile < posteriorfiles.length; nfile++)
3639 {
3640 String szposteriorfiles_nfile = posteriorfiles[nfile];
3641
3642 //going through all posterior files
3643 if ((szposteriorfiles_nfile.contains("_signal"))&&(!(new File(szposteriorfiles_nfile)).isHidden()))
3644 {
3645 BufferedReader brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
3646 szLine = brposterior.readLine();
3647 if (szLine ==null)
3648 {
3649 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" is empty!");
3650 }
3651 StringTokenizer st =new StringTokenizer(szLine,"\t");
3652 String szcurrcell = st.nextToken().trim();
3653 if ((!szcurrcell.equals(szcell))&&(!szcell.equals("")))
3654 {
3655 brposterior.close();
3656 }
3657 else
3658 {
3659 bposteriorfound = true;
3660
3661 //must match cell type or consistent with empty cell type
3662
3663 String szchrom = st.nextToken().trim();
3664
3665 int numlines = 0;
3666 szLine = brposterior.readLine(); //gets state header
3667 if (szLine == null)
3668 {
3669 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" only has one line!");
3670 }
3671 st = new StringTokenizer(szLine,"\t");
3672 int numcurrstates = st.countTokens();
3673 if (bfirst)
3674 {
3675 chorder = st.nextToken().trim().charAt(0);
3676 bfirst = false;
3677 nfirstindex = nfile;
3678 numposteriorstates = numcurrstates;
3679 tallylabel = new double[numposteriorstates];
3680 tallyoverlaplabel = new double[numintervals][numposteriorstates];
3681 }
3682 else if (numposteriorstates != numcurrstates)
3683 {
3684 throw new IllegalArgumentException("Number of states "+numcurrstates+" in "+szposteriorfiles_nfile+
3685 " does not match number of states "+numposteriorstates+" in "+posteriorfiles[nfirstindex]);
3686 }
3687
3688 while ((szLine = brposterior.readLine())!=null)
3689 {
3690 numlines++;
3691 }
3692 brposterior.close();
3693 numlocs += numlines;
3694 //loading in the posterior data
3695 float[][] posterior = new float[numlines][numposteriorstates];
3696
3697 brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
3698 int nline = 0;
3699 brposterior.readLine();//specifies the header
3700 szmarknames = brposterior.readLine();
3701 while ((szLine = brposterior.readLine())!=null)
3702 {
3703 st = new StringTokenizer(szLine,"\t ");
3704 float[] posterior_nline = posterior[nline];
3705 for (int nstate = 0; nstate < numposteriorstates; nstate++)
3706 {
3707 float fval = Float.parseFloat(st.nextToken());
3708 posterior_nline[nstate] = fval;
3709 //keeps a tally of often each state occurs probabilistically
3710 tallylabel[nstate] += fval;
3711 }
3712 nline++;
3713 }
3714 brposterior.close();
3715
3716 boolean[] counted = null;
3717
3718 BufferedReader brcoords = Util.getBufferedReader(szanchorpositions);
3719 RecAnchorIndex theAnchorIndex = getAnchorIndex(szcolfields, busestrand, busesignal);
3720 while ((szLine = brcoords.readLine())!=null)
3721 {
3722 if (szLine.trim().equals("")) continue;
3723 //going through all the coordinates keeping only those for the current chromosome
3724 String[] szLineA = szLine.split("\\s+");
3725
3726 if (szLineA.length < nminnumcols)
3727 {
3728 //v1.26
3729 throw new IllegalArgumentException("Line: "+szLine +" in "+szanchorpositions+" has "+szLineA.length+" columns while expecting "+nminnumcols);
3730 }
3731
3732 String szreadchrom = szLineA[theAnchorIndex.nchromindex];
3733
3734 if (szreadchrom.equals(szchrom))
3735 {
3736 bchrommatch = true;
3737 int nanchor = (Integer.parseInt(szLineA[theAnchorIndex.npositionindex])-noffsetanchor);
3738 boolean bposstrand = true;
3739 if (busestrand)
3740 {
3741 String szstrand = szLineA[theAnchorIndex.nstrandindex];
3742 if (szstrand.equals("+"))
3743 {
3744 bposstrand = true;
3745 }
3746 else if (szstrand.equals("-"))
3747 {
3748 bposstrand = false;
3749 }
3750 else
3751 {
3752 throw new IllegalArgumentException(szstrand +" is an valid strand. Strand should be '+' or '-'");
3753 }
3754 }
3755
3756 double damount;
3757
3758 if ((busesignal)&&(theAnchorIndex.nsignalindex < szLineA.length))
3759 {
3760 damount = Double.parseDouble(szLineA[theAnchorIndex.nsignalindex]);
3761 }
3762 else
3763 {
3764 damount = 1;
3765 }
3766
3767 if (bposstrand)
3768 {
3769 int ntallyindex = 0;
3770 for(int noffset= -numleft; noffset <= numright; noffset++)
3771 {
3772 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3773
3774 if ((nposindex >=0)&&(nposindex < posterior.length))
3775 {
3776 //within interval
3777 float[] posterior_nposindex = posterior[nposindex];
3778 double[] tallyoverlaplabel_ntallyindex = tallyoverlaplabel[ntallyindex];
3779 for (int nstate = 0; nstate < numposteriorstates; nstate++)
3780 {
3781 //increments each state by the posterior amount
3782 tallyoverlaplabel_ntallyindex[nstate]+= damount*posterior_nposindex[nstate];
3783 }
3784 dsumoverlaplabel[ntallyindex]++;
3785 }
3786 ntallyindex++;
3787 }
3788 }
3789 else
3790 {
3791 int ntallyindex = 0;
3792 for(int noffset= numright; noffset >= -numleft; noffset--)
3793 {
3794 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
3795
3796 if ((nposindex >=0)&&(nposindex < posterior.length))
3797 {
3798 float[] posterior_nposindex = posterior[nposindex];
3799 double[] tallyoverlaplabel_ntallyindex = tallyoverlaplabel[ntallyindex];
3800 for (int nstate = 0; nstate < numposteriorstates; nstate++)
3801 {
3802 //increments each state by the posterior amount
3803 tallyoverlaplabel_ntallyindex[nstate]+=damount*posterior_nposindex[nstate];
3804 }
3805 dsumoverlaplabel[ntallyindex]++;
3806 }
3807 ntallyindex++;
3808 }
3809 }
3810 }
3811 }
3812 brcoords.close();
3813 }
3814 }
3815 }
3816
3817 if (!bposteriorfound)
3818 {
3819 throw new IllegalArgumentException("No posterior file found for cell type "+szcell);
3820 }
3821
3822 if (!bchrommatch)
3823 {
3824 throw new IllegalArgumentException("No chromosome name matches found between "+szanchorpositions+
3825 " and those in the segmentation file.");
3826 }
3827
3828 outputneighborhoodsignal(tallyoverlaplabel,tallylabel,dsumoverlaplabel,numlocs,szoutfile,nspacing,numright,
3829 numleft,theColor,ChromHMM.convertCharOrderToStringOrder(chorder),sztitle,szmarknames,szlabelmapping,chorder,bprintimage);
3830 }
3831
3832
3833 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3834
3835 /**
3836 * Outputs a neighborhood enrichment based on a given posterior segmentaation
3837 * szinputsegmentation - szposteriordir the directory with the posterior files
3838 * szcell - the cell type to use for the neighborhood enrichments
3839 * szanchorpositions - is a file with the coordinates of the anchor positions
3840 * nbinsize - the binsize used in the segmentation, this ensures any position at this bin size
3841 * numleft - the number of intervals to the left of the anchor position to display the heatmap for
3842 * numright - the number of intervals to the right of the anchor position to display the heatmap for
3843 * nspacing - the frequency at which to display enrichments
3844 * noffsetanchor - the amount that should be substract so the anchor coordinates are 0 based
3845 * busestrand - true if strand orientation associated with the position is given
3846 * busesignal - true if signal associated with the data file should be used
3847 * szcolfields - a comma list of the 0-based index of
3848 * if (busestrand and busesignal) chromosome,pos,strand,signal default is 0,1,2,3
3849 * if (busestrand and not busesignal) chromosome,pos,strand default is 0,1,2
3850 * if (not busestrand and busesignal) chromosome,pos,signal default is 0,1,2
3851 * if (not busestrand not busesignal) chromosome,pos default is 0,1
3852 * szoutfile - the name of the text file for which the enrichments should be displayed
3853 * a heatmap is written to the same place with the extensions '.png' and '.svg'
3854 * theColor - theColor to use for the heatmap program
3855 */
3856 public static void neighborhoodPosterior(String szposteriordir,String szcell,String szanchorpositions, int nbinsize, int numleft, int numright, int nspacing,
3857 boolean busestrand, boolean busesignal,String szcolfields, int noffsetanchor,
3858 String szoutfile,Color theColor,String sztitle,String szlabelmapping, boolean bprintimage) throws IOException
3859 {
3860 //v1.26
3861 int nminnumcols =3;
3862 if (busestrand && busesignal)
3863 {
3864 nminnumcols = 4;
3865 }
3866 else if (!busestrand && !busesignal)
3867 {
3868 nminnumcols = 2;
3869 }
3870
3871 boolean bchrommatch = false;//added in 1.23 to check for chromosome matches
3872 //list of possible posterior files
3873 File posteriordir = new File(szposteriordir);
3874 if (!posteriordir.exists())
3875 {
3876 throw new IllegalArgumentException(szposteriordir+" was not found!");
3877 }
3878 String[] posteriorfiles = posteriordir.list();
3879
3880 String szLine;
3881
3882 int numposteriorstates = 0;
3883 char chorder= '0';//just need to initalize it to something
3884 int nfirstindex = 0; //the index of the first file found
3885 boolean bfirst = true;
3886
3887 int numintervals = 1+numleft+numright; //total number of intervals
3888
3889 double[][] tallyoverlaplabel = null; //tally of the overlap of each interval and state
3890 double[] tallylabel = null; //tally of the overlap of each interval
3891
3892 double[] dsumoverlaplabel = new double[numintervals];
3893
3894 boolean bposteriorfound = false;
3895 for (int nfile = 0; nfile < posteriorfiles.length; nfile++)
3896 {
3897 String szposteriorfiles_nfile = posteriorfiles[nfile];
3898
3899 //going through all posterior files
3900 if ((szposteriorfiles_nfile.contains("_posterior"))&&(!(new File(szposteriorfiles_nfile)).isHidden()))
3901 {
3902 BufferedReader brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
3903 szLine = brposterior.readLine();
3904 if (szLine ==null)
3905 {
3906 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" is empty!");
3907 }
3908 StringTokenizer st =new StringTokenizer(szLine,"\t");
3909 String szcurrcell = st.nextToken().trim();
3910 if ((!szcurrcell.equals(szcell))&&(!szcell.equals("")))
3911 {
3912 brposterior.close();
3913 }
3914 else
3915 {
3916 bposteriorfound = true;
3917
3918 //must match cell type or consistent with empty cell type
3919
3920 String szchrom = st.nextToken().trim();
3921
3922 int numlines = 0;
3923 szLine = brposterior.readLine(); //gets state header
3924 if (szLine == null)
3925 {
3926 throw new IllegalArgumentException(szposteriordir+"/"+szposteriorfiles_nfile+" only has one line!");
3927 }
3928 st = new StringTokenizer(szLine,"\t");
3929 int numcurrstates = st.countTokens();
3930 if (bfirst)
3931 {
3932 chorder = st.nextToken().trim().charAt(0);
3933 bfirst = false;
3934 nfirstindex = nfile;
3935 numposteriorstates = numcurrstates;
3936 tallylabel = new double[numposteriorstates];
3937 tallyoverlaplabel = new double[numintervals][numposteriorstates];
3938 }
3939 else if (numposteriorstates != numcurrstates)
3940 {
3941 throw new IllegalArgumentException("Number of states "+numcurrstates+" in "+szposteriorfiles_nfile+
3942 " does not match number of states "+numposteriorstates+" in "+posteriorfiles[nfirstindex]);
3943 }
3944
3945 while ((szLine = brposterior.readLine())!=null)
3946 {
3947 numlines++;
3948 }
3949 brposterior.close();
3950
3951 //loading in the posterior data
3952 float[][] posterior = new float[numlines][numposteriorstates];
3953
3954 brposterior = Util.getBufferedReader(szposteriordir+"/"+szposteriorfiles_nfile);
3955 int nline = 0;
3956 brposterior.readLine();//specifies the header
3957 brposterior.readLine();
3958 while ((szLine = brposterior.readLine())!=null)
3959 {
3960 st = new StringTokenizer(szLine,"\t ");
3961 float[] posterior_nline = posterior[nline];
3962 for (int nstate = 0; nstate < numposteriorstates; nstate++)
3963 {
3964 float fval = Float.parseFloat(st.nextToken());
3965 posterior_nline[nstate] = fval;
3966 //keeps a tally of often each state occurs probabilistically
3967 tallylabel[nstate] += fval;
3968 }
3969 nline++;
3970 }
3971 brposterior.close();
3972
3973 boolean[] counted = null;
3974
3975 BufferedReader brcoords = Util.getBufferedReader(szanchorpositions);
3976 RecAnchorIndex theAnchorIndex = getAnchorIndex(szcolfields, busestrand, busesignal);
3977 while ((szLine = brcoords.readLine())!=null)
3978 {
3979 if (szLine.trim().equals("")) continue;
3980 //going through all the coordinates keeping only those for the current chromosome
3981 String[] szLineA = szLine.split("\\s+");
3982
3983 if (szLineA.length < nminnumcols)
3984 {
3985 //v1.26
3986 throw new IllegalArgumentException("Line: "+szLine +" in "+szanchorpositions+" has "+szLineA.length+" columns while expecting "+nminnumcols);
3987 }
3988
3989
3990 String szreadchrom = szLineA[theAnchorIndex.nchromindex];
3991
3992 if (szreadchrom.equals(szchrom))
3993 {
3994 bchrommatch = true;
3995 int nanchor = (Integer.parseInt(szLineA[theAnchorIndex.npositionindex])-noffsetanchor);
3996 boolean bposstrand = true;
3997 if (busestrand)
3998 {
3999 String szstrand = szLineA[theAnchorIndex.nstrandindex];
4000 if (szstrand.equals("+"))
4001 {
4002 bposstrand = true;
4003 }
4004 else if (szstrand.equals("-"))
4005 {
4006 bposstrand = false;
4007 }
4008 else
4009 {
4010 throw new IllegalArgumentException(szstrand +" is an valid strand. Strand should be '+' or '-'");
4011 }
4012 }
4013
4014 double damount;
4015
4016 if ((busesignal)&&(theAnchorIndex.nsignalindex < szLineA.length))
4017 {
4018 damount = Double.parseDouble(szLineA[theAnchorIndex.nsignalindex]);
4019 }
4020 else
4021 {
4022 damount = 1;
4023 }
4024
4025 if (bposstrand)
4026 {
4027 int ntallyindex = 0;
4028 for(int noffset= -numleft; noffset <= numright; noffset++)
4029 {
4030 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
4031
4032 if ((nposindex >=0)&&(nposindex < posterior.length))
4033 {
4034 //within interval
4035 float[] posterior_nposindex = posterior[nposindex];
4036 double[] tallyoverlaplabel_ntallyindex = tallyoverlaplabel[ntallyindex];
4037 for (int nstate = 0; nstate < numposteriorstates; nstate++)
4038 {
4039 //increments each state by the posterior amount
4040 tallyoverlaplabel_ntallyindex[nstate]+= damount*posterior_nposindex[nstate];
4041 }
4042 }
4043 ntallyindex++;
4044 }
4045 }
4046 else
4047 {
4048 int ntallyindex = 0;
4049 for(int noffset= numright; noffset >= -numleft; noffset--)
4050 {
4051 int nposindex = (nanchor + nspacing*noffset)/nbinsize;
4052
4053 if ((nposindex >=0)&&(nposindex < posterior.length))
4054 {
4055 float[] posterior_nposindex = posterior[nposindex];
4056 double[] tallyoverlaplabel_ntallyindex = tallyoverlaplabel[ntallyindex];
4057 for (int nstate = 0; nstate < numposteriorstates; nstate++)
4058 {
4059 //increments each state by the posterior amount
4060 tallyoverlaplabel_ntallyindex[nstate]+=damount*posterior_nposindex[nstate];
4061 }
4062 }
4063 ntallyindex++;
4064 }
4065 }
4066 }
4067 }
4068 brcoords.close();
4069 }
4070 }
4071 }
4072
4073 if (!bposteriorfound)
4074 {
4075 throw new IllegalArgumentException("No posterior file found for cell type "+szcell);
4076 }
4077
4078 if (!bchrommatch)
4079 {
4080 throw new IllegalArgumentException("No chromosome name matches found between "+szanchorpositions+
4081 " and those in the segmentation file.");
4082 }
4083
4084 outputneighborhood(tallyoverlaplabel,tallylabel,dsumoverlaplabel,szoutfile,nspacing,numright,
4085 numleft,theColor,ChromHMM.convertCharOrderToStringOrder(chorder),sztitle,1,
4086 szlabelmapping,chorder,bprintimage, false, null);
4087 }
4088
4089 /////////////////////////////////////////////////////////////////////////////////////////////////
4090 /**
4091 * This handles outputing to text and heatmap from the fold enrichments tally info
4092 */
4093 private static void outputneighborhoodsignal(double[][] tallyoverlaplabel, double[] tallylabel, double[] dsumoverlaplabel, double dsumlabel, String szoutfile,
4094 int nspacing, int numright, int numleft, Color theColor, String szstateorder,String sztitle,String szmarknames,
4095 String szlabelmapping, char chorder, boolean bprintimage) throws IOException
4096 {
4097 NumberFormat nf5 = NumberFormat.getInstance();
4098 nf5.setMaximumFractionDigits(5);
4099 nf5.setGroupingUsed(false);
4100 nf5.setMinimumFractionDigits(5);
4101
4102 HashMap hmlabelExtend = makeLabelMapping(szlabelmapping);
4103
4104 String[] collabels = new String[tallyoverlaplabel.length];
4105 System.out.println("Writing to file "+szoutfile+".txt");
4106 PrintWriter pw = new PrintWriter(new FileWriter(szoutfile+".txt"));
4107
4108 //prints out the column labels
4109 //and stores them in collabels for the heatmap
4110 int ninterval = 0;
4111 pw.print("State ("+szstateorder+" order)");
4112 for(int npos = -nspacing*numleft; npos <= nspacing*numright; npos+=nspacing)
4113 {
4114 pw.print("\t"+npos);
4115 collabels[ninterval] = ""+npos;
4116 ninterval++;
4117 }
4118 pw.println();
4119
4120 //each row in the heatmap corresponds to a state and each column a position in tallyoverlaplabel
4121 double[][] heatmapfold = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length];
4122 int numelim = 0;
4123
4124 //computes the fold enrichment for each non-empty state and outputs
4125 //the fold enrichment
4126 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
4127 {
4128 if (tallylabel[nstate] > 0)
4129 {
4130 //state actually occurs
4131 pw.print((nstate+1));
4132 String szsuffix;
4133 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(nstate+1)))!=null)
4134 {
4135 pw.print("_"+szsuffix);
4136 }
4137
4138 for (int nfile = 0; nfile < tallyoverlaplabel.length; nfile++)
4139 {
4140 //the numerator is the fraction of the signal at this relative anchor assigned to this state
4141 //the denominator is the fraction of the genome assigned to this state
4142 double dfold = (tallyoverlaplabel[nfile][nstate]/dsumoverlaplabel[nfile])/
4143 (tallylabel[nstate]/dsumlabel);
4144 heatmapfold[nstate][nfile] = dfold;
4145 pw.print("\t"+nf5.format(dfold));
4146 }
4147 pw.println();
4148 }
4149 else
4150 {
4151 //we are elminating this state when generating the heatmap since it was not found
4152 numelim++;
4153 }
4154 }
4155 pw.close();
4156
4157 StringTokenizer stheader = new StringTokenizer(szmarknames,"\t");
4158 String[] rowlabels;// = new String[tallyoverlaplabel[0].length];
4159 if (numelim > 0)
4160 {
4161 //we need to collapse the heatmap
4162 double[][] heatmapreduce = new double[heatmapfold.length-numelim][heatmapfold[0].length];
4163 rowlabels = new String[heatmapreduce.length];
4164 int nkeepindex = 0;
4165 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
4166 {
4167 if (tallylabel[nstate] > 0)
4168 {
4169 //keeping this index
4170 for (int ncol = 0; ncol < heatmapfold[nstate].length; ncol++)
4171 {
4172 //copying over the contents
4173 heatmapreduce[nkeepindex][ncol] = heatmapfold[nstate][ncol];
4174 }
4175 rowlabels[nkeepindex] = stheader.nextToken().trim();//""+(nstate+1);
4176 nkeepindex++;
4177 }
4178 else //added in 1.23
4179 {
4180 stheader.nextToken();
4181 }
4182 }
4183 heatmapfold = heatmapreduce;
4184 }
4185 else
4186 {
4187 rowlabels = new String[tallyoverlaplabel[0].length];
4188 for (int ni = 0; ni < rowlabels.length; ni++)
4189 {
4190 rowlabels[ni] = ""+stheader.nextToken().trim();
4191 }
4192 }
4193
4194
4195 for (int ni = 0; ni < rowlabels.length; ni++)
4196 {
4197 String szsuffix;
4198 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+rowlabels[ni]))!=null)
4199 {
4200 rowlabels[ni] = rowlabels[ni]+"_"+szsuffix;
4201 }
4202 }
4203
4204 if (bprintimage)
4205 {
4206 makeEnrichmentHeatMap(heatmapfold, collabels, rowlabels,szoutfile,theColor,sztitle,"Position","State ("+szstateorder+" order)");
4207 }
4208 }
4209
4210 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
4211
4212 /**
4213 * This handles outputing to text and heatmap form the fold enrichments tally info
4214 */
4215 private static void outputneighborhood(double[][] tallyoverlaplabel, double[] tallylabel, double[] dsumoverlaplabel, String szoutfile,
4216 int nspacing, int numright, int numleft, Color theColor, String szstateorder,String sztitle,
4217 int noffset, String szlabelmapping, char chorder, boolean bprintimage,
4218 boolean bstringlabels, HashMap hmIndexToLabel) throws IOException
4219 {
4220 NumberFormat nf5 = NumberFormat.getInstance();
4221 nf5.setMaximumFractionDigits(5);
4222 nf5.setGroupingUsed(false);
4223 nf5.setMinimumFractionDigits(5);
4224
4225 HashMap hmlabelExtend = makeLabelMapping(szlabelmapping);
4226
4227 //computes the total sum of signal each position, but summing over the
4228 //signal at each state at that position
4229 for (int npos = 0; npos < tallyoverlaplabel.length; npos++)
4230 {
4231 for (int nindex = 0; nindex < tallyoverlaplabel[npos].length; nindex++)
4232 {
4233 dsumoverlaplabel[npos] += tallyoverlaplabel[npos][nindex];
4234 }
4235 }
4236
4237 double dsumlabel = 0;
4238 for (int ni = 0; ni < tallylabel.length; ni++)
4239 {
4240 dsumlabel += tallylabel[ni];
4241 }
4242
4243 String[] collabels = new String[tallyoverlaplabel.length];
4244 System.out.println("Writing to file "+szoutfile+".txt");
4245 PrintWriter pw = new PrintWriter(new FileWriter(szoutfile+".txt"));
4246
4247 //prints out the column labels
4248 //and stores them in collabels for the heatmap
4249 int ninterval = 0;
4250 pw.print("State ("+szstateorder+" order)");
4251 for(int npos = -nspacing*numleft; npos <= nspacing*numright; npos+=nspacing)
4252 {
4253 pw.print("\t"+npos);
4254 collabels[ninterval] = ""+npos;
4255 ninterval++;
4256 }
4257 pw.println();
4258
4259 //each row in the heatmap corresponds to a state and each column a position in tallyoverlaplabel
4260 double[][] heatmapfold = new double[tallyoverlaplabel[0].length][tallyoverlaplabel.length];
4261 int numelim = 0;
4262
4263 //computes the fold enrichment for each non-empty state and outputs
4264 //the fold enrichment
4265 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
4266 {
4267 if (tallylabel[nstate] > 0)
4268 {
4269 if (bstringlabels)
4270 {
4271 pw.print(hmIndexToLabel.get(""+nstate));
4272 }
4273 else
4274 {
4275 //state actually occurs
4276 pw.print((nstate+noffset));
4277 String szsuffix;
4278 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(nstate+noffset)))!=null)
4279 {
4280 pw.print("_"+szsuffix);
4281 }
4282 }
4283
4284 for (int nfile = 0; nfile < tallyoverlaplabel.length; nfile++)
4285 {
4286 //the numerator is the fraction of the signal at this relative anchor assigned to this state
4287 //the denominator is the fraction of the genome assigned to this state
4288 double dfold = (tallyoverlaplabel[nfile][nstate]/dsumoverlaplabel[nfile])/
4289 (tallylabel[nstate]/dsumlabel);
4290 heatmapfold[nstate][nfile] = dfold;
4291 pw.print("\t"+nf5.format(dfold));
4292 }
4293 pw.println();
4294 }
4295 else
4296 {
4297 //we are elminating this state when generating the heatmap since it was not found
4298 numelim++;
4299 }
4300 }
4301 pw.close();
4302
4303
4304 String[] rowlabels;// = new String[tallyoverlaplabel[0].length];
4305 if (numelim > 0)
4306 {
4307 //we need to collapse the heatmap
4308 double[][] heatmapreduce = new double[heatmapfold.length-numelim][heatmapfold[0].length];
4309 rowlabels = new String[heatmapreduce.length];
4310 int nkeepindex = 0;
4311 for (int nstate = 0; nstate < tallyoverlaplabel[0].length; nstate++)
4312 {
4313 if (tallylabel[nstate] > 0)
4314 {
4315 //keeping this index
4316 for (int ncol = 0; ncol < heatmapfold[nstate].length; ncol++)
4317 {
4318 //copying over the contents
4319 heatmapreduce[nkeepindex][ncol] = heatmapfold[nstate][ncol];
4320 }
4321
4322 if (bstringlabels)
4323 {
4324 rowlabels[nkeepindex] = (String) hmIndexToLabel.get(""+nstate);
4325 }
4326 else
4327 {
4328 rowlabels[nkeepindex] = ""+(nstate+noffset);
4329 }
4330 nkeepindex++;
4331 }
4332 }
4333 heatmapfold = heatmapreduce;
4334 }
4335 else
4336 {
4337 rowlabels = new String[tallyoverlaplabel[0].length];
4338 if (bstringlabels)
4339 {
4340 for (int ni = 0; ni < rowlabels.length; ni++)
4341 {
4342 rowlabels[ni] = (String) hmIndexToLabel.get(""+ni);
4343 }
4344 }
4345 else
4346 {
4347 for (int ni = 0; ni < rowlabels.length; ni++)
4348 {
4349 rowlabels[ni] = ""+(ni+noffset);
4350 }
4351 }
4352 }
4353
4354 if (!bstringlabels)
4355 {
4356 for (int ni = 0; ni < rowlabels.length; ni++)
4357 {
4358 String szsuffix;
4359 if ((szsuffix = (String) hmlabelExtend.get(chorder+rowlabels[ni]))!=null)
4360 {
4361 rowlabels[ni] = rowlabels[ni]+"_"+szsuffix;
4362 }
4363 }
4364 }
4365
4366 if (bprintimage)
4367 {
4368 makeEnrichmentHeatMap(heatmapfold, collabels, rowlabels,szoutfile,theColor,sztitle,"Position","State ("+szstateorder+" order)");
4369 }
4370 }
4371
4372
4373 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
4374
4375 /**
4376 * szmainmodelfile is the reference set of emission parameters to use
4377 * szcomparedir is the directory for which the files beginning with emissions_ and ending with .txt will be compared
4378 * szoutputdir is the directory where the parametercorrelation .txt and .png output files will go
4379 * theColor is a Color object indicating the color of the heatmap
4380 */
4381 public static void makeModelEmissionCompare(String szmainmodelfile, String szcomparedir,
4382 String szoutputprefix, Color theColor, boolean bprintimage) throws IOException
4383 {
4384 ArrayList alrecs = new ArrayList();
4385
4386 NumberFormat nf5 = NumberFormat.getInstance();
4387 nf5.setMaximumFractionDigits(5);
4388 nf5.setGroupingUsed(false);
4389 nf5.setMinimumFractionDigits(5);
4390
4391 File filemain = new File(szmainmodelfile);
4392 if ((!filemain.getName().startsWith("emissions_"))||((!szmainmodelfile.endsWith(".txt"))&&(!szmainmodelfile.endsWith(".txt.gz"))))
4393 {
4394 throw new IllegalArgumentException("Reference set of emission parameters must start with emissions_ and end with .txt or .txt.gz");
4395 }
4396
4397 BufferedReader bremissions = Util.getBufferedReader(szmainmodelfile);
4398 String szheader = bremissions.readLine();
4399 if (szheader == null)
4400 {
4401 throw new IllegalArgumentException(szmainmodelfile+" is empty!");
4402 }
4403 StringTokenizer stheader = new StringTokenizer(szheader, "\t");
4404 int numcols = stheader.countTokens()-1;//substracts one since first column is state label column
4405
4406 //maps each mark identifier to a consistent indext value
4407 HashMap hmNameToID = new HashMap();
4408 String szaxis = stheader.nextToken().trim();
4409 int ncol = 0;
4410 while (stheader.hasMoreTokens())
4411 {
4412 hmNameToID.put(stheader.nextToken().trim(), Integer.valueOf(ncol));
4413 ncol++;
4414 }
4415
4416 //counts the number of states in the main file
4417 int numstatesmain = 0;
4418 String szLine;
4419 while ((szLine = bremissions.readLine())!=null)
4420 {
4421 numstatesmain++;
4422 }
4423 bremissions.close();
4424
4425
4426 //this reads in the emission parameters of the reference model
4427 double[][] emissionparamsmain = new double[numstatesmain][numcols];
4428 bremissions = Util.getBufferedReader(szmainmodelfile);
4429 bremissions.readLine();
4430 String[] rowlabels = new String[numstatesmain];
4431 for (int nstate = 0; nstate < numstatesmain; nstate++)
4432 {
4433 szLine = bremissions.readLine();
4434 if (szLine == null)
4435 {
4436 throw new IllegalArgumentException("Expecting "+numstatesmain+" lines in "+szmainmodelfile+" found fewer.");
4437 }
4438 StringTokenizer stLine = new StringTokenizer(szLine,"\t");
4439 rowlabels[nstate] = stLine.nextToken().trim();
4440 for (ncol = 0; ncol < numcols; ncol++)
4441 {
4442 emissionparamsmain[nstate][ncol] = Double.parseDouble(stLine.nextToken().trim());
4443 }
4444 }
4445 bremissions.close();
4446
4447 //this contains a mapping from mark identifier to regular column index
4448 int[] mappedcol = new int[hmNameToID.size()];
4449
4450 File emissionsdir = new File(szcomparedir);
4451 if (!emissionsdir.exists())
4452 {
4453 throw new IllegalArgumentException(szcomparedir+" was not found!");
4454 }
4455 String[] comparefiles = emissionsdir.list();
4456
4457 for (int nfile = 0; nfile < comparefiles.length; nfile++)
4458 {
4459 //compares to any file in the szcomparedir with the prefix "emissions_" and the suffix ".txt" or .txt.gz
4460 RecEmissionFile theRecEmissionFile = new RecEmissionFile();
4461 if ((comparefiles[nfile].startsWith("emissions_"))&&((comparefiles[nfile].endsWith(".txt"))||(comparefiles[nfile].endsWith(".txt.gz")))&&
4462 (!(new File(comparefiles[nfile])).isHidden()))
4463 {
4464 //first figures out the number of states
4465 bremissions = Util.getBufferedReader(szcomparedir+"/"+comparefiles[nfile]);
4466 bremissions.readLine(); //remove header
4467 int numstates = 0;
4468 while ((szLine = bremissions.readLine())!=null)
4469 {
4470 numstates++;
4471 }
4472 bremissions.close();
4473 theRecEmissionFile.numstates = numstates;
4474 theRecEmissionFile.szfilename = comparefiles[nfile];
4475
4476 bremissions = Util.getBufferedReader(szcomparedir+"/"+comparefiles[nfile]);
4477 szheader = bremissions.readLine();
4478 if (szheader == null)
4479 {
4480 throw new IllegalArgumentException(szcomparedir+"/"+comparefiles[nfile]+" is empty!");
4481 }
4482 stheader = new StringTokenizer(szheader, "\t");
4483 int numcurrcols = stheader.countTokens()-1;
4484 stheader.nextToken();
4485 if (numcurrcols != mappedcol.length)
4486 {
4487 throw new IllegalArgumentException("number of cols invalid found "+numcurrcols+" expecting "+mappedcol.length);
4488 }
4489 else
4490 {
4491 //gets the mapping to the mark columns in this file to the reference order
4492 ncol = 0;
4493 while (stheader.hasMoreTokens())
4494 {
4495 String sznametokentrim = stheader.nextToken().trim();
4496 if (hmNameToID.get(sznametokentrim) == null)
4497 {
4498 throw new IllegalArgumentException(sznametokentrim+" in "+comparefiles[nfile]+" was not found in "+szmainmodelfile+". "+
4499 "Mark names should match.");
4500 }
4501 else
4502 {
4503 mappedcol[ncol] = ((Integer) hmNameToID.get(sznametokentrim)).intValue();
4504 }
4505 ncol++;
4506 }
4507 }
4508
4509 theRecEmissionFile.emissionparams = new double[theRecEmissionFile.numstates][numcols];
4510
4511 for (int nstate = 0; nstate < theRecEmissionFile.numstates; nstate++)
4512 {
4513 szLine = bremissions.readLine();
4514 if (szLine == null)
4515 {
4516 throw new IllegalArgumentException("Expecting "+theRecEmissionFile.numstates+" states in "+
4517 szcomparedir+"/"+comparefiles[nfile]+" found fewer");
4518 }
4519 StringTokenizer stLine = new StringTokenizer(szLine,"\t");
4520 stLine.nextToken(); //remove state ID
4521 for (ncol = 0; ncol < numcols; ncol++)
4522 {
4523 //storing the emission parameter for
4524 theRecEmissionFile.emissionparams[nstate][mappedcol[ncol]] = Double.parseDouble(stLine.nextToken().trim());
4525 }
4526 }
4527 //adds a record for this emission file containing the parameters, number of states, and number of marks
4528 alrecs.add(theRecEmissionFile);
4529 bremissions.close();
4530 }
4531 }
4532
4533 if (alrecs.size()==0)
4534 {
4535 throw new IllegalArgumentException("No emission files to compare to found in "+szcomparedir);
4536 }
4537 RecEmissionFile[] theRecEmissionFileCompareA = new RecEmissionFile[alrecs.size()];
4538 double[][] bestcorrelation = new double[numstatesmain][alrecs.size()];
4539
4540 //orders the comparison files by state and then ID
4541 for (int nindex = 0; nindex < theRecEmissionFileCompareA.length; nindex++)
4542 {
4543 theRecEmissionFileCompareA[nindex] = (RecEmissionFile) alrecs.get(nindex);
4544 }
4545 Arrays.sort(theRecEmissionFileCompareA, new RecEmissionFileCompare());
4546
4547 BufferedReader br;
4548 double dcorr;
4549
4550 for (int nfile = 0; nfile < theRecEmissionFileCompareA.length; nfile++)
4551 {
4552 //goes through each comparison file
4553 int numstatescompare = theRecEmissionFileCompareA[nfile].numstates;
4554 double[][] emissionparamscompare = theRecEmissionFileCompareA[nfile].emissionparams;
4555 for (int nstatemain = 0; nstatemain < numstatesmain; nstatemain++)
4556 {
4557 //goes through each main state
4558 double dbestcorr = -1;
4559 for (int nstatecompare = 0; nstatecompare < numstatescompare; nstatecompare++)
4560 {
4561 //find the best correlated state in terms of emission parameters in the correlated vector
4562 dcorr = Util.correlation(emissionparamsmain[nstatemain],emissionparamscompare[nstatecompare]);
4563
4564 if (dcorr > dbestcorr)
4565 {
4566 dbestcorr = dcorr;
4567 }
4568 }
4569 //record this best correlation
4570 bestcorrelation[nstatemain][nfile] = dbestcorr;
4571 }
4572 }
4573
4574
4575 String szfile = szoutputprefix+".txt";
4576
4577 System.out.println("Writing to file "+szfile);
4578 PrintWriter pwcompare = new PrintWriter(new FileWriter(szfile));
4579
4580 String[] collabels = new String[theRecEmissionFileCompareA.length];
4581
4582
4583 pwcompare.print("State");
4584 for (ncol = 0; ncol < theRecEmissionFileCompareA.length; ncol++)
4585 {
4586 collabels[ncol] = ""+theRecEmissionFileCompareA[ncol].numstates;
4587 }
4588
4589 for (ncol = 0; ncol < collabels.length; ncol++)
4590 {
4591 pwcompare.print("\t"+theRecEmissionFileCompareA[ncol].szfilename);
4592 }
4593 pwcompare.println();
4594
4595 //print to text file
4596 for (int nstate = 0; nstate < numstatesmain; nstate++)
4597 {
4598 pwcompare.print(rowlabels[nstate]);
4599 for (int nfile = 0; nfile < bestcorrelation[nstate].length; nfile++)
4600 {
4601 pwcompare.print("\t"+nf5.format(bestcorrelation[nstate][nfile]));
4602 }
4603 pwcompare.println();
4604 }
4605 pwcompare.close();
4606
4607
4608 if (bprintimage)
4609 {
4610 HeatChart map = new HeatChart(bestcorrelation);
4611
4612 map.setTitle("Best Emission Parameter Correlation");
4613 map.setXAxisLabel("Number of States in Model");
4614 map.setAxisValuesFont(new Font("SansSerif",0,20));
4615 map.setAxisLabelsFont(new Font("SansSerif",0,22));
4616 map.setTitleFont(new Font("SansSerif",0,24));
4617 map.setYAxisLabel(szaxis);
4618 map.setXValues(collabels);
4619 map.setYValues(rowlabels);
4620 map.setHighValueColour(theColor);
4621
4622 map.saveToFile(new File(szoutputprefix+".png"));
4623 Util.printImageToSVG(map, szoutputprefix+".svg");
4624 System.out.println("Writing to file "+szoutputprefix+".png");
4625 System.out.println("Writing to file "+szoutputprefix+".svg");
4626 }
4627
4628 }
4629 }
4630