Debian Codegraph @

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