Debian Codegraph @

current/jgi/CallPeaks.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7
8 import fileIO.ByteFile1;
9 import fileIO.ByteFile2;
10 import fileIO.ByteStreamWriter;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import fileIO.TextFile;
14 import shared.Parse;
15 import shared.Parser;
16 import shared.PreParser;
17 import shared.Shared;
18 import shared.Timer;
19 import shared.Tools;
20 import structures.ByteBuilder;
21 import structures.LongList;
22 import tracker.ReadStats;
23
24 /**
25 * @author Brian Bushnell
26 * @date Oct 28, 2014
27 *
28 */
29 public class CallPeaks {
30
31 /*--------------------------------------------------------------*/
32 /*---------------- Initialization ----------------*/
33 /*--------------------------------------------------------------*/
34
35 public static void main(String[] args){
36 Timer t=new Timer();
37 CallPeaks x=new CallPeaks(args);
38 x.process(t);
39
40 //Close the print stream if it was redirected
41 Shared.closeStream(x.outstream);
42 }
43
44 public CallPeaks(String[] args){
45
46 {//Preparse block for help, config files, and outstream
47 PreParser pp=new PreParser(args, outstream, printClass ? getClass() : null, false);
48 args=pp.args;
49 outstream=pp.outstream;
50 }
51
52 for(int i=0; i<args.length; i++){
53 String arg=args[i];
54 String[] split=arg.split("=");
55 String a=split[0].toLowerCase();
56 String b=split.length>1 ? split[1] : null;
57
58 if(Parser.parseZip(arg, a, b)){
59 //do nothing
60 }else if(a.equals("append") || a.equals("app")){
61 append=ReadStats.append=Parse.parseBoolean(b);
62 }else if(a.equals("overwrite") || a.equals("ow")){
63 overwrite=Parse.parseBoolean(b);
64 }else if(a.equals("verbose")){
65 verbose=Parse.parseBoolean(b);
66 ByteFile1.verbose=verbose;
67 ByteFile2.verbose=verbose;
68 ReadWrite.verbose=verbose;
69 }else if(a.equals("in")){
70 in=b;
71 }else if(a.equals("out")){
72 out=b;
73 }else if(a.equals("minheight") || a.equals("h")){
74 minHeight=Long.parseLong(b);
75 }else if(a.equals("minvolume") || a.equals("v")){
76 minVolume=Long.parseLong(b);
77 }else if(a.equals("minwidth") || a.equals("w")){
78 minWidth=Integer.parseInt(b);
79 }else if(a.equals("minpeak") || a.equals("minp")){
80 minPeak=Integer.parseInt(b);
81 }else if(a.equals("maxpeak") || a.equals("maxp")){
82 maxPeak=(int)Tools.min(Integer.MAX_VALUE, Parse.parseKMG(b));
83 }else if(a.equals("maxpeakcount") || a.equals("maxpc") || a.equals("maxpeaks")){
84 maxPeakCount=Integer.parseInt(b);
85 }else if(a.equals("smoothradius")){
86 smoothRadius=Integer.parseInt(b);
87 }else if(a.equals("smoothprogressive")){
88 smoothProgressiveFlag=Parse.parseBoolean(b);
89 }else if(a.equals("maxradius")){
90 maxRadius=Integer.parseInt(b);
91 }else if(a.equals("progressivemult")){
92 progressiveMult=Float.parseFloat(b);
93 }else if(a.equals("ploidy")){
94 ploidyClaimed=Integer.parseInt(b);
95 }else if(a.equalsIgnoreCase("ploidyLogic")){
96 ploidyLogic=Integer.parseInt(b);
97 }else if(a.equals("column") || a.equals("col") || a.equals("countcolumn")){
98 countColumn=Integer.parseInt(b);
99 }else if(a.equals("k")){
100 k=Integer.parseInt(b);
101 }else if(a.equals("logscale")){
102 logScale=Parse.parseBoolean(b);
103 }else if(a.equals("logwidth")){
104 logWidth=Double.parseDouble(b);
105 }else if(a.equals("logpasses")){
106 logPasses=Integer.parseInt(b);
107 }
108
109 else if(a.equals("byheight")){
110 CALL_MODE=BY_HEIGHT;
111 }else if(a.equals("byvolume")){
112 CALL_MODE=BY_VOLUME;
113 }else if(a.equalsIgnoreCase("weightByRelief")){
114 weightByRelief=Parse.parseBoolean(b);
115 }
116
117 else if(in==null && i==0 && Tools.looksLikeInputStream(arg)){
118 in=arg;
119 }else{
120 outstream.println("Unknown parameter "+args[i]);
121 assert(false) : "Unknown parameter "+args[i];
122 // throw new RuntimeException("Unknown parameter "+args[i]);
123 }
124 }
125 // assert(logScale);
126 if(out==null){out="stdout.txt";}
127
128 ffout=FileFormat.testOutput(out, FileFormat.TEXT, null, true, overwrite, append, false);
129 ffin=FileFormat.testInput(in, FileFormat.TEXT, null, true, false);
130 }
131
132 /*--------------------------------------------------------------*/
133 /*---------------- Outer Methods ----------------*/
134 /*--------------------------------------------------------------*/
135
136 public void process(Timer t){
137 LongList lists[]=loadHistogram(ffin, k);//TODO: Add support for GC here
138 LongList hist=lists[0];
139 LongList gchist=lists[1];
140 ArrayList<Peak> peaks=callPeaks(hist, gchist);
141 long sum=shared.Vector.sum(hist.array);
142 printPeaks(peaks, k, sum, hist.array, (gchist==null ? null : gchist.array));
143 hist=null;
144 t.stop();
145 System.err.println("Found "+peaks.size()+" peaks in "+t);
146
147 peaks=null;
148
149 if(errorState){
150 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
151 }
152 }
153
154 public static boolean printPeaks(long[] array, long[] gcArray, String fname, boolean ow, long minHeight, long minVolume, int minWidth,
155 int minPeak, int maxPeak, int maxPeakCount, int k, int ploidy, boolean logScale, double logWidth, ArrayList<String> list){
156 if(list==null){list=new ArrayList<String>();}
157 list.add("out="+fname);
158 list.add("ow="+ow);
159 list.add("minheight="+minHeight);
160 list.add("minvolume="+minVolume);
161 list.add("minwidth="+minWidth);
162 list.add("minpeak="+minPeak);
163 list.add("maxpeak="+maxPeak);
164 list.add("maxpeaks="+maxPeakCount);
165 list.add("k="+(k<1 ? 31 : k));
166 if(logScale){
167 list.add("logscale=t");
168 list.add("logwidth="+logWidth);
169 }
170 if(ploidy>0){list.add("ploidy="+ploidy);}
171 CallPeaks cp=new CallPeaks(list.toArray(new String[0]));
172 ArrayList<Peak> peaks=cp.callPeaks(array, gcArray, array.length);
173 cp.printPeaks(peaks, k, shared.Vector.sum(array), array, gcArray);
174 return cp.errorState;
175 }
176
177 /*--------------------------------------------------------------*/
178 /*---------------- Inner Methods ----------------*/
179 /*--------------------------------------------------------------*/
180
181 public static LongList[] loadHistogram(FileFormat ff, int k){//TODO: Add GC support
182 LongList list=new LongList(8000);
183 LongList gcList=new LongList(8000);
184 boolean hasGC=false;
185 TextFile tf=new TextFile(ff);
186 for(String line=tf.nextLine(); line!=null; line=tf.nextLine()){
187 if(line.startsWith("#")){
188 //ignore
189 }else{
190 String[] split=line.split("\\s+");
191 if(split.length==1){
192 list.add(Long.parseLong(split[0]));
193 }else{
194 final int x=Integer.parseInt(split[0]);
195 final long y=Long.parseLong(split[countColumn]);
196 list.set(x, y);
197 String last=split[split.length-1];
198 if(split.length>2 && last.indexOf('.')>=0 && Tools.isNumeric(last)){
199 hasGC=true;
200 double gc=Double.parseDouble(last)*0.01;
201 gcList.set(x, Math.round(y*gc*k));
202 }
203 }
204 }
205 }
206 boolean errorState_=tf.close();
207 assert(!errorState_) : "Encountered an error when reading "+ff.name()+".\n" +
208 "To skip this error message, run with the '-da' flag.";
209
210 return new LongList[] {list, hasGC ? gcList : null};
211 }
212
213 private static ArrayList<Peak> condense(ArrayList<Peak> in, int maxCount){
214 if(in==null || in.isEmpty()){return in;}
215 maxCount=Tools.max(Tools.min(in.size(), maxCount), 1);
216 ArrayList<Peak> out=new ArrayList<Peak>(Tools.min(maxCount, in.size()));
217
218 final long hlimit, vlimit;
219 {
220 {
221 long[] heights=new long[in.size()];
222 for(int i=0; i<in.size(); i++){
223 Peak p=in.get(i);
224 heights[i]=(callByRawCount ? p.maxHeight2() : p.maxHeight);
225 }
226 Arrays.sort(heights);
227 hlimit=heights[heights.length-maxCount];
228 }
229
230 {
231 int mc2=(maxCount+1)/2;
232 long[] volumes=new long[in.size()];
233 for(int i=0; i<in.size(); i++){
234 Peak p=in.get(i);
235 volumes[i]=(callByRawCount ? p.volume2 : p.volume);
236 }
237 Arrays.sort(volumes);
238 vlimit=volumes[volumes.length-mc2];
239 }
240 }
241
242 for(Peak p : in){
243 final long height=(callByRawCount ? p.maxHeight2() : p.maxHeight);
244 final long volume=(callByRawCount ? p.volume2 : p.volume);
245 if(volume>=vlimit || height>=hlimit){
246 // assert(!out.contains(p)) : height+", "+volume+", "+hlimit+", "+vlimit+", "+p;
247 out.add(p);
248 // System.err.println("Adding "+height+", "+volume+", "+hlimit+", "+vlimit+", "+p);
249 }
250 }
251
252 // for(Peak p : in){
253 // final long height=(callByRawCount ? p.maxHeight2() : p.maxHeight);
254 // final long volume=(callByRawCount ? p.volume2 : p.volume);
255 // if(volume>=vlimit || height>=hlimit){
256 // assert(out.contains(p));
257 // }else{
258 // assert(!out.contains(p));
259 // assert(volume<vlimit && height<hlimit);
260 // }
261 // }
262
263 for(Peak p : in){
264 final long height=(callByRawCount ? p.maxHeight2() : p.maxHeight);
265 final long volume=(callByRawCount ? p.volume2 : p.volume);
266 if(volume<vlimit && height<hlimit){
267 // assert(!out.contains(p)) : height+", "+volume+", "+hlimit+", "+vlimit+", "+p;
268 Peak p2=out.get(0);
269 for(Peak temp : out){
270 if(Tools.absdif(p.center, temp.center)<Tools.absdif(p.center, p2.center)){
271 p2=temp;
272 }
273 }
274 if(p2.compatibleWith(p)){
275 // assert(!out.contains(p)) : height+", "+volume+", "+hlimit+", "+vlimit+", "+p;
276 // assert((callByRawCount ? p2.maxHeight2() : p2.maxHeight)>=hlimit || (callByRawCount ? p2.volume2 : p2.volume)>=vlimit);
277 p2.absorb(p);
278 // assert(!out.contains(p)) : height+", "+volume+", "+hlimit+", "+vlimit+", "+p;
279 // assert((callByRawCount ? p2.maxHeight2() : p2.maxHeight)>=hlimit || (callByRawCount ? p2.volume2 : p2.volume)>=vlimit);
280 }//else discard
281 }
282 }
283
284 return out;
285 }
286
287 private static void capWidth(ArrayList<Peak> peaks, float maxWidthMult, long[] counts){
288 float mult=1/maxWidthMult;
289 for(Peak p : peaks){
290 p.start=(int)Math.round(Tools.max(p.start, p.center*mult));
291 p.stop=(int)Math.round(Tools.min(p.stop, p.center*maxWidthMult));
292 p.recalculate(counts);
293 }
294
295 // for(int i=0; i<peaks.)
296 }
297
298 private void printPeaks(ArrayList<Peak> peaks, int k, long uniqueKmers, long[] hist, long[] gcHist){
299 if(ffout==null){return;}
300 ByteStreamWriter bsw=new ByteStreamWriter(ffout);
301 bsw.start();
302
303 double gcmult=1.0/k;
304 if(peaks.size()>0){
305 try {
306 // final Peak p0=peaks.get(0);
307 // final int center0=p0.center;
308 float minHetRate=0.0003f; //Less than the human rate of ~0.001, but this will miss the first peak for inbred species.
309 final float minVolumeFraction=Tools.min(1, singleCopyKmerFraction(minHetRate, k, 2));
310 final int ploidyEstimate=calcPloidy(peaks, minVolumeFraction);
311 final int ploidy=ploidyClaimed>0 ? ploidyClaimed : ploidyEstimate;
312 final float haploidPeakCenter=haploidPeakCenter(peaks, ploidy);
313 final long errorKmers=errorKmers(peaks, hist, minVolumeFraction);
314 final long genomeSizeInPeaks=genomeSizeInPeaks(peaks, ploidy, haploidPeakCenter);
315 final long totalGenomeSize=genomeSize2(peaks, ploidy, haploidPeakCenter, hist);
316 final double gcContent=(gcHist==null ? -1 : gcContent(peaks, k));
317 final double gcContent2=(gcHist==null ? -1 : gcContent2(peaks, k, hist, gcHist));
318 final long repeatSize=repeatSize(peaks, ploidy, haploidPeakCenter);
319 final long repeatSize2=hist==null ? -1 : repeatSize2(peaks, ploidy, haploidPeakCenter, hist);
320 final long haploidSize=totalGenomeSize/ploidy;
321 final long hetLocs=calcHetLocations(peaks, ploidy, haploidPeakCenter, k);
322 final double hetRate=(hetLocs/(double)haploidSize)/2;//Final /2 is because a SNP will make BOTH paired chromosomes single-copy
323 final double repeatRate=repeatSize*1.0/genomeSizeInPeaks;
324 final double repeatRate2=repeatSize2*1.0/totalGenomeSize;
325
326 if(verbose) {
327 System.err.println("genomeSize="+genomeSizeInPeaks+", \trepeatSize="+repeatSize);
328 System.err.println("genomeSize2="+totalGenomeSize+",\trepeatSize2="+repeatSize2);
329 }
330
331 Peak p0=peaks.get(0);
332 Peak ploidyPeak=p0, mainPeak=p0;
333 float target=haploidPeakCenter*ploidy;
334 int haploidCov;
335 for(Peak p : peaks){
336 if(p.volume>mainPeak.volume){
337 mainPeak=p;
338 }
339 if(Tools.absdif(p.center, target)<Tools.absdif(ploidyPeak.center, target)){
340 ploidyPeak=p;
341 }
342 }
343 if(Tools.max(target,ploidyPeak.center)/(float)Tools.min(target,ploidyPeak.center)<1.3f){
344 haploidCov=ploidyPeak.center;
345 }else{
346 haploidCov=(int)target;
347 }
348
349 // System.err.println("ploidyEstimate="+ploidyEstimate);
350 // System.err.println("genomeSize="+genomeSize);
351 // System.err.println("repeatSize="+repeatSize);
352 // System.err.println("haploidSize="+haploidSize);
353 // System.err.println("hetLocs="+hetLocs);
354 // System.err.println("biggestPeak="+biggestPeak(peaks));
355 // System.err.println("homozygousPeak("+ploidy+")="+homozygousPeak(peaks, ploidy));
356 // System.err.println("homozygousPeak("+ploidyEstimate+")="+homozygousPeak(peaks, ploidyEstimate));
357
358 if(ploidy!=ploidyEstimate){
359 System.err.println("Warning - ploidy detected at "+ploidyEstimate+" differs from stated ploidy of "+ploidyClaimed);
360 }
361
362 if(k>0){bsw.println("#k\t"+k);}
363 bsw.println("#unique_kmers\t"+uniqueKmers);
364 bsw.println("#error_kmers\t"+errorKmers);
365 bsw.println("#genomic_kmers\t"+(uniqueKmers-errorKmers));
366 bsw.println("#main_peak\t"+mainPeak.center);
367 bsw.println("#genome_size_in_peaks\t"+genomeSizeInPeaks);
368 bsw.println("#genome_size\t"+totalGenomeSize);
369 if(mainPeak.gc>0){
370 bsw.println("#main_peak_gc\t"+Tools.format("%.3f", Tools.mid(0, 1, mainPeak.gc*gcmult/mainPeak.volume)));
371 }
372 if(gcHist!=null){
373 bsw.println("#gc_content_in_peaks\t"+Tools.format("%.3f", Tools.mid(0, 1, gcContent)));
374 bsw.println("#gc_content\t"+Tools.format("%.3f", Tools.mid(0, 1, gcContent2)));
375 }
376 if(ploidy>1 || true){bsw.println("#haploid_genome_size\t"+haploidSize);}
377 bsw.println("#fold_coverage\t"+Math.round(haploidPeakCenter));
378 if(ploidy>1 || true){bsw.println("#haploid_fold_coverage\t"+haploidCov);}
379 bsw.println("#ploidy\t"+ploidy);
380 if(ploidy!=ploidyEstimate){bsw.println("#ploidy_detected\t"+ploidyEstimate);}
381 if(ploidy>1){bsw.println("#het_rate\t"+Tools.format("%.5f", hetRate));}
382 bsw.println("#percent_repeat_in_peaks\t"+Tools.format("%.3f", (100*repeatRate)));
383 if(repeatSize2>=0){bsw.println("#percent_repeat\t"+Tools.format("%.3f", (100*repeatRate2)));}
384 } catch (Exception e) {
385 e.printStackTrace();
386 }
387 }
388
389 bsw.println("#start\tcenter\tstop\tmax\tvolume"+(gcHist!=null ? "\tgc":""));
390 ByteBuilder bb=new ByteBuilder(200);
391 for(Peak p : peaks){
392 if(p.volume>=minVolume){
393 p.toBytes(bb);
394 if(gcHist!=null){bb.tab().append(Tools.mid(0, 1, p.gc*gcmult/p.volume), 3);}
395 bb.nl();
396 bsw.print(bb);
397 bb.setLength(0);
398 }
399 }
400 errorState|=bsw.poisonAndWait();
401 }
402
403 private static Peak firstGenomicPeak(ArrayList<Peak> peaks, float minFraction) {
404 if(peaks.size()<1) {return null;}
405 assert(minFraction<=1);
406 final Peak biggest=peaks.get(biggestPeak(peaks));
407 final long minVolume=(long)(biggest.volume*minFraction);
408 for(Peak p : peaks) {
409 if(p.volume>=minVolume) {return p;}
410 }
411 assert(false) : peaks.size()+", "+biggest;
412 return null;
413 }
414
415 //single-copy kmers as a fraction of haploid genome size (result can range from 0 to ploidy).
416 //The math here is all totally wrong and terrible but might be within a factor of 4 of correct
417 private static float singleCopyKmerFraction(float hetRate, int k, int ploidy) {
418 if(ploidy<2) {return 1;}
419 float kmersPerSnp=k;//*(ploidy==2 ? 2 : 1);//Could be 1 or 2 in higher ploidies depending on the structure
420 float singleCopyKmers=hetRate*kmersPerSnp; //Fraction of whole genome size
421 float asymptote=singleCopyKmers/(1+singleCopyKmers);//Prevents the number from going over 1
422 return asymptote*2;
423 }
424
425 private static long errorKmers(ArrayList<Peak> peaks, long[] hist, float minVolumeFraction){
426 if(peaks.size()<1) {return 0;}
427 final Peak first=firstGenomicPeak(peaks, minVolumeFraction);
428 if(first==null || hist==null){return -1;}
429 long sum=0;
430 for(int i=0; i<first.start; i++){
431 sum+=hist[i];
432 }
433 return sum;
434 }
435
436 private static long genomeSizeInPeaks(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter){
437 if(peaks.size()<1){return 0;}
438
439 long sizeSum=0;
440 final double mult=1.0/(Tools.max(1, haploidPeakCenter));
441 for(Peak p : peaks){
442 long size=p.volume*(Math.round(p.center*mult));
443 sizeSum+=size;
444 }
445 return sizeSum;
446 }
447
448 private static long genomeSize2(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter, long[] hist){
449 if(peaks.size()<1){return 0;}
450
451 long sizeSum=0;
452 final double mult=1.0/(Tools.max(1, haploidPeakCenter));
453
454 final Peak p0=peaks.get(0);
455 for(int i=p0.start; i<hist.length; i++){
456 long size=hist[i]*(Tools.max(1, (long)Math.round(i*mult)));
457 sizeSum+=size;
458 }
459 return sizeSum;
460 }
461
462 private static double gcContent(ArrayList<Peak> peaks, int k){
463 if(peaks.size()<1){return 0;}
464
465 long sizeSum=0, gcSum=0;
466 final Peak p0=peaks.get(0);
467 final int center0=p0.center;
468 final double mult=1.0/(Tools.max(1, center0));
469 for(Peak p : peaks){
470 final long copies=Math.round(p.center*mult);
471 long size=p.volume*copies;
472 long gc=p.gc*copies;
473 sizeSum+=size;
474 gcSum+=gc;
475 }
476 return (gcSum*1.0)/(sizeSum*k);
477 }
478
479 private static double gcContent2(ArrayList<Peak> peaks, int k, long[] hist, long[] gcHist){
480 if(peaks.size()<1){return 0;}
481
482 long sizeSum=0, gcSum=0;
483 final Peak p0=peaks.get(0);
484 final int center0=p0.center;
485 final double mult=1.0/(Tools.max(1, center0));
486
487 for(int i=p0.start; i<hist.length; i++){
488 final long copies=(Tools.max(1, Math.round(i*mult)));
489 long size=hist[i]*copies;
490 long gc=gcHist[i]*copies;
491 sizeSum+=size;
492 gcSum+=gc;
493 }
494 return (gcSum*1.0)/(sizeSum*k);
495 }
496
497 /** Based on all peaks */
498 private static long repeatSize(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter){
499 if(peaks.size()<2){return 0;}
500 assert(ploidy>0) : ploidy;
501 final int homozygousLoc=homozygousPeak(peaks, ploidy, haploidPeakCenter);
502 final double mult=1.0/(Tools.max(1, haploidPeakCenter));
503
504 long sizeSum=0;
505 for(int i=homozygousLoc+1; i<peaks.size(); i++){
506 Peak p=peaks.get(i);
507 long size=p.volume*((Math.round(p.center*mult)-1));
508 sizeSum+=size;
509 }
510 return sizeSum;
511 }
512
513 /** Based on ploidy peak only */
514 private static long repeatSize2(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter, long[] hist){
515 assert(ploidy>0) : ploidy;
516 final double mult=1.0/(Tools.max(1, haploidPeakCenter));
517 int valley=(int)Math.ceil(haploidPeakCenter*ploidy*(1.2f+1.0f/Tools.max(2,ploidy)));
518
519 //Optional
520 final int homozygousLoc=homozygousPeak(peaks, ploidy, haploidPeakCenter);
521 if(ploidy>1 && homozygousLoc>=0) {
522 Peak p=peaks.get(homozygousLoc);
523 valley=p.stop+1;
524 }
525
526 long sizeSum=0;
527 for(int i=valley; i<hist.length; i++){
528 long size=hist[i]*(Math.round(i*mult)-1);
529 sizeSum+=size;
530 }
531 return sizeSum;
532 }
533
534 // /** Based on primary peak only */
535 // private static long repeatSize2(ArrayList<Peak> peaks, final float haploidPeakCenter, final int ploidy, long[] hist){
536 // assert(ploidy>0) : ploidy;
537 //// final int homozygousLoc=homozygousPeak(peaks, haploidPeakCenter, ploidy);
538 // final Peak p0=peaks.get(0);
539 // final int center0=p0.center;
540 // final double mult=1.0/(Tools.max(1, center0));
541 //
542 //
543 // final int valley=(int)Math.ceil(center0*1.7f);
544 // long sizeSum=0;
545 // for(int i=valley; i<hist.length; i++){
546 // long size=hist[i]*(Math.round(i*mult)-1);
547 // sizeSum+=size;
548 // }
549 // return sizeSum;
550 // }
551
552 private static int biggestPeak(ArrayList<Peak> peaks){
553 if(peaks.size()<2){return peaks.size()-1;}
554
555 final Peak p0=peaks.get(0);
556 Peak biggest=p0;
557 int loc=0;
558 for(int i=1; i<peaks.size(); i++){
559 Peak p=peaks.get(i);
560 if(p.volume>biggest.volume){
561 loc=i;
562 biggest=p;
563 }
564 }
565 return loc;
566 }
567
568 private static int secondBiggestPeak(ArrayList<Peak> peaks){
569 if(peaks.size()<2){return peaks.size()-1;}
570
571 Peak biggest=peaks.get(0);
572 Peak second=peaks.get(1);
573 int bloc=0;
574 int sloc=1;
575 if(second.volume>biggest.volume){
576 Peak temp=second;
577 second=biggest;
578 biggest=temp;
579 bloc=1;
580 sloc=0;
581 }
582 for(int i=2; i<peaks.size(); i++){
583 Peak p=peaks.get(i);
584 if(p.volume>second.volume){
585 sloc=i;
586 second=p;
587 if(second.volume>biggest.volume){
588 Peak temp=second;
589 second=biggest;
590 biggest=temp;
591 sloc=bloc;
592 bloc=i;
593 }
594 }
595 }
596 return sloc;
597 }
598
599 private static int homozygousPeak(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter){
600 if(peaks.size()<2){return peaks.size()-1;}
601 assert(ploidy>0) : ploidy;
602
603 final float target=haploidPeakCenter*ploidy;
604 // System.err.println("target="+target);
605 float bestDif=Integer.MAX_VALUE;
606 int loc=0;
607 for(int i=0; i<peaks.size(); i++){
608 Peak p=peaks.get(i);
609 float dif=Tools.absdif(target, p.center);
610 // System.err.println("dif="+dif+" for peak "+i+", center "+p.center);
611 if(dif<bestDif){
612 bestDif=dif;
613 loc=i;
614 // System.err.println("New best at loc "+i);
615 }
616 }
617 return loc;
618 }
619
620 private static float haploidPeakCenter(ArrayList<Peak> peaks, int ploidy) {
621 assert(ploidy>0);
622 final Peak biggest=peaks.get(biggestPeak(peaks));
623 final Peak second=peaks.get(secondBiggestPeak(peaks));
624 if(second.volume*4>=biggest.volume) {//Similar volume; lowest is haploid peak
625 return Tools.min(biggest.center, second.center);
626 }
627 //Assume biggest is ploidy peak
628 return biggest.center/(float)ploidy;
629 }
630
631 private static int calcPloidy(ArrayList<Peak> peaks, float minVolumeFraction){
632 if(peaks.size()<2){return 1;}
633
634 final Peak p0=peaks.get(0);
635 final Peak biggest=peaks.get(biggestPeak(peaks));
636 final Peak second=peaks.get(secondBiggestPeak(peaks));
637
638 if(ploidyLogic==1) {//Old code path, assumes no error/contamination peaks
639 if(biggest==p0){//p0 is biggest.
640 // System.err.println("a: "+biggest+" > "+second);
641 if(second.volume*4<biggest.volume){return 1;} //Probably second is a repeat peak.
642 int ratio=Math.round((second.center/(float)biggest.center));
643 // System.err.println("b: "+ratio);
644 return Tools.max(1, ratio);
645 }else {//p0 is not biggest.
646 //I wonder if this should be biggest/second...
647 int ratio=Math.round((biggest.center/(float)p0.center));
648 // System.err.println("c: "+biggest+", "+((biggest.center/(float)p0.center)));
649 return ratio;
650 }
651 }else {
652
653 if(second==biggest) {
654 return 1;
655 }else if(second.center<biggest.center) {//Second volume could be low, and is based on het rate
656 if(second.volume<biggest.volume*minVolumeFraction) {
657 //Second peak is tiny and likely contamination.
658 return 1;
659 }
660 }else {//second volume should be substantial since it is the heterozygous fraction
661 if(second.volume*4<biggest.volume) {
662 //Second peak is small and likely repeat.
663 return 1;
664 }
665 }
666 final int max=Tools.max(biggest.center, second.center);
667 final int min=Tools.min(biggest.center, second.center);
668 return Math.round(max/(float)min);
669 }
670 }
671
672 private static long calcHetLocations(ArrayList<Peak> peaks, final int ploidy, final float haploidPeakCenter, final int k){
673 if(peaks.size()<2){return 0;}
674 assert(ploidy>0) : ploidy;
675 final int homozygousLoc=homozygousPeak(peaks, ploidy, haploidPeakCenter);
676 final Peak homoPeak=peaks.get(homozygousLoc);
677 long sum=0;
678 final int lim=ploidy/2;
679 for(int i=0; i<homozygousLoc; i++){
680 final Peak p=peaks.get(i);
681 final int copyCount=Math.round((p.center*ploidy)/(float)homoPeak.center);
682 // System.err.println("lim="+lim+". For peak "+i+", copyCount="+copyCount+", volume="+p.volume);
683 if(copyCount>lim){break;}
684 // double peakLocs=(p.volume/(double)k);
685 sum=sum+p.volume;
686 }
687 return sum/k;
688 }
689
690 public ArrayList<Peak> callPeaks(LongList list, LongList gcList){
691 return callPeaks(list.array, gcList==null ? null : gcList.array, list.size);
692 }
693
694 public ArrayList<Peak> callPeaks(final long[] original, final long gcArray[], final int length){
695
696 long[] array=original;
697
698 if(logScale){
699 array=logScale(array, logWidth, 1, logPasses);
700 }
701
702 if(smoothRadius>0){
703 if(smoothProgressiveFlag){
704 array=smoothProgressive(array, smoothRadius);
705 }else{
706 array=smooth(array, smoothRadius);
707 }
708 }
709
710 ArrayList<Peak> peaks=new ArrayList<Peak>();
711
712 int dip0=-1;
713 for(int i=1; i<length; i++){
714 if(array[i-1]<array[i]){
715 dip0=i-1;
716 break;
717 }
718 }
719 if(dip0<0){return peaks;}
720 // assert(false) : dip0+", "+array[dip0);
721
722 final int UP=0, DOWN=1;
723 int mode=UP;
724 int start=dip0, center=-1;
725 long prev=array[dip0];
726 long sum=prev;
727 long gcSum=gcArray==null ? -1 : gcArray[dip0];
728 long sum2=prev*dip0;
729 for(int i=dip0+1; i<length; i++){
730 final long x=array[i];
731
732 // if(i<16){System.err.println("i="+i+", x="+x+", mode="+mode+", center="+center+", start="+start+", dip0="+dip0);}
733
734 if(mode==UP){
735 if(x<prev){
736 mode=DOWN;
737 center=i-1;
738 }
739 }else{
740 if(x>prev){
741 mode=UP;
742 int stop=i-1;
743 long max=array[center];
744 if(center>=minPeak && center<=maxPeak && max>=minHeight && (stop-start)>=minWidth && sum>=minVolume){
745 for(int j=center-1; j>=0; j--){//find middle of mesas
746 if(array[j]!=max){
747 center=(center+j+2)/2;
748 break;
749 }
750 }
751 {
752 long valley=array[stop];
753 for(int j=stop; j>=0; j--){//find middle of valleys
754 if(array[j]!=valley){
755 if(valley==0){stop=j+1;}
756 else{stop=(stop+j+2)/2;}
757 break;
758 }
759 }
760 }
761
762 long height1=array[start], height2=array[stop];
763 Peak p=new Peak(center, start, stop, center, max, height1, height2, height1, height2, sum, sum2, gcSum);
764 peaks.add(p);
765 }else{
766 // Peak p=new Peak(center, start, stop, max, sum);
767 // System.err.println("*"+p);
768 }
769 start=stop;
770 stop=-1;
771 sum=sum2=0;
772 gcSum=0;
773 center=-1;
774 if(i>maxPeak){break;}
775 while(i<array.length && array[i]==0){i++;}//Skip zero regions
776 }
777 }
778 gcSum=(gcArray==null ? -1 : gcSum+gcArray[i]);
779 sum+=x;
780 sum2+=(x*i);
781 prev=x;
782 }
783
784 if(mode==DOWN){
785 int stop=length;
786 long max=array[center];
787 for(int j=center-1; j>=0; j--){//find middle of mesas
788 if(array[j]!=max){
789 center=(center+j+2)/2;
790 break;
791 }
792 }
793 {
794 long valley=array[stop-1];
795 for(int j=stop-1; j>=0; j--){//find middle of valleys
796 if(array[j]!=valley){
797 if(valley==0){stop=j+1;}
798 else{stop=(stop+j+2)/2;}
799 break;
800 }
801 }
802 }
803 if(center>=minPeak && center<=maxPeak && max>=minHeight && (stop-start)>=minWidth && sum>=minVolume){
804 long height1=array[start], height2=array[Tools.min(stop, length-1)];
805 Peak p=new Peak(center, start, Tools.min(stop, length-1), center, max, height1, height2, height1, height2, sum, sum2, gcSum);
806 peaks.add(p);
807 }else{
808 // Peak p=new Peak(center, start, stop, max, sum);
809 // System.err.println("*"+p);
810 }
811 }
812
813 //Ensure peaks don't violate maxWidthMult by shrinking those that do, for each side, relative to the center.
814 capWidth(peaks, maxWidthMult, array);
815
816 //Have peaks absorb adjacent smaller peaks
817 if(maxPeakCount<peaks.size()){
818 peaks=condense(peaks, maxPeakCount);
819 }
820
821 // System.err.println("start\tcenter\tstop\tmax\tvolume");
822 // for(Peak p : peaks){
823 // System.err.println(p.toString());
824 // }
825 // assert(false);
826
827 capWidth(peaks, maxWidthMult, array);
828
829 if(peaks.size()>1){
830 Peak biggest=peaks.get(biggestPeak(peaks));
831 while(peaks.size()>1 && peaks.get(0).volume<0.0001*biggest.volume){
832 peaks.remove(0);
833 }
834 }
835
836 ArrayList<Peak> peaksOut=peaks;
837 if(array!=original){
838 peaksOut=new ArrayList<Peak>();
839 recalculate(peaks, original);
840 for(Peak p : peaks){
841 if(p.volume>=minVolume){peaksOut.add(p);}
842 }
843 }
844
845 return peaksOut;
846 }
847
848 private static void recalculate(ArrayList<Peak> peaks, long[] array){
849 for(Peak p : peaks){
850 p.recalculate(array);
851 }
852 }
853
854 public static long[] logScale(long[] array, double width, double scale, int passes){
855 assert(passes>0);
856 long[] log=array;
857 for(int pass=0; pass<passes; pass++){
858 final double halfWidth=width/2;
859 final double limit=array.length-0.00001;
860 log=new long[array.length];
861 for(int pos=1; pos<array.length; pos++){
862 final double center=pos+0.5;
863 final double min=Tools.max(0, center-halfWidth*pos);
864 final double max=Tools.min(limit, center+halfWidth*pos);
865 final int mini=(int)min;
866 final int maxi=(int)max;
867 if(mini==maxi){
868 log[pos]=Math.round((max-min)*array[mini]*scale);
869 }else{
870 double sum=0;
871 sum+=(array[mini]*(mini+1-min));
872 sum+=(array[maxi]*(max-maxi));
873 for(int i=mini+1; i<maxi; i++){
874 sum+=array[i];
875 }
876 log[pos]=Math.round(sum*scale);
877 }
878 }
879 array=log;
880 }
881 return log;
882 }
883
884 /*--------------------------------------------------------------*/
885 /*---------------- Smoothing ----------------*/
886 /*--------------------------------------------------------------*/
887
888 public static long[] smoothProgressive(final long[] data, int radius0){
889 int radius=radius0;
890 long div=radius*radius;
891 double mult=1.0/div;
892 long[] smoothed=new long[data.length];
893 for(int i=0, next=5; i<data.length; i++){
894 long sum=sumPoint(data, i, radius);
895 double product=sum*mult;
896 // if(data[i]>=product){smoothed[i]=(long)Math.ceil(product);}
897 // else{smoothed[i]=(long)product;}
898 smoothed[i]=Math.round(product);
899 if(i>next){
900 next=(int)Math.ceil(1+next*progressiveMult);
901 radius+=1;
902 div=radius*radius;
903 mult=1.0/div;
904 if(radius>maxRadius){next=Integer.MAX_VALUE;}
905 // System.err.println(radius+", "+div);
906 }
907 }
908 return smoothed;
909 }
910
911 public static long[] smooth(final long[] data, int radius){
912 final long div=radius*radius;
913 final double mult=1.0/div;
914 long[] smoothed=new long[data.length];
915 for(int i=0; i<data.length; i++){
916 long sum=sumPoint(data, i, radius);
917 double product=sum*mult;
918 // if(data[i]>=product){smoothed[i]=(long)Math.ceil(product);}
919 // else{smoothed[i]=(long)product;}
920 smoothed[i]=Math.round(product);
921 }
922 return smoothed;
923 }
924
925 private static long sumPoint(long[] data, int loc, int radius){
926 long sum=0;
927 int start=loc-radius+1;
928 int stop=loc+radius-1;
929 for(int i=start, x=1; i<loc; i++, x++){
930 int i2=Tools.max(i, 0);
931 sum+=data[i2]*x;
932 }
933 for(int i=loc, x=radius, max=data.length-1; i<=stop; i++, x--){
934 int i2=Tools.min(i, max);
935 sum+=data[i2]*x;
936 }
937 return sum;
938 }
939
940 public static int[] smoothProgressive(final int[] data, int radius0){
941 int radius=radius0;
942 long div=radius*radius;
943 double mult=1.0/div;
944 int[] smoothed=new int[data.length];
945 for(int i=0, next=5; i<data.length; i++){
946 long sum=sumPoint(data, i, radius);
947 double product=sum*mult;
948 // if(data[i]>=product){smoothed[i]=(long)Math.ceil(product);}
949 // else{smoothed[i]=(long)product;}
950 smoothed[i]=(int)Math.round(product);
951 if(i>next){
952 next=(int)Math.ceil(next*2);
953 radius+=1;
954 div=radius*radius;
955 mult=1.0/div;
956 if(radius>10){next=Integer.MAX_VALUE;}
957 // System.err.println(radius+", "+div);
958 }
959 }
960 return smoothed;
961 }
962
963 public static int[] smooth(final int[] data, int radius){
964 final long div=radius*radius;
965 final double mult=1.0/div;
966 int[] smoothed=new int[data.length];
967 for(int i=0; i<data.length; i++){
968 long sum=sumPoint(data, i, radius);
969 double product=sum*mult;
970 // if(data[i]>=product){smoothed[i]=(int)Math.ceil(product);}
971 // else{smoothed[i]=(int)product;}
972 smoothed[i]=(int)Math.round(product);
973 }
974 return smoothed;
975 }
976
977 private static long sumPoint(int[] data, int loc, int radius){
978 long sum=0;
979 int start=loc-radius+1;
980 int stop=loc+radius-1;
981 for(int i=start, x=1; i<loc; i++, x++){
982 int i2=Tools.max(i, 0);
983 sum+=data[i2]*x;
984 }
985 for(int i=loc, x=radius, max=data.length-1; i<=stop; i++, x--){
986 int i2=Tools.min(i, max);
987 sum+=data[i2]*x;
988 }
989 return sum;
990 }
991
992 /*--------------------------------------------------------------*/
993 /*---------------- Nested Classes ----------------*/
994 /*--------------------------------------------------------------*/
995
996 private class Peak{
997
998 Peak(int center_, int start_, int stop_, int maxPos_, long maxHeight_, long startHeight_, long stopHeight_,
999 long leftMin_, long rightMin_, long volume_, long volume2_, long gc_){
1000
1001 center=center_;
1002 start=Tools.max(0, start_);
1003 stop=stop_;
1004 maxPos=maxPos_;
1005
1006 maxHeight=maxHeight_;
1007 startHeight=startHeight_;
1008 stopHeight=stopHeight_;
1009 volume=volume_;
1010 volume2=volume2_;
1011
1012 leftMin=leftMin_;
1013 rightMin=rightMin_;
1014
1015 gc=gc_;
1016
1017 assert(center>=0) : this;
1018 assert(start<center) : this;
1019 assert(stop>center) : this;
1020 }
1021
1022 public boolean compatibleWith(Peak p) {
1023 int min=Tools.min(center, p.stop);
1024 int max=Tools.max(stop, p.center);
1025 // assert(min*maxWidthMult>=max) : this+", "+p+", "+(min*maxWidthMult)+", "+max;
1026 return min*maxWidthMult>=max;
1027 }
1028
1029 /**
1030 * @param array
1031 */
1032 public void recalculate(long[] array) {
1033 maxHeight=array[center];
1034 startHeight=array[start];
1035 stopHeight=array[stop];
1036 leftMin=startHeight;
1037 rightMin=stopHeight;
1038 maxPos=center;
1039 volume=0;
1040 volume2=0;
1041 for(int i=start; i<stop; i++){
1042 long x=array[i];
1043 if(x>maxHeight){
1044 maxPos=i;
1045 maxHeight=x;
1046 }
1047 if(i<center){leftMin=Tools.min(leftMin, x);}
1048 else if(i>center){rightMin=Tools.min(rightMin, x);}
1049 volume+=x;
1050 volume2+=(x*i);
1051 }
1052 }
1053
1054 /**
1055 * @param p
1056 */
1057 public void absorb(Peak p) {
1058 assert(this!=p);
1059
1060 if(center>p.center){
1061 assert(p.stop<stop) : "\n"+this+"\n"+p+"\n";
1062 if(start>p.start){
1063 start=p.start;
1064 startHeight=p.startHeight;
1065 }
1066 leftMin=Tools.min(leftMin, p.leftMin);
1067 }else{
1068 assert(p.start>start) : "\n"+this+"\n"+p+"\n";
1069 if(stop<p.stop){
1070 stop=p.stop;
1071 stopHeight=p.stopHeight;
1072 }
1073 rightMin=Tools.min(rightMin, p.rightMin);
1074 }
1075
1076 //Potentially shift the center
1077 // {
1078 // long c1=callMetric();
1079 // long c2=p.callMetric();
1080 // System.err.print(this+" absorbed "+p);
1081 // if(c1<c2){
1082 // assert(false);
1083 // center=p.center;
1084 // }else{
1085 //
1086 // }
1087 // }
1088
1089 if(maxHeight<p.maxHeight){
1090 maxHeight=p.maxHeight;
1091 maxPos=p.maxPos;
1092 }
1093
1094 volume+=p.volume;
1095 volume2+=p.volume2;
1096 gc+=p.gc;
1097 // System.err.println(" -> "+this);
1098 }
1099
1100 int width(){return stop-start;}
1101
1102 @Override
1103 public String toString(){
1104 return start+"\t"+center+"\t"+stop+"\t"+maxHeight+"\t"+volume;
1105 }
1106
1107 public ByteBuilder toBytes(ByteBuilder bb){
1108 if(bb==null){bb=new ByteBuilder();}
1109 bb.append(start);
1110 bb.tab();
1111 bb.append(center);
1112 bb.tab();
1113 bb.append(stop);
1114 bb.tab();
1115 bb.append(maxHeight);
1116 bb.tab();
1117 bb.append(volume);
1118 return bb;
1119 }
1120
1121 /** Inclusive */
1122 public int start;
1123 public int center;
1124 /** Exclusive */
1125 public int stop;
1126 public int maxPos;
1127
1128 //Unique counts
1129 public long startHeight;
1130 // public long centerHeight;
1131 public long stopHeight;
1132 public long volume;
1133 public long volume2;
1134
1135 public long leftMin;
1136 public long rightMin;
1137 public long maxHeight;
1138 public long gc;
1139
1140 //Raw counts
1141 public long startHeight2(){return startHeight*start;}
1142 // public long centerHeight2(){return centerHeight*center;}
1143 public long maxHeight2(){return maxHeight*center;}
1144 public long stopHeight2(){return stopHeight*stop;}
1145 public long callMetric(){
1146 if(CALL_MODE==BY_VOLUME){return callByRawCount ? volume2 : volume;}
1147 return callByRawCount ? maxHeight2() : maxHeight;
1148 }
1149
1150
1151
1152 }
1153
1154 /*--------------------------------------------------------------*/
1155 /*---------------- Fields ----------------*/
1156 /*--------------------------------------------------------------*/
1157
1158 private long minHeight=2;
1159 private long minVolume=5;
1160 private int minWidth=3;
1161 private int minPeak=2;
1162 private int maxPeak=Integer.MAX_VALUE;
1163 private int maxPeakCount=10;
1164 private float maxWidthMult=2.5f;
1165 private int smoothRadius=0;
1166 private boolean smoothProgressiveFlag=true;
1167 private int k=31;
1168
1169 private int ploidyClaimed=-1;
1170
1171 private boolean logScale=false;
1172 private double logWidth=0.1;
1173 private int logPasses=1;
1174
1175 private String in;
1176 private String out;
1177
1178 private final FileFormat ffin;
1179 private final FileFormat ffout;
1180
1181 /*--------------------------------------------------------------*/
1182 /*---------------- Static Fields ----------------*/
1183 /*--------------------------------------------------------------*/
1184
1185 public static int maxRadius=10;
1186 public static float progressiveMult=2;
1187
1188 /*--------------------------------------------------------------*/
1189 /*---------------- Common Fields ----------------*/
1190 /*--------------------------------------------------------------*/
1191
1192 private static int countColumn=1;
1193
1194 private PrintStream outstream=System.err;
1195 public static boolean verbose=false;
1196 public boolean errorState=false;
1197 private boolean overwrite=true;
1198 private boolean append=false;
1199 public static boolean printClass=true;
1200
1201 public static boolean callByRawCount=false;
1202 public static boolean weightByRelief=false;
1203 public static final int BY_VOLUME=0, BY_HEIGHT=1;
1204 public static int CALL_MODE=BY_VOLUME;
1205 public static int ploidyLogic=2;
1206
1207 }