Debian Codegraph @

current/hiseq/AnalyzeFlowCell.java

raw symbols SCIP
1 package hiseq;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Collections;
8 import java.util.concurrent.ConcurrentHashMap;
9 import java.util.concurrent.locks.ReadWriteLock;
10 import java.util.concurrent.locks.ReentrantReadWriteLock;
11
12 import aligner.SideChannel3;
13 import barcode.Barcode;
14 import barcode.BarcodeStats;
15 import bloom.BloomFilter;
16 import bloom.KmerCountAbstract;
17 import bloom.PolyFilter;
18 import dna.AminoAcid;
19 import dna.Data;
20 import fileIO.ByteFile;
21 import fileIO.ByteStreamWriter;
22 import fileIO.FileFormat;
23 import fileIO.ReadWrite;
24 import jgi.BBMerge;
25 import jgi.CalcTrueQuality;
26 import jgi.Dedupe;
27 import shared.Parse;
28 import shared.Parser;
29 import shared.PreParser;
30 import shared.Shared;
31 import shared.Timer;
32 import shared.Tools;
33 import shared.TrimRead;
34 import stream.ConcurrentReadInputStream;
35 import stream.ConcurrentReadOutputStream;
36 import stream.FASTQ;
37 import stream.FastaReadInputStream;
38 import stream.Read;
39 import stream.SamLine;
40 import stream.SamLineStreamer;
41 import structures.AtomicStringNum;
42 import structures.ByteBuilder;
43 import structures.IntList;
44 import structures.ListNum;
45 import structures.LongList;
46 import template.Accumulator;
47 import template.ThreadWaiter;
48
49 /**
50 * Analyzes a flow cell for low-quality areas.
51 * Removes reads in the low-quality areas.
52 *
53 * @author Brian Bushnell
54 * @date August 31, 2016
55 *
56 */
57 public class AnalyzeFlowCell implements Accumulator<AnalyzeFlowCell.ProcessThread> {
58
59 /*--------------------------------------------------------------*/
60 /*---------------- Initialization ----------------*/
61 /*--------------------------------------------------------------*/
62
63 /**
64 * Code entrance from the command line.
65 * @param args Command line arguments
66 */
67 public static void main(String[] args){
68 Timer t=new Timer();
69 AnalyzeFlowCell x=new AnalyzeFlowCell(args);
70 x.process(t);
71
72 //Close the print stream if it was redirected
73 Shared.closeStream(x.outstream);
74 }
75
76 /**
77 * Constructor.
78 * @param args Command line arguments
79 */
80 public AnalyzeFlowCell(String[] args){
81
82 {//Preparse block for help, config files, and outstream
83 PreParser pp=new PreParser(args, getClass(), false);
84 args=pp.args;
85 outstream=pp.outstream;
86 }
87
88 //Set shared static variables
89 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
90 ReadWrite.setZipThreads(Shared.threads());
91
92 Parser parser=parse(args);
93
94 if(gToN || discardG){MicroTile.TRACK_CYCLES=true;}
95
96 {//Process parser fields
97 Parser.processQuality();
98
99 maxReads=parser.maxReads;
100
101 overwrite=parser.overwrite;
102 append=parser.append;
103 setInterleaved=parser.setInterleaved;
104
105 in1=parser.in1;
106 in2=parser.in2;
107
108 out1=parser.out1;
109 out2=parser.out2;
110
111 extin=parser.extin;
112 extout=parser.extout;
113
114
115 trimq=parser.trimq;
116 trimE=parser.trimE();
117 minlen=parser.minReadLength;
118 trimLeft=parser.qtrimLeft;
119 trimRight=parser.qtrimRight;
120 }
121
122
123 Read.VALIDATE_IN_CONSTRUCTOR=true;
124 align=(align || alignOut!=null) && samInput==null && dumpIn==null;
125
126 if(recalibrate) {
127 CalcTrueQuality.initializeMatrices();
128 }
129 // if(mapper!=null) {
130 // assert(mapper.getMap().size()>0) : refPath+", "+alignK+", "+minIdentity;
131 // }
132 checkFiles();
133
134 //Create output FileFormat objects
135 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
136 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
137 ffoutbad=FileFormat.testOutput(outbad, FileFormat.FASTQ, extout, true, overwrite, append, false);
138
139 //Create input FileFormat objects
140 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
141 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
142 }
143
144 /*--------------------------------------------------------------*/
145 /*---------------- Initialization Helpers ----------------*/
146 /*--------------------------------------------------------------*/
147
148 private Parser parse(String[] args){
149 //Create a parser object
150 Parser parser=new Parser();
151 parser.qtrimRight=trimRight;
152 parser.trimq=trimq;
153 parser.minReadLength=minlen;
154
155 //Parse each argument
156 for(int i=0; i<args.length; i++){
157 String arg=args[i];
158
159 //Break arguments into their constituent parts, in the form of "a=b"
160 String[] split=arg.split("=");
161 String a=split[0].toLowerCase();
162 String b=split.length>1 ? split[1] : null;
163
164 if(a.equals("verbose")){
165 verbose=Parse.parseBoolean(b);
166 }else if(a.equals("outb") || a.equals("outbad")){
167 outbad=b;
168 }else if(a.equals("sam") || a.equals("insam") ||
169 a.equals("samin") || a.equals("saminput")){
170 samInput=b;
171 }else if(a.equals("sammt")){
172 // processSamMT=Parse.parseBoolean(b);
173 }else if(a.equals("divisor") || a.equals("size")){
174 targetX=targetY=Tile.xSize=Tile.ySize=Parse.parseIntKMG(b);
175 }else if(a.equals("xdivisor") || a.equals("xsize") || a.equals("x")){
176 targetX=Tile.xSize=Parse.parseIntKMG(b);
177 }else if(a.equals("ydivisor") || a.equals("ysize") || a.equals("y")){
178 targetY=Tile.ySize=Parse.parseIntKMG(b);
179 }else if(a.equals("target") || a.equals("targetreads")){
180 targetAverageReads=Parse.parseIntKMG(b);
181 }else if(a.equals("targetalignedreads") || a.equals("alignedreads")){
182 targetAlignedReads=Parse.parseIntKMG(b);
183 }else if(a.equals("dump") || a.equals("dumpout") || a.equals("outdump")){
184 dumpOut=b;
185 }else if(a.equals("indump") || a.equals("ind") || a.equals("dumpin")){
186 dumpIn=b;
187 }else if(a.equals("filterout") || a.equals("filterlist") || a.equals("coordinates")
188 || a.equals("coords") || a.equals("coordsout") || a.equals("coordinatesout")){
189 coordsOut=b;
190 }else if(a.equals("loadkmers") || a.equals("usekmers")){
191 loadKmers=Parse.parseBoolean(b);
192 }else if(a.equals("loadthreads")){
193 loadThreads=Integer.parseInt(b);
194 }else if(a.equals("fillthreads")){
195 fillThreads=Integer.parseInt(b);
196 }else if(a.equals("minprob")){
197 minProb=Float.parseFloat(b);
198 }else if(a.equals("bits") || a.equals("cbits")){
199 cbits=Integer.parseInt(b);
200 }else if(a.equals("hashes")){
201 hashes=Integer.parseInt(b);
202 }
203
204 else if(a.equals("smooth") || a.equals("fixspikes")){
205 if(!Tools.startsWithDigit(b)) {
206 smoothDepths=Parse.parseBoolean(b) ? 3 : 0;
207 }else {
208 smoothDepths=Integer.parseInt(b);
209 }
210 }else if(a.equals("deblur") || a.equals("deconvolute")){
211 deblurDepths=Parse.parseBoolean(b);
212 }
213
214 else if(a.equals("blur") || a.equals("blurtiles") || a.equals("smoothtiles")){
215 blurTiles=Parse.parseBoolean(b);
216 }
217
218 else if(a.equals("recalibrate") || a.equals("recal")) {
219 recalibrate=Parse.parseBoolean(b);
220 }
221
222 else if(a.equals("minpolyg")){
223 MicroTile.MIN_POLY_G=Integer.parseInt(b);
224 }else if(a.equals("trackcycles")){
225 MicroTile.TRACK_CYCLES=Parse.parseBoolean(b);
226 }else if(a.equals("extra")){
227 if(b!=null) {
228 for(String s : b.split(",")) {
229 extra.add(s);
230 }
231 }
232 }else if(a.equals("expectedbarcodes") || a.equals("expected") || a.equals("barcodes") || a.equals("barcodesin")){
233 expectedBarcodes=b;
234 }else if(a.equals("barcodesout") || a.equals("barcodecounts") || a.equals("counts")){
235 barcodeCounts=b;
236 }
237
238 else if(a.equals("merge")){
239 merge=Parse.parseBoolean(b);
240 }else if(a.equals("strict")){
241 strictmerge=Parse.parseBoolean(b);
242 }else if(a.equals("loose")){
243 strictmerge=!Parse.parseBoolean(b);
244 }
245
246 else if(a.equals("alignout") || a.equals("sideout") || a.equals("phixout") || a.equals("outphix") ||
247 a.equals("outsam") || a.equals("samout")){
248 alignOut=b;
249 }else if(a.equals("align")){
250 align=Parse.parseBoolean(b);
251 }else if(a.equals("ref") || a.equals("alignref") || a.equals("sideref")){
252 alignRef=b;
253 }else if(a.equals("alignk") || a.equals("sidek") || a.equals("alignk1") || a.equals("sidek1")){
254 alignK1=Integer.parseInt(b);
255 }else if(a.equals("alignk2") || a.equals("sidek2")){
256 alignK2=Integer.parseInt(b);
257 }else if(a.equals("alignminid") || a.equals("alignminid1") ||
258 a.equals("sideminid") || a.equals("sideminid1") || a.equals("minid") || a.equals("minid1")){
259 alignMinid1=Float.parseFloat(b);
260 }else if(a.equals("alignminid2") || a.equals("sideminid2") || a.equals("minid2")){
261 alignMinid2=Float.parseFloat(b);
262 }else if(a.equals("alignmm1") || a.equals("alignmidmask1") || a.equals("sidemm1") ||
263 a.equals("sidemidmask1")){
264 alignMM1=Integer.parseInt(b);
265 }else if(a.equals("alignmm2") || a.equals("alignmidmask2") || a.equals("sidemm2") ||
266 a.equals("sidemidmask2")){
267 alignMM2=Integer.parseInt(b);
268 }
269
270 else if(a.equals("lqo") || a.equals("lowqualityonly")){
271 discardOnlyLowQuality=Parse.parseBoolean(b);
272 }else if(a.equals("dmult")){
273 dmult=Float.parseFloat(b);
274 }else if(a.equals("idmaskread")){
275 idmask_read=Integer.parseInt(b);
276 }else if(a.equals("idmaskwrite")){
277 idmask_write=Integer.parseInt(b);
278 }else if(a.equals("allkmers")){
279 // kmersPerRead=(Parse.parseBoolean(b) ? 0 : 1);
280 boolean x=Parse.parseBoolean(b);
281 idmask_write=(x ? 0 : 15);
282 }
283 // else if(a.equals("kmersperread")){
284 // kmersPerRead=Integer.parseInt(b);
285 // }
286
287 else if(a.equals("parse_flag_goes_here")){
288 //Set a variable here
289 }else if(TileDump.parseStatic(arg, a, b)){
290 //do nothing
291 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
292 //do nothing
293 }else if(b==null && new File(arg).exists()){
294 extra.add(b);
295 }else{
296 outstream.println("Unknown parameter "+args[i]);
297 assert(false) : "Unknown parameter "+args[i];
298 // throw new RuntimeException("Unknown parameter "+args[i]);
299 }
300 }
301 return parser;
302 }
303
304 private void checkFiles(){
305 doPoundReplacement();
306 adjustInterleaving();
307 checkFileExistence();
308 checkStatics();
309 }
310
311 private void doPoundReplacement(){
312 //Do input file # replacement
313 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
314 in2=in1.replace("#", "2");
315 in1=in1.replace("#", "1");
316 }
317
318 //Do output file # replacement
319 if(out1!=null && out2==null && out1.indexOf('#')>-1){
320 out2=out1.replace("#", "2");
321 out1=out1.replace("#", "1");
322 }
323
324 //Ensure there is an input file
325 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
326
327 //Ensure out2 is not set without out1
328 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
329 }
330
331 private void checkFileExistence(){
332
333 //Ensure output files can be written
334 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, outbad, dumpOut, barcodeCounts)){
335 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2+", "+outbad);
336 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+", "+outbad+", "+dumpOut+"\n");
337 }
338
339 //Ensure input files can be read
340 if(!Tools.testInputFiles(false, true, in1, in2, samInput, dumpIn, expectedBarcodes)){
341 throw new RuntimeException("\nCan't read some input files.\n");
342 }
343
344 //Ensure that no file was specified multiple times
345 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2, outbad, samInput,
346 dumpIn, dumpOut, expectedBarcodes, barcodeCounts)){
347 throw new RuntimeException("\nSome file names were specified multiple times.\n");
348 }
349 }
350
351 private void adjustInterleaving(){
352 //Adjust interleaved detection based on the number of input files
353 if(in2!=null){
354 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
355 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
356 }
357
358 //Adjust interleaved settings based on number of output files
359 if(!setInterleaved){
360 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
361 if(in2!=null){ //If there are 2 input streams.
362 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
363 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
364 }else{ //There is one input stream.
365 if(out2!=null){
366 FASTQ.FORCE_INTERLEAVED=true;
367 FASTQ.TEST_INTERLEAVED=false;
368 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
369 }
370 }
371 }
372 }
373
374 private static void checkStatics(){
375 //Adjust the number of threads for input file reading
376 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
377 ByteFile.FORCE_MODE_BF2=true;
378 }
379
380 assert(FastaReadInputStream.settingsOK());
381 }
382
383 /*--------------------------------------------------------------*/
384 /*---------------- Outer Methods ----------------*/
385 /*--------------------------------------------------------------*/
386
387 /** Create read streams and process all data */
388 public void process(Timer t){
389
390 //Reset counters
391 readsProcessed=0;
392 basesProcessed=0;
393
394 if(dumpIn==null){
395 barcodeStats=loadBarcodes(expectedBarcodes);
396 if(barcodeCounts!=null) {
397 barcodeMap=new ConcurrentHashMap<String, AtomicStringNum>();
398 }
399 if(loadKmers){loadKmers();}
400 flowcell=new FlowCell(k);
401 fillTiles();
402
403 bloomFilter=null;//Clearing before widen saves memory
404 ArrayList<MicroTile> mtList;
405 // if(!processSamMT) {loadSam_ST(samInput);}
406 Timer t2=new Timer();
407 boolean showTime=false;
408 synchronized(flowcell) {
409 mtList=flowcell.calcStats();
410 if(showTime) {t2.stopAndStart("calcStats: ");}
411 if(flowcell.avgReads<targetAverageReads){
412 flowcell=flowcell.widenToTargetReads(targetAverageReads);
413 if(showTime) {t2.stopAndStart("Widen: ");}
414 mtList=flowcell.toList();
415 if(showTime) {t2.stopAndStart("toList: ");}
416 }
417 if(blurTiles) {
418 flowcell.blur();
419 if(showTime) {t2.stopAndStart("Blur: ");}
420 }
421 //Temporarily widen to calculate a regression
422 if(flowcell.avgAlignedReads<targetAlignedReads && flowcell.readsAligned>targetAlignedReads) {
423 final int oldX=Tile.xSize, oldY=Tile.ySize;
424 FlowCell temp=flowcell.widenToTargetAlignedReads(targetAlignedReads);
425 temp.calcStats();
426 flowcell.uniqueToReadErrorRateFormula=temp.uniqueToReadErrorRateFormula;
427 flowcell.uniqueToBaseErrorRateFormula=temp.uniqueToBaseErrorRateFormula;
428 Tile.xSize=oldX;
429 Tile.ySize=oldY;
430 if(showTime) {t2.stopAndStart("Widen2: ");}
431 }
432 // if(MicroTile.trackDepth) {flowcell.summarizeDepth();}
433 }
434
435 long readsToDiscard=TileDump.markTiles(flowcell, mtList, outstream);
436
437 if(dumpOut!=null){
438 flowcell.dump(dumpOut, overwrite);
439 if(showTime) {t2.stopAndStart("Dump: ");}
440 }
441 if(barcodeCounts!=null) {
442 dumpBarcodes(barcodeMap.values(), barcodeCounts, overwrite);
443 if(showTime) {t2.stopAndStart("Dump Barcodes: ");}
444 }
445 }else{
446 flowcell=new FlowCell(dumpIn);
447 // if(loadKmers){loadKmers();}
448 if(targetX>Tile.xSize || targetY>Tile.ySize) {
449 flowcell=flowcell.widen(targetX, targetY, true);
450 }
451 if(flowcell.avgReads<targetAverageReads){
452 flowcell.calcStats();//May be necessary for calculating average reads
453 flowcell=flowcell.widenToTargetReads(targetAverageReads);
454 }
455 if(blurTiles) {flowcell.blur();}
456 ArrayList<MicroTile> mtList=flowcell.calcStats();
457 long readsToDiscard=TileDump.markTiles(flowcell, mtList, outstream);
458 }
459 System.err.println("Avg quality: \t"+Tools.format("%.3f", flowcell.avgQuality));
460 System.err.println("STDev quality: \t"+Tools.format("%.4f", flowcell.stdQuality));
461 System.err.println("Avg uniqueness: \t"+Tools.format("%.4f", flowcell.avgUnique));
462 System.err.println("STDev uniqueness:\t"+Tools.format("%.4f", flowcell.stdUnique));
463 System.err.println("Avg depth: \t"+Tools.format("%.4f", flowcell.avgDepth));
464 System.err.println("STDev depth: \t"+Tools.format("%.4f", flowcell.stdDepth));
465 System.err.println("Avg poly-G: \t"+Tools.format("%.4f", flowcell.avgPolyG));
466 System.err.println("STDev poly-G: \t"+Tools.format("%.4f", flowcell.stdPolyG));
467 System.err.println("Alignment Rate: \t"+Tools.format("%.8f", flowcell.alignmentRate()));
468 System.err.println("Base Error Rate: \t"+Tools.format("%.8f", flowcell.baseErrorRate()));
469
470 if(sidechannel!=null && sidechannel.samOut) {Data.unloadAll();}
471
472 processReads(t);
473 }
474
475 /** Create read streams and process all data */
476 void loadKmers(){
477 Timer t2=new Timer();
478 outstream.print("Loading kmers: \t");
479
480 loadThreads=Tools.min(loadThreads, Shared.threads());
481 final int oldMCT=KmerCountAbstract.MAX_COUNT_THREADS;
482 final float oldProb=KmerCountAbstract.minProb;
483 // KmerCountAbstract.KMERS_PER_READ=kmersPerRead;
484 KmerCountAbstract.IDMASK=idmask_write;
485 KmerCountAbstract.minProb=minProb;
486 KmerCountAbstract.CANONICAL=true;
487
488 if(loadThreads>1) {
489 if(idmask_write>7) {
490 KmerCountAbstract.MAX_COUNT_THREADS=loadThreads;
491 }
492 bloomFilter=new BloomFilter(in1, in2, extra, k, k, cbits, hashes,
493 1, true, false, false, 0.65f);
494 bloomFilter.filter.shutdown();
495 }else {
496 //Create a read input stream
497 final ConcurrentReadInputStream cris;
498 {
499 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
500 cris.start(); //Start the stream
501 if(verbose){outstream.println("Started cris");}
502 }
503 boolean paired=cris.paired();
504 //Process the read stream
505 loadKmersInner(cris);
506
507 // if(verbose){outstream.println("Finished; closing streams.");}
508
509 //Close the read streams
510 errorState|=ReadWrite.closeStreams(cris);
511 bloomFilter.filter.shutdown();
512 }
513
514 KmerCountAbstract.KMERS_PER_READ=0;
515 KmerCountAbstract.IDMASK=0;
516 KmerCountAbstract.MAX_COUNT_THREADS=oldMCT;
517 KmerCountAbstract.minProb=oldProb;
518
519 double used=bloomFilter.filter.usedFraction();
520 long unique=(long)bloomFilter.filter.estimateUniqueKmersFromUsedFraction(hashes, used);
521 System.err.println(String.format("Bloom Occupancy:\t%.2f%%", 100*used));
522 System.err.println("Unique Kmers: \t"+unique);
523
524 t2.stop();
525 outstream.println(t2);
526 }
527
528 /** Create read streams and process all data */
529 void fillTiles(){
530
531 //Create a read input stream
532 final ConcurrentReadInputStream cris;
533 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
534 cris.start(); //Start the stream
535 if(verbose){outstream.println("Started cris");}
536 boolean paired=cris.paired();
537
538 SamLineStreamer ss=null;
539 if(samInput!=null && processSamMT) {
540 outstream.println("Loading sam file.");
541 FileFormat ff=FileFormat.testInput(samInput, FileFormat.SAM, null, true, false);
542 final int streamerThreads=Tools.min(4, Shared.threads());
543 ss=new SamLineStreamer(ff, streamerThreads, false, maxReads);
544 ss.start();
545 }
546
547
548 if(align) {
549 sidechannel=new SideChannel3(alignRef, alignOut, null, alignK1, alignK2,
550 alignMinid1, alignMinid2, alignMM1, alignMM2, overwrite, ordered);
551 sidechannel.start();
552 }else {
553 sidechannel=null;
554 }
555
556 //Process the read stream
557 fillTilesInner(cris, ss);
558
559 if(verbose){outstream.println("Finished; closing streams.");}
560
561 //Close the read streams
562 errorState|=ReadWrite.closeStreams(cris);
563 if(sidechannel!=null) {errorState|=sidechannel.shutdown();}
564 }
565
566 // /** Singlethreaded version. */
567 // private void loadSam_ST(String fname) {
568 // if(fname==null || processSamMT) {return;}
569 // Timer t=new Timer();
570 // outstream.println("Loading sam file.");
571 // final SamReadStreamer ss;
572 // FileFormat ff=FileFormat.testInput(fname, FileFormat.SAM, null, true, false);
573 // final int streamerThreads=Tools.min(4, Shared.threads());
574 //
575 // ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
576 // ss.start();
577 //
578 // ListNum<Read> ln=ss.nextList();
579 // ArrayList<Read> reads=(ln==null ? null : ln.list);
580 // final IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
581 //
582 // while(ln!=null && reads!=null && reads.size()>0){
583 //
584 // for(int idx=0; idx<reads.size(); idx++){
585 // Read r=reads.get(idx);
586 // assert(r.mate==null);
587 // processSamLine(r, ihp);
588 // }
589 // ln=ss.nextList();
590 // reads=(ln==null ? null : ln.list);
591 // }
592 // t.stopAndPrint();
593 // }
594 //
595 // private void processSamLine(Read r, IlluminaHeaderParser2 ihp) {
596 // if(r==null){return;}
597 // final SamLine sl=r.samline;
598 //// if(!sl.mapped() && !sl.nextMapped()) {return;} //Probably not PhiX
599 // if(!sl.mapped()) {return;}//TODO: Track unmapped info; requires modifying dump format
600 //
601 //
602 // if(!sl.mapped() || r.bases==null || r.match==null) {return;}
603 // final int pairnum=sl.pairnum();
604 // assert(sl.strand()==r.strand());
605 //
606 //// final boolean needsFixing=(varMap!=null && Read.containsVars(r.match));
607 //
608 // if(r.shortmatch()){r.toLongMatchString(false);}
609 // final byte[] match=r.match;
610 //
611 // int subs=0, inss=0, dels=0;
612 //// final AtomicLongArray matchCounts=lane.matchCounts[pairnum];
613 //// final AtomicLongArray subCounts=lane.subCounts[pairnum];
614 // for(int mpos=0, qpos=0; mpos<match.length; mpos++){
615 // byte m=match[mpos];
616 // if(m=='m'){
617 //// matchCounts.incrementAndGet(qpos);
618 // qpos++;
619 // }else if(m=='S' || m=='N'){
620 //// subCounts.incrementAndGet(qpos);
621 // subs++;
622 // qpos++;
623 // }else if(m=='I'){
624 //// subCounts.incrementAndGet(qpos);
625 // inss++;
626 // qpos++;
627 // }else if(m=='X' || m=='Y' || m=='C'){
628 // qpos++;
629 // }else if(m=='D'){
630 // dels++;
631 // }else{
632 // assert(false) : "Unhandled symbol "+m;
633 // }
634 // }
635 //
636 // final MicroTile mt;
637 // final Lane lane;
638 // ihp.parse(r.id);
639 // final int lnum=ihp.lane(), tile=ihp.tile(), x=ihp.xPos(), y=ihp.yPos();
640 // synchronized(flowcell) {
641 // lane=flowcell.getLane(lnum);
642 // mt=lane.getMicroTile(tile, x, y);
643 // }
644 //
645 // synchronized(mt) {
646 // mt.alignedReadCount++;
647 // mt.alignedBaseCount+=r.countAlignedBases();
648 // mt.readErrorCount+=((subs+inss+dels>0) ? 1 : 0);
649 // mt.baseErrorCount+=(subs+inss);
650 // mt.readInsCount+=(inss>0 ? 1 : 0);
651 // mt.readDelCount+=(dels>0 ? 1 : 0);
652 // }
653 // }
654
655 //This version is not really any faster,
656 //though it does use 15% less CPU-time.
657 private void processSamLine(SamLine sl, IlluminaHeaderParser2 ihp) {
658 if(sl==null){return;}
659 // if(!sl.mapped() && !sl.nextMapped()) {return;} //Probably not PhiX
660 if(!sl.mapped()) {return;}//TODO: Track unmapped info; requires modifying dump format
661
662 if(!sl.mapped() || sl.seq==null || !sl.hasCigar()) {return;}
663 final int pairnum=sl.pairnum();
664
665 // final boolean needsFixing=(varMap!=null && Read.containsVars(r.match));
666
667 final byte[] shortmatch=sl.toShortMatch(false);
668 final byte[] match=Read.toLongMatchString(shortmatch);
669
670 int subs=0, inss=0, dels=0;
671 //Atomics are too slow here
672 // final AtomicLongArray matchCounts=lane.matchCounts[pairnum];
673 // final AtomicLongArray subCounts=lane.subCounts[pairnum];
674 for(int mpos=0, qpos=0; mpos<match.length; mpos++){
675 byte m=match[mpos];
676 if(m=='m'){
677 // matchCounts.incrementAndGet(qpos);
678 qpos++;
679 }else if(m=='S' || m=='N'){
680 // subCounts.incrementAndGet(qpos);
681 subs++;
682 qpos++;
683 }else if(m=='I'){
684 // subCounts.incrementAndGet(qpos);
685 inss++;
686 qpos++;
687 }else if(m=='X' || m=='Y' || m=='C'){
688 qpos++;
689 }else if(m=='D'){
690 dels++;
691 }else{
692 assert(false) : "Unhandled symbol "+m;
693 }
694 }
695
696 final MicroTile mt;
697 final Lane lane;
698 ihp.parse(sl.qname);
699 final int lnum=ihp.lane(), tile=ihp.tile(), x=ihp.xPos(), y=ihp.yPos();
700 synchronized(flowcell) {
701 lane=flowcell.getLane(lnum);
702 mt=lane.getMicroTile(tile, x, y);
703 }
704
705 synchronized(mt) {
706 mt.alignedReadCount++;
707 mt.alignedBaseCount+=Read.countAlignedBases(match);
708 mt.readErrorCount+=((subs+inss+dels>0) ? 1 : 0);
709 mt.baseErrorCount+=(subs+inss);
710 mt.readInsCount+=(inss>0 ? 1 : 0);
711 mt.readDelCount+=(dels>0 ? 1 : 0);
712 }
713 }
714
715 /** Create read streams and process all data */
716 void processReads(Timer t){
717
718 if(ffout1!=null || ffoutbad!=null || coordsOut!=null){
719 Timer t2=new Timer();
720 outstream.print("Filtering reads:\t");
721
722 //Create a read input stream
723 final ConcurrentReadInputStream cris;
724 {
725 Read.VALIDATE_IN_CONSTRUCTOR=true;
726 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
727 cris.start(); //Start the stream
728 if(verbose){outstream.println("Started cris");}
729 }
730 boolean paired=cris.paired();
731 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
732
733 //Optionally read output streams
734 final ConcurrentReadOutputStream ros, rosb;
735 final int buff=4;
736 if(ffout1!=null){
737 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, buff, null, false);
738 ros.start(); //Start the stream
739 }else{ros=null;}
740
741 if(ffoutbad!=null){
742 rosb=ConcurrentReadOutputStream.getStream(ffoutbad, null, null, null, buff, null, false);
743 rosb.start(); //Start the stream
744 }else{rosb=null;}
745
746 final ByteStreamWriter coords=(coordsOut==null ? null :
747 ByteStreamWriter.makeBSW(coordsOut, overwrite, append, true));
748
749 //Process the read stream
750 processInner(cris, ros, rosb, coords);
751
752 if(verbose){outstream.println("Finished; closing streams.");}
753
754 //Close the read streams
755 errorState|=ReadWrite.closeStreams(cris, ros, rosb);
756
757 if(coords!=null) {
758 errorState=coords.poisonAndWait()|errorState;
759 }
760
761 t2.stop();
762 outstream.println(t2);
763 }
764
765 //Report timing and results
766 {
767 t.stop();
768 lastReadsOut=readsProcessed-readsDiscarded;
769 outstream.println();
770 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
771
772 if(ffout1!=null || ffoutbad!=null || coordsOut!=null){
773
774 String rpstring=Tools.padKMB(readsDiscarded, 8);
775 String bpstring=Tools.padKMB(basesDiscarded, 8);
776 String gpstring=Tools.padKMB(gsTransformedToN, 8);
777 outstream.println();
778 outstream.println("Reads Discarded: "+rpstring+" \t"+Tools.format("%.3f%%", readsDiscarded*100.0/readsProcessed));
779 outstream.println("Bases Discarded: "+bpstring+" \t"+Tools.format("%.3f%%", basesDiscarded*100.0/basesProcessed));
780 if(gToN){outstream.println("Gs Masked By N: "+gpstring+" \t"+Tools.format("%.3f%%", gsTransformedToN*100.0/basesProcessed));}
781 outstream.println();
782 }
783 }
784
785 //Throw an exception of there was an error in a thread
786 if(errorState){
787 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
788 }
789 }
790
791 /** Iterate through the reads */
792 void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros,
793 final ConcurrentReadOutputStream rosb, final ByteStreamWriter coords){
794
795 //Do anything necessary prior to processing
796 readsProcessed=0;
797 basesProcessed=0;
798 final IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
799 final ByteBuilder bb=new ByteBuilder();
800 {
801 //Grab the first ListNum of reads
802 ListNum<Read> ln=cris.nextList();
803 //Grab the actual read list from the ListNum
804 ArrayList<Read> reads=(ln!=null ? ln.list : null);
805
806 //Check to ensure pairing is as expected
807 if(reads!=null && !reads.isEmpty()){
808 Read r=reads.get(0);
809 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
810 }
811
812 //As long as there is a nonempty read list...
813 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
814 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
815
816 ArrayList<Read> keepList=new ArrayList<Read>(reads.size());
817 ArrayList<Read> tossList=new ArrayList<Read>(4);
818
819 //Loop through each read in the list
820 for(int idx=0; idx<reads.size(); idx++){
821 final Read r1=reads.get(idx);
822 final Read r2=r1.mate;
823
824 //Track the initial length for statistics
825 final int initialLength1=r1.length();
826 final int initialLength2=(r1.mateLength());
827
828 //Increment counters
829 readsProcessed+=r1.pairCount();
830 basesProcessed+=initialLength1+initialLength2;
831
832 boolean keep=processReadPair(r1, r2);
833 if(keep){
834 keepList.add(r1);
835 }else{
836 tossList.add(r1);
837 readsDiscarded+=r1.pairCount();
838 basesDiscarded+=initialLength1+initialLength2;
839 }
840 }
841
842 //Output reads to the output stream
843 if(ros!=null){ros.add(keepList, ln.id);}
844 if(rosb!=null){rosb.add(tossList, ln.id);}
845 if(coords!=null) {
846 bb.clear();
847 for(Read r : tossList) {
848 ihp.parse(r);
849 ihp.appendCoordinates(bb);
850 bb.nl();
851 }
852 if(!bb.isEmpty()) {coords.print(bb);}
853 }
854
855 //Notify the input stream that the list was used
856 cris.returnList(ln);
857 if(verbose){outstream.println("Returned a list.");}
858
859 //Fetch a new list
860 ln=cris.nextList();
861 reads=(ln!=null ? ln.list : null);
862 }
863
864 //Notify the input stream that the final list was used
865 if(ln!=null){
866 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
867 }
868 }
869
870 //Do anything necessary after processing
871
872 }
873
874 /** Iterate through the reads */
875 public void loadKmersInner(final ConcurrentReadInputStream cris){
876
877 bloomFilter=new BloomFilter(k, k, cbits, hashes, 1, true, false, true, 0.7f);
878
879 {
880 //Grab the first ListNum of reads
881 ListNum<Read> ln=cris.nextList();
882 //Grab the actual read list from the ListNum
883 ArrayList<Read> reads=(ln!=null ? ln.list : null);
884
885 //Check to ensure pairing is as expected
886 if(reads!=null && !reads.isEmpty()){
887 Read r=reads.get(0);
888 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
889 }
890
891 LongList kmers=new LongList(300);
892 //As long as there is a nonempty read list...
893 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
894 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
895
896 for(int idx=0; idx<reads.size(); idx++){
897 final Read r1=reads.get(idx);
898 final Read r2=r1.mate;
899
900 loadKmers(r1, kmers);
901 loadKmers(r2, kmers);
902 }
903
904 //Notify the input stream that the list was used
905 cris.returnList(ln);
906 if(verbose){outstream.println("Returned a list.");}
907
908 //Fetch a new list
909 ln=cris.nextList();
910 reads=(ln!=null ? ln.list : null);
911 }
912
913 //Notify the input stream that the final list was used
914 if(ln!=null){
915 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
916 }
917 }
918 }
919
920 private void loadKmers(Read r, LongList kmers) {
921 if(r==null || r.length()<k) {return;}
922 // if(!randy.nextBoolean()) {return;}//Speed optimization, I guess
923
924 kmers.clear();
925 BloomFilter.toKmers(r, kmers, k, 0, 0, true);
926 final int idmod=(int)((r.numericID+3)&idmask_write);
927 for(int i=0; i<kmers.size; i++) {
928 if((i&idmask_write)==idmod) {
929 long kmer=kmers.array[i];
930 bloomFilter.filter.increment(kmer);
931 }
932 }
933 }
934
935 /** Iterate through the reads */
936 public void fillTilesInner(final ConcurrentReadInputStream cris, final SamLineStreamer ss){
937 Timer t2=new Timer();
938
939 if(merge && loadKmers) {fillThreads=Tools.max(fillThreads, fillThreadsM);}
940 fillThreads=Tools.min(fillThreads, Shared.threads());
941 outstream.print("Filling tiles with "+fillThreads+" threads: \t");
942 spawnThreads(cris, ss);
943
944 t2.stop();
945 outstream.println(t2);
946 }
947
948 private void processTileKmers(Read r, IntList klist, IntList blist) {
949 fillDepthList(r, klist);
950 if(smoothDepths>3) {smooth5(klist);}
951 else if(smoothDepths>=3) {smooth3(klist);}
952 if(deblurDepths) {deblur(klist, blist);}
953 }
954
955 //Samples all kmers
956 private void fillDepthList(Read r, IntList depths) {
957 if(r==null || r.length()<k) {return;}
958 final byte[] bases=r.bases;
959 final int shift=2*k;
960 final int shift2=shift-2;
961 final long mask=(-1L)>>>(64-shift);
962
963 long kmer=0, rkmer=0;
964
965 depths.clear();
966
967 final int idmod=(int)(r.numericID&idmask_read);
968
969 //TODO: Debranch using 2 loops; one for 1st k-1 bases, and one for the rest.
970 for(int i=0, len=0; i<bases.length; i++) {
971 final byte b=bases[i];
972 final long x=AminoAcid.baseToNumber[b];
973 final long x2=AminoAcid.baseToComplementNumber[b];
974 kmer=((kmer<<2)|x)&mask;
975 rkmer=x<0 ? 0 : ((rkmer>>>2)|(x2<<shift2))&mask;
976
977 len=(x<0 ? 0 : len+1);
978 rkmer=(x<0 ? 0 : rkmer);//is this necessary? TODO: Check.
979 // if(x<0){len=0; rkmer=0;}else{len++;}//old branchy version
980 if(i>=k && ((i&idmask_read)==idmod)) {
981 final long key=toKey(kmer, rkmer);
982 final int value=(len>=k ? bloomFilter.getCount(key) : 0);
983 depths.add(value);
984 }
985 }
986 }
987
988 private void smooth3(IntList list) {
989 if(list.size<3) {return;}
990 final int max=list.size-1;
991 {
992 int a=list.get(0), b=list.get(1), c=list.get(2);
993 a=Tools.min(a, b, c);
994 list.set(0, a);
995 }
996 {
997 int a=list.get(max), b=list.get(max-1), c=list.get(max-2);
998 a=Tools.min(a, b, c);
999 list.set(0, a);
1000 }
1001 for(int i=1; i<max; i++) {
1002 int a=list.get(i-1), b=list.get(i), c=list.get(i+1);
1003 list.set(i, Tools.min(b, Tools.max(a, c)));
1004 }
1005 }
1006
1007 private void smooth5(IntList list) {
1008 if(list.size<5) {return;}
1009 final int max=list.size-1;
1010 {
1011 int a=list.get(0), b=list.get(1), c=list.get(2), d=list.get(3);
1012 a=Tools.min(a, b, c);
1013 b=Tools.min(b, Tools.max(a, Tools.min(c, d)));
1014 list.set(0, a);
1015 list.set(1, b);
1016 }
1017 {
1018 int a=list.get(max), b=list.get(max-1), c=list.get(max-2), d=list.get(max-3);
1019 a=Tools.min(a, b, c);
1020 b=Tools.min(b, Tools.max(a, Tools.min(c, d)));
1021 list.set(0, a);
1022 list.set(1, b);
1023 }
1024 for(int i=2; i<max-1; i++) {
1025 int a=list.get(i-2), b=list.get(i-1), c=list.get(i), d=list.get(i+1), e=list.get(i+2);
1026 int left=Tools.min(a, b);
1027 int right=Tools.min(d, e);
1028 list.set(i, Tools.min(c, Tools.max(left, right)));
1029 }
1030 }
1031
1032 void deblur(IntList klist, IntList blist) {
1033 blist.clearFull();
1034 blist.set(klist.size+k-1, 0);
1035 for(int i=0; i<klist.size; i++) {
1036 int kdepth=klist.get(i);
1037 //Since max is only 3 this could be much more efficient, without a double loop
1038 if(kdepth>0) {
1039 for(int j=i, max=i+k; j<max; j++) {
1040 blist.set(j, Tools.max(blist.get(i), kdepth));
1041 }
1042 }
1043 }
1044 }
1045
1046 // //Samples multiple kmers
1047 // private void processTileKmersSampled(Read r, MicroTile mt, int samples) {
1048 // if(r.length()<=3*k+1) {samples=1;}
1049 // samples=Tools.min(samples, r.length()-k2);
1050 // final int cutoff=(kmersPerRead<1 ? 2 : 1);
1051 //
1052 // long depthSum=0;
1053 // for(int i=0; i<samples; i++) {
1054 // int value=getKmerCount(r.bases, getPos(r.numericID+74+k3*i, r.length()));
1055 // depthSum+=value;
1056 // if(value>=cutoff) {mt.hits++;}
1057 // else {mt.misses++;}
1058 // }
1059 // mt.depthSum+=depthSum;
1060 // }
1061 //
1062 // private int getKmerCount(byte[] bases, int pos) {
1063 // final int lim=bases.length-k2;
1064 // pos=pos%(bases.length-k2);
1065 // assert(pos>=0 && pos<=lim);
1066 // final long kmer=toKmer(bases, pos, k);
1067 // if(kmer<0) {return 0;}
1068 // final long key=toKey(kmer);
1069 // final int value=bloomFilter.getCount(key);
1070 //// if(maxReads==1) {System.err.println("Got "+value+" for kmer "+key);}
1071 // return value;
1072 // }
1073 //
1074 // private int getPos(long id, int len) {
1075 // return (deterministic ? (int)((id)%(len-k2)) : randy.nextInt(len-k2));
1076 // }
1077
1078 private final long toKey(long kmer) {
1079 return Tools.max(kmer, AminoAcid.reverseComplementBinaryFast(kmer, k));
1080 // return (kmersPerRead==1 || kmer==-1 ? kmer :
1081 // Tools.max(kmer, AminoAcid.reverseComplementBinaryFast(kmer, k)));
1082 }
1083
1084 private final long toKey(long kmer, long rkmer) {
1085 return Tools.max(kmer, rkmer);
1086 }
1087
1088 /*--------------------------------------------------------------*/
1089 /*---------------- Inner Methods ----------------*/
1090 /*--------------------------------------------------------------*/
1091
1092 boolean processReadPair(final Read r1, final Read r2){
1093 boolean passes=processReadPair_inner(r1, r2);
1094 if(passes){return true;}
1095 if(trimq>0){
1096 TrimRead.trimFast(r1, trimLeft, trimRight, trimq, trimE, 0);
1097 if(r2!=null){TrimRead.trimFast(r2, trimLeft, trimRight, trimq, trimE, 0);}
1098 return r1.length()>=minlen && (r2==null || r2.length()>=minlen);
1099 }else{
1100 return false;
1101 }
1102 }
1103
1104 /**
1105 * Process a single read pair.
1106 * @param r1 Read 1
1107 * @param r2 Read 2 (may be null)
1108 * @return True if the reads should be kept, false if they should be discarded.
1109 */
1110 boolean processReadPair_inner(final Read r1, final Read r2){
1111
1112 MicroTile mt=flowcell.getMicroTile(r1.id);
1113 if(mt==null){
1114 if(!warned){
1115 outstream.println("\nWarning - a read was found with no corresponding MicroTile:\n"+r1.id);
1116 warned=true;
1117 }
1118 return true;
1119 }
1120 if(mt.discard<discardLevel){return true;}
1121 if(!discardOnlyLowQuality){return false;}
1122
1123 if(shouldDiscard(r1, mt)) {return false;}
1124 if(gToN){gsTransformedToN+=doGToN(r1, mt);}
1125
1126 if(shouldDiscard(r2, mt)) {return false;}
1127 if(gToN){gsTransformedToN+=doGToN(r2, mt);}
1128
1129 return true;
1130 }
1131
1132 private boolean shouldDiscard(Read r, MicroTile mt) {
1133 if(r==null || r.length()<1) {return false;}
1134 final int len=r.length();
1135 double qual=r.avgQualityByProbabilityDouble(true, len);
1136 double prob=100*r.probabilityErrorFree(true, len);
1137 if(qual<=flowcell.avgQuality-(dmult*TileDump.qDeviations*flowcell.stdQuality)){return true;}
1138 if(prob<=flowcell.avgErrorFree-(dmult*TileDump.eDeviations*flowcell.stdErrorFree)){return true;}
1139 if(PolyFilter.polymerLen(r.bases, (byte)'G', 0.16f)>15) {return true;}
1140 if(discardG && shouldDiscardG(r, mt)){return true;}
1141 return false;
1142 }
1143
1144 private boolean shouldDiscardG(Read r, MicroTile mt){
1145 final byte[] bases=r.bases;
1146 final float[] gArray=mt.tracker.cycleAverages[2];
1147
1148 final float thresh=(float)(flowcell.avgG+Tools.max(TileDump.gDeviations*flowcell.stdG,
1149 flowcell.avgG*TileDump.gFraction, TileDump.gAbs));
1150 for(int i=0; i<bases.length; i++){
1151 byte b=bases[i];
1152 if(b=='G' && gArray[i]>thresh){
1153 return true;
1154 }
1155 }
1156 return false;
1157 }
1158
1159 private int doGToN(Read r, MicroTile mt){
1160 if(r==null || r.length()<1) {return 0;}
1161 final byte[] bases=r.bases;
1162 final byte[] quals=r.quality;
1163 final float[] gArray=mt.tracker.cycleAverages[2];
1164
1165 final float thresh=(float)(flowcell.avgG+Tools.max(TileDump.gDeviations*flowcell.stdG,
1166 flowcell.avgG*TileDump.gFraction, TileDump.gAbs));
1167 int changes=0;
1168 for(int i=0; i<bases.length; i++){
1169 byte b=bases[i];
1170 if(b=='G' && gArray[i]>thresh){
1171 bases[i]='N';
1172 changes++;
1173 if(quals!=null){quals[i]=0;}
1174 }
1175 }
1176 return changes;
1177 }
1178
1179 /*--------------------------------------------------------------*/
1180 /*---------------- Helper Methods ----------------*/
1181 /*--------------------------------------------------------------*/
1182
1183 /**
1184 * Generate a kmer from specified start location
1185 * @param bases
1186 * @param start
1187 * @param klen kmer length
1188 * @return kmer
1189 */
1190 private static final long toKmer(final byte[] bases, final int start, final int klen){
1191 final int stop=start+klen;
1192 assert(stop<=bases.length) : klen+", "+bases.length;
1193 long kmer=0;
1194
1195 for(int i=start; i<stop; i++){
1196 final byte b=bases[i];
1197 final long x=Dedupe.baseToNumber[b];
1198 kmer=((kmer<<2)|x);
1199 }
1200 return kmer;
1201 }
1202
1203 /*--------------------------------------------------------------*/
1204 /*---------------- Barcodes ----------------*/
1205 /*--------------------------------------------------------------*/
1206
1207 BarcodeStats loadBarcodes(String expectedBarcodesFile) {
1208 if(delimiter<0) {
1209 delimiter=(byte)ffin1.barcodeDelimiter();
1210 barcodesPerRead=ffin1.barcodesPerRead();
1211 }
1212 BarcodeStats bs=new BarcodeStats(delimiter, barcodesPerRead, extin);
1213 if(bs.length1<1 && bs.length2<1) {
1214 bs.length1=ffin1.barcodeLength(1);
1215 bs.length2=ffin1.barcodeLength(2);
1216 }
1217 if(expectedBarcodesFile!=null) {
1218 bs.loadBarcodeList(expectedBarcodesFile, barcodesPerRead>1 ? delimiter : 0, false, false);
1219 }
1220 return bs;
1221 }
1222
1223 private static void dumpBarcodes(Collection<AtomicStringNum> counts, String fname, boolean overwrite) {
1224 System.err.println("Writing barcode counts.");
1225 if(fname==null || counts==null) {return;}
1226 ArrayList<AtomicStringNum> list=new ArrayList<AtomicStringNum>(counts);
1227 Collections.sort(list);
1228 Collections.reverse(list);
1229 long sum=0;
1230 for(AtomicStringNum asn : list) {sum+=asn.n.get();}
1231 ByteStreamWriter bsw=ByteStreamWriter.makeBSW(fname, overwrite, false, true);
1232 bsw.print("#Barcodes\t").print(sum).nl();
1233 bsw.print("#Unique\t").print(list.size()).nl();
1234 bsw.print("#Code\tCount\n");
1235 for(AtomicStringNum count : list) {
1236 bsw.print(count.s).tab().print(count.n.get()).nl();
1237 }
1238 bsw.poisonAndWait();
1239 }
1240
1241 /*--------------------------------------------------------------*/
1242 /*---------------- Thread Management ----------------*/
1243 /*--------------------------------------------------------------*/
1244
1245 /** Spawn process threads */
1246 private void spawnThreads(final ConcurrentReadInputStream cris, final SamLineStreamer ss){
1247
1248 //Do anything necessary prior to processing
1249
1250 //Increases concurrency by making flowcell copies
1251 //2 seems to be sufficient when merging is used.
1252 FlowCell[] fca=new FlowCell[Tools.mid(1, (merge || loadKmers ? 2 : 3), (fillThreads+4)/8)];
1253 fca[0]=flowcell;
1254 for(int i=1; i<fca.length; i++) {fca[i]=new FlowCell(k);}
1255
1256 //Fill a list with ProcessThreads
1257 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(fillThreads);
1258 for(int i=0; i<fillThreads; i++){
1259 alpt.add(new ProcessThread(cris, ss, i, fca[(i%fca.length)]));
1260 }
1261 //Start the threads and wait for them to finish
1262 boolean success=ThreadWaiter.startAndWait(alpt, this);
1263 errorState&=!success;
1264
1265 //Do anything necessary after processing
1266
1267 //Combine flowcell copies
1268 synchronized(flowcell) {
1269 for(int i=1; i<fca.length; i++) {
1270 synchronized(fca[i]) {
1271 flowcell.add(fca[i]);
1272 }
1273 }
1274 }
1275 }
1276
1277 @Override
1278 public final void accumulate(ProcessThread pt){
1279 synchronized(pt) {
1280 readsProcessed+=pt.readsProcessedT;
1281 basesProcessed+=pt.basesProcessedT;
1282 errorState|=(!pt.success);
1283 synchronized(flowcell) {
1284 flowcell.xMin=(flowcell.xMin<0 ? pt.xmin : Tools.min(pt.xmin, flowcell.xMin));
1285 flowcell.xMax=(flowcell.xMax<0 ? pt.xmax : Tools.max(pt.xmax, flowcell.xMax));
1286 flowcell.yMin=(flowcell.yMin<0 ? pt.ymin : Tools.min(pt.ymin, flowcell.yMin));
1287 flowcell.yMax=(flowcell.yMax<0 ? pt.ymax : Tools.max(pt.ymax, flowcell.yMax));
1288 flowcell.tMin=(flowcell.tMin<0 ? pt.tmin : Tools.min(pt.tmin, flowcell.tMin));
1289 flowcell.tMax=(flowcell.tMax<0 ? pt.tmax : Tools.max(pt.tmax, flowcell.tMax));
1290 if(pt.flowcellName!=null) {
1291 assert(flowcell.name==null || flowcell.name.equals(pt.flowcellName));
1292 flowcell.name=pt.flowcellName;
1293 }
1294 // for(Lane lane : flowcell.lanes) {
1295 // if(lane!=null) {
1296 // for(int pairnum=0; pairnum<2; pairnum++) {
1297 // long[] counts=pt.laneDepthCounts[lane.lane][pairnum];
1298 // long[] sums=pt.laneDepthSums[lane.lane][pairnum];
1299 // for(int i=0; i<counts.length; i++) {
1300 // lane.depthCounts[pairnum].addAndGet(i, counts[i]);
1301 // lane.depthSums[pairnum].addAndGet(i, sums[i]);
1302 // }
1303 // }
1304 // }
1305 // }
1306 }
1307 }
1308 }
1309
1310 @Override
1311 public final boolean success(){return !errorState;}
1312 @Override
1313 public final ReadWriteLock rwlock() {return rwlock;}
1314 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
1315
1316 class ProcessThread extends Thread {
1317
1318 //Constructor
1319 ProcessThread(final ConcurrentReadInputStream cris_, final SamLineStreamer ss_, final int tid_, final FlowCell flowcell_){
1320 cris=cris_;
1321 ss=ss_;
1322 tid=tid_;
1323 flowcellT=flowcell_;
1324 }
1325
1326 //Called by start()
1327 @Override
1328 public void run(){
1329 //Do anything necessary prior to processing
1330
1331 //Process the reads
1332 processInner();
1333
1334 //Do anything necessary after processing
1335
1336 //Indicate successful exit status
1337 success=true;
1338 }
1339
1340 /** Iterate through the reads */
1341 void processInner(){
1342
1343 //Grab the first ListNum of reads
1344 ListNum<Read> ln=cris.nextList();
1345
1346 //As long as there is a nonempty read list...
1347 while(ln!=null && ln.size()>0){
1348 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
1349
1350 processList(ln);
1351
1352 //Notify the input stream that the list was used
1353 cris.returnList(ln);
1354 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
1355
1356 //Fetch a new list
1357 ln=cris.nextList();
1358 }
1359
1360 //Notify the input stream that the final list was used
1361 if(ln!=null){
1362 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
1363 }
1364
1365 if(ss!=null) {processSam();}
1366 }
1367
1368 void processList(ListNum<Read> ln){
1369
1370 //Grab the actual read list from the ListNum
1371 final ArrayList<Read> reads=ln.list;
1372
1373 //Loop through each read in the list
1374 for(int idx=0; idx<reads.size(); idx++){
1375 final Read r1=reads.get(idx);
1376 final Read r2=r1.mate;
1377
1378 //Validate reads in worker threads
1379 if(!r1.validated()){r1.validate(true);}
1380 if(r2!=null && !r2.validated()){r2.validate(true);}
1381
1382 //Track the initial length for statistics
1383 final int initialLength1=r1.length();
1384 final int initialLength2=r1.mateLength();
1385
1386 //Increment counters
1387 readsProcessedT+=r1.pairCount();
1388 basesProcessedT+=initialLength1+initialLength2;
1389
1390 processReadPair(r1, r2);
1391 }
1392 if(sidechannel!=null) {sidechannel.writeByStatus(reads, ln.id);}
1393 }
1394
1395 /**
1396 * Process a read or a read pair.
1397 * @param r1 Read 1
1398 * @param r2 Read 2 (may be null)
1399 */
1400 void processReadPair(final Read r1, final Read r2){
1401 final int cutoff=(idmask_write<=3 && cbits>1) ? 2 : 1;
1402 if(recalibrate) {
1403 CalcTrueQuality.recalibrate(r1);
1404 CalcTrueQuality.recalibrate(r2);
1405 }
1406
1407 ihp.parse(r1.id);
1408 final int lnum=ihp.lane(), tile=ihp.tile(), x=ihp.xPos(), y=ihp.yPos();
1409 xmin=Tools.min(x, xmin);
1410 xmax=Tools.max(x, xmax);
1411 ymin=Tools.min(y, ymin);
1412 ymax=Tools.max(y, ymax);
1413 tmin=Tools.min(tile, tmin);
1414 tmax=Tools.max(tile, tmax);
1415 if(flowcellName==null) {
1416 flowcellName=ihp.machine()+":"+ihp.run()+":"+ihp.flowcell();
1417 }
1418
1419 long hits1=0, hits2=0, misses=0, depthSum=0;
1420 if(loadKmers){//All kmer processing is outside of the sync block
1421 processTileKmers(r1, kmerDepths0, baseDepths0);
1422 processTileKmers(r2, kmerDepths1, baseDepths1);
1423
1424 IntList list0=(deblurDepths ? baseDepths0 : kmerDepths0);
1425 // long[] counts0=laneDepthCounts[lnum][0];
1426 // long[] sums0=laneDepthSums[lnum][0];
1427 for(int i=0; i<list0.size; i++) {
1428 int d=list0.get(i);
1429 int hit=(d>=cutoff ? 1 : 0);
1430 hits1+=hit;
1431 misses+=(hit^1);//This is clever. No conditionals!
1432 depthSum+=d;
1433 //TODO: This atomic increment is super slow; replace it with locals.
1434 // lane.depthSums[0].addAndGet(i, d);
1435 // lane.depthCounts[0].incrementAndGet(i);
1436 // counts0[i]++;
1437 // sums0[i]+=d;
1438 }
1439 // assert(sums0[0]==0) : Arrays.toString(counts0)+"\n"+Arrays.toString(sums0);
1440 IntList list1=(deblurDepths ? baseDepths1 : kmerDepths1);
1441 // long[] counts1=laneDepthCounts[lnum][1];
1442 // long[] sums1=laneDepthSums[lnum][1];
1443 for(int i=0; i<list1.size; i++) {
1444 int d=list1.get(i);
1445 int hit=(d>=cutoff ? 1 : 0);
1446 hits2+=hit;
1447 misses+=(hit^1);
1448 depthSum+=d;
1449 // lane.depthSums[1].addAndGet(i, d);
1450 // lane.depthCounts[1].incrementAndGet(i);
1451 // counts1[i]++;
1452 // sums1[i]+=d;
1453 }
1454 }
1455
1456 int merged=0;
1457 int insert=0;
1458 int overlap=0;
1459 int mergeErrors=0;
1460 if(merge && r2!=null) {
1461 if(strictmerge) {
1462 insert=BBMerge.findOverlapStrict(r1, r2, false);
1463 }else {
1464 insert=BBMerge.findOverlapLoose(r1, r2, false);
1465 }
1466 if(insert>0) {
1467 merged=2;
1468 overlap=Tools.min(insert, r1.length()+r2.length()-insert);
1469 mergeErrors=BBMerge.countErrors(r1.bases, r2.bases, insert);
1470 }else {insert=0;}
1471 }
1472
1473 if(sidechannel!=null) {
1474 sidechannel.map(r1, r2);
1475 }
1476
1477 int bchdist=0;
1478 int barcodePolymers=0;
1479 if(barcodeStats!=null) {
1480 String code=ihp.barcode();
1481 if(!barcodeStats.expectedCodeList.isEmpty()) {
1482 bchdist=barcodeStats.calcHdist(code);
1483 }
1484 barcodePolymers=Barcode.countPolymers(code);
1485 // assert(barcodePolymers==0 && !code.contains("GGGGGGGG")) : code+", "+barcodePolymers;
1486 if(barcodeMap!=null) {
1487 AtomicStringNum count=barcodeMap.get(code);
1488 if(count==null) {
1489 count=new AtomicStringNum(code, 0);
1490 barcodeMap.put(code, count);
1491 }
1492 count.increment();
1493 }
1494 }
1495
1496 //Changes hits to misses if the read was a poly-G read.
1497 //Unwise for short-insert libraries.
1498 //Probably not necessary, either
1499 if(changePolyGHitsToMisses && r1!=null && r1.discarded()) {misses+=hits1; hits1=0;}
1500 if(changePolyGHitsToMisses && r2!=null && r2.discarded()) {misses+=hits2; hits2=0;}
1501
1502 final MicroTile mt;
1503 synchronized(flowcellT) {
1504 mt=flowcellT.getMicroTile(lnum, tile, x, y, true);
1505 }
1506
1507 // boolean addQuick=true; //This has a very minor impact on speed, <5% at t=64
1508 // double readQualityByProbSum=0, probErrorFreeSum=0, baseErrorProbSum=0;
1509 // int alignedReadCount=0, alignedBaseCount=0, readErrorCount=0, baseErrorCount=0, readInsCount=0, readDelCount=0;
1510 // if(addQuick){//Moving things out of the synchronized block to improve threading; changes add to addQuick
1511 // if(r1!=null) {
1512 // int len=r1.length();
1513 // readQualityByProbSum+=r1.avgQualityByProbabilityDouble(true, len);
1514 // probErrorFreeSum+=100*r1.probabilityErrorFree(true, len);
1515 // baseErrorProbSum+=r1.expectedErrors(true, len);
1516 //
1517 // if(r1.match!=null) {
1518 // int bc=r1.countAlignedBases();
1519 // if(bc>0) {
1520 // alignedReadCount++;
1521 // alignedBaseCount+=bc;
1522 // int errors=r1.countErrors();
1523 // readErrorCount+=(errors>0 ? 1 : 0);
1524 // baseErrorCount+=errors;
1525 // int[] mSCNID=Read.countMatchEvents(r1.match);
1526 // readInsCount+=(mSCNID[4]>0 ? 1 : 0);
1527 // readDelCount+=(mSCNID[5]>0 ? 1 : 0);
1528 // }
1529 // }else if(r1.samline!=null && r1.samline.mapped()) {
1530 // alignedReadCount++;
1531 // }
1532 //
1533 // }
1534 // if(r2!=null) {
1535 // int len=r2.length();
1536 // readQualityByProbSum+=r2.avgQualityByProbabilityDouble(true, len);
1537 // probErrorFreeSum+=100*r2.probabilityErrorFree(true, len);
1538 // baseErrorProbSum+=r2.expectedErrors(true, len);
1539 //
1540 // if(r2.match!=null) {
1541 // int bc=r2.countAlignedBases();
1542 // if(bc>0) {
1543 // alignedReadCount++;
1544 // alignedBaseCount+=bc;
1545 // int errors=r2.countErrors();
1546 // readErrorCount+=(errors>0 ? 1 : 0);
1547 // baseErrorCount+=errors;
1548 // int[] mSCNID=Read.countMatchEvents(r2.match);
1549 // readInsCount+=(mSCNID[4]>0 ? 1 : 0);
1550 // readDelCount+=(mSCNID[5]>0 ? 1 : 0);
1551 // }
1552 // }else if(r2.samline!=null && r2.samline.mapped()) {
1553 // alignedReadCount++;
1554 // }
1555 // }
1556 // }
1557
1558 synchronized(mt) {
1559 // if(addQuick) {
1560 // mt.addQuick(r1);
1561 // mt.addQuick(r2);
1562 //
1563 // mt.readQualityByProbSum+=readQualityByProbSum;
1564 // mt.probErrorFreeSum+=probErrorFreeSum;
1565 // mt.baseErrorProbSum+=baseErrorProbSum;
1566 //
1567 // mt.alignedReadCount+=alignedReadCount;
1568 // mt.alignedBaseCount+=alignedBaseCount;
1569 // mt.readErrorCount+=readErrorCount;
1570 // mt.baseErrorCount+=baseErrorCount;
1571 // mt.readInsCount+=readInsCount;
1572 // mt.readDelCount+=readDelCount;
1573 // }else {
1574 mt.add(r1);
1575 mt.add(r2);
1576 // }
1577
1578 mt.hits+=(hits1+hits2);
1579 mt.misses+=misses;
1580 mt.depthSum+=depthSum;
1581
1582 mt.barcodes+=barcodesPerRead;
1583 mt.barcodeHDistSum+=bchdist;
1584 mt.barcodePolymers+=barcodePolymers;
1585
1586 mt.mergedReads+=merged;
1587 mt.insertSum+=insert;
1588 mt.overlapSum+=overlap;
1589 mt.mergeErrorSum+=mergeErrors;
1590 }
1591 }
1592
1593 private void processSam() {
1594 ListNum<SamLine> ln=ss.nextLines();
1595 ArrayList<SamLine> reads=(ln==null ? null : ln.list);
1596 final IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
1597
1598 while(ln!=null && reads!=null && reads.size()>0){
1599
1600 for(int idx=0; idx<reads.size(); idx++){
1601 SamLine sl=reads.get(idx);
1602 processSamLine(sl, ihp);
1603 }
1604 ln=ss.nextLines();
1605 reads=(ln==null ? null : ln.list);
1606 }
1607 }
1608
1609 /** Number of reads processed by this thread */
1610 protected long readsProcessedT=0;
1611 /** Number of bases processed by this thread */
1612 protected long basesProcessedT=0;
1613
1614 int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, tmin=Integer.MAX_VALUE;
1615 int xmax=-1, ymax=-1, tmax=-1;
1616 public String flowcellName=null;
1617
1618 private IntList kmerDepths0=new IntList(151);
1619 private IntList kmerDepths1=new IntList(151);
1620 private IntList baseDepths0=new IntList(151);
1621 private IntList baseDepths1=new IntList(151);
1622
1623 // long[][][] laneDepthSums=new long[9][2][500];
1624 // long[][][] laneDepthCounts=new long[9][2][500];
1625
1626 private IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
1627
1628 /** True only if this thread has completed successfully */
1629 boolean success=false;
1630
1631 /** Shared input stream */
1632 private final ConcurrentReadInputStream cris;
1633 /** Optional sam input stream */
1634 private final SamLineStreamer ss;
1635 /** Thread ID */
1636 final int tid;
1637 final FlowCell flowcellT;
1638 }
1639
1640 /*--------------------------------------------------------------*/
1641 /*---------------- Fields ----------------*/
1642 /*--------------------------------------------------------------*/
1643
1644 /** Primary input file path */
1645 private String in1=null;
1646 /** Secondary input file path */
1647 private String in2=null;
1648
1649 private ArrayList<String> extra=new ArrayList<String>();
1650
1651 /** Primary output file path */
1652 private String out1=null;
1653 /** Secondary output file path */
1654 private String out2=null;
1655
1656 /** Discard output file path */
1657 private String outbad=null;
1658
1659 /** Optional aligned reads (e.g. PhiX) */
1660 private String samInput=null;
1661 private final boolean processSamMT=true;
1662
1663 /** Override input file extension */
1664 private String extin=null;
1665 /** Override output file extension */
1666 private String extout=null;
1667
1668 /*--------------------------------------------------------------*/
1669
1670 // private boolean pound=true;
1671 private String dumpOut=null;
1672 private String dumpIn=null;
1673 private String coordsOut=null;
1674
1675 /*--------------------------------------------------------------*/
1676
1677 private byte delimiter='+';
1678 private int barcodesPerRead=2;
1679 private String expectedBarcodes;
1680 private String barcodeCounts;
1681 private BarcodeStats barcodeStats;
1682
1683 private ConcurrentHashMap<String, AtomicStringNum> barcodeMap;
1684
1685 /*--------------------------------------------------------------*/
1686 /*---------------- Side Channel ----------------*/
1687 /*--------------------------------------------------------------*/
1688
1689 boolean align=false;
1690 String alignOut=null;
1691 String alignRef="phix";
1692 float alignMinid1=0.66f;
1693 float alignMinid2=0.56f;
1694 int alignK1=17; //Phix is unique down to k=13 solid; unsure about gapped
1695 int alignK2=13;
1696 int alignMM1=1;
1697 int alignMM2=1;
1698 SideChannel3 sidechannel;
1699
1700 /*--------------------------------------------------------------*/
1701
1702 /** Number of reads processed */
1703 public long readsProcessed=0;
1704 /** Number of bases processed */
1705 public long basesProcessed=0;
1706
1707 /** Number of reads discarded */
1708 public long readsDiscarded=0;
1709 /** Number of bases discarded */
1710 public long basesDiscarded=0;
1711
1712 protected long gsTransformedToN=0;
1713
1714 /** Quit after processing this many input reads; -1 means no limit */
1715 private long maxReads=-1;
1716
1717 /** Whether interleaved was explicitly set. */
1718 private boolean setInterleaved=false;
1719
1720 //Test this; may need to be higher. Was 16, now 24.
1721 //Seems unused though, since switching to a mask...
1722 //And Perlmutter seems to saturate at ~2000% CPU
1723 private int loadThreads=24;
1724 //32 was not quite enough on Perlmutter; maybe OK on Dori though
1725 //64 is not enough with merge enabled
1726 private int fillThreads=64;
1727 //128 threads only ran at 5600% utilization... may be too many.
1728 private static final int fillThreadsM=96;//threads when merge is enabled
1729 private BloomFilter bloomFilter;
1730
1731 int idmask_read=7;
1732 int idmask_write=15;
1733 private int smoothDepths=0;
1734 private boolean deblurDepths=false;
1735
1736 private boolean blurTiles=false;
1737
1738 private boolean loadKmers=true;
1739 // private int kmersPerRead=0;//for loading
1740 private float minProb=0;
1741 private boolean deterministic=true;
1742 private int cbits=2;
1743 private int hashes=2;
1744
1745 private boolean recalibrate=false;
1746 private boolean merge=false;
1747 private boolean strictmerge=false;
1748
1749 private int targetAverageReads=1600;
1750 private int targetAlignedReads=250;
1751 private int targetX=Tile.xSize;
1752 private int targetY=Tile.ySize;
1753
1754 private static final int k=31;
1755
1756 private FlowCell flowcell;
1757
1758 private boolean changePolyGHitsToMisses=false;
1759
1760 private float dmult=-0.2f;
1761
1762 private boolean discardOnlyLowQuality=true;
1763 private int discardLevel=1;
1764 private boolean gToN=false;
1765 private boolean discardG=false;
1766
1767 private int minlen=30;
1768 private float trimq=-1;
1769 private final float trimE;
1770 private boolean trimLeft=false;
1771 private boolean trimRight=true;
1772
1773 private boolean warned=false;
1774
1775 /*--------------------------------------------------------------*/
1776 /*---------------- Final Fields ----------------*/
1777 /*--------------------------------------------------------------*/
1778
1779 /** Primary input file */
1780 private final FileFormat ffin1;
1781 /** Secondary input file */
1782 private final FileFormat ffin2;
1783
1784 /** Primary output file */
1785 private final FileFormat ffout1;
1786 /** Secondary output file */
1787 private final FileFormat ffout2;
1788
1789 /** Output for discarded reads */
1790 private final FileFormat ffoutbad;
1791
1792 /*--------------------------------------------------------------*/
1793 /*---------------- Common Fields ----------------*/
1794 /*--------------------------------------------------------------*/
1795
1796 /** Number of reads output in the last run */
1797 public static long lastReadsOut;
1798 /** Print status messages to this output stream */
1799 private PrintStream outstream=System.err;
1800 /** Print verbose messages */
1801 public static boolean verbose=false;
1802 /** True if an error was encountered */
1803 public boolean errorState=false;
1804 /** Overwrite existing output files */
1805 private boolean overwrite=true;
1806 /** Append to existing output files */
1807 private boolean append=false;
1808 /** Output reads in input order (possibly todo) */
1809 private final boolean ordered=false;
1810
1811 }