Debian Codegraph @

current/jgi/KmerCountExact.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5
6 import assemble.Shaver;
7 import assemble.Tadpole;
8 import bloom.KmerCountAbstract;
9 import fileIO.ByteFile;
10 import fileIO.ByteStreamWriter;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import kmer.AbstractKmerTable;
14 import kmer.AbstractKmerTableSet;
15 import kmer.DumpThread;
16 import kmer.HashArray1D;
17 import kmer.HashForest;
18 import kmer.KmerNode;
19 import kmer.KmerNode1D;
20 import kmer.KmerTableSet;
21 import kmer.Walker;
22 import shared.Parse;
23 import shared.Parser;
24 import shared.PreParser;
25 import shared.Shared;
26 import shared.Timer;
27 import shared.Tools;
28 import sketch.Sketch;
29 import sketch.SketchObject;
30 import sketch.SketchTool;
31 import stream.FastaReadInputStream;
32 import tracker.ReadStats;
33 import ukmer.AbstractKmerTableU;
34 import ukmer.HashArrayU1D;
35 import ukmer.HashForestU;
36 import ukmer.Kmer;
37 import ukmer.KmerNodeU;
38 import ukmer.KmerNodeU1D;
39 import ukmer.KmerTableSetU;
40 import ukmer.WalkerU;
41
42 /**
43 * @author Brian Bushnell
44 * @date Nov 22, 2013
45 *
46 */
47 public class KmerCountExact {
48
49 /**
50 * Code entrance from the command line.
51 * @param args Command line arguments
52 */
53 public static void main(String[] args){
54 Timer t=new Timer(), t2=new Timer();
55 t.start();
56 t2.start();
57
58 //Create a new CountKmersExact instance
59 KmerCountExact x=new KmerCountExact(args);
60 t2.stop();
61 // outstream.println("Initialization Time: \t"+t2);
62
63 ///And run it
64 x.process(t);
65
66 //Close the print stream if it was redirected
67 Shared.closeStream(outstream);
68 }
69
70 /**
71 * Constructor.
72 * @param args Command line arguments
73 */
74 public KmerCountExact(String[] args){
75
76 {//Preparse block for help, config files, and outstream
77 PreParser pp=new PreParser(args, getClass(), false);
78 args=pp.args;
79 outstream=pp.outstream;
80 }
81
82 /* Set global defaults */
83 ReadWrite.ZIPLEVEL=2;
84 ReadWrite.USE_UNPIGZ=true;
85
86 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
87 ByteFile.FORCE_MODE_BF2=true;
88 }
89
90 /* Initialize local variables with defaults */
91 boolean useForest_=false, useTable_=false, useArray_=true;
92 Parser parser=new Parser();
93
94 /* Parse arguments */
95 for(int i=0; i<args.length; i++){
96
97 final String arg=args[i];
98 String[] split=arg.split("=");
99 String a=split[0].toLowerCase();
100 String b=split.length>1 ? split[1] : null;
101
102 if(Parser.parseCommonStatic(arg, a, b)){
103 //do nothing
104 }else if(Parser.parseZip(arg, a, b)){
105 //do nothing
106 }else if(Parser.parseQuality(arg, a, b)){
107 //do nothing
108 }else if(Parser.parseFasta(arg, a, b)){
109 //do nothing
110 }else if(parser.parseInterleaved(arg, a, b)){
111 //do nothing
112 }else if(parser.parseTrim(arg, a, b)){
113 //do nothing
114 }else if(a.equals("out") || a.equals("out1") || a.equals("outkmers") || a.equals("outk") || a.equals("dump")){
115 outKmers=b;
116 }else if(a.equals("ref")){
117 ref=b;
118 }else if(a.equals("intersection") || a.equals("refout") || a.equals("outref")){
119 intersectionFile=b;
120 }else if(a.equals("mincounttodump") || a.equals("mindump") || a.equals("mincount")){
121 minToDump=Integer.parseInt(b);
122 }else if(a.equals("maxcounttodump") || a.equals("maxdump") || a.equals("maxcount")){
123 maxToDump=Integer.parseInt(b);
124 }else if(a.equals("dumpthreads")){
125 DumpThread.NUM_THREADS=Integer.parseInt(b);
126 }else if(a.equals("hist") || a.equals("khist")){
127 outHist=b;
128 }else if(a.equals("append") || a.equals("app")){
129 append=ReadStats.append=Parse.parseBoolean(b);
130 }else if(a.equals("overwrite") || a.equals("ow")){
131 overwrite=Parse.parseBoolean(b);
132 }else if(a.equals("forest")){
133 useForest_=Parse.parseBoolean(b);
134 if(useForest_){useTable_=useArray_=false;}
135 assert(false) : a+" is deprecated.";
136 }else if(a.equals("table")){
137 useTable_=Parse.parseBoolean(b);
138 if(useTable_){useForest_=useArray_=false;}
139 assert(false) : a+" is deprecated.";
140 }else if(a.equals("array")){
141 useArray_=Parse.parseBoolean(b);
142 if(useArray_){useTable_=useForest_=false;}
143 assert(false) : a+" is deprecated.";
144 }else if(a.equals("threads") || a.equals("t")){
145 THREADS=(b==null || b.equalsIgnoreCase("auto") ? Shared.threads() : Integer.parseInt(b));
146 }else if(a.equals("verbose")){
147 assert(false) : "Verbose flag is currently static final; must be recompiled to change.";
148 // verbose=Parse.parseBoolean(b);
149 }else if(a.equals("shave")){
150 shave=Parse.parseBoolean(b);
151 }else if(a.equals("rinse")){
152 rinse=Parse.parseBoolean(b);
153 }else if(a.equals("shavedepth")){
154 shaveDepth=Integer.parseInt(b);
155 }else if(a.equals("histcolumns")){
156 histColumns=Integer.parseInt(b);
157 }else if(a.equals("histmax") || a.equals("histlen") || a.equals("khistlen") || a.equals("histsize") || a.equals("khistsize")){
158 histMax=Parse.parseIntKMG(b);
159 }else if(a.equals("refmax")){
160 refMax=Parse.parseIntKMG(b);
161 }else if(a.equals("histheader")){
162 histHeader=Parse.parseBoolean(b);
163 }else if(a.equals("nzo") || a.equals("nonzeroonly")){
164 histZeros=!Parse.parseBoolean(b);
165 }else if(a.equals("gchist")){
166 gcHist=Parse.parseBoolean(b);
167 }else if(a.equals("logscale")){
168 doLogScale=Parse.parseBoolean(b);
169 }else if(a.equals("logwidth")){
170 logWidth=Double.parseDouble(b);
171 }else if(a.equals("logpasses")){
172 logPasses=Integer.parseInt(b);
173 }
174
175 else if(a.equals("minheight")){
176 minHeight=Long.parseLong(b);
177 }else if(a.equals("minvolume")){
178 minVolume=Long.parseLong(b);
179 }else if(a.equals("minwidth")){
180 minWidth=Integer.parseInt(b);
181 }else if(a.equals("minpeak")){
182 minPeak=Integer.parseInt(b);
183 }else if(a.equals("maxpeak")){
184 maxPeak=Integer.parseInt(b);
185 }else if(a.equals("maxpeakcount") || a.equals("maxpc") || a.equals("maxpeaks")){
186 maxPeakCount=Integer.parseInt(b);
187 }else if(a.equals("ploidy")){
188 ploidy=Integer.parseInt(b);
189 }else if(a.equals("peaks") || a.equals("peaksout")){
190 outPeaks=b;
191 }else if(a.equals("smooth") || a.equals("smoothe")){
192 smoothKhist=smoothPeaks=Parse.parseBoolean(b);
193 }else if(a.equals("smoothkhist") || a.equals("smoothhist")){
194 smoothKhist=Parse.parseBoolean(b);
195 }else if(a.equals("smoothpeaks")){
196 smoothPeaks=Parse.parseBoolean(b);
197 }else if(a.equals("smoothradius") || a.equals("smootheradius")){
198 smoothRadius=Integer.parseInt(b);
199 }else if(a.equals("maxradius")){
200 CallPeaks.maxRadius=Integer.parseInt(b);
201 }else if(a.equals("progressivemult")){
202 CallPeaks.progressiveMult=Float.parseFloat(b);
203 }
204
205 else if(KmerTableSet.isValidArgument(a)){
206 //Do nothing
207 }else if(a.equals("decimals")){
208 decimals=Integer.parseInt(b);
209 }
210
211 else if(a.equals("sketchmode")){
212 KmerCountAbstract.SKETCH_MODE=Parse.parseBoolean(b);
213 }else if(a.equals("sketch")){
214 sketchPath=b;
215 }else if(a.equals("sketchlen") || a.equals("sketchlength") || a.equals("sketchsize")){
216 sketchLength=Parse.parseIntKMG(b);
217 }else if(a.equals("sketchname")){
218 sketchName=b;
219 }else if(a.equals("sketchid")){
220 sketchID=Integer.parseInt(b);
221 }else if(SketchObject.parseSketchFlags(arg, a, b)){
222 //Do nothing
223 }
224
225 else{
226 throw new RuntimeException("Unknown parameter "+args[i]);
227 }
228 }
229
230 if(sketchPath!=null){
231 SketchObject.postParse();
232 }
233
234 {//Process parser fields
235 Parser.processQuality();
236 }
237
238 /* Adjust I/O settings and filenames */
239
240 assert(FastaReadInputStream.settingsOK());
241
242 if(outKmers!=null && !Tools.canWrite(outKmers, overwrite)){throw new RuntimeException("Output file "+outKmers+" already exists, and overwrite="+overwrite);}
243 if(sketchPath!=null && !Tools.canWrite(sketchPath, overwrite)){throw new RuntimeException("Output file "+sketchPath+" already exists, and overwrite="+overwrite);}
244
245 assert(THREADS>0);
246
247 if(DISPLAY_PROGRESS){
248 outstream.println("Initial:");
249 Shared.printMemory();
250 outstream.println();
251 }
252
253 // final int tableType=(useForest ? AbstractKmerTable.FOREST1D : useTable ? AbstractKmerTable.TABLE : useArray ? AbstractKmerTable.ARRAY1D : 0);
254 k=Tadpole.preparseK(args);
255
256 if(k<=31){//TODO: 123 add "false" to the clause to force KmerTableSetU usage.
257 tables=new KmerTableSet(args, 12);
258 if(ref!=null){tables2=new KmerTableSet(new String[] {"k="+k, "in="+ref, "rcomp="+tables.rcomp()}, 12);}
259 }else{
260 tables=new KmerTableSetU(args, 0);
261 if(ref!=null){tables2=new KmerTableSetU(new String[] {"k="+k, "in="+ref, "rcomp="+tables.rcomp()}, 0);}
262 }
263 if(tables.prefilter){tables.minProbMain=false;}
264
265 ffSketch=FileFormat.testOutput(sketchPath, FileFormat.TXT, null, true, overwrite, append, false);
266
267
268 // shift=bitsPerBase*k;
269 // shift2=shift-bitsPerBase;
270 // mask=(shift>63 ? -1L : ~((-1L)<<shift));
271 // kmask=lengthMasks[k];
272 }
273
274
275 /*--------------------------------------------------------------*/
276 /*---------------- Outer Methods ----------------*/
277 /*--------------------------------------------------------------*/
278
279
280 public void process(Timer t){
281
282 /* Check for output file collisions */
283 Tools.testOutputFiles(overwrite, append, false, outKmers, outHist, outPeaks, sketchPath);
284
285 /* Count kmers */
286 process2();
287
288 makeKhistAndPeaks();
289
290 if(ffSketch!=null){
291 makeSketch();
292 }
293
294 /* Stop timer and calculate speed statistics */
295 t.stop();
296
297 /* Throw an exception if errors were detected */
298 if(errorState){
299 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
300 }
301 }
302
303
304 public void process2(){
305
306 /* Start phase timer */
307 Timer t=new Timer();
308
309 AbstractKmerTableSet.DISPLAY_STATS=false;
310
311 /* Fill tables with kmers */
312 tables.process(t);
313
314 if(DISPLAY_PROGRESS){
315 outstream.println("After loading:");
316 Shared.printMemory();
317 outstream.println();
318 }
319
320 errorState|=tables.errorState;
321
322 t.stop();
323 outstream.println("Input: \t"+tables.readsIn+" reads \t\t"+tables.basesIn+" bases.");
324
325 if(ref!=null){
326 t.start();
327 processRef();
328 t.stop();
329 // assert(false) : "Display stuff";
330 }
331
332 if(tables.qtrimLeft() || tables.qtrimRight()){
333 outstream.println("QTrimmed: \t"+tables.readsTrimmed+" reads ("+Tools.format("%.2f",tables.readsTrimmed*100.0/tables.readsIn)+"%) \t"+
334 tables.basesTrimmed+" bases ("+Tools.format("%.2f",tables.basesTrimmed*100.0/tables.basesIn)+"%)");
335 }
336 if(tables.minAvgQuality()>0){
337 outstream.println("Low quality discards: \t"+tables.lowqReads+" reads ("+Tools.format("%.2f",tables.lowqReads*100.0/tables.readsIn)+"%) \t"+
338 tables.lowqBases+" bases ("+Tools.format("%.2f",tables.lowqBases*100.0/tables.basesIn)+"%)");
339 }
340
341 if(shave || rinse){
342 kmersRemoved=shave(shave, rinse, shaveDepth);
343 }
344
345 outstream.println("\nFor K="+tables.kbig());
346 outstream.println("Unique Kmers: \t"+tables.kmersLoaded);
347 if(shave || rinse){
348 outstream.println("After Shaving: \t"+(tables.kmersLoaded-kmersRemoved));
349 }
350
351 averageCount=tables.kmersIn*1.0/tables.kmersLoaded;
352 double actualDepth=Tools.observedToActualCoverage(averageCount);
353 double readDepth=(actualDepth*tables.basesIn)/(tables.kmersIn);
354
355 outstream.println("Average Kmer Count: \t"+Tools.format("%."+decimals+"f", averageCount));
356 outstream.println("Estimated Kmer Depth: \t"+Tools.format("%."+decimals+"f", actualDepth));
357 outstream.println("Estimated Read Depth: \t"+Tools.format("%."+decimals+"f", readDepth));
358 outstream.println();
359
360 outstream.println("Load Time: \t"+t);
361 }
362
363 /*--------------------------------------------------------------*/
364 /*---------------- Ref Processing ----------------*/
365 /*--------------------------------------------------------------*/
366
367 void processRef(){
368 long[][] counts=intersectionST(tables, tables2, histMax, refMax, bidirectional);
369 ByteStreamWriter bsw=new ByteStreamWriter(intersectionFile, overwrite, append, false);
370 bsw.start();
371 bsw.print("#Depth");
372 for(int i=0; i<counts[0].length; i++){
373 bsw.print("\t"+i+"-Copy");
374 }
375 bsw.nl();
376
377 int maxDepth=counts.length-1;
378 while(maxDepth>0 && shared.Vector.sum(counts[maxDepth])<1){
379 maxDepth--;
380 }
381
382 for(int depth=0; depth<=maxDepth; depth++){
383 if(histZeros || shared.Vector.sum(counts[depth])>0){
384 bsw.print(depth);
385 for(int copy=0; copy<counts[depth].length; copy++){
386 bsw.tab();
387 bsw.print(counts[depth][copy]);
388 }
389 bsw.nl();
390 }
391 }
392 bsw.poisonAndWait();
393 }
394
395 //qualities asdkjasdkasdladeudns,u384Gnah&dhhsd
396 public static long[][] intersectionST_first(final AbstractKmerTableSet tables,
397 final AbstractKmerTableSet tables2, final int xMax, final int yMax, final boolean bidirectional){
398
399 long[][] counts=new long[xMax+1][yMax+1];
400
401 Timer t=new Timer();
402 tables2.process(t);
403 if(tables.getClass()==KmerTableSet.class){
404
405 KmerTableSet ktsRead=(KmerTableSet)tables;
406 KmerTableSet ktsRef=(KmerTableSet)tables2;
407 for(AbstractKmerTable akt : ktsRead.tables()){
408 assert(akt.getClass()==HashArray1D.class);
409 HashArray1D ha=(HashArray1D)akt;
410 long[] kmers=ha.array();
411 int[] values=ha.values();
412 for(int i=0; i<kmers.length; i++){
413 final int readCount=Tools.mid(0, values[i], xMax);
414 if(readCount>0){
415 final long kmer=kmers[i];
416 final int refCount=Tools.mid(0, ktsRef.getCount(kmer), yMax);
417 counts[readCount][refCount]++;
418 }
419 }
420 HashForest victims=ha.victims();
421 for(KmerNode node : victims){
422 KmerNode1D n=(KmerNode1D)node;
423 final int readCount=Tools.mid(0, n.value(), xMax);
424 if(readCount>0){
425 final long kmer=n.pivot();
426 final int refCount=Tools.mid(0, ktsRef.getCount(kmer), yMax);
427 counts[readCount][refCount]++;
428 }
429 }
430 }
431
432 if(bidirectional){
433 for(AbstractKmerTable akt : ktsRef.tables()){
434 assert(akt.getClass()==HashArray1D.class);
435 HashArray1D ha=(HashArray1D)akt;
436 long[] kmers=ha.array();
437 int[] values=ha.values();
438 for(int i=0; i<kmers.length; i++){
439 final int refCount=Tools.mid(0, values[i], yMax);
440 if(refCount>0){
441 final long kmer=kmers[i];
442 final int readCount=Tools.mid(0, ktsRead.getCount(kmer), xMax);
443 if(readCount<1){counts[readCount][refCount]++;}
444 }
445 }
446 HashForest victims=ha.victims();
447 for(KmerNode node : victims){
448 KmerNode1D n=(KmerNode1D)node;
449 final int refCount=Tools.mid(0, n.value(), yMax);
450 if(refCount>0){
451 final long kmer=n.pivot();
452 final int readCount=Tools.mid(0, ktsRead.getCount(kmer), xMax);
453 if(readCount<1){counts[readCount][refCount]++;}
454 }
455 }
456 }
457 }
458
459 }else if(tables.getClass()==KmerTableSetU.class){
460
461 Kmer kmer=new Kmer(tables.kbig());
462 KmerTableSetU ktsRead=(KmerTableSetU)tables;
463 KmerTableSetU ktsRef=(KmerTableSetU)tables2;
464 for(AbstractKmerTableU akt : ktsRead.tables()){
465 assert(akt.getClass()==HashArrayU1D.class);
466 HashArrayU1D ha=(HashArrayU1D)akt;
467 int[] values=ha.values();
468 for(int i=0; i<values.length; i++){
469 final int readCount=Tools.mid(0, values[i], xMax);
470 if(readCount>0){
471 ha.fillKmer(i, kmer);
472 final int refCount=Tools.mid(0, ktsRef.getCount(kmer), yMax);
473 counts[readCount][refCount]++;
474 }
475 }
476 HashForestU victims=ha.victims();
477 for(KmerNodeU node : victims){
478 KmerNodeU1D n=(KmerNodeU1D)node;
479 final int readCount=Tools.mid(0, n.value(), xMax);
480 if(readCount>0){
481 n.fillKmer(kmer);
482 final int refCount=Tools.mid(0, ktsRef.getCount(kmer), yMax);
483 counts[readCount][refCount]++;
484 }
485 }
486 }
487
488 if(bidirectional){
489 for(AbstractKmerTableU akt : ktsRef.tables()){
490 assert(akt.getClass()==HashArrayU1D.class);
491 HashArrayU1D ha=(HashArrayU1D)akt;
492 int[] values=ha.values();
493 for(int i=0; i<values.length; i++){
494 final int refCount=Tools.mid(0, values[i], yMax);
495 if(refCount>0){
496 ha.fillKmer(i, kmer);
497 final int readCount=Tools.mid(0, ktsRead.getCount(kmer), xMax);
498 if(readCount<1){counts[refCount][readCount]++;}
499 }
500 }
501 HashForestU victims=ha.victims();
502 for(KmerNodeU node : victims){
503 KmerNodeU1D n=(KmerNodeU1D)node;
504 final int refCount=Tools.mid(0, n.value(), yMax);
505 if(refCount>0){
506 n.fillKmer(kmer);
507 final int readCount=Tools.mid(0, ktsRead.getCount(kmer), xMax);
508 if(readCount<1){counts[refCount][readCount]++;}
509 }
510 }
511 }
512 }
513
514 }else{
515 assert(false) : tables.getClass();
516 }
517 return counts;
518 }
519
520 public static long[][] intersectionST_second(final AbstractKmerTableSet tables,
521 final AbstractKmerTableSet tables2, final int xMax, final int yMax, final boolean bidirectional){
522
523 long[][] counts=new long[xMax+1][yMax+1];
524
525 Timer t=new Timer();
526 tables2.process(t);
527 if(tables.getClass()==KmerTableSet.class){
528
529 KmerTableSet ktsRead=(KmerTableSet)tables;
530 KmerTableSet ktsRef=(KmerTableSet)tables2;
531 for(AbstractKmerTable akt : ktsRead.tables()){
532 assert(akt.getClass()==HashArray1D.class);//If Walker is made abstract, these lines can be omitted
533 HashArray1D ha=(HashArray1D)akt;
534
535 Walker w=ha.walk();
536 while(w.next()){
537 final int readCount=Tools.mid(0, w.value(), xMax);
538 final int refCount=Tools.mid(0, ktsRef.getCount(w.kmer()), yMax);
539 counts[readCount][refCount]++;
540 }
541 }
542
543 if(bidirectional){
544 for(AbstractKmerTable akt : ktsRef.tables()){
545 assert(akt.getClass()==HashArray1D.class);//If Walker is made abstract, these lines can be omitted
546 HashArray1D ha=(HashArray1D)akt;
547
548 Walker w=ha.walk();
549 while(w.next()){
550 final int refCount=Tools.mid(0, w.value(), yMax);
551 final int readCount=Tools.mid(0, ktsRead.getCount(w.kmer()), xMax);
552 if(readCount<1){counts[readCount][refCount]++;}
553 }
554 }
555 }
556
557 }else if(tables.getClass()==KmerTableSetU.class){
558
559 KmerTableSetU ktsRead=(KmerTableSetU)tables;
560 KmerTableSetU ktsRef=(KmerTableSetU)tables2;
561 for(AbstractKmerTableU akt : ktsRead.tables()){
562 assert(akt.getClass()==HashArrayU1D.class);
563 HashArrayU1D ha=(HashArrayU1D)akt;
564
565 WalkerU w=ha.walk();
566 while(w.next()){
567 final int readCount=Tools.mid(0, w.value(), xMax);
568 final int refCount=Tools.mid(0, ktsRef.getCount(w.kmer()), yMax);
569 counts[readCount][refCount]++;
570 }
571 }
572
573 if(bidirectional){
574 for(AbstractKmerTableU akt : ktsRef.tables()){
575 assert(akt.getClass()==HashArrayU1D.class);
576 HashArrayU1D ha=(HashArrayU1D)akt;
577
578 WalkerU w=ha.walk();
579 while(w.next()){
580 final int refCount=Tools.mid(0, w.value(), yMax);
581 final int readCount=Tools.mid(0, ktsRead.getCount(w.kmer()), xMax);
582 if(readCount<1){counts[readCount][refCount]++;}
583 }
584 }
585 }
586
587 }else{
588 assert(false) : tables.getClass();
589 }
590 return counts;
591 }
592
593 public static long[][] intersectionST(final AbstractKmerTableSet tables,
594 final AbstractKmerTableSet tables2, final int xMax, final int yMax, final boolean bidirectional){
595
596 long[][] counts=new long[xMax+1][yMax+1];
597
598 Timer t=new Timer();
599 tables2.process(t);
600 if(tables.getClass()==KmerTableSet.class){
601
602 KmerTableSet ktsRead=(KmerTableSet)tables;
603 KmerTableSet ktsRef=(KmerTableSet)tables2;
604 {
605 Walker w=ktsRead.walk();
606 while(w.next()){
607 final int readCount=Tools.mid(0, w.value(), xMax);
608 final int refCount=Tools.mid(0, ktsRef.getCount(w.kmer()), yMax);
609 counts[readCount][refCount]++;
610 }
611 }
612 if(bidirectional){
613 Walker w=ktsRef.walk();
614 while(w.next()){
615 final int refCount=Tools.mid(0, w.value(), yMax);
616 final int readCount=Tools.mid(0, ktsRead.getCount(w.kmer()), xMax);
617 if(readCount<1){counts[readCount][refCount]++;}
618 }
619 }
620
621 }else if(tables.getClass()==KmerTableSetU.class){
622
623 KmerTableSetU ktsRead=(KmerTableSetU)tables;
624 KmerTableSetU ktsRef=(KmerTableSetU)tables2;
625 {
626 WalkerU w=ktsRead.walk();
627 while(w.next()){
628 final int readCount=Tools.mid(0, w.value(), xMax);
629 final int refCount=Tools.mid(0, ktsRef.getCount(w.kmer()), yMax);
630 counts[readCount][refCount]++;
631 }
632 }
633 if(bidirectional){
634 WalkerU w=ktsRef.walk();
635 while(w.next()){
636 final int refCount=Tools.mid(0, w.value(), yMax);
637 final int readCount=Tools.mid(0, ktsRead.getCount(w.kmer()), xMax);
638 if(readCount<1){counts[readCount][refCount]++;}
639 }
640 }
641
642 }else{
643 assert(false) : tables.getClass();
644 }
645 return counts;
646 }
647
648 // void processRef(){
649 // FileFormat ffref=FileFormat.testInput(ref, FileFormat.FA, null, true, false);
650 // ConcurrentReadInputStream cris=makeCris(ffref);
651 // //Do anything necessary prior to processing
652 //
653 // {
654 // //Grab the first ListNum of reads
655 // ListNum<Read> ln=cris.nextList();
656 //
657 // //Check to ensure pairing is as expected
658 // if(ln!=null && !ln.isEmpty()){
659 // Read r=ln.get(0);
660 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired());
661 // }
662 //
663 // //As long as there is a nonempty read list...
664 // while(ln!=null && ln.size()>0){
665 //
666 // processList(ln, cris);
667 //
668 // //Fetch a new list
669 // ln=cris.nextList();
670 // }
671 //
672 // //Notify the input stream that the final list was used
673 // if(ln!=null){
674 // cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
675 // }
676 // }
677 //
678 // //Do anything necessary after processing
679 // ReadWrite.closeStream(cris);
680 // }
681 //
682 // /**
683 // * Process a list of Reads.
684 // * @param ln The list.
685 // * @param cris Read Input Stream
686 // * @param ros Read Output Stream for reads that will be retained
687 // */
688 // void processList(ListNum<Read> ln, final ConcurrentReadInputStream cris){
689 //
690 // //Grab the actual read list from the ListNum
691 // final ArrayList<Read> reads=ln.list;
692 //
693 // //Loop through each read in the list
694 // for(int idx=0; idx<reads.size(); idx++){
695 // final Read r1=reads.get(idx);
696 // final Read r2=r1.mate;
697 //
698 // //Validate reads in worker threads
699 // if(!r1.validated()){r1.validate(true);}
700 // if(r2!=null && !r2.validated()){r2.validate(true);}
701 //
702 // //Track the initial length for statistics
703 // final int initialLength1=r1.length();
704 // final int initialLength2=r1.mateLength();
705 //
706 // //Increment counters
707 // readsProcessed+=r1.pairCount();
708 // basesProcessed+=initialLength1+initialLength2;
709 //
710 // {
711 // //Reads are processed in this block.
712 // boolean keep=processReadPair(r1, r2);
713 //
714 // if(!keep){reads.set(idx, null);}
715 // else{
716 // readsOut+=r1.pairCount();
717 // basesOut+=r1.pairLength();
718 // }
719 // }
720 // }
721 //
722 // //Output reads to the output stream
723 // if(ros!=null){ros.add(reads, ln.id);}
724 //
725 // //Notify the input stream that the list was used
726 // cris.returnList(ln);
727 //// if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
728 // }
729 //
730 // private ConcurrentReadInputStream makeCris(FileFormat ff){
731 // ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff, null);
732 // cris.start(); //Start the stream
733 // if(verbose){outstream.println("Started ref cris");}
734 // boolean paired=cris.paired();
735 // assert(!paired);
736 // return cris;
737 // }
738 //
739 //
740 // /**
741 // * Process a single contig.
742 // * @param r The contig
743 // */
744 // void processContig(final Read r){
745 //
746 // final byte[] bases=r.bases;
747 // long kmer=0;
748 // long rkmer=0;
749 // long added=0;
750 // int len=0;
751 //
752 // for(int i=0; i<bases.length; i++){
753 // final byte b=bases[i];
754 // final long x=AminoAcid.baseToNumber[b];
755 // final long x2=AminoAcid.baseToComplementNumber[b];
756 //// assert(x!=x2) : x+", "+x2+", "+Character.toString((char)b)+"\n"+Arrays.toString(symbolToNumber0)+"\n"+Arrays.toString(symbolToComplementNumber);
757 // kmer=((kmer<<bitsPerBase)|x)&mask;
758 // //10000, 1111111111, 16, 16, 2, 10, 8
759 // rkmer=((rkmer>>>bitsPerBase)|(x2<<shift2))&mask;
760 // if(x>=0){len++;}else{len=0; rkmer=0;}
761 // if(verbose){
762 // if(verbose){
763 // String fwd=new String(bases, Tools.max(0, i-k2), Tools.min(i+1, k));
764 // String rev=AminoAcid.reverseComplementBases(fwd);
765 // String fwd2=kmerToString(kmer, Tools.min(len, k));
766 // outstream.println("fwd="+fwd+", fwd2="+fwd2+", rev="+rev+", kmer="+kmer+", rkmer="+rkmer);
767 // outstream.println("b="+(char)b+", x="+x+", x2="+x2+", bitsPerBase="+bitsPerBase+", shift2="+shift2);
768 // if(!amino){
769 // assert(AminoAcid.stringToKmer(fwd)==kmer) : fwd+", "+AminoAcid.stringToKmer(fwd)+", "+kmer+", "+len;
770 // if(len>=k){
771 // assert(AminoAcid.reverseComplementBinaryFast(kmer, Tools.min(len, k))==rkmer);
772 // assert(AminoAcid.reverseComplementBinaryFast(rkmer, Tools.min(len, k))==kmer);
773 // assert(AminoAcid.kmerToString(kmer, Tools.min(len, k)).equals(fwd));
774 // assert(AminoAcid.kmerToString(rkmer, Tools.min(len, k)).equals(rev)) : AminoAcid.kmerToString(rkmer, Tools.min(len, k))+" != "+rev+" (rkmer)";
775 // }
776 // assert(fwd.equalsIgnoreCase(fwd2)) : fwd+", "+fwd2; //may be unsafe
777 // }
778 // outstream.println("Scanning6 i="+i+", len="+len+", kmer="+kmer+", rkmer="+rkmer+", bases="+fwd+", rbases="+rev);
779 // }
780 // }
781 // if(len>=k){
782 //// assert(kmer==AminoAcid.reverseComplementBinaryFast(rkmer, k)) : Long.toBinaryString(kmer)+", "+Long.toBinaryString(rkmer)+", "+Long.toBinaryString(mask)+", x="+x+", x2="+x2+", bits="+bitsPerBase+", s="+shift+", s2="+shift2+", b="+Character.toString((char)b);
783 // refKmersT++;
784 // final long extraBase=(i>=bases.length-1 ? -1 : symbolToNumber[bases[i+1]]);
785 // final long atm=addToMap(kmer, rkmer, k, extraBase, id, kmask, hammingDistance, editDistance);
786 // added+=atm;
787 //// assert(false) : atm+", "+map.contains(toValue(kmer, rkmer, kmask));
788 // if(useShortKmers){
789 // if(i==k2){added+=addToMapRightShift(kmer, rkmer, id);}
790 // if(i==bases.length-1){added+=addToMapLeftShift(kmer, rkmer, extraBase, id);}
791 // }
792 // }
793 // }
794 // }
795
796 /*--------------------------------------------------------------*/
797 /*---------------- Helper Methods ----------------*/
798 /*--------------------------------------------------------------*/
799
800 long shave(boolean shave, boolean rinse, int maxShaveDepth){
801 long sum=0;
802
803 for(int i=0; i<maxShaveDepth; i++){
804 int a=i+1, b=maxShaveDepth, c=i+1;
805 // if(i>3){Shaver2.verbose2=true;}
806 outstream.println("\nShave("+a+", "+b+", "+c+")");
807 final Shaver shaver=Shaver.makeShaver(tables, THREADS, a, b, c, 1, 3, 100, 100, shave, rinse);
808 long removed=shaver.shave(a, b);
809 sum+=removed;
810 }
811
812 System.err.println();
813 return sum;
814 }
815
816 private double makeKhist(String fname, String peaks, int cols, int max, boolean printHeader, boolean printZeros, boolean printTime, boolean smoothKhist, boolean smoothPeaks){
817 if(fname==null && peaks==null){return -1;}
818
819 final long[][] arrays=tables.makeKhist(fname, cols, max, printHeader, printZeros, printTime, smoothKhist, gcHist, doLogScale, logWidth, logPasses, smoothRadius);
820 final long[] array=arrays[0];
821 final long[] gcArray=arrays[1];
822
823 double avg=Tools.averageHistogram(array);
824
825 if(peaks!=null){
826 CallPeaks.printClass=false;
827 ArrayList<String> args=new ArrayList<String>();
828 if((smoothPeaks && !smoothKhist) && smoothRadius>0){//!smoothKhist because if smoothKhist is true the array will already be smoothed
829 args.add("smoothradius="+smoothRadius);
830 args.add("smoothprogressive=t");
831 }
832 CallPeaks.printPeaks(array, gcArray, peaks, overwrite, minHeight, minVolume, minWidth,
833 Tools.max(tables.filterMax()+2, minPeak), maxPeak, maxPeakCount, k, ploidy, doLogScale, logWidth, args);
834 }
835 return avg;
836 }
837
838 private void makeSketch(){
839 Timer ts=new Timer();
840 outstream.println("Generating sketch.");
841 SketchObject.maxGenomeFraction=1;
842 SketchObject.k=k;
843 SketchTool sketcher=new SketchTool(sketchLength, minToDump, false, false, SketchObject.rcomp);
844 Sketch sketch=sketcher.toSketch((KmerTableSet)tables, true);
845 if(sketch==null){
846 errorState=true;
847 System.err.println("WARNING: No sketch was produced, presumably because no kmers passed the filter criteria.");
848 assert(false);
849 return;
850 }
851 sketch.setName0(ReadWrite.stripToCore(ffSketch.name()));
852 SketchTool.write(sketch, ffSketch);
853 ts.stop();
854 outstream.println("Sketch Time: \t"+ts);
855 }
856
857 private void makeKhistAndPeaks(){
858 if(THREADS>1 && (outHist!=null || outPeaks!=null) && outKmers!=null){
859 Timer tout=new Timer();
860 tout.start();
861 Thread a=new DumpKmersThread();
862 Thread b=new MakeKhistThread();
863 a.start();
864 b.start();
865 while(a.getState()!=Thread.State.TERMINATED){
866 try {
867 a.join();
868 } catch (InterruptedException e) {
869 // TODO Auto-generated catch block
870 e.printStackTrace();
871 }
872 }
873 while(b.getState()!=Thread.State.TERMINATED){
874 try {
875 b.join();
876 } catch (InterruptedException e) {
877 // TODO Auto-generated catch block
878 e.printStackTrace();
879 }
880 }
881 tout.stop();
882 outstream.println("Write Time: \t"+tout);
883 }else{
884 if(outHist!=null || outPeaks!=null){
885 averageCount=makeKhist(outHist, outPeaks, histColumns, histMax, histHeader, histZeros, true, smoothKhist, smoothPeaks);
886 }
887 if(outKmers!=null){
888 // tables.dumpKmersAsText(outKmers, minToDump, true);
889 tables.dumpKmersAsBytes_MT(outKmers, minToDump, maxToDump, true, null);
890 }
891 }
892 }
893
894 /*--------------------------------------------------------------*/
895 /*---------------- Helper Classes ----------------*/
896 /*--------------------------------------------------------------*/
897
898 private class DumpKmersThread extends Thread {
899
900 DumpKmersThread(){}
901
902 @Override
903 public void run(){
904 tables.dumpKmersAsBytes_MT(outKmers, minToDump, maxToDump, false, null);
905 }
906
907 }
908
909 private class MakeKhistThread extends Thread {
910
911 MakeKhistThread(){}
912
913 @Override
914 public void run(){
915 makeKhist(outHist, outPeaks, histColumns, histMax, histHeader, histZeros, false, smoothKhist, smoothPeaks);
916 }
917 }
918
919 /*--------------------------------------------------------------*/
920 /*---------------- Fields ----------------*/
921 /*--------------------------------------------------------------*/
922
923 /** Hold kmers. */
924 private final AbstractKmerTableSet tables;
925 private AbstractKmerTableSet tables2;//ref kmers
926
927 private boolean shave=false;
928 private boolean rinse=false;
929 private int shaveDepth=1;
930
931 private double averageCount=-1;
932 private long basesIn=-1;
933 private long readsIn=-1;
934 private int decimals=3;
935
936 private long kmersRemoved=0;
937
938 /** Kmer count output file */
939 private String outKmers=null;
940 /** Histogram output file */
941 private String outHist=null;
942 /** Histogram peak output file */
943 private String outPeaks=null;
944
945 private int smoothRadius=1;
946 private boolean smoothKhist=false;
947 private boolean smoothPeaks=false;
948
949 private boolean errorState=false;
950
951 /** Histogram columns */
952 private int histColumns=2;
953 /** Histogram rows */
954 private int histMax=100000;
955 /** Print a histogram header */
956 private boolean histHeader=true;
957 /** Histogram show rows with 0 count */
958 private boolean histZeros=false;
959 /** Add gc information to kmer histogram */
960 protected boolean gcHist=false;
961
962 boolean doLogScale=true;
963 double logWidth=0.1;
964 int logPasses=1;
965
966 private long minHeight=2;
967 private long minVolume=5;
968 private int minWidth=3;
969 private int minPeak=2;
970 private int maxPeak=Integer.MAX_VALUE;
971 private int maxPeakCount=12;
972
973 private int ploidy=-1;
974
975 private String sketchPath=null;
976 private int sketchLength=10000;
977 private String sketchName;
978 private int sketchID;
979 private final FileFormat ffSketch;
980
981 /*--------------------------------------------------------------*/
982 /*---------------- Ref Counting ----------------*/
983 /*--------------------------------------------------------------*/
984
985 private String ref=null;
986 private String intersectionFile=null;
987 private boolean bidirectional=true;
988
989
990 private int refMax=6;
991
992 /*--------------------------------------------------------------*/
993 /*---------------- Final Primitives ----------------*/
994 /*--------------------------------------------------------------*/
995
996 /** min kmer count to dump to text */
997 private int minToDump=1;
998 private int maxToDump=Integer.MAX_VALUE;
999
1000 final int k;
1001
1002 /*--------------------------------------------------------------*/
1003 /*---------------- Static Fields ----------------*/
1004 /*--------------------------------------------------------------*/
1005
1006 /** Print messages to this stream */
1007 private static PrintStream outstream=System.err;
1008 /** Permission to overwrite existing files */
1009 public static boolean overwrite=true;
1010 /** Permission to append to existing files */
1011 public static boolean append=false;
1012 /** Display progress messages such as memory usage */
1013 public static boolean DISPLAY_PROGRESS=true;
1014 /** Verbose messages */
1015 public static final boolean verbose=false;
1016 /** Number of ProcessThreads */
1017 public static int THREADS=Shared.threads();
1018
1019
1020 }