Debian Codegraph @

current/jgi/ReadKmerDepthDistribution.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.lang.Thread.State;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.List;
9 import java.util.concurrent.atomic.AtomicLong;
10 import java.util.concurrent.atomic.AtomicLongArray;
11
12 import bloom.KCountArray;
13 import bloom.KmerCountAbstract;
14 import bloom.ReadCounter;
15 import dna.AminoAcid;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import fileIO.TextStreamWriter;
19 import shared.Parse;
20 import shared.Parser;
21 import shared.PreParser;
22 import shared.Shared;
23 import shared.Timer;
24 import shared.Tools;
25 import stream.ConcurrentReadInputStream;
26 import stream.ConcurrentReadOutputStream;
27 import stream.FastaReadInputStream;
28 import stream.Read;
29 import structures.ListNum;
30 import tracker.ReadStats;
31
32
33
34 /**
35 * This class is designed to visualize the distribution of kmer depths across individual reads.
36 * @author Brian Bushnell
37 * @date May 15, 2013
38 *
39 */
40 public class ReadKmerDepthDistribution {
41
42 public static void main(String[] args){
43
44 {//Preparse block for help, config files, and outstream
45 PreParser pp=new PreParser(args, new Object() { }.getClass().getEnclosingClass(), false);
46 args=pp.args;
47 outstream=pp.outstream;
48 }
49
50 String reads1=(args[0].indexOf("=")>0 ? null : args[0]);
51 String reads2=(reads1!=null && args.length>1 ? args[1] : null);
52 if(reads2!=null && "null".equalsIgnoreCase(reads2)){reads2=null;}
53
54 {
55 if(reads1!=null && !reads1.contains(",")){
56 File f=new File(reads1);
57 if(!f.exists() || !f.isFile()){throw new RuntimeException(reads1+" does not exist.");}
58 }
59 if(reads2!=null && !reads2.contains(",")){
60 File f=new File(reads2);
61 if(!f.exists() || !f.isFile()){throw new RuntimeException(reads2+" does not exist.");}
62 if(reads2.equalsIgnoreCase(reads1)){
63 throw new RuntimeException("Both input files are the same.");
64 }
65 }
66 }
67
68 KmerCountAbstract.minQuality=4;
69 KmerCountAbstract.minProb=0.4f;
70 KmerCountAbstract.CANONICAL=true;
71
72 int k=31;
73 int cbits=32;
74 int hashes=3;
75 // int matrixbits=-1;
76 long cells=-1;
77 long maxReads=-1;
78 int buildpasses=1;
79 long tablereads=-1; //How many reads to process when building the hashtable
80 int buildStepsize=4;
81 String outKeep=null;
82 int prehashes=-1;
83 long precells=-1;
84 String histFile=null;
85 int threads=-1;
86 ReadWrite.ZIPLEVEL=2;
87 int minq=KmerCountAbstract.minQuality;
88
89 boolean auto=true;
90 boolean deterministic=true;
91
92 List<String> extra=null;
93
94 long memory=Runtime.getRuntime().maxMemory();
95
96 Parser parser=new Parser();
97 for(int i=(reads1==null ? 0 : 1); i<args.length; i++){
98 if(args[i]==null){args[i]="null";}
99 final String arg=args[i];
100 final String[] split=arg.split("=");
101 String a=split[0].toLowerCase();
102 String b=split.length>1 ? split[1] : null;
103
104 if(Parser.parseCommonStatic(arg, a, b)){
105 //do nothing
106 }else if(Parser.parseZip(arg, a, b)){
107 //do nothing
108 }else if(Parser.parseQuality(arg, a, b)){
109 //do nothing
110 }else if(Parser.parseFasta(arg, a, b)){
111 //do nothing
112 }else if(parser.parseInterleaved(arg, a, b)){
113 //do nothing
114 }else if(a.equals("k") || a.equals("kmer")){
115 k=Integer.parseInt(b);
116 }else if(a.equals("in") || a.equals("in1")){
117 reads1=b;
118 }else if(a.equals("in2")){
119 reads2=b;
120 }else if(a.startsWith("bits") ||a.startsWith("cbits") || a.startsWith("cellbits")){
121 cbits=Integer.parseInt(b);
122 }else if(a.startsWith("histlen") ||a.startsWith("histogramlen")){
123 HIST_LEN_PRINT=Tools.min(Integer.MAX_VALUE, Long.parseLong(b)+1);
124 }else if(a.startsWith("matrixbits")){
125 int matrixbits=Integer.parseInt(b);
126 assert(matrixbits<63);
127 cells=1L<<matrixbits;
128 }else if(a.startsWith("cells")){
129 cells=Parse.parseKMG(b);
130 }else if(a.startsWith("precells") || a.startsWith("prefiltercells")){
131 precells=Parse.parseKMG(b);
132 prefilter=prefilter || precells!=0;
133 }else if(a.startsWith("minq")){
134 minq=Byte.parseByte(b);
135 }else if(a.equals("zerobin")){
136 ZERO_BIN=Parse.parseBoolean(b);
137 }else if(a.equals("deterministic") || a.equals("dr")){
138 boolean x=Parse.parseBoolean(b);
139 deterministic=x;
140 }else if(a.startsWith("minprob")){
141 KmerCountAbstract.minProb=Float.parseFloat(b);
142 }else if(a.startsWith("hashes")){
143 hashes=Integer.parseInt(b);
144 }else if(a.startsWith("prehashes") || a.startsWith("prefilterhashes")){
145 prehashes=Integer.parseInt(b);
146 prefilter=prefilter || prehashes!=0;
147 }else if(a.equals("prefilter")){
148 prefilter=Parse.parseBoolean(b);
149 }else if(a.startsWith("stepsize") || a.startsWith("buildstepsize")){
150 buildStepsize=Integer.parseInt(b);
151 }else if(a.startsWith("passes") || a.startsWith("buildpasses")){
152 buildpasses=Integer.parseInt(b);
153 }else if(a.equals("printcoverage")){
154 assert(false) : "This is not the program you are looking for. Try KmerCoverage.";
155 }else if(a.equals("threads") || a.equals("t")){
156 threads=Integer.parseInt(b);
157 }else if(a.equals("reads") || a.startsWith("maxreads")){
158 maxReads=Parse.parseKMG(b);
159 }else if(a.startsWith("tablereads") || a.startsWith("buildreads")){
160 tablereads=Parse.parseKMG(b);
161 }else if(a.equals("out") || a.equals("outk") || a.equals("outkeep") || a.equals("outgood")){
162 outKeep=b;
163 }else if(a.startsWith("hist")){
164 histFile=b;
165 }else if(a.startsWith("verbose")){
166 verbose=Parse.parseBoolean(b);
167 }else if(a.equals("ordered") || a.equals("ord")){
168 ordered=Parse.parseBoolean(b);
169 }else if(a.equals("append") || a.equals("app")){
170 append=ReadStats.append=Parse.parseBoolean(b);
171 }else if(a.equals("overwrite") || a.equals("ow")){
172 overwrite=Parse.parseBoolean(b);
173 }else if(a.equals("auto") || a.equals("automatic")){
174 auto=Parse.parseBoolean(b);
175 }else if(a.equals("canonical")){
176 CANONICAL=KmerCountAbstract.CANONICAL=Parse.parseBoolean(b);
177 }else if(a.equals("fixspikes")){
178 FIX_SPIKES=Parse.parseBoolean(b);
179 }else if(a.equals("printzerocoverage") || a.equals("pzc")){
180 PRINT_ZERO_COVERAGE=Parse.parseBoolean(b);
181 }else if(a.equals("removeduplicatekmers") || a.equals("rdk")){
182 KmerCountAbstract.KEEP_DUPLICATE_KMERS=!Parse.parseBoolean(b);
183 }else if(a.equals("target") || a.equals("targetdepth")){
184 TARGET_DEPTH=Integer.parseInt(b);
185 }else if(a.equals("max") || a.equals("maxdepth")){
186 MAX_DEPTH=Integer.parseInt(b);
187 }else if(a.equals("min") || a.equals("mindepth")){
188 MIN_DEPTH=Integer.parseInt(b);
189 }else if(a.equals("minkmers") || a.equals("minkmersovermindepth") || a.equals("mingoodkmersperread") || a.equals("mgkpr")){
190 MIN_KMERS_OVER_MIN_DEPTH=Tools.max(1, Integer.parseInt(b));
191 }else if(a.equals("percentile") || a.equals("depthpercentile") || a.equals("dp")){
192 DEPTH_PERCENTILE=Float.parseFloat(b);
193 if(DEPTH_PERCENTILE>1 && DEPTH_PERCENTILE<=100){DEPTH_PERCENTILE/=100;}
194 assert(DEPTH_PERCENTILE>=0 && DEPTH_PERCENTILE<=1) : "Depth percentile must be between 0 and 100.";
195 }else if(a.equals("extra")){
196 if(b!=null && !b.equalsIgnoreCase("null")){
197 if(new File(b).exists()){
198 extra=new ArrayList<String>();
199 extra.add(b);
200 }else{
201 extra=Arrays.asList(b.split(","));
202 }
203 }
204 }else{
205 throw new RuntimeException("Unknown parameter "+arg);
206 }
207 }
208
209 {//Process parser fields
210 Parser.processQuality();
211 }
212
213 MAX_DEPTH=Tools.max(MAX_DEPTH, TARGET_DEPTH);
214 assert(TARGET_DEPTH>0);
215
216 assert(FastaReadInputStream.settingsOK());
217 if(k>31){CANONICAL=KmerCountAbstract.CANONICAL=false;}
218 assert(CANONICAL==KmerCountAbstract.CANONICAL);
219
220 // if(output!=null && reads1.contains(",")){
221 // throw new RuntimeException("\nLists of input files can only be used with histogram output, not full output.\n" +
222 // "Please set output=null or move the extra input files to 'extra=file1,file2,...fileN'");
223 // }
224
225 {
226 if(histFile==null){
227 // HIST_LEN=Tools.min(20000, HIST_LEN);
228 // HIST_LEN_PRINT=Tools.min(20000, HIST_LEN_PRINT);
229 }else{
230 USE_HISTOGRAM=true;
231 }
232
233 final int maxCount=(int)(cbits>16 ? Integer.MAX_VALUE : (1L<<cbits)-1);
234 assert(maxCount>0);
235 HIST_LEN_PRINT=Tools.max(1, Tools.min(HIST_LEN_PRINT, maxCount+1));
236 assert(HIST_LEN_PRINT<=Integer.MAX_VALUE) : HIST_LEN_PRINT+", "+Integer.MAX_VALUE;
237 HIST_LEN=(int)Tools.min(maxCount+1, Tools.max(HIST_LEN_PRINT, HIST_LEN));
238 THREAD_HIST_LEN=Tools.min(THREAD_HIST_LEN, HIST_LEN);
239
240 histogram_total=new AtomicLongArray(HIST_LEN);
241 }
242
243 if(extra!=null){
244 for(String s : extra){
245 File f=new File(s);
246 if(!f.exists() || !f.isFile()){throw new RuntimeException(s+" does not exist.");}
247 assert(!s.equalsIgnoreCase(reads1) && (reads2==null || !s.equalsIgnoreCase(reads2))) : "\nInput file "+s+" should not be included as an extra file.\n";
248 }
249 }
250
251 // outstream.println("ForceInterleaved = "+FASTQ.FORCE_INTERLEAVED);
252
253 // assert(false) : reads1+", "+reads2+", "+output;
254 // if(FASTQ.FORCE_INTERLEAVED && in2==null){
255 // outstream.println()
256 // }
257
258 if(threads<=0){
259 if(auto){THREADS=Shared.LOGICAL_PROCESSORS;}
260 else{THREADS=8;}
261 }else{
262 THREADS=threads;
263 }
264
265 // System.err.println("THREADS="+THREADS+", KmerCountAbstract.THREADS="+KmerCountAbstract.THREADS);
266
267 if(auto && cells==-1){
268 final long usable=(long)Tools.max(((memory-96000000)*.73), memory*0.45);
269 long mem=usable-(USE_HISTOGRAM ? (HIST_LEN*8*(1)) : 0);
270 if(buildpasses>1){mem/=2;}
271 cells=(mem*8)/cbits;
272 //
273 // long tablebytes=((1L<<matrixbits)*cbits)/8;
274 // if(tablebytes*3<usable){matrixbits++;}
275 // outstream.println(tablebytes/1000000+", "+usable/1000000+", "+(tablebytes*3)/1000000);
276
277 }else if(cells==-1){
278 cells=1L<<34;
279 }
280
281 if(prefilter){
282 if(precells<1){
283 long totalbits=cells*cbits;
284 long prebits=(long)(totalbits*0.35);
285 precells=prebits/2;
286 cells=(totalbits-prebits+cbits-1)/cbits; //Steal memory from cell allocation
287 }
288 if(prehashes<1){
289 prehashes=(hashes+1)/2;
290 }
291 }
292
293 {
294 outstream.println("\nSettings:");
295 outstream.println("threads: \t"+THREADS);
296 outstream.println("k: \t"+k);
297 outstream.println("deterministic: \t"+deterministic);
298 outstream.println("passes: \t"+buildpasses);
299 outstream.println("bits per cell: \t"+cbits);
300 // outstream.println("matrixbits: \t"+matrixbits);
301 outstream.println("cells: \t"+Tools.toKMG(cells));
302 outstream.println("hashes: \t"+hashes);
303 if(prefilter){
304 outstream.println("prefilter bits: \t"+2);
305 // outstream.println("matrixbits: \t"+matrixbits);
306 outstream.println("prefilter cells: \t"+(precells>0 && prehashes>0 ? Tools.toKMG(precells) : "?"));
307 outstream.println("prefilter hashes: \t"+(precells>0 && prehashes>0 ? ""+prehashes : "?"));
308 }
309 outstream.println("base min quality: \t"+KmerCountAbstract.minQuality);
310 outstream.println("kmer min prob: \t"+KmerCountAbstract.minProb);
311
312 outstream.println();
313 outstream.println("target depth: \t"+TARGET_DEPTH);
314 outstream.println("min depth: \t"+MIN_DEPTH);
315 outstream.println("max depth: \t"+MAX_DEPTH);
316 outstream.println("min good kmers: \t"+MIN_KMERS_OVER_MIN_DEPTH);
317 outstream.println("depth percentile: \t"+Tools.format("%.1f", 100*DEPTH_PERCENTILE));
318 outstream.println("remove duplicates:\t"+!KmerCountAbstract.KEEP_DUPLICATE_KMERS);
319 outstream.println("fix spikes: \t"+FIX_SPIKES);
320 if(USE_HISTOGRAM && HIST_LEN>0){
321 outstream.println("histogram length: \t"+(USE_HISTOGRAM ? HIST_LEN : 0));
322 }
323 if(histFile!=null){
324 outstream.println("print zero cov: \t"+PRINT_ZERO_COVERAGE);
325 }
326
327 outstream.println();
328 }
329
330 if(!prefilter && k<32 && cells>(1L<<(2*k))){cells=(1L<<(2*k));}
331 assert(cells>0);
332
333 // KmerCountAbstract.THREADS=Tools.max(THREADS/2, KmerCountAbstract.THREADS); //Seems like 4 is actually optimal...
334
335 FastaReadInputStream.MIN_READ_LEN=k;
336
337 Timer t=new Timer();
338 Timer ht=new Timer();
339 t.start();
340 ht.start();
341 KCountArray kca;
342 KCountArray prefilterArray=null;
343 // outstream.println();
344 ReadCounter rc=new ReadCounter(k, true, false, false, Shared.AMINO_IN);
345 rc.detectStepsize=buildStepsize;
346 if(prefilter){
347 prefilterArray=rc.makeKca(reads1, reads2, extra, 2, precells, prehashes, minq,
348 tablereads, 1, 1, 1, null, 0);
349 outstream.println("Made prefilter: \t"+prefilterArray.toShortString(prehashes));
350 double uf=prefilterArray.usedFraction();
351 if(uf>0.6){
352 outstream.println("Warning: This table is "+(uf>0.995 ? "totally" : uf>0.99 ? "crazy" : uf>0.95 ? "incredibly" : uf>0.9 ? "extremely" : uf>0.8 ? "very" :
353 uf>0.7 ? "fairly" : "somewhat")+" full, which may reduce accuracy for kmers of depth under 3. Ideal load is under 60% used." +
354 "\nFor better accuracy, run on a node with more memory; quality-trim or error-correct reads; " +
355 "or increase the values of the minprob flag to reduce spurious kmers.");
356 }
357 }
358 kca=rc.makeKca(reads1, reads2, extra, cbits, cells, hashes, minq,
359 tablereads, buildpasses, 2, 2, prefilterArray, (prefilterArray==null ? 0 : prefilterArray.maxValue));
360 ht.stop();
361
362 outstream.println("Made hash table: \t"+kca.toShortString(hashes));
363 double uf=kca.usedFraction();
364 if(uf>0.6){
365 outstream.println("Warning: This table is "+(uf>0.995 ? "totally" : uf>0.99 ? "crazy" : uf>0.95 ? "incredibly" : uf>0.9 ? "extremely" : uf>0.8 ? "very" :
366 uf>0.7 ? "fairly" : "somewhat")+" full, which may reduce accuracy. Ideal load is under 60% used." +
367 "\nFor better accuracy, use the 'prefilter' flag; run on a node with more memory; quality-trim or error-correct reads; " +
368 "or increase the values of the minprob flag to reduce spurious kmers. In practice you should still get good normalization results " +
369 "even with loads over 90%, but the histogram and statistics will be off.");
370 }
371
372 long estUnique;
373 outstream.println();
374 if(prefilterArray!=null){
375 int lim1=prefilterArray.maxValue, lim2=prefilterArray.maxValue+1;
376 double a=prefilterArray.estimateUniqueKmers(prehashes);
377 double b=kca.estimateUniqueKmers(hashes, lim2);
378 a=a-b;
379 if(CANONICAL){
380 // a=(a*KCountArray.canonMask)/(KCountArray.canonMask+1);
381 // b=(b*KCountArray.canonMask)/(KCountArray.canonMask+1);
382 }else{
383 a/=2;
384 b/=2;
385 }
386 estUnique=((long)((a+b)));
387 outstream.println("Estimated kmers of depth 1-"+lim1+": \t"+(long)a);
388 outstream.println("Estimated kmers of depth "+lim2+"+ : \t"+(long)b);
389 }else{
390 // double est=kca.cells*(1-Math.pow(1-Math.sqrt(kca.usedFraction()), 1.0/hashes));
391 // double est=kca.cells*(1-Math.pow(1-kca.usedFraction(), 1.0/hashes));
392 double est=kca.estimateUniqueKmers(hashes);
393 // outstream.println("Used cells: "+kca.cellsUsed(1));
394 if(CANONICAL){
395 // est=(est*KCountArray.canonMask)/(KCountArray.canonMask+1);
396 }else{
397 est/=2;
398 }
399 estUnique=((long)((est)));
400
401 }
402 outstream.println("Estimated unique kmers: \t"+estUnique);//+", or "+estUnique+" counting forward kmers only.");
403 // outstream.println("(Includes forward and reverse kmers)");
404 outstream.println();
405 outstream.println("Table creation time:\t\t"+ht);//+" \t"+Tools.format("%.2f", totalBases*1000000.0/(ht.elapsed))+" kb/sec");
406
407 long bases=0;
408
409 ListNum.setDeterministicRandom(deterministic);
410
411 if(reads1!=null && reads1.contains(",") && !new File(reads1).exists()){
412 throw new RuntimeException("This class is not designed to deal with lists of input files.");
413 }else{
414 bases=count(reads1, reads2, kca, k, maxReads, outKeep, overwrite, histFile, estUnique);
415 }
416 printTopology();
417
418 t.stop();
419 outstream.println("\nTotal time: \t\t"+t+" \t"+Tools.format("%.2f", bases*1000000.0/(t.elapsed))+" kb/sec");
420
421 //Close the print stream if it was redirected
422 Shared.closeStream(outstream);
423 }
424
425
426 public static void printTopology(){
427 long total=peaks.get()+spikes.get()+flats.get()+valleys.get()+slopes.get();
428 double mult=100.0/total;
429
430 long sp=spikes.get();
431 long pe=peaks.get();
432 long va=valleys.get();
433 long sl=slopes.get();
434 long fl=flats.get();
435 double dsp=mult*sp;
436 double dpe=mult*pe;
437 double dva=mult*va;
438 double dsl=mult*sl;
439 double dfl=mult*fl;
440
441 System.err.println("\nDepth Topology:\t");
442 System.err.println("Spikes: \t\t\t"+(dsp<10 ? " " : "")+Tools.format("%.3f%% \t%d",dsp,sp));
443 System.err.println("Peaks: \t\t\t"+(dpe<10 ? " " : "")+Tools.format("%.3f%% \t%d",dpe,pe));
444 System.err.println("Valleys: \t\t\t"+(dva<10 ? " " : "")+Tools.format("%.3f%% \t%d",dva,va));
445 System.err.println("Slopes: \t\t\t"+(dsl<10 ? " " : "")+Tools.format("%.3f%% \t%d",dsl,sl));
446 System.err.println("Flats: \t\t\t"+(dfl<10 ? " " : "")+Tools.format("%.3f%% \t%d",dfl,fl));
447 }
448
449
450 public static long count(String in1, String in2, KCountArray kca, int k, long maxReads,
451 String outKeep, boolean overwrite, String histFile, long estUnique) {
452 final ConcurrentReadInputStream cris;
453 {
454 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
455 FileFormat ff2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true);
456 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
457 if(verbose){System.err.println("Started cris");}
458 cris.start(); //4567
459 }
460 boolean paired=cris.paired();
461 if(verbose){System.err.println("Paired: "+paired);}
462
463 ConcurrentReadOutputStream rosKeep=null;
464 if(outKeep!=null){
465 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
466
467 String out1=outKeep.replaceFirst("#", "1");
468 String out2=null;
469
470 if(cris.paired()){
471 if(outKeep.contains("#")){
472 out2=outKeep.replaceFirst("#", "2");
473 }else{
474 outstream.println("Writing interleaved.");
475 }
476 }
477
478 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
479 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
480
481 // assert(false) : out1+", "+out2;
482
483 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, "attachment", true, overwrite, append, ordered);
484 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, "attachment", true, overwrite, append, ordered);
485 rosKeep=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
486 }
487
488 if(rosKeep!=null){
489 rosKeep.start();
490 outstream.println("Started output threads.");
491 }
492
493 long bases=downsample(cris, kca, k, maxReads, rosKeep, histFile, overwrite, estUnique);
494
495 ReadWrite.closeStreams(cris, rosKeep);
496 if(verbose){System.err.println("Closed streams");}
497
498 return bases;
499 }
500
501
502
503 public static long downsample(ConcurrentReadInputStream cris, KCountArray kca, int k, long maxReads, ConcurrentReadOutputStream rosKeep,
504 String histFile, boolean overwrite, long estUnique) {
505 Timer tdetect=new Timer();
506 tdetect.start();
507
508 long totalBases=0;
509 long totalReads=0;
510 long basesKept=0;
511 long readsKept=0;
512 long basesTossed=0;
513 long readsTossed=0;
514
515 // assert(false) : THREADS;
516 ProcessThread[] pta=new ProcessThread[THREADS];
517 for(int i=0; i<pta.length; i++){
518 pta[i]=new ProcessThread(cris, kca, k, rosKeep);
519 pta[i].start();
520 }
521
522 for(int i=0; i<pta.length; i++){
523 ProcessThread ct=pta[i];
524 synchronized(ct){
525 while(ct.getState()!=State.TERMINATED){
526 try {
527 ct.join(1000);
528 } catch (InterruptedException e) {
529 // TODO Auto-generated catch block
530 e.printStackTrace();
531 }
532 }
533 totalBases+=ct.totalBases;
534 totalReads+=ct.totalReads;
535 basesKept+=ct.basesKept;
536 readsKept+=ct.readsKept;
537 basesTossed+=ct.basesTossed;
538 readsTossed+=ct.readsTossed;
539
540 for(int j=0; j<ct.hist.length; j++){
541 histogram_total.addAndGet(j, ct.hist[j]);
542 }
543 }
544 }
545
546 if(!ZERO_BIN && histogram_total!=null && histogram_total.length()>1){
547 histogram_total.addAndGet(1, histogram_total.get(0));
548 histogram_total.set(0, 0);
549 }
550
551 // outstream.println();
552 tdetect.stop();
553 outstream.println("Table read time: \t\t"+tdetect+" \t"+Tools.format("%.2f", totalBases*1000000.0/(tdetect.elapsed))+" kb/sec");
554
555 {
556 String pad="";
557 String s=""+totalReads;
558 while(pad.length()+s.length()<9){pad+=" ";}
559 outstream.println("Total reads in: \t\t"+totalReads+pad+Tools.format("\t(%.3f%% Kept)", (readsKept*100.0/totalReads)));
560 s=""+totalBases;
561 while(pad.length()+s.length()<9){pad+=" ";}
562 outstream.println("Total bases in: \t\t"+totalBases+pad+Tools.format("\t(%.3f%% Kept)", (basesKept*100.0/totalBases)));
563 }
564 // outstream.println();
565 if(histogram_total!=null){
566 TextStreamWriter tswh=null;
567 StringBuilder sb=new StringBuilder(100);
568 if(USE_HISTOGRAM){
569 tswh=new TextStreamWriter(histFile, overwrite, false, false);
570 tswh.start();
571 tswh.print("#Depth\tRaw_Count\tUnique_Kmers\n");
572 }
573 int lim=(int)(HIST_LEN_PRINT-1);
574 long remaining=Tools.sum(histogram_total);
575 long sumRaw1=0;
576 long sumRaw2=0;
577 long sum1=0;
578 long sum2=0;
579 long sumsquare=0;
580 for(int i=0; i<lim; i++){
581 long x=histogram_total.get(i);
582 long y=((x+i/2)/(i<1 ? 1 : i)); //x+i/2 rounds to compensate for colliding kmers being put in an overly high bin
583 // long y=((x)/(i<1 ? 1 : i));
584 sumRaw1+=x;
585 sum1+=y;
586 sumsquare+=(x*Tools.max(1, i));
587 if(tswh!=null){
588 if(PRINT_ZERO_COVERAGE /*|| x>0*/ || y>0){
589 sb.append(i).append('\t');
590 sb.append(x).append('\t');
591 sb.append(y).append('\n');
592 }
593 tswh.print(sb.toString());
594 sb.setLength(0);
595 }
596 if(sumRaw1>=remaining){break;} //Stop once there is no more coverage, even if PRINT_ZERO_COVERAGE is not set.
597 }
598 for(int i=lim; i<histogram_total.length(); i++){
599 long x=histogram_total.get(i);
600 sumRaw2+=x;
601 long y=((x+i/2)/(i<1 ? 1 : i)); //x+i/2 rounds to compensate for colliding kmers being put in an overly high bin
602 // long y=((x)/(i<1 ? 1 : i));
603 sum2+=y;
604 }
605 if(tswh!=null){
606 if(sumRaw2>0 || sum2>0){
607 sb.append(lim).append('\t');
608 sb.append(sumRaw2).append('\t');
609 sb.append(sum2).append('\n');
610 }
611 tswh.print(sb.toString());
612 tswh.poison();
613 tswh.waitForFinish();
614 outstream.println("Wrote histogram to "+histFile);
615 }
616
617 long histCount=Tools.sum(histogram_total); //Total number of kmers counted
618 long halfCount=(histCount+1)/2;
619 double histCountU=0; //Unique kmers counted
620 long temp1=0;
621 double temp2=0;
622 int median_all=-1;
623 int median_unique=-1;
624 for(int i=0; i<histogram_total.length(); i++){
625 long x=histogram_total.get(i);
626 temp1+=x;
627 if(temp1>=halfCount && median_all<0){median_all=i;}
628 // histSum+=(x*(double)i);
629 histCountU+=(x/(double)Tools.max(1, i));
630 }
631 double halfCount2=(histCountU)/2;
632 for(int i=0; i<histogram_total.length(); i++){
633 long x=histogram_total.get(i);
634 temp2+=(x/Tools.max(i, 1.0));
635 if(temp2>=halfCount2 && median_unique<0){
636 median_unique=i;
637 break;
638 }
639 }
640 if(median_all<0){median_all=0;}
641 double avg_all=sumsquare/(double)histCount;
642 double avg_unique=histCount/histCountU;
643 double stdev_unique=Tools.standardDeviationHistogramKmer(histogram_total);
644 double stdev_all=Tools.standardDeviationHistogram(histogram_total);
645 outstream.println("Total kmers counted: \t"+(sumRaw1+sumRaw2));
646
647 double uniqueC=((sum1+sum2)*100.0/(sumRaw1+sumRaw2));
648 double uniqueE=((estUnique)*100.0/(sumRaw1+sumRaw2));
649 double uniqueM=Tools.max(uniqueC, uniqueE);
650 outstream.println("Total unique kmer count: \t"+(sum1+sum2));
651 if(CANONICAL){outstream.println("Includes forward kmers only.");}
652 outstream.println("The unique kmer estimate can be more accurate than the unique count, if the tables are very full.");
653 outstream.println("The most accurate value is the greater of the two.");
654 outstream.println();
655
656 outstream.println("Percent unique: \t"+(uniqueM<10 ? " " : "")+Tools.format("%.2f%%", uniqueM));
657
658 outstream.println("Depth average: \t"+Tools.format("%.2f\t(unique kmers)", avg_unique));
659 outstream.println("Depth median: \t"+Tools.format("%d\t(unique kmers)", median_unique));
660 outstream.println("Depth standard deviation: \t"+Tools.format("%.2f\t(unique kmers)", stdev_unique));
661
662 outstream.println("\nDepth average: \t"+Tools.format("%.2f\t(all kmers)", avg_all));
663 outstream.println("Depth median: \t"+Tools.format("%d\t(all kmers)", median_all));
664 outstream.println("Depth standard deviation: \t"+Tools.format("%.2f\t(all kmers)", stdev_all));
665 }
666
667 return totalBases;
668 }
669
670
671
672 /**
673 * Locates and fixes spikes in a coverage profile (potentially) caused by false positives in a bloom filter.
674 * Theory: If a high-count kmer is adjacent on both sides to low-count kmers, it may be a false positive.
675 * It could either be reduced to the max of the two flanking points or examined in more detail.
676 * @param array An array of kmer counts for adjacent kmers in a read.
677 */
678 private static void fixSpikes(int[] array){
679
680 for(int i=1; i<array.length-1; i++){
681 long a=Tools.max(1, array[i-1]);
682 int b=array[i];
683 long c=Tools.max(1, array[i+1]);
684 if(b>1 && b>a && b>c){
685 //peak
686 if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
687 //spike
688 array[i]=(int)Tools.max(a, c);
689 }
690 }
691 }
692 }
693 private static void fixSpikes(int[] array, long[] kmers, KCountArray kca, int k){
694 if(array.length<3){return;}
695 if(array[1]-array[0]>1){
696 array[0]=kca.readPrecise(kmers[0], k, CANONICAL);
697 }
698 if(array[array.length-1]-array[array.length-2]>1){
699 array[array.length-1]=kca.readPrecise(kmers[array.length-1], k, CANONICAL);
700 }
701
702 for(int i=1; i<array.length-1; i++){
703 int b=array[i];
704 if(b>1){
705 long a=Tools.max(1, array[i-1]);
706 long c=Tools.max(1, array[i+1]);
707 long key=kmers[i];
708
709 if(b>a && b>c){
710 //peak
711 if(b<6 || b>a+1 || b>c+1){
712 array[i]=kca.readPreciseMin(key, k, CANONICAL);
713 }
714 // if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
715 // //spike
716 // int b1=(int)((a+c)/2);
717 // int b2=kca.readLeft(key, k, CANONICAL);
718 // int b3=kca.readRight(key, k, CANONICAL);
719 // array[i]=Tools.min(b, b1, b2, b3);
720 // }
721 // else
722 // {
723 //// array[i]=kca.readPreciseMin(key, k, CANONICAL);
724 // }
725 }
726 // else
727 // if(Tools.max(ada, adc)>=Tools.max(2, Tools.min((int)a, b, (int)c)/4)){
728 // array[i]=kca.readPrecise(key, k, CANONICAL);
729 // }
730 // else
731 // if(b>a+1 || b>c+1){
732 // //steep
733 // array[i]=kca.readPrecise(key, k, CANONICAL);
734 // }
735 }
736 }
737 }
738
739
740 private static void analyzeSpikes(int[] array, int width){
741 if(array.length<3){return;}
742 int peakcount=0, valleycount=0, spikecount=0, flatcount=0, slopecount=0;
743 for(int i=1; i<array.length-1; i++){
744 long a=array[i-1];
745 int b=array[i];
746 long c=array[i+1];
747 if(b>a && b>c){
748 peakcount++;
749 if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
750 spikecount++;
751 }
752 }else if(b<a && b<c){
753 valleycount++;
754 }else if(b==a && b==c){
755 flatcount++;
756 }else{
757 slopecount++;
758 }
759 }
760 if(peakcount>0){peaks.addAndGet(peakcount);}
761 if(valleycount>0){valleys.addAndGet(valleycount);}
762 if(spikecount>0){spikes.addAndGet(spikecount);}
763 if(flatcount>0){flats.addAndGet(flatcount);}
764 if(slopecount>0){slopes.addAndGet(slopecount);}
765 }
766
767 public static int[] generateCoverage(Read r, KCountArray kca, int k, int[] out, long[] kmers) {
768 if(k>31){return generateCoverageLong(r, kca, k, out);}
769 if(r==null || r.bases==null || r.length()<k){return new int[] {0};}
770
771 final int kbits=2*k;
772 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
773
774 if(r.bases==null || r.length()<k){return null;} //Read is too short to detect errors
775
776 int len=0;
777 long kmer=0;
778 final byte[] bases=r.bases;
779 final int arraylen=r.length()-k+1;
780 if(out==null || out.length!=arraylen){out=new int[arraylen];}
781 Arrays.fill(out, -1);
782 if(FIX_SPIKES){
783 if(kmers==null || kmers.length!=arraylen){kmers=new long[arraylen];}
784 Arrays.fill(kmers, -1);
785 }
786
787 for(int i=0; i<bases.length; i++){
788 byte b=bases[i];
789 int x=AminoAcid.baseToNumber[b];
790 if(x<0){
791 len=0;
792 kmer=0;
793 }else{
794 kmer=((kmer<<2)|x)&mask;
795 len++;
796
797 if(len>=k){
798 // int count=kca.readPrecise(kmer, k, CANONICAL);
799 int count=kca.read(kmer, k, CANONICAL);
800 out[i-k+1]=count;
801 if(kmers!=null){kmers[i-k+1]=kmer;}
802 }
803 }
804 }
805
806 if(FIX_SPIKES){fixSpikes(out, kmers, kca, k);}
807 // fixSpikes(out, 1);
808
809 analyzeSpikes(out, 1);
810 return out;
811 }
812
813 public static int[] generateCoverageLong(Read r, KCountArray kca, int k, int[] out) {
814 assert(k>31);
815 if(r==null || r.bases==null || r.length()<k){return new int[] {0};}
816
817 if(r.bases==null || r.length()<k){return null;} //Read is too short to detect errors
818
819 int len=0;
820 long kmer=0;
821 final byte[] bases=r.bases;
822
823 final int arraylen=r.length()-k+1;
824 if(out==null || out.length!=arraylen){out=new int[arraylen];}
825 Arrays.fill(out, -1);
826
827 int tailshift=k%32;
828 int tailshiftbits=tailshift*2;
829
830
831 for(int i=0; i<bases.length; i++){
832 byte b=bases[i];
833 int x=AminoAcid.baseToNumber[b];
834 if(x<0){
835 len=0;
836 kmer=0;
837 }else{
838 kmer=Long.rotateLeft(kmer, 2);
839 kmer=kmer^x;
840 len++;
841 if(len>k){
842 long x2=AminoAcid.baseToNumber[bases[i-k]];
843 kmer=kmer^(x2<<tailshiftbits);
844 }
845
846 if(len>=k){
847 int count=kca.read(kmer);
848 out[i-k+1]=count;
849 }
850 }
851 }
852
853 fixSpikes(out);
854
855 analyzeSpikes(out, 1);
856 return out;
857 }
858
859
860 private static class ProcessThread extends Thread{
861
862 ProcessThread(ConcurrentReadInputStream cris_, KCountArray kca_, int k_, ConcurrentReadOutputStream rosk_){
863 cris=cris_;
864 kca=kca_;
865 k=k_;
866 rosk=rosk_;
867 }
868
869 @Override
870 public void run(){
871 countInThread();
872 }
873
874 void countInThread() {
875
876 ListNum<Read> ln=cris.nextList();
877 ArrayList<Read> reads=(ln!=null ? ln.list : null);
878
879 final ArrayList<Read> keep=new ArrayList<Read>(Shared.bufferLen());
880
881 int[] cov1=null;
882 long[] kmers1=null;
883
884 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
885 for(int rnum=0; rnum<reads.size(); rnum++){
886 Read r=reads.get(rnum);
887 Read r2=r.mate;
888 assert(r!=r2);
889
890 int depth=-1;
891
892 int readcount=0;
893 int basecount=0;
894
895 int min=0;
896 int max=0;
897 int[] cov=null;
898 long[] kmers=null;
899
900 if(r!=null && r.bases!=null){
901 readcount++;
902 basecount+=r.length();
903 if(r.length()>=k){
904 if(verbose){outstream.println();}
905 if(FIX_SPIKES && k<32){
906 final int arraylen=r.length()-k+1;
907 if(kmers1==null || kmers1.length!=arraylen){kmers1=new long[arraylen];}
908 kmers=kmers1;
909 }
910 cov=getSortedCoverageAndIncrementHistogram(r, cov1, kmers1);
911 if(cov!=null){;
912 int i=cov.length-1;
913 while(i>=0 && cov[i]<MIN_DEPTH){i--;}
914 if(i+1>=MIN_KMERS_OVER_MIN_DEPTH){depth=cov[(int)(i*(1-DEPTH_PERCENTILE))];}
915 cov1=cov;
916 min=cov[cov.length-1];
917 max=cov[(int)(cov.length*0.05f)];
918 }
919 }
920 }
921
922
923 totalReads+=readcount;
924 totalBases+=basecount;
925 if(max>TARGET_DEPTH && max>2*min){
926 readsKept+=readcount;
927 basesKept+=basecount;
928 StringBuilder sb=new StringBuilder();
929 sb.append(cov[0]);
930 for(int i=1; i<cov.length; i++){
931 sb.append('\t');
932 sb.append(cov[i]);
933 }
934 r.obj=sb.toString();
935 keep.add(r);
936 }else{
937 readsTossed+=readcount;
938 basesTossed+=basecount;
939 }
940 }
941
942
943 if(rosk!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
944 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
945 rosk.add(keep, ln.id);
946 }
947 keep.clear();
948
949 cris.returnList(ln);
950 //System.err.println("fetching list");
951 ln=cris.nextList();
952 reads=(ln!=null ? ln.list : null);
953 }
954 if(verbose){System.err.println("Finished reading");}
955 cris.returnList(ln);
956 if(verbose){System.err.println("Returned list");}
957 }
958
959 private final int[] getSortedCoverageAndIncrementHistogram(Read r, int[] cov, long[] kmers){
960 assert(r!=null && r.bases!=null && r.length()>=k) : r;
961 cov=generateCoverage(r, kca, k, cov, kmers);
962 if(cov!=null){
963 Arrays.sort(cov);
964 Tools.reverseInPlace(cov);
965 incrementHistogramSorted(cov);
966 }
967 return cov;
968 }
969
970 private final void incrementHistogramSorted(int[] cov){
971 if(hist==null || cov==null || cov.length==0){return;}
972
973 // outstream.println(Arrays.toString(cov));
974
975 int last=cov[0];
976 long sum=0;
977 // long sum2=0;
978 for(int x : cov){
979 // outstream.println("Processing "+x);
980 if(x<0){break;}
981 int y=Tools.min(x, HIST_LEN-1);
982 if(y==last){sum++;}
983 else if(sum>0){
984 // outstream.println("Incrementing "+last+" by "+sum);
985 // sum2+=sum;
986 if(last<hist.length){hist[last]+=sum;}
987 else{histogram_total.addAndGet(last, sum);}
988 sum=1;
989 }
990 last=y;
991 }
992 // outstream.println("Ended loop");
993 if(sum>0){
994 // outstream.println("Incrementing "+last+" by "+sum);
995 // sum2+=sum;
996 if(last<hist.length){hist[last]+=sum;}
997 else{histogram_total.addAndGet(last, sum);}
998 }
999 // assert(sum2==cov.length) : sum2+", "+cov.length+", "+last+", "+sum;
1000 }
1001
1002 private final ConcurrentReadInputStream cris;
1003 private final KCountArray kca;
1004 private final int k;
1005 /** Stream for kept reads */
1006 private final ConcurrentReadOutputStream rosk;
1007 public final long[] hist=new long[THREAD_HIST_LEN];//(USE_HISTOGRAM ? new long[HIST_LEN] : null);
1008
1009 private long totalBases=0;
1010 private long totalReads=0;
1011
1012 public long readsKept=0;
1013 public long readsTossed=0;
1014 public long basesKept=0;
1015 public long basesTossed=0;
1016 }
1017
1018 public static PrintStream outstream=System.err;
1019
1020 public static int THREAD_HIST_LEN=1<<12;
1021 public static int HIST_LEN=1<<20;
1022 public static long HIST_LEN_PRINT=HIST_LEN;
1023 public static boolean USE_HISTOGRAM=false;
1024 public static boolean PRINT_ZERO_COVERAGE=false;
1025 public static AtomicLongArray histogram_total;
1026
1027 private static int THREADS=8;
1028 private static boolean verbose=false;
1029
1030
1031 private static int TARGET_DEPTH=50;
1032 private static int MAX_DEPTH=-1;
1033 private static int MIN_DEPTH=3;
1034 private static int MIN_KMERS_OVER_MIN_DEPTH=10;
1035 private static float DEPTH_PERCENTILE=0.5f;
1036
1037
1038 public static boolean CANONICAL=true;
1039 public static boolean ZERO_BIN=false;
1040 public static boolean FIX_SPIKES=true;
1041 public static boolean ordered=false;
1042 public static boolean overwrite=true;
1043 public static boolean append=false;
1044 public static boolean prefilter=false;
1045
1046 public static AtomicLong peaks=new AtomicLong();
1047 public static AtomicLong spikes=new AtomicLong();
1048 public static AtomicLong flats=new AtomicLong();
1049 public static AtomicLong valleys=new AtomicLong();
1050 public static AtomicLong slopes=new AtomicLong();
1051 }