Debian Codegraph @

current/align2/AbstractMapper.java

raw symbols SCIP
1 package align2;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.lang.Thread.State;
6 import java.util.ArrayList;
7
8 import bloom.BloomFilter;
9 import dna.ChromosomeArray;
10 import dna.Data;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import fileIO.TextStreamWriter;
14 import jgi.CoveragePileup;
15 import shared.KillSwitch;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.ConcurrentLegacyReadInputStream;
23 import stream.ConcurrentReadInputStream;
24 import stream.ConcurrentReadOutputStream;
25 import stream.FASTQ;
26 import stream.RandomReadInputStream3;
27 import stream.Read;
28 import stream.ReadStreamWriter;
29 import stream.SamHeader;
30 import stream.SamLine;
31 import stream.SequentialReadInputStream;
32 import stream.SiteScore;
33 import tracker.ReadStats;
34
35 /**
36 * Abstract superclass created from BBMap variants.
37 * Handles argument parsing, I/O stream initialization and shutdown,
38 * thread management, statistics collection and formatting.
39 * @author Brian Bushnell
40 * @date Oct 15, 2013
41 *
42 */
43 public abstract class AbstractMapper {
44
45 public AbstractMapper(String[] args){
46 CoveragePileup.printCommand=false;
47 if(Shared.COMMAND_LINE==null){
48 Shared.COMMAND_LINE=(args==null ? null : args.clone());
49 Shared.BBMAP_CLASS=this.getClass().getName();
50 int x=Shared.BBMAP_CLASS.lastIndexOf('.');
51 if(x>=0){Shared.BBMAP_CLASS=Shared.BBMAP_CLASS.substring(x+1);}
52 }
53 SamHeader.PN="BBMap";
54 setDefaults();
55 String[] args2=preparse0(args);
56 String[] args3=preparse(args2);
57 parse(args3);
58 postparse(args3);
59 setup();
60 checkFiles();
61 }
62
63 final void abort(AbstractMapThread[] mtts, String message){
64 // System.err.println("Attempting to abort.");
65 closeStreams(cris, rosA, rosM, rosU, rosB);
66 KillSwitch.kill(message==null ? "" : message);
67 // if(mtts!=null){int x=shutDownThreads(mtts, true);}
68 // if(message==null){throw new RuntimeException();}
69 // throw new RuntimeException(message);
70 }
71
72 /** In megabytes */
73 final void adjustThreadsforMemory(long threadMem){
74 Runtime rt=Runtime.getRuntime();
75 long mmemory=rt.maxMemory()/1000000;
76 long tmemory=rt.totalMemory()/1000000;
77 long fmemory=rt.freeMemory()/1000000;
78 long umemory=tmemory-fmemory;
79 long amemory=mmemory-umemory;
80 // System.err.println("mmemory="+mmemory+", tmemory="+tmemory+", fmemory="+fmemory+", umemory="+umemory+", amemory="+amemory);
81 // int maxThreads=Tools.max(1, (int)((amemory-70)/threadMem));
82 int maxThreads=(int)((amemory-100)/threadMem);
83 if(Shared.threads()>maxThreads){
84 System.err.println("\nMax Memory = "+mmemory+" MB\nAvailable Memory = "+amemory+" MB");
85 if(maxThreads<1){abort(null, "\n\nNot enough memory. Please run on a node with at least "+((long)((umemory+100+threadMem)*1.15))+" MB.\n");}
86 System.err.println("Reducing threads from "+Shared.threads()+" to "+maxThreads+" due to low system memory.");
87 Shared.setThreads(maxThreads);
88 }
89 }
90
91 abstract void setDefaults();
92
93 abstract String[] preparse(String[] args);
94
95 abstract void postparse(String[] args);
96
97 abstract void setup();
98
99 abstract void loadIndex();
100
101 abstract void processAmbig2();
102
103 abstract void testSpeed(String[] args);
104
105 abstract void setSemiperfectMode();
106
107 abstract void setPerfectMode();
108
109 abstract void printSettings(int k);
110
111 private final void parse(String[] args){
112
113 {//Preparse block for help, config files, and outstream
114 PreParser pp=new PreParser(args, getClass(), true);
115 args=pp.args;
116 outstream=pp.outstream;
117 }
118
119 Read.TO_UPPER_CASE=true;
120
121 Timer t=new Timer();
122 boolean setMaxIndel1=false, setMaxIndel2=false;
123 boolean forceRebuild=false;
124 Parser parser=new Parser();
125 parser.minTrimLength=minTrimLength;
126
127 for(int i=0; i<args.length; i++){
128 final String arg=(args[i]==null ? "null" : args[i]);
129 final String[] split=arg.split("=");
130 final String a=split[0].toLowerCase();
131 String b=split.length>1 ? split[1] : null;
132
133 if(Parser.parseZip(arg, a, b)){
134 if(a.equals("ziplevel") || a.equals("zl")){//Handle conflated term
135 ziplevel=Integer.parseInt(b);
136 }
137 }else if(Parser.parseHist(arg, a, b)){
138 //do nothing
139 }else if(Parser.parseSam(arg, a, b)){
140 //do nothing
141 }else if(Parser.parseCommonStatic(arg, a, b)){
142 //do nothing
143 }else if(Parser.parseQuality(arg, a, b)){
144 //do nothing
145 }else if(Parser.parseFasta(arg, a, b)){
146 //do nothing
147 }else if(parser.parseInterleaved(arg, a, b)){
148 //do nothing
149 }else if(parser.parseCommon(arg, a, b)){
150 //do nothing
151 }else if(parser.parseMapping(arg, a, b)){
152 //do nothing
153 }else if(parser.parseTrim(arg, a, b)){
154 //do nothing
155 }else if(a.equals("printtoerr")){
156 if(Parse.parseBoolean(b)){
157 outstream=System.err;
158 outstream=System.err;
159 }
160 }else if(a.equals("path") || a.equals("root")){
161 Data.setPath(b);
162 }else if(a.equals("ref") || a.equals("reference") || a.equals("fasta")){
163 reference=b;
164 if(reference!=null && !Tools.isReadableFile(b)) {
165 if(reference.equalsIgnoreCase("phix")) {
166 reference=Data.findPath("?phix2.fa.gz");
167 }
168 }
169 }else if(a.equals("in") || a.equals("in1")){
170 in1=b;
171 }else if(a.equals("in2")){
172 in2=b;
173 }else if(a.equals("qfin") || a.equals("qfin1")){
174 qfin1=b;
175 }else if(a.equals("qfin2")){
176 qfin2=b;
177 }else if(a.equals("out")){
178 if(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")){
179 outFile=null;
180 }else{
181 outFile=b;
182 // outFile=b.replace('#', '1');
183 // outFile2=(b.contains("#") ? b.replace('#', '2') : null);
184 }
185 }else if(a.equals("out1")){
186 outFile=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
187 if(outFile==null){
188 outFile=null;
189 }
190 }else if(a.equals("out2")){
191 outFile2=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
192 }else if(a.equals("outm") || a.equals("outm1") || a.equals("outmapped") || a.equals("outmapped1")){
193 outFileM=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
194 }else if(a.equals("outm2") || a.equals("outmapped2")){
195 outFileM2=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
196 }else if(a.equals("outu") || a.equals("outu1") || a.equals("outunmapped") || a.equals("outunmapped1")){
197 outFileU=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
198 }else if(a.equals("outu2") || a.equals("outunmapped2")){
199 outFileU2=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
200 }else if(a.equals("outb") || a.equals("outb1") || a.equals("outblack") || a.equals("outblack1") || a.equals("outblacklist") || a.equals("outblacklist1")){
201 outFileB=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
202 }else if(a.equals("outb2") || a.equals("outblack2") || a.equals("outblacklist2")){
203 outFileB2=(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")) ? null : b;
204 }else if(a.equals("blacklist") && !Data.scaffoldPrefixes){
205 if(b==null || b.equalsIgnoreCase("null") || b.equalsIgnoreCase("none")){blacklist=null;}
206 else{
207 if(blacklist==null){blacklist=new ArrayList<String>();}
208 if(b.indexOf(',')<0 || new File(b).exists()){blacklist.add(b);}
209 else{
210 String[] temp=b.split(",");
211 for(String tmp : temp){blacklist.add(tmp);}
212 }
213 }
214 }else if(a.startsWith("out_") && b!=null){
215 //ignore, it will be processed later
216 if(splitterOutputs==null){splitterOutputs=new ArrayList<String>();}
217 splitterOutputs.add(b);
218 }else if(a.equals("bamscript") || a.equals("bs")){
219 bamscript=b;
220 }else if(a.equals("local")){
221 LOCAL_ALIGN=Parse.parseBoolean(b);
222 }else if(a.equals("averagepairdist") || a.equals("apd")){
223 AbstractMapThread.INITIAL_AVERAGE_PAIR_DIST=Parse.parseIntKMG(b);
224 }else if(a.equals("deterministic")){
225 AbstractMapThread.DYNAMIC_INSERT_LENGTH=!Parse.parseBoolean(b);
226 }else if(a.equals("skipreads")){
227 AbstractMapThread.SKIP_INITIAL=Parse.parseKMG(b);
228 }else if(a.equals("readlen") || a.equals("length") || a.equals("len")){
229 synthReadlen=Integer.parseInt(b);
230 }else if(a.equals("kfilter")){
231 KFILTER=Integer.parseInt(b);
232 }else if(a.equals("renamebyinsert")){
233 RenameByInsert=Parse.parseBoolean(b);
234 }else if(a.equals("msa")){
235 MSA_TYPE=b;
236 }else if(a.equals("bandwidth") || a.equals("bw")){
237 int x=Tools.max(0, Integer.parseInt(b));
238 MSA.bandwidth=x;
239 }else if(a.equals("bandwidthratio") || a.equals("bwr")){
240 float x=Tools.max(0, Float.parseFloat(b));
241 MSA.bandwidthRatio=x;
242 assert(x>=0) : "Bandwidth ratio should be at least 0.";
243 }else if(a.equals("eono") || a.equals("erroronnooutput")){
244 ERROR_ON_NO_OUTPUT=Parse.parseBoolean(b);
245 }else if(a.equals("log")){
246 RefToIndex.LOG=Parse.parseBoolean(b);
247 }else if(a.equals("sitesonly") || a.equals("outputsitesonly")){
248 outputSitesOnly=Parse.parseBoolean(b);
249 outstream.println("Set outputSitesOnly to "+outputSitesOnly);
250 }else if(a.equals("discardambiguous") || a.equals("tossambiguous")){
251 REMOVE_DUPLICATE_BEST_ALIGNMENTS=Parse.parseBoolean(b);
252 outstream.println("Set REMOVE_DUPLICATE_BEST_ALIGNMENTS to "+REMOVE_DUPLICATE_BEST_ALIGNMENTS);
253 }else if(a.equals("ambiguous") || a.equals("ambig")){
254 if(b==null){
255 throw new RuntimeException(arg);
256 }else if(b.equalsIgnoreCase("keep") || b.equalsIgnoreCase("best") || b.equalsIgnoreCase("first")){
257 ambigMode=AMBIG_BEST;
258 }else if(b.equalsIgnoreCase("all")){
259 ambigMode=AMBIG_ALL;
260 }else if(b.equalsIgnoreCase("random")){
261 ambigMode=AMBIG_RANDOM;
262 }else if(b.equalsIgnoreCase("toss") || b.equalsIgnoreCase("discard") || b.equalsIgnoreCase("remove")){
263 ambigMode=AMBIG_TOSS;
264 }else{
265 throw new RuntimeException(arg);
266 }
267 // sysout.println("Set REMOVE_DUPLICATE_BEST_ALIGNMENTS to "+REMOVE_DUPLICATE_BEST_ALIGNMENTS);
268 }else if(a.equals("penalizeambiguous") || a.equals("penalizeambig") || a.equals("pambig")){
269 AbstractMapThread.PENALIZE_AMBIG=SamLine.PENALIZE_AMBIG=Parse.parseBoolean(b);
270 }else if(a.equals("maxsites")){
271 int x=Integer.parseInt(b);
272 assert(x>0) : "maxsites must be at least 1.";
273 MAX_SITESCORES_TO_PRINT=Tools.max(x, 1);
274 AbstractMapThread.MAX_TRIM_SITES_TO_RETAIN=Tools.max(MAX_SITESCORES_TO_PRINT*2, AbstractMapThread.MAX_TRIM_SITES_TO_RETAIN);
275 }else if(a.equals("maxsites2")){
276 int x=Integer.parseInt(b);
277 assert(x>1) : "maxsites2 must be at least 2.";
278 AbstractMapThread.MAX_TRIM_SITES_TO_RETAIN=Tools.max(x, 2);
279 }else if(a.equals("secondary")){
280 PRINT_SECONDARY_ALIGNMENTS=Parse.parseBoolean(b);
281 ReadStreamWriter.OUTPUT_SAM_SECONDARY_ALIGNMENTS=PRINT_SECONDARY_ALIGNMENTS;
282 }else if(a.equals("sssr") || a.equals("secondarysitescoreratio")){
283 AbstractMapThread.SECONDARY_SITE_SCORE_RATIO=Float.parseFloat(b);
284 }else if(a.equals("ssao") || a.equals("secondarysiteasambiguousonly")){
285 AbstractMapThread.PRINT_SECONDARY_ALIGNMENTS_ONLY_FOR_AMBIGUOUS_READS=Parse.parseBoolean(b);
286 }else if(a.equals("quickmatch")){
287 QUICK_MATCH_STRINGS=Parse.parseBoolean(b);
288 }else if(a.equals("ambiguous2") || a.equals("ambig2")){
289 if(b==null){
290 throw new RuntimeException(arg);
291 }else if(b.equalsIgnoreCase("split") || b.equalsIgnoreCase("stream")){
292 BBSplitter.AMBIGUOUS2_MODE=BBSplitter.AMBIGUOUS2_SPLIT;
293 }else if(b.equalsIgnoreCase("keep") || b.equalsIgnoreCase("best") || b.equalsIgnoreCase("first")){
294 BBSplitter.AMBIGUOUS2_MODE=BBSplitter.AMBIGUOUS2_FIRST;
295 }else if(b.equalsIgnoreCase("toss") || b.equalsIgnoreCase("discard") || b.equalsIgnoreCase("remove")){
296 BBSplitter.AMBIGUOUS2_MODE=BBSplitter.AMBIGUOUS2_TOSS;
297 }else if(b.equalsIgnoreCase("random")){
298 BBSplitter.AMBIGUOUS2_MODE=BBSplitter.AMBIGUOUS2_RANDOM;
299 }else if(b.equalsIgnoreCase("all")){
300 BBSplitter.AMBIGUOUS2_MODE=BBSplitter.AMBIGUOUS2_ALL;
301 }else{
302 throw new RuntimeException(arg);
303 }
304 }else if(a.equals("forbidselfmapping")){
305 FORBID_SELF_MAPPING=Parse.parseBoolean(b);
306 outstream.println("Set FORBID_SELF_MAPPING to "+FORBID_SELF_MAPPING);
307 }else if(a.equals("match") || a.equals("cigar")){
308 if(b!=null){b=b.toLowerCase();}else{b="true";}
309 if(b.equals("long") || b.equals("normal")){
310 MAKE_MATCH_STRING=true;
311 Read.COMPRESS_MATCH_BEFORE_WRITING=false;
312 // sysout.println("Writing long match strings.");
313 }else if(b.equals("short") || b.equals("compressed")){
314 MAKE_MATCH_STRING=true;
315 Read.COMPRESS_MATCH_BEFORE_WRITING=true;
316 // sysout.println("Writing short match strings.");
317 }else{
318 MAKE_MATCH_STRING=Parse.parseBoolean(b);
319 }
320
321 if(MAKE_MATCH_STRING){
322 outstream.println("Cigar strings enabled.");
323 }else{
324 outstream.println("Cigar strings disabled.");
325 }
326 }else if(a.equals("semiperfectmode")){
327 SEMIPERFECTMODE=Parse.parseBoolean(b);
328 if(ziplevel==-1){ziplevel=2;}
329 }else if(a.equals("perfectmode")){
330 PERFECTMODE=Parse.parseBoolean(b);
331 if(ziplevel==-1){ziplevel=2;}
332 }else if(a.equals("trimlist")){
333 TRIM_LIST=Parse.parseBoolean(b);
334 }else if(a.equals("pairedrandom")){
335 PAIRED_RANDOM_READS=Parse.parseBoolean(b);
336 }else if(a.equals("ordered") || a.equals("ord")){
337 ORDERED=Parse.parseBoolean(b);
338 outstream.println("Set OUTPUT_ORDERED_READS to "+ORDERED);
339 }else if(a.equals("outputunmapped")){
340 OUTPUT_MAPPED_ONLY=!Parse.parseBoolean(b);
341 outstream.println("Set OUTPUT_MAPPED_ONLY to "+OUTPUT_MAPPED_ONLY);
342 }else if(a.equals("mappedonly")){
343 OUTPUT_MAPPED_ONLY=Parse.parseBoolean(b);
344 outstream.println("Set OUTPUT_MAPPED_ONLY to "+OUTPUT_MAPPED_ONLY);
345 }else if(a.equals("outputblacklisted")){
346 DONT_OUTPUT_BLACKLISTED_READS=!Parse.parseBoolean(b);
347 outstream.println("Set DONT_OUTPUT_BLACKLISTED_READS to "+DONT_OUTPUT_BLACKLISTED_READS);
348 }else if(a.equals("indexloaded")){
349 INDEX_LOADED=Parse.parseBoolean(b);
350 }else if(a.equals("build") || a.equals("genome") || a.equals("index")){
351 build=Integer.parseInt(b);
352 }else if(a.equals("minchrom")){
353 minChrom=Integer.parseInt(b);
354 maxChrom=Tools.max(minChrom, maxChrom);
355 }else if(a.equals("maxchrom")){
356 maxChrom=Byte.parseByte(b);
357 minChrom=Tools.min(minChrom, maxChrom);
358 }else if(a.equals("expectedsites")){
359 expectedSites=Integer.parseInt(b);
360 }else if(a.equals("targetsize")){
361 targetGenomeSize=Parse.parseKMG(b);
362 }else if(a.equals("fgte")){
363 fractionGenomeToExclude=Float.parseFloat(b);
364 outstream.println("Set fractionGenomeToExclude to "+Tools.format("%.4f",fractionGenomeToExclude));
365 }else if(a.equals("minratio")){
366 MINIMUM_ALIGNMENT_SCORE_RATIO=Float.parseFloat(b);
367 outstream.println("Set MINIMUM_ALIGNMENT_SCORE_RATIO to "+Tools.format("%.3f",MINIMUM_ALIGNMENT_SCORE_RATIO));
368 minid=-1;
369 }else if(a.equals("minidentity") || a.equals("minid")){
370 assert(b!=null) : "Bad parameter: "+arg;
371 if(b.lastIndexOf('%')==b.length()-1){minid=Double.parseDouble(b.substring(b.length()-1))/100;}
372 else{minid=Double.parseDouble(b);}
373 assert(minid>=0 && minid<=100) : "min identity must be between 0 and 1. Values from 1 to 100 will be assumed percent and divided by 100.";
374 }else if(a.equals("rcompmate") || a.equals("reversecomplementmate")){
375 rcompMate=Parse.parseBoolean(b);
376 outstream.println("Set RCOMP_MATE to "+rcompMate);
377 }else if(a.equals("rcomp") || a.equals("reversecomplement")){
378 AbstractMapThread.RCOMP=Parse.parseBoolean(b);
379 outstream.println("Set RCOMP to "+rcompMate);
380 }else if(a.equals("verbose")){
381 verbose=Parse.parseBoolean(b);
382 Read.verbose=verbose;
383 SiteScore.verbose=verbose;
384 TranslateColorspaceRead.verbose=verbose;
385 AbstractIndex.verbose2=verbose;
386 }else if(a.equals("verbosestats")){
387 if(b!=null && Tools.isDigit(b.charAt(0))){
388 verbose_stats=Integer.parseInt(b);
389 }else{
390 verbose_stats=Parse.parseBoolean(b) ? 9 : 0;
391 }
392 }else if(a.equals("maxdellen")){
393 maxDelLen=Integer.parseInt(b);
394 }else if(a.equals("maxinslen")){
395 maxInsLen=Integer.parseInt(b);
396 }else if(a.equals("maxsublen")){
397 maxSubLen=Integer.parseInt(b);
398 }else if(a.equals("minqual")){
399 minQuality=Byte.parseByte(b);
400 midQuality=Tools.max(minQuality, midQuality);
401 maxQuality=Tools.max(midQuality, maxQuality);
402 }else if(a.equals("midqual")){
403 midQuality=Byte.parseByte(b);
404 maxQuality=Tools.max(midQuality, maxQuality);
405 minQuality=Tools.min(minQuality, midQuality);
406 }else if(a.equals("maxqual")){
407 maxQuality=Byte.parseByte(b);
408 midQuality=Tools.min(maxQuality, midQuality);
409 minQuality=Tools.min(minQuality, midQuality);
410 }else if(a.equals("matelen") || a.equals("pairlen")){
411 int x=Integer.parseInt(b);
412 AbstractMapThread.MAX_PAIR_DIST=x;
413 }else if(a.equals("s") || a.equals("snps")){
414 maxSnps=Integer.parseInt(b);
415 baseSnpRate=1;
416 }else if(a.equals("u") || a.equals("subs")){
417 maxInss=Integer.parseInt(b);
418 baseInsRate=1;
419 }else if(a.equals("d") || a.equals("dels")){
420 maxDels=Integer.parseInt(b);
421 baseDelRate=1;
422 }else if(a.equals("i") || a.equals("inss")){
423 maxSubs=Integer.parseInt(b);
424 baseSubRate=1;
425 }else if(a.equals("sequentialoverlap")){
426 sequentialOverlap=Integer.parseInt(b);
427 }else if(a.equals("sequentialstrandalt")){
428 sequentialStrandAlt=Parse.parseBoolean(b);
429 }else if(a.equals("k") || a.equals("keylen")){
430 keylen=Integer.parseInt(b);
431 assert(keylen>0 && keylen<16) : "k must lie between 1 and 15, inclusive.";
432 }else if(a.equals("genscaffoldinfo")){
433 RefToIndex.genScaffoldInfo=Parse.parseBoolean(b);
434 }else if(a.equals("loadscaffolds")){
435 Data.LOAD_SCAFFOLDS=Parse.parseBoolean(b);
436 }else if(a.equals("autoRefToIndex.chrombits")){
437 if("auto".equalsIgnoreCase(b)){RefToIndex.AUTO_CHROMBITS=true;}
438 else{RefToIndex.AUTO_CHROMBITS=Parse.parseBoolean(b);}
439 }else if(a.equals("RefToIndex.chrombits") || a.equals("cbits")){
440 if("auto".equalsIgnoreCase(b)){RefToIndex.AUTO_CHROMBITS=true;}
441 else{
442 RefToIndex.AUTO_CHROMBITS=false;
443 RefToIndex.chrombits=Integer.parseInt(b);
444 }
445 }else if(a.equals("requirecorrectstrand") || a.equals("rcs")){
446 REQUIRE_CORRECT_STRANDS_PAIRS=Parse.parseBoolean(b);
447 }else if(a.equals("samestrandpairs") || a.equals("ssp")){
448 SAME_STRAND_PAIRS=Parse.parseBoolean(b);
449 if(SAME_STRAND_PAIRS){outstream.println("Warning! SAME_STRAND_PAIRS=true mode is not fully tested.");}
450 }else if(a.equals("killbadpairs") || a.equals("kbp")){
451 KILL_BAD_PAIRS=Parse.parseBoolean(b);
452 }else if(a.equals("pairedonly") || a.equals("po")){
453 AbstractMapThread.OUTPUT_PAIRED_ONLY=Parse.parseBoolean(b);
454 }else if(a.equals("idmodulo") || a.equals("idmod")){
455 idmodulo=Integer.parseInt(b);
456 }else if(a.equals("minhits") || a.equals("minapproxhits")){
457 minApproxHits=Integer.parseInt(b);
458 }else if(a.equals("maxindel")){
459 maxIndel1=(int)Tools.max(0, Parse.parseKMG(b));
460 if(!setMaxIndel2){maxIndel2=2*maxIndel1;}
461 }else if(a.equals("maxindel1") || a.equals("maxindelsingle")){
462 maxIndel1=(int)Tools.max(0, Parse.parseKMG(b));
463 maxIndel2=Tools.max(maxIndel1, maxIndel2);
464 setMaxIndel1=true;
465 }else if(a.equals("maxindel2") || a.equals("maxindelsum")){
466 maxIndel2=(int)Tools.max(0, Parse.parseKMG(b));
467 maxIndel1=Tools.min(maxIndel1, maxIndel2);
468 setMaxIndel2=true;
469 }else if(a.equals("strictmaxindel")){
470 if(b!=null && Tools.isDigit(b.charAt(0))){
471 maxIndel1=(int)Tools.max(0, Parse.parseKMG(b));
472 if(!setMaxIndel2){maxIndel2=2*maxIndel1;}
473 STRICT_MAX_INDEL=true;
474 }else{
475 STRICT_MAX_INDEL=Parse.parseBoolean(b);
476 }
477 }else if(a.equals("padding")){
478 SLOW_ALIGN_PADDING=Integer.parseInt(b);
479 SLOW_RESCUE_PADDING=SLOW_ALIGN_PADDING;
480 }else if(a.equals("rescue")){
481 RESCUE=Parse.parseBoolean(b);
482 }else if(a.equals("rescuemismatches")){
483 AbstractMapThread.MAX_RESCUE_MISMATCHES=Integer.parseInt(b);
484 }else if(a.equals("rescuedist")){
485 AbstractMapThread.MAX_RESCUE_DIST=Parse.parseIntKMG(b);
486 }else if(a.equals("tipsearch")){
487 if(b!=null && ("f".equalsIgnoreCase(b) || "false".equalsIgnoreCase(b))){TIP_SEARCH_DIST=0;}
488 else{TIP_SEARCH_DIST=Tools.max(0, Integer.parseInt(b));}
489 }else if(a.equals("dper") || a.equals("dprr")){
490 DOUBLE_PRINT_ERROR_RATE=Parse.parseBoolean(b);
491 }else if(a.equals("chromgz")){
492 Data.CHROMGZ=Parse.parseBoolean(b);
493 }else if(a.equals("nodisk")){
494 RefToIndex.NODISK=Parse.parseBoolean(b);
495 }else if(a.equals("maxchromlen")){
496 RefToIndex.maxChromLen=Parse.parseKMG(b);
497 }else if(a.equals("minscaf") || a.equals("mincontig")){
498 RefToIndex.minScaf=Integer.parseInt(b);
499 }else if(a.equals("midpad") || a.equals("interpad")){
500 RefToIndex.midPad=Integer.parseInt(b);
501 }else if(a.equals("startpad")){
502 RefToIndex.startPad=Integer.parseInt(b);
503 }else if(a.equals("stoppad")){
504 RefToIndex.stopPad=Integer.parseInt(b);
505 }else if(a.equals("forceanalyze")){
506 forceanalyze=Parse.parseBoolean(b);
507 }else if(a.equals("machineoutput") || a.equals("machineout")){
508 MACHINE_OUTPUT=Parse.parseBoolean(b);
509 }else if(a.equals("showprogress") || a.equals("showprogress2")){
510 if(b!=null && Tools.isDigit(b.charAt(0))){
511 long x=Parse.parseKMG(b);
512 ConcurrentReadInputStream.PROGRESS_INCR=x;
513 ConcurrentReadInputStream.SHOW_PROGRESS=(x>0);
514 }else{
515 ConcurrentReadInputStream.PROGRESS_INCR=ConcurrentReadInputStream.PROGRESS_INCR<1 ? 1000000 : ConcurrentReadInputStream.PROGRESS_INCR;
516 ConcurrentReadInputStream.SHOW_PROGRESS=Parse.parseBoolean(b);
517 }
518 if(a.equals("showprogress2")){ConcurrentReadInputStream.SHOW_PROGRESS2=ConcurrentReadInputStream.SHOW_PROGRESS;}
519 }else if(a.equals("scafstats") || a.equals("scaffoldstats")){
520 if(b==null && arg.indexOf('=')<0){b="stdout";}
521 if(b==null || b.equalsIgnoreCase("false") || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("none") || b.equalsIgnoreCase("null")){
522 BBSplitter.TRACK_SCAF_STATS=false;
523 BBSplitter.SCAF_STATS_FILE=null;
524 outstream.println("No file specified; not tracking scaffold statistics.");
525 }else{
526 BBSplitter.TRACK_SCAF_STATS=true;
527 BBSplitter.SCAF_STATS_FILE=b;
528 outstream.println("Scaffold statistics will be written to "+b);
529 }
530 }else if(a.equals("setstats") || a.equals("refstats")){
531 if(b==null && arg.indexOf('=')<0){b="stdout";}
532 if(b==null || b.equalsIgnoreCase("false") || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("none") || b.equalsIgnoreCase("null")){
533 BBSplitter.TRACK_SET_STATS=false;
534 BBSplitter.SET_STATS_FILE=null;
535 outstream.println("No file specified; not tracking reference set statistics.");
536 }else{
537 BBSplitter.TRACK_SET_STATS=true;
538 BBSplitter.SET_STATS_FILE=b;
539 outstream.println("Reference set statistics will be written to "+b);
540 }
541 }else if(a.equals("camelwalk")){
542 AbstractIndex.USE_CAMELWALK=Parse.parseBoolean(b);
543 }else if(a.equals("usequality") || a.equals("uq")){
544 AbstractIndex.GENERATE_KEY_SCORES_FROM_QUALITY=AbstractIndex.GENERATE_BASE_SCORES_FROM_QUALITY=Parse.parseBoolean(b);
545 }else if(a.equals("ignorequality")){
546 AbstractIndex.GENERATE_KEY_SCORES_FROM_QUALITY=AbstractIndex.GENERATE_BASE_SCORES_FROM_QUALITY=!Parse.parseBoolean(b);
547 }else if(a.equals("keepbadkeys") || a.equals("kbk")){
548 KeyRing.KEEP_BAD_KEYS=Parse.parseBoolean(b);
549 }else if(a.equals("usemodulo") || a.equals("um")){
550 USE_MODULO=AbstractMapThread.USE_MODULO=IndexMaker4.USE_MODULO=IndexMaker5.USE_MODULO=Parse.parseBoolean(b);
551 }else if(a.equals("lowmem") || a.equals("lowram") || a.equals("lowmemory")){
552 boolean x=Parse.parseBoolean(b);
553 if(x){
554 Shared.LOW_MEMORY=true;
555 USE_MODULO=AbstractMapThread.USE_MODULO=IndexMaker4.USE_MODULO=IndexMaker5.USE_MODULO=Parse.parseBoolean(b);
556 }else{
557 Shared.LOW_MEMORY=false;
558 }
559 }else if(a.equals("coverage") || a.equals("cov") || a.equals("calccov") || a.equals("calccoverage")){
560 calcCov=Parse.parseBoolean(b);
561 }else if(a.equals("coveragestats") || a.equals("covstats")){
562 coverageStats=b;
563 }else if(a.equals("coverageminscaf") || a.equals("covminscaf")){
564 coverageMinScaf=Integer.parseInt(b);
565 }else if(a.equals("binnedcoverage") || a.equals("bincov")){
566 coverageBinned=b;
567 }else if(a.equals("coverage") || a.equals("basecov")){
568 coverageBase=b;
569 }else if(a.equals("rangecov")){
570 rangeCov=b;
571 }else if(a.equals("secondarycoverage") || a.equals("secondarycov")){
572 CoveragePileup.USE_SECONDARY=Parse.parseBoolean(b);
573 }else if(a.equals("coveragehistogram") || a.equals("covhist")){
574 coverageHist=b;
575 }else if(a.equals("normcov")){
576 normcov=b;
577 }else if(a.equals("normcovo")){
578 normcovOverall=b;
579 }else if(a.equals("normb") || a.equals("normbins")){
580 CoveragePileup.NORMALIZE_LENGTH_BINS=Integer.parseInt(b);
581 }else if(a.equals("rpkm") || a.equals("fpkm")){
582 coverageRPKM=b;
583 }else if(a.equals("physicalcoverage") || a.equals("physcov")){
584 coveragePhysical=Parse.parseBoolean(b);
585 }else if(a.equals("32bit") || a.equals("32bits") || a.equals("bits32")){
586 cov32bit=Parse.parseBoolean(b);
587 }else if(a.equals("bitset")){
588 covBitset=Parse.parseBoolean(b);
589 covSetbs=true;
590 }else if(a.equals("arrays")){
591 covArrays=Parse.parseBoolean(b);
592 covSetbs=true;
593 }else if(a.equals("nzo") || a.equals("nonzeroonly")){
594 covNzo=scafNzo=Parse.parseBoolean(b);
595 }else if(a.equals("sortstats") || a.equals("sortscafs")){
596 sortStats=Parse.parseBoolean(b);
597 }else if(a.equals("twocolumn")){
598 covTwocolumn=Parse.parseBoolean(b);
599 }else if(a.equals("ksb") || a.equals("keepshortbins")){
600 covKsb=Parse.parseBoolean(b);
601 }else if(a.equals("covbinsize")){
602 covBinSize=Integer.parseInt(b);
603 }else if(a.equals("covk") || a.equals("kcov")){
604 covK=Integer.parseInt(b);
605 }else if(a.equals("strandedcoverage") || a.equals("strandedcov") || a.equals("covstranded")){
606 covStranded=Parse.parseBoolean(b);
607 }else if(a.equals("startcov") || a.equals("covstart")){
608 covStartOnly=Parse.parseBoolean(b);
609 }else if(a.equals("stopcov") || a.equals("covstop")){
610 covStartOnly=Parse.parseBoolean(b);
611 }else if(a.equals("concisecov")){
612 CoveragePileup.CONCISE=Parse.parseBoolean(b);
613 }else if(a.equals("covwindow")){
614 if(b==null || b.length()<1 || Character.isLetter(b.charAt(0))){
615 CoveragePileup.USE_WINDOW=Parse.parseBoolean(b);
616 }else{
617 CoveragePileup.LOW_COV_WINDOW=Integer.parseInt(b);
618 CoveragePileup.USE_WINDOW=(CoveragePileup.LOW_COV_WINDOW>0);
619 }
620 }else if(a.equals("covwindowavg")){
621 CoveragePileup.LOW_COV_DEPTH=Double.parseDouble(b);
622 }else if(a.equals("delcov") || a.equals("includedels") || a.equals("includedeletions") || a.equals("delcoverage")){
623 CoveragePileup.INCLUDE_DELETIONS=Parse.parseBoolean(b);
624 }else if(a.equals("rebuild")){
625 forceRebuild=Parse.parseBoolean(b);
626 }else if(a.equals("printunmappedcount")){
627 PRINT_UNMAPPED_COUNT=Parse.parseBoolean(b);
628 }else if(a.equals("timetag")){
629 boolean x=Parse.parseBoolean(b);
630 AbstractMapThread.TIME_TAG=x;
631 SamLine.MAKE_TIME_TAG=x;
632 if(x){AbstractMapThread.CLEAR_ATTACHMENT=false;}
633 }else if(a.equals("correctthresh")){
634 CORRECT_THRESH=Integer.parseInt(b);
635 }else if(a.equals("statsfile")){
636 statsOutputFile=b;
637 }else if(a.equals("ignorefrequentkmers") || a.equals("ifk")){
638 AbstractIndex.REMOVE_FREQUENT_GENOME_FRACTION=Parse.parseBoolean(b);
639 }else if(a.equals("trimbygreedy") || a.equals("tbg") || a.equals("greedy")){
640 AbstractIndex.TRIM_BY_GREEDY=Parse.parseBoolean(b);
641 }else if(a.equals("printsettings")){
642 printSettings=Parse.parseBoolean(b);
643 }else if(a.equals("printstats")){
644 printStats=Parse.parseBoolean(b);
645 }
646
647 else if(a.equals("minmapq")){
648 MIN_MAPQ=Integer.parseInt(b);
649 }else if(a.equals("minmateq")){
650 MIN_MAPQ_UNPAIRED=Integer.parseInt(b);
651 }
652
653 else if(a.equalsIgnoreCase("bloom") || a.equalsIgnoreCase("bloomfilter")){
654 makeBloomFilter=Parse.parseBoolean(b);
655 }else if(a.equalsIgnoreCase("bloomHashes") || a.equalsIgnoreCase("bloomFilterHashes")){
656 bloomFilterHashes=Integer.parseInt(b);
657 }else if(a.equalsIgnoreCase("bloomMinHits") || a.equalsIgnoreCase("bloomFilterMinHits")){
658 bloomFilterMinHits=Integer.parseInt(b);
659 }else if(a.equalsIgnoreCase("bloomK") || a.equalsIgnoreCase("bloomFilterK")){
660 bloomFilterK=Integer.parseInt(b);
661 }else if(a.equalsIgnoreCase("bloomserial") || a.equalsIgnoreCase("serialbloom")){
662 bloomSerial=Parse.parseBoolean(b);
663 }else if(a.equalsIgnoreCase("forcereadonly")){
664 RefToIndex.FORCE_READ_ONLY=Parse.parseBoolean(b);
665 }
666
667 else{
668 throw new RuntimeException("Unknown parameter: "+arg);
669 }
670 }
671 Parser.postparseReadgroup(in1);
672
673 {//Process parser fields
674 Parser.processQuality();
675
676 qtrimLeft=parser.qtrimLeft;
677 qtrimRight=parser.qtrimRight;
678 TRIM_QUALITY=parser.trimq;
679 AbstractMapThread.MIN_AVERAGE_QUALITY=parser.minAvgQuality;
680 AbstractMapThread.MIN_AVERAGE_QUALITY_BASES=parser.minAvgQualityBases;
681 AbstractMapThread.MIN_READ_LENGTH=parser.minReadLength;
682 AbstractMapThread.MAX_READ_LENGTH=parser.maxReadLength;
683 minTrimLength=parser.minTrimLength;
684 untrim=parser.untrim;
685
686 maxReads=parser.maxReads;
687 overwrite=ReadStats.overwrite=CoveragePileup.overwrite=parser.overwrite;
688 append=ReadStats.append=parser.append;
689 setintron=SamLine.setintron;
690
691 samplerate=parser.samplerate;
692 sampleseed=parser.sampleseed;
693 MIN_IDFILTER=parser.minIdFilter;
694 build=parser.build;
695 if(MIN_IDFILTER>0){
696 if(MIN_IDFILTER==1f){PERFECTMODE=true;}
697 MAKE_MATCH_STRING=true;
698 }
699
700 if(parser.nfilter>-1){AbstractMapThread.NFILTER=parser.nfilter;}
701 if(parser.subfilter>-1){AbstractMapThread.SUBFILTER=parser.subfilter;}
702 if(parser.delfilter>-1){AbstractMapThread.DELFILTER=parser.delfilter;}
703 if(parser.insfilter>-1){AbstractMapThread.INSFILTER=parser.insfilter;}
704 if(parser.indelfilter>-1){AbstractMapThread.INDELFILTER=parser.indelfilter;}
705 if(parser.dellenfilter>-1){AbstractMapThread.DELLENFILTER=parser.dellenfilter;}
706 if(parser.inslenfilter>-1){AbstractMapThread.INSLENFILTER=parser.inslenfilter;}
707 if(parser.editfilter>-1){AbstractMapThread.EDITFILTER=parser.editfilter;}
708
709 if(ReadStats.COLLECT_TIME_STATS){AbstractMapThread.TIME_TAG=true;}
710 }
711
712 {
713 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, 0, 0, false, false, false);
714 parser.validateStdio(ff1);
715 }
716
717 if(forceRebuild){
718 String sf=RefToIndex.summaryLoc(build);
719 if(sf!=null){
720 File f=new File(sf);
721 if(f.exists() && f.isFile()){f.delete();}
722 }
723 }
724
725 ChromosomeArray.CHANGE_UNDEFINED_TO_N_ON_READ=(!INDEX_LOADED);
726
727 if(BBSplitter.AMBIGUOUS2_MODE==BBSplitter.AMBIGUOUS2_SPLIT && splitterOutputs!=null){
728 ArrayList<String> clone=(ArrayList<String>) splitterOutputs.clone();
729 for(String s : clone){
730 splitterOutputs.add("AMBIGUOUS_"+s);
731 }
732 }
733 }
734
735 private final void checkFiles(){
736 if(in1!=null && in1.contains("#") && !new File(in1).exists()){
737 int pound=in1.lastIndexOf('#');
738 String a=in1.substring(0, pound);
739 String b=in1.substring(pound+1);
740 in1=a+1+b;
741 in2=a+2+b;
742 }
743
744 if(in2!=null && (in2.contains("=") || in2.equalsIgnoreCase("null"))){in2=null;}
745 if(in2!=null){
746 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
747 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
748 }
749 in1=Tools.fixExtension(in1);
750 in2=Tools.fixExtension(in2);
751 qfin1=Tools.fixExtension(qfin1);
752 qfin2=Tools.fixExtension(qfin2);
753
754 if(outFile!=null && outFile2==null && outFile.contains("#") && !outFile.contains(".sam") && !outFile.contains(".bam") && outFile.contains(".")){
755 int pound=outFile.lastIndexOf('#');
756 String a=outFile.substring(0, pound);
757 String b=outFile.substring(pound+1);
758 outFile=a+1+b;
759 outFile2=a+2+b;
760 }
761
762 if(outFileM!=null && outFileM2==null && outFileM.contains("#") && !outFileM.contains(".sam") && !outFileM.contains(".bam") && outFileM.contains(".")){
763 int pound=outFileM.lastIndexOf('#');
764 String a=outFileM.substring(0, pound);
765 String b=outFileM.substring(pound+1);
766 outFileM=a+1+b;
767 outFileM2=a+2+b;
768 }
769
770 if(outFileU!=null && outFileU2==null && outFileU.contains("#") && !outFileU.contains(".sam") && !outFileU.contains(".bam") && outFileU.contains(".")){
771 int pound=outFileU.lastIndexOf('#');
772 String a=outFileU.substring(0, pound);
773 String b=outFileU.substring(pound+1);
774 outFileU=a+1+b;
775 outFileU2=a+2+b;
776 }
777
778 if(OUTPUT_READS && !Tools.testOutputFiles(overwrite, append, false, outFile, outFile2)){
779 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+outFile+", "+outFile2+"\n");
780 }
781
782 if(maxReads>0 && maxReads<Long.MAX_VALUE){outstream.println("Max reads: "+maxReads);}
783
784 ReadStats.testFiles(false);
785
786 assert(synthReadlen<0 || synthReadlen>=keylen);
787 }
788
789 private final String[] preparse0(String[] args){
790 int nulls=0;
791 boolean foundInput=false;
792 for(int i=0; i<args.length; i++){
793 if(args[i]==null){nulls++;}
794 else{
795 final String arg=args[i];
796 final String[] split=arg.split("=");
797 assert(split.length>0) : "\n= symbol must be adjacent to 2 terms, with no spaces. E.g. 'out=mapped.sam'";
798 String a=split[0].toLowerCase();
799 String b=split.length>1 ? split[1] : null;
800 String blc=(b==null ? null : b.toLowerCase());
801 if("null".equalsIgnoreCase(blc)){blc=null;}
802 if(blc!=null && (blc.equals("stdout") || blc.startsWith("stdout."))){
803 outstream=System.err;
804 outstream=System.err;
805 }else if(a.equals("printtoerr")){
806 if(Parse.parseBoolean(blc)){outstream=System.err; outstream=System.err;}
807 }else if(blc!=null && (blc.equals("stdin") || blc.startsWith("stdin."))){
808 SYSIN=true;
809 }else if(a.equals("fast")){
810 fast=Parse.parseBoolean(blc);
811 if(fast){slow=false;}
812 args[i]=null;
813 nulls++;
814 }else if(a.equals("slow")){
815 slow=Parse.parseBoolean(blc);
816 if(slow){fast=false;}
817 args[i]=null;
818 nulls++;
819 }else if(a.equals("vslow")){
820 vslow=Parse.parseBoolean(blc);
821 if(vslow){fast=false;slow=true;}
822 args[i]=null;
823 nulls++;
824 }else if(a.equals("excludefraction") || a.equals("ef")){
825 excludeFraction=Float.parseFloat(blc);
826 args[i]=null;
827 nulls++;
828 }else if(a.equals("in")){
829 // assert(b!=null) : "Null input file.";
830 if(b!=null){
831 assert(b.equals("stdin") || b.startsWith("stdin.") || new File(b).exists() || new File(b.replace('#', '1')).exists()) : "Invalid input file: '"+b+"'";
832 foundInput=true;
833 // FileFormat ff=FileFormat.testInput(b, FileFormat.FASTQ, null, false, false);
834 }
835 }else if(a.equals("ref")){
836 assert(b!=null) : "Null reference file.";
837 if(b.indexOf(',')<0 && !"phix".equalsIgnoreCase(b)){
838 assert(b.equals("stdin") || b.startsWith("stdin.") || new File(b).exists()) : "Invalid input file: '"+b+"'";
839 FileFormat ff=FileFormat.testInput(b, FileFormat.FASTA, null, true, true);
840 assert(ff.stdin() || ff.fasta()) : "References must be in fasta format.";
841 }
842 }
843 }
844 }
845 // assert(foundInput) : "No input file specified.";
846 if(nulls>0){args=Tools.condenseStrict(args);}
847 return args;
848 }
849
850 static final String padPercent(double value, int places){
851 String x=Tools.format("%."+places+"f", value);
852 int desired=3+(places<1 ? 0 : 1+places);
853 while(x.length()<desired){x=" "+x;}
854 return x;
855 }
856
857 static final String pad(long value, int places){
858 String x=""+value;
859 while(x.length()<places){x=" "+x;}
860 return x;
861 }
862
863 static final String padPercentMachine(double value, int places){
864 String x=Tools.format("%."+places+"f", value);
865 return x;
866 }
867
868
869 boolean openStreams(Timer t, String[] args){
870
871 cris=getReadInputStream(in1, in2, qfin1, qfin2);
872 final boolean paired=cris.paired();
873 cris.setSampleRate(samplerate, sampleseed);
874
875 final int buff=(!ORDERED ? 12 : Tools.max(32, 2*Shared.threads()));
876 if(OUTPUT_READS){
877 ReadStreamWriter.MINCHROM=minChrom;
878 ReadStreamWriter.MAXCHROM=maxChrom;
879
880 AbstractMapThread.OUTPUT_SAM=false;
881 if(outFile!=null){
882 FileFormat ff1=FileFormat.testOutput(outFile, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
883 FileFormat ff2=outFile2==null ? null : FileFormat.testOutput(outFile2, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
884 rosA=ConcurrentReadOutputStream.getStream(ff1, ff2, qfout, qfout2, buff, null, false);
885 rosA.start();
886 t.stop();
887 outstream.println("Started output stream:\t"+t);
888 t.start();
889 AbstractMapThread.OUTPUT_SAM|=ff1.samOrBam();
890 }
891 if(outFileM!=null){
892 FileFormat ff1=FileFormat.testOutput(outFileM, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
893 FileFormat ff2=outFileM2==null ? null : FileFormat.testOutput(outFileM2, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
894 rosM=ConcurrentReadOutputStream.getStream(ff1, ff2, qfoutM, qfoutM2, buff, null, false);
895 rosM.start();
896 t.stop();
897 outstream.println("Started output stream:\t"+t);
898 t.start();
899 AbstractMapThread.OUTPUT_SAM|=ff1.samOrBam();
900 }
901 if(outFileU!=null){
902 FileFormat ff1=FileFormat.testOutput(outFileU, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
903 FileFormat ff2=outFileU2==null ? null : FileFormat.testOutput(outFileU2, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
904 rosU=ConcurrentReadOutputStream.getStream(ff1, ff2, qfoutU, qfoutU2, buff, null, false);
905 rosU.start();
906 t.stop();
907 outstream.println("Started output stream:\t"+t);
908 t.start();
909 AbstractMapThread.OUTPUT_SAM|=ff1.samOrBam();
910 }
911 if(outFileB!=null && !Data.scaffoldPrefixes){
912 FileFormat ff1=FileFormat.testOutput(outFileB, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
913 FileFormat ff2=outFileB2==null ? null : FileFormat.testOutput(outFileB2, DEFAULT_OUTPUT_FORMAT, 0, 0, true, overwrite, append, ORDERED);
914 rosB=ConcurrentReadOutputStream.getStream(ff1, ff2, qfoutB, qfoutB2, buff, null, false);
915 rosB.start();
916 t.stop();
917 outstream.println("Started output stream:\t"+t);
918 t.start();
919 AbstractMapThread.OUTPUT_SAM|=ff1.samOrBam();
920 }
921 }
922
923 if(Data.scaffoldPrefixes){
924 BBSplitter.streamTable=BBSplitter.makeOutputStreams(args, OUTPUT_READS, ORDERED, buff, paired, overwrite, append, false);
925 if(BBSplitter.AMBIGUOUS2_MODE==BBSplitter.AMBIGUOUS2_SPLIT){
926 BBSplitter.streamTableAmbiguous=BBSplitter.makeOutputStreams(args, OUTPUT_READS, ORDERED, buff, paired, overwrite, append, true);
927 }
928 }else{
929 BBSplitter.TRACK_SET_STATS=false;
930 }
931
932 if(BBSplitter.TRACK_SET_STATS){
933 outstream.print("Creating ref-set statistics table: ");
934 BBSplitter.makeSetCountTable();
935 t.stop();
936 outstream.println(" \t"+t);
937 t.start();
938 }
939 if(BBSplitter.TRACK_SCAF_STATS){
940 outstream.print("Creating scaffold statistics table:");
941 BBSplitter.makeScafCountTable();
942 t.stop();
943 outstream.println(" \t"+t);
944 t.start();
945 }
946
947 {
948 String syncObj=new String("syncObj");
949 synchronized(syncObj){
950 System.gc();
951 Thread.yield();
952 // if(waitForMemoryClear){
953 try {syncObj.wait(waitForMemoryClear ? 1000 : 100);}
954 catch (InterruptedException e) {e.printStackTrace();}
955 // }
956 }
957
958 t.stop();
959 outstream.println("Cleared Memory: \t"+t);
960 }
961
962 return paired;
963 }
964
965 static final int shutDownThreads(AbstractMapThread[] mtts, boolean force){
966 int broken=0;
967 long millis=force ? 500 : 8000;
968 for(int i=0; i<mtts.length; i++){
969 AbstractMapThread mtt=mtts[i];
970 if(mtt==null){broken++;}
971 else{
972 synchronized(mtt){
973 while(mtt.working()){
974 State st=mtt.getState();
975 if(st==State.TERMINATED){
976 if(mtt.working()){
977 broken++;
978 break;
979 }
980 }
981 try {
982 mtt.wait(millis);
983 } catch (InterruptedException e) {
984 // TODO Auto-generated catch block
985 e.printStackTrace();
986 }
987 if(force && mtt.working()){
988 mtt.interrupt();
989 broken++;
990 break;
991 }
992 }
993 }
994 if(i==0){
995 outstream.print("Detecting finished threads: 0");
996 }else{
997 outstream.print(", "+i);
998 }
999 }
1000 }
1001
1002 if(broken>0){
1003 System.err.println("\n\n**************************************************************************\n" +
1004 "Warning! "+broken+" mapping thread"+(broken==1 ? "" : "s")+" did not terminate normally.\n" +
1005 "Check the error log; the output may be corrupt or incomplete.\n" +
1006 "Please submit the full stderr output as a bug report, not just this message.\n" +
1007 "**************************************************************************\n\n");
1008 }
1009 return broken;
1010 }
1011
1012 static final boolean closeStreams(ConcurrentReadInputStream cris, ConcurrentReadOutputStream rosA, ConcurrentReadOutputStream rosM, ConcurrentReadOutputStream rosU, ConcurrentReadOutputStream rosB){
1013 errorState|=ReadWrite.closeStreams(cris, rosA, rosM, rosU, rosB);
1014 if(BBSplitter.streamTable!=null){
1015 for(ConcurrentReadOutputStream tros : BBSplitter.streamTable.values()){
1016 errorState|=ReadWrite.closeStream(tros);
1017 }
1018 }
1019 if(BBSplitter.streamTableAmbiguous!=null){
1020 for(ConcurrentReadOutputStream tros : BBSplitter.streamTableAmbiguous.values()){
1021 errorState|=ReadWrite.closeStream(tros);
1022 }
1023 }
1024 return errorState;
1025 }
1026
1027 static final ConcurrentReadInputStream getReadInputStream(String in1, String in2, String qf1, String qf2){
1028
1029 assert(in1!=null);
1030 assert(!in1.equalsIgnoreCase(in2)) : in1+", "+in2;
1031
1032 final ConcurrentReadInputStream cris;
1033
1034 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, 0, 0, true, true, false);
1035 FileFormat ff2=FileFormat.testInput(in2, FileFormat.FASTQ, 0, 0, true, true, false);
1036
1037 if(ff1.fastq() || ff1.fasta() || ff1.samOrBam() || ff1.scarf() || ff1.bread()){
1038 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, ff1.samOrBam(), ff1, ff2, qf1, qf2);
1039 }else if(ff1.sequential()){
1040 if(maxReads<0){maxReads=Long.MAX_VALUE;}
1041 // assert(false) : trials;
1042 SequentialReadInputStream ris=new SequentialReadInputStream(maxReads, synthReadlen, Tools.max(50, synthReadlen/2), sequentialOverlap, sequentialStrandAlt);
1043 cris=new ConcurrentLegacyReadInputStream(ris, maxReads);
1044
1045 }else if(ff1.random()){
1046
1047 useRandomReads=true;
1048 assert(synthReadlen>0);
1049
1050 RandomReads3.PERFECT_READ_RATIO=PERFECT_READ_RATIO;
1051
1052 RandomReadInputStream3 ris=new RandomReadInputStream3(maxReads, synthReadlen, synthReadlen,
1053 maxSnps, maxInss, maxDels, maxSubs,
1054 baseSnpRate, baseInsRate, baseDelRate, baseSubRate,
1055 maxInsLen, maxDelLen, maxSubLen,
1056 minChrom, maxChrom, PAIRED_RANDOM_READS,
1057 minQuality, midQuality, maxQuality);
1058 cris=new ConcurrentLegacyReadInputStream(ris, maxReads);
1059 }else{
1060 throw new RuntimeException("Can't determine read input source: ff1="+ff1+", ff2="+ff2);
1061 }
1062 return cris;
1063 }
1064
1065 void printOutput(final AbstractMapThread[] mtts, final Timer t, final int keylen, final boolean paired, final boolean SKIMMER, final CoveragePileup pile,
1066 boolean nzoStats, boolean sortStats, String dest){
1067
1068 if(printStats){
1069 printOutputStats(mtts, t, keylen, paired, SKIMMER, nzoStats, sortStats, dest);
1070 }
1071
1072 errorState|=ReadStats.writeAll();
1073
1074 if(pile!=null){
1075 CoveragePileup.overwrite=overwrite;
1076 CoveragePileup.append=append;
1077 outstream.println();
1078 pile.printOutput();
1079 }
1080
1081 }
1082
1083 static void printOutputStats(final AbstractMapThread[] mtts, final Timer t, final int keylen, final boolean paired, final boolean SKIMMER,
1084 boolean nzoStats, boolean sortStats, String dest){
1085 if(MACHINE_OUTPUT){
1086 printOutput_Machine(mtts, t, keylen, paired, SKIMMER, nzoStats, sortStats, dest);
1087 return;
1088 }
1089 if(dest==null){dest="stderr.txt";}
1090 TextStreamWriter tswStats=new TextStreamWriter(dest, overwrite, append, false);
1091 tswStats.start();
1092
1093 long readsUsed1=0;
1094 long readsUsed2=0;
1095 long readsIn1=0;
1096 long readsIn2=0;
1097
1098 long lowQualityReadsDiscarded1=0;
1099 long lowQualityReadsDiscarded2=0;
1100 long lowQualityBasesDiscarded1=0;
1101 long lowQualityBasesDiscarded2=0;
1102
1103 long msaIterationsLimited=0;
1104 long msaIterationsUnlimited=0;
1105
1106 long basesUsed1=0;
1107 long basesUsed2=0;
1108 long basesIn1=0;
1109 long basesIn2=0;
1110 long readsPassedBloomFilter=0;
1111 long basesPassedBloomFilter=0;
1112 long keysUsed=0;
1113 long bothUnmapped=0;
1114 long bothUnmappedBases=0;
1115 long eitherMapped=0;
1116 long eitherMappedBases=0;
1117
1118 long syntheticReads=0;
1119 long numMated=0;
1120 long numMatedBases=0;
1121 long badPairs=0;
1122 long badPairBases=0;
1123 long innerLengthSum=0;
1124 long outerLengthSum=0;
1125 long insertSizeSum=0;
1126
1127 long callsToScore=0;
1128 long callsToExtend=0;
1129 long initialKeys=0;
1130 long initialKeyIterations=0;
1131 long usedKeys=0;
1132 long usedKeyIterations=0;
1133
1134 long[] hist_hits=new long[41];
1135 long[] hist_hits_score=new long[41];
1136 long[] hist_hits_extend=new long[41];
1137
1138 long initialSiteSum1=0;
1139 long postTrimSiteSum1=0;
1140 long postRescueSiteSum1=0;
1141 long siteSum1=0;
1142 long topSiteSum1=0;
1143
1144 long matchCountS1=0;
1145 long matchCountI1=0;
1146 long matchCountD1=0;
1147 long matchCountM1=0;
1148 long matchCountN1=0;
1149
1150 long readCountS1=0;
1151 long readCountI1=0;
1152 long readCountD1=0;
1153 long readCountN1=0;
1154 long readCountSplice1=0;
1155 long readCountE1=0;
1156
1157
1158 long mapped1=0;
1159 long mappedRetained1=0;
1160 long mappedRetainedBases1=0;
1161 long rescuedP1=0;
1162 long rescuedM1=0;
1163 long truePositiveP1=0;
1164 long truePositiveM1=0;
1165 long falsePositive1=0;
1166 long totalCorrectSites1=0;
1167 long firstSiteCorrectP1=0;
1168 long firstSiteCorrectM1=0;
1169 long firstSiteIncorrect1=0;
1170 long firstSiteCorrectLoose1=0;
1171 long firstSiteIncorrectLoose1=0;
1172 long firstSiteCorrectPaired1=0;
1173 long firstSiteCorrectSolo1=0;
1174 long firstSiteCorrectRescued1=0;
1175 long perfectHit1=0; //Highest score is max score
1176 long uniqueHit1=0; //Only one hit has highest score
1177 long correctUniqueHit1=0; //unique highest hit on answer site
1178 long correctMultiHit1=0; //non-unique highest hit on answer site (non-skimmer only)
1179 long correctLowHit1=0; //hit on answer site, but not highest scorer
1180 long noHit1=0;
1181 long perfectMatch1=0; //Highest slow score is max slow score
1182 long semiperfectMatch1=0;
1183 long perfectMatchBases1=0;
1184 long semiperfectMatchBases1=0;
1185 long perfectHitCount1=0;
1186 long semiPerfectHitCount1=0;
1187 long duplicateBestAlignment1=0;
1188 long duplicateBestAlignmentBases1=0;
1189
1190 long totalNumCorrect1=0; //Only for skimmer
1191 long totalNumIncorrect1=0; //Only for skimmer
1192 long totalNumIncorrectPrior1=0; //Only for skimmer
1193 long totalNumCapturedAllCorrect1=0; //Only for skimmer
1194 long totalNumCapturedAllCorrectTop1=0; //Only for skimmer
1195 long totalNumCapturedAllCorrectOnly1=0; //Only for skimmer
1196
1197 long initialSiteSum2=0;
1198 long postTrimSiteSum2=0;
1199 long postRescueSiteSum2=0;
1200 long siteSum2=0;
1201 long topSiteSum2=0;
1202
1203 long mapped2=0;
1204 long mappedRetained2=0;
1205 long mappedRetainedBases2=0;
1206 long rescuedP2=0;
1207 long rescuedM2=0;
1208 long truePositiveP2=0;
1209 long truePositiveM2=0;
1210 long falsePositive2=0;
1211 long totalCorrectSites2=0;
1212 long firstSiteCorrectP2=0;
1213 long firstSiteCorrectM2=0;
1214 long firstSiteIncorrect2=0;
1215 long firstSiteCorrectLoose2=0;
1216 long firstSiteIncorrectLoose2=0;
1217 long firstSiteCorrectPaired2=0;
1218 long firstSiteCorrectSolo2=0;
1219 long firstSiteCorrectRescued2=0;
1220 long perfectHit2=0; //Highest score is max score
1221 long perfectHitCount2=0;
1222 long semiPerfectHitCount2=0;
1223
1224 long uniqueHit2=0; //Only one hit has highest score
1225 long correctUniqueHit2=0; //unique highest hit on answer site
1226 long correctMultiHit2=0; //non-unique highest hit on answer site (non-skimmer only)
1227 long correctLowHit2=0; //hit on answer site, but not highest scorer
1228 long noHit2=0;
1229 long perfectMatch2=0; //Highest slow score is max slow score
1230 long semiperfectMatch2=0;
1231 long perfectMatchBases2=0;
1232 long semiperfectMatchBases2=0;
1233 long duplicateBestAlignment2=0;
1234 long duplicateBestAlignmentBases2=0;
1235
1236 long totalNumCorrect2=0; //Only for skimmer
1237 long totalNumIncorrect2=0; //Only for skimmer
1238 long totalNumIncorrectPrior2=0; //Only for skimmer
1239 long totalNumCapturedAllCorrect2=0; //Only for skimmer
1240 long totalNumCapturedAllCorrectTop2=0; //Only for skimmer
1241 long totalNumCapturedAllCorrectOnly2=0; //Only for skimmer
1242
1243 long matchCountS2=0;
1244 long matchCountI2=0;
1245 long matchCountD2=0;
1246 long matchCountM2=0;
1247 long matchCountN2=0;
1248
1249 long readCountS2=0;
1250 long readCountI2=0;
1251 long readCountD2=0;
1252 long readCountN2=0;
1253 long readCountSplice2=0;
1254 long readCountE2=0;
1255
1256 readsUsed1=0;
1257 readsUsed2=0;
1258 readsIn1=0;
1259 readsIn2=0;
1260 for(int i=0; i<mtts.length; i++){
1261 AbstractMapThread mtt=mtts[i];
1262
1263 if(mtt.msa!=null){
1264 msaIterationsLimited+=mtt.msa.iterationsLimited;
1265 msaIterationsUnlimited+=mtt.msa.iterationsUnlimited;
1266 }
1267
1268 readsUsed1+=mtt.readsUsed1;
1269 readsUsed2+=mtt.readsUsed2;
1270 readsIn1+=mtt.readsIn1;
1271 readsIn2+=mtt.readsIn2;
1272 syntheticReads+=mtt.syntheticReads;
1273 numMated+=mtt.numMated;
1274 numMatedBases+=mtt.numMatedBases;
1275 badPairs+=mtt.badPairs;
1276 badPairBases+=mtt.badPairBases;
1277 innerLengthSum+=mtt.innerLengthSum;
1278 outerLengthSum+=mtt.outerLengthSum;
1279 insertSizeSum+=mtt.insertSizeSum;
1280 basesUsed1+=mtt.basesUsed1;
1281 basesUsed2+=mtt.basesUsed2;
1282 basesIn1+=mtt.basesIn1;
1283 basesIn2+=mtt.basesIn2;
1284 readsPassedBloomFilter+=mtt.readsPassedBloomFilter;
1285 basesPassedBloomFilter+=mtt.basesPassedBloomFilter;
1286 keysUsed+=mtt.keysUsed;
1287 bothUnmapped+=mtt.bothUnmapped;
1288 bothUnmappedBases+=mtt.bothUnmappedBases;
1289 eitherMapped+=mtt.eitherMapped;
1290 eitherMappedBases+=mtt.eitherMappedBases;
1291
1292 mapped1+=mtt.mapped1;
1293 mappedRetained1+=mtt.mappedRetained1;
1294 mappedRetainedBases1+=mtt.mappedRetainedBases1;
1295 rescuedP1+=mtt.rescuedP1;
1296 rescuedM1+=mtt.rescuedM1;
1297 lowQualityReadsDiscarded1+=mtt.lowQualityReadsDiscarded1;
1298 lowQualityBasesDiscarded1+=mtt.lowQualityBasesDiscarded1;
1299 truePositiveP1+=mtt.truePositiveP1;
1300 truePositiveM1+=mtt.truePositiveM1;
1301 falsePositive1+=mtt.falsePositive1;
1302 // System.err.println("Adding "+mtt.falsePositive+" false positives -> "+falsePositive);
1303 totalCorrectSites1+=mtt.totalCorrectSites1;
1304
1305 // assert(false) : mtt.firstSiteCorrectP1;
1306 firstSiteCorrectP1+=mtt.firstSiteCorrectP1;
1307 firstSiteCorrectM1+=mtt.firstSiteCorrectM1;
1308 firstSiteIncorrect1+=mtt.firstSiteIncorrect1;
1309 firstSiteCorrectLoose1+=mtt.firstSiteCorrectLoose1;
1310 firstSiteIncorrectLoose1+=mtt.firstSiteIncorrectLoose1;
1311 firstSiteCorrectPaired1+=mtt.firstSiteCorrectPaired1;
1312 firstSiteCorrectSolo1+=mtt.firstSiteCorrectSolo1;
1313 firstSiteCorrectRescued1+=mtt.firstSiteCorrectRescued1;
1314
1315 perfectHit1+=mtt.perfectHit1; //Highest score is max score
1316 perfectHitCount1+=mtt.perfectHitCount1;
1317 semiPerfectHitCount1+=mtt.semiPerfectHitCount1;
1318 uniqueHit1+=mtt.uniqueHit1; //Only one hit has highest score
1319 correctUniqueHit1+=mtt.correctUniqueHit1; //unique highest hit on answer site
1320 correctMultiHit1+=mtt.correctMultiHit1; //non-unique highest hit on answer site
1321 correctLowHit1+=mtt.correctLowHit1; //hit on answer site, but not highest scorer
1322 noHit1+=mtt.noHit1;
1323
1324 totalNumCorrect1+=mtt.totalNumCorrect1; //Skimmer only
1325 totalNumIncorrect1+=mtt.totalNumIncorrect1; //Skimmer only
1326 totalNumIncorrectPrior1+=mtt.totalNumIncorrectPrior1; //Skimmer only
1327 totalNumCapturedAllCorrect1+=mtt.totalNumCapturedAllCorrect1; //Skimmer only
1328 totalNumCapturedAllCorrectTop1+=mtt.totalNumCapturedAllCorrectTop1; //Skimmer only
1329 totalNumCapturedAllCorrectOnly1+=mtt.totalNumCapturedAllCorrectOnly1; //Skimmer only
1330
1331 perfectMatch1+=mtt.perfectMatch1; //Highest slow score is max slow score
1332 semiperfectMatch1+=mtt.semiperfectMatch1; //A semiperfect mapping was found
1333 perfectMatchBases1+=mtt.perfectMatchBases1;
1334 semiperfectMatchBases1+=mtt.semiperfectMatchBases1;
1335
1336 duplicateBestAlignment1+=mtt.ambiguousBestAlignment1;
1337 duplicateBestAlignmentBases1+=mtt.ambiguousBestAlignmentBases1;
1338
1339 initialSiteSum1+=mtt.initialSiteSum1;
1340 postTrimSiteSum1+=mtt.postTrimSiteSum1;
1341 postRescueSiteSum1+=mtt.postRescueSiteSum1;
1342 siteSum1+=mtt.siteSum1;
1343 topSiteSum1+=mtt.topSiteSum1;
1344
1345 AbstractIndex index=mtt.index();
1346 callsToScore+=index.callsToScore;
1347 callsToExtend+=index.callsToExtendScore;
1348 initialKeys+=index.initialKeys;
1349 initialKeyIterations+=index.initialKeyIterations;
1350 usedKeys+=index.usedKeys;
1351 usedKeyIterations+=index.usedKeyIterations;
1352
1353 for(int j=0; j<index.hist_hits.length; j++){
1354 int x=Tools.min(hist_hits.length-1, j);
1355 hist_hits[x]+=index.hist_hits[j];
1356 hist_hits_score[x]+=index.hist_hits_score[j];
1357 hist_hits_extend[x]+=index.hist_hits_extend[j];
1358 }
1359
1360 matchCountS1+=mtt.matchCountS1;
1361 matchCountI1+=mtt.matchCountI1;
1362 matchCountD1+=mtt.matchCountD1;
1363 matchCountM1+=mtt.matchCountM1;
1364 matchCountN1+=mtt.matchCountN1;
1365
1366 readCountS1+=mtt.readCountS1;
1367 readCountI1+=mtt.readCountI1;
1368 readCountD1+=mtt.readCountD1;
1369 readCountN1+=mtt.readCountN1;
1370 readCountSplice1+=mtt.readCountSplice1;
1371 readCountE1+=mtt.readCountE1;
1372
1373 mapped2+=mtt.mapped2;
1374 mappedRetained2+=mtt.mappedRetained2;
1375 mappedRetainedBases2+=mtt.mappedRetainedBases2;
1376 rescuedP2+=mtt.rescuedP2;
1377 rescuedM2+=mtt.rescuedM2;
1378 lowQualityReadsDiscarded2+=mtt.lowQualityReadsDiscarded2;
1379 lowQualityBasesDiscarded2+=mtt.lowQualityBasesDiscarded2;
1380 truePositiveP2+=mtt.truePositiveP2;
1381 truePositiveM2+=mtt.truePositiveM2;
1382 falsePositive2+=mtt.falsePositive2;
1383 // System.err.println("Adding "+mtt.falsePositive+" false positives -> "+falsePositive);
1384 totalCorrectSites2+=mtt.totalCorrectSites2;
1385
1386 firstSiteCorrectP2+=mtt.firstSiteCorrectP2;
1387 firstSiteCorrectM2+=mtt.firstSiteCorrectM2;
1388 firstSiteIncorrect2+=mtt.firstSiteIncorrect2;
1389 firstSiteCorrectLoose2+=mtt.firstSiteCorrectLoose2;
1390 firstSiteIncorrectLoose2+=mtt.firstSiteIncorrectLoose2;
1391 firstSiteCorrectPaired2+=mtt.firstSiteCorrectPaired2;
1392 firstSiteCorrectSolo2+=mtt.firstSiteCorrectSolo2;
1393 firstSiteCorrectRescued2+=mtt.firstSiteCorrectRescued2;
1394
1395 perfectHit2+=mtt.perfectHit2; //Highest score is max score
1396 perfectHitCount2+=mtt.perfectHitCount2;
1397 semiPerfectHitCount2+=mtt.semiPerfectHitCount2;
1398 uniqueHit2+=mtt.uniqueHit2; //Only one hit has highest score
1399 correctUniqueHit2+=mtt.correctUniqueHit2; //unique highest hit on answer site
1400 correctMultiHit2+=mtt.correctMultiHit2; //non-unique highest hit on answer site
1401 correctLowHit2+=mtt.correctLowHit2; //hit on answer site, but not highest scorer
1402 noHit2+=mtt.noHit2;
1403
1404 totalNumCorrect2+=mtt.totalNumCorrect2; //Skimmer only
1405 totalNumIncorrect2+=mtt.totalNumIncorrect2; //Skimmer only
1406 totalNumIncorrectPrior2+=mtt.totalNumIncorrectPrior2; //Skimmer only
1407 totalNumCapturedAllCorrect2+=mtt.totalNumCapturedAllCorrect2; //Skimmer only
1408 totalNumCapturedAllCorrectTop2+=mtt.totalNumCapturedAllCorrectTop2; //Skimmer only
1409 totalNumCapturedAllCorrectOnly2+=mtt.totalNumCapturedAllCorrectOnly2; //Skimmer only
1410
1411 perfectMatch2+=mtt.perfectMatch2; //Highest slow score is max slow score
1412 semiperfectMatch2+=mtt.semiperfectMatch2; //A semiperfect mapping was found
1413 perfectMatchBases2+=mtt.perfectMatchBases2;
1414 semiperfectMatchBases2+=mtt.semiperfectMatchBases2;
1415
1416 duplicateBestAlignment2+=mtt.ambiguousBestAlignment2;
1417 duplicateBestAlignmentBases2+=mtt.ambiguousBestAlignmentBases2;
1418
1419 initialSiteSum2+=mtt.initialSiteSum2;
1420 postTrimSiteSum2+=mtt.postTrimSiteSum2;
1421 postRescueSiteSum2+=mtt.postRescueSiteSum2;
1422 siteSum2+=mtt.siteSum2;
1423 topSiteSum2+=mtt.topSiteSum2;
1424
1425 matchCountS2+=mtt.matchCountS2;
1426 matchCountI2+=mtt.matchCountI2;
1427 matchCountD2+=mtt.matchCountD2;
1428 matchCountM2+=mtt.matchCountM2;
1429 matchCountN2+=mtt.matchCountN2;
1430
1431 readCountS2+=mtt.readCountS2;
1432 readCountI2+=mtt.readCountI2;
1433 readCountD2+=mtt.readCountD2;
1434 readCountN2+=mtt.readCountN2;
1435 readCountSplice2+=mtt.readCountSplice2;
1436 readCountE2+=mtt.readCountE2;
1437
1438 }
1439 maxReads=readsUsed1;
1440 if(syntheticReads>0){SYNTHETIC=true;}
1441
1442 t.stop();
1443 long nanos=t.elapsed;
1444
1445 if(verbose_stats>1){
1446 StringBuilder sb=new StringBuilder(1000);
1447 sb.append("\n\n###################\n#hits\tcount\tscore\textend\n");
1448 for(int i=0; i<hist_hits.length; i++){
1449 sb.append(i+"\t"+hist_hits[i]+"\t"+hist_hits_score[i]+"\t"+hist_hits_extend[i]+"\n");
1450 }
1451 try {
1452 ReadWrite.writeString(sb, "hist_hits.txt", true);
1453 } catch (Throwable e) {
1454 // TODO Auto-generated catch block
1455 e.printStackTrace();
1456 }
1457 }
1458
1459 final long basesUsed=basesUsed1+basesUsed2;
1460
1461 final double invTrials=1d/maxReads;
1462 final double invTrials100=100d/maxReads;
1463 final double invBases100=100d/(basesUsed);
1464 final double invBases100_1=100d/basesUsed1;
1465 final double invBases100_2=100d/basesUsed2;
1466 double invSites100=100d/siteSum1;
1467
1468 final double matedPercent=(numMated*invTrials100);
1469 final double badPairsPercent=(badPairs*invTrials100);
1470 final double matedPercentBases=(numMatedBases*invBases100);
1471 final double badPairsPercentBases=(badPairBases*invBases100);
1472 final double innerLengthAvg=(innerLengthSum*1d/numMated);
1473 final double outerLengthAvg=(outerLengthSum*1d/numMated);
1474 final double insertSizeAvg=(insertSizeSum*1d/numMated);
1475
1476 final double readsPerSecond=((readsUsed1+readsUsed2)*1000000000d)/nanos;
1477 final double fragsPerSecond=(keysUsed*1000000000d)/nanos;
1478 final double kiloBasesPerSecond=(basesUsed*1000000d)/nanos;
1479
1480 double perfectHitPercent=(perfectHit1*invTrials100); //Highest score is max score
1481 double perfectMatchPercent=(perfectMatch1*invTrials100);
1482 double semiperfectMatchPercent=(semiperfectMatch1*invTrials100);
1483 double perfectMatchPercentBases=(perfectMatchBases1*invBases100_1);
1484 double semiperfectMatchPercentBases=(semiperfectMatchBases1*invBases100_1);
1485
1486 double perfectHitCountPercent=perfectHitCount1*invSites100;
1487 double semiPerfectHitCountPercent=semiPerfectHitCount1*invSites100;
1488
1489 double uniqueHitPercent=(uniqueHit1*invTrials100); //Only one hit has highest score
1490 double correctUniqueHitPercent=(correctUniqueHit1*invTrials100); //unique highest hit on answer site
1491 double correctMultiHitPercent=(correctMultiHit1*invTrials100); //non-unique highest hit on answer site
1492 double correctLowHitPercent=(correctLowHit1*invTrials100); //hit on answer site, but not highest scorer
1493 double ambiguousFound=(duplicateBestAlignment1*invTrials100);
1494 double ambiguousBasesFound=(duplicateBestAlignmentBases1*invBases100_1);
1495 double correctHighHitPercent=((correctMultiHit1+correctUniqueHit1)*invTrials100);
1496 double correctHitPercent=((correctLowHit1+correctMultiHit1+correctUniqueHit1)*invTrials100);
1497
1498 double mappedB=(mapped1*invTrials100);
1499 double mappedRetainedB=(mappedRetained1*invTrials100);
1500 double mappedRetainedBasesB=(mappedRetainedBases1*invBases100_1);
1501 double rescuedPB=(rescuedP1*invTrials100);
1502 double rescuedMB=(rescuedM1*invTrials100);
1503
1504 double falsePositiveB=(firstSiteIncorrect1*invTrials100);
1505 double falsePositiveLooseB=(firstSiteIncorrectLoose1*invTrials100);
1506 double truePositivePB=(firstSiteCorrectP1*invTrials100);
1507 double truePositiveMB=(firstSiteCorrectM1*invTrials100);
1508 double truePositiveStrict=((firstSiteCorrectP1+firstSiteCorrectM1)*invTrials100);
1509 double truePositiveLoose=(firstSiteCorrectLoose1*invTrials100);
1510 double snrStrict=10*Math.log10((firstSiteCorrectM1+firstSiteCorrectP1+0.1)/(firstSiteIncorrect1+0.1));
1511 double snrLoose=10*Math.log10((firstSiteCorrectLoose1+0.1)/(firstSiteIncorrectLoose1+0.1));
1512 double truePositivePMRatio=(truePositivePB/truePositiveMB);
1513 double truePositivePairedB=(firstSiteCorrectPaired1*100d/numMated);
1514 double truePositiveSoloB=(firstSiteCorrectSolo1*100d/(mappedRetained1-numMated));
1515 double truePositiveRescuedB=(firstSiteCorrectRescued1*100d/(rescuedP1+rescuedM1));
1516
1517 double noHitPercent=(noHit1*invTrials100);
1518
1519 long mappedReads, unambiguousReads, mappedBases, unambiguousBases;
1520 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
1521 mappedReads=mappedRetained1+duplicateBestAlignment1;
1522 unambiguousReads=mappedRetained1;
1523 mappedBases=mappedRetainedBases1+duplicateBestAlignmentBases1;
1524 unambiguousBases=mappedRetainedBases1;
1525 }else{
1526 mappedReads=mappedRetained1;
1527 unambiguousReads=mappedRetained1-duplicateBestAlignment1;
1528 mappedBases=mappedRetainedBases1;
1529 unambiguousBases=mappedRetainedBases1-duplicateBestAlignmentBases1;
1530 }
1531
1532 double avgNumCorrect=(SKIMMER ? totalNumCorrect1*invTrials : (totalCorrectSites1/(1d*(truePositiveP1+truePositiveM1))));
1533 double avgNumIncorrect=totalNumIncorrect1*invTrials; //Skimmer only
1534 double avgNumIncorrectPrior=totalNumIncorrectPrior1*invTrials; //Skimmer only
1535
1536 double rateCapturedAllCorrect=totalNumCapturedAllCorrect1*invTrials100; //Skimmer only
1537 double rateCapturedAllTop=totalNumCapturedAllCorrectTop1*invTrials100; //Skimmer only
1538 double rateCapturedAllOnly=totalNumCapturedAllCorrectOnly1*invTrials100; //Skimmer only
1539
1540 double avgCallsToScore=(callsToScore*invTrials);
1541 double avgCallsToExtendScore=(callsToExtend*invTrials);
1542 double avgInitialKeys=(initialKeys*1d/initialKeyIterations);
1543 double avgUsedKeys=(usedKeys*1d/usedKeyIterations);
1544
1545 double avgInitialSites=(initialSiteSum1*invTrials);
1546 double avgPostTrimSites=(postTrimSiteSum1*invTrials);
1547 double avgPostRescueSites=(postRescueSiteSum1*invTrials);
1548 double avgSites=(siteSum1*invTrials);
1549 double avgPerfectSites=(perfectHitCount1*invTrials);
1550 double avgSemiPerfectSites=(semiPerfectHitCount1*invTrials);
1551 double avgTopSites=(topSiteSum1*invTrials);
1552 double lowQualityReadsDiscardedPercent=(lowQualityReadsDiscarded1*invTrials100);
1553 double lowQualityBasesDiscardedPercent=(lowQualityBasesDiscarded1*invBases100_1);
1554
1555 long matchErrors=matchCountS1+matchCountI1+matchCountD1;
1556 long baseLen=matchCountM1+matchCountI1+matchCountS1+matchCountN1;
1557 long matchLen=matchCountM1+matchCountI1+matchCountS1+matchCountN1+matchCountD1;
1558 long refLen=matchCountM1+matchCountS1+matchCountN1+matchCountD1;
1559 double errorRate=matchErrors*100d/matchLen;
1560 double matchRate=matchCountM1*100d/matchLen;
1561 double subRate=matchCountS1*100d/matchLen;
1562 double delRate=matchCountD1*100d/matchLen;
1563 double insRate=matchCountI1*100d/matchLen;
1564 double nRate=matchCountN1*100d/matchLen;
1565 double readSubRate=readCountS1*100d/mapped1;
1566 double readDelRate=readCountD1*100d/mapped1;
1567 double readInsRate=readCountI1*100d/mapped1;
1568 double readNRate=readCountN1*100d/mapped1;
1569 double readSpliceRate=readCountSplice1*100d/mapped1;
1570 double readErrorRate=readCountE1*100d/mapped1;
1571
1572 if(SYNTHETIC && verbose_stats==-1){verbose_stats=Tools.max(verbose_stats,9);}
1573
1574 tswStats.println("Reads Used: \t"+(readsUsed1+readsUsed2)+"\t("+(basesUsed)+" bases)");
1575 tswStats.println();
1576
1577 if(useRandomReads){
1578 tswStats.println("Read Length: \t"+synthReadlen);
1579 tswStats.println("SNP rate: \t"+baseSnpRate+"\t(max = "+maxSnps+")");
1580 tswStats.println("INS rate: \t"+baseInsRate+"\t(max = "+maxInss+", maxLen = "+maxInsLen+")");
1581 tswStats.println("DEL rate: \t"+baseDelRate+"\t(max = "+maxDels+", maxLen = "+maxDelLen+")");
1582 tswStats.println("SUB rate: \t"+baseSubRate+"\t(max = "+maxSubs+", maxLen = "+maxSubLen+")");
1583 tswStats.println("minQuality: \t"+minQuality);
1584 tswStats.println("midQuality: \t"+midQuality);
1585 tswStats.println("maxQuality: \t"+maxQuality);
1586 tswStats.println("prefect fraction: \t"+PERFECT_READ_RATIO);
1587 tswStats.println();
1588 }
1589
1590 tswStats.println("Mapping: \t"+t);
1591 tswStats.println(Tools.format("Reads/sec: \t%.2f", readsPerSecond));
1592 tswStats.println(Tools.format("kBases/sec: \t%.2f", kiloBasesPerSecond));
1593 double milf=msaIterationsLimited*invTrials;
1594 double milu=msaIterationsUnlimited*invTrials;
1595 if(verbose_stats>=1){tswStats.println("MSA iterations: \t"+Tools.format("%.2fL + %.2fU = %.2f", milf,milu,milf+milu));}
1596
1597 if(paired){
1598 tswStats.println("\n\nPairing data: \tpct pairs\tnum pairs \tpct bases\t num bases");
1599 tswStats.println();
1600 if(paired){
1601 tswStats.println("mated pairs: \t"+padPercent(matedPercent,4)+"% \t"+pad(numMated,9)+" \t"+padPercent(matedPercentBases,4)+"% \t"+pad(numMatedBases,12));
1602 tswStats.println("bad pairs: \t"+padPercent(badPairsPercent,4)+"% \t"+pad(badPairs,9)+" \t"+padPercent(badPairsPercentBases,4)+"% \t"+pad(badPairBases,12));
1603 }
1604
1605 tswStats.println("insert size avg: \t "+padPercent(insertSizeAvg,2));
1606 if(ReadStats.COLLECT_INSERT_STATS){
1607 if(ReadStats.merged==null){ReadStats.mergeAll();}
1608 long[] array=ReadStats.merged.insertHist.array;
1609 double median=Tools.medianHistogram(array);
1610 double q1=Tools.percentileHistogram(array, 0.25);
1611 double q3=Tools.percentileHistogram(array, 0.75);
1612 double stdev=Tools.standardDeviationHistogram(array);
1613 //TODO: Quartiles
1614 tswStats.println("insert 25th %: \t "+padPercent(q1,2));
1615 tswStats.println("insert median: \t "+padPercent(median,2));
1616 tswStats.println("insert 75th %: \t "+padPercent(q3,2));
1617 tswStats.println("insert std dev: \t "+padPercent(stdev,2));
1618 tswStats.println("insert mode: \t "+Tools.calcModeHistogram(array));
1619 }
1620 if(verbose_stats>=1){
1621 tswStats.println(Tools.format("avg inner length:\t %.2f", innerLengthAvg));
1622 tswStats.println(Tools.format("avg insert size: \t %.2f", outerLengthAvg));
1623 }
1624 }
1625
1626 /** For RQCFilter */
1627 lastBothUnmapped=bothUnmapped;
1628 lastBothUnmappedBases=bothUnmappedBases;
1629 lastEitherMapped=eitherMapped;
1630 lastEitherMappedBases=eitherMappedBases;
1631 lastReadsUsed=readsUsed1+readsUsed2;
1632 lastBasesUsed=basesUsed;
1633 lastReadsIn=readsIn1+readsIn2;
1634 lastBasesIn=basesIn1+basesIn2;
1635 lastReadsPassedBloomFilter=readsPassedBloomFilter;
1636 lastBasesPassedBloomFilter=basesPassedBloomFilter;
1637
1638 if(PRINT_UNMAPPED_COUNT){
1639 double invReadsUsed100=100.0/(readsUsed1+readsUsed2);
1640 double invBasesUsed100=100.0/basesUsed;
1641 double x=bothUnmapped*invReadsUsed100;
1642 double y=bothUnmappedBases*invBasesUsed100;
1643 if(!paired){tswStats.println();}
1644 tswStats.println("unmapped: \t"+padPercent(x,4)+"% \t"+pad(bothUnmapped,9)+" \t"+padPercent(y,4)+"% \t"+pad(bothUnmappedBases,12));
1645 }
1646
1647 tswStats.println();
1648 tswStats.println("\nRead 1 data: \tpct reads\tnum reads \tpct bases\t num bases");
1649 if(verbose_stats>=1){
1650 if(avgInitialKeys>0){tswStats.println(Tools.format("Avg Initial Keys: \t"+(avgInitialKeys<100?" ":"")+"%.3f",
1651 avgInitialKeys));}
1652 if(avgUsedKeys>0){tswStats.println(Tools.format("Avg Used Keys: \t"+(avgUsedKeys<100?" ":"")+"%.3f",
1653 avgUsedKeys));}
1654 if(avgCallsToScore>0){tswStats.println(Tools.format("Avg Calls to Score: \t"+(avgCallsToScore<100?" ":"")+"%.3f",
1655 avgCallsToScore));}
1656 if(avgCallsToExtendScore>0){tswStats.println(Tools.format("Avg Calls to Extend:\t"+(avgCallsToExtendScore<100?" ":"")+"%.3f",
1657 avgCallsToExtendScore));}
1658 tswStats.println();
1659
1660 tswStats.println(Tools.format("Avg Initial Sites: \t"+(avgInitialSites<10?" ":"")+"%.3f", avgInitialSites));
1661 if(TRIM_LIST){tswStats.println(Tools.format("Avg Post-Trim: \t"+(avgPostTrimSites<10?" ":"")+"%.3f", avgPostTrimSites));}
1662 if(paired){tswStats.println(Tools.format("Avg Post-Rescue: \t"+(avgPostRescueSites<10?" ":"")+"%.3f", avgPostRescueSites));}
1663 tswStats.println(Tools.format("Avg Final Sites: \t"+(avgSites<10?" ":"")+"%.3f", avgSites));
1664 tswStats.println(Tools.format("Avg Top Sites: \t"+(avgTopSites<10?" ":"")+"%.3f", avgTopSites));
1665 if(verbose_stats>1){
1666 tswStats.println(Tools.format("Avg Perfect Sites: \t"+(avgPerfectSites<10?" ":"")+"%.3f \t"+
1667 (perfectHitCountPercent<10?" ":"")+"%.3f%%", avgPerfectSites, perfectHitCountPercent));
1668 tswStats.println(Tools.format("Avg Semiperfect Sites:\t"+(avgSemiPerfectSites<10?" ":"")+"%.3f \t"+
1669 (semiPerfectHitCountPercent<10?" ":"")+"%.3f%%", avgSemiPerfectSites, semiPerfectHitCountPercent));
1670 }
1671
1672 if(SYNTHETIC){
1673 tswStats.println(Tools.format("Avg Correct Sites: \t"+(avgNumCorrect<10?" ":"")+"%.3f", avgNumCorrect));
1674 if(SKIMMER){
1675 tswStats.println(Tools.format("Avg Incorrect Sites:\t"+(avgNumIncorrect<10?" ":"")+"%.3f", avgNumIncorrect));
1676 tswStats.println(Tools.format("Avg IncorrectP Sites:\t"+(avgNumIncorrectPrior<10?" ":"")+"%.3f", avgNumIncorrectPrior));
1677 }
1678 }
1679 }
1680
1681 tswStats.println();
1682 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
1683 double x=ambiguousFound+mappedRetainedB;
1684 double y=ambiguousBasesFound+mappedRetainedBasesB;
1685 tswStats.println("mapped: \t"+padPercent(x,4)+"% \t"+pad(mappedReads,9)+" \t"+padPercent(y,4)+"% \t"+pad(mappedBases,12));
1686 tswStats.println("unambiguous: \t"+padPercent(mappedRetainedB,4)+"% \t"+pad(unambiguousReads,9)+" \t"+padPercent(mappedRetainedBasesB,4)+"% \t"+pad(unambiguousBases,12));
1687 }else{
1688 double x=mappedRetainedB-ambiguousFound;
1689 double y=mappedRetainedBasesB-ambiguousBasesFound;
1690 tswStats.println("mapped: \t"+padPercent(mappedRetainedB,4)+"% \t"+pad(mappedReads,9)+" \t"+padPercent(mappedRetainedBasesB,4)+"% \t"+pad(mappedBases,12));
1691 tswStats.println("unambiguous: \t"+padPercent(x,4)+"% \t"+pad(unambiguousReads,9)+" \t"+padPercent(y,4)+"% \t"+pad(unambiguousBases,12));
1692 }
1693 tswStats.println("ambiguous: \t"+padPercent(ambiguousFound,4)+"% \t"+pad(duplicateBestAlignment1,9)+
1694 " \t"+padPercent(ambiguousBasesFound,4)+"% \t"+pad(duplicateBestAlignmentBases1,12));
1695 tswStats.println("low-Q discards: \t"+padPercent(lowQualityReadsDiscardedPercent,4)+"% \t"+pad(lowQualityReadsDiscarded1,9)+
1696 " \t"+padPercent(lowQualityBasesDiscardedPercent,4)+"% \t"+pad(lowQualityBasesDiscarded1,12));
1697
1698 tswStats.println();
1699 tswStats.println("perfect best site:\t"+padPercent(perfectMatchPercent,4)+"% \t"+pad(perfectMatch1,9)+
1700 " \t"+padPercent(perfectMatchPercentBases,4)+"% \t"+pad(perfectMatchBases1,12));
1701 tswStats.println("semiperfect site:\t"+padPercent(semiperfectMatchPercent,4)+"% \t"+pad(semiperfectMatch1,9)+
1702 " \t"+padPercent(semiperfectMatchPercentBases,4)+"% \t"+pad(semiperfectMatchBases1,12));
1703 if(paired){
1704 tswStats.println("rescued: \t"+padPercent(rescuedPB+rescuedMB,4)+"% \t"+pad(rescuedP1+rescuedM1,9));
1705 }
1706
1707 if(MAKE_MATCH_STRING){
1708
1709 tswStats.println();
1710 // tswStats.println(" \tpct reads\tnum reads \tpct bases\t num bases");
1711 tswStats.println("Match Rate: \t NA \t NA \t"+padPercent(matchRate,4)+"% \t"+pad(matchCountM1,12));
1712 tswStats.println("Error Rate: \t"+padPercent(readErrorRate,4)+"% \t"+pad(readCountE1,9)+" \t"+padPercent(errorRate,4)+"% \t"+pad(matchErrors,12));
1713 tswStats.println("Sub Rate: \t"+padPercent(readSubRate,4)+"% \t"+pad(readCountS1,9)+" \t"+padPercent(subRate,4)+"% \t"+pad(matchCountS1,12));
1714 tswStats.println("Del Rate: \t"+padPercent(readDelRate,4)+"% \t"+pad(readCountD1,9)+" \t"+padPercent(delRate,4)+"% \t"+pad(matchCountD1,12));
1715 tswStats.println("Ins Rate: \t"+padPercent(readInsRate,4)+"% \t"+pad(readCountI1,9)+" \t"+padPercent(insRate,4)+"% \t"+pad(matchCountI1,12));
1716 tswStats.println("N Rate: \t"+padPercent(readNRate,4)+"% \t"+pad(readCountN1,9)+" \t"+padPercent(nRate,4)+"% \t"+pad(matchCountN1,12));
1717 if(SamLine.INTRON_LIMIT<Integer.MAX_VALUE){
1718 tswStats.println("Splice Rate: \t"+padPercent(readSpliceRate,4)+"% \t"+pad(readCountSplice1,9)+" \t(splices at least "+SamLine.INTRON_LIMIT+" bp)");
1719 }
1720
1721 if(DOUBLE_PRINT_ERROR_RATE){
1722 System.err.println();
1723 System.err.println(Tools.format("Match Rate: \t"+(matchRate<10?" ":"")+"%.4f", matchRate)+"% \t"+matchCountM1);
1724 System.err.println(Tools.format("Error Rate: \t"+(errorRate<10?" ":"")+"%.4f", errorRate)+"% \t"+matchErrors);
1725 System.err.println(Tools.format("Sub Rate: \t"+(subRate<10?" ":"")+"%.4f", subRate)+"% \t"+matchCountS1);
1726 System.err.println(Tools.format("Del Rate: \t"+(delRate<10?" ":"")+"%.4f", delRate)+"% \t"+matchCountD1);
1727 System.err.println(Tools.format("Ins Rate: \t"+(insRate<10?" ":"")+"%.4f", insRate)+"% \t"+matchCountI1);
1728 System.err.println(Tools.format("N Rate: \t"+(nRate<10?" ":"")+"%.4f", nRate)+"% \t"+matchCountN1);
1729 }
1730 }
1731
1732 if(SYNTHETIC){
1733 tswStats.println();
1734 tswStats.println("true positive: \t"+padPercent(truePositiveStrict,4)+"%\t(loose: "+padPercent(truePositiveLoose,4)+"%)");
1735 tswStats.println("false positive: \t"+padPercent(falsePositiveB,4)+"%\t(loose: "+padPercent(falsePositiveLooseB,4)+"%)");
1736 tswStats.println("false negative: \t"+padPercent(noHitPercent,4)+"%");
1737 tswStats.println("SNR: \t"+padPercent(snrStrict,4)+" \t(loose: "+padPercent(snrLoose,4)+")");
1738 if(verbose_stats>0){
1739 tswStats.println("correctLowHit: \t"+padPercent(correctLowHitPercent,4)+"%");
1740 tswStats.println(Tools.format("Plus/Minus ratio:\t %1.4f", truePositivePMRatio));
1741 }
1742
1743 if(paired){
1744 tswStats.println("correct pairs: \t"+padPercent(truePositivePairedB,4)+"%\t(of mated)");
1745 tswStats.println("correct singles: \t"+padPercent(truePositiveSoloB,4)+"%");
1746 tswStats.println("correct rescued: \t"+padPercent(truePositiveRescuedB,4)+"%");
1747 }
1748
1749 if(SKIMMER){
1750 tswStats.println("found all correct:\t"+padPercent(rateCapturedAllCorrect,4)+"%)");
1751 tswStats.println("all correct top: \t"+padPercent(rateCapturedAllTop,4)+"%)");
1752 tswStats.println("all correct only: \t"+padPercent(rateCapturedAllOnly,4)+"%)");
1753 }
1754 }
1755
1756 if(paired){
1757
1758 invSites100=100d/siteSum2;
1759
1760 perfectHitPercent=(perfectHit2*invTrials100); //Highest score is max score
1761 perfectMatchPercent=(perfectMatch2*invTrials100);
1762 semiperfectMatchPercent=(semiperfectMatch2*invTrials100);
1763 perfectMatchPercentBases=(perfectMatchBases2*invBases100_2);
1764 semiperfectMatchPercentBases=(semiperfectMatchBases2*invBases100_2);
1765
1766 perfectHitCountPercent=perfectHitCount2*invSites100;
1767 semiPerfectHitCountPercent=semiPerfectHitCount2*invSites100;
1768
1769 uniqueHitPercent=(uniqueHit2*invTrials100); //Only one hit has highest score
1770 correctUniqueHitPercent=(correctUniqueHit2*invTrials100); //unique highest hit on answer site
1771 correctMultiHitPercent=(correctMultiHit2*invTrials100); //non-unique highest hit on answer site
1772 correctLowHitPercent=(correctLowHit2*invTrials100); //hit on answer site, but not highest scorer
1773 ambiguousFound=(duplicateBestAlignment2*invTrials100);
1774 ambiguousBasesFound=(duplicateBestAlignmentBases2*invBases100_2);
1775 correctHighHitPercent=((correctMultiHit2+correctUniqueHit2)*invTrials100);
1776 correctHitPercent=((correctLowHit2+correctMultiHit2+correctUniqueHit2)*invTrials100);
1777
1778 mappedB=(mapped2*invTrials100);
1779 mappedRetainedB=(mappedRetained2*invTrials100);
1780 mappedRetainedBasesB=(mappedRetainedBases2*invBases100_2);
1781 rescuedPB=(rescuedP2*invTrials100);
1782 rescuedMB=(rescuedM2*invTrials100);
1783 falsePositiveB=(firstSiteIncorrect2*invTrials100);
1784 falsePositiveLooseB=(firstSiteIncorrectLoose2*invTrials100);
1785 truePositivePB=(firstSiteCorrectP2*invTrials100);
1786 truePositiveMB=(firstSiteCorrectM2*invTrials100);
1787 truePositiveStrict=((firstSiteCorrectP2+firstSiteCorrectM2)*invTrials100);
1788 truePositiveLoose=(firstSiteCorrectLoose2*invTrials100);
1789 snrStrict=10*Math.log10((firstSiteCorrectM2+firstSiteCorrectP2+0.1)/(firstSiteIncorrect2+0.1));
1790 snrLoose=10*Math.log10((firstSiteCorrectLoose2+0.1)/(firstSiteIncorrectLoose2+0.1));
1791 truePositivePMRatio=(truePositivePB/truePositiveMB);
1792 truePositivePairedB=(firstSiteCorrectPaired2*100d/numMated);
1793 truePositiveSoloB=(firstSiteCorrectSolo2*100d/(mappedRetained2-numMated));
1794 truePositiveRescuedB=(firstSiteCorrectRescued2*100d/(rescuedP2+rescuedM2));
1795 noHitPercent=(noHit2*invTrials100);
1796
1797 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
1798 mappedReads=mappedRetained2+duplicateBestAlignment2;
1799 unambiguousReads=mappedRetained2;
1800 mappedBases=mappedRetainedBases2+duplicateBestAlignmentBases2;
1801 unambiguousBases=mappedRetainedBases2;
1802 }else{
1803 mappedReads=mappedRetained2;
1804 unambiguousReads=mappedRetained2-duplicateBestAlignment2;
1805 mappedBases=mappedRetainedBases2;
1806 unambiguousBases=mappedRetainedBases2-duplicateBestAlignmentBases2;
1807 }
1808
1809 avgNumCorrect=(SKIMMER ? totalNumCorrect2*invTrials : (totalCorrectSites2/(2d*(truePositiveP2+truePositiveM2))));
1810 avgNumIncorrect=totalNumIncorrect2*invTrials; //Skimmer only
1811 avgNumIncorrectPrior=totalNumIncorrectPrior2*invTrials; //Skimmer only
1812
1813 rateCapturedAllCorrect=totalNumCapturedAllCorrect2*invTrials100; //Skimmer only
1814 rateCapturedAllTop=totalNumCapturedAllCorrectTop2*invTrials100; //Skimmer only
1815 rateCapturedAllOnly=totalNumCapturedAllCorrectOnly2*invTrials100; //Skimmer only
1816
1817 avgCallsToScore=(callsToScore*invTrials);
1818 avgCallsToExtendScore=(callsToExtend*invTrials);
1819 avgInitialKeys=(initialKeys*2d/initialKeyIterations);
1820 avgUsedKeys=(usedKeys*2d/usedKeyIterations);
1821
1822 avgInitialSites=(initialSiteSum2*invTrials);
1823 avgPostTrimSites=(postTrimSiteSum2*invTrials);
1824 avgPostRescueSites=(postRescueSiteSum2*invTrials);
1825 avgSites=(siteSum2*invTrials);
1826 avgPerfectSites=(perfectHitCount2*invTrials);
1827 avgSemiPerfectSites=(semiPerfectHitCount2*invTrials);
1828 avgTopSites=(topSiteSum2*invTrials);
1829 lowQualityReadsDiscardedPercent=(lowQualityReadsDiscarded2*invTrials100);
1830 lowQualityBasesDiscardedPercent=(lowQualityBasesDiscarded2*invBases100_2);
1831
1832 matchErrors=matchCountS2+matchCountI2+matchCountD2;
1833 baseLen=matchCountM2+matchCountI2+matchCountS2+matchCountN2;
1834 matchLen=matchCountM2+matchCountI2+matchCountS2+matchCountN2+matchCountD2;
1835 refLen=matchCountM2+matchCountS2+matchCountN2+matchCountD2;
1836 errorRate=matchErrors*100d/matchLen;
1837 matchRate=matchCountM2*100d/matchLen;
1838 subRate=matchCountS2*100d/matchLen;
1839 delRate=matchCountD2*100d/matchLen;
1840 insRate=matchCountI2*100d/matchLen;
1841 nRate=matchCountN2*100d/matchLen;
1842 readSubRate=readCountS2*100d/mapped2;
1843 readDelRate=readCountD2*100d/mapped2;
1844 readInsRate=readCountI2*100d/mapped2;
1845 readNRate=readCountN2*100d/mapped2;
1846 readSpliceRate=readCountSplice2*100d/mapped2;
1847 readErrorRate=readCountE2*100d/mapped2;
1848
1849 tswStats.println();
1850 tswStats.println("\nRead 2 data: \tpct reads\tnum reads \tpct bases\t num bases");
1851 if(verbose_stats>=1){
1852 if(avgInitialKeys>0){tswStats.println(Tools.format("Avg Initial Keys: \t"+(avgInitialKeys<100?" ":"")+"%.3f",
1853 avgInitialKeys));}
1854 if(avgUsedKeys>0){tswStats.println(Tools.format("Avg Used Keys: \t"+(avgUsedKeys<100?" ":"")+"%.3f",
1855 avgUsedKeys));}
1856 if(avgCallsToScore>0){tswStats.println(Tools.format("Avg Calls to Score: \t"+(avgCallsToScore<100?" ":"")+"%.3f",
1857 avgCallsToScore));}
1858 if(avgCallsToExtendScore>0){tswStats.println(Tools.format("Avg Calls to Extend:\t"+(avgCallsToExtendScore<100?" ":"")+"%.3f",
1859 avgCallsToExtendScore));}
1860 tswStats.println();
1861
1862 tswStats.println(Tools.format("Avg Initial Sites: \t"+(avgInitialSites<10?" ":"")+"%.3f", avgInitialSites));
1863 if(TRIM_LIST){tswStats.println(Tools.format("Avg Post-Trim: \t"+(avgPostTrimSites<10?" ":"")+"%.3f", avgPostTrimSites));}
1864 if(paired){tswStats.println(Tools.format("Avg Post-Rescue: \t"+(avgPostRescueSites<10?" ":"")+"%.3f", avgPostRescueSites));}
1865 tswStats.println(Tools.format("Avg Final Sites: \t"+(avgSites<10?" ":"")+"%.3f", avgSites));
1866 tswStats.println(Tools.format("Avg Top Sites: \t"+(avgTopSites<10?" ":"")+"%.3f", avgTopSites));
1867 if(verbose_stats>1){
1868 tswStats.println(Tools.format("Avg Perfect Sites: \t"+(avgPerfectSites<10?" ":"")+"%.3f \t"+
1869 (perfectHitCountPercent<10?" ":"")+"%.3f%%", avgPerfectSites, perfectHitCountPercent));
1870 tswStats.println(Tools.format("Avg Semiperfect Sites:\t"+(avgSemiPerfectSites<10?" ":"")+"%.3f \t"+
1871 (semiPerfectHitCountPercent<10?" ":"")+"%.3f%%", avgSemiPerfectSites, semiPerfectHitCountPercent));
1872 }
1873
1874 if(SYNTHETIC){
1875 tswStats.println(Tools.format("Avg Correct Sites: \t"+(avgNumCorrect<10?" ":"")+"%.3f", avgNumCorrect));
1876 if(SKIMMER){
1877 tswStats.println(Tools.format("Avg Incorrect Sites:\t"+(avgNumIncorrect<10?" ":"")+"%.3f", avgNumIncorrect));
1878 tswStats.println(Tools.format("Avg IncorrectP Sites:\t"+(avgNumIncorrectPrior<10?" ":"")+"%.3f", avgNumIncorrectPrior));
1879 }
1880 }
1881 }
1882
1883 tswStats.println();
1884 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
1885 double x=ambiguousFound+mappedRetainedB;
1886 double y=ambiguousBasesFound+mappedRetainedBasesB;
1887 tswStats.println("mapped: \t"+padPercent(x,4)+"% \t"+pad(mappedReads,9)+" \t"+padPercent(y,4)+"% \t"+pad(mappedBases,12));
1888 tswStats.println("unambiguous: \t"+padPercent(mappedRetainedB,4)+"% \t"+pad(unambiguousReads,9)+" \t"+padPercent(mappedRetainedBasesB,4)+"% \t"+pad(unambiguousBases,12));
1889 }else{
1890 double x=mappedRetainedB-ambiguousFound;
1891 double y=mappedRetainedBasesB-ambiguousBasesFound;
1892 tswStats.println("mapped: \t"+padPercent(mappedRetainedB,4)+"% \t"+pad(mappedReads,9)+" \t"+padPercent(mappedRetainedBasesB,4)+"% \t"+pad(mappedBases,12));
1893 tswStats.println("unambiguous: \t"+padPercent(x,4)+"% \t"+pad(unambiguousReads,9)+" \t"+padPercent(y,4)+"% \t"+pad(unambiguousBases,12));
1894 }
1895 tswStats.println("ambiguous: \t"+padPercent(ambiguousFound,4)+"% \t"+pad(duplicateBestAlignment2,9)+
1896 " \t"+padPercent(ambiguousBasesFound,4)+"% \t"+pad(duplicateBestAlignmentBases2,12));
1897 tswStats.println("low-Q discards: \t"+padPercent(lowQualityReadsDiscardedPercent,4)+"% \t"+pad(lowQualityReadsDiscarded2,9)+
1898 " \t"+padPercent(lowQualityBasesDiscardedPercent,4)+"% \t"+pad(lowQualityBasesDiscarded2,12));
1899
1900 tswStats.println();
1901 tswStats.println("perfect best site:\t"+padPercent(perfectMatchPercent,4)+"% \t"+pad(perfectMatch2,9)+
1902 " \t"+padPercent(perfectMatchPercentBases,4)+"% \t"+pad(perfectMatchBases2,12));
1903 tswStats.println("semiperfect site:\t"+padPercent(semiperfectMatchPercent,4)+"% \t"+pad(semiperfectMatch2,9)+
1904 " \t"+padPercent(semiperfectMatchPercentBases,4)+"% \t"+pad(semiperfectMatchBases2,12));
1905 if(paired){
1906 tswStats.println("rescued: \t"+padPercent(rescuedPB+rescuedMB,4)+"% \t"+pad(rescuedP2+rescuedM2,9));
1907 }
1908
1909 if(MAKE_MATCH_STRING){
1910
1911 tswStats.println();
1912 // tswStats.println(" \tpct reads\tnum reads \tpct bases\t num bases");
1913 tswStats.println("Match Rate: \t NA \t NA \t"+padPercent(matchRate,4)+"% \t"+pad(matchCountM2,12));
1914 tswStats.println("Error Rate: \t"+padPercent(readErrorRate,4)+"% \t"+pad(readCountE2,9)+" \t"+padPercent(errorRate,4)+"% \t"+pad(matchErrors,12));
1915 tswStats.println("Sub Rate: \t"+padPercent(readSubRate,4)+"% \t"+pad(readCountS2,9)+" \t"+padPercent(subRate,4)+"% \t"+pad(matchCountS2,12));
1916 tswStats.println("Del Rate: \t"+padPercent(readDelRate,4)+"% \t"+pad(readCountD2,9)+" \t"+padPercent(delRate,4)+"% \t"+pad(matchCountD2,12));
1917 tswStats.println("Ins Rate: \t"+padPercent(readInsRate,4)+"% \t"+pad(readCountI2,9)+" \t"+padPercent(insRate,4)+"% \t"+pad(matchCountI2,12));
1918 tswStats.println("N Rate: \t"+padPercent(readNRate,4)+"% \t"+pad(readCountN2,9)+" \t"+padPercent(nRate,4)+"% \t"+pad(matchCountN2,12));
1919 if(SamLine.INTRON_LIMIT<Integer.MAX_VALUE){
1920 tswStats.println("Splice Rate: \t"+padPercent(readSpliceRate,4)+"% \t"+pad(readCountSplice2,9)+" \t(splices at least "+SamLine.INTRON_LIMIT+" bp)");
1921 }
1922
1923 if(DOUBLE_PRINT_ERROR_RATE){
1924 System.err.println();
1925 System.err.println(Tools.format("Match Rate: \t"+(matchRate<10?" ":"")+"%.4f", matchRate)+"% \t"+matchCountM2);
1926 System.err.println(Tools.format("Error Rate: \t"+(errorRate<10?" ":"")+"%.4f", errorRate)+"% \t"+matchErrors);
1927 System.err.println(Tools.format("Sub Rate: \t"+(subRate<10?" ":"")+"%.4f", subRate)+"% \t"+matchCountS2);
1928 System.err.println(Tools.format("Del Rate: \t"+(delRate<10?" ":"")+"%.4f", delRate)+"% \t"+matchCountD2);
1929 System.err.println(Tools.format("Ins Rate: \t"+(insRate<10?" ":"")+"%.4f", insRate)+"% \t"+matchCountI2);
1930 System.err.println(Tools.format("N Rate: \t"+(nRate<10?" ":"")+"%.4f", nRate)+"% \t"+matchCountN2);
1931 }
1932 }
1933
1934 if(SYNTHETIC){
1935 tswStats.println();
1936 tswStats.println("true positive: \t"+padPercent(truePositiveStrict,4)+"%\t(loose: "+padPercent(truePositiveLoose,4)+"%)");
1937 tswStats.println("false positive: \t"+padPercent(falsePositiveB,4)+"%\t(loose: "+padPercent(falsePositiveLooseB,4)+"%)");
1938 tswStats.println("false negative: \t"+padPercent(noHitPercent,4)+"%");
1939 tswStats.println("SNR: \t"+padPercent(snrStrict,4)+" \t(loose: "+padPercent(snrLoose,4)+")");
1940 if(verbose_stats>0){
1941 tswStats.println("correctLowHit: \t"+padPercent(correctLowHitPercent,4)+"%");
1942 tswStats.println(Tools.format("Plus/Minus ratio:\t %2.4f", truePositivePMRatio));
1943 }
1944
1945 if(paired){
1946 tswStats.println("correct pairs: \t"+padPercent(truePositivePairedB,4)+"%\t(of mated)");
1947 tswStats.println("correct singles: \t"+padPercent(truePositiveSoloB,4)+"%");
1948 tswStats.println("correct rescued: \t"+padPercent(truePositiveRescuedB,4)+"%");
1949 }
1950
1951 if(SKIMMER){
1952 tswStats.println("found all correct:\t"+padPercent(rateCapturedAllCorrect,4)+"%)");
1953 tswStats.println("all correct top: \t"+padPercent(rateCapturedAllTop,4)+"%)");
1954 tswStats.println("all correct only: \t"+padPercent(rateCapturedAllOnly,4)+"%)");
1955 }
1956 }
1957 }
1958 errorState|=tswStats.poisonAndWait();
1959
1960 if(BBSplitter.TRACK_SCAF_STATS){
1961 BBSplitter.printCounts(BBSplitter.SCAF_STATS_FILE, BBSplitter.scafCountTable, true, readsUsed1+readsUsed2, nzoStats, sortStats);
1962 }
1963
1964 if(BBSplitter.TRACK_SET_STATS){
1965 BBSplitter.printCounts(BBSplitter.SET_STATS_FILE, BBSplitter.setCountTable, true, readsUsed1+readsUsed2, nzoStats, sortStats);
1966 }
1967
1968 final long pbf2=(readsUsed2==0 ? readsPassedBloomFilter : readsPassedBloomFilter/2);
1969 final long readSum=truePositiveP1+truePositiveM1+falsePositive1+noHit1+lowQualityReadsDiscarded1+pbf2;
1970 assert(!CALC_STATISTICS || readSum==maxReads) :
1971 "\nThe number of reads out does not add up to the number of reads in.\nThis may indicate that a mapping thread crashed." +
1972 "\nIf you submit a bug report, include the entire console output, not just this error message.\n"+
1973 truePositiveP1+"+"+truePositiveM1+"+"+falsePositive1+"+"+noHit1+"+"+lowQualityReadsDiscarded1+"+"+pbf2+" = "+
1974 readSum+" != "+maxReads;
1975 if(!SKIMMER){
1976 assert(!CALC_STATISTICS || truePositiveP1+truePositiveM1==correctLowHit1+correctMultiHit1+correctUniqueHit1);
1977 }else{
1978 assert(!CALC_STATISTICS || truePositiveP1+truePositiveM1==correctLowHit1+correctUniqueHit1);
1979 }
1980 }
1981
1982
1983 static void printOutput_Machine(final AbstractMapThread[] mtts, final Timer t, final int keylen, final boolean paired, final boolean SKIMMER,
1984 boolean nzoStats, boolean sortStats, String dest){
1985 if(dest==null){dest="stderr.txt";}
1986 TextStreamWriter tswStats=new TextStreamWriter(dest, overwrite, append, false);
1987 tswStats.start();
1988
1989 long readsUsed1=0;
1990 long readsUsed2=0;
1991 long readsIn1=0;
1992 long readsIn2=0;
1993
1994 long lowQualityReadsDiscarded1=0;
1995 long lowQualityReadsDiscarded2=0;
1996 long lowQualityBasesDiscarded1=0;
1997 long lowQualityBasesDiscarded2=0;
1998
1999 long msaIterationsLimited=0;
2000 long msaIterationsUnlimited=0;
2001
2002 long basesUsed1=0;
2003 long basesUsed2=0;
2004 long basesIn1=0;
2005 long basesIn2=0;
2006 long readsPassedBloomFilter=0;
2007 long basesPassedBloomFilter=0;
2008 long basesAtQuickmap=0;
2009 long keysUsed=0;
2010 long bothUnmapped=0;
2011 long bothUnmappedBases=0;
2012 long eitherMapped=0;
2013 long eitherMappedBases=0;
2014
2015 long syntheticReads=0;
2016 long numMated=0;
2017 long badPairs=0;
2018 long innerLengthSum=0;
2019 long outerLengthSum=0;
2020 long insertSizeSum=0;
2021
2022 long callsToScore=0;
2023 long callsToExtend=0;
2024 long initialKeys=0;
2025 long initialKeyIterations=0;
2026 long usedKeys=0;
2027 long usedKeyIterations=0;
2028
2029 long[] hist_hits=new long[41];
2030 long[] hist_hits_score=new long[41];
2031 long[] hist_hits_extend=new long[41];
2032
2033 long initialSiteSum1=0;
2034 long postTrimSiteSum1=0;
2035 long postRescueSiteSum1=0;
2036 long siteSum1=0;
2037 long topSiteSum1=0;
2038
2039 long matchCountS1=0;
2040 long matchCountI1=0;
2041 long matchCountD1=0;
2042 long matchCountM1=0;
2043 long matchCountN1=0;
2044
2045
2046 long mapped1=0;
2047 long mappedRetained1=0;
2048 long rescuedP1=0;
2049 long rescuedM1=0;
2050 long truePositiveP1=0;
2051 long truePositiveM1=0;
2052 long falsePositive1=0;
2053 long totalCorrectSites1=0;
2054 long firstSiteCorrectP1=0;
2055 long firstSiteCorrectM1=0;
2056 long firstSiteIncorrect1=0;
2057 long firstSiteCorrectLoose1=0;
2058 long firstSiteIncorrectLoose1=0;
2059 long firstSiteCorrectPaired1=0;
2060 long firstSiteCorrectSolo1=0;
2061 long firstSiteCorrectRescued1=0;
2062 long perfectHit1=0; //Highest score is max score
2063 long uniqueHit1=0; //Only one hit has highest score
2064 long correctUniqueHit1=0; //unique highest hit on answer site
2065 long correctMultiHit1=0; //non-unique highest hit on answer site (non-skimmer only)
2066 long correctLowHit1=0; //hit on answer site, but not highest scorer
2067 long noHit1=0;
2068 long perfectMatch1=0; //Highest slow score is max slow score
2069 long semiperfectMatch1=0;
2070 long perfectMatchBases1=0;
2071 long semiperfectMatchBases1=0;
2072 long perfectHitCount1=0;
2073 long semiPerfectHitCount1=0;
2074 long duplicateBestAlignment1=0;
2075
2076 long totalNumCorrect1=0; //Only for skimmer
2077 long totalNumIncorrect1=0; //Only for skimmer
2078 long totalNumIncorrectPrior1=0; //Only for skimmer
2079 long totalNumCapturedAllCorrect1=0; //Only for skimmer
2080 long totalNumCapturedAllCorrectTop1=0; //Only for skimmer
2081 long totalNumCapturedAllCorrectOnly1=0; //Only for skimmer
2082
2083 long initialSiteSum2=0;
2084 long postTrimSiteSum2=0;
2085 long postRescueSiteSum2=0;
2086 long siteSum2=0;
2087 long topSiteSum2=0;
2088
2089 long mapped2=0;
2090 long mappedRetained2=0;
2091 long rescuedP2=0;
2092 long rescuedM2=0;
2093 long truePositiveP2=0;
2094 long truePositiveM2=0;
2095 long falsePositive2=0;
2096 long totalCorrectSites2=0;
2097 long firstSiteCorrectP2=0;
2098 long firstSiteCorrectM2=0;
2099 long firstSiteIncorrect2=0;
2100 long firstSiteCorrectLoose2=0;
2101 long firstSiteIncorrectLoose2=0;
2102 long firstSiteCorrectPaired2=0;
2103 long firstSiteCorrectSolo2=0;
2104 long firstSiteCorrectRescued2=0;
2105 long perfectHit2=0; //Highest score is max score
2106 long perfectHitCount2=0;
2107 long semiPerfectHitCount2=0;
2108
2109 long uniqueHit2=0; //Only one hit has highest score
2110 long correctUniqueHit2=0; //unique highest hit on answer site
2111 long correctMultiHit2=0; //non-unique highest hit on answer site (non-skimmer only)
2112 long correctLowHit2=0; //hit on answer site, but not highest scorer
2113 long noHit2=0;
2114 long perfectMatch2=0; //Highest slow score is max slow score
2115 long semiperfectMatch2=0;
2116 long perfectMatchBases2=0;
2117 long semiperfectMatchBases2=0;
2118 long duplicateBestAlignment2=0;
2119
2120 long totalNumCorrect2=0; //Only for skimmer
2121 long totalNumIncorrect2=0; //Only for skimmer
2122 long totalNumIncorrectPrior2=0; //Only for skimmer
2123 long totalNumCapturedAllCorrect2=0; //Only for skimmer
2124 long totalNumCapturedAllCorrectTop2=0; //Only for skimmer
2125 long totalNumCapturedAllCorrectOnly2=0; //Only for skimmer
2126
2127 long matchCountS2=0;
2128 long matchCountI2=0;
2129 long matchCountD2=0;
2130 long matchCountM2=0;
2131 long matchCountN2=0;
2132
2133 readsUsed1=0;
2134 readsUsed2=0;
2135 readsIn1=0;
2136 readsIn2=0;
2137 for(int i=0; i<mtts.length; i++){
2138 AbstractMapThread mtt=mtts[i];
2139
2140 if(mtt.msa!=null){
2141 msaIterationsLimited+=mtt.msa.iterationsLimited;
2142 msaIterationsUnlimited+=mtt.msa.iterationsUnlimited;
2143 }
2144
2145 readsUsed1+=mtt.readsUsed1;
2146 readsUsed2+=mtt.readsUsed2;
2147 readsIn1+=mtt.readsIn1;
2148 readsIn2+=mtt.readsIn2;
2149 syntheticReads+=mtt.syntheticReads;
2150 numMated+=mtt.numMated;
2151 // numMatedBases+=mtt.numMatedBases;
2152 badPairs+=mtt.badPairs;
2153 // badPairBases+=mtt.badPairBases;
2154 innerLengthSum+=mtt.innerLengthSum;
2155 outerLengthSum+=mtt.outerLengthSum;
2156 insertSizeSum+=mtt.insertSizeSum;
2157 basesUsed1+=mtt.basesUsed1;
2158 basesUsed2+=mtt.basesUsed2;
2159 basesIn1+=mtt.basesIn1;
2160 basesIn2+=mtt.basesIn2;
2161 readsPassedBloomFilter+=mtt.readsPassedBloomFilter;
2162 basesPassedBloomFilter+=mtt.basesPassedBloomFilter;
2163 keysUsed+=mtt.keysUsed;
2164 bothUnmapped+=mtt.bothUnmapped;
2165 bothUnmappedBases+=mtt.bothUnmappedBases;
2166 eitherMapped+=mtt.eitherMapped;
2167 eitherMappedBases+=mtt.eitherMappedBases;
2168
2169 mapped1+=mtt.mapped1;
2170 mappedRetained1+=mtt.mappedRetained1;
2171 rescuedP1+=mtt.rescuedP1;
2172 rescuedM1+=mtt.rescuedM1;
2173 lowQualityReadsDiscarded1+=mtt.lowQualityReadsDiscarded1;
2174 truePositiveP1+=mtt.truePositiveP1;
2175 truePositiveM1+=mtt.truePositiveM1;
2176 falsePositive1+=mtt.falsePositive1;
2177 // System.err.println("Adding "+mtt.falsePositive+" false positives -> "+falsePositive);
2178 totalCorrectSites1+=mtt.totalCorrectSites1;
2179
2180 firstSiteCorrectP1+=mtt.firstSiteCorrectP1;
2181 firstSiteCorrectM1+=mtt.firstSiteCorrectM1;
2182 firstSiteIncorrect1+=mtt.firstSiteIncorrect1;
2183 firstSiteCorrectLoose1+=mtt.firstSiteCorrectLoose1;
2184 firstSiteIncorrectLoose1+=mtt.firstSiteIncorrectLoose1;
2185 firstSiteCorrectPaired1+=mtt.firstSiteCorrectPaired1;
2186 firstSiteCorrectSolo1+=mtt.firstSiteCorrectSolo1;
2187 firstSiteCorrectRescued1+=mtt.firstSiteCorrectRescued1;
2188
2189 perfectHit1+=mtt.perfectHit1; //Highest score is max score
2190 perfectHitCount1+=mtt.perfectHitCount1;
2191 semiPerfectHitCount1+=mtt.semiPerfectHitCount1;
2192 uniqueHit1+=mtt.uniqueHit1; //Only one hit has highest score
2193 correctUniqueHit1+=mtt.correctUniqueHit1; //unique highest hit on answer site
2194 correctMultiHit1+=mtt.correctMultiHit1; //non-unique highest hit on answer site
2195 correctLowHit1+=mtt.correctLowHit1; //hit on answer site, but not highest scorer
2196 noHit1+=mtt.noHit1;
2197
2198 totalNumCorrect1+=mtt.totalNumCorrect1; //Skimmer only
2199 totalNumIncorrect1+=mtt.totalNumIncorrect1; //Skimmer only
2200 totalNumIncorrectPrior1+=mtt.totalNumIncorrectPrior1; //Skimmer only
2201 totalNumCapturedAllCorrect1+=mtt.totalNumCapturedAllCorrect1; //Skimmer only
2202 totalNumCapturedAllCorrectTop1+=mtt.totalNumCapturedAllCorrectTop1; //Skimmer only
2203 totalNumCapturedAllCorrectOnly1+=mtt.totalNumCapturedAllCorrectOnly1; //Skimmer only
2204
2205 perfectMatch1+=mtt.perfectMatch1; //Highest slow score is max slow score
2206 semiperfectMatch1+=mtt.semiperfectMatch1; //A semiperfect mapping was found
2207 perfectMatchBases1+=mtt.perfectMatchBases1;
2208 semiperfectMatchBases1+=mtt.semiperfectMatchBases1;
2209
2210 duplicateBestAlignment1+=mtt.ambiguousBestAlignment1;
2211
2212 initialSiteSum1+=mtt.initialSiteSum1;
2213 postTrimSiteSum1+=mtt.postTrimSiteSum1;
2214 postRescueSiteSum1+=mtt.postRescueSiteSum1;
2215 siteSum1+=mtt.siteSum1;
2216 topSiteSum1+=mtt.topSiteSum1;
2217
2218 AbstractIndex index=mtt.index();
2219 callsToScore+=index.callsToScore;
2220 callsToExtend+=index.callsToExtendScore;
2221 initialKeys+=index.initialKeys;
2222 initialKeyIterations+=index.initialKeyIterations;
2223 usedKeys+=index.usedKeys;
2224 usedKeyIterations+=index.usedKeyIterations;
2225
2226 for(int j=0; j<index.hist_hits.length; j++){
2227 int x=Tools.min(hist_hits.length-1, j);
2228 hist_hits[x]+=index.hist_hits[j];
2229 hist_hits_score[x]+=index.hist_hits_score[j];
2230 hist_hits_extend[x]+=index.hist_hits_extend[j];
2231 }
2232
2233 matchCountS1+=mtt.matchCountS1;
2234 matchCountI1+=mtt.matchCountI1;
2235 matchCountD1+=mtt.matchCountD1;
2236 matchCountM1+=mtt.matchCountM1;
2237 matchCountN1+=mtt.matchCountN1;
2238
2239 mapped2+=mtt.mapped2;
2240 mappedRetained2+=mtt.mappedRetained2;
2241 rescuedP2+=mtt.rescuedP2;
2242 rescuedM2+=mtt.rescuedM2;
2243 lowQualityReadsDiscarded2+=mtt.lowQualityReadsDiscarded2;
2244 truePositiveP2+=mtt.truePositiveP2;
2245 truePositiveM2+=mtt.truePositiveM2;
2246 falsePositive2+=mtt.falsePositive2;
2247 // System.err.println("Adding "+mtt.falsePositive+" false positives -> "+falsePositive);
2248 totalCorrectSites2+=mtt.totalCorrectSites2;
2249
2250 firstSiteCorrectP2+=mtt.firstSiteCorrectP2;
2251 firstSiteCorrectM2+=mtt.firstSiteCorrectM2;
2252 firstSiteIncorrect2+=mtt.firstSiteIncorrect2;
2253 firstSiteCorrectLoose2+=mtt.firstSiteCorrectLoose2;
2254 firstSiteIncorrectLoose2+=mtt.firstSiteIncorrectLoose2;
2255 firstSiteCorrectPaired2+=mtt.firstSiteCorrectPaired2;
2256 firstSiteCorrectSolo2+=mtt.firstSiteCorrectSolo2;
2257 firstSiteCorrectRescued2+=mtt.firstSiteCorrectRescued2;
2258
2259 perfectHit2+=mtt.perfectHit2; //Highest score is max score
2260 perfectHitCount2+=mtt.perfectHitCount2;
2261 semiPerfectHitCount2+=mtt.semiPerfectHitCount2;
2262 uniqueHit2+=mtt.uniqueHit2; //Only one hit has highest score
2263 correctUniqueHit2+=mtt.correctUniqueHit2; //unique highest hit on answer site
2264 correctMultiHit2+=mtt.correctMultiHit2; //non-unique highest hit on answer site
2265 correctLowHit2+=mtt.correctLowHit2; //hit on answer site, but not highest scorer
2266 noHit2+=mtt.noHit2;
2267
2268 totalNumCorrect2+=mtt.totalNumCorrect2; //Skimmer only
2269 totalNumIncorrect2+=mtt.totalNumIncorrect2; //Skimmer only
2270 totalNumIncorrectPrior2+=mtt.totalNumIncorrectPrior2; //Skimmer only
2271 totalNumCapturedAllCorrect2+=mtt.totalNumCapturedAllCorrect2; //Skimmer only
2272 totalNumCapturedAllCorrectTop2+=mtt.totalNumCapturedAllCorrectTop2; //Skimmer only
2273 totalNumCapturedAllCorrectOnly2+=mtt.totalNumCapturedAllCorrectOnly2; //Skimmer only
2274
2275 perfectMatch2+=mtt.perfectMatch2; //Highest slow score is max slow score
2276 semiperfectMatch2+=mtt.semiperfectMatch2; //A semiperfect mapping was found
2277 perfectMatchBases1+=mtt.perfectMatchBases1;
2278 semiperfectMatchBases1+=mtt.semiperfectMatchBases1;
2279
2280 duplicateBestAlignment2+=mtt.ambiguousBestAlignment2;
2281
2282 initialSiteSum2+=mtt.initialSiteSum2;
2283 postTrimSiteSum2+=mtt.postTrimSiteSum2;
2284 postRescueSiteSum2+=mtt.postRescueSiteSum2;
2285 siteSum2+=mtt.siteSum2;
2286 topSiteSum2+=mtt.topSiteSum2;
2287
2288 matchCountS2+=mtt.matchCountS2;
2289 matchCountI2+=mtt.matchCountI2;
2290 matchCountD2+=mtt.matchCountD2;
2291 matchCountM2+=mtt.matchCountM2;
2292 matchCountN2+=mtt.matchCountN2;
2293
2294 }
2295 maxReads=readsUsed1;
2296 if(syntheticReads>0){SYNTHETIC=true;}
2297
2298 t.stop();
2299 long nanos=t.elapsed;
2300
2301 if(verbose_stats>1){
2302 StringBuilder sb=new StringBuilder(1000);
2303 sb.append("\n\n###################\n#hits\tcount\tscore\textend\n");
2304 for(int i=0; i<hist_hits.length; i++){
2305 sb.append(i+"\t"+hist_hits[i]+"\t"+hist_hits_score[i]+"\t"+hist_hits_extend[i]+"\n");
2306 }
2307 try {
2308 ReadWrite.writeString(sb, "hist_hits.txt", true);
2309 } catch (Throwable e) {
2310 // TODO Auto-generated catch block
2311 e.printStackTrace();
2312 }
2313 }
2314
2315 final long basesUsed=(basesUsed1+basesUsed2);
2316
2317 final double invTrials=1d/maxReads;
2318 final double invTrials100=100d/maxReads;
2319 double invSites100=100d/siteSum1;
2320
2321 final double matedPercent=(numMated*invTrials100);
2322 final double badPairsPercent=(badPairs*invTrials100);
2323 final double innerLengthAvg=(innerLengthSum*1d/numMated);
2324 final double outerLengthAvg=(outerLengthSum*1d/numMated);
2325 final double insertSizeAvg=(insertSizeSum*1d/numMated);
2326
2327 final double readsPerSecond=((readsUsed1+readsUsed2)*1000000000d)/nanos;
2328 final double fragsPerSecond=(keysUsed*1000000000d)/nanos;
2329 final double kiloBasesPerSecond=(basesUsed*1000000d)/nanos;
2330
2331 double perfectHitPercent=(perfectHit1*invTrials100); //Highest score is max score
2332 double perfectMatchPercent=(perfectMatch1*invTrials100);
2333 double semiperfectMatchPercent=(semiperfectMatch1*invTrials100);
2334
2335 double perfectHitCountPercent=perfectHitCount1*invSites100;
2336 double semiPerfectHitCountPercent=semiPerfectHitCount1*invSites100;
2337
2338 double uniqueHitPercent=(uniqueHit1*invTrials100); //Only one hit has highest score
2339 double correctUniqueHitPercent=(correctUniqueHit1*invTrials100); //unique highest hit on answer site
2340 double correctMultiHitPercent=(correctMultiHit1*invTrials100); //non-unique highest hit on answer site
2341 double correctLowHitPercent=(correctLowHit1*invTrials100); //hit on answer site, but not highest scorer
2342 double ambiguousFound=(duplicateBestAlignment1*invTrials100);
2343 double correctHighHitPercent=((correctMultiHit1+correctUniqueHit1)*invTrials100);
2344 double correctHitPercent=((correctLowHit1+correctMultiHit1+correctUniqueHit1)*invTrials100);
2345
2346 double mappedB=(mapped1*invTrials100);
2347 double mappedRetainedB=(mappedRetained1*invTrials100);
2348 double rescuedPB=(rescuedP1*invTrials100);
2349 double rescuedMB=(rescuedM1*invTrials100);
2350 double falsePositiveB=(firstSiteIncorrect1*invTrials100);
2351 double falsePositiveLooseB=(firstSiteIncorrectLoose1*invTrials100);
2352 double truePositivePB=(firstSiteCorrectP1*invTrials100);
2353 double truePositiveMB=(firstSiteCorrectM1*invTrials100);
2354 double truePositiveStrict=((firstSiteCorrectP1+firstSiteCorrectM1)*invTrials100);
2355 double truePositiveLoose=(firstSiteCorrectLoose1*invTrials100);
2356 double snrStrict=10*Math.log10((firstSiteCorrectM1+firstSiteCorrectP1+0.1)/(firstSiteIncorrect1+0.1));
2357 double snrLoose=10*Math.log10((firstSiteCorrectLoose1+0.1)/(firstSiteIncorrectLoose1+0.1));
2358 double truePositivePMRatio=(truePositivePB/truePositiveMB);
2359 double truePositivePairedB=(firstSiteCorrectPaired1*100d/numMated);
2360 double truePositiveSoloB=(firstSiteCorrectSolo1*100d/(mappedRetained1-numMated));
2361 double truePositiveRescuedB=(firstSiteCorrectRescued1*100d/(rescuedP1+rescuedM1));
2362 double noHitPercent=(noHit1*invTrials100);
2363
2364 long mappedReads, unambiguousReads;
2365 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
2366 mappedReads=mappedRetained1+duplicateBestAlignment1;
2367 unambiguousReads=mappedRetained1;
2368 }else{
2369 mappedReads=mappedRetained1;
2370 unambiguousReads=mappedRetained1-duplicateBestAlignment1;
2371 }
2372
2373 double avgNumCorrect=(SKIMMER ? totalNumCorrect1*invTrials : (totalCorrectSites1/(1d*(truePositiveP1+truePositiveM1))));
2374 double avgNumIncorrect=totalNumIncorrect1*invTrials; //Skimmer only
2375 double avgNumIncorrectPrior=totalNumIncorrectPrior1*invTrials; //Skimmer only
2376
2377 double rateCapturedAllCorrect=totalNumCapturedAllCorrect1*invTrials100; //Skimmer only
2378 double rateCapturedAllTop=totalNumCapturedAllCorrectTop1*invTrials100; //Skimmer only
2379 double rateCapturedAllOnly=totalNumCapturedAllCorrectOnly1*invTrials100; //Skimmer only
2380
2381 double avgCallsToScore=(callsToScore*invTrials);
2382 double avgCallsToExtendScore=(callsToExtend*invTrials);
2383 double avgInitialKeys=(initialKeys*1d/initialKeyIterations);
2384 double avgUsedKeys=(usedKeys*1d/usedKeyIterations);
2385
2386 double avgInitialSites=(initialSiteSum1*invTrials);
2387 double avgPostTrimSites=(postTrimSiteSum1*invTrials);
2388 double avgPostRescueSites=(postRescueSiteSum1*invTrials);
2389 double avgSites=(siteSum1*invTrials);
2390 double avgPerfectSites=(perfectHitCount1*invTrials);
2391 double avgSemiPerfectSites=(semiPerfectHitCount1*invTrials);
2392 double avgTopSites=(topSiteSum1*invTrials);
2393 double lowQualityReadsDiscardedPercent=(lowQualityReadsDiscarded1*invTrials100);
2394
2395 long matchErrors=matchCountS1+matchCountI1+matchCountD1;
2396 long baseLen=matchCountM1+matchCountI1+matchCountS1+matchCountN1;
2397 long matchLen=matchCountM1+matchCountI1+matchCountS1+matchCountN1+matchCountD1;
2398 long refLen=matchCountM1+matchCountS1+matchCountN1+matchCountD1;
2399 double errorRate=matchErrors*100d/matchLen;
2400 double matchRate=matchCountM1*100d/matchLen;//baseLen;
2401 double subRate=matchCountS1*100d/matchLen;//baseLen;
2402 double delRate=matchCountD1*100d/matchLen;
2403 double insRate=matchCountI1*100d/matchLen;//baseLen;
2404 double nRate=matchCountN1*100d/matchLen;//baseLen;
2405
2406 if(SYNTHETIC && verbose_stats==-1){verbose_stats=Tools.max(verbose_stats,9);}
2407
2408 tswStats.println("Reads_Used"+DELIMITER+(readsUsed1+readsUsed2));
2409 tswStats.println("Bases_Used"+DELIMITER+(basesUsed));
2410 tswStats.println(Tools.format("Reads/sec"+DELIMITER+"%.2f", readsPerSecond));
2411 tswStats.println(Tools.format("kBases/sec"+DELIMITER+"%.2f", kiloBasesPerSecond));
2412 double milf=msaIterationsLimited*invTrials;
2413 double milu=msaIterationsUnlimited*invTrials;
2414 if(verbose_stats>=1){tswStats.println("MSA_iterations"+DELIMITER+Tools.format("%.2fL + %.2fU = %.2f", milf,milu,milf+milu));}
2415
2416 // tswStats.println();
2417 // tswStats.println("\nRead 1 data:");
2418
2419 tswStats.println();
2420
2421 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
2422 double x=ambiguousFound+mappedRetainedB;
2423 tswStats.println("R1_Mapped_Percent"+DELIMITER+padPercentMachine(x,4)+"%");
2424 tswStats.println("R1_Unambiguous_Percent"+DELIMITER+padPercentMachine(mappedRetainedB,4)+"%");
2425 tswStats.println("R1_Mapped_Reads"+DELIMITER+mappedReads);
2426 tswStats.println("R1_Unambiguous_Reads"+DELIMITER+unambiguousReads);
2427 }else{
2428 double x=mappedRetainedB-ambiguousFound;
2429 tswStats.println("R1_Mapped_Percent"+DELIMITER+padPercentMachine(mappedRetainedB,4)+"%");
2430 tswStats.println("R1_Unambiguous_Percent"+DELIMITER+padPercentMachine(x,4)+"%");
2431 tswStats.println("R1_Mapped_Reads"+DELIMITER+mappedReads);
2432 tswStats.println("R1_Unambiguous_Reads"+DELIMITER+unambiguousReads);
2433 }
2434
2435 tswStats.println();
2436 if(paired){
2437 tswStats.println(Tools.format("Mated_Pairs"+DELIMITER+"%.4f%%", matedPercent));
2438 tswStats.println(Tools.format("Bad_Pairs"+DELIMITER+"%.3f%%", badPairsPercent));
2439 }
2440 if(paired){
2441 tswStats.println(Tools.format("R1_Rescued"+DELIMITER+"%.3f", rescuedPB+rescuedMB)+"%");
2442 tswStats.println(Tools.format("Avg_Insert_Size"+DELIMITER+"%.2f", insertSizeAvg));
2443 }
2444 tswStats.println();
2445 tswStats.println(Tools.format("R1_Perfect_Best_Site"+DELIMITER+"%.4f", perfectMatchPercent)+"%");
2446 tswStats.println(Tools.format("R1_Semiperfect_Site"+DELIMITER+"%.4f", semiperfectMatchPercent)+"%");
2447 tswStats.println(Tools.format("R1_Ambiguous_Mapping"+DELIMITER+"%.4f", ambiguousFound)+"%");
2448 // +(REMOVE_DUPLICATE_BEST_ALIGNMENTS ? " (Removed)" : " (Kept)"));
2449 tswStats.println(Tools.format("R1_Low_Quality_Discards"+DELIMITER+"%.4f", lowQualityReadsDiscardedPercent)+"%");
2450
2451 if(MAKE_MATCH_STRING){
2452 tswStats.println();
2453 tswStats.println("R1_Match_Rate"+DELIMITER+padPercentMachine(matchRate,4)+"%");
2454 tswStats.println("R1_Error_Rate"+DELIMITER+padPercentMachine(errorRate,4)+"%");
2455 tswStats.println("R1_Sub_Rate"+DELIMITER+padPercentMachine(subRate,4)+"%");
2456 tswStats.println("R1_Del_Rate"+DELIMITER+padPercentMachine(delRate,4)+"%");
2457 tswStats.println("R1_Ins_Rate"+DELIMITER+padPercentMachine(insRate,4)+"%");
2458 tswStats.println("R1_N_Rate"+DELIMITER+padPercentMachine(nRate,4)+"%");
2459
2460 tswStats.println("R1_Match_Count"+DELIMITER+matchCountM1);
2461 tswStats.println("R1_Error_Count"+DELIMITER+matchErrors);
2462 tswStats.println("R1_Sub_Count"+DELIMITER+matchCountS1);
2463 tswStats.println("R1_Del_Count"+DELIMITER+matchCountD1);
2464 tswStats.println("R1_Ins_Count"+DELIMITER+matchCountI1);
2465 tswStats.println("R1_N_Count"+DELIMITER+matchCountN1);
2466 }
2467
2468 if(paired){
2469 invSites100=100d/siteSum2;
2470
2471 perfectHitPercent=perfectHit2*invTrials100; //Highest score is max score
2472 perfectMatchPercent=perfectMatch2*invTrials100;
2473 semiperfectMatchPercent=semiperfectMatch2*invTrials100;
2474
2475 perfectHitCountPercent=perfectHitCount2*invSites100;
2476 semiPerfectHitCountPercent=semiPerfectHitCount2*invSites100;
2477
2478 uniqueHitPercent=uniqueHit2*invTrials100; //Only one hit has highest score
2479 correctUniqueHitPercent=correctUniqueHit2*invTrials100; //unique highest hit on answer site
2480 correctMultiHitPercent=correctMultiHit2*invTrials100; //non-unique highest hit on answer site
2481 correctLowHitPercent=correctLowHit2*invTrials100; //hit on answer site, but not highest scorer
2482 ambiguousFound=(duplicateBestAlignment2*invTrials100);
2483 correctHighHitPercent=(correctMultiHit2+correctUniqueHit2)*invTrials100;
2484 correctHitPercent=(correctLowHit2+correctMultiHit2+correctUniqueHit2)*invTrials100;
2485
2486 mappedB=(mapped2*invTrials100);
2487 mappedRetainedB=(mappedRetained2*invTrials100);
2488 rescuedPB=(rescuedP2*invTrials100);
2489 rescuedMB=(rescuedM2*invTrials100);
2490 falsePositiveB=(firstSiteIncorrect2*invTrials100);
2491 falsePositiveLooseB=(firstSiteIncorrectLoose2*invTrials100);
2492 truePositivePB=(firstSiteCorrectP2*invTrials100);
2493 truePositiveMB=(firstSiteCorrectM2*invTrials100);
2494 truePositiveStrict=((firstSiteCorrectP2+firstSiteCorrectM2)*invTrials100);
2495 truePositiveLoose=(firstSiteCorrectLoose2*invTrials100);
2496 snrStrict=10*Math.log10((firstSiteCorrectM2+firstSiteCorrectP2+0.1)/(firstSiteIncorrect2+0.1));
2497 snrLoose=10*Math.log10((firstSiteCorrectLoose2+0.1)/(firstSiteIncorrectLoose2+0.1));
2498 truePositivePMRatio=(truePositivePB/truePositiveMB);
2499 truePositivePairedB=(firstSiteCorrectPaired2*100d/numMated);
2500 truePositiveSoloB=(firstSiteCorrectSolo2*100d/(mappedRetained2-numMated));
2501 truePositiveRescuedB=(firstSiteCorrectRescued2*100d/(rescuedP2+rescuedM2));
2502 avgNumCorrect=(totalCorrectSites2/(1d*(truePositiveP2+truePositiveM2)));
2503 noHitPercent=noHit2*invTrials100;
2504
2505 avgNumCorrect=(SKIMMER ? totalNumCorrect2*invTrials : (totalCorrectSites2/(1d*(truePositiveP2+truePositiveM2))));
2506 avgNumIncorrect=totalNumIncorrect1*invTrials; //Skimmer only
2507 avgNumIncorrectPrior=totalNumIncorrectPrior1*invTrials; //Skimmer only
2508
2509 rateCapturedAllCorrect=totalNumCapturedAllCorrect2*invTrials100; //Skimmer only
2510 rateCapturedAllTop=totalNumCapturedAllCorrectTop2*invTrials100; //Skimmer only
2511 rateCapturedAllOnly=totalNumCapturedAllCorrectOnly2*invTrials100; //Skimmer only
2512
2513 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
2514 mappedReads=mappedRetained2+duplicateBestAlignment2;
2515 unambiguousReads=mappedRetained2;
2516 }else{
2517 mappedReads=mappedRetained2;
2518 unambiguousReads=mappedRetained2-duplicateBestAlignment2;
2519 }
2520
2521 avgInitialSites=initialSiteSum2*invTrials;
2522 avgPostTrimSites=postTrimSiteSum2*invTrials;
2523 avgPostRescueSites=postRescueSiteSum2*invTrials;
2524 avgSites=siteSum2*invTrials;
2525 avgPerfectSites=(perfectHitCount1*invTrials);
2526 avgSemiPerfectSites=(semiPerfectHitCount1*invTrials);
2527 avgTopSites=topSiteSum2*invTrials;
2528 lowQualityReadsDiscardedPercent=lowQualityReadsDiscarded2*invTrials100;
2529
2530 matchErrors=matchCountS2+matchCountI2+matchCountD2;
2531 baseLen=matchCountM2+matchCountI2+matchCountS2+matchCountN2;
2532 matchLen=matchCountM2+matchCountI2+matchCountS2+matchCountN2+matchCountD2;
2533 refLen=matchCountM2+matchCountS2+matchCountN2+matchCountD2;
2534 errorRate=matchErrors*100d/matchLen;
2535 matchRate=matchCountM2*100d/matchLen;//baseLen;
2536 subRate=matchCountS2*100d/matchLen;//baseLen;
2537 delRate=matchCountD2*100d/matchLen;
2538 insRate=matchCountI2*100d/matchLen;//baseLen;
2539 nRate=matchCountN2*100d/matchLen;//baseLen;
2540
2541 // tswStats.println("\n\nRead 2 data:");
2542 tswStats.println();
2543 // tswStats.println(Tools.format("perfectHit"+DELIMITER+"%.2f", perfectHitPercent)+"%");
2544 // tswStats.println(Tools.format("uniqueHit"+DELIMITER+"%.2f", uniqueHitPercent)+"%");
2545 // tswStats.println(Tools.format("correctUniqueHit"+DELIMITER+"%.2f", correctUniqueHitPercent)+"%");
2546 // tswStats.println(Tools.format("correctMultiHit"+DELIMITER+"%.2f", correctMultiHitPercent)+"%");
2547 // tswStats.println(Tools.format("correctHighHit"+DELIMITER+"%.2f", correctHighHitPercent)+"%");
2548 // tswStats.println(Tools.format("correctHit"+DELIMITER+"%.2f", correctHitPercent)+"%");
2549
2550 //tswStats.println(Tools.format("mapped"+DELIMITER+(mappedB<10?" ":"")+"%.3f", mappedB)+"%");
2551 if(REMOVE_DUPLICATE_BEST_ALIGNMENTS){
2552 double x=ambiguousFound+mappedRetainedB;
2553 tswStats.println("R2_Mapped_Percent"+DELIMITER+padPercentMachine(x,4)+"%");
2554 tswStats.println("R2_Unambiguous_Percent"+DELIMITER+padPercentMachine(mappedRetainedB,4)+"%");
2555 tswStats.println("R2_Mapped_Reads"+DELIMITER+mappedReads);
2556 tswStats.println("R2_Unambiguous_Reads"+DELIMITER+unambiguousReads);
2557 }else{
2558 double x=mappedRetainedB-ambiguousFound;
2559 tswStats.println("R2_Mapped_Percent"+DELIMITER+padPercentMachine(mappedRetainedB,4)+"%");
2560 tswStats.println("R2_Unambiguous_Percent"+DELIMITER+padPercentMachine(x,4)+"%");
2561 tswStats.println("R2_Mapped_Reads"+DELIMITER+mappedReads);
2562 tswStats.println("R2_Unambiguous_Reads"+DELIMITER+unambiguousReads);
2563 }
2564 tswStats.println();
2565 if(paired){
2566 tswStats.println(Tools.format("R2_Rescued"+DELIMITER+"%.3f", rescuedPB+rescuedMB)+"%");
2567 }
2568 tswStats.println();
2569 tswStats.println(Tools.format("R2_Perfect_Best_Site"+DELIMITER+"%.4f", perfectMatchPercent)+"%");
2570 tswStats.println(Tools.format("R2_Semiperfect_Site"+DELIMITER+"%.4f", semiperfectMatchPercent)+"%");
2571 tswStats.println(Tools.format("R2_Ambiguous_Mapping"+DELIMITER+"%.4f", ambiguousFound)+"%");
2572 //(REMOVE_DUPLICATE_BEST_ALIGNMENTS ? "(Removed)" : "(Kept)"));
2573 tswStats.println(Tools.format("R2_Low_Quality_Discards"+DELIMITER+"%.4f", lowQualityReadsDiscardedPercent)+"%");
2574
2575 if(MAKE_MATCH_STRING){
2576 tswStats.println();
2577 tswStats.println("R2_Match_Rate"+DELIMITER+padPercentMachine(matchRate,4)+"%");
2578 tswStats.println("R2_Error_Rate"+DELIMITER+padPercentMachine(errorRate,4)+"%");
2579 tswStats.println("R2_Sub_Rate"+DELIMITER+padPercentMachine(subRate,4)+"%");
2580 tswStats.println("R2_Del_Rate"+DELIMITER+padPercentMachine(delRate,4)+"%");
2581 tswStats.println("R2_Ins_Rate"+DELIMITER+padPercentMachine(insRate,4)+"%");
2582 tswStats.println("R2_N_Rate"+DELIMITER+padPercentMachine(nRate,4)+"%");
2583
2584 tswStats.println("R2_Match_Count"+DELIMITER+matchCountM2);
2585 tswStats.println("R2_Error_Count"+DELIMITER+matchErrors);
2586 tswStats.println("R2_Sub_Count"+DELIMITER+matchCountS2);
2587 tswStats.println("R2_Del_Count"+DELIMITER+matchCountD2);
2588 tswStats.println("R2_Ins_Count"+DELIMITER+matchCountI2);
2589 tswStats.println("R2_N_Count"+DELIMITER+matchCountN2);
2590 }
2591 }
2592 errorState|=tswStats.poisonAndWait();
2593
2594 /** For RQCFilter */
2595 lastBothUnmapped=bothUnmapped;
2596 lastBothUnmappedBases=bothUnmappedBases;
2597 lastEitherMapped=eitherMapped;
2598 lastEitherMappedBases=eitherMappedBases;
2599 lastReadsUsed=readsUsed1+readsUsed2;
2600 lastBasesUsed=basesUsed;
2601 lastReadsIn=readsIn1+readsIn2;
2602 lastBasesIn=basesIn1+basesIn2;
2603 lastReadsPassedBloomFilter=readsPassedBloomFilter;
2604 lastBasesPassedBloomFilter=basesPassedBloomFilter;
2605
2606 if(BBSplitter.TRACK_SCAF_STATS){
2607 BBSplitter.printCounts(BBSplitter.SCAF_STATS_FILE, BBSplitter.scafCountTable, true, readsUsed1+readsUsed2, nzoStats, sortStats);
2608 }
2609
2610 if(BBSplitter.TRACK_SET_STATS){
2611 BBSplitter.printCounts(BBSplitter.SET_STATS_FILE, BBSplitter.setCountTable, true, readsUsed1+readsUsed2, nzoStats, sortStats);
2612 }
2613
2614 final long pbf2=(readsUsed2==0 ? readsPassedBloomFilter : readsPassedBloomFilter/2);
2615 final long readSum=truePositiveP1+truePositiveM1+falsePositive1+noHit1+lowQualityReadsDiscarded1+pbf2;
2616 assert(!CALC_STATISTICS || readSum==maxReads) :
2617 "\nThe number of reads out does not add up to the number of reads in.\nThis may indicate that a mapping thread crashed." +
2618 "\nIf you submit a bug report, include the entire console output, not just this error message.\n"+
2619 truePositiveP1+"+"+truePositiveM1+"+"+falsePositive1+"+"+noHit1+"+"+lowQualityReadsDiscarded1+"+"+pbf2+" = "+
2620 readSum+" != "+maxReads;
2621 if(!SKIMMER){
2622 assert(!CALC_STATISTICS || truePositiveP1+truePositiveM1==correctLowHit1+correctMultiHit1+correctUniqueHit1);
2623 }else{
2624 assert(!CALC_STATISTICS || truePositiveP1+truePositiveM1==correctLowHit1+correctUniqueHit1);
2625 }
2626 }
2627
2628 static final void printSettings0(int k, int maxindel, float minratio){
2629 if(MACHINE_OUTPUT){
2630 outstream.println("Genome"+DELIMITER+Data.GENOME_BUILD);
2631 outstream.println("Key_Length"+DELIMITER+k);
2632 outstream.println("Max_Indel"+DELIMITER+maxindel);
2633 outstream.println("Minimum_Score_Ratio"+DELIMITER+minratio);
2634 outstream.println("Mapping_Mode"+DELIMITER+(PERFECTMODE ? "perfect" : SEMIPERFECTMODE ? "semiperfect" : "normal"));
2635 }else{
2636 outstream.println("Genome: \t"+Data.GENOME_BUILD);
2637 outstream.println("Key Length: \t"+k);
2638 outstream.println("Max Indel: \t"+maxindel);
2639 outstream.println("Minimum Score Ratio: \t"+minratio);
2640 outstream.println("Mapping Mode: \t"+(PERFECTMODE ? "perfect" : SEMIPERFECTMODE ? "semiperfect" : "normal"));
2641 }
2642 }
2643
2644
2645 static final int absdif(int a, int b){
2646 return a>b ? a-b : b-a;
2647 }
2648
2649 static void clearStatics(){
2650 maxReads=-1;
2651 // readsUsed=0;
2652 // readsUsed2=0;
2653 // lowQualityReadsDiscarded1=0;
2654 // lowQualityReadsDiscarded2=0;
2655 // lowQualityBasesDiscarded1=0;
2656 // lowQualityBasesDiscarded2=0;
2657
2658 outFile=null;
2659 outFile2=null;
2660 outFileM=null;
2661 outFileM2=null;
2662 outFileU=null;
2663 outFileU2=null;
2664 outFileB=null;
2665 outFileB2=null;
2666 blacklist=null;
2667
2668 errorState=false;
2669
2670 BBSplitter.clearStatics();
2671 }
2672
2673 /* ------------ Non-static fields ----------- */
2674
2675
2676 ConcurrentReadInputStream cris;
2677 ConcurrentReadOutputStream rosA=null, rosM=null, rosU=null, rosB=null;
2678
2679 float fractionGenomeToExclude=-1;
2680 int maxIndel1=-1;
2681 int maxIndel2=-1;
2682 int minApproxHits=-1;
2683 int expectedSites=-1;
2684 int ambigMode=AMBIG_BEST;
2685 // int ambigMode2=AMBIG_BEST;
2686 boolean fast=false;
2687 boolean slow=false;
2688 boolean vslow=false;
2689 float excludeFraction=-1;
2690 boolean verbose=false;
2691 boolean rcompMate=false;
2692 boolean outputSitesOnly=false;
2693 long targetGenomeSize=-1;
2694 int ziplevel=-1;
2695 int build=1;
2696 String reference=null;
2697 int keylen=13;
2698 boolean printSettings=true;
2699 boolean printStats=true;
2700 int idmodulo=1;
2701 float samplerate=1f;
2702 double minid=-1;
2703 long sampleseed=1;
2704 boolean ambiguousRandom=false, ambiguousAll=false;
2705 boolean forceanalyze=false;
2706 // private boolean gunzip=false;
2707 // private boolean gzip=false;
2708 // private boolean pigz=false;
2709 // private boolean unpigz=false;
2710 boolean setxs=false, setintron=false;
2711 String bamscript=null;
2712 String in1=null, in2=null, qfin1=null, qfin2=null;
2713 String qfout=null, qfout2=null, qfoutM=null, qfoutM2=null, qfoutU=null, qfoutU2=null, qfoutB=null, qfoutB2=null;
2714
2715 /** Scores below the (max possible alignment score)*(MINIMUM_ALIGNMENT_SCORE_RATIO) will be discarded.
2716 * Default: 0.4 ~ 0.5 for clean data against raw PacBio data.
2717 * Very sensitive! A value of 0.2 will potentially produce many false positives. */
2718 float MINIMUM_ALIGNMENT_SCORE_RATIO;
2719
2720 float keyDensity;//Normal key density
2721 float maxKeyDensity; //For situations where some of the read is too low quality, this is the max for the rest of the read.
2722 float minKeyDensity;
2723 int maxDesiredKeys; //Don't go above this number of keys except to maintain minKeyDensity.
2724
2725 /** Additional ref bases on each end of site mapping location in alignment window.
2726 * If there are no insertions or deletions, 0 is fine. */
2727 int SLOW_ALIGN_PADDING;
2728 int SLOW_RESCUE_PADDING;
2729 int TIP_SEARCH_DIST;
2730
2731 /** Class name of MSA to use */
2732 String MSA_TYPE;
2733 int MAX_SITESCORES_TO_PRINT;
2734 boolean PRINT_SECONDARY_ALIGNMENTS;
2735
2736
2737 boolean makeBloomFilter=false;
2738 int bloomFilterHashes=2;
2739 int bloomFilterMinHits=3;
2740 int bloomFilterK=31;
2741 BloomFilter bloomFilter;
2742 boolean bloomSerial=true;
2743
2744 /* ------------ Coverage ----------- */
2745
2746 CoveragePileup pileup;
2747 String coverageStats=null, coverageBinned=null, coverageBase=null, rangeCov=null, coverageHist=null, coverageRPKM=null, normcov=null, normcovOverall=null;
2748 /** Force coverage calculation even if there is no output file */
2749 boolean calcCov=false;
2750 int coverageMinScaf=0;
2751 boolean coveragePhysical=false;
2752 boolean cov32bit=false;
2753 boolean covBitset=false;
2754 boolean covSetbs=false;
2755 boolean covArrays=true;
2756 boolean covNzo=false;
2757 boolean scafNzo=true;
2758 boolean sortStats=true;
2759 boolean covTwocolumn=false;
2760 boolean covKsb=true;
2761 boolean covStranded=false;
2762 boolean covStartOnly=false;
2763 boolean covStopOnly=false;
2764 int covBinSize=1000;
2765 int covK=0;
2766
2767
2768 /* ------------ Static fields ----------- */
2769
2770 public static long lastBothUnmapped=0;
2771 public static long lastBothUnmappedBases=0;
2772
2773 public static long lastEitherMapped=0;
2774 public static long lastEitherMappedBases=0;
2775
2776 public static long lastReadsUsed=0;
2777 public static long lastBasesUsed=0;
2778
2779 public static long lastReadsIn=0;
2780 public static long lastBasesIn=0;
2781
2782 public static long lastReadsPassedBloomFilter=0;
2783 public static long lastBasesPassedBloomFilter=0;
2784
2785 static final int AMBIG_BEST=0;
2786 static final int AMBIG_TOSS=1;
2787 static final int AMBIG_RANDOM=2;
2788 static final int AMBIG_ALL=3;
2789 static int MIN_MAPQ=0;
2790 static int MIN_MAPQ_UNPAIRED=0;
2791
2792 static int CORRECT_THRESH=0; //Threshold for calculating true positives on synthetic data, or something.
2793
2794 static int synthReadlen=150;
2795
2796 static int maxInsLen=30; //Default 40
2797 static int maxSubLen=30; //Default 40
2798 static int maxDelLen=40; //Default 8000
2799
2800 static byte minQuality=3;
2801 static byte midQuality=23;
2802 static byte maxQuality=35;
2803
2804 static int maxSnps=4;//4;
2805 static int maxInss=3;//2;
2806 static int maxDels=3;
2807 static int maxSubs=3;//2;
2808
2809 static float baseSnpRate=0.50f;
2810 static float baseInsRate=0.30f;
2811 static float baseDelRate=0.30f;
2812 static float baseSubRate=0.30f;//0.3f;
2813 static float PERFECT_READ_RATIO=0.0f;//0.2f;//0.8f
2814
2815 //Extra work for rare cases in human only.
2816 static boolean SAVE_AMBIGUOUS_XY=false;
2817
2818
2819 static boolean TRIM_LIST=true; //Increases speed many times; reduces accuracy a bit
2820
2821 static boolean PAIRED_RANDOM_READS=false;
2822 static boolean REQUIRE_CORRECT_STRANDS_PAIRS=true;
2823 static boolean SAME_STRAND_PAIRS=false;
2824 static boolean KILL_BAD_PAIRS=false;
2825
2826 static boolean INDEX_LOADED=false;
2827 static final boolean SLOW_ALIGN=true; //Do a more accurate scoring pass with MSA
2828 static boolean MAKE_MATCH_STRING=SLOW_ALIGN;
2829
2830 /** Rescue paired reads by searching near mate */
2831 static boolean RESCUE=true;
2832
2833 /** Generally should be set to false unless SLOW_ALIGN==true */
2834 static boolean REMOVE_DUPLICATE_BEST_ALIGNMENTS=false;
2835
2836 /** Forbid alignments with indels longer than MAX_INDEL */
2837 static boolean STRICT_MAX_INDEL=false;
2838 /** Don't allow reads to map to their origin location in the reference. Useful for self-correcting reads. */
2839 static boolean FORBID_SELF_MAPPING=false;
2840 /** Only allow perfect and semiperfect mappings */
2841 static boolean SEMIPERFECTMODE=false;
2842 /** Only allow perfect mappings */
2843 static boolean PERFECTMODE=false;
2844 /** Only allow sites with at least this many contiguous matches */
2845 static int KFILTER=-1;
2846 /** Only allow sites with identity of at least this */
2847 static float MIN_IDFILTER=0f;
2848
2849 /** Rename reads to indicate their mapped insert size */
2850 static boolean RenameByInsert=false;
2851
2852 /** Quality-trim left side of read before mapping */
2853 static boolean qtrimLeft=false;
2854 /** Quality-trim right side of read before mapping */
2855 static boolean qtrimRight=false;
2856 /** Restore read to untrimmed state after mapping (and destroy match string) */
2857 static boolean untrim=false;
2858 /** Trim bases with quality less than or equal to this value */
2859 static float TRIM_QUALITY=6;
2860 /** Don't trim reads to be shorter than this */
2861 static int minTrimLength=60;
2862 /** Produce local alignments instead of global alignments */
2863 static boolean LOCAL_ALIGN=false;
2864
2865 public static int minChrom=1;
2866 public static int maxChrom=Integer.MAX_VALUE;
2867
2868 static long maxReads=-1;
2869
2870 static boolean CALC_STATISTICS=true;
2871
2872 static boolean QUICK_MATCH_STRINGS=false;
2873 static boolean OUTPUT_READS=false;
2874 static boolean OUTPUT_MAPPED_ONLY=false;
2875 static boolean DONT_OUTPUT_BLACKLISTED_READS=false;
2876
2877 static boolean ORDERED=false;
2878 static boolean DOUBLE_PRINT_ERROR_RATE=false;
2879 static boolean PRINT_UNMAPPED_COUNT=false;
2880
2881 static String outFile=null;
2882 static String outFile2=null;
2883 static String outFileM=null;
2884 static String outFileM2=null;
2885 static String outFileU=null;
2886 static String outFileU2=null;
2887 static String outFileB=null;
2888 static String outFileB2=null;
2889 static ArrayList<String> blacklist=null;
2890 static ArrayList<String> splitterOutputs=null;
2891
2892 static boolean useRandomReads=false;
2893 static int sequentialOverlap=5;
2894 static boolean sequentialStrandAlt=false;
2895
2896 static boolean overwrite=true;
2897 static boolean append=false;
2898 static boolean SYNTHETIC=false;
2899 static boolean ERROR_ON_NO_OUTPUT=false;
2900 static boolean MACHINE_OUTPUT=false;
2901 static boolean USE_MODULO=false;
2902 static String statsOutputFile="stderr.txt";
2903 final static String DELIMITER="=";
2904
2905 static PrintStream outstream=System.err;
2906 static boolean SYSIN=false;
2907 static int verbose_stats=0;
2908 static boolean waitForMemoryClear=false;
2909 static int DEFAULT_OUTPUT_FORMAT=FileFormat.SAM;
2910
2911 public static boolean errorState=false;
2912
2913 }