Debian Codegraph @

current/jgi/KmerNormalize.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.lang.Thread.State;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashSet;
10 import java.util.List;
11 import java.util.Random;
12 import java.util.concurrent.atomic.AtomicLong;
13 import java.util.concurrent.atomic.AtomicLongArray;
14
15 import bloom.KCountArray;
16 import bloom.KmerCountAbstract;
17 import bloom.ReadCounter;
18 import dna.AminoAcid;
19 import fileIO.ByteStreamWriter;
20 import fileIO.FileFormat;
21 import fileIO.ReadWrite;
22 import fileIO.TextStreamWriter;
23 import shared.KillSwitch;
24 import shared.Parse;
25 import shared.Parser;
26 import shared.PreParser;
27 import shared.Shared;
28 import shared.Timer;
29 import shared.Tools;
30 import shared.TrimRead;
31 import sort.ReadErrorComparator;
32 import stream.ConcurrentReadInputStream;
33 import stream.ConcurrentReadOutputStream;
34 import stream.FASTQ;
35 import stream.FastaReadInputStream;
36 import stream.Read;
37 import structures.ListNum;
38 import tracker.ReadStats;
39 import ukmer.Kmer;
40
41
42 /**
43 * AKA BBNorm.
44 * Normalize depth by downsampling reads with high coverage.
45 * Uses atomic arrays for bloom filter and an atomic histogram.
46 * Succeeds KmerDownsampleAH.
47 * Includes fast error correction and keep-count-based (rather than random) normalization.
48 *
49 * @author Brian Bushnell
50 * @date May 30, 2013
51 *
52 */
53 public class KmerNormalize {
54
55 public static void main(String[] args){
56
57 {//Preparse block for help, config files, and outstream
58 PreParser pp=new PreParser(args, new Object() { }.getClass().getEnclosingClass(), false);
59 args=pp.args;
60 outstream=pp.outstream;
61 }
62
63 String in1=(args[0].indexOf("=")>0 ? null : args[0]);
64 String in2=(in1!=null && args.length>1 ? args[1] : null);
65 if(in2!=null && "null".equalsIgnoreCase(in2)){in2=null;}
66
67 {
68 if(in1!=null && !in1.contains(",")){
69 File f=new File(in1);
70 if(!f.exists() || !f.isFile()){
71 in1=null;
72 // throw new RuntimeException(reads1+" does not exist.");
73 }
74 }
75 if(in2!=null && !in2.contains(",")){
76 File f=new File(in2);
77 if(!f.exists() || !f.isFile()){
78 in2=null;
79 // throw new RuntimeException(reads2+" does not exist.");
80 }else if(in2.equalsIgnoreCase(in1)){
81 throw new RuntimeException("Both input files are the same.");
82 }
83 }
84 }
85
86 KmerCountAbstract.minQuality=5;
87 KmerCountAbstract.minProb=0.5f;
88
89 Parser parser=new Parser();
90 parser.trimq=TRIM_QUALITY;
91 parser.minReadLength=MIN_LENGTH;
92
93 int k=31;
94 int cbits=32;
95 int precbits=2;
96 int cbits1=-1;
97 int hashes=3;
98 // int matrixbits=-1;
99 long cells=-1;
100 long maxReads=-1;
101 int buildpasses=1;
102 long tablereads=-1; //How many reads to process when building the hashtable
103 int buildStepsize=4;
104
105 String outKeep1=null;
106 String outToss1=null;
107 String outLow1=null, outMid1=null, outHigh1=null, outUnc1=null;
108
109 String outKeep2=null;
110 String outToss2=null;
111 String outLow2=null, outMid2=null, outHigh2=null, outUnc2=null;
112
113 int prehashes=-1;
114 long precells=-1;
115 String khistFile=null;
116 String rhistFile=null;
117 String peakFile=null;
118 String khistFileOut=null;
119 String rhistFileOut=null;
120 String peakFileOut=null;
121 int threads=-1;
122 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
123
124 int minq=KmerCountAbstract.minQuality;
125 KmerCountAbstract.CANONICAL=true;
126 KmerCountAbstract.KEEP_DUPLICATE_KMERS=false;
127
128
129 int targetDepthF=TARGET_DEPTH_F;
130 int targetDepth1=TARGET_DEPTH_1;
131 int maxDepth=MAX_DEPTH;
132 int minDepth=MIN_DEPTH;
133 int minKmersOverMinDepth=MIN_KMERS_OVER_MIN_DEPTH;
134 float depthPercentile=DEPTH_PERCENTILE;
135
136 int passes=2;
137 boolean tossErrorReadsF=TOSS_ERROR_READS_F;
138 boolean tossErrorReads1=TOSS_ERROR_READS_1;
139 boolean discardBadOnlyF=DISCARD_BAD_ONLY_F;
140 boolean discardBadOnly1=DISCARD_BAD_ONLY_1;
141 boolean fixSpikes=FIX_SPIKES;
142 float highPercentile=HIGH_PERCENTILE;
143 float lowPercentile=LOW_PERCENTILE;
144 int errorDetectRatio=ERROR_DETECT_RATIO;
145 int hthresh=HTHRESH;
146 int lthresh=LTHRESH;
147 boolean countup=COUNTUP;
148 boolean rbb=REQUIRE_BOTH_BAD;
149 boolean setOverlap=false;
150
151
152 boolean auto=true;
153
154 List<String> extra=null;
155
156 long memory=Runtime.getRuntime().maxMemory();
157 long tmemory=Runtime.getRuntime().totalMemory();
158 // assert(false) : memory+", "+tmemory;
159
160 for(int i=(in1==null ? 0 : 1); i<args.length; i++){
161 if(args[i]==null){args[i]="null";}
162 final String arg=args[i];
163 final String[] split=arg.split("=");
164 String a=split[0].toLowerCase();
165 String b=split.length>1 ? split[1] : null;
166
167 if(Parser.parseCommonStatic(arg, a, b)){
168 if(a.equals("tbr")){//Handle conflated case
169 tossErrorReads1=tossErrorReadsF=Parse.parseBoolean(b);
170 }
171 }else if(Parser.parseZip(arg, a, b)){
172 //do nothing
173 }else if(Parser.parseQualityAdjust(arg, a, b)){
174 //do nothing
175 }else if(Parser.parseQuality(arg, a, b)){
176 //do nothing
177 }else if(Parser.parseFasta(arg, a, b)){
178 //do nothing
179 }else if(parser.parseInterleaved(arg, a, b)){
180 //do nothing
181 }else if(parser.parseTrim(arg, a, b)){
182 //do nothing
183 }else if(a.equals("keepall")){
184 KEEP_ALL=Parse.parseBoolean(b);
185 }else if(a.equals("k") || a.equals("kmer")){
186 k=Integer.parseInt(b);
187 }else if(a.equals("in") || a.equals("in1")){
188 in1=b;
189 }else if(a.equals("in2")){
190 in2=b;
191 }else if(a.equals("bits") ||a.equals("cbits") || a.equals("cellbits")){
192 cbits=Integer.parseInt(b);
193 }else if(a.equals("bits1") ||a.equals("cbits1") || a.equals("cellbits1")){
194 cbits1=Integer.parseInt(b);
195 }else if(a.equals("prefilterbits") ||a.equals("prebits")){
196 precbits=Integer.parseInt(b);
197 }else if(a.equals("histlen") ||a.equals("histogramlen")){
198 HIST_LEN_PRINT=Tools.min(Integer.MAX_VALUE, Long.parseLong(b)+1);
199 }else if(a.equals("matrixbits")){
200 int matrixbits=Integer.parseInt(b);
201 assert(matrixbits<63);
202 cells=1L<<matrixbits;
203 }else if(a.equals("cells")){
204 cells=Parse.parseKMG(b);
205 }else if(a.equals("precells") || a.equals("prefiltercells")){
206 precells=Parse.parseKMG(b);
207 prefilter=prefilter || precells!=0;
208 }else if(a.equals("prefiltersize") || a.equals("prefilterfraction")){
209 prefilterFraction=Double.parseDouble(b);
210 prefilter=prefilterFraction>0;
211 }else if(a.equals("minq") || a.equals("minqual")){
212 minq=Byte.parseByte(b);
213 }else if(a.equals("zerobin")){
214 ZERO_BIN=Parse.parseBoolean(b);
215 }else if(a.equals("deterministic") || a.equals("dr") || a.equals("det")){
216 boolean x=Parse.parseBoolean(b);
217 DETERMINISTIC=x;
218 }else if(a.equals("minprob")){
219 KmerCountAbstract.minProb=Float.parseFloat(b);
220 assert(KmerCountAbstract.minProb<1) : "minprob must be less than 1. At 1, even kmers with 100% probablity of being error-free will be discarded.";
221 }else if(a.equals("hashes")){
222 hashes=Integer.parseInt(b);
223 }else if(a.equals("prehashes") || a.equals("prefilterhashes")){
224 prehashes=Integer.parseInt(b);
225 prefilter=prefilter || prehashes!=0;
226 }else if(a.equals("prefilter")){
227 prefilter=Parse.parseBoolean(b);
228 }else if(a.equals("countup")){
229 countup=Parse.parseBoolean(b);
230 }else if(a.equals("stepsize") || a.equals("buildstepsize")){
231 buildStepsize=Integer.parseInt(b);
232 }else if(a.equals("passes") || a.equals("p")){
233 passes=Integer.parseInt(b);
234 assert(passes>=1 && passes<=4) : "Passes should be in range 1~4.";
235 }else if(a.equals("1pass") || a.equals("1p")){
236 passes=1;
237 }else if(a.equals("2pass") || a.equals("2p")){
238 passes=2;
239 }else if(a.equals("buildpasses")){
240 buildpasses=Integer.parseInt(b);
241 }else if(a.equals("printcoverage")){
242 assert(false) : "This is not the program you are looking for. Try KmerCoverage. Move along.";
243 }else if(a.equals("threads") || a.equals("t")){
244 threads=Integer.parseInt(b);
245 }else if(a.equals("rn") || a.equals("rename") || a.equals("renamereads")){
246 renameReads=Parse.parseBoolean(b);
247 }else if(a.equals("reads") || a.equals("maxreads")){
248 maxReads=Parse.parseKMG(b);
249 }else if(a.equals("tablereads") || a.equals("buildreads")){
250 tablereads=Parse.parseKMG(b);
251 }else if(a.equals("out") || a.equals("out1") || a.equals("outk") || a.equals("outkeep") || a.equals("outgood")){
252 outKeep1=b;
253 }else if(a.equals("outt") || a.equals("outt1") || a.equals("outtoss") || a.equals("outoss") || a.equals("outbad")){
254 outToss1=b;
255 }else if(a.equals("outl") || a.equals("outl1") || a.equals("outlow") || a.equals("outlow1")){
256 outLow1=b;
257 }else if(a.equals("outm") || a.equals("outm1") || a.equals("outmid") || a.equals("outmid1") || a.equals("outmiddle")){
258 outMid1=b;
259 }else if(a.equals("outh") || a.equals("outh1") || a.equals("outhigh") || a.equals("outhigh1")){
260 outHigh1=b;
261 }else if(a.equals("outu") || a.equals("outu1") || a.equals("outuncorrected")){
262 outUnc1=b;
263 }else if(a.equals("out2") || a.equals("outk2") || a.equals("outkeep2") || a.equals("outgood2")){
264 outKeep2=b;
265 }else if(a.equals("outt2") || a.equals("outtoss2") || a.equals("outoss2") || a.equals("outbad2")){
266 outToss2=b;
267 }else if(a.equals("outl2") || a.equals("outlow2")){
268 outLow2=b;
269 }else if(a.equals("outm2") || a.equals("outmid2") || a.equals("outmiddle2")){
270 outMid2=b;
271 }else if(a.equals("outh2") || a.equals("outhigh2")){
272 outHigh2=b;
273 }else if(a.equals("outu2") || a.equals("outuncorrected2")){
274 outUnc2=b;
275 }else if(a.equals("lbd") || a.equals("lowbindepth") || a.equals("lowerlimit")){
276 LOW_BIN_DEPTH=Integer.parseInt(b);
277 }else if(a.equals("hbd") || a.equals("highbindepth") || a.equals("upperlimit")){
278 HIGH_BIN_DEPTH=Integer.parseInt(b);
279 }else if(a.equals("hist") || a.equals("histin") || a.equals("inhist") || a.equals("khist")){
280 khistFile=b;
281 }else if(a.equals("rhist")){
282 rhistFile=b;
283 }else if(a.equals("histout") || a.equals("outhist") || a.equals("hist2") || a.equals("khistout")){
284 khistFileOut=b;
285 }else if(a.equals("rhistout")){
286 rhistFileOut=b;
287 }else if(a.equals("peaks")){
288 peakFile=b;
289 }else if(a.equals("peaksout")){
290 peakFileOut=b;
291 }else if(a.equals("verbose")){
292 verbose=Parse.parseBoolean(b);
293 }else if(a.equals("ordered") || a.equals("ord")){
294 ordered=Parse.parseBoolean(b);
295 }else if(a.equals("append") || a.equals("app")){
296 append=ReadStats.append=Parse.parseBoolean(b);
297 }else if(a.equals("overwrite") || a.equals("ow")){
298 overwrite=Parse.parseBoolean(b);
299 }else if(a.equals("auto") || a.equals("automatic")){
300 auto=Parse.parseBoolean(b);
301 }else if(a.equals("canonical")){
302 CANONICAL=KmerCountAbstract.CANONICAL=Parse.parseBoolean(b);
303 }else if(a.equals("fixspikes") || a.equals("fs")){
304 fixSpikes=Parse.parseBoolean(b);
305 }else if(a.equals("printzerocoverage") || a.equals("pzc")){
306 PRINT_ZERO_COVERAGE=Parse.parseBoolean(b);
307 }else if(a.equals("removeduplicatekmers") || a.equals("rdk")){
308 KmerCountAbstract.KEEP_DUPLICATE_KMERS=!Parse.parseBoolean(b);
309 }else if(a.equals("target") || a.equals("targetdepth") || a.equals("tgt")){
310 targetDepthF=Integer.parseInt(b);
311 }else if(a.equals("target1") || a.equals("targetdepth1") || a.equals("tgt1")){
312 targetDepth1=Integer.parseInt(b);
313 }else if(a.equals("max") || a.equals("maxdepth")){
314 maxDepth=Integer.parseInt(b);
315 }else if(a.equals("min") || a.equals("mindepth")){
316 minDepth=Integer.parseInt(b);
317 }else if(a.equals("minkmers") || a.equals("minkmersovermindepth") || a.equals("mingoodkmersperread") || a.equals("mgkpr")){
318 minKmersOverMinDepth=Tools.max(1, Integer.parseInt(b));
319 }else if(a.equals("percentile") || a.equals("depthpercentile") || a.equals("dp")){
320 depthPercentile=Float.parseFloat(b);
321 if(depthPercentile>1 && depthPercentile<=100){depthPercentile/=100;}
322 assert(depthPercentile>=0 && depthPercentile<=1) : "Depth percentile must be between 0 and 100.";
323 }else if(a.equals("highdepthpercentile") || a.equals("highpercentile") || a.equals("hdp")){
324 highPercentile=Float.parseFloat(b);
325 if(highPercentile>1 && highPercentile<=100){highPercentile/=100;}
326 assert(highPercentile>=0 && highPercentile<=1) : "Depth percentile must be between 0 and 100.";
327 }else if(a.equals("lowdepthpercentile") || a.equals("lowpercentile") || a.equals("ldp")){
328 lowPercentile=Float.parseFloat(b);
329 if(lowPercentile>1 && lowPercentile<=100){lowPercentile/=100;}
330 assert(lowPercentile>=0 && highPercentile<=1) : "Depth percentile must be between 0 and 100.";
331 }else if(a.equals("targetbadpercentilelow") || a.equals("tbpl")){
332 double d=Double.parseDouble(b);
333 if(d>1 && d<=100){d/=100;}
334 assert(d>=0) : "TARGET_BAD_PERCENT_LOW must be at least 0.";
335 TARGET_BAD_PERCENT_LOW=d;
336 TARGET_BAD_PERCENT_HIGH=Tools.max(TARGET_BAD_PERCENT_HIGH, TARGET_BAD_PERCENT_LOW);
337 }else if(a.equals("targetbadpercentilehigh") || a.equals("tbph")){
338 double d=Double.parseDouble(b);
339 if(d>1 && d<=100){d/=100;}
340 assert(d>=0 && lowPercentile<=1) : "TARGET_BAD_PERCENT_HIGH must be at least 0.";
341 TARGET_BAD_PERCENT_HIGH=d;
342 TARGET_BAD_PERCENT_LOW=Tools.min(TARGET_BAD_PERCENT_HIGH, TARGET_BAD_PERCENT_LOW);
343 }else if(a.equals("errordetectratio") || a.equals("edr")){
344 errorDetectRatio=Integer.parseInt(b);
345 }else if(a.equals("errorcorrectratio") || a.equals("ecr")){
346 ERROR_CORRECT_RATIO=Integer.parseInt(b);
347 }else if(a.equals("highthresh") || a.equals("hthresh") || a.equals("ht")){
348 hthresh=Integer.parseInt(b);
349 }else if(a.equals("lowthresh") || a.equals("lthresh") || a.equals("lt")){
350 lthresh=Integer.parseInt(b);
351 }else if(a.equals("echighthresh") || a.equals("echthresh") || a.equals("echt")){
352 EC_HTHRESH=Integer.parseInt(b);
353 }else if(a.equals("eclowthresh") || a.equals("eclthresh") || a.equals("eclt")){
354 EC_LTHRESH=Integer.parseInt(b);
355 }else if(a.equals("markerrors") || a.equals("markonly") || a.equals("meo")){
356 MARK_ERRORS_ONLY=Parse.parseBoolean(b);
357 }else if(a.equals("markuncorrectableerrors") || a.equals("markuncorrectable") || a.equals("mue")){
358 MARK_UNCORRECTABLE_ERRORS=Parse.parseBoolean(b);
359 }else if(a.equals("tam") || a.equals("trimaftermarking")){
360 TRIM_AFTER_MARKING=Parse.parseBoolean(b);
361 }else if(a.equals("markwith1") || a.equals("markwithone") || a.equals("mw1")){
362 MARK_WITH_1=Parse.parseBoolean(b);
363 // TrimRead.PROB1=10;
364 }else if(a.equals("aec") || a.equals("aecc") || a.equals("aggressiveerrorcorrection")){
365 boolean x=Parse.parseBoolean(b);
366 if(x){
367 USE_ECC1=USE_ECCF=true;
368 EC_HTHRESH=Tools.min(EC_HTHRESH, 16);
369 EC_LTHRESH=Tools.max(EC_LTHRESH, 3);
370 ERROR_CORRECT_RATIO=Tools.min(ERROR_CORRECT_RATIO, 100);
371 MAX_ERRORS_TO_CORRECT=Tools.max(MAX_ERRORS_TO_CORRECT, 7);
372 SUFFIX_LEN=Tools.min(SUFFIX_LEN, 3);
373 PREFIX_LEN=Tools.min(PREFIX_LEN, 2);
374 }
375 }else if(a.equals("cec") || a.equals("cecc") || a.equals("conservativeerrorcorrection")){
376 boolean x=Parse.parseBoolean(b);
377 if(x){
378 USE_ECC1=USE_ECCF=true;
379 EC_HTHRESH=Tools.max(EC_HTHRESH, 30);
380 EC_LTHRESH=Tools.min(EC_LTHRESH, 1);
381 ERROR_CORRECT_RATIO=Tools.max(ERROR_CORRECT_RATIO, 170);
382 MAX_ERRORS_TO_CORRECT=Tools.min(MAX_ERRORS_TO_CORRECT, 2);
383 MAX_QUAL_TO_CORRECT=Tools.min(MAX_QUAL_TO_CORRECT, 25);
384 SUFFIX_LEN=Tools.max(SUFFIX_LEN, 4);
385 PREFIX_LEN=Tools.max(PREFIX_LEN, 4);
386 }
387 }else if(a.equals("tossbadreads") || a.equals("tosserrorreads") || a.equals("tbr") || a.equals("ter")){
388 tossErrorReads1=tossErrorReadsF=Parse.parseBoolean(b);
389 }else if(a.equals("tossbadreads2") || a.equals("tosserrorreads2") || a.equals("tbr2") || a.equals("ter2") ||
390 a.equals("tossbadreadsf") || a.equals("tosserrorreadsf") || a.equals("tbrf") || a.equals("terf")){
391 tossErrorReadsF=Parse.parseBoolean(b);
392 }else if(a.equals("tossbadreads1") || a.equals("tosserrorreads1") || a.equals("tbr1") || a.equals("ter1")){
393 tossErrorReads1=Parse.parseBoolean(b);
394 }else if(a.equals("abrc") || a.equals("addbadreadscountup")){
395 ADD_BAD_READS_COUNTUP=Parse.parseBoolean(b);
396 }else if(a.equals("discardbadonly") || a.equals("dbo")){
397 discardBadOnly1=discardBadOnlyF=Parse.parseBoolean(b);
398 }else if(a.equals("discardbadonly1") || a.equals("dbo1")){
399 discardBadOnly1=Parse.parseBoolean(b);
400 }else if(a.equals("discardbadonlyf") || a.equals("dbof") || a.equals("discardbadonly2") || a.equals("dbo2")){
401 discardBadOnlyF=Parse.parseBoolean(b);
402 }else if(a.equals("requirebothbad") || a.equals("rbb")){
403 rbb=Parse.parseBoolean(b);//Already caught by parser
404 }else if(a.equals("saverarereads") || a.equals("srr")){
405 SAVE_RARE_READS=Parse.parseBoolean(b);
406 }else if(a.equals("eccbyoverlap") || a.equals("ecco") || a.equals("overlap")){
407 if("auto".equalsIgnoreCase(b)){eccByOverlapAuto=true;}
408 else{
409 eccByOverlap=Parse.parseBoolean(b);
410 eccByOverlapAuto=false;
411 }
412 setOverlap=true;
413 }else if(a.equals("ecc")){
414 USE_ECC1=USE_ECCF=Parse.parseBoolean(b);
415 }else if(a.equals("ecc1")){
416 USE_ECC1=Parse.parseBoolean(b);
417 }else if(a.equals("ecc2") || a.equals("eccf")){
418 USE_ECCF=Parse.parseBoolean(b);
419 }else if(a.equals("ecclimit")){
420 MAX_ERRORS_TO_CORRECT=Integer.parseInt(b);
421 }else if(a.equals("eccmaxqual")){
422 MAX_QUAL_TO_CORRECT=Integer.parseInt(b);
423 }else if(a.equals("cfl")){
424 CORRECT_FROM_LEFT=Parse.parseBoolean(b);
425 }else if(a.equals("cfr")){
426 CORRECT_FROM_RIGHT=Parse.parseBoolean(b);
427 }else if(a.equals("sl") || a.equals("suflen") || a.equals("suffixlen")){
428 SUFFIX_LEN=Integer.parseInt(b);
429 }else if(a.equals("pl") || a.equals("prelen") || a.equals("prefixlen")){
430 PREFIX_LEN=Integer.parseInt(b);
431 }else if(a.equals("histcol") || a.equals("histcolumns") || a.equals("histogramcolumns")){
432 HIST_COLUMNS=Integer.parseInt(b);
433 }else if(a.equals("minheight")){
434 minHeight=Long.parseLong(b);
435 }else if(a.equals("minvolume")){
436 minVolume=Long.parseLong(b);
437 }else if(a.equals("minwidth")){
438 minWidth=Integer.parseInt(b);
439 }else if(a.equals("minpeak")){
440 minPeak=Integer.parseInt(b);
441 }else if(a.equals("maxpeak")){
442 maxPeak=Integer.parseInt(b);
443 }else if(a.equals("ploidy")){
444 ploidy=Integer.parseInt(b);
445 }else if(a.equals("maxpeakcount") || a.equals("maxpc") || a.equals("maxpeaks")){
446 maxPeakCount=Integer.parseInt(b);
447 }else if(a.equals("usetmpdir")){
448 USE_TMPDIR=Parse.parseBoolean(b);
449 }else if(a.equals("uselowerdepth") || a.equals("uld")){
450 USE_LOWER_DEPTH=Parse.parseBoolean(b);
451 }else if(a.equals("tmpdir")){
452 TMPDIR=b;
453 if(b!=null){
454 b=b.trim();
455 if(b.length()==0){b=null;}
456 else{b=(b.replace('\\', '/')+"/").replaceAll("//", "/");}
457 }
458 }else if(a.equals("extra")){
459 if(b!=null && !b.equalsIgnoreCase("null")){
460 if(new File(b).exists()){
461 extra=new ArrayList<String>();
462 extra.add(b);
463 }else{
464 extra=Arrays.asList(b.split(","));
465 }
466 }
467 }else{
468 throw new RuntimeException("Unknown parameter "+arg);
469 }
470 }
471
472 {//Process parser fields
473 Parser.processQuality(); //TODO: This may cause problems with multiple passes! Best to not change the quality.
474
475 TRIM_LEFT=parser.qtrimLeft;
476 TRIM_RIGHT=parser.qtrimRight;
477 TRIM_QUALITY=parser.trimq;
478 trimE=parser.trimE();
479 MIN_LENGTH=parser.minReadLength;
480 rbb=parser.requireBothBad;
481 }
482
483 assert(passes<2 || (outLow1==null && outMid1==null && outHigh1==null && outUnc1==null)) :
484 "\noutLow, outMid, outHigh, and outUnc don't work with multiple passes. Set passes=1 or eliminate those output streams.";
485
486 assert(in1!=null && !in1.equalsIgnoreCase("stdin") && !in1.toLowerCase().startsWith("stdin.")) :
487 "\nThis program does not allow input from standard in,\nbecause it needs to read the input multiple times.\nOnly files are permitted.";
488
489 if(MARK_ERRORS_ONLY){
490 MAX_ERRORS_TO_CORRECT=Tools.max(MAX_ERRORS_TO_CORRECT, 9999);
491 if(!USE_ECC1 && !USE_ECCF){USE_ECC1=true;}
492 }
493
494 if(!setOverlap && (USE_ECC1 || USE_ECCF)){
495 eccByOverlapAuto=true;
496 }
497
498 if(in1!=null && in1.contains("#") && !new File(in1).exists()){
499 int pound=in1.lastIndexOf('#');
500 String a=in1.substring(0, pound);
501 String b=in1.substring(pound+1);
502 in1=a+1+b;
503 in2=a+2+b;
504 }
505 if(in2!=null && (in2.contains("=") || in2.equalsIgnoreCase("null"))){in2=null;}
506 final boolean paired=(FASTQ.FORCE_INTERLEAVED || in2!=null);
507 if(in2!=null){
508 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
509 }
510 in1=Tools.fixExtension(in1);
511 in2=Tools.fixExtension(in2);
512
513 if(DETERMINISTIC){ordered=true;}
514
515 boolean ok=Tools.testOutputFiles(overwrite, append, false, outKeep1, outToss1, outKeep2, outToss2, khistFile, khistFileOut, rhistFile, rhistFileOut, peakFile, peakFileOut);
516
517 if(cbits>16 && passes>1){cbits=16;}
518
519 maxDepth=Tools.max(maxDepth, targetDepthF);
520 assert(targetDepthF>0);
521
522 assert(FastaReadInputStream.settingsOK());
523 if(k>31){CANONICAL=KmerCountAbstract.CANONICAL=false;}
524 assert(CANONICAL==KmerCountAbstract.CANONICAL);
525
526 // if(output!=null && reads1.contains(",")){
527 // throw new RuntimeException("\nLists of input files can only be used with histogram output, not full output.\n" +
528 // "Please set output=null or move the extra input files to 'extra=file1,file2,...fileN'");
529 // }
530 if(extra!=null){
531 for(String s : extra){
532 File f=new File(s);
533 if(!f.exists() || !f.isFile()){throw new RuntimeException(s+" does not exist.");}
534 assert(!s.equalsIgnoreCase(in1) && (in2==null || !s.equalsIgnoreCase(in2))) : "\nInput file "+s+" should not be included as an extra file.\n";
535 }
536 }
537
538 // outstream.println("ForceInterleaved = "+FASTQ.FORCE_INTERLEAVED);
539
540 // assert(false) : reads1+", "+reads2+", "+output;
541 // if(FASTQ.FORCE_INTERLEAVED && in2==null){
542 // outstream.println()
543 // }
544
545 if(threads<=0){
546 THREADS=Shared.threads();
547 }else{
548 THREADS=threads;
549 }
550
551 // assert(false) : THREADS;
552
553 // System.err.println("THREADS="+THREADS+", KmerCountAbstract.THREADS="+KmerCountAbstract.THREADS);
554
555 long bases=0;
556 qhist_total=new long[128];
557 Timer t=new Timer();
558
559 if(passes>1){
560 String lastTemp1=null;
561 String lastTemp2=null;
562
563 if(passes>2){
564 // System.out.println(">>>A");
565
566 ERROR_DETECT_RATIO+=50;
567 EC_HTHRESH=EC_HTHRESH*2+20;
568
569 for(int pass=1; pass<passes-1; pass++){
570 final String tempOutPrefix1=getTempPrefix(in1, outKeep1, pass, 1);
571 final String tempOut1=getTempOut(outKeep1, tempOutPrefix1);
572 final String tempOutToss1=(outToss1==null ? null : getTempOut(outToss1, tempOutPrefix1));
573
574 final String tempOutPrefix2=(outKeep2==null ? null : getTempPrefix(in1, outKeep2, pass, 2));
575 final String tempOut2=(outKeep2==null ? null : getTempOut(outKeep2, tempOutPrefix2));
576 final String tempOutToss2=(outToss2==null ? null : getTempOut(outToss2, tempOutPrefix2));
577
578 outstream.println("\n *********** Pass "+pass+" ********** \n");
579
580 int tgt=(targetDepth1<1 ? targetDepthF*4 : targetDepth1*2);
581 int max=(tgt+tgt/4);
582
583 int tgtBadLow=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_LOW*1.5));
584 int tgtBadHigh=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_HIGH*1.5));
585
586 CORRECT_ERRORS_THIS_PASS=USE_ECC1;
587 TRIM_LEFT_THIS_PASS=(pass==1 && TRIM_LEFT);
588 TRIM_RIGHT_THIS_PASS=(pass==1 && TRIM_RIGHT);
589 bases+=runPass(auto, memory, (cbits1<1 ? cbits : cbits1), cells, precbits, precells, buildpasses, hashes, prehashes, k,
590 maxReads, tablereads, minq, buildStepsize,
591 (pass==1 ? in1 : lastTemp1), (pass==1 ? in2 : lastTemp2),
592 tempOut1, tempOutToss1, null, null, null, null,
593 tempOut2, tempOutToss2, null, null, null, null,
594 (pass==1 ? khistFile : null), (pass==1 ? rhistFile : null), (pass==1 ? peakFile : null), (pass==1 ? extra : null),
595 tgt, tgtBadLow, tgtBadHigh, max, Tools.min(minDepth, 2), Tools.min(minKmersOverMinDepth, 5),
596 Tools.min(0.8f, Tools.max(0.4f, depthPercentile)*1.2f), false, rbb, true,
597 highPercentile, 0, (errorDetectRatio>100 ? 100+(errorDetectRatio-100)/2 : errorDetectRatio), hthresh, lthresh, false, false, false);
598 lastTemp1=tempOut1;
599 lastTemp2=tempOut2;
600 FASTQ.TEST_INTERLEAVED=true;
601 FASTQ.FORCE_INTERLEAVED=(paired && outKeep2==null);
602 }
603 FASTQ.TEST_INTERLEAVED=true;
604 FASTQ.FORCE_INTERLEAVED=(paired && outKeep2==null);
605 // System.out.println(">>>C");
606
607 ERROR_DETECT_RATIO-=50;
608 EC_HTHRESH=(EC_HTHRESH-20)/2;
609
610 for(int pass=passes-1; pass<passes; pass++){
611 final String tempOutPrefix1=getTempPrefix(in1, outKeep1, pass, 1);
612 final String tempOut1=getTempOut(outKeep1, tempOutPrefix1);
613 final String tempOutToss1=(outToss1==null ? null : getTempOut(outToss1, tempOutPrefix1));
614
615 final String tempOutPrefix2=(outKeep2==null ? null : getTempPrefix(in1, outKeep2, pass, 2));
616 final String tempOut2=(outKeep2==null ? null : getTempOut(outKeep2, tempOutPrefix2));
617 final String tempOutToss2=(outToss2==null ? null : getTempOut(outToss2, tempOutPrefix2));
618
619 outstream.println("\n *********** Pass "+pass+" ********** \n");
620
621 int tgt=(targetDepth1<1 ? targetDepthF*2 : targetDepth1);
622 int max=(tgt+tgt/4);
623
624 int tgtBadLow=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_LOW));
625 int tgtBadHigh=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_HIGH));
626
627 CORRECT_ERRORS_THIS_PASS=USE_ECC1;
628 TRIM_LEFT_THIS_PASS=(pass==1 && TRIM_LEFT);
629 TRIM_RIGHT_THIS_PASS=(pass==1 && TRIM_RIGHT);
630 bases+=runPass(auto, memory, (cbits1<1 ? cbits : cbits1), cells, precbits, precells, buildpasses, hashes, prehashes, k,
631 maxReads, tablereads, minq, buildStepsize,
632 (pass==1 ? in1 : lastTemp1), (pass==1 ? in2 : lastTemp2),
633 tempOut1, tempOutToss1, null, null, null, null,
634 tempOut2, tempOutToss2, null, null, null, null,
635 (pass==1 ? khistFile : null), (pass==1 ? rhistFile : null), (pass==1 ? peakFile : null), (pass==1 ? extra : null),
636 tgt, tgtBadLow, tgtBadHigh, max, Tools.min(minDepth, 3), minKmersOverMinDepth,
637 Tools.min(0.8f, Tools.max(0.4f, depthPercentile)*1.2f), tossErrorReads1, rbb, discardBadOnly1,
638 highPercentile, lowPercentile, errorDetectRatio, hthresh, lthresh, false, false, false);
639 lastTemp1=tempOut1;
640 lastTemp2=tempOut2;
641 }
642 }else{
643 // System.out.println(">>>E");
644 for(int pass=1; pass<passes; pass++){
645 final String tempOutPrefix1=getTempPrefix(in1, outKeep1, pass, 1);
646 final String tempOut1=getTempOut(outKeep1, tempOutPrefix1);
647 final String tempOutToss1=(outToss1==null ? null : getTempOut(outToss1, tempOutPrefix1));
648
649 final String tempOutPrefix2=(outKeep2==null ? null : getTempPrefix(in1, outKeep2, pass, 2));
650 final String tempOut2=(outKeep2==null ? null : getTempOut(outKeep2, tempOutPrefix2));
651 final String tempOutToss2=(outToss2==null ? null : getTempOut(outToss2, tempOutPrefix2));
652
653 outstream.println("\n *********** Pass "+pass+" ********** \n");
654
655 int tgt=(targetDepth1<1 ? targetDepthF*4 : targetDepth1);
656 int max=(tgt+tgt/4);
657
658 int tgtBadLow=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_LOW));
659 int tgtBadHigh=(int)Math.ceil(Tools.min(tgt, targetDepthF*TARGET_BAD_PERCENT_HIGH));
660
661 CORRECT_ERRORS_THIS_PASS=USE_ECC1;
662 TRIM_LEFT_THIS_PASS=(pass==1 && TRIM_LEFT);
663 TRIM_RIGHT_THIS_PASS=(pass==1 && TRIM_RIGHT);
664 bases+=runPass(auto, memory, (cbits1<1 ? cbits : cbits1), cells, precbits, precells, buildpasses, hashes, prehashes, k,
665 maxReads, tablereads, minq, buildStepsize,
666 (pass==1 ? in1 : lastTemp1), (pass==1 ? in2 : lastTemp2),
667 tempOut1, tempOutToss1, null, null, null, null,
668 tempOut2, tempOutToss2, null, null, null, null,
669 (pass==1 ? khistFile : null), (pass==1 ? rhistFile : null), (pass==1 ? peakFile : null), (pass==1 ? extra : null),
670 tgt, tgtBadLow, tgtBadHigh, max, Tools.min(minDepth, 3), minKmersOverMinDepth,
671 Tools.min(0.8f, Tools.max(0.4f, depthPercentile)*1.2f), tossErrorReads1, rbb, discardBadOnly1,
672 highPercentile, lowPercentile, errorDetectRatio, hthresh, lthresh, false, false, false);
673 lastTemp1=tempOut1;
674 lastTemp2=tempOut2;
675 FASTQ.TEST_INTERLEAVED=true;
676 FASTQ.FORCE_INTERLEAVED=(paired && outKeep2==null);
677 }
678 // System.out.println(">>>G");
679 }
680
681 outstream.println("\n *********** Pass "+(passes)+" ********** \n");
682
683 CORRECT_ERRORS_THIS_PASS=USE_ECCF;
684 TRIM_LEFT_THIS_PASS=false;
685 TRIM_RIGHT_THIS_PASS=false;
686 bases+=runPass(auto, memory, cbits, cells, precbits, precells, buildpasses, hashes, prehashes, k,
687 maxReads, tablereads, minq, buildStepsize,
688 lastTemp1, lastTemp2,
689 outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
690 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2,
691 null, null, null, null,
692 targetDepthF, targetDepthF, targetDepthF, maxDepth, minDepth, minKmersOverMinDepth, depthPercentile, tossErrorReadsF, rbb, discardBadOnlyF,
693 highPercentile, lowPercentile, errorDetectRatio, hthresh, lthresh, fixSpikes, countup, renameReads);
694 }else{
695
696 // assert(false) : "=auto"+", m="+memory+", cb="+cbits+", cl="+cells+", pcb="+precbits+
697 // "\n pcl="+precells+", bp="+buildpasses+", h="+hashes+", ph="+prehashes+", k="+k+
698 // "\n ="+maxReads+", ="+tablereads+", ="+minq+", ="+buildStepsize+
699 // "\n ="+in1+", ="+in2+
700 // "\n ="+outKeep1+", ="+outToss1+", ="+outLow1+", ="+outMid1+", ="+outHigh1+", ="+outUnc1+
701 // "\n ="+outKeep2+", ="+outToss2+", ="+outLow2+", ="+outMid2+", ="+outHigh2+", ="+outUnc2+
702 // "\n ="+khistFile+", ="+rhistFile+", ="+peakFile+", ="+extra+
703 // "\n ="+targetDepthF+", ="+targetDepthF+", ="+targetDepthF+", ="+maxDepth+", ="+minDepth+
704 // "\n ="+minKmersOverMinDepth+", ="+depthPercentile+", ="+tossErrorReadsF+", ="+rbb+", ="+discardBadOnlyF+
705 // "\n ="+highPercentile+", ="+lowPercentile+", ="+errorDetectRatio+", ="+hthresh+", ="+lthresh+
706 // "\n ="+fixSpikes+", ="+countup+", ="+renameReads;
707
708 CORRECT_ERRORS_THIS_PASS=(USE_ECC1 || USE_ECCF);
709 TRIM_LEFT_THIS_PASS=(TRIM_LEFT);
710 TRIM_RIGHT_THIS_PASS=(TRIM_RIGHT);
711 bases+=runPass(auto, memory, cbits, cells, precbits, precells, buildpasses, hashes, prehashes, k,
712 maxReads, tablereads, minq, buildStepsize,
713 in1, in2,
714 outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
715 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2,
716 khistFile, rhistFile, peakFile, extra,
717 targetDepthF, targetDepthF, targetDepthF, maxDepth, minDepth, minKmersOverMinDepth, depthPercentile, tossErrorReadsF, rbb, discardBadOnlyF,
718 highPercentile, lowPercentile, errorDetectRatio, hthresh, lthresh, fixSpikes, countup, renameReads);
719 }
720
721 if(outKeep1!=null && (khistFileOut!=null || rhistFileOut!=null || peakFileOut!=null)){
722 outstream.println("\n *********** Output Histogram Generation ********** \n");
723 FASTQ.TEST_INTERLEAVED=true;
724 FASTQ.FORCE_INTERLEAVED=(paired && outKeep2==null);
725 CORRECT_ERRORS_THIS_PASS=false;
726 TRIM_LEFT_THIS_PASS=false;
727 TRIM_RIGHT_THIS_PASS=false;
728 bases+=runPass(auto, memory, cbits, cells, precbits, precells, buildpasses, hashes, prehashes, k,
729 maxReads, tablereads, minq, buildStepsize,
730 outKeep1, outKeep2,
731 null, null, null, null, null, null,
732 null, null, null, null, null, null,
733 khistFileOut, rhistFileOut, peakFileOut, extra,
734 99999999, 99999999, 99999999, 99999999, 0, 0, .5f, false, rbb, false,
735 1, 0, 100, 10, 3, fixSpikes, false, false);
736 }
737
738 if(REMOVE_TEMP_FILES && temp_file_set!=null){
739 outstream.println("\nRemoving temp files.");
740 for(String s : temp_file_set){
741 File f=new File(s);
742 if(f.exists()){
743 // System.out.println("Deleting "+s);
744 boolean success=false;
745 for(int i=0; i<100 && f.exists() && !success; i++){
746 success=f.delete();
747 f=new File(s);
748 }
749 if(f.exists() && !success){
750 // System.err.println(f.canExecute());
751 // System.err.println(f.canRead());
752 // System.err.println(f.canWrite());
753 // System.err.println(f.lastModified());
754 // try {
755 // java.nio.file.Files.delete(f.toPath());
756 // } catch (IOException e) {
757 // // TODO Auto-generated catch block
758 // e.printStackTrace();
759 // }
760 System.err.println("Some temp files (prefixed TEMPFILE_BBNORM) could not be removed may need to be deleted manually.");
761 f.deleteOnExit();
762 }
763 }
764 }
765 }
766
767 t.stop();
768
769
770 outstream.println("\nTotal time: \t\t"+t+" \t"+Tools.format("%.2f", bases*1000000.0/(t.elapsed))+" kb/sec");
771
772 if(errorState){throw new RuntimeException("KmerNormalize terminated in an error state; the output may be corrupt.");}
773
774 //Close the print stream if it was redirected
775 Shared.closeStream(outstream);
776 }
777
778 private static String getTempPrefix(String inFname, String outFname, int pass, int pairnum){
779 String tempOut=null, tempOutPrefix=null;
780 for(int i=0; i<2000 && tempOut==null; i++){
781 tempOutPrefix=(useTmpdir() ? Shared.tmpdir() : "")+"TEMPFILE_BBNORM_P"+pass+"_R"+pairnum+"_"+getSalt(inFname, i)+"_";
782 tempOut=getTempOut(outFname, tempOutPrefix);
783 if(new File(tempOut).exists()){
784 tempOut=null;
785 tempOutPrefix=null;
786 }
787 }
788 if(tempOutPrefix==null){
789 throw new RuntimeException("Can't generate a random temp file name. Try deleting old temp files.");
790 }
791 return tempOutPrefix;
792 }
793
794 private static String getTempOut(String outFname, final String tempOutPrefix){
795 assert(tempOutPrefix!=null);
796 String tempOut=null;
797 if(outFname==null || useTmpdir()){
798 tempOut=tempOutPrefix+".fq.gz";
799 }else{
800 outFname=outFname.replace('\\', '/');
801 int idx=outFname.lastIndexOf('/');
802 if(idx<0){
803 tempOut=tempOutPrefix+outFname;
804 }else{
805 tempOut=outFname.substring(0, idx+1)+tempOutPrefix+outFname.substring(idx+1);
806 }
807 }
808 if(temp_file_set==null){temp_file_set=new HashSet<String>();}
809 if(temp_file_set.contains(tempOut) || new File(tempOut).exists()){
810 return getTempOut(outFname, tempOutPrefix+"_"+(100000*Math.random()));
811 }
812 temp_file_set.add(tempOut);
813 return tempOut;
814 }
815
816 public static String getSalt(String fname, int attempt){
817 return Long.toHexString(System.nanoTime()+attempt)+Long.toHexString(Long.rotateLeft(fname.hashCode(), 31)^System.currentTimeMillis());
818 }
819
820 private static boolean inMemorySort(ArrayList<Read> reads, String sorted, boolean reverse){
821 try{
822 Shared.sort(reads, ReadErrorComparator.comparator);
823 if(reverse){Collections.reverse(reads);}
824 TextStreamWriter tsw=new TextStreamWriter(sorted, overwrite, false, true);
825 tsw.start();
826 // assert(false) : "\nreads: "+reads.size()+"\n"+tsw+"\n";
827 for(Read r : reads){
828 tsw.println(r);
829 if(r.mate!=null){tsw.println(r.mate);}
830 }
831 tsw.poisonAndWait();
832 }catch(Throwable t){
833 System.err.println("ERROR: "+t);
834 return false;
835 }
836 return true;
837 }
838
839 private static long runPass(boolean auto, long memory, int cbits, long cells, int pcbits, long precells, int buildpasses, int hashes, int prehashes, int k,
840 long maxReads, long tablereads, int minq, int buildStepsize,
841 String in1, String in2,
842 String outKeep1, String outToss1, String outLow1, String outMid1, String outHigh1, String outUnc1,
843 String outKeep2, String outToss2, String outLow2, String outMid2, String outHigh2, String outUnc2,
844 String khistFile, String rhistFile, String peakFile, List<String> extra,
845 int targetDepth, int targetDepthBadLow, int targetDepthBadHigh, int maxDepth, int minDepth,
846 int minKmersOverMinDepth, float depthPercentile, boolean tossErrorReads, boolean rbb, boolean discardBadOnly,
847 float highPercentile, float lowPercentile, int errorDetectRatio, int hthresh, int lthresh, boolean fixSpikes, boolean countup,
848 boolean rename){
849 assert(in1!=null);
850 TARGET_DEPTH=targetDepth;
851 TARGET_DEPTH_BAD_LOW=targetDepthBadLow;
852 TARGET_DEPTH_BAD_HIGH=targetDepthBadHigh;
853 MAX_DEPTH=maxDepth;
854 MIN_DEPTH=minDepth;
855 MIN_KMERS_OVER_MIN_DEPTH=minKmersOverMinDepth;
856 DEPTH_PERCENTILE=depthPercentile;
857 RENAME_THIS_PASS=rename;
858
859 COUNTUP=countup;
860 if(COUNTUP){
861 TARGET_DEPTH=(int)Math.round(TARGET_DEPTH*0.95);
862 }
863 TOSS_ERROR_READS=tossErrorReads;
864 // REQUIRE_BOTH_BAD=(rbb);
865 REQUIRE_BOTH_BAD=(rbb || COUNTUP);
866 DISCARD_BAD_ONLY=discardBadOnly;
867 HIGH_PERCENTILE=highPercentile;
868 LOW_PERCENTILE=(COUNTUP ? LOW_PERCENTILE_COUNTUP : lowPercentile);
869 // assert(!COUNTUP) : COUNTUP+", "+LOW_PERCENTILE_COUNTUP+", "+lowPercentile+", "+LOW_PERCENTILE;
870 ERROR_DETECT_RATIO=errorDetectRatio;
871 HTHRESH=hthresh;
872 LTHRESH=lthresh;
873 FIX_SPIKES=fixSpikes;
874
875 {
876 if(khistFile!=null || peakFile!=null){USE_KHISTOGRAM=true;}
877 if(rhistFile!=null){USE_RHISTOGRAM=true;}
878
879 final int maxCount=(int)(cbits>16 ? Shared.MAX_ARRAY_LEN-1 : (1L<<cbits)-1);
880 assert(maxCount>0);
881
882 // assert(false) : maxCount+", "+HIST_LEN_PRINT+", "+HIST_LEN+", "+THREAD_HIST_LEN;
883
884 HIST_LEN_PRINT=Tools.max(2, Tools.min(HIST_LEN_PRINT, maxCount+1));
885 assert(HIST_LEN_PRINT<=Integer.MAX_VALUE) : HIST_LEN_PRINT+", "+Integer.MAX_VALUE;
886 HIST_LEN=(int)Tools.min(maxCount+1, Tools.max(HIST_LEN_PRINT, HIST_LEN));
887 THREAD_HIST_LEN=Tools.min(THREAD_HIST_LEN, HIST_LEN);
888
889 khistogram=new AtomicLongArray(HIST_LEN);
890 if(USE_RHISTOGRAM && rhistFile!=null){
891 rhistogram=new AtomicLongArray(HIST_LEN);
892 bhistogram=new AtomicLongArray(HIST_LEN);
893 }else{
894 rhistogram=null;
895 bhistogram=null;
896 }
897 }
898
899 if(auto && cells==-1){
900 final long usable=(long)Tools.max(((memory-96000000)*.73), memory*0.45);
901 long mem=usable-(khistogram!=null ? (HIST_LEN*16L*(1)) : 0)-(rhistogram!=null ? (HIST_LEN*8L*(1)) : 0)-(bhistogram!=null ? (HIST_LEN*8L*(1)) : 0);
902 if(buildpasses>1){mem/=2;}
903
904 FILTERBYTES=(COUNTUP ? mem/2 : mem);
905 cells=(FILTERBYTES*8)/cbits;
906 //
907 // long tablebytes=((1L<<matrixbits)*cbits)/8;
908 // if(tablebytes*3<usable){matrixbits++;}
909 // outstream.println(tablebytes/1000000+", "+usable/1000000+", "+(tablebytes*3)/1000000);
910
911 }else if(cells==-1){
912 cells=1L<<34;
913 }
914
915 if(prefilter){
916 if(precells<1){
917 long totalbits=cells*cbits;
918 long prebits=(long)(totalbits*prefilterFraction);
919 precells=prebits/pcbits;
920 cells=(totalbits-prebits+cbits-1)/cbits; //Steal memory from cell allocation
921 }
922 if(prehashes<1){
923 prehashes=(hashes+1)/2;
924 }
925 }
926
927 {
928 outstream.println("\nSettings:");
929 outstream.println("threads: \t"+THREADS);
930 outstream.println("k: \t"+k);
931 outstream.println("deterministic: \t"+DETERMINISTIC);
932 outstream.println("toss error reads: \t"+TOSS_ERROR_READS);
933 outstream.println("passes: \t"+buildpasses);
934 outstream.println("bits per cell: \t"+cbits);
935 // outstream.println("matrixbits: \t"+matrixbits);
936 outstream.println("cells: \t"+Tools.toKMG(cells));
937 outstream.println("hashes: \t"+hashes);
938 if(prefilter){
939 outstream.println("prefilter bits: \t"+pcbits);
940 // outstream.println("matrixbits: \t"+matrixbits);
941 outstream.println("prefilter cells: \t"+(precells>0 && prehashes>0 ? Tools.toKMG(precells) : "?"));
942 outstream.println("prefilter hashes: \t"+(precells>0 && prehashes>0 ? ""+prehashes : "?"));
943 }
944 // outstream.println("base min quality: \t"+KmerCountAbstract.minQuality);
945 outstream.println("base min quality: \t"+minq);
946 outstream.println("kmer min prob: \t"+KmerCountAbstract.minProb);
947
948 outstream.println();
949 outstream.println("target depth: \t"+TARGET_DEPTH);
950 outstream.println("min depth: \t"+MIN_DEPTH);
951 outstream.println("max depth: \t"+MAX_DEPTH);
952 outstream.println("min good kmers: \t"+MIN_KMERS_OVER_MIN_DEPTH);
953 outstream.println("depth percentile: \t"+Tools.format("%.1f", 100*DEPTH_PERCENTILE));
954 outstream.println("ignore dupe kmers:\t"+!KmerCountAbstract.KEEP_DUPLICATE_KMERS);
955 outstream.println("fix spikes: \t"+FIX_SPIKES);
956 if((USE_KHISTOGRAM || USE_RHISTOGRAM) && HIST_LEN>0){
957 outstream.println("histogram length: \t"+HIST_LEN);
958 }
959 if(khistFile!=null || rhistFile!=null){
960 outstream.println("print zero cov: \t"+PRINT_ZERO_COVERAGE);
961 }
962
963 outstream.println();
964 }
965
966 if(!prefilter && k<32 && cells>(1L<<(2*k))){cells=(1L<<(2*k));}
967 assert(cells>0);
968
969 // KmerCountAbstract.THREADS=Tools.max(THREADS/2, KmerCountAbstract.THREADS); //Seems like 4 is actually optimal...
970
971 FastaReadInputStream.MIN_READ_LEN=k;
972
973 if(eccByOverlapAuto){
974 eccByOverlapAuto=false;
975 float overlapRatio=BBMerge.mergeableFraction(in1, in2, 1000000, 0.01f);
976 eccByOverlap=(overlapRatio>0.25f);
977 if(eccByOverlap){
978 System.err.println("Enabled overlap correction ("+Tools.format("%.1f%% percent overlap)", 100*overlapRatio));
979 }
980 }
981
982 Timer t=new Timer();
983 Timer ht=new Timer();
984 t.start();
985 ht.start();
986 KCountArray kca;
987 KCountArray prefilterArray=null;
988 // outstream.println();
989 ReadCounter rc=new ReadCounter(k, true, eccByOverlap, false, Shared.AMINO_IN);
990 rc.detectStepsize=buildStepsize;
991 if(prefilter){
992 prefilterArray=rc.makeKca(in1, in2, extra, pcbits, precells, prehashes, minq,
993 tablereads, 1, 1, 1, null, 0);
994 outstream.println("Made prefilter: \t"+prefilterArray.toShortString(prehashes));
995 double uf=prefilterArray.usedFraction();
996 if(uf>0.6){
997 outstream.println("Warning: This table is "+(uf>0.995 ? "totally" : uf>0.99 ? "crazy" : uf>0.95 ? "incredibly" : uf>0.9 ? "extremely" : uf>0.8 ? "very" :
998 uf>0.7 ? "fairly" : "somewhat")+" full, which may reduce accuracy for kmers of depth under 3. Ideal load is under 60% used." +
999 "\nFor better accuracy, run on a node with more memory; quality-trim or error-correct reads; " +
1000 "or increase the values of the minprob flag to reduce spurious kmers.");
1001 }
1002 }
1003
1004 kca=rc.makeKca(in1, in2, extra, cbits, cells, hashes, minq,
1005 tablereads, buildpasses, 2, 2, prefilterArray, (prefilterArray==null ? 0 : prefilterArray.maxValue));
1006 ht.stop();
1007
1008 outstream.println("Made hash table: \t"+kca.toShortString(hashes));
1009 double uf=kca.usedFraction();
1010 if(uf>0.6){
1011 outstream.println("Warning: This table is "+(uf>0.995 ? "totally" : uf>0.99 ? "crazy" : uf>0.95 ? "incredibly" : uf>0.9 ? "extremely" : uf>0.8 ? "very" :
1012 uf>0.7 ? "fairly" : "somewhat")+" full, which may reduce accuracy. Ideal load is under 60% used." +
1013 "\nFor better accuracy, use the 'prefilter' flag; run on a node with more memory; quality-trim or error-correct reads; " +
1014 "or increase the values of the minprob flag to reduce spurious kmers. In practice you should still get good normalization results " +
1015 "even with loads over 90%, but the histogram and statistics will be off.");
1016 }
1017
1018 long estUnique;
1019 outstream.println();
1020 if(prefilterArray!=null){
1021 int lim1=prefilterArray.maxValue, lim2=prefilterArray.maxValue+1;
1022 double a=prefilterArray.estimateUniqueKmers(prehashes);
1023 double b=kca.estimateUniqueKmers(hashes, lim2);
1024 a=a-b;
1025 if(CANONICAL){
1026 // a=(a*KCountArray.canonMask)/(KCountArray.canonMask+1);
1027 // b=(b*KCountArray.canonMask)/(KCountArray.canonMask+1);
1028 }else{
1029 a/=2;
1030 b/=2;
1031 }
1032 estUnique=((long)((a+b)));
1033 outstream.println("Estimated kmers of depth 1-"+lim1+": \t"+(long)a);
1034 outstream.println("Estimated kmers of depth "+lim2+"+ : \t"+(long)b);
1035 }else{
1036 // double est=kca.cells*(1-Math.pow(1-Math.sqrt(kca.usedFraction()), 1.0/hashes));
1037 // double est=kca.cells*(1-Math.pow(1-kca.usedFraction(), 1.0/hashes));
1038 double est=kca.estimateUniqueKmers(hashes);
1039 // outstream.println("Used cells: "+kca.cellsUsed(1));
1040 if(CANONICAL){
1041 // est=(est*KCountArray.canonMask)/(KCountArray.canonMask+1);
1042 }else{
1043 est/=2;
1044 }
1045 estUnique=((long)((est)));
1046
1047 }
1048 outstream.println("Estimated unique kmers: \t"+estUnique);//+", or "+estUnique+" counting forward kmers only.");
1049 // outstream.println("(Includes forward and reverse kmers)");
1050 outstream.println();
1051 outstream.println("Table creation time:\t\t"+ht);//+" \t"+Tools.format("%.2f", totalBases*1000000.0/(ht.elapsed))+" kb/sec");
1052
1053 ListNum.setDeterministicRandom(DETERMINISTIC);
1054
1055 long bases=0;
1056 if(COUNTUP){
1057 COUNTUP=false;
1058
1059 int td0=TARGET_DEPTH, md0=MIN_DEPTH, mxd0=MAX_DEPTH, mkomd0=MIN_KMERS_OVER_MIN_DEPTH;
1060 TARGET_DEPTH=TARGET_DEPTH*4;
1061 MIN_DEPTH=MIN_DEPTH/2;
1062 MAX_DEPTH=MAX_DEPTH*4;
1063 MIN_KMERS_OVER_MIN_DEPTH=MIN_KMERS_OVER_MIN_DEPTH/2;
1064
1065 int rnd=(int)(100+Math.random()*1000000);
1066 final String tempOutPrefix1=getTempPrefix(in1, outKeep1, rnd, 1);
1067 final String tempOut1=getTempOut(outKeep1, tempOutPrefix1);
1068 final String tempOutPrefix2=(outKeep2==null ? null : getTempPrefix(in1, outKeep2, rnd, 2));
1069 final String tempOut2=(outKeep2==null ? null : getTempOut(outKeep2, tempOutPrefix2));
1070 ArrayList<Read> storage=new ArrayList<Read>();
1071
1072 if(in1!=null && in1.contains(",") && !new File(in1).exists()){
1073 String[] list1=in1.split(",");
1074 String[] list2=(in2==null ? null : in2.split(","));
1075 bases+=count(list1, list2, kca, k, maxReads, null, null, null, null, null, null,
1076 null, null, null, null, null, null, false, overwrite, null, null, null, estUnique, storage);
1077 }else{
1078 bases+=count(in1, in2, kca, k, maxReads, null, null, null, null, null, null,
1079 null, null, null, null, null, null, false, overwrite, null, null, null, estUnique, storage);
1080 }
1081 inMemorySort(storage, tempOut1, false);
1082 storage=null;
1083 in1=tempOut1;
1084 in2=null;
1085
1086 TARGET_DEPTH=td0;
1087 MIN_DEPTH=md0;
1088 MAX_DEPTH=mxd0;
1089 MIN_KMERS_OVER_MIN_DEPTH=mkomd0;
1090
1091 COUNTUP=true;
1092
1093
1094 if(in1!=null && in1.contains(",") && !new File(in1).exists()){
1095 String[] list1=in1.split(",");
1096 String[] list2=(in2==null ? null : in2.split(","));
1097 bases+=count(list1, list2, kca, k, maxReads, outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
1098 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2, ordered, overwrite, khistFile, rhistFile, peakFile, estUnique, null);
1099 }else{
1100 bases+=count(in1, in2, kca, k, maxReads, outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
1101 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2, ordered, overwrite, khistFile, rhistFile, peakFile, estUnique, null);
1102 }
1103
1104 }else{
1105
1106
1107 if(in1!=null && in1.contains(",") && !new File(in1).exists()){
1108 String[] list1=in1.split(",");
1109 String[] list2=(in2==null ? null : in2.split(","));
1110 bases+=count(list1, list2, kca, k, maxReads, outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
1111 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2, ordered, overwrite, khistFile, rhistFile, peakFile, estUnique, null);
1112 }else{
1113 bases+=count(in1, in2, kca, k, maxReads, outKeep1, outToss1, outLow1, outMid1, outHigh1, outUnc1,
1114 outKeep2, outToss2, outLow2, outMid2, outHigh2, outUnc2, ordered, overwrite, khistFile, rhistFile, peakFile, estUnique, null);
1115 }
1116 }
1117
1118 if(ANALYZE_TOPOLOGY){printTopology();}
1119
1120 t.stop();
1121 // outstream.println("\nTotal time: \t\t"+t+" \t"+Tools.format("%.2f", bases*1000000.0/(t.elapsed))+" kb/sec");
1122 return bases;
1123 }
1124
1125
1126 public static void printTopology(){
1127 long total=peaks.get()+spikes.get()+flats.get()+valleys.get()+slopes.get();
1128 double mult=100.0/total;
1129
1130 long sp=spikes.get();
1131 long pe=peaks.get();
1132 long va=valleys.get();
1133 long sl=slopes.get();
1134 long fl=flats.get();
1135 double dsp=mult*sp;
1136 double dpe=mult*pe;
1137 double dva=mult*va;
1138 double dsl=mult*sl;
1139 double dfl=mult*fl;
1140
1141 System.err.println("\nDepth Topology:\t");
1142 System.err.println("Spikes: \t\t\t"+(dsp<10 ? " " : "")+Tools.format("%.3f%% \t%d",dsp,sp));
1143 System.err.println("Peaks: \t\t\t"+(dpe<10 ? " " : "")+Tools.format("%.3f%% \t%d",dpe,pe));
1144 System.err.println("Valleys: \t\t\t"+(dva<10 ? " " : "")+Tools.format("%.3f%% \t%d",dva,va));
1145 System.err.println("Slopes: \t\t\t"+(dsl<10 ? " " : "")+Tools.format("%.3f%% \t%d",dsl,sl));
1146 System.err.println("Flats: \t\t\t"+(dfl<10 ? " " : "")+Tools.format("%.3f%% \t%d",dfl,fl));
1147 }
1148
1149
1150 public static long count(String in1, String in2, KCountArray kca, int k, long maxReads,
1151 String outKeep1, String outToss1, String outLow1, String outMid1, String outHigh1, String outUnc1,
1152 String outKeep2, String outToss2, String outLow2, String outMid2, String outHigh2, String outUnc2,
1153 boolean ordered, boolean overwrite, String khistFile, String rhistFile, String peakFile, long estUnique, ArrayList<Read> storage) {
1154 final ConcurrentReadInputStream cris;
1155 {
1156 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
1157 FileFormat ff2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true);
1158 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
1159 if(verbose){System.err.println("Started cris");}
1160 cris.start(); //4567
1161 }
1162 boolean paired=cris.paired();
1163 if(verbose){System.err.println("Paired: "+paired);}
1164
1165 ConcurrentReadOutputStream rosKeep=null;
1166 if(outKeep1!=null){
1167 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1168
1169 final String out=outKeep1;
1170 String out1=outKeep1.replaceFirst("#", "1");
1171 String out2=outKeep2;
1172
1173 if(cris.paired() && out2==null){
1174 if(out.contains("#")){
1175 out2=out.replaceFirst("#", "2");
1176 }else{
1177 outstream.println("Writing interleaved.");
1178 }
1179 }
1180
1181 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1182 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1183
1184 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1185 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1186 rosKeep=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1187 rosKeep.start();
1188 outstream.println("Started output threads.");
1189 }
1190
1191 ConcurrentReadOutputStream rosToss=null;
1192 if(outToss1!=null){
1193 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1194
1195 final String out=outToss1;
1196 String out1=outToss1.replaceFirst("#", "1");
1197 String out2=outToss2;
1198
1199 if(cris.paired() && out2==null){
1200 if(out.contains("#")){
1201 out2=out.replaceFirst("#", "2");
1202 }else{
1203 outstream.println("Writing interleaved.");
1204 }
1205 }
1206
1207 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1208 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1209
1210 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1211 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1212 rosToss=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1213
1214 rosToss.start();
1215 outstream.println("Started output threads.");
1216 }
1217
1218 ConcurrentReadOutputStream rosLow=null;
1219 if(outLow1!=null){
1220 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1221
1222 final String out=outLow1;
1223 String out1=outLow1.replaceFirst("#", "1");
1224 String out2=outLow2;
1225
1226 if(cris.paired() && out2==null){
1227 if(out.contains("#")){
1228 out2=out.replaceFirst("#", "2");
1229 }else{
1230 outstream.println("Writing interleaved.");
1231 }
1232 }
1233
1234 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1235 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1236
1237 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1238 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1239 rosLow=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1240
1241 rosLow.start();
1242 outstream.println("Started output threads.");
1243 }
1244
1245 ConcurrentReadOutputStream rosMid=null;
1246 if(outMid1!=null){
1247 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1248
1249 final String out=outMid1;
1250 String out1=outMid1.replaceFirst("#", "1");
1251 String out2=outMid2;
1252
1253 if(cris.paired() && out2==null){
1254 if(out.contains("#")){
1255 out2=out.replaceFirst("#", "2");
1256 }else{
1257 outstream.println("Writing interleaved.");
1258 }
1259 }
1260
1261 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1262 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1263
1264 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1265 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1266 rosMid=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1267
1268 rosMid.start();
1269 outstream.println("Started output threads.");
1270 }
1271
1272 ConcurrentReadOutputStream rosHigh=null;
1273 if(outHigh1!=null){
1274 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1275
1276 final String out=outHigh1;
1277 String out1=outHigh1.replaceFirst("#", "1");
1278 String out2=outHigh2;
1279
1280 if(cris.paired() && out2==null){
1281 if(out.contains("#")){
1282 out2=out.replaceFirst("#", "2");
1283 }else{
1284 outstream.println("Writing interleaved.");
1285 }
1286 }
1287
1288 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1289 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1290
1291 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1292 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1293 rosHigh=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1294
1295 rosHigh.start();
1296 outstream.println("Started output threads.");
1297 }
1298
1299 ConcurrentReadOutputStream rosUnc=null;
1300 if(outUnc1!=null){
1301 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1302
1303 final String out=outUnc1;
1304 String out1=outUnc1.replaceFirst("#", "1");
1305 String out2=outUnc2;
1306
1307 if(cris.paired() && out2==null){
1308 if(out.contains("#")){
1309 out2=out.replaceFirst("#", "2");
1310 }else{
1311 outstream.println("Writing interleaved.");
1312 }
1313 }
1314
1315 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1316 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2)));
1317
1318 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1319 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1320 rosUnc=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1321
1322 rosUnc.start();
1323 outstream.println("Started output threads.");
1324 }
1325
1326 long bases=downsample(cris, kca, k, maxReads, rosKeep, rosToss, rosLow, rosMid, rosHigh, rosUnc, khistFile, rhistFile, peakFile, overwrite, estUnique, storage);
1327
1328 errorState|=ReadWrite.closeStreams(cris, rosKeep, rosToss, rosLow, rosMid, rosHigh, rosUnc);
1329 if(verbose){System.err.println("Closed streams");}
1330
1331 return bases;
1332 }
1333
1334
1335 public static long count(String[] list1, String[] list2, KCountArray kca, int k, long maxReads,
1336 String outKeep1, String outToss1, String outLow1, String outMid1, String outHigh1, String outUnc1,
1337 String outKeep2, String outToss2, String outLow2, String outMid2, String outHigh2, String outUnc2,
1338 boolean ordered, boolean overwrite, String khistFile, String rhistFile, String peakFile, long estUnique, ArrayList<Read> storage) {
1339
1340 ConcurrentReadOutputStream rosKeep=null, rosToss=null, rosLow=null, rosMid=null, rosHigh=null, rosUnc=null;
1341 String[] outKeep1a=null, outKeep2a=null;
1342 String[] outToss1a=null, outToss2a=null;
1343 String[] outLow1a=null, outLow2a=null;
1344 String[] outMid1a=null, outMid2a=null;
1345 String[] outHigh1a=null, outHigh2a=null;
1346 String[] outUnc1a=null, outUnc2a=null;
1347
1348
1349 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
1350 if(outKeep1!=null){
1351 if(!new File(outKeep1).exists()){
1352 outKeep1a=outKeep1.split(",");
1353 }else{
1354 outKeep1a=new String[] {outKeep1};
1355 }
1356 if(outKeep2!=null){
1357 if(!new File(outKeep2).exists()){
1358 outKeep2a=outKeep2.split(",");
1359 }else{
1360 outKeep2a=new String[] {outKeep2};
1361 }
1362 }else{
1363 outKeep2a=new String[outKeep1a.length];
1364 for(int i=0; i<outKeep1a.length; i++){
1365 if(outKeep1a[i].contains("#")){
1366 outKeep2a[i]=outKeep1a[i].replaceFirst("#", "2");
1367 outKeep1a[i]=outKeep1a[i].replaceFirst("#", "1");
1368 }
1369 }
1370 }
1371 }
1372 if(outToss1!=null){
1373 if(!new File(outToss1).exists()){
1374 outToss1a=outToss1.split(",");
1375 }else{
1376 outToss1a=new String[] {outToss1};
1377 }
1378 if(outToss2!=null){
1379 if(!new File(outToss2).exists()){
1380 outToss2a=outToss2.split(",");
1381 }else{
1382 outToss2a=new String[] {outToss2};
1383 }
1384 }else{
1385 outToss2a=new String[outToss1a.length];
1386 for(int i=0; i<outToss1a.length; i++){
1387 if(outToss1a[i].contains("#")){
1388 outToss2a[i]=outToss1a[i].replaceFirst("#", "2");
1389 outToss1a[i]=outToss1a[i].replaceFirst("#", "1");
1390 }
1391 }
1392 }
1393 }
1394 if(outLow1!=null){
1395 if(!new File(outLow1).exists()){
1396 outLow1a=outLow1.split(",");
1397 }else{
1398 outLow1a=new String[] {outLow1};
1399 }
1400 if(outLow2!=null){
1401 if(!new File(outLow2).exists()){
1402 outLow2a=outLow2.split(",");
1403 }else{
1404 outLow2a=new String[] {outLow2};
1405 }
1406 }else{
1407 outLow2a=new String[outLow1a.length];
1408 for(int i=0; i<outLow1a.length; i++){
1409 if(outLow1a[i].contains("#")){
1410 outLow2a[i]=outLow1a[i].replaceFirst("#", "2");
1411 outLow1a[i]=outLow1a[i].replaceFirst("#", "1");
1412 }
1413 }
1414 }
1415 }
1416 if(outMid1!=null){
1417 if(!new File(outMid1).exists()){
1418 outMid1a=outMid1.split(",");
1419 }else{
1420 outMid1a=new String[] {outMid1};
1421 }
1422 if(outMid2!=null){
1423 if(!new File(outMid2).exists()){
1424 outMid2a=outMid2.split(",");
1425 }else{
1426 outMid2a=new String[] {outMid2};
1427 }
1428 }else{
1429 outMid2a=new String[outMid1a.length];
1430 for(int i=0; i<outMid1a.length; i++){
1431 if(outMid1a[i].contains("#")){
1432 outMid2a[i]=outMid1a[i].replaceFirst("#", "2");
1433 outMid1a[i]=outMid1a[i].replaceFirst("#", "1");
1434 }
1435 }
1436 }
1437 }
1438 if(outHigh1!=null){
1439 if(!new File(outHigh1).exists()){
1440 outHigh1a=outHigh1.split(",");
1441 }else{
1442 outHigh1a=new String[] {outHigh1};
1443 }
1444 if(outHigh2!=null){
1445 if(!new File(outHigh2).exists()){
1446 outHigh2a=outHigh2.split(",");
1447 }else{
1448 outHigh2a=new String[] {outHigh2};
1449 }
1450 }else{
1451 outHigh2a=new String[outHigh1a.length];
1452 for(int i=0; i<outHigh1a.length; i++){
1453 if(outHigh1a[i].contains("#")){
1454 outHigh2a[i]=outHigh1a[i].replaceFirst("#", "2");
1455 outHigh1a[i]=outHigh1a[i].replaceFirst("#", "1");
1456 }
1457 }
1458 }
1459 }
1460 if(outUnc1!=null){
1461 if(!new File(outUnc1).exists()){
1462 outUnc1a=outUnc1.split(",");
1463 }else{
1464 outUnc1a=new String[] {outUnc1};
1465 }
1466 if(outUnc2!=null){
1467 if(!new File(outUnc2).exists()){
1468 outUnc2a=outUnc2.split(",");
1469 }else{
1470 outUnc2a=new String[] {outUnc2};
1471 }
1472 }else{
1473 outUnc2a=new String[outUnc1a.length];
1474 for(int i=0; i<outUnc1a.length; i++){
1475 if(outUnc1a[i].contains("#")){
1476 outUnc2a[i]=outUnc1a[i].replaceFirst("#", "2");
1477 outUnc1a[i]=outUnc1a[i].replaceFirst("#", "1");
1478 }
1479 }
1480 }
1481 }
1482
1483 long bases=0;
1484
1485 for(int x=0; x<list1.length; x++){
1486
1487 if(outKeep1a!=null){
1488 if(x==0 || outKeep1a.length>1){
1489 if(rosKeep!=null){
1490 rosKeep.close();
1491 rosKeep.join();
1492 }
1493
1494 FileFormat ff1=FileFormat.testOutput(outKeep1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1495 FileFormat ff2=FileFormat.testOutput(outKeep2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1496 rosKeep=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1497
1498 rosKeep.start();
1499 outstream.println("Started output threads.");
1500 }else{
1501 rosKeep.resetNextListID();
1502 }
1503 }
1504
1505 if(outToss1a!=null){
1506 if(x==0 || outToss1a.length>1){
1507 if(rosToss!=null){
1508 rosToss.close();
1509 rosToss.join();
1510 }
1511
1512 FileFormat ff1=FileFormat.testOutput(outToss1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1513 FileFormat ff2=FileFormat.testOutput(outToss2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1514 rosToss=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1515
1516 rosToss.start();
1517 outstream.println("Started output threads.");
1518 }else{
1519 rosToss.resetNextListID();
1520 }
1521 }
1522
1523 if(outLow1a!=null){
1524 if(x==0 || outLow1a.length>1){
1525 if(rosLow!=null){
1526 rosLow.close();
1527 rosLow.join();
1528 }
1529
1530 FileFormat ff1=FileFormat.testOutput(outLow1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1531 FileFormat ff2=FileFormat.testOutput(outLow2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1532 rosLow=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1533
1534 rosLow.start();
1535 outstream.println("Started output threads.");
1536 }else{
1537 rosLow.resetNextListID();
1538 }
1539 }
1540
1541 if(outMid1a!=null){
1542 if(x==0 || outMid1a.length>1){
1543 if(rosMid!=null){
1544 rosMid.close();
1545 rosMid.join();
1546 }
1547
1548 FileFormat ff1=FileFormat.testOutput(outMid1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1549 FileFormat ff2=FileFormat.testOutput(outMid2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1550 rosMid=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1551
1552 rosMid.start();
1553 outstream.println("Started output threads.");
1554 }else{
1555 rosMid.resetNextListID();
1556 }
1557 }
1558
1559 if(outHigh1a!=null){
1560 if(x==0 || outHigh1a.length>1){
1561 if(rosHigh!=null){
1562 rosHigh.close();
1563 rosHigh.join();
1564 }
1565
1566 FileFormat ff1=FileFormat.testOutput(outHigh1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1567 FileFormat ff2=FileFormat.testOutput(outHigh2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1568 rosHigh=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1569
1570 rosHigh.start();
1571 outstream.println("Started output threads.");
1572 }else{
1573 rosHigh.resetNextListID();
1574 }
1575 }
1576
1577 if(outUnc1a!=null){
1578 if(x==0 || outUnc1a.length>1){
1579 if(rosUnc!=null){
1580 rosUnc.close();
1581 rosUnc.join();
1582 }
1583
1584 FileFormat ff1=FileFormat.testOutput(outUnc1a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1585 FileFormat ff2=FileFormat.testOutput(outUnc2a[x], FileFormat.FASTQ, null, true, overwrite, append, ordered);
1586 rosUnc=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
1587
1588 rosUnc.start();
1589 outstream.println("Started output threads.");
1590 }else{
1591 rosUnc.resetNextListID();
1592 }
1593 }
1594
1595 String in1=list1[x];
1596 String in2=(list2==null || list2.length<=x ? null : list2[x]);
1597
1598 final ConcurrentReadInputStream cris;
1599 {
1600 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
1601 FileFormat ff2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true);
1602 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
1603 if(verbose){System.err.println("Started cris");}
1604 cris.start(); //4567
1605 }
1606 boolean paired=cris.paired();
1607 if(verbose){System.err.println("Paired: "+paired);}
1608
1609 bases+=downsample(cris, kca, k, maxReads, rosKeep, rosToss, rosLow, rosMid, rosHigh, rosUnc, khistFile, rhistFile, peakFile, overwrite, estUnique, storage);
1610
1611 errorState|=ReadWrite.closeStream(cris);
1612 if(verbose){System.err.println("Closed stream");}
1613
1614 }
1615
1616 errorState|=ReadWrite.closeStreams(null, rosKeep, rosToss, rosLow, rosMid, rosHigh, rosUnc);
1617
1618 return bases;
1619 }
1620
1621
1622
1623 public static long downsample(ConcurrentReadInputStream cris, KCountArray kca, int k, long maxReads,
1624 ConcurrentReadOutputStream rosKeep, ConcurrentReadOutputStream rosToss, ConcurrentReadOutputStream rosLow, ConcurrentReadOutputStream rosMid, ConcurrentReadOutputStream rosHigh, ConcurrentReadOutputStream rosUnc,
1625 String khistFile, String rhistFile, String peakFile, boolean overwrite, long estUnique, ArrayList<Read> storage) {
1626 Timer tdetect=new Timer();
1627 tdetect.start();
1628
1629 long totalBases=0;
1630 long totalReads=0;
1631
1632 long readsKept=0;
1633 long readsTossed=0;
1634 long readsLowBin=0;
1635 long readsMidBin=0;
1636 long readsHighBin=0;
1637 long readsUncorrected=0;
1638 long basesKept=0;
1639 long basesTossed=0;
1640 long basesLowBin=0;
1641 long basesMidBin=0;
1642 long basesHighBin=0;
1643 long basesUncorrected=0;
1644
1645
1646 long errorReads=0;
1647 long errorPairs=0;
1648 long errorType1=0;
1649 long errorType2=0;
1650 long errorType3=0;
1651
1652 long errorsDetected=0;
1653 long errorsMarked=0;
1654 long errorsCorrected=0;
1655 long basesTrimmed=0;
1656
1657 {
1658 KCountArray kcaup=null;
1659 if(COUNTUP){
1660 final int bits;
1661 if(TARGET_DEPTH<=15){
1662 bits=4;
1663 }else if(TARGET_DEPTH<=255){
1664 bits=8;
1665 }else{
1666 bits=16;
1667 }
1668
1669 long cells=(FILTERBYTES*8)/bits;
1670 int kbits=2*k;
1671 kcaup=KCountArray.makeNew(cells, bits, 3, null, 0);
1672 }
1673
1674 ProcessThread[] pta=new ProcessThread[THREADS];
1675 for(int i=0; i<pta.length; i++){
1676 pta[i]=new ProcessThread(cris, kca, kcaup, k, rosKeep, rosToss, rosLow, rosMid, rosHigh, rosUnc, storage);
1677 pta[i].start();
1678 }
1679
1680 kca=kcaup=null;
1681
1682 for(int i=0; i<pta.length; i++){
1683 ProcessThread ct=pta[i];
1684 synchronized(ct){
1685 while(ct.getState()!=State.TERMINATED){
1686 try {
1687 ct.join(1000);
1688 } catch (InterruptedException e) {
1689 // TODO Auto-generated catch block
1690 e.printStackTrace();
1691 }
1692 }
1693 totalBases+=ct.totalBases;
1694 totalReads+=ct.totalReads;
1695 errorReads+=ct.errorReads;
1696 errorPairs+=ct.errorPairs;
1697 errorType1+=ct.errorType1;
1698 errorType2+=ct.errorType2;
1699 errorType3+=ct.errorType3;
1700
1701 readsKept+=ct.readsKept;
1702 readsTossed+=ct.readsTossed;
1703 readsLowBin+=ct.readsLowBin;
1704 readsMidBin+=ct.readsMidBin;
1705 readsHighBin+=ct.readsHighBin;
1706 readsUncorrected+=ct.readsUncorrected;
1707
1708 basesKept+=ct.basesKept;
1709 basesTossed+=ct.basesTossed;
1710 basesLowBin+=ct.basesLowBin;
1711 basesMidBin+=ct.basesMidBin;
1712 basesHighBin+=ct.basesHighBin;
1713 basesUncorrected+=ct.basesUncorrected;
1714
1715 errorsDetected+=ct.errorsDetected;
1716 errorsMarked+=ct.errorsMarked;
1717 errorsCorrected+=ct.errorsCorrected;
1718 basesTrimmed+=ct.basesTrimmed;
1719 errorState|=ct.errorStateT;
1720
1721 for(int j=0; j<ct.hist.length; j++){
1722 khistogram.addAndGet(j, ct.hist[j]);
1723 }
1724 for(int j=0; j<ct.qhist.length; j++){
1725 qhist_total[j]+=ct.qhist[j];
1726 }
1727 }
1728 }
1729 }
1730
1731 if(!ZERO_BIN && khistogram!=null && khistogram.length()>1){
1732 khistogram.addAndGet(1, khistogram.get(0));
1733 khistogram.set(0, 0);
1734 }
1735
1736 // outstream.println();
1737 tdetect.stop();
1738 outstream.println("Table read time: \t\t"+tdetect+" \t"+Tools.format("%.2f", totalBases*1000000.0/(tdetect.elapsed))+" kb/sec");
1739
1740 {
1741 String pad="";
1742 String s=""+totalReads;
1743 while(pad.length()+s.length()<9){pad+=" ";}
1744 outstream.println("Total reads in: \t\t"+totalReads+pad+Tools.format("\t%.3f%% Kept", (readsKept*100.0/totalReads)));
1745 s=""+totalBases;
1746 while(pad.length()+s.length()<9){pad+=" ";}
1747 outstream.println("Total bases in: \t\t"+totalBases+pad+Tools.format("\t%.3f%% Kept", (basesKept*100.0/totalBases)));
1748
1749 if(rosLow!=null){
1750 s=""+readsLowBin;
1751 while(pad.length()+s.length()<9){pad+=" ";}
1752 outstream.println("Low bin reads: \t\t"+readsLowBin+pad+Tools.format("\t%.3f%%", (readsLowBin*100.0/totalReads)));
1753 s=""+basesLowBin;
1754 while(pad.length()+s.length()<9){pad+=" ";}
1755 outstream.println("Low bin bases: \t\t"+basesLowBin+pad+Tools.format("\t%.3f%%", (basesLowBin*100.0/totalBases)));
1756 }
1757 if(rosMid!=null){
1758 s=""+readsMidBin;
1759 while(pad.length()+s.length()<9){pad+=" ";}
1760 outstream.println("Mid bin reads: \t\t"+readsMidBin+pad+Tools.format("\t%.3f%%", (readsMidBin*100.0/totalReads)));
1761 s=""+basesMidBin;
1762 while(pad.length()+s.length()<9){pad+=" ";}
1763 outstream.println("Mid bin bases: \t\t"+basesMidBin+pad+Tools.format("\t%.3f%%", (basesMidBin*100.0/totalBases)));
1764 }
1765 if(rosHigh!=null){
1766 s=""+readsHighBin;
1767 while(pad.length()+s.length()<9){pad+=" ";}
1768 outstream.println("High bin reads: \t\t"+readsHighBin+pad+Tools.format("\t%.3f%%", (readsHighBin*100.0/totalReads)));
1769 s=""+basesHighBin;
1770 while(pad.length()+s.length()<9){pad+=" ";}
1771 outstream.println("High bin bases: \t\t"+basesHighBin+pad+Tools.format("\t%.3f%%", (basesHighBin*100.0/totalBases)));
1772 }
1773
1774 s=""+errorReads;
1775 while(pad.length()+s.length()<9){pad+=" ";}
1776 outstream.println("Error reads in: \t\t"+errorReads+pad+Tools.format("\t%.3f%%", (errorReads*100.0/totalReads)));
1777 if(cris.paired()){
1778 s=""+errorPairs;
1779 while(pad.length()+s.length()<9){pad+=" ";}
1780 outstream.println("Error pairs in: \t\t"+errorPairs+pad+Tools.format("\t%.3f%%", (errorPairs*200.0/totalReads)));
1781 }
1782 s=""+errorType1;
1783 while(pad.length()+s.length()<9){pad+=" ";}
1784 outstream.println("Error type 1: \t\t"+errorType1+pad+Tools.format("\t%.3f%%", (errorType1*100.0/totalReads)));
1785 s=""+errorType2;
1786 while(pad.length()+s.length()<9){pad+=" ";}
1787 outstream.println("Error type 2: \t\t"+errorType2+pad+Tools.format("\t%.3f%%", (errorType2*100.0/totalReads)));
1788 s=""+errorType3;
1789 while(pad.length()+s.length()<9){pad+=" ";}
1790 outstream.println("Error type 3: \t\t"+errorType3+pad+Tools.format("\t%.3f%%", (errorType3*100.0/totalReads)));
1791
1792
1793 if(TRIM_LEFT_THIS_PASS || TRIM_RIGHT_THIS_PASS){
1794 outstream.println("\nDuring Trimming:");
1795 s=""+(errorsDetected+errorsCorrected+errorsMarked);
1796 while(pad.length()+s.length()<9){pad+=" ";}
1797 outstream.println("Bases Trimmed: \t\t"+(basesTrimmed));
1798 }
1799
1800 if(CORRECT_ERRORS_THIS_PASS){
1801 outstream.println("\nDuring Error Correction:");
1802 s=""+(errorsDetected+errorsCorrected+errorsMarked);
1803 while(pad.length()+s.length()<9){pad+=" ";}
1804 outstream.println("Errors Suspected:\t\t"+(errorsDetected+errorsCorrected+errorsMarked));
1805 s=""+errorsCorrected;
1806 pad="";
1807 while(pad.length()+s.length()<9){pad+=" ";}
1808 outstream.println("Errors Corrected:\t\t"+errorsCorrected);
1809 s=""+errorsMarked;
1810 pad="";
1811 while(pad.length()+s.length()<9){pad+=" ";}
1812 outstream.println("Errors Marked: \t\t"+errorsMarked+"\n");
1813 }
1814 }
1815
1816 // outstream.println();
1817 if(khistogram!=null){
1818
1819 if(peakFile!=null){
1820 CallPeaks.printClass=false;
1821 long[] array=Tools.toArray(khistogram);
1822 for(int i=0; i<array.length; i++){
1823 long x=array[i];
1824 long y=((x+i/2)/(i<1 ? 1 : i)); //x+i/2 rounds to compensate for colliding kmers being put in an overly high bin
1825 array[i]=y;
1826 }
1827
1828 ArrayList<String> args=new ArrayList<String>();
1829 args.add("smoothradius=1");
1830 args.add("smoothprogressive=t");
1831 CallPeaks.printPeaks(array, null, peakFile, overwrite, minHeight, minVolume, minWidth, minPeak, maxPeak, maxPeakCount, k, ploidy, doLogScale, logWidth, args);
1832 }
1833
1834 ByteStreamWriter bsw=null;
1835 if(USE_KHISTOGRAM && khistFile!=null){
1836 bsw=new ByteStreamWriter(khistFile, overwrite, false, false);
1837 bsw.start();
1838
1839 if(HIST_COLUMNS==1){
1840 bsw.print("#tUnique_Kmers\n");
1841 }else if(HIST_COLUMNS==2){
1842 bsw.print("#Depth\tUnique_Kmers\n");
1843 }else if(HIST_COLUMNS==3){
1844 bsw.print("#Depth\tRaw_Count\tUnique_Kmers\n");
1845 }
1846
1847 }
1848 int lim=(int)(HIST_LEN_PRINT-1);
1849 long remaining=Tools.sum(khistogram);
1850 long sumRaw1=0;
1851 long sumRaw2=0;
1852 long sum1=0;
1853 long sum2=0;
1854 long sumsquare=0;
1855 for(int i=0; i<lim; i++){
1856 long x=khistogram.get(i);
1857 long y=((x+i/2)/(i<1 ? 1 : i)); //x+i/2 rounds to compensate for colliding kmers being put in an overly high bin
1858 // long y=((x)/(i<1 ? 1 : i));
1859 sumRaw1+=x;
1860 sum1+=y;
1861 sumsquare+=(x*Tools.max(1, i));
1862 if(bsw!=null){
1863 if(PRINT_ZERO_COVERAGE /*|| x>0*/ || y>0 || HIST_COLUMNS==1){
1864 if(HIST_COLUMNS>1){
1865 bsw.print(i);
1866 bsw.print('\t');
1867 }
1868 if(HIST_COLUMNS==3){
1869 bsw.print(x);
1870 bsw.print('\t');
1871 }
1872 bsw.print(y);
1873 bsw.print('\n');
1874 }
1875 }
1876 if(sumRaw1>=remaining){break;} //Stop once there is no more coverage, even if PRINT_ZERO_COVERAGE is not set.
1877 }
1878 for(int i=lim; i<khistogram.length(); i++){
1879 long x=khistogram.get(i);
1880 sumRaw2+=x;
1881 long y=((x+i/2)/(i<1 ? 1 : i)); //x+i/2 rounds to compensate for colliding kmers being put in an overly high bin
1882 // long y=((x)/(i<1 ? 1 : i));
1883 sum2+=y;
1884 }
1885 if(bsw!=null){
1886 if(sumRaw2>0 || sum2>0){
1887 if(HIST_COLUMNS>1){
1888 bsw.print(lim);
1889 bsw.print('\t');
1890 }
1891 if(HIST_COLUMNS==3){
1892 bsw.print(sumRaw2);
1893 bsw.print('\t');
1894 }
1895 bsw.print(sum2);
1896 bsw.print('\n');
1897 }
1898 bsw.poisonAndWait();
1899 outstream.println("\nWrote histogram to "+khistFile);
1900 }
1901
1902 long histCount=Tools.sum(khistogram); //Total number of kmers counted
1903 long halfCount=(histCount+1)/2;
1904 double histCountU=0; //Unique kmers counted
1905 long temp1=0;
1906 double temp2=0;
1907 int median_all=-1;
1908 int median_unique=-1;
1909 for(int i=0; i<khistogram.length(); i++){
1910 long x=khistogram.get(i);
1911 temp1+=x;
1912 if(temp1>=halfCount && median_all<0){median_all=i;}
1913 // histSum+=(x*(double)i);
1914 histCountU+=(x/(double)Tools.max(1, i));
1915 }
1916 double halfCount2=(histCountU)/2;
1917 for(int i=0; i<khistogram.length(); i++){
1918 long x=khistogram.get(i);
1919 temp2+=(x/Tools.max(i, 1.0));
1920 if(temp2>=halfCount2 && median_unique<0){
1921 median_unique=i;
1922 break;
1923 }
1924 }
1925 if(median_all<0){median_all=0;}
1926 double avg_all=sumsquare/(double)histCount;
1927 double avg_unique=histCount/histCountU;
1928 double stdev_unique=Tools.standardDeviationHistogramKmer(khistogram);
1929 double stdev_all=Tools.standardDeviationHistogram(khistogram);
1930 outstream.println("Total kmers counted: \t"+(sumRaw1+sumRaw2));
1931
1932 double uniqueC=((sum1+sum2)*100.0/(sumRaw1+sumRaw2));
1933 double uniqueE=((estUnique)*100.0/(sumRaw1+sumRaw2));
1934 double uniqueM=Tools.max(uniqueC, uniqueE);
1935 outstream.println("Total unique kmer count: \t"+(sum1+sum2));
1936 if(CANONICAL){outstream.println("Includes forward kmers only.");}
1937 outstream.println("The unique kmer estimate can be more accurate than the unique count, if the tables are very full.");
1938 outstream.println("The most accurate value is the greater of the two.");
1939 outstream.println();
1940
1941 outstream.println("Percent unique: \t"+(uniqueM<10 ? " " : "")+Tools.format("%.2f%%", uniqueM));
1942
1943 outstream.println("Depth average: \t"+Tools.format("%.2f\t(unique kmers)", avg_unique));
1944 outstream.println("Depth median: \t"+Tools.format("%d\t(unique kmers)", median_unique));
1945 outstream.println("Depth standard deviation: \t"+Tools.format("%.2f\t(unique kmers)", stdev_unique));
1946 outstream.println("Corrected depth average: \t"+Tools.format("%.2f\t", Tools.observedToActualCoverage(avg_unique)));
1947
1948 outstream.println("\nDepth average: \t"+Tools.format("%.2f\t(all kmers)", avg_all));
1949 outstream.println("Depth median: \t"+Tools.format("%d\t(all kmers)", median_all));
1950 outstream.println("Depth standard deviation: \t"+Tools.format("%.2f\t(all kmers)", stdev_all));
1951
1952 double avgReadLen=totalBases*1.0/totalReads;
1953 double readDepth=median_all*(avgReadLen/(avgReadLen-k+1));
1954
1955 outstream.println("\nApprox. read depth median: \t"+Tools.format("%.2f", (readDepth)));
1956 }
1957
1958
1959 if(rhistogram!=null){
1960 TextStreamWriter tswh=null;
1961 StringBuilder sb=new StringBuilder(100);
1962 if(USE_RHISTOGRAM && rhistFile!=null){
1963 tswh=new TextStreamWriter(rhistFile, overwrite, false, false);
1964 tswh.start();
1965 tswh.print("#Depth\tReads\tBases\n");
1966 }
1967 int lim=(int)(HIST_LEN_PRINT-1);
1968 long remaining=Tools.sum(rhistogram);
1969 long sumReads1=0;
1970 long sumReads2=0;
1971 long sumBases1=0;
1972 long sumBases2=0;
1973 long sumSquareReads=0;
1974 long sumSquareBases=0;
1975 for(int i=0; i<lim; i++){
1976 final long x=rhistogram.get(i);
1977 final long y=bhistogram.get(i);
1978 sumReads1+=x;
1979 sumBases1+=y;
1980 sumSquareReads+=(x*Tools.max(1, i));
1981 sumSquareBases+=(y*Tools.max(1, i));
1982 if(tswh!=null){
1983 if(PRINT_ZERO_COVERAGE /*|| x>0*/ || y>0){
1984 sb.append(i).append('\t');
1985 sb.append(x).append('\t');
1986 sb.append(y).append('\n');
1987 }
1988 tswh.print(sb.toString());
1989 sb.setLength(0);
1990 }
1991 if(sumReads1>=remaining){break;} //Stop once there is no more coverage, even if PRINT_ZERO_COVERAGE is not set.
1992 }
1993 for(int i=lim; i<rhistogram.length(); i++){
1994 final long x=rhistogram.get(i);
1995 final long y=bhistogram.get(i);
1996 sumReads2+=x;
1997 sumBases2+=y;
1998 }
1999 if(tswh!=null){
2000 if(sumReads2>0 || sumBases2>0){
2001 sb.append(lim).append('\t');
2002 sb.append(sumReads2).append('\t');
2003 sb.append(sumBases2).append('\n');
2004 }
2005 tswh.print(sb.toString());
2006 tswh.poison();
2007 tswh.waitForFinish();
2008 outstream.println("\nWrote histogram to "+rhistFile);
2009 }
2010
2011 long rhistCount=Tools.sum(rhistogram); //Total number of reads counted
2012 long bhistCount=Tools.sum(bhistogram); //Total number of bases counted
2013 int median_reads=-1;
2014 int median_bases=-1;
2015 {
2016 long halfCount=(rhistCount+1)/2;
2017 long temp=0;
2018 for(int i=0; i<rhistogram.length(); i++){
2019 long x=rhistogram.get(i);
2020 temp+=x;
2021 if(temp>=halfCount && median_reads<0){median_reads=i;}
2022 }
2023 if(median_reads<0){median_reads=0;}
2024 }
2025 {
2026 long halfCount=(bhistCount+1)/2;
2027 long temp=0;
2028 for(int i=0; i<bhistogram.length(); i++){
2029 long x=bhistogram.get(i);
2030 temp+=x;
2031 if(temp>=halfCount && median_bases<0){median_bases=i;}
2032 }
2033 if(median_bases<0){median_bases=0;}
2034 }
2035 double avg_reads=sumSquareReads/(double)rhistCount;
2036 double avg_bases=sumSquareBases/(double)bhistCount;
2037 // double read_stdev_unique=Tools.standardDeviationHistogramKmer(rhistogram_total);
2038 double read_stdev_all=Tools.standardDeviationHistogram(rhistogram);
2039 double base_stdev_all=Tools.standardDeviationHistogram(bhistogram);
2040 outstream.println("Total reads counted: \t"+(sumReads1+sumReads2));
2041
2042 // double uniqueC=((sumBases1+sumBases2)*100.0/(sumReads1+sumReads2));
2043 // double uniqueE=((estUnique)*100.0/(sumReads1+sumReads2));
2044 // double uniqueM=Tools.max(uniqueC, uniqueE);
2045 outstream.println("Total bases counted: \t"+(sumBases1+sumBases2));
2046
2047 outstream.println("Read depth average: \t"+Tools.format("%.2f", avg_reads));
2048 outstream.println("Read depth median: \t"+Tools.format("%d", median_reads));
2049 outstream.println("Read depth standard deviation:\t"+Tools.format("%.2f", read_stdev_all));
2050
2051 outstream.println("\nBase depth average: \t"+Tools.format("%.2f)", avg_bases));
2052 outstream.println("Base depth median: \t"+Tools.format("%d", median_bases));
2053 outstream.println("Base depth standard deviation:\t"+Tools.format("%.2f", base_stdev_all));
2054 }
2055
2056 if(errorState){throw new RuntimeException("BBNorm terminated in an error state; the output may be corrupt.");}
2057
2058 return totalBases;
2059 }
2060
2061
2062
2063 /**
2064 * Locates and fixes spikes in a coverage profile (potentially) caused by false positives in a bloom filter.
2065 * Theory: If a high-count kmer is adjacent on both sides to low-count kmers, it may be a false positive.
2066 * It could either be reduced to the max of the two flanking points or examined in more detail.
2067 * @param cov An array of kmer counts for adjacent kmers in a read.
2068 */
2069 private static void fixSpikes(int[] cov){
2070
2071 for(int i=1; i<cov.length-1; i++){
2072 long a=Tools.max(1, cov[i-1]);
2073 int b=cov[i];
2074 long c=Tools.max(1, cov[i+1]);
2075 if(b>1 && b>a && b>c){
2076 //peak
2077 if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
2078 //spike
2079 cov[i]=(int)Tools.max(a, c);
2080 }
2081 }
2082 }
2083 }
2084
2085 private static void fixSpikes(int[] cov, long[] kmers, KCountArray kca, final int k){
2086 assert(k<32) : "this function not tested with k>31";
2087 if(cov.length<3){return;}
2088 if(cov[1]-cov[0]>1){
2089 cov[0]=kca.readPrecise(kmers[0], k, true);
2090 }
2091 if(cov[cov.length-1]-cov[cov.length-2]>1){
2092 cov[cov.length-1]=kca.readPrecise(kmers[cov.length-1], k, true);
2093 }
2094
2095 for(int i=1; i<cov.length-1; i++){
2096 int b=cov[i];
2097 if(b>1){
2098 long a=Tools.max(1, cov[i-1]);
2099 long c=Tools.max(1, cov[i+1]);
2100 long key=kmers[i];
2101
2102 if(b>a && b>c){
2103 //peak
2104 if(b<6 || b>a+1 || b>c+1){
2105 cov[i]=kca.readPreciseMin(key, k, true);
2106 }
2107 // if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
2108 // //spike
2109 // int b1=(int)((a+c)/2);
2110 // int b2=kca.readLeft(key, k, CANONICAL);
2111 // int b3=kca.readRight(key, k, CANONICAL);
2112 // array[i]=Tools.min(b, b1, b2, b3);
2113 // }
2114 // else
2115 // {
2116 //// array[i]=kca.readPreciseMin(key, k, CANONICAL);
2117 // }
2118 }
2119 // else
2120 // if(Tools.max(ada, adc)>=Tools.max(2, Tools.min((int)a, b, (int)c)/4)){
2121 // array[i]=kca.readPrecise(key, k, CANONICAL);
2122 // }
2123 // else
2124 // if(b>a+1 || b>c+1){
2125 // //steep
2126 // array[i]=kca.readPrecise(key, k, CANONICAL);
2127 // }
2128 }
2129 }
2130 }
2131
2132
2133 private static int correctErrors(Read r, int[] cov, long[] kmers, KCountArray kca, final int k,
2134 final int low, final int high, final int mult, int maxToCorrect, int maxQual, boolean kmersAlreadyValid, boolean coverageAlreadyValid, long[] qhist,
2135 final boolean markOnly, Kmer longkmer){
2136 assert(k<32) : "this function not tested with k>31";
2137 assert(maxToCorrect>0) : "Don't do error correction with a maximum of 0 errors; it's a waste of time.";
2138 if(maxToCorrect<1){return 0;}
2139
2140 if(!kmersAlreadyValid){kmers=r.toKmers(k, 0, kmers, false, longkmer);}
2141 if(kmers==null || kmers.length<3){return -99;}
2142
2143 if(!coverageAlreadyValid){cov=generateCoverage(kca, k, cov, kmers, true);}
2144
2145 int disc=countDiscontinuities(cov, low, high, mult);
2146
2147 if(disc==0){return 0;}
2148
2149 byte[] copy=r.bases.clone();
2150
2151 byte[] suffix=new byte[SUFFIX_LEN];
2152
2153 int cfl=0, cfr=0;
2154
2155 if(CORRECT_FROM_LEFT){
2156 cfl=correctErrorsFromLeft(r, cov, kmers, kca, k, low, high, mult, maxToCorrect, maxQual, suffix, qhist, markOnly, longkmer);
2157 if(cfl<0){
2158 //Failed correction.
2159 r.bases=copy;
2160 return cfl;
2161 }
2162 maxToCorrect-=cfl;
2163 }
2164
2165 if(CORRECT_FROM_RIGHT && maxToCorrect>0){
2166 {//Optional block - allows saving of errors corrected from left even if correctErrorsFromRight fails.
2167 if(cfl>0){
2168 for(int i=0; i<r.length(); i++){
2169 copy[i]=r.bases[i];
2170 }
2171 }
2172 }
2173 cfr=correctErrorsFromRight(r, cov, kmers, kca, k, low, high, mult, maxToCorrect, maxQual, suffix, qhist, markOnly, longkmer);
2174 if(cfr<0){
2175 //Failed correction.
2176 r.bases=copy;
2177 return cfr;
2178 }
2179 }
2180
2181 return cfl+cfr;
2182 }
2183
2184 private static int markErrors(Read r, int[] cov, long[] kmers, KCountArray kca, final int k,
2185 final int low, final int high, final int mult, int maxToCorrect, boolean kmersAlreadyValid, boolean coverageAlreadyValid, long[] qhist, Kmer longkmer){
2186 assert(k<32) : "this function not tested with k>31";
2187 assert(maxToCorrect>0) : "Don't do error correction with a maximum of 0 errors; it's a waste of time.";
2188 if(maxToCorrect<1){return 0;}
2189
2190 if(!kmersAlreadyValid){kmers=r.toKmers(k, 0, kmers, false, longkmer);}
2191 if(kmers==null || kmers.length<3){return 0;}
2192
2193 if(!coverageAlreadyValid){cov=generateCoverage(kca, k, cov, kmers, true);}
2194
2195 int disc=countDiscontinuities(cov, low, high, mult);
2196
2197 if(disc==0){return 0;}
2198
2199 int cfl=0, cfr=0;
2200
2201 if(CORRECT_FROM_LEFT){
2202 cfl=markErrorsFromLeft(r, cov, k, low, high, mult, maxToCorrect, qhist);
2203 maxToCorrect-=cfl;
2204 }
2205
2206 if(CORRECT_FROM_RIGHT){
2207 cfr=markErrorsFromRight(r, cov, k, low, high, mult, maxToCorrect, qhist);
2208 }
2209
2210 int marked=cfl+cfr;
2211 final byte[] quals=r.quality;
2212 if(marked>0){
2213 int found=0;
2214 if(quals!=null){
2215 for(int i=0; i<quals.length; i++){
2216 byte q=quals[i];
2217 if(q<0){
2218 byte q2=(byte)(MARK_WITH_1 ? 1 : Tools.max(1, -(q/2+3)));
2219 quals[i]=q2;
2220 found++;
2221 }
2222 }
2223 }
2224 assert(found==marked);
2225 }else{
2226 if(quals!=null){
2227 for(int i=0; i<quals.length; i++){
2228 assert(quals[i]>=0);
2229 }
2230 }
2231 assert(marked==0) : marked;
2232 }
2233
2234 return marked;
2235 }
2236
2237 /** Returns number of discontinuities detected. This is not the same as the number of errors,
2238 * but the presence of discontinuities indicates the presence of errors.
2239 * @param cov
2240 * @param low
2241 * @param high
2242 * @param mult
2243 * @return
2244 */
2245 private static int countDiscontinuities(final int[] cov, final int low, final int high, final int mult){
2246
2247 int found=0;
2248
2249 for(int i=2; i<cov.length; i++){
2250 int a=Tools.min(cov[i-2], cov[i-1]);
2251 int b=cov[i];
2252 if(a>=high && (b<=low || a>=b*mult)){//error
2253 found++;
2254 }
2255 }
2256
2257 for(int i=cov.length-3; i>=0; i--){
2258 int a=Tools.min(cov[i+2], cov[i+1]);
2259 int b=cov[i];
2260 if(a>=high && (b<=low || a>=b*mult)){//error
2261 found++;
2262 }
2263 }
2264
2265 return found;
2266 }
2267
2268
2269 private static void regenerateKmersAndCoverage(final Read r, final long[] kmers, final int[] cov, final KCountArray kca, final int k, boolean makeCanonical,
2270 Kmer longkmer){
2271 assert(r!=null && kmers!=null && cov!=null && kca!=null);
2272 final byte[] bases=r.bases;
2273 if(bases==null || bases.length<k){return;}
2274
2275 if(k>31){
2276 r.toKmers(k, 0, kmers, false, longkmer);
2277 generateCoverage(kca, k, cov, kmers, true);
2278 return;
2279 }
2280
2281 final int kbits=2*k;
2282 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
2283
2284 int len=0;
2285 long kmer=0;
2286 final int arraylen=bases.length-k+1;
2287 assert(kmers.length==arraylen && cov.length==arraylen);
2288
2289 for(int i=0, j=1-k; i<bases.length; i++, j++){
2290 byte b=bases[i];
2291 long x=AminoAcid.baseToNumber[b];
2292 // assert(x>=0) : "This program does not allow degenerate bases other than N. Invalid symbol: ASCII character "+b+" ("+(char)(b<33 ? ' ' : b)+")";
2293 if(x<0){
2294 len=0;
2295 kmer=0;
2296 }else{
2297 kmer=((kmer<<2)|x)&mask;
2298 len++;
2299
2300 if(len>=k){
2301 long y=kmer;
2302 if(makeCanonical){
2303 y=KCountArray.makeCanonical2(y, k);
2304 }
2305
2306 if(kmers[j]!=y){
2307 kmers[j]=y;
2308 cov[j]=kca.read(y, k, !makeCanonical);
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315
2316 private static int correctErrorsFromLeft(final Read r, final int[] cov, final long[] kmers, final KCountArray kca, final int k,
2317 final int low, final int high, final int mult, final int maxToCorrect, int maxQual, final byte[] suffix, final long[] qhist, boolean markOnly,
2318 Kmer longkmer){
2319
2320 int found=0;
2321 int corrected=0;
2322 int uncorrected=0;
2323 final byte[] quals=r.quality;
2324
2325 for(int i=PREFIX_LEN; i<cov.length; i++){
2326 // int a=Tools.min(cov[i-2], cov[i-1]);
2327 final int a=Tools.min(cov, i-PREFIX_LEN, i-1);
2328 final int b=cov[i];
2329 if(a>=high && (b<=low || a>=b*mult)){//error
2330 found++;
2331 final int loc=i+k-1;
2332 final byte q=(quals==null ? 10 : quals[loc]);
2333 if(qhist!=null){qhist[q]++;}
2334
2335 if(markOnly){
2336 corrected++;
2337 if(quals==null){r.bases[loc]='N';}
2338 // else if(q>0){quals[loc]=(byte)Tools.max(1, q/2);}
2339 else if(q>0){quals[loc]=(byte)Tools.max(1, q/2-3);}
2340 }else{
2341 if(found>maxToCorrect || q>maxQual){return 0-found;}
2342 boolean success=correctErrorFromLeft(r, cov, kmers, kca, k, low, Tools.max(high, a/2), 2*a, mult, i, suffix);
2343 if(success){
2344 corrected++;
2345 // r.toKmers(k, 0, kmers, false);
2346 // generateCoverage(kca, k, cov, kmers, true);
2347 regenerateKmersAndCoverage(r, kmers, cov, kca, k, false, longkmer);
2348 }else{
2349 uncorrected++;
2350 break;
2351 }
2352 }
2353 }
2354 }
2355
2356 // assert(false) : Arrays.toString(cov)+"\nlow="+low+", high="+high+", mult="+mult+", found="+found+", corrected="+corrected+", uncorrected="+uncorrected;
2357
2358
2359 return (uncorrected>0 ? 0-found : corrected);
2360 }
2361
2362
2363 private static int correctErrorsFromRight(final Read r, final int[] cov, final long[] kmers, final KCountArray kca, final int k,
2364 final int low, final int high, final int mult, final int maxToCorrect, int maxQual, final byte[] suffix, final long[] qhist, final boolean markOnly,
2365 Kmer longkmer){
2366
2367 int found=0;
2368 int corrected=0;
2369 int uncorrected=0;
2370 final byte[] quals=r.quality;
2371
2372 final int start=(markOnly ? Tools.min(cov.length-PREFIX_LEN-1, k-1) : cov.length-PREFIX_LEN-1);
2373 for(int i=start; i>=0; i--){
2374 // int a=Tools.min(cov[i+2], cov[i+1]);
2375 int a=Tools.min(cov, i+1, i+PREFIX_LEN);
2376 int b=cov[i];
2377 if(a>=high && (b<=low || a>=b*mult)){//error
2378 found++;
2379 final byte q=(quals==null ? 10 : quals[i]);
2380 if(qhist!=null){qhist[q]++;}
2381
2382 if(markOnly){
2383 corrected++;
2384 if(quals==null){r.bases[i]='N';}
2385 // else if(q>0){quals[i]=(byte)Tools.max(1, q/2);}
2386 else if(q>0){quals[i]=(byte)Tools.max(1, q/2-3);}
2387 }else{
2388 if(found>maxToCorrect || q>maxQual){return 0-found;}
2389 boolean success=correctErrorFromRight(r, cov, kmers, kca, k, low, Tools.max(high, a/2), 2*a, mult, i, suffix);
2390 if(success){
2391 corrected++;
2392 // r.toKmers(k, 0, kmers, false);
2393 // generateCoverage(kca, k, cov, kmers, true);
2394 regenerateKmersAndCoverage(r, kmers, cov, kca, k, false, longkmer);
2395 }else{
2396 uncorrected++;
2397 break;
2398 }
2399 }
2400 }
2401 }
2402
2403 // assert(false) : Arrays.toString(cov)+"\nlow="+low+", high="+high+", mult="+mult+", found="+found+", corrected="+corrected+", uncorrected="+uncorrected;
2404
2405
2406 return (uncorrected>0 ? 0-found : corrected);
2407 }
2408
2409
2410 private static int markErrorsFromLeft(final Read r, final int[] cov, final int k,
2411 final int low, final int high, final int mult, final int maxToCorrect, final long[] qhist){
2412
2413 int found=0;
2414 final byte[] quals=r.quality, bases=r.bases;
2415
2416 for(int i=PREFIX_LEN; i<cov.length; i++){
2417 final int a=Tools.min(cov, i-PREFIX_LEN, i-1);
2418 final int b=cov[i];
2419 if(a>=high && (b<=low || a>=b*mult)){//error
2420 final int loc=i+k-1;
2421 final byte q=(quals==null ? 10 : quals[loc]);
2422
2423 if(q>0){
2424 found++;
2425 if(qhist!=null){qhist[q]++;}
2426 if(quals==null){bases[loc]='N';}
2427 else{quals[loc]=(byte)-q;}
2428 }
2429 }
2430 }
2431 return found;
2432 }
2433
2434
2435 private static int markErrorsFromRight(final Read r, final int[] cov, final int k,
2436 final int low, final int high, final int mult, final int maxToCorrect, final long[] qhist){
2437
2438 int found=0;
2439 final byte[] quals=r.quality, bases=r.bases;
2440
2441 final int start=cov.length-PREFIX_LEN-1;
2442 for(int i=start; i>=0; i--){
2443 int a=Tools.min(cov, i+1, i+PREFIX_LEN);
2444 int b=cov[i];
2445 if(a>=high && (b<=low || a>=b*mult)){//error
2446 final byte q=(quals==null ? 10 : quals[i]);
2447
2448 if(q>0){
2449 found++;
2450 if(qhist!=null){qhist[q]++;}
2451 if(quals==null){bases[i]='N';}
2452 else{quals[i]=(byte)-q;}
2453 }
2454 }
2455 }
2456
2457 return found;
2458 }
2459
2460 private static boolean correctErrorFromLeft(final Read r, final int[] cov, final long[] kmers, final KCountArray kca, final int k,
2461 final int low, final int targetLowerBound, final int targetUpperBound, final int mult, final int loc, final byte[] suffix){
2462
2463 for(int i=0, j=loc+k-1; i<suffix.length; i++, j++){
2464 if(j<r.length()){
2465 suffix[i]=r.bases[j];
2466 }else{
2467 suffix[i]='N';
2468 }
2469 }
2470
2471 // if(r.numericID!=3500){return false;}
2472
2473
2474 long kmer=kmers[loc];
2475 final boolean defined=(AminoAcid.isFullyDefined(suffix[0]));
2476
2477 //This block added to allow correction of no-calls
2478 if(!defined && loc>0){
2479 assert(kmer==-1L) : new String(suffix)+"\t"+kmer;
2480 if(kmers[loc-1]!=-1L){
2481 final int kbits=2*k;
2482 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
2483 kmer=((kmers[loc-1]<<2)&mask);
2484 }
2485 }
2486 // int leftCov=Tools.min(cov[loc-1], cov[loc-2]);
2487
2488 // assert(false) : "kmer = "+AminoAcid.kmerToString(kmers[0], k);
2489 // assert(false) : "suffix = "+new String(suffix);
2490
2491 // assert(false) : new String(suffix)+"\t"+kmer;
2492
2493 suffix[0]='A';
2494 final int a=testRightSuffix(kca, k, kmer, suffix);
2495 suffix[0]='C';
2496 final int c=testRightSuffix(kca, k, kmer, suffix);
2497 suffix[0]='G';
2498 final int g=testRightSuffix(kca, k, kmer, suffix);
2499 suffix[0]='T';
2500 final int t=testRightSuffix(kca, k, kmer, suffix);
2501
2502 final int max=Tools.max(a, c, g, t);
2503 byte best='N';
2504
2505 // assert(false) : "rid="+r.numericID+"\n"+Arrays.toString(cov)+"\n" +
2506 // new String(r.bases)+"\n" +
2507 // "loc="+loc+", "+new String(suffix)+"\n" +
2508 // "low="+low+", high="+high+", mult="+mult+", a="+a+", c="+c+", g="+g+", t="+t+", max="+max;
2509
2510 if(max>=targetLowerBound && max<=targetUpperBound){
2511 //Found correct answer!
2512 final int max2;
2513 if(a==max){
2514 max2=Tools.max(c, g, t);
2515 best='A';
2516 }else if(c==max){
2517 max2=Tools.max(a, g, t);
2518 best='C';
2519 }else if(g==max){
2520 max2=Tools.max(a, c, t);
2521 best='G';
2522 }else if(t==max){
2523 max2=Tools.max(a, c, g);
2524 best='T';
2525 }else{
2526 max2=max;
2527 assert(false);
2528 }
2529
2530 // assert(false) : max+", "+max2+", "+low+", "+(char)best;
2531 if(max2<=low || max2*mult<=max){
2532 final int bnum=loc+k-1;
2533 r.bases[bnum]=best;
2534 if(!defined && r.quality!=null){
2535 assert(r.quality[bnum]==0) : r;
2536 r.quality[bnum]=FIXED_N_QUAL;
2537 }
2538 return true;
2539 }
2540 }
2541
2542 // assert(false) : max+", "+targetLowerBound+", "+targetUpperBound+", "+low+", "+(char)best;
2543
2544 return false;
2545 }
2546
2547 private static boolean correctErrorFromRight(final Read r, final int[] cov, final long[] kmers, final KCountArray kca, final int k,
2548 final int low, final int targetLowerBound, final int targetUpperBound, final int mult, final int loc, final byte[] suffix){
2549
2550 for(int i=0, j=loc; i<suffix.length; i++, j--){
2551 if(j>=0){
2552 suffix[i]=r.bases[j];
2553 }else{
2554 suffix[i]='N';
2555 }
2556 }
2557 // if(r.numericID!=3500){return false;}
2558
2559 long kmer=kmers[loc];
2560 final boolean defined=(AminoAcid.isFullyDefined(suffix[0]));
2561
2562 //This block added to allow correction of no-calls
2563 if(!defined && loc+1<kmers.length){
2564 assert(kmer==-1L) : new String(suffix)+"\t"+kmer;
2565 if(kmers[loc+1]!=-1L){
2566 final int kbits=2*k;
2567 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
2568 kmer=((kmers[loc+1]>>2)&mask);
2569 }
2570 }
2571 // int rightCov=Tools.min(cov[loc+1], cov[loc+2]);
2572
2573 // assert(false) : "kmer = "+AminoAcid.kmerToString(kmers[0], k);
2574 // assert(false) : "suffix = "+new String(suffix);
2575
2576 suffix[0]='A';
2577 final int a=testLeftSuffix(kca, k, kmer, suffix);
2578 suffix[0]='C';
2579 final int c=testLeftSuffix(kca, k, kmer, suffix);
2580 suffix[0]='G';
2581 final int g=testLeftSuffix(kca, k, kmer, suffix);
2582 suffix[0]='T';
2583 final int t=testLeftSuffix(kca, k, kmer, suffix);
2584
2585 final int max=Tools.max(a, c, g, t);
2586 byte best='N';
2587
2588 // assert(false) : "\nrid="+r.numericID+"\n"+Arrays.toString(cov)+"\n" +
2589 // new String(r.bases)+"\n"+
2590 // "kmer-2 = "+AminoAcid.kmerToString(kmers[loc-2], k)+"\n"+
2591 // "kmer-1 = "+AminoAcid.kmerToString(kmers[loc-1], k)+"\n"+
2592 // "kmer = "+AminoAcid.kmerToString(kmer, k)+"\n"+
2593 // "kmer+1 = "+AminoAcid.kmerToString(kmers[loc+1], k)+"\n"+
2594 // "kmer+2 = "+AminoAcid.kmerToString(kmers[loc+2], k)+"\n"+
2595 // "count=("+kca.read(kmers[loc-2], k, true)+", "+kca.read(kmers[loc-1], k, true)+", "+
2596 // kca.read(kmer, k, true)+", "+kca.read(kmers[loc+1], k, true)+", "+kca.read(kmers[loc+2], k, true)+")\n"+
2597 // "loc="+loc+", suffix="+new String(suffix)+"\n" +
2598 // "low="+low+", high="+high+", mult="+mult+", a="+a+", c="+c+", g="+g+", t="+t+", max="+max;
2599
2600 if(max>=targetLowerBound && max<=targetUpperBound){
2601 //Found correct answer!
2602 final int max2;
2603 if(a==max){
2604 max2=Tools.max(c, g, t);
2605 best='A';
2606 }else if(c==max){
2607 max2=Tools.max(a, g, t);
2608 best='C';
2609 }else if(g==max){
2610 max2=Tools.max(a, c, t);
2611 best='G';
2612 }else if(t==max){
2613 max2=Tools.max(a, c, g);
2614 best='T';
2615 }else{
2616 max2=max;
2617 assert(false);
2618 }
2619
2620 if(max2<=low || max2*mult<=max){
2621 r.bases[loc]=best;
2622 if(!defined && r.quality!=null){
2623 assert(r.quality[loc]==0) : r;
2624 r.quality[loc]=FIXED_N_QUAL;
2625 }
2626 return true;
2627 }
2628 }
2629 return false;
2630 }
2631
2632 private static int testRightSuffix(final KCountArray kca, final int k, final long kmer0, final byte[] suffix){
2633 assert(k<=31);
2634 final int kbits=2*k;
2635 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
2636
2637 long kmer=kmer0>>2;
2638 int min=Integer.MAX_VALUE;
2639
2640 // System.out.println("Processing suffix "+new String(suffix));
2641 // System.out.println("kmer = "+AminoAcid.kmerToString(kmer0, k));
2642 // System.out.println("cov = "+kca.read(kmer0, k, true));
2643
2644
2645 for(int i=0; i<suffix.length && min>0; i++){
2646 byte b=suffix[i];
2647 long x=AminoAcid.baseToNumber[b];
2648 if(x<0){
2649 //TODO: Find best next letter
2650 return 0;
2651 }
2652
2653 kmer=((kmer<<2)|x)&mask;
2654 int cov=kca.read(kmer, k, true);
2655 min=Tools.min(min, cov);
2656
2657 // System.out.println("kmer = "+AminoAcid.kmerToString(kmer, k));
2658 // System.out.println("cov = "+cov);
2659 }
2660 // System.out.println("returning "+min);
2661
2662 assert(min<Integer.MAX_VALUE);
2663 return min;
2664 }
2665
2666 private static int testLeftSuffix(final KCountArray kca, final int k, final long kmer0, final byte[] suffix){
2667 assert(k<=31);
2668 final int kbits=2*k;
2669 final int shift=kbits-2;
2670 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
2671
2672 long kmer=(kmer0<<2)&mask;
2673 int min=Integer.MAX_VALUE;
2674
2675 // System.out.println("Processing suffix "+new String(suffix));
2676 // System.out.println("kmer = "+AminoAcid.kmerToString(kmer0, k));
2677 // System.out.println("cov = "+kca.read(kmer0, k, true));
2678
2679
2680 for(int i=0; i<suffix.length && min>0; i++){
2681 byte b=suffix[i];
2682 long x=AminoAcid.baseToNumber[b];
2683 if(x<0){
2684 //TODO: Find best next letter
2685 return 0;
2686 }
2687
2688 kmer=((kmer>>2)|(x<<shift));
2689 int cov=kca.read(kmer, k, true);
2690 min=Tools.min(min, cov);
2691
2692 // System.out.println("kmer = "+AminoAcid.kmerToString(kmer, k));
2693 // System.out.println("cov = "+cov);
2694 }
2695 // System.out.println("returning "+min);
2696
2697 assert(min<Integer.MAX_VALUE);
2698 return min;
2699 }
2700
2701 private static void analyzeSpikes(int[] array, int width){
2702 if(array.length<3){return;}
2703 int peakcount=0, valleycount=0, spikecount=0, flatcount=0, slopecount=0;
2704 for(int i=1; i<array.length-1; i++){
2705 long a=array[i-1];
2706 int b=array[i];
2707 long c=array[i+1];
2708 if(b>a && b>c){
2709 peakcount++;
2710 if((b>=2*a || b>a+2) && (b>=2*c || b>c+2)){
2711 spikecount++;
2712 }
2713 }else if(b<a && b<c){
2714 valleycount++;
2715 }else if(b==a && b==c){
2716 flatcount++;
2717 }else{
2718 slopecount++;
2719 }
2720 }
2721 if(peakcount>0){peaks.addAndGet(peakcount);}
2722 if(valleycount>0){valleys.addAndGet(valleycount);}
2723 if(spikecount>0){spikes.addAndGet(spikecount);}
2724 if(flatcount>0){flats.addAndGet(flatcount);}
2725 if(slopecount>0){slopes.addAndGet(slopecount);}
2726 }
2727
2728 /**
2729 * kmer array must be valid at this point
2730 * @param r
2731 * @param kca
2732 * @param k
2733 * @param out
2734 * @param kmers
2735 * @return Array of coverage per kmer
2736 */
2737 public static int[] generateCoverage(Read r, KCountArray kca, final int k, int[] out, long[] kmers){
2738
2739 assert(kmers!=null);
2740 if(kmers==null){return null;} //Read is too short
2741
2742 out=generateCoverage(kca, k, out, kmers, k<=31);
2743
2744 if(ANALYZE_TOPOLOGY){analyzeSpikes(out, 1);}
2745 return out;
2746 }
2747
2748 /**
2749 * kmer array must be valid at this point
2750 * @param kca
2751 * @param k
2752 * @param out
2753 * @param kmers
2754 * @param makeCanonical
2755 * @return Array of coverage per kmer
2756 */
2757 public static int[] generateCoverage(KCountArray kca, int k, int[] out, long[] kmers, boolean makeCanonical){
2758 if(kmers==null){return null;}
2759
2760 if(out==null || out.length!=kmers.length){out=new int[kmers.length];}
2761 Arrays.fill(out, -1);
2762
2763 for(int i=0; i<kmers.length; i++){
2764 long kmer=kmers[i];
2765 if(kmer!=-1){
2766 int count=kca.read(kmer, k, makeCanonical);
2767 out[i]=count;
2768 }
2769 }
2770
2771 if(FIX_SPIKES){fixSpikes(out, kmers, kca, k);}
2772 return out;
2773 }
2774
2775 /** Returns {depth1, depth2, errors1, errors2} */
2776 public static int[] parseDepth(String s, int[] array){
2777 if(s==null || !s.startsWith("id=")){return null;}
2778 if(array==null){array=KillSwitch.allocInt1D(4);}
2779 String[] split=s.split("[, ]");
2780 Arrays.fill(array, -1);
2781 // assert(false) : s+"\n"+Arrays.toString(split);
2782 try {
2783 for(int i=1; i<split.length; i++){
2784 final String ss=split[i];
2785 if(ss.startsWith("d1=")){array[0]=Integer.parseInt(ss.substring(3));}
2786 else if(ss.startsWith("d2=")){array[2]=Integer.parseInt(ss.substring(3));}
2787 else if(ss.startsWith("e1=")){array[3]=Integer.parseInt(ss.substring(3));}
2788 else if(ss.startsWith("e2=")){array[4]=Integer.parseInt(ss.substring(3));}
2789 }
2790 return array;
2791 } catch (NumberFormatException e) {
2792 return null;
2793 }
2794 }
2795
2796
2797 private static class ProcessThread extends Thread{
2798
2799 ProcessThread(ConcurrentReadInputStream cris_, KCountArray kca_, KCountArray kcaup_, int k_,
2800 ConcurrentReadOutputStream rosk_, ConcurrentReadOutputStream rost_, ConcurrentReadOutputStream rosl_, ConcurrentReadOutputStream rosm_, ConcurrentReadOutputStream rosh_, ConcurrentReadOutputStream rosu_,
2801 ArrayList<Read> storage_){
2802 cris=cris_;
2803 kca=kca_;
2804 kcaup=kcaup_;
2805 k=k_;
2806 rosk=rosk_;
2807 rost=rost_;
2808 rosl=rosl_;
2809 rosm=rosm_;
2810 rosh=rosh_;
2811 rosu=rosu_;
2812 storage=storage_;
2813 }
2814
2815 @Override
2816 public void run(){
2817 errorStateT=true;
2818 randy=Shared.threadLocalRandom();
2819 if(COUNTUP){
2820 normalizeInThreadByCountup();
2821 }else{
2822 normalizeInThread();
2823 }
2824 errorStateT=false;
2825 }
2826
2827 void normalizeInThread() {
2828
2829 Kmer longkmer=(k<32 ? null : new Kmer(k));
2830
2831 ListNum<Read> ln=cris.nextList();
2832 ArrayList<Read> reads=(ln!=null ? ln.list : null);
2833
2834 final ArrayList<Read> keepList=(rosk==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2835 final ArrayList<Read> tossList=(rost==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2836 final ArrayList<Read> lowList=(rosl==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2837 final ArrayList<Read> midList=(rosm==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2838 final ArrayList<Read> highList=(rosh==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2839 final ArrayList<Read> uncList=(rosu==null ? null : new ArrayList<Read>(Shared.bufferLen()));
2840
2841 int[] cov1=null, cov2=null;
2842 long[] kmers1=null, kmers2=null;
2843
2844 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
2845 for(int rnum=0; rnum<reads.size(); rnum++){
2846 Read r1=reads.get(rnum);
2847 Read r2=r1.mate;
2848 assert(r1!=r2);
2849
2850 if(eccByOverlap && r1!=null && r2!=null){BBMerge.findOverlapStrict(r1, r2, true);}
2851
2852 if(!TRIM_AFTER_MARKING && (TRIM_LEFT_THIS_PASS || TRIM_RIGHT_THIS_PASS)){
2853 if(r1!=null){basesTrimmed+=TrimRead.trimFast(r1, TRIM_LEFT_THIS_PASS, TRIM_RIGHT_THIS_PASS, TRIM_QUALITY, trimE, 1);}
2854 if(r2!=null){basesTrimmed+=TrimRead.trimFast(r2, TRIM_LEFT_THIS_PASS, TRIM_RIGHT_THIS_PASS, TRIM_QUALITY, trimE, 1);}
2855 }
2856
2857 int depthAL1=-1, depthAL2=-1;
2858 int truedepth1=-1, truedepth2=-1;
2859 int mintruedepth1=-1, mintruedepth2=-1;
2860
2861 int readcount=0;
2862 int basecount=0;
2863
2864 int lowcount=0, totalcount=0, ec1=0, ec2=0;
2865 boolean error1=false, error2=false, uncorrectable1=false, uncorrectable2=false, marked1=false, marked2=false;
2866
2867 if(r1!=null && r1.bases!=null){
2868 readcount++;
2869 basecount+=r1.length();
2870 if(r1.length()>=k){
2871 if(verbose){outstream.println();}
2872 kmers1=r1.toKmers(k, 0, kmers1, true, longkmer);
2873 cov1=generateCoverage(kca, k, cov1, kmers1, k<32);
2874 int[] cov=cov1.clone();
2875 sortCoverageAndIncrementHistogram(cov);
2876
2877 if(cov!=null){
2878 final int covlast=cov.length-1;
2879 final int high=cov[(int)((covlast)*(1-HIGH_PERCENTILE))];
2880 final int low=cov[(int)((covlast)*(1-LOW_PERCENTILE))];
2881 mintruedepth1=low;
2882 int aboveLimit=covlast;
2883 int lc=0;
2884 final int mindepth=Tools.max(MIN_DEPTH, high/ERROR_DETECT_RATIO);
2885 truedepth1=cov[(int)((covlast)*(1-DEPTH_PERCENTILE))];
2886 while(aboveLimit>=0 && cov[aboveLimit]<mindepth){aboveLimit--;}
2887 if(aboveLimit+1>=MIN_KMERS_OVER_MIN_DEPTH || (aboveLimit>=0 && MIN_KMERS_OVER_MIN_DEPTH>cov.length)){
2888 depthAL1=cov[(int)(aboveLimit*(1-DEPTH_PERCENTILE))];
2889 }
2890 if(high<=LTHRESH || (high>=HTHRESH && low<=LTHRESH) || high>=low*ERROR_DETECT_RATIO){
2891 error1=true;
2892 if(high<=LTHRESH){errorType1++;}
2893 if(high>=HTHRESH && low<=LTHRESH){errorType2++;}
2894 if(high>=low*ERROR_DETECT_RATIO){errorType3++;}
2895 }
2896
2897 totalcount+=cov.length;
2898 if(cov[0]<=LTHRESH){
2899 lc+=cov.length;
2900 }else if(high>=HTHRESH){
2901 int lim=Tools.min(LTHRESH, high/ERROR_DETECT_RATIO);
2902 for(int i=covlast; i>=0 && cov[i]<=lim; i--){lc++;}
2903 }
2904 lowcount+=lc;
2905
2906 if(rhistogram!=null){
2907 int d=depthAL1>=0 ? depthAL1 : truedepth1>=0 ? truedepth1 : 0;
2908 d=Tools.min(d, HIST_LEN-1);
2909 rhistogram.incrementAndGet(d);
2910 bhistogram.addAndGet(d, r1.length());
2911 }
2912 }
2913 }
2914 }
2915 if(r2!=null && r2.bases!=null){
2916 readcount++;
2917 basecount+=r2.length();
2918 if(r2.length()>=k){
2919 if(verbose){outstream.println();}
2920 kmers2=r2.toKmers(k, 0, kmers2, true, longkmer);
2921 cov2=generateCoverage(kca, k, cov2, kmers2, k<32);
2922 int[] cov=cov2.clone();
2923 sortCoverageAndIncrementHistogram(cov);
2924
2925 if(cov!=null){
2926 final int covlast=cov.length-1;
2927 final int high=cov[(int)((covlast)*(1-HIGH_PERCENTILE))];
2928 final int low=cov[(int)((covlast)*(1-LOW_PERCENTILE))];
2929 mintruedepth2=low;
2930 int aboveLimit=covlast;
2931 int lc=0;
2932 final int mindepth=Tools.max(MIN_DEPTH, high/ERROR_DETECT_RATIO);
2933 truedepth2=cov[(int)((covlast)*(1-DEPTH_PERCENTILE))];
2934 while(aboveLimit>=0 && cov[aboveLimit]<mindepth){aboveLimit--;}
2935 if(aboveLimit+1>=MIN_KMERS_OVER_MIN_DEPTH || (aboveLimit>=0 && MIN_KMERS_OVER_MIN_DEPTH>cov.length)){
2936 depthAL2=cov[(int)(aboveLimit*(1-DEPTH_PERCENTILE))];
2937 }
2938 if(high<=LTHRESH || (high>=HTHRESH && low<=LTHRESH) || high>=low*ERROR_DETECT_RATIO){
2939 error2=true;
2940 if(high<=LTHRESH){errorType1++;}
2941 if(high>=HTHRESH && low<=LTHRESH){errorType2++;}
2942 if(high>=low*ERROR_DETECT_RATIO){errorType3++;}
2943 }
2944
2945 totalcount+=cov.length;
2946 if(cov[0]<=LTHRESH){
2947 lc+=cov.length;
2948 }else if(high>=HTHRESH){
2949 int lim=Tools.min(LTHRESH, high/ERROR_DETECT_RATIO);
2950 for(int i=covlast; i>=0 && cov[i]<=lim; i--){lc++;}
2951 }
2952 lowcount+=lc;
2953 cov2=cov;
2954
2955 if(rhistogram!=null){
2956 int d=depthAL2>=0 ? depthAL2 : truedepth2>=0 ? truedepth2 : 0;
2957 d=Tools.min(d, HIST_LEN-1);
2958 rhistogram.incrementAndGet(d);
2959 bhistogram.addAndGet(d, r2.length());
2960 }
2961 }
2962 }
2963 }
2964
2965 if(RENAME_THIS_PASS){
2966 if(r2==null){
2967 final String s="id="+r1.numericID+",d1="+depthAL1+(CORRECT_ERRORS_THIS_PASS ? ",e1="+(ec1<0 ? -ec1 : 0) : "");
2968 r1.id=s;
2969 if(EA){
2970 int[] quad=parseDepth(r1.id, null);
2971 assert(quad[0]==depthAL1);
2972 assert(quad[1]==-1);
2973 assert(quad[2]==(CORRECT_ERRORS_THIS_PASS ? (ec1<0 ? -ec1 : 0) : -1));
2974 assert(quad[3]==-1);
2975 }
2976 }else{
2977 final String s="id="+r1.numericID+",d1="+depthAL1+",d2="+depthAL2+(CORRECT_ERRORS_THIS_PASS ? ",e1="+(ec1<0 ? -ec1 : 0)+",e2="+(ec2<0 ? -ec2 : 0) : "");
2978 r1.id=s+" /1";
2979 r2.id=s+" /2";
2980 if(EA){
2981 int[] quad=parseDepth(r1.id, null);
2982 assert(quad[0]==depthAL1);
2983 assert(quad[1]==depthAL2);
2984 assert(quad[2]==(CORRECT_ERRORS_THIS_PASS ? (ec1<0 ? -ec1 : 0) : -1));
2985 assert(quad[3]==(CORRECT_ERRORS_THIS_PASS ? (ec2<0 ? -ec2 : 0) : -1));
2986 }
2987 }
2988 }
2989
2990 r1.errors=lowcount;
2991
2992 int maxDepth=MAX_DEPTH;
2993 int targetDepth=TARGET_DEPTH;
2994
2995 if(lowcount>0){
2996 // targetDepth=(int)((TARGET_DEPTH_BAD_LOW*(long)lowcount+TARGET_DEPTH_BAD_HIGH*(totalcount-(long)lowcount))/totalcount);
2997
2998 double fractionGood=(totalcount-lowcount)/(float)totalcount;
2999 targetDepth=(int)(TARGET_DEPTH_BAD_LOW+(TARGET_DEPTH_BAD_HIGH-TARGET_DEPTH_BAD_LOW)*(fractionGood*fractionGood));
3000 assert(TARGET_DEPTH_BAD_LOW<=TARGET_DEPTH_BAD_HIGH);
3001 assert(TARGET_DEPTH>=99999999 || (targetDepth>0 && targetDepth<=TARGET_DEPTH)) :
3002 targetDepth+", "+TARGET_DEPTH+", "+TARGET_DEPTH_BAD_LOW+", "+TARGET_DEPTH_BAD_HIGH+", "+lowcount+", "+totalcount;
3003 assert(TARGET_DEPTH>=99999999 || (targetDepth>=TARGET_DEPTH_BAD_LOW && targetDepth<=TARGET_DEPTH_BAD_HIGH)) :
3004 targetDepth+", "+TARGET_DEPTH+", "+TARGET_DEPTH_BAD_LOW+", "+TARGET_DEPTH_BAD_HIGH+", "+lowcount+", "+totalcount;
3005 maxDepth=targetDepth;
3006 }
3007
3008 final int minAL=(depthAL1>=0 ? (depthAL2>=0 ? Tools.min(depthAL1, depthAL2) : depthAL1) : depthAL2);
3009 final int maxAL=Tools.max(depthAL1, depthAL2);
3010 final int minTrueDepth=(r2==null ? truedepth1 : Tools.min(truedepth1, truedepth2));
3011 final int maxTrueDepth=Tools.max(truedepth1, truedepth2);
3012 final int depthproxyAL=USE_LOWER_DEPTH ? minAL : maxAL;
3013 final int truedepthproxy=USE_LOWER_DEPTH ? minTrueDepth : maxTrueDepth;
3014 long coin=0;
3015 if(depthproxyAL>maxDepth && (error1 || error2 || !DISCARD_BAD_ONLY)){
3016 if(r1.rand<0){
3017 coin=randy.nextInt(depthproxyAL)+1;
3018 }else{
3019 coin=((long)(r1.rand*depthproxyAL))+1;
3020 }
3021 }
3022
3023 totalReads+=readcount;
3024 totalBases+=basecount;
3025
3026 boolean toss=(depthproxyAL<0 || coin>targetDepth || (r1!=null && r1.length()<MIN_LENGTH) || (r2!=null && r2.length()<MIN_LENGTH));
3027 if(TOSS_ERROR_READS && (error1 || error2)){
3028 if(SAVE_RARE_READS && depthproxyAL<=targetDepth && depthproxyAL>=HTHRESH){
3029 //do nothing
3030 }else if(!REQUIRE_BOTH_BAD || r2==null || (error1 && error2)){
3031 toss=true;
3032 }
3033 }
3034
3035 if(TOSS_BY_LOW_TRUEDEPTH && !SAVE_RARE_READS && maxTrueDepth<MIN_DEPTH && (!REQUIRE_BOTH_BAD || (mintruedepth1<MIN_DEPTH && mintruedepth2<MIN_DEPTH))){
3036 toss=true;
3037 }
3038
3039 if(KEEP_ALL){toss=false;}
3040
3041 // if((r==null || verybad1) && (r2==null || verybad2)){toss=true;} //Always toss verybad reads. Turned out to not be helpful.
3042
3043 if(error1){errorReads++;}
3044 if(error2){errorReads++;}
3045 if(error1 || error2){errorPairs++;}
3046
3047 if(toss){
3048 if(tossList!=null){tossList.add(r1);}
3049 readsTossed+=readcount;
3050 basesTossed+=basecount;
3051 }else{
3052 if(CORRECT_ERRORS_THIS_PASS){
3053 if(r1!=null && r1.length()>=k){
3054 if(MARK_ERRORS_ONLY){
3055 ec1=markErrors(r1, cov1, kmers1, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, true, true, qhist, longkmer);
3056 errorsMarked+=ec1;
3057 if(ec1>0){marked1=true;}
3058 }else{
3059 ec1=correctErrors(r1, cov1, kmers1, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, MAX_QUAL_TO_CORRECT, true, true, qhist, MARK_ERRORS_ONLY, longkmer);
3060 if(ec1>=0){
3061 errorsCorrected+=ec1;
3062 }else{
3063 uncorrectable1=true;
3064 if(MAX_ERRORS_TO_CORRECT>0){regenerateKmersAndCoverage(r1, kmers1, cov1, kca, k, false, longkmer);}
3065 if(MARK_UNCORRECTABLE_ERRORS){
3066 ec1=markErrors(r1, cov1, kmers1, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, true, true, qhist, longkmer);
3067 errorsMarked+=ec1;
3068 if(ec1>0){marked1=true;}
3069 }else{
3070 errorsDetected-=ec1;
3071 }
3072 }
3073 }
3074 if(TRIM_AFTER_MARKING){
3075 if(marked1 || TRIM_EVEN_IF_NO_ERRORS_DETECTED){
3076 basesTrimmed+=TrimRead.trimFast(r1, TRIM_LEFT_THIS_PASS, TRIM_RIGHT_THIS_PASS, TRIM_QUALITY, trimE, 1);
3077 }
3078 }
3079 }
3080
3081 if(r2!=null && r2.length()>=k){
3082 if(MARK_ERRORS_ONLY){
3083 ec2=markErrors(r2, cov2, kmers2, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, true, true, qhist, longkmer);
3084 errorsMarked+=ec2;
3085 if(ec2>0){marked2=true;}
3086 }else{
3087 ec2=correctErrors(r2, cov2, kmers2, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, MAX_QUAL_TO_CORRECT, true, true, qhist, MARK_ERRORS_ONLY, longkmer);
3088 if(ec2>=0){
3089 errorsCorrected+=ec2;
3090 }else{
3091 uncorrectable2=true;
3092 if(MAX_ERRORS_TO_CORRECT>0){regenerateKmersAndCoverage(r2, kmers2, cov2, kca, k, false, longkmer);}
3093 if(MARK_UNCORRECTABLE_ERRORS){
3094 ec2=markErrors(r2, cov2, kmers2, kca, k, EC_LTHRESH, EC_HTHRESH, ERROR_CORRECT_RATIO, MAX_ERRORS_TO_CORRECT, true, true, qhist, longkmer);
3095 errorsMarked+=ec2;
3096 if(ec2>0){marked2=true;}
3097 }else{
3098 errorsDetected-=ec2;
3099 }
3100 }
3101 }
3102 if(TRIM_AFTER_MARKING){
3103 if(marked2 || TRIM_EVEN_IF_NO_ERRORS_DETECTED){
3104 basesTrimmed+=TrimRead.trimFast(r2, TRIM_LEFT_THIS_PASS, TRIM_RIGHT_THIS_PASS, TRIM_QUALITY, trimE, 1);
3105 }
3106 }
3107 }
3108 }
3109
3110 if(keepList!=null){keepList.add(r1);}
3111 readsKept+=readcount;
3112 basesKept+=basecount;
3113 }
3114
3115 if(depthAL1<LOW_BIN_DEPTH && depthAL2<LOW_BIN_DEPTH){
3116 readsLowBin+=readcount;
3117 basesLowBin+=basecount;
3118 if(lowList!=null){lowList.add(r1);}
3119 // }else if((depth1<0 || depth1>HIGH_BIN_DEPTH) && (depth2<0 || depth2>=HIGH_BIN_DEPTH)){
3120 }else if((depthAL1<LOW_BIN_DEPTH || depthAL1>HIGH_BIN_DEPTH) && (depthAL2<LOW_BIN_DEPTH || depthAL2>=HIGH_BIN_DEPTH)){
3121 readsHighBin+=readcount;
3122 basesHighBin+=basecount;
3123 if(highList!=null){highList.add(r1);}
3124 }else{
3125 assert((depthAL1>=LOW_BIN_DEPTH && depthAL1<=HIGH_BIN_DEPTH) || (depthAL2>=LOW_BIN_DEPTH && depthAL2<=HIGH_BIN_DEPTH)) :
3126 depthAL1+", "+depthAL2+", "+LOW_BIN_DEPTH+", "+HIGH_BIN_DEPTH;
3127 readsMidBin+=readcount;
3128 basesMidBin+=basecount;
3129 if(midList!=null){midList.add(r1);}
3130 }
3131
3132 if(uncorrectable1 || uncorrectable2){
3133 readsUncorrected+=readcount;
3134 basesUncorrected+=basecount;
3135 if(uncList!=null){uncList.add(r1);}
3136 }
3137 }
3138
3139
3140 if(storage!=null){
3141 synchronized(storage){
3142 storage.addAll(keepList);
3143 if(ADD_BAD_READS_COUNTUP){storage.addAll(tossList);}
3144 }
3145 }
3146
3147
3148 if(rosk!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3149 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3150 rosk.add(keepList, ln.id);
3151 keepList.clear();
3152 }
3153 if(rost!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3154 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3155 rost.add(tossList, ln.id);
3156 tossList.clear();
3157 }
3158
3159 if(rosl!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3160 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3161 rosl.add(lowList, ln.id);
3162 lowList.clear();
3163 }
3164 if(rosm!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3165 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3166 rosm.add(midList, ln.id);
3167 midList.clear();
3168 }
3169 if(rosh!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3170 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3171 rosh.add(highList, ln.id);
3172 highList.clear();
3173 }
3174 if(rosu!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3175 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3176 rosu.add(uncList, ln.id);
3177 uncList.clear();
3178 }
3179
3180 cris.returnList(ln);
3181 //System.err.println("fetching list");
3182 ln=cris.nextList();
3183 reads=(ln!=null ? ln.list : null);
3184 }
3185 if(verbose){System.err.println("Finished reading");}
3186 cris.returnList(ln);
3187 if(verbose){System.err.println("Returned list");}
3188 }
3189
3190
3191 void normalizeInThreadByCountup() {
3192
3193 Kmer longkmer=(k<32 ? null : new Kmer(k));
3194
3195 ListNum<Read> ln=cris.nextList();
3196 ArrayList<Read> reads=(ln!=null ? ln.list : null);
3197
3198 final ArrayList<Read> keepList=(rosk==null ? null : new ArrayList<Read>(Shared.bufferLen()));
3199 final ArrayList<Read> tossList=(rost==null ? null : new ArrayList<Read>(Shared.bufferLen()));
3200
3201 int[] cov=null, covSorted=null, covup=null;
3202 long[] kmers1=null, kmers2=null, kmers3=null;
3203
3204 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
3205 for(int rnum=0; rnum<reads.size(); rnum++){
3206 Read r=reads.get(rnum);
3207 Read r2=r.mate;
3208 assert(r!=r2);
3209
3210 int readcount=0;
3211 int basecount=0;
3212 int errors=0, nonerrors=0;
3213
3214 boolean k1valid=false, k2valid=false;
3215
3216 if(r!=null && r.bases!=null){
3217 readcount++;
3218 basecount+=r.length();
3219 if(r.length()>=k){
3220 if(verbose){outstream.println();}
3221 kmers1=r.toKmers(k, 0, kmers1, true, longkmer);
3222 k1valid=true;
3223 }
3224 }
3225 if(r2!=null && r2.bases!=null){
3226 readcount++;
3227 basecount+=r2.length();
3228 if(r2.length()>=k){
3229 if(verbose){outstream.println();}
3230 kmers2=r2.toKmers(k, 0, kmers2, true, longkmer);
3231 k2valid=true;
3232 }
3233 }
3234
3235 final int mergelen=(k1valid ? kmers1.length : 0)+(k2valid ? kmers2.length : 0);
3236 int valid=0, unique=0, desired=0, needed=0, badlyneeded=0;
3237 if(mergelen>0){
3238 if(kmers3==null || kmers3.length!=mergelen){kmers3=new long[mergelen];}
3239 int j=0;
3240 if(k1valid){
3241 for(int i=0; i<kmers1.length; i++, j++){kmers3[j]=kmers1[i];}
3242 }
3243 if(k2valid){
3244 for(int i=0; i<kmers2.length; i++, j++){kmers3[j]=kmers2[i];}
3245 }
3246 Arrays.sort(kmers3);
3247
3248 if(cov==null || cov.length!=mergelen){cov=new int[mergelen];}
3249 if(covup==null || covup.length!=mergelen){covup=new int[mergelen];}
3250 for(int i=0; i<mergelen; i++){
3251 long kmer=kmers3[i];
3252 if(kmer==-1){
3253 cov[i]=-1;
3254 covup[i]=-1;
3255 }else if(IGNORE_DUPLICATE_KMERS_COUNTUP && i>0 && kmer==kmers3[i-1]){
3256 cov[i]=-1;
3257 covup[i]=-1;
3258 valid++;
3259 }else{
3260 cov[i]=kca.read(kmer);
3261 covup[i]=kcaup.read(kmer);
3262 valid++;
3263 unique++;
3264 if(cov[i]>=MIN_DEPTH){
3265 desired++;
3266 if(covup[i]<TARGET_DEPTH){
3267 needed++;
3268 if(covup[i]<(Tools.min(TARGET_DEPTH, cov[i])*3)/4){badlyneeded++;}
3269 }
3270 }
3271 }
3272 }
3273 final int invalid=cov.length-valid;
3274
3275 if(covSorted==null || covSorted.length!=mergelen){covSorted=new int[mergelen];}
3276 for(int i=0; i<cov.length; i++){covSorted[i]=cov[i];}
3277 Arrays.sort(covSorted);
3278
3279 int prev=-1;
3280 for(int i=0; i<covSorted.length; i++){
3281 int x=covSorted[i];
3282 if(prev>-1){
3283 if((x>=HTHRESH && prev<=LTHRESH) || x>=prev*ERROR_DETECT_RATIO){
3284 errors=covSorted.length-i;
3285 break;
3286 }else{nonerrors++;}
3287 }
3288 prev=x;
3289 }
3290 }
3291
3292 int t1=Tools.max(8, (unique+5)/6);
3293 int t2=Tools.max(2, (unique+23)/24);
3294
3295 boolean toss=!((needed>=t1 || badlyneeded>=t2) && (desired>=MIN_KMERS_OVER_MIN_DEPTH || unique<MIN_KMERS_OVER_MIN_DEPTH));
3296 if(TOSS_ERROR_READS && errors>8 && (needed<2*t1 && badlyneeded<2*t2)){toss=true;}
3297 if(TOSS_ERROR_READS && errors>unique/2 && (needed<3*t1 && badlyneeded<4*t2)){toss=true;}
3298 // assert(false) : "\n"+TOSS_ERROR_READS+", "+unique+", "+desired+", "+needed+", "+badlyneeded+", "+errors+", "+t1+", "+t2;
3299 // System.out.println("valid="+valid+", unique="+unique+", desired="+desired+", needed="+needed+", toss="+toss);
3300 if(KEEP_ALL){toss=false;}
3301
3302 totalReads+=readcount;
3303 totalBases+=basecount;
3304
3305 if(toss){
3306 // System.out.println("valid="+valid+", unique="+unique+", desired="+desired+", needed="+needed+", toss="+toss);
3307 if(tossList!=null){tossList.add(r);}
3308 readsTossed+=readcount;
3309 basesTossed+=basecount;
3310 }else{
3311 // System.out.println("valid="+valid+", unique="+unique+", desired="+desired+", needed="+needed+", toss="+toss);
3312 // System.out.println("valid="+valid+", unique="+unique+", desired="+desired+", needed="+needed+", toss="+toss+"\n"+Arrays.toString(cov)
3313 // +"\n"+Arrays.toString(covup)+"\n"+Arrays.toString(kmers3));
3314 for(int i=0; i<mergelen; i++){
3315 if(cov[i]>=MIN_DEPTH){
3316 long kmer=kmers3[i];
3317 kcaup.increment(kmer);
3318 }
3319 }
3320 if(keepList!=null){keepList.add(r);}
3321 readsKept+=readcount;
3322 basesKept+=basecount;
3323 }
3324
3325 if(mergelen>0){
3326 // Arrays.sort(cov);
3327 // incrementHistogramSorted(cov);
3328 incrementHistogramSorted(covSorted);
3329 }
3330 }
3331
3332 if(storage!=null){
3333 synchronized(storage){
3334 storage.addAll(keepList);
3335 }
3336 }
3337
3338 if(rosk!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3339 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3340 rosk.add(keepList, ln.id);
3341 keepList.clear();
3342 }
3343 if(rost!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
3344 // System.err.println("Adding list "+ln.id+" of length "+reads.size());
3345 rost.add(tossList, ln.id);
3346 tossList.clear();
3347 }
3348
3349 assert(rosl==null) : "Low fraction out not supported by countup.";
3350 assert(rosm==null) : "Mid fraction out not supported by countup.";
3351 assert(rosh==null) : "High fraction out not supported by countup.";
3352 assert(rosu==null) : "TODO - Uncorrectable fraction out not supported by countup.";
3353
3354 cris.returnList(ln);
3355 //System.err.println("fetching list");
3356 ln=cris.nextList();
3357 reads=(ln!=null ? ln.list : null);
3358 }
3359 if(verbose){System.err.println("Finished reading");}
3360 cris.returnList(ln);
3361 if(verbose){System.err.println("Returned list");}
3362 }
3363
3364 private final int[] getSortedCoverageAndIncrementHistogram(Read r, int[] cov, long[] kmers,
3365 boolean kmersAlreadyValid, boolean kmersAlreadyCanonical, boolean coverageAlreadyValid, Kmer longkmer){
3366 assert(r!=null && r.bases!=null && r.length()>=k) : r;
3367
3368 if(!coverageAlreadyValid){
3369 if(!kmersAlreadyValid){kmers=r.toKmers(k, 0, kmers, false, longkmer);}
3370 cov=generateCoverage(kca, k, cov, kmers, (!kmersAlreadyCanonical && k<32));
3371 }
3372
3373 sortCoverageAndIncrementHistogram(cov);
3374 return cov;
3375 }
3376
3377 private void sortCoverageAndIncrementHistogram(int[] cov){
3378 if(cov==null || cov.length==0){return;}
3379 Arrays.sort(cov);
3380 Tools.reverseInPlace(cov);
3381 incrementHistogramSorted(cov);
3382 }
3383
3384 /** Handles coverage sorted in either direction */
3385 private final void incrementHistogramSorted(int[] cov){
3386 if(hist==null || cov==null || cov.length==0){return;}
3387
3388 // outstream.println(Arrays.toString(cov));
3389
3390 int last=cov[0];
3391 long sum=0;
3392 // long sum2=0;
3393 int i=0;
3394 while(i<cov.length && cov[i]<0){i++;}
3395 for(; i<cov.length; i++){
3396 int x=cov[i];
3397 // outstream.println("Processing "+x);
3398 if(x<0){break;}
3399 int y=Tools.min(x, HIST_LEN-1);
3400 if(y==last){sum++;}
3401 else if(sum>0){
3402 // outstream.println("Incrementing "+last+" by "+sum);
3403 // sum2+=sum;
3404 if(last<hist.length){hist[last]+=sum;}
3405 else{khistogram.addAndGet(last, sum);}
3406 sum=1;
3407 }
3408 last=y;
3409 }
3410 // outstream.println("Ended loop");
3411 if(sum>0){
3412 // outstream.println("Incrementing "+last+" by "+sum);
3413 // sum2+=sum;
3414 if(last<hist.length){hist[last]+=sum;}
3415 else{khistogram.addAndGet(last, sum);}
3416 }
3417 // assert(sum2==cov.length) : sum2+", "+cov.length+", "+last+", "+sum;
3418 }
3419
3420 private final ConcurrentReadInputStream cris;
3421 /** Premade table holding counts of input kmers */
3422 private final KCountArray kca;
3423 /** Dynamic table holding counts of output kmers */
3424 private final KCountArray kcaup;
3425 /** kmer length */
3426 private final int k;
3427 /** Stream for kept reads */
3428 private final ConcurrentReadOutputStream rosk;
3429 /** Stream for tossed reads */
3430 private final ConcurrentReadOutputStream rost;
3431 /** Stream for low-count reads */
3432 private final ConcurrentReadOutputStream rosl;
3433 /** Stream for mid-count reads */
3434 private final ConcurrentReadOutputStream rosm;
3435 /** Stream for high-count reads */
3436 private final ConcurrentReadOutputStream rosh;
3437 /** Stream for reads with uncorrectable errors */
3438 private final ConcurrentReadOutputStream rosu;
3439
3440 public final long[] hist=new long[THREAD_HIST_LEN];//(USE_HISTOGRAM ? new long[HIST_LEN] : null);
3441 public final long[] qhist=new long[128];
3442
3443 private final ArrayList<Read> storage;
3444
3445 private long totalBases=0;
3446 private long totalReads=0;
3447 // private final java.util.Random randy=new java.util.Random();
3448 private Random randy; //Note that Random does not support nextLong(long)
3449
3450 public long readsKept=0;
3451 public long readsTossed=0;
3452 public long readsLowBin=0;
3453 public long readsMidBin=0;
3454 public long readsHighBin=0;
3455 public long readsUncorrected=0;
3456 public long basesKept=0;
3457 public long basesTossed=0;
3458 public long basesLowBin=0;
3459 public long basesMidBin=0;
3460 public long basesHighBin=0;
3461 public long basesUncorrected=0;
3462
3463 public long errorReads=0;
3464 public long errorPairs=0;
3465 public long errorType1=0;
3466 public long errorType2=0;
3467 public long errorType3=0;
3468
3469 public long errorsDetected=0;
3470 public long errorsCorrected=0;
3471 public long errorsMarked=0;
3472 public long basesTrimmed=0;
3473
3474 boolean errorStateT=false;
3475 }
3476
3477 public static boolean errorState(){return errorState;}
3478 public static boolean setErrorState(boolean b){return errorState=b;}
3479
3480 public static PrintStream outstream=System.err;
3481
3482 private static long minHeight=2;
3483 private static long minVolume=5;
3484 private static int minWidth=3;
3485 private static int minPeak=2;
3486 private static int maxPeak=Integer.MAX_VALUE;
3487 private static int maxPeakCount=10;
3488 private static int ploidy=-1;
3489 private static boolean doLogScale=false;
3490 private static double logWidth=0.05;
3491
3492 public static int THREAD_HIST_LEN=1<<12;
3493 public static int HIST_LEN=1<<20;
3494 public static long HIST_LEN_PRINT=HIST_LEN;
3495 public static long HIST_COLUMNS=3;
3496 public static boolean USE_KHISTOGRAM=false;
3497 public static boolean USE_RHISTOGRAM=false;
3498 public static boolean PRINT_ZERO_COVERAGE=false;
3499 public static AtomicLongArray khistogram;
3500 public static AtomicLongArray rhistogram;
3501 public static AtomicLongArray bhistogram;
3502 public static long[] qhist_total;
3503
3504 private static int THREADS=Shared.threads();
3505 private static boolean verbose=false;
3506 private static boolean errorState=false;
3507
3508 private static boolean EA=Shared.EA();
3509
3510 private static boolean eccByOverlap=false;
3511 private static boolean eccByOverlapAuto=false;
3512
3513 /** High-depth reads will be downsampled to this level in the current pass */
3514 private static int TARGET_DEPTH=100;
3515 /** Error-containing reads will be downsampled to at least this level in the current pass */
3516 private static int TARGET_DEPTH_BAD_LOW=100;
3517 /** Error-containing reads will be downsampled to at most this level in the current pass */
3518 private static int TARGET_DEPTH_BAD_HIGH=100;
3519 /** High-depth reads will be downsampled to this level in the final pass */
3520 private static int TARGET_DEPTH_F=100;
3521 /** High-depth reads will be downsampled to this level in the first pass */
3522 private static int TARGET_DEPTH_1=-1;
3523 /** Reads under this depth will not be downsampled */
3524 private static int MAX_DEPTH=-1;
3525 /** Reads under this depth will be discarded, and kmers under this depth will be ignored */
3526 private static int MIN_DEPTH=5;
3527 /** Reads without this many kmers of at least min depth will be discarded */
3528 private static int MIN_KMERS_OVER_MIN_DEPTH=15;
3529 /** Position in sorted kmer depths array to use as proxy for overall read depth */
3530 private static float DEPTH_PERCENTILE=0.54f;
3531
3532 /** Normalize based on depth of read with lower depth, instead of read with higher depth */
3533 public static boolean USE_LOWER_DEPTH=true;
3534 /** Throw out reads with depth at absolute depth percentile below mindepth */
3535 public static boolean TOSS_BY_LOW_TRUEDEPTH=true;
3536 /** Throw out reads containing errors in the current pass */
3537 public static boolean TOSS_ERROR_READS=false;
3538 /** Throw out reads containing errors in the final pass */
3539 public static boolean TOSS_ERROR_READS_F=false;
3540 /** Throw out reads containing errors in the first pass */
3541 public static boolean TOSS_ERROR_READS_1=false;
3542 /** Only downsample error reads on current pass (keep all error-free reads) */
3543 public static boolean DISCARD_BAD_ONLY=false;
3544 /** Only downsample error reads on first pass (keep all error-free reads) */
3545 public static boolean DISCARD_BAD_ONLY_F=false;
3546 /** Only downsample error reads on final pass (keep all error-free reads) */
3547 public static boolean DISCARD_BAD_ONLY_1=false;
3548 /** Require both reads in a pair to be bad before tossing the read */
3549 public static boolean REQUIRE_BOTH_BAD=false;
3550 /** Don't toss error reads with depth below max */
3551 public static boolean SAVE_RARE_READS=false;
3552 /** Position in sorted kmer depths array to use as proxy for high depth kmer */
3553 public static float HIGH_PERCENTILE=0.90f;
3554 /** Position in sorted kmer depths array to use as proxy for low depth kmer */
3555 public static float LOW_PERCENTILE=0.25f;
3556 /** Position in sorted kmer depths array to use as proxy for low depth kmer, during countup presort pass */
3557 public static float LOW_PERCENTILE_COUNTUP=0.20f;
3558 /** Set to true to keep error reads during countup presort pass */
3559 public static boolean ADD_BAD_READS_COUNTUP=false;
3560
3561 /** Reads with a high/low ratio of at least this are considered error reads. */
3562 public static int ERROR_DETECT_RATIO=125;
3563 /** Threshold for high kmer in detection. A high kmer at this or above is considered possibly non-error. */
3564 public static int HTHRESH=12;
3565 /** Threshold for low kmer in detection. Kmers at this and below are always considered errors. */
3566 public static int LTHRESH=3;
3567
3568 /** Reads with a high/low ratio of at least this are considered error reads. */
3569 public static int ERROR_CORRECT_RATIO=140;
3570 /** Threshold for high kmer in correction. A high kmer at this or above considered possibly non-error. */
3571 public static int EC_HTHRESH=22;
3572 /** Threshold for low kmer in correction. Kmers at this and below are considered errors if an adjacent kmer is at or above the high thresh. */
3573 public static int EC_LTHRESH=2;
3574
3575 public static double TARGET_BAD_PERCENT_LOW=0.85;
3576 public static double TARGET_BAD_PERCENT_HIGH=1.5;
3577
3578 private static long FILTERBYTES=-1;
3579
3580 private static int SUFFIX_LEN=3;
3581 private static int PREFIX_LEN=3;
3582
3583 private static boolean TRIM_LEFT_THIS_PASS=false;
3584 private static boolean TRIM_RIGHT_THIS_PASS=false;
3585 private static boolean RENAME_THIS_PASS=false;
3586
3587 private static boolean CORRECT_ERRORS_THIS_PASS=false;
3588 private static boolean MARK_ERRORS_ONLY=false;
3589 private static boolean TRIM_AFTER_MARKING=false;
3590 private static boolean TRIM_EVEN_IF_NO_ERRORS_DETECTED=true;
3591 private static boolean MARK_WITH_1=false;
3592 private static boolean MARK_UNCORRECTABLE_ERRORS=false;
3593 private static boolean USE_ECC1=false;
3594 private static boolean USE_ECCF=false;
3595 private static boolean CORRECT_FROM_LEFT=true;
3596 private static boolean CORRECT_FROM_RIGHT=true;
3597
3598 private static double prefilterFraction=0.35;
3599
3600 private static int LOW_BIN_DEPTH=10;
3601 private static int HIGH_BIN_DEPTH=80;
3602
3603 /** ECC_LIMIT */
3604 private static int MAX_ERRORS_TO_CORRECT=3;
3605 private static int MAX_QUAL_TO_CORRECT=127;
3606
3607
3608 public static boolean IGNORE_DUPLICATE_KMERS_COUNTUP=true;
3609
3610 public static boolean CANONICAL=true;
3611 public static boolean ZERO_BIN=false;
3612 public static boolean FIX_SPIKES=false;
3613 public static boolean KEEP_ALL=false;
3614 public static boolean ordered=false;
3615 public static boolean overwrite=true;
3616 public static boolean append=false;
3617 public static boolean prefilter=false;
3618 public static boolean renameReads=false;
3619 public static boolean DETERMINISTIC=true;
3620 public static boolean COUNTUP=false;
3621 public static boolean ANALYZE_TOPOLOGY=false;
3622 /** Quality-trim left side of reads before further processing. */
3623 public static boolean TRIM_LEFT=false;
3624 /** Quality-trim right side of reads before further processing. */
3625 public static boolean TRIM_RIGHT=false;
3626 public static int MIN_LENGTH=1;
3627 /** Trim until 2 consecutive bases are encountered with at least this quality. */
3628 public static float TRIM_QUALITY=5;
3629 /** Error rate for trimming (derived from trimq) */
3630 private static float trimE;
3631
3632 public static boolean REMOVE_TEMP_FILES=true;
3633 public static boolean USE_TMPDIR=true;
3634 public static String TMPDIR=Shared.tmpdir();
3635 public static boolean useTmpdir(){return USE_TMPDIR && TMPDIR!=null;}
3636
3637 private static HashSet<String> temp_file_set=null;
3638
3639 public static AtomicLong peaks=new AtomicLong();
3640 public static AtomicLong spikes=new AtomicLong();
3641 public static AtomicLong flats=new AtomicLong();
3642 public static AtomicLong valleys=new AtomicLong();
3643 public static AtomicLong slopes=new AtomicLong();
3644
3645 public static final byte FIXED_N_QUAL=20;
3646
3647 }