Debian Codegraph @

edu/mit/compbio/ChromHMM/BrowserOutput.java

raw symbols SCIP
1 /**
2 * ChromHMM - automating chromatin state discovery and characterization
3 * Copyright (C) 2008-2012 Massachusetts Institute of Technology
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 **/
18 package edu.mit.compbio.ChromHMM;
19
20 import java.io.*;
21 import java.util.*;
22 import java.util.zip.GZIPOutputStream;
23
24 /**
25 * This class handles generating the browser output.
26 * The ChromHMM code was written by Jason Ernst.
27 */
28
29 public class BrowserOutput
30 {
31
32
33 /**
34 * Record store an integer interval
35 */
36 static class BeginEndRec
37 {
38 int nbegin;
39 int nend;
40 BeginEndRec(int nbegin, int nend)
41 {
42 this.nbegin = nbegin;
43 this.nend = nend;
44 }
45 }
46
47
48 //////////////////////////////////////////////////////////////////////////////////////////////////////////////
49 /**
50 * Does a string comparison by first converting strings to integers
51 * If neither are integers does a stander string comparison
52 */
53 static class LabelCompare implements Comparator, Serializable
54 {
55 public int compare(Object o1, Object o2)
56 {
57 String sz1 = (String) o1;
58 String sz2 = (String) o2;
59 try
60 {
61 int n1 = Integer.parseInt(sz1);
62 int n2 = Integer.parseInt(sz2);
63 if (n1 < n2)
64 {
65 return -1;
66 }
67 else if (n1 > n2)
68 {
69 return 1;
70 }
71 else
72 {
73 return 0;
74 }
75 }
76 catch (NumberFormatException nfex)
77 {
78 return (sz1.compareTo(sz2));
79 }
80 }
81 }
82
83 /**
84 * Stores the mapping from state IDs to R,G,B
85 */
86 HashMap hmcolor = new HashMap();
87
88 /**
89 * Stores the mapping from state IDs to descriptive labels
90 */
91 HashMap hmlabelExtend = new HashMap();
92
93 /**
94 * The file with the segmentation being loaded
95 */
96 String szsegmentfile;
97
98 /**
99 * Name of the file mapping color IDs to labels
100 */
101 String szcolormapping;
102
103 /**
104 * Name of the file mapping IDs to labels
105 */
106 String szidlabelmapping;
107
108 /**
109 * The name of the segmentation that will be used in the browser
110 */
111 String szsegmentationname;
112
113 /**
114 * The prefix for the output files
115 */
116 String szoutputfileprefix;
117
118 /**
119 * Number of states to make a segmentation for
120 */
121 int numstates;
122
123 /**
124 * True if files should be in gzip format
125 */
126 boolean bgzip;
127
128 /**
129 * True if header leaders on browser bed files should be surpressed
130 */
131 boolean bnobrowserheader;
132
133 public BrowserOutput(String szsegmentfile, String szcolormapping,String szidlabelmapping,
134 String szsegmentationname, String szoutputfileprefix, int numstates, boolean bgzip, boolean bnobrowserheader) throws IOException
135 {
136 this.szsegmentfile = szsegmentfile;
137 this.szcolormapping =szcolormapping;
138 this.szidlabelmapping = szidlabelmapping;
139 this.szsegmentationname = szsegmentationname;
140 this.szoutputfileprefix = szoutputfileprefix;
141 this.numstates = numstates;
142 this.bgzip = bgzip;
143 this.bnobrowserheader = bnobrowserheader;
144
145 hmcolor = new HashMap();
146 hmlabelExtend = new HashMap();
147 makeColorMapping();
148 makeLabelMapping();
149 }
150
151 ////////////////////////////////////////////////////////////////////////////////////////////////
152
153
154 private void makeColorMapping() throws IOException
155 {
156 String szLine;
157
158 if (szcolormapping != null)
159 {
160 BufferedReader brcolor = Util.getBufferedReader(szcolormapping);
161
162 //Loading in a mapping from state ID to R,G,B color
163
164 while ((szLine = brcolor.readLine())!=null)
165 {
166 StringTokenizer st = new StringTokenizer(szLine,"\t");
167 String szID = st.nextToken().trim();
168 String szColor = st.nextToken().trim();
169 hmcolor.put(szID, szColor);
170 }
171 brcolor.close();
172 }
173 else
174 {
175 BufferedReader brsegment = Util.getBufferedReader(szsegmentfile);
176 HashSet hs = new HashSet();
177 while ((szLine =brsegment.readLine())!=null)
178 {
179 String[] szLineA = szLine.split("\\s+");
180 hs.add(szLineA[3].substring(1)); //this removes first char giving ordering type
181 }
182 brsegment.close();
183
184 Iterator itr = hs.iterator();
185 int nmaxval=1;
186 int nminval=1;
187
188 while (itr.hasNext())
189 {
190 int nval = Integer.parseInt((String)itr.next());
191
192 if (nval < nminval)
193 {
194 nminval = nval;
195 }
196 else if (nval > nmaxval)
197 {
198 nmaxval = nval;
199 }
200 }
201
202
203
204 nmaxval = Math.max(nmaxval, nminval + numstates - 1);
205 String[] szlabels = new String[nmaxval-nminval+1];
206
207 for (int nindex = nminval; nindex <= nmaxval; nindex++)
208 {
209 szlabels[nindex-nminval] = ""+nindex;
210 }
211
212
213 int[][] colortable = getMaxDiverseOrder(szlabels.length);
214
215 for (int nindex = 0; nindex < szlabels.length; nindex++)
216 {
217 hmcolor.put(szlabels[nindex], colortable[nindex][0]+","+colortable[nindex][1]+","+colortable[nindex][2]);
218 }
219 }
220 }
221
222
223 /**
224 * From the set of 216 web colors excluding white and black selects the nsize most diverse
225 * based on a greedy algorithm. From this set orders them by a greedy algorithm to find similiar
226 * colors starting at Blue
227 */
228 private int[][] getMaxDiverseOrder(int nsize)
229 {
230
231 Random theRandom = new Random(132);
232 int[] colors = new int[] {0, 51,102,153,204,255};
233 int[][] colorscandidate =new int[colors.length*colors.length*colors.length][3];
234 boolean[] taken = new boolean[colorscandidate.length];
235 taken[0] = true;
236 taken[taken.length-1] = true;
237
238 //generating all pairs of r,g,b values from the above six
239 int ncandidate = 0;
240 for (int nr = 0; nr < colors.length; nr++)
241 {
242 for (int ng = 0; ng < colors.length; ng++)
243 {
244 for (int nb = 0; nb < colors.length; nb++)
245 {
246 colorscandidate[ncandidate][0] = colors[nr];
247 colorscandidate[ncandidate][1] = colors[ng];
248 colorscandidate[ncandidate][2] = colors[nb];
249 ncandidate++;
250 }
251 }
252 }
253
254 int[][] colorspaced = new int[nsize][3];
255 colorspaced[0][0] = colorscandidate[colors.length-1][0];
256 colorspaced[0][1] = colorscandidate[colors.length-1][1];
257 colorspaced[0][2] = colorscandidate[colors.length-1][2];
258
259 for (int nstate =1; nstate < colorspaced.length; nstate++)
260 {
261 int nbestdist = -1;
262 int nbestindex = -1;
263 for (ncandidate = 1; ncandidate < colorscandidate.length-1; ncandidate++)
264 {
265 //ignoring first and last color
266 if (!taken[ncandidate])
267 {
268 //not already used
269 int ndist;
270 int nmindist = Integer.MAX_VALUE;
271 //finding closest distance to already selected
272 for (int ncurrel = 0; ncurrel < nstate; ncurrel++)
273 {
274
275 ndist = Math.abs(colorscandidate[ncandidate][0]-colorspaced[ncurrel][0])+
276 Math.abs(colorscandidate[ncandidate][1]-colorspaced[ncurrel][1])+
277 Math.abs(colorscandidate[ncandidate][2]-colorspaced[ncurrel][2]);
278
279
280 if (ndist < nmindist)
281 {
282 nmindist = ndist;
283 }
284 }
285
286 //if this candidate has the furthest closest distance so far then keep
287 if (nmindist > nbestdist)
288 {
289 nbestdist = nmindist;
290 nbestindex = ncandidate;
291 }
292 }
293 }
294 if (nbestindex == -1)
295 {
296 nbestindex = theRandom.nextInt(colorscandidate.length);
297 }
298 colorspaced[nstate][0] = colorscandidate[nbestindex][0];
299 colorspaced[nstate][1] = colorscandidate[nbestindex][1];
300 colorspaced[nstate][2] = colorscandidate[nbestindex][2];
301 taken[nbestindex] = true;
302 }
303
304 boolean[] takenordered = new boolean[colorspaced.length];
305 int[][] colorsordered = new int[colorspaced.length][3];
306 colorsordered[0][0] = colorspaced[0][0];
307 colorsordered[0][1] = colorspaced[0][1];
308 colorsordered[0][2] = colorspaced[0][2];
309 //no ordering greedily taking the closest non selected one each iteration
310 for (int npos =1; npos < colorsordered.length; npos++)
311 {
312 int nbestdist = Integer.MAX_VALUE;
313 int nbestindex = -1;
314 for (ncandidate = 1; ncandidate < colorsordered.length; ncandidate++)
315 {
316 if (!takenordered[ncandidate])
317 {
318 int ndist = Math.abs(colorspaced[ncandidate][0]-colorsordered[npos-1][0])+
319 Math.abs(colorspaced[ncandidate][1]-colorsordered[npos-1][1])+
320 Math.abs(colorspaced[ncandidate][2]-colorsordered[npos-1][2]);
321
322 if (ndist < nbestdist)
323 {
324 nbestdist = ndist;
325 nbestindex = ncandidate;
326 }
327 }
328 }
329
330 takenordered[nbestindex] = true;
331 colorsordered[npos][0] = colorspaced[nbestindex][0];
332 colorsordered[npos][1] = colorspaced[nbestindex][1];
333 colorsordered[npos][2] = colorspaced[nbestindex][2];
334 }
335
336 return colorsordered;
337 }
338
339
340 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
341
342
343 private void makeLabelMapping() throws IOException
344 {
345 if (szidlabelmapping != null)
346 {
347 BufferedReader bridlabel = Util.getBufferedReader(szidlabelmapping);
348 String szLine;
349
350 //Loading in a mapping from state ID to a label description
351
352 while ((szLine = bridlabel.readLine())!=null)
353 {
354 StringTokenizer st = new StringTokenizer(szLine,"\t");
355 String szID = st.nextToken().trim();
356 String szLabelExtend = st.nextToken().trim();
357 hmlabelExtend.put(szID,szLabelExtend);
358 }
359 bridlabel.close();
360 }
361
362 }
363
364 //////////////////////////////////////////////////////////////////////////////////////////////////////////////
365 /**
366 * Makes a single track browser view of the segmentation represented in szsegmentfile
367 * szcolormapping is a two or three column text file which maps state ID to R,G,B color triples and optionally a state label
368 * Name of segmentation in the browser file is given by szsegmentationame
369 * Output is a file named szoutputfileprefix_browserdense.bed of segmentation viewable in a single track in dense mode in browser
370 */
371 public void makebrowserdense() throws IOException
372 {
373 if (bgzip)
374 {
375 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed.gz");
376 //PrintWriter pwzip = new PrintWriter(new FileWriter(szoutputfileprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed.gz"));
377 GZIPOutputStream pwzip = new GZIPOutputStream(new FileOutputStream(szoutputfileprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed.gz"));
378
379 BufferedReader brsegment = Util.getBufferedReader(szsegmentfile);
380 String szLine;
381 boolean bfirst = true;
382
383 while ((szLine =brsegment.readLine())!=null)
384 {
385 StringTokenizer st = new StringTokenizer(szLine,"\t");
386 String szcurrchrom = st.nextToken().trim();
387 int nbegin = Integer.parseInt(st.nextToken().trim());
388 int nend = Integer.parseInt(st.nextToken().trim());
389 String szFullID = st.nextToken().trim();
390 String szID = szFullID.substring(1); //this removes ordering type
391 if ((bfirst)&&(!bnobrowserheader))
392 {
393 String szout = "track name=\""+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szFullID.charAt(0))
394 +" ordered)"+"\" visibility=1 itemRgb=\"On\""+"\n";
395 byte[] btformat = szout.getBytes();
396 pwzip.write(btformat,0,btformat.length);
397 //pw.println("track name=\""+szsegmentationname+"\" description=\" "+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szFullID.charAt(0))
398 // +" ordered)"+"\" visibility=1 itemRgb=\"On\"");
399 bfirst = false;
400 }
401 String szColor = (String) hmcolor.get(szID);
402 if (szColor == null)
403 {
404 throw new IllegalArgumentException("Color not given for "+szID);
405 }
406
407 String szsuffix;
408 if ((szsuffix = (String) hmlabelExtend.get(szFullID))!=null)
409 {
410 szID = szID+"_"+szsuffix;
411 }
412
413 String szout = szcurrchrom+"\t"+nbegin+"\t"+nend+"\t"+szID+"\t0\t.\t"+nbegin+"\t"+nend+"\t"+szColor +"\n";
414 //pw.println(szcurrchrom+"\t"+nbegin+"\t"+nend+"\t"+szID+"\t0\t.\t"+nbegin+"\t"+nend+"\t"+szColor);
415 byte[] btformat = szout.getBytes();
416 pwzip.write(btformat,0,btformat.length);
417 }
418 brsegment.close();
419 pwzip.finish();
420 pwzip.close();
421 }
422 else
423 {
424 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed");
425 PrintWriter pw = new PrintWriter(new FileWriter(szoutputfileprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed"));
426
427 BufferedReader brsegment = Util.getBufferedReader(szsegmentfile);
428 String szLine;
429 boolean bfirst = true;
430
431 while ((szLine = brsegment.readLine())!=null)
432 {
433 StringTokenizer st = new StringTokenizer(szLine,"\t");
434 String szcurrchrom = st.nextToken().trim();
435 int nbegin = Integer.parseInt(st.nextToken().trim());
436 int nend = Integer.parseInt(st.nextToken().trim());
437 String szFullID = st.nextToken().trim();
438 String szID = szFullID.substring(1); //this removes ordering type
439 if ((bfirst)&&(!bnobrowserheader))
440 {
441 pw.println("track name=\""+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szFullID.charAt(0))
442 +" ordered)"+"\" visibility=1 itemRgb=\"On\"");
443 bfirst = false;
444 }
445 String szColor = (String) hmcolor.get(szID);
446 if (szColor == null)
447 {
448 throw new IllegalArgumentException("Color not given for "+szID);
449 }
450
451 String szsuffix;
452 if ((szsuffix = (String) hmlabelExtend.get(szFullID))!=null)
453 {
454 szID = szID+"_"+szsuffix;
455 }
456
457 pw.println(szcurrchrom+"\t"+nbegin+"\t"+nend+"\t"+szID+"\t0\t.\t"+nbegin+"\t"+nend+"\t"+szColor);
458 }
459 brsegment.close();
460 pw.close();
461 }
462 }
463
464
465 //////////////////////////////////////////////////////////////////////////////////////////////////
466 /**
467 * Makes a single track browser view of the segmentation represented in szsegmentfile
468 * szcolormapping is a two or three column text file which maps state ID to R,G,B color triples and optionally a state label
469 * Name of segmentation in the browser file is given by szsegmentationame
470 * Output is a file named szoutputfileprefix_browserdense.bed of segmentation viewable with one state per row
471 */
472 public void makebrowserexpanded() throws IOException
473 {
474 if (bgzip)
475 {
476 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed.gz");
477 }
478 else
479 {
480 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed");
481 }
482
483 String szLine;
484
485 BufferedReader brsegment = Util.getBufferedReader(szsegmentfile);
486
487 //stores set of chromosomes and labels
488 HashSet hschroms = new HashSet();
489 HashSet hslabels = new HashSet();
490
491 //stores for each chromosome the maximum coordinate
492 HashMap hmchromMax = new HashMap();
493
494 //stores the set of interval coordinates for each chromosome and label
495 HashMap hmcoords = new HashMap();
496
497 //maps a label without the prefix back to the full label
498 HashMap hmlabelToFull = new HashMap();
499
500 String szLabelFull=null;
501 while ((szLine = brsegment.readLine())!=null)
502 {
503 StringTokenizer st = new StringTokenizer(szLine,"\t");
504 String szchrom = st.nextToken().trim();
505 int nbegin = Integer.parseInt(st.nextToken().trim());
506 int nend = Integer.parseInt(st.nextToken().trim());
507 szLabelFull = st.nextToken().trim();
508 String szLabel = szLabelFull.substring(1);
509
510 hmlabelToFull.put(szLabel, szLabelFull);
511
512 hschroms.add(szchrom);
513 hslabels.add(szLabel);
514 ArrayList alRecs = (ArrayList) hmcoords.get(szchrom+"\t"+szLabel);
515 if (alRecs ==null)
516 {
517 //creating first entry for chromsome and coordinate
518 alRecs = new ArrayList();
519 hmcoords.put(szchrom+"\t"+szLabel,alRecs);
520 }
521 alRecs.add(new BeginEndRec(nbegin,nend));
522
523 //potentially updating maximum coordinate for chromosome
524 Object obj = ((Integer) hmchromMax.get(szchrom));
525 if (obj != null)
526 {
527 int nval = ((Integer) obj).intValue();
528
529 if (nend > nval)
530 {
531 hmchromMax.put(szchrom,Integer.valueOf(nend));
532 }
533 }
534 else
535 {
536 hmchromMax.put(szchrom,Integer.valueOf(nend));
537 }
538 }
539 brsegment.close();
540
541
542 //gets all the state labels and sorts them
543 String[] szLabels = new String[hslabels.size()];
544 Iterator itrLabels = hslabels.iterator();
545 int nindex = 0;
546 while (itrLabels.hasNext())
547 {
548 szLabels[nindex] = (String) itrLabels.next();
549 nindex++;
550 }
551 Arrays.sort(szLabels, new LabelCompare());
552
553 //gets all the chromsomes and sorts them
554 String[] szChroms = new String[hschroms.size()];
555 Iterator itrChroms = hschroms.iterator();
556 nindex = 0;
557 while (itrChroms.hasNext())
558 {
559 szChroms[nindex] = (String) itrChroms.next();
560 nindex++;
561 }
562 Arrays.sort(szChroms);
563
564 if (bgzip)
565 {
566 GZIPOutputStream pwzip = new GZIPOutputStream(new FileOutputStream(szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed.gz"));
567 byte[] btformat;
568 if (!bnobrowserheader)
569 {
570 String szout = "track name=\"Expanded_"+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
571 +" ordered)"+"\" visibility=2 itemRgb=\"On\""+"\n";
572 btformat = szout.getBytes();
573 pwzip.write(btformat,0,btformat.length);
574
575 //pw.println("track name=\"Expanded_"+szsegmentationname+"\" description=\" "+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
576 // +" ordered)"+"\" visibility=2 itemRgb=\"On\"");
577 int nbrowserend = (int) (((Integer)hmchromMax.get(szChroms[0])).intValue()*.001)+1;
578
579 szout = "browser position "+szChroms[0]+":1-"+nbrowserend+"\n";
580 btformat = szout.getBytes();
581 pwzip.write(btformat,0,btformat.length);
582 //pwzip.println("browser position "+szChroms[0]+":1-"+nbrowserend);
583 }
584
585 for (int nlabel = szLabels.length-1; nlabel >=0; nlabel--)
586 {
587 //UCSC browser seems to reverse the ordering of browser track files
588 String szcolor = (String) hmcolor.get(""+szLabels[nlabel]);
589 for (int nchrom = 0; nchrom < szChroms.length; nchrom++)
590 {
591 //omits those segment labels not observed at all on chromosome
592 ArrayList alRecs = (ArrayList) hmcoords.get(szChroms[nchrom]+"\t"+szLabels[nlabel]);
593 if (alRecs == null) continue;
594
595 int nmax = ((Integer) hmchromMax.get(szChroms[nchrom])).intValue();
596
597 //this forces browser to display segment until the end of the chromosome
598 alRecs.add(new BeginEndRec(nmax-1,nmax));
599
600 int nsize = alRecs.size();
601 int nmin = ((BeginEndRec) alRecs.get(0)).nbegin;
602 int nfinalend = nmax;
603
604 String szoutlabel;
605 String szsuffix;
606 if ((szsuffix = (String) hmlabelExtend.get((String) hmlabelToFull.get(szLabels[nlabel])))!=null)
607 {
608 szoutlabel = szLabels[nlabel]+"_"+szsuffix;
609 }
610 else
611 {
612 szoutlabel = szLabels[nlabel];
613 }
614
615 StringBuffer sbout = new StringBuffer();
616 sbout.append(szChroms[nchrom]+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
617 //pw.print(szChroms[nchrom]+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
618 //pw.print(0); //forcing the display to start at the beginning of the chromosome
619 sbout.append(0);
620 for (int ni = 0; ni < nsize; ni++)
621 {
622 BeginEndRec theBeginEndRec = (BeginEndRec) alRecs.get(ni);
623 int ndiff = theBeginEndRec.nend - theBeginEndRec.nbegin;
624 sbout.append(",");
625 sbout.append(ndiff);
626 //pw.print(",");
627 //pw.print(ndiff);
628 }
629 sbout.append("\t");
630 sbout.append(0);
631 //pw.print("\t");
632 //pw.print(0);
633 for (int ni = 0; ni < nsize; ni++)
634 {
635 int nloc = ((BeginEndRec) alRecs.get(ni)).nbegin;
636 sbout.append(",");
637 sbout.append(nloc);
638 //pw.print(",");
639 //pw.print(nloc);
640 }
641 sbout.append("\n");
642 // pw.println();
643 btformat = sbout.toString().getBytes();
644 pwzip.write(btformat,0,btformat.length);
645 }
646 }
647 pwzip.finish();
648 pwzip.close();
649 }
650 else
651 {
652 PrintWriter pw = new PrintWriter(new FileWriter(szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed"));
653
654 if (!bnobrowserheader)
655 {
656 pw.println("track name=\"Expanded_"+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
657 +" ordered)"+"\" visibility=2 itemRgb=\"On\"");
658 int nbrowserend = (int) (((Integer)hmchromMax.get(szChroms[0])).intValue()*.001)+1;
659 pw.println("browser position "+szChroms[0]+":1-"+nbrowserend);
660 }
661
662 for (int nlabel = szLabels.length-1; nlabel >=0; nlabel--)
663 {
664 //UCSC browser seems to reverse the ordering of browser track files
665 String szcolor = (String) hmcolor.get(""+szLabels[nlabel]);
666 for (int nchrom = 0; nchrom < szChroms.length; nchrom++)
667 {
668 //omits those segment labels not observed at all on chromosome
669 ArrayList alRecs = (ArrayList) hmcoords.get(szChroms[nchrom]+"\t"+szLabels[nlabel]);
670 if (alRecs == null) continue;
671
672 int nmax = ((Integer) hmchromMax.get(szChroms[nchrom])).intValue();
673
674 //this forces browser to display segment until the end of the chromosome
675 alRecs.add(new BeginEndRec(nmax-1,nmax));
676
677 int nsize = alRecs.size();
678 int nmin = ((BeginEndRec) alRecs.get(0)).nbegin;
679 int nfinalend = nmax;
680
681 String szoutlabel;
682 String szsuffix;
683 if ((szsuffix = (String) hmlabelExtend.get((String) hmlabelToFull.get(szLabels[nlabel])))!=null)
684 {
685 szoutlabel = szLabels[nlabel]+"_"+szsuffix;
686 }
687 else
688 {
689 szoutlabel = szLabels[nlabel];
690 }
691
692 pw.print(szChroms[nchrom]+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
693 pw.print(0); //forcing the display to start at the beginning of the chromosome
694 for (int ni = 0; ni < nsize; ni++)
695 {
696 BeginEndRec theBeginEndRec = (BeginEndRec) alRecs.get(ni);
697 int ndiff = theBeginEndRec.nend - theBeginEndRec.nbegin;
698 pw.print(",");
699 pw.print(ndiff);
700 }
701 pw.print("\t");
702 pw.print(0);
703 for (int ni = 0; ni < nsize; ni++)
704 {
705 int nloc = ((BeginEndRec) alRecs.get(ni)).nbegin;
706 pw.print(",");
707 pw.print(nloc);
708 }
709 pw.println();
710 }
711 }
712 pw.close();
713 }
714 }
715
716
717
718
719 //////////////////////////////////////////////////////////////////////////////////////////////////
720 /**
721 * Makes a single track browser view of the segmentation represented in szsegmentfile
722 * szcolormapping is a two or three column text file which maps state ID to R,G,B color triples and optionally a state label
723 * Name of segmentation in the browser file is given by szsegmentationame
724 * Output is a file named szoutputfileprefix_browserdense.bed of segmentation viewable with one state per row
725 */
726 public void makebrowserexpandedLowMem() throws IOException
727 {
728 if (bgzip)
729 {
730 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed.gz");
731 }
732 else
733 {
734 System.out.println("Writing to file "+szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed");
735 }
736
737 String szLine;
738
739 BufferedReader brsegment = Util.getBufferedReader(szsegmentfile);
740
741 //stores set of chromosomes and labels
742 HashSet hschroms = new HashSet();
743 HashSet hslabels = new HashSet();
744
745 //stores for each chromosome the maximum coordinate
746 HashMap hmchromMax = new HashMap();
747
748
749 //maps a label without the prefix back to the full label
750 HashMap hmlabelToFull = new HashMap();
751
752 String szLabelFull=null;
753 while ((szLine = brsegment.readLine())!=null)
754 {
755 StringTokenizer st = new StringTokenizer(szLine,"\t");
756 String szchrom = st.nextToken().trim();
757 int nbegin = Integer.parseInt(st.nextToken().trim());
758 int nend = Integer.parseInt(st.nextToken().trim());
759 szLabelFull = st.nextToken().trim();
760 String szLabel = szLabelFull.substring(1);
761
762 hmlabelToFull.put(szLabel, szLabelFull);
763
764 hschroms.add(szchrom);
765 hslabels.add(szLabel);
766 //ArrayList alRecs = (ArrayList) hmcoords.get(szchrom+"\t"+szLabel);
767 //if (alRecs ==null)
768 //{
769 //creating first entry for chromsome and coordinate
770 // alRecs = new ArrayList();
771 // hmcoords.put(szchrom+"\t"+szLabel,alRecs);
772 //}
773 //alRecs.add(new BeginEndRec(nbegin,nend));
774
775 //potentially updating maximum coordinate for chromosome
776 Object obj = ((Integer) hmchromMax.get(szchrom));
777 if (obj != null)
778 {
779 int nval = ((Integer) obj).intValue();
780
781 if (nend > nval)
782 {
783 hmchromMax.put(szchrom,Integer.valueOf(nend));
784 }
785 }
786 else
787 {
788 hmchromMax.put(szchrom,Integer.valueOf(nend));
789 }
790 }
791 brsegment.close();
792
793
794 //gets all the state labels and sorts them
795 String[] szLabels = new String[hslabels.size()];
796 Iterator itrLabels = hslabels.iterator();
797 int nindex = 0;
798 while (itrLabels.hasNext())
799 {
800 szLabels[nindex] = (String) itrLabels.next();
801 nindex++;
802 }
803 Arrays.sort(szLabels, new LabelCompare());
804
805 //gets all the chromsomes and sorts them
806 String[] szChroms = new String[hschroms.size()];
807 Iterator itrChroms = hschroms.iterator();
808 nindex = 0;
809 while (itrChroms.hasNext())
810 {
811 szChroms[nindex] = (String) itrChroms.next();
812 nindex++;
813 }
814 Arrays.sort(szChroms);
815
816 if (bgzip)
817 {
818 byte[] btformat;
819
820 GZIPOutputStream pwzip = new GZIPOutputStream(new FileOutputStream(szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed.gz"));
821 if (!bnobrowserheader)
822 {
823 String szout = "track name=\"Expanded_"+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
824 +" ordered)"+"\" visibility=2 itemRgb=\"On\""+"\n";
825 btformat = szout.getBytes();
826 pwzip.write(btformat,0,btformat.length);
827
828 //pw.println("track name=\"Expanded_"+szsegmentationname+"\" description=\" "+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
829 // +" ordered)"+"\" visibility=2 itemRgb=\"On\"");
830 int nbrowserend = (int) (((Integer)hmchromMax.get(szChroms[0])).intValue()*.001)+1;
831
832 szout = "browser position "+szChroms[0]+":1-"+nbrowserend+"\n";
833 btformat = szout.getBytes();
834 pwzip.write(btformat,0,btformat.length);
835 //pwzip.println("browser position "+szChroms[0]+":1-"+nbrowserend);
836 }
837
838 for (int nchrom = 0; nchrom < szChroms.length; nchrom++)
839 {
840 HashMap hmcoords = new HashMap();
841 String szcurrchrom = szChroms[nchrom];
842
843 //stores the set of interval coordinates for each chromosome and label
844 brsegment = Util.getBufferedReader(szsegmentfile);
845 while ((szLine = brsegment.readLine())!=null)
846 {
847 StringTokenizer st = new StringTokenizer(szLine,"\t");
848 String szchrom = st.nextToken().trim();
849 if (szchrom.equals(szcurrchrom))
850 {
851 int nbegin = Integer.parseInt(st.nextToken().trim());
852 int nend = Integer.parseInt(st.nextToken().trim());
853 szLabelFull = st.nextToken().trim();
854 String szLabel = szLabelFull.substring(1);
855
856 ArrayList alRecs = (ArrayList) hmcoords.get(szLabel);
857 if (alRecs ==null)
858 {
859 //creating first entry for chromsome and coordinate
860 alRecs = new ArrayList();
861 hmcoords.put(szLabel,alRecs);
862 }
863 alRecs.add(new BeginEndRec(nbegin,nend));
864 }
865 }
866 brsegment.close();
867
868
869 //UCSC browser seems to reverse the ordering of browser track files
870 for (int nlabel = szLabels.length-1; nlabel >=0; nlabel--)
871 {
872 String szcolor = (String) hmcolor.get(""+szLabels[nlabel]);
873 //omits those segment labels not observed at all on chromosome
874
875 ArrayList alRecs = (ArrayList) hmcoords.get(szLabels[nlabel]);
876 if (alRecs == null) continue;
877
878 int nmax = ((Integer) hmchromMax.get(szChroms[nchrom])).intValue();
879
880 //this forces browser to display segment until the end of the chromosome
881 alRecs.add(new BeginEndRec(nmax-1,nmax));
882
883 int nsize = alRecs.size();
884 int nmin = ((BeginEndRec) alRecs.get(0)).nbegin;
885 int nfinalend = nmax;
886
887 String szoutlabel;
888 String szsuffix;
889 if ((szsuffix = (String) hmlabelExtend.get((String) hmlabelToFull.get(szLabels[nlabel])))!=null)
890 {
891 szoutlabel = szLabels[nlabel]+"_"+szsuffix;
892 }
893 else
894 {
895 szoutlabel = szLabels[nlabel];
896 }
897
898 StringBuffer sbout = new StringBuffer();
899 sbout.append(szcurrchrom+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
900 //pw.print(szChroms[nchrom]+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
901 //pw.print(0); //forcing the display to start at the beginning of the chromosome
902 sbout.append(0);
903 for (int ni = 0; ni < nsize; ni++)
904 {
905 BeginEndRec theBeginEndRec = (BeginEndRec) alRecs.get(ni);
906 int ndiff = theBeginEndRec.nend - theBeginEndRec.nbegin;
907 sbout.append(",");
908 sbout.append(ndiff);
909 //pw.print(",");
910 //pw.print(ndiff);
911 }
912 sbout.append("\t");
913 sbout.append(0);
914 //pw.print("\t");
915 //pw.print(0);
916 for (int ni = 0; ni < nsize; ni++)
917 {
918 int nloc = ((BeginEndRec) alRecs.get(ni)).nbegin;
919 sbout.append(",");
920 sbout.append(nloc);
921 //pw.print(",");
922 //pw.print(nloc);
923 }
924 sbout.append("\n");
925 // pw.println();
926 btformat = sbout.toString().getBytes();
927 pwzip.write(btformat,0,btformat.length);
928 }
929 }
930 pwzip.finish();
931 pwzip.close();
932 }
933 else
934 {
935 PrintWriter pw = new PrintWriter(new FileWriter(szoutputfileprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed"));
936 if (!bnobrowserheader)
937 {
938
939 pw.println("track name=\"Expanded_"+szsegmentationname+"\" description=\""+szsegmentationname+" ("+ChromHMM.convertCharOrderToStringOrder(szLabelFull.charAt(0))
940 +" ordered)"+"\" visibility=2 itemRgb=\"On\"");
941 int nbrowserend = (int) (((Integer)hmchromMax.get(szChroms[0])).intValue()*.001)+1;
942 pw.println("browser position "+szChroms[0]+":1-"+nbrowserend);
943 }
944
945 for (int nchrom = 0; nchrom < szChroms.length; nchrom++)
946 {
947 String szcurrchrom = szChroms[nchrom];
948 HashMap hmcoords = new HashMap();
949
950 //stores the set of interval coordinates for each chromosome and label
951 brsegment = Util.getBufferedReader(szsegmentfile);
952 while ((szLine = brsegment.readLine())!=null)
953 {
954 StringTokenizer st = new StringTokenizer(szLine,"\t");
955 String szchrom = st.nextToken().trim();
956 if (szchrom.equals(szcurrchrom))
957 {
958 int nbegin = Integer.parseInt(st.nextToken().trim());
959 int nend = Integer.parseInt(st.nextToken().trim());
960 szLabelFull = st.nextToken().trim();
961 String szLabel = szLabelFull.substring(1);
962
963 ArrayList alRecs = (ArrayList) hmcoords.get(szLabel);
964 if (alRecs ==null)
965 {
966 //creating first entry for chromsome and coordinate
967 alRecs = new ArrayList();
968 hmcoords.put(szLabel,alRecs);
969 }
970 alRecs.add(new BeginEndRec(nbegin,nend));
971 }
972 }
973 brsegment.close();
974
975 //UCSC browser seems to reverse the ordering of browser track files
976 for (int nlabel = szLabels.length-1; nlabel >=0; nlabel--)
977 {
978 String szcolor = (String) hmcolor.get(""+szLabels[nlabel]);
979
980 //omits those segment labels not observed at all on chromosome
981 ArrayList alRecs = (ArrayList) hmcoords.get(szLabels[nlabel]);
982 if (alRecs == null) continue;
983
984 int nmax = ((Integer) hmchromMax.get(szChroms[nchrom])).intValue();
985
986 //this forces browser to display segment until the end of the chromosome
987 alRecs.add(new BeginEndRec(nmax-1,nmax));
988
989 int nsize = alRecs.size();
990 int nmin = ((BeginEndRec) alRecs.get(0)).nbegin;
991 int nfinalend = nmax;
992
993 String szoutlabel;
994 String szsuffix;
995 if ((szsuffix = (String) hmlabelExtend.get((String) hmlabelToFull.get(szLabels[nlabel])))!=null)
996 {
997 szoutlabel = szLabels[nlabel]+"_"+szsuffix;
998 }
999 else
1000 {
1001 szoutlabel = szLabels[nlabel];
1002 }
1003
1004 pw.print(szcurrchrom+"\t"+0+"\t"+nfinalend+"\t"+szoutlabel+"\t0\t.\t"+nmin+"\t"+nfinalend+"\t"+szcolor+"\t"+(nsize+1)+"\t");
1005 pw.print(0); //forcing the display to start at the beginning of the chromosome
1006 for (int ni = 0; ni < nsize; ni++)
1007 {
1008 BeginEndRec theBeginEndRec = (BeginEndRec) alRecs.get(ni);
1009 int ndiff = theBeginEndRec.nend - theBeginEndRec.nbegin;
1010 pw.print(",");
1011 pw.print(ndiff);
1012 }
1013 pw.print("\t");
1014 pw.print(0);
1015 for (int ni = 0; ni < nsize; ni++)
1016 {
1017 int nloc = ((BeginEndRec) alRecs.get(ni)).nbegin;
1018 pw.print(",");
1019 pw.print(nloc);
1020 }
1021 pw.println();
1022 }
1023 }
1024 pw.close();
1025 }
1026 }
1027 }
1028