Debian Codegraph @

current/jgi/BBMerge.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.BitSet;
8
9 import align2.QualityTools;
10 import assemble.Tadpole;
11 import bloom.BloomFilter;
12 import bloom.BloomFilterCorrector;
13 import bloom.KmerCountAbstract;
14 import cardinality.CardinalityTracker;
15 import dna.AminoAcid;
16 import dna.Data;
17 import fileIO.FileFormat;
18 import fileIO.ReadWrite;
19 import kmer.KmerTableSet;
20 import ml.CellNet;
21 import ml.CellNetParser;
22 import shared.KillSwitch;
23 import shared.Parse;
24 import shared.Parser;
25 import shared.PreParser;
26 import shared.Shared;
27 import shared.Timer;
28 import shared.Tools;
29 import shared.TrimRead;
30 import stream.ConcurrentReadInputStream;
31 import stream.ConcurrentReadOutputStream;
32 import stream.CustomHeader;
33 import stream.FASTQ;
34 import stream.Read;
35 import stream.ReadStreamWriter;
36 import structures.ByteBuilder;
37 import structures.FloatList;
38 import structures.IntList;
39 import structures.ListNum;
40 import structures.LongList;
41 import structures.Quantizer;
42 import tracker.AdapterTracker;
43 import tracker.ReadStats;
44 import ukmer.Kmer;
45
46 /**
47 * @author Brian Bushnell
48 * @date Aug 14, 2012
49 *
50 */
51 public class BBMerge {
52
53 public static void main(String[] args){
54 // boolean old=Shared.USE_JNI;
55 // Shared.USE_JNI=false; //TODO: This is for RQCFilter. Can be removed.
56
57 MAKE_VECTOR=BBMergeOverlapper.MAKE_VECTOR=true;//This doesn't work in a static context, so...
58 BBMerge x=new BBMerge(args);
59 x.process();
60 MAKE_VECTOR=BBMergeOverlapper.MAKE_VECTOR=false;
61 // Shared.USE_JNI=old;
62 Read.VALIDATE_IN_CONSTRUCTOR=true;
63
64 //Close the print stream if it was redirected
65 Shared.closeStream(outstream);
66 }
67
68 private static String[] preparse(String[] args){
69 if(args==null){return new String[0];}
70 int nulls=0;
71 final int XSTRICT=1, USTRICT=2, VSTRICT=3, STRICT=4, NORMAL=5, LOOSE=6, VLOOSE=7, ULOOSE=8, XLOOSE=9, FAST=10;
72 int mode=NORMAL;
73 for(int i=0; i<args.length; i++){
74 String arg=args[i];
75 String[] split=arg.split("=");
76 String a=split[0].toLowerCase();
77 String b=split.length>1 ? split[1] : null;
78
79 if(a.equals("jni") || a.equals("usejni")){
80 Shared.USE_JNI=Parse.parseBoolean(b);
81 }else if(a.equals("showfullargs") || a.equalsIgnoreCase("showFullArgs")){
82 showFullArgs=Parse.parseBoolean(b);
83 args[i]=null;
84 nulls++;
85 }else if(a.equals("vstrict") || a.equals("verystrict")){
86 boolean x=Parse.parseBoolean(b);
87 if(x){mode=VSTRICT;}else if(mode==VSTRICT){mode=NORMAL;}
88 args[i]=null;
89 nulls++;
90 }else if(a.equals("ustrict") || a.equals("ultrastrict")){
91 boolean x=Parse.parseBoolean(b);
92 if(x){mode=USTRICT;}else if(mode==USTRICT){mode=NORMAL;}
93 args[i]=null;
94 nulls++;
95 }else if(a.equals("xstrict") || a.equals("hstrict") || a.equals("hyperstrict") || a.equals("maxstrict")){
96 boolean x=Parse.parseBoolean(b);
97 if(x){mode=XSTRICT;}else if(mode==XSTRICT){mode=NORMAL;}
98 args[i]=null;
99 nulls++;
100 }else if(a.equals("strict")){
101 boolean x=Parse.parseBoolean(b);
102 if(x){mode=STRICT;}else if(mode==STRICT){mode=NORMAL;}
103 args[i]=null;
104 nulls++;
105 }else if(a.equals("loose")){
106 boolean x=Parse.parseBoolean(b);
107 if(x){mode=LOOSE;}else if(mode==LOOSE){mode=NORMAL;}
108 args[i]=null;
109 nulls++;
110 }else if(a.equals("vloose") || a.equals("veryloose")){
111 boolean x=Parse.parseBoolean(b);
112 if(x){mode=VLOOSE;}else if(mode==VLOOSE){mode=NORMAL;}
113 args[i]=null;
114 nulls++;
115 }else if(a.equals("uloose") || a.equals("ultraloose")){
116 boolean x=Parse.parseBoolean(b);
117 if(x){mode=ULOOSE;}else if(mode==ULOOSE){mode=NORMAL;}
118 args[i]=null;
119 nulls++;
120 }else if(a.equals("xloose") || a.equals("hloose") || a.equals("hyperloose") || a.equals("maxloose")){
121 boolean x=Parse.parseBoolean(b);
122 if(x){mode=XLOOSE;}else if(mode==XLOOSE){mode=NORMAL;}
123 args[i]=null;
124 nulls++;
125 }else if(a.equals("fast")){
126 boolean x=Parse.parseBoolean(b);
127 if(x){mode=FAST;}else if(mode==FAST){mode=NORMAL;}
128 args[i]=null;
129 nulls++;
130 }else if(a.equals("default")){
131 boolean x=Parse.parseBoolean(b);
132 if(x){mode=NORMAL;}
133 args[i]=null;
134 nulls++;
135 }
136 }
137
138 if(mode==FAST){fast=true;}
139 else if(mode==XSTRICT){xstrict=true;}
140 else if(mode==USTRICT){ustrict=true;}
141 else if(mode==VSTRICT){vstrict=true;}
142 else if(mode==STRICT){strict=true;}
143 else if(mode==LOOSE){loose=true;}
144 else if(mode==VLOOSE){vloose=true;}
145 else if(mode==ULOOSE){uloose=true;}
146 else if(mode==XLOOSE){xloose=true;}
147
148 if(nulls==0){return args;}
149 ArrayList<String> args2=new ArrayList<String>(args.length-nulls+5);
150 if(strict || vstrict || ustrict || xstrict){
151 strict=true;
152 loose=vloose=uloose=xloose=false;
153
154 args2.add("maxbad=4");
155 args2.add("margin=3");
156 args2.add("minqo=8");
157 args2.add("qualiters=2");
158
159 if(xstrict){
160 args2.add("ratiomode=t");
161 args2.add("flatmode=t");
162 args2.add("requireratiomatch=t");
163
164 args2.add("minentropy=56");
165 args2.add("minoverlap=14");
166 args2.add("minoverlap0=3");
167
168 args2.add("maxratio=0.055");
169 args2.add("ratiomargin=12");
170 args2.add("ratiooffset=0.65");
171 args2.add("ratiominoverlapreduction=4");
172 args2.add("efilter=2");
173 args2.add("pfilter=0.25");
174 args2.add("minsecondratio=0.24");
175 args2.add("minapproxoverlap=18");
176 }else if(ustrict){
177 args2.add("ratiomode=t");
178 args2.add("flatmode=t");
179 args2.add("requireratiomatch=t");
180
181 args2.add("minentropy=56");
182 args2.add("minoverlap=14");
183 args2.add("minoverlap0=3");
184
185 args2.add("maxratio=0.045");
186 args2.add("ratiomargin=12");
187 args2.add("ratiooffset=0.5");
188 args2.add("ratiominoverlapreduction=4");
189 args2.add("efilter=2");
190 args2.add("pfilter=0.03");
191 args2.add("minsecondratio=0.20");
192 args2.add("minapproxoverlap=20");
193 }else if(vstrict){
194 args2.add("ratiomode=t");
195 args2.add("flatmode=f");
196
197 args2.add("minentropy=52");
198 args2.add("minoverlap=12");
199 args2.add("minoverlap0=4");
200
201 args2.add("maxratio=0.05");
202 args2.add("ratiomargin=12");
203 args2.add("ratiooffset=0.5");
204 args2.add("ratiominoverlapreduction=4");
205 args2.add("efilter=2");
206 args2.add("pfilter=0.008");
207 args2.add("minsecondratio=0.16");
208 args2.add("minapproxoverlap=22");
209 }else{
210 args2.add("ratiomode=t");
211 args2.add("flatmode=f");
212
213 args2.add("minentropy=42");
214 args2.add("minoverlap0=7");
215 args2.add("minoverlap=11");
216
217 args2.add("maxratio=0.075");
218 args2.add("ratiomargin=7.5");
219 args2.add("ratiooffset=0.55");
220 args2.add("ratiominoverlapreduction=4");
221 args2.add("efilter=4");
222 args2.add("pfilter=0.0008");
223 args2.add("minsecondratio=0.12");
224 args2.add("minapproxoverlap=24");
225 }
226 }else if(loose || vloose || uloose || xloose){
227 loose=true;
228 strict=vstrict=ustrict=xstrict=false;
229 args2.add("minoverlap=8");
230 args2.add("minoverlap0=9");
231 args2.add("qualiters=4");
232 args2.add("mismatches=3");
233 args2.add("margin=2");
234
235 args2.add("ratiooffset=0.4");
236 args2.add("minsecondratio=0.08");
237
238 if(xloose){
239 args2.add("owq=t");
240 args2.add("ouq=t");
241 args2.add("minentropy=22");
242 args2.add("minoverlap=8");
243 args2.add("minoverlap0=7");
244 args2.add("maxratio=0.2");
245 args2.add("mismatches=3");
246 args2.add("ratiomargin=2");
247 args2.add("flatmode=t");
248 args2.add("pfilter=0.0000001");
249 args2.add("efilter=8");
250 args2.add("margin=2");
251 args2.add("ratiominoverlapreduction=2");
252 args2.add("minapproxoverlap=38");
253 }else if(vloose || uloose){
254 args2.add("owq=t");
255 args2.add("ouq=t");
256 if(uloose){
257 // args2.add("maxratio=0.14");
258 // args2.add("ratiomargin=2");
259 // args2.add("flatmode=t");
260 // args2.add("pfilter=0.0000001");
261
262
263 args2.add("minoverlap=8");
264 args2.add("minoverlap0=7");
265 args2.add("mismatches=3");
266 args2.add("margin=2");
267
268 args2.add("ratiominoverlapreduction=2");
269 args2.add("efilter=8");
270 args2.add("maxratio=0.16");
271 args2.add("ratiomargin=2.2");
272 args2.add("pfilter=0.0000002");
273 args2.add("minentropy=24");
274 args2.add("minapproxoverlap=34");
275 }else{
276 args2.add("ratiominoverlapreduction=3");
277 args2.add("maxratio=0.12");
278 args2.add("ratiomargin=3");
279 args2.add("pfilter=0.000004");
280 args2.add("minentropy=28");
281 args2.add("efilter=7.5");
282 args2.add("ratiooffset=0.45");
283 args2.add("minapproxoverlap=32");
284 }
285 }else{
286 args2.add("maxratio=0.11");
287 args2.add("ratiomargin=4.7");
288 args2.add("ratiominoverlapreduction=2");
289 args2.add("pfilter=0.00002");
290 args2.add("efilter=8");
291 args2.add("minentropy=30");
292 args2.add("minapproxoverlap=30");
293 }
294 }else if(fast){
295 args2.add("maxratio=0.08");
296 args2.add("ratiomargin=2.5");
297 args2.add("ratiominoverlapreduction=3");
298 args2.add("pfilter=0.0002");
299 args2.add("efilter=8");
300 args2.add("minentropy=39");
301 args2.add("mininsert0=50");
302 args2.add("minsecondratio=0.08");
303 }
304
305 for(String s : args){
306 if(s!=null){args2.add(s);}
307 }
308 return args2.toArray(new String[args2.size()]);
309 }
310
311 public BBMerge(String[] args){
312
313 {//Preparse block for help, config files, and outstream
314 PreParser pp=new PreParser(args, getClass(), true);
315 args=pp.args;
316 outstream=pp.outstream;
317 }
318
319 {
320 String[] args0=args;
321 args=preparse(args);
322
323 if(args0!=args && showFullArgs){
324 outstream.println("Revised arguments: "+Arrays.toString(args)+"\n");
325 }
326 }
327
328 Timer ttotal=new Timer();
329 ttotal.start();
330
331 in1=(args[0].indexOf('=')>0 ? null : args[0]);
332 in2=(in1!=null && args.length>1 && args[1].indexOf('=')<0 ? args[1] : null);
333 if(in2!=null && "null".equalsIgnoreCase(in2)){in2=null;}
334
335 {
336 if(in1!=null && !in1.contains(",") && !in1.startsWith("stdin.") && !in1.equals("stdin")){
337 File f=new File(in1);
338 if(!f.exists() || !f.isFile()){
339 in1=null;
340 // throw new RuntimeException(in1+" does not exist.");
341 }
342 }
343 if(in2!=null && !in2.contains(",")){
344 File f=new File(in2);
345 if(!f.exists() || !f.isFile()){
346 in2=null;
347 // throw new RuntimeException(in2+" does not exist.");
348 }else if(in1.equalsIgnoreCase(in2)){
349 throw new RuntimeException("Both input files are the same.");
350 }
351 }
352 }
353
354 ReadWrite.setZipThreads(Tools.max(Shared.threads()>1 ? 2 : 1, Shared.threads()>20 ? Shared.threads()/2 : Shared.threads()));
355 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
356 Shared.setBufferLen(Tools.max(Shared.bufferLen(), 400));
357 boolean setMix=false;
358
359 boolean mm0set=false;
360
361 Parser parser=new Parser();
362 parser.trimq2=trimq;
363 parser.minAvgQuality=minAvgQuality;
364 parser.minReadLength=minReadLength;
365 parser.maxReadLength=maxReadLength;
366
367 for(int i=0; i<args.length; i++){
368 String arg=args[i];
369 String[] split=arg.split("=");
370 String a=split[0].toLowerCase();
371 String b=split.length>1 ? split[1] : null;
372
373 if(a.equals("parsecustom")){
374 parseCustom=Parse.parseBoolean(b);
375 // }else if(a.equals("tagcustom")){
376 // TAG_CUSTOM=Parse.parseBoolean(b);
377 }else if(Parser.parseZip(arg, a, b)){
378 //do nothing
379 }else if(Parser.parseCommonStatic(arg, a, b)){
380 //do nothing
381 }else if(Parser.parseQuality(arg, a, b)){
382 //do nothing
383 }else if(Parser.parseQualityAdjust(arg, a, b)){
384 //do nothing
385 }else if(parser.parseInterleaved(arg, a, b)){
386 //do nothing
387 }else if(parser.parseTrim(arg, a, b)){
388 //do nothing
389 }else if(parser.parseCardinality(arg, a, b)){
390 //do nothing
391 }else if(a.equals("in") || a.equals("in1")){
392 in1=b;
393 }else if(a.equals("in2")){
394 in2=b;
395 }else if(a.equals("extra")){
396 if(b!=null){
397 for(String s : b.split(",")){
398 extra.add(s);
399 }
400 }
401 }else if(a.equals("useratio") || a.equals("ratio") || a.equals("ratiomode")){
402 useRatioMode=Parse.parseBoolean(b);
403 }else if(a.equals("useflatmode") || a.equals("flatmode") || a.equals("usenormalmode") || a.equals("normalmode")){
404 useFlatMode=Parse.parseBoolean(b);
405 }else if(a.equals("requireratiomatch") || a.equals("rrm")){
406 requireRatioMatch=Parse.parseBoolean(b);
407 }else if(a.equals("makevector") || a.equals("nn")){
408 MAKE_VECTOR=BBMergeOverlapper.MAKE_VECTOR=Parse.parseBoolean(b);
409 }else if(a.equals("net")){
410 netFile=b;
411 }else if(a.equals("netcutoff") || a.equals("cutoff")){
412 netCutoff=Float.parseFloat(b);
413 assert(netCutoff>=0 && netCutoff<=1) : netCutoff;
414 setCutoff=true;
415 }else if(a.equals("maxratio")){
416 MAX_RATIO=Float.parseFloat(b);
417 // useRatioMode=true;
418 }else if(a.equals("maxmismatchesr") || a.equals("maxmismatches")){
419 MAX_MISMATCHES_R=Integer.parseInt(b);
420 // useRatioMode=true;
421 }else if(a.equals("ratiomargin")){
422 RATIO_MARGIN=Float.parseFloat(b);
423 // useRatioMode=true;
424 }else if(a.equals("ratiooffset")){
425 RATIO_OFFSET=Float.parseFloat(b);
426 // useRatioMode=true;
427 }else if(a.equals("ratiominoverlapreduction")){
428 MIN_OVERLAPPING_BASES_RATIO_REDUCTION=Integer.parseInt(b);
429 // useRatioMode=true;
430 }else if(a.equals("minentropy") || a.equals("entropy")){
431 if(b!=null && Tools.isDigit(b.charAt(0))){
432 minEntropyScore=Integer.parseInt(b);
433 }else{
434 useEntropy=Parse.parseBoolean(b);
435 }
436 }else if(a.equals("minoverlappingbases") || a.equals("minoverlapbases") || a.equals("minoverlap")){
437 MIN_OVERLAPPING_BASES=Integer.parseInt(b);
438 }else if(a.equals("minoverlappingbases0") || a.equals("minoverlapbases0") || a.equals("minoverlap0")){
439 MIN_OVERLAPPING_BASES_0=Integer.parseInt(b);
440 }else if(a.equals("minqo") || a.equals("minq")){
441 MIN_QUALITY=(byte)Integer.parseInt(b);
442 }else if(a.equals("maxq")){
443 Read.MAX_MERGE_QUALITY=(byte)Integer.parseInt(b);
444 }else if(a.equals("qualiters")){
445 QUAL_ITERS=Tools.max(1, Integer.parseInt(b));
446 }else if(a.equals("maxbadbases") || a.equals("maxbad") || a.equals("mismatches")){
447 MAX_MISMATCHES=Integer.parseInt(b);
448 }else if(a.equals("maxbadbases0") || a.equals("maxbad0") || a.equals("mismatches0")){
449 MAX_MISMATCHES0=Integer.parseInt(b);
450 mm0set=true;
451 }else if(a.equals("margin")){
452 MISMATCH_MARGIN=Integer.parseInt(b);
453 }else if(a.equals("usemapping")){
454 USE_MAPPING=Parse.parseBoolean(b);
455 }else if(a.equals("bin")){
456 bin=Integer.parseInt(b);
457 }else if(a.equals("threads") || a.equals("t")){
458 THREADS=Shared.setThreads(b);
459 }else if(a.equals("reads") || a.startsWith("maxreads")){
460 maxReads=Parse.parseKMG(b);
461 }else if(a.equals("outgood") || a.equals("outmerged") || a.equals("outm") || a.equals("out")){
462 out1=(b==null || b.equals("null") ? null : b);
463 }else if(a.equals("outgood1") || a.equals("outmerged1") || a.equals("outm1") || a.equals("out1")){
464 out1=(b==null || b.equals("null") ? null : b);
465 }else if(a.equals("outgood2") || a.equals("outmerged2") || a.equals("outm2") || a.equals("out2")){
466 out2=(b==null || b.equals("null") ? null : b);
467 }else if(a.equals("outb") || a.equals("outu") || a.equals("outunmerged") || a.equals("outbad")){
468 outb1=(b==null || b.equals("null") ? null : b);
469 }else if(a.equals("outb1") || a.equals("outu1") || a.equals("outunmerged1") || a.equals("outbad1")){
470 outb1=(b==null || b.equals("null") ? null : b);
471 }else if(a.equals("outb2") || a.equals("outu2") || a.equals("outunmerged2") || a.equals("outbad2")){
472 outb2=(b==null || b.equals("null") ? null : b);
473 }else if(a.startsWith("outinsert") || a.startsWith("outi") || a.startsWith("outlength")){
474 outinsert=(b==null || b.equals("null") ? null : b);
475 }else if(a.startsWith("outhist") || a.equals("hist") || a.equals("histogram") || a.equals("ihist")){
476 ihist=(b==null || b.equals("null") ? null : b);
477 }else if(a.equals("outa") || a.equals("outadapter")){
478 outAdapter=b;
479 findAdapterSequence=(outAdapter!=null);
480 }else if(a.equals("ignorephix") || a.equals("ignorephixadapters")){
481 ignorePhixAdapters=AdapterTracker.ignorePhixAdapters=Parse.parseBoolean(b);
482 }else if(a.equals("outc") || a.equals("outcardinality")){
483 outCardinality=b;
484 // }else if(a.equals("outputfailed")){
485 // OUTPUT_FAILED=Parse.parseBoolean(b);outCardinality
486 }else if(a.equals("trimpolya")){
487 trimPolyA=AdapterTracker.trimPolyAorG=Parse.parseBoolean(b);
488 }else if(a.equals("mix")){
489 MIX_BAD_AND_GOOD=Parse.parseBoolean(b);
490 setMix=true;
491 }else if(a.equals("ooi") || a.equals("onlyoutputincorrect")){
492 ONLY_OUTPUT_INCORRECT=Parse.parseBoolean(b);
493 }else if(a.equals("ofp") || a.equals("outputfalsepositive")){
494 OUTPUT_FALSE_POSITIVE=Parse.parseBoolean(b);
495 }else if(a.equals("oofp") || a.equals("onlyoutputfalsepositive")){
496 ONLY_OUTPUT_FALSE_POSITIVE=Parse.parseBoolean(b);
497 }else if(a.equals("ofn") || a.equals("outputfalsenegative")){
498 OUTPUT_FALSE_NEGATIVE=Parse.parseBoolean(b);
499 }else if(a.equals("otp") || a.equals("outputtruepositive")){
500 OUTPUT_TRUE_POSITIVE=Parse.parseBoolean(b);
501 }else if(a.equals("otn") || a.equals("outputtruenegative")){
502 OUTPUT_TRUE_NEGATIVE=Parse.parseBoolean(b);
503 }else if(a.equals("train") || a.equals("training")){
504 TRAINING=Parse.parseBoolean(b);
505 }else if(a.equals("nzo") || a.equals("nonzeroonly")){
506 NONZERO_ONLY=Parse.parseBoolean(b);
507 }else if(a.equals("exemptshortoverlaps") || a.equals("exemptshort") || a.equals("ignoreshort")){
508 EXEMPT_SHORT_OVERLAPS_FROM_STATS=Parse.parseBoolean(b);
509 }else if(a.equals("showhiststats")){
510 showHistStats=Parse.parseBoolean(b);
511 }else if(a.equals("verbose")){
512 assert(false) : "verbose flag is static final; recompile to change it.";
513 // verbose=Parse.parseBoolean(b);
514 }else if(a.equals("trimnonoverlapping") || a.equals("tno")){
515 trimNonOverlapping=Parse.parseBoolean(b);
516 }else if(a.equals("join") || a.equals("merge")){
517 join=Parse.parseBoolean(b);
518 if(join){ecco=false;}
519 }else if(a.equals("ecco") || a.equals("ecc") || a.equals("errorcorrect")){
520 ecco=Parse.parseBoolean(b);
521 if(ecco){join=false;}
522 }else if(a.equals("tbo") || a.equals("trimbyoverlap")){
523 trimByOverlap=Parse.parseBoolean(b);
524 }else if(a.equals("useoverlap") || a.equals("usebases") || a.equals("matebyoverlap") || a.equals("matebybases")){
525 MATE_BY_OVERLAP=Parse.parseBoolean(b);
526 }
527 // else if(a.startsWith("skipmated")){
528 // SKIP_MATED_READS=Parse.parseBoolean(b);
529 // }
530 else if(a.equals("lowercase")){
531 lowercaseAdapters=Parse.parseBoolean(b);
532 }else if(a.equals("append") || a.equals("app")){
533 append=ReadStats.append=Parse.parseBoolean(b);
534 }else if(a.equals("overwrite") || a.equals("ow")){
535 overwrite=Parse.parseBoolean(b);
536 }else if(a.equals("trimonfailure") || a.equals("tof")){
537 if(b!=null && Tools.isDigit(b.charAt(0))){
538 TRIM_ON_OVERLAP_FAILURE=Integer.parseInt(b);
539 }else{
540 TRIM_ON_OVERLAP_FAILURE=(Parse.parseBoolean(b) ? 1 : 0);
541 }
542 }else if(a.equals("overlapusingquality") || a.equals("ouq")){
543 overlapUsingQuality=Parse.parseBoolean(b);
544 }else if(a.equals("overlapwithoutquality") || a.equals("owoq") || a.equals("owuq") || a.equals("owq")){
545 overlapWithoutQuality=Parse.parseBoolean(b);
546 }else if(a.equals("maxexpectederrors") || a.equals("mee") || a.equals("meefilter")){
547 maxExpectedErrors=Float.parseFloat(b);
548 }else if(a.equals("mi") || a.equals("minins") || a.equals("mininsert")){
549 minInsert=Integer.parseInt(b);
550 }else if(a.equals("mi0") || a.equals("mininsert0")){
551 minInsert0=Integer.parseInt(b);
552 }else if(a.equals("minprob")){
553 minProb=Float.parseFloat(b);
554 assert(minProb<1) : "minprob must be less than 1. At 1, even kmers with 100% probablity of being error-free will be discarded.";
555 }else if(a.equals("prealloc")){
556 prealloc=Parse.parseBoolean(b);
557 }else if(a.equals("prefilter")){
558 if(b==null){prefilter=2;}
559 else if(Character.isLetter(b.charAt(0))){prefilter=Parse.parseBoolean(b) ? 2 : 0;}
560 else{prefilter=Integer.parseInt(b);}
561 }else if(a.equalsIgnoreCase("filterMemoryOverride") || a.equalsIgnoreCase("filterMemory") ||
562 a.equalsIgnoreCase("prefilterMemory") || a.equalsIgnoreCase("filtermem")){
563 filterMemoryOverride=Parse.parseKMG(b);
564 }else if(a.equals("k")){
565 kmerLength=Integer.parseInt(b);
566 }else if(a.equals("tail")){
567 eccTail=Parse.parseBoolean(b);
568 }else if(a.equals("pincer")){
569 eccPincer=Parse.parseBoolean(b);
570 }else if(a.equals("reassemble")){
571 eccReassemble=Parse.parseBoolean(b);
572 }
573
574 else if(a.equals("efilter")){
575 if(b==null || Character.isLetter(b.charAt(0))){
576 boolean x=Parse.parseBoolean(b);
577 if(!x){efilterRatio=-1;}
578 }else{
579 efilterRatio=Float.parseFloat(b);
580 }
581 useEfilter=efilterRatio>=0;
582 }else if(a.equals("pfilter")){
583 if(b==null || Character.isLetter(b.charAt(0))){
584 boolean x=Parse.parseBoolean(b);
585 if(!x){pfilterRatio=0;}
586 }else{
587 pfilterRatio=Float.parseFloat(b);
588 }
589 }else if(a.equals("efilteroffset")){
590 efilterOffset=Float.parseFloat(b);
591 }else if(a.equals("kfilter")){
592 if(b!=null && Tools.isDigit(b.charAt(0))){
593 filterCutoff=Integer.parseInt(b);
594 useKFilter=filterCutoff>0;
595 }else{
596 useKFilter=Parse.parseBoolean(b);
597 }
598 }else if(a.equals("usequality")){
599 useQuality=Parse.parseBoolean(b);
600 }else if(a.equals("ignorequality")){
601 useQuality=!Parse.parseBoolean(b);
602 }else if(a.equals("ordered")){
603 ordered=Parse.parseBoolean(b);
604 }else if(a.equals("samplerate")){
605 samplerate=Float.parseFloat(b);
606 assert(samplerate<=1f && samplerate>=0f) : "samplerate="+samplerate+"; should be between 0 and 1";
607 }else if(a.equals("sampleseed")){
608 sampleseed=Long.parseLong(b);
609 }else if(a.equals("recalibrate") || a.equals("recalibratequality") || a.equals("recal")){
610 recalibrateQuality=Parse.parseBoolean(b);
611 }else if(a.equals("recalpairnum") || a.equals("recalibratepairnum")){
612 CalcTrueQuality.USE_PAIRNUM=Parse.parseBoolean(b);
613 }else if(a.equals("path")){
614 Data.setPath(b);
615 }else if(a.equals("iupacton") || a.equals("itn")){
616 iupacToN=Parse.parseBoolean(b);
617 }else if(a.equals("minsecondratio")){
618 MIN_SECOND_RATIO=Float.parseFloat(b);
619 }
620
621 //Adapter parameters
622
623 else if(a.equals("adapter") || a.equals("adapters")){
624 adapterList1=adapterList2=getAdapterList(b);
625 }else if(a.equals("adapter1") || a.equals("adapters1")){
626 adapterList1=adapterList2=getAdapterList(b);
627 }else if(a.equals("adapter2") || a.equals("adapters2")){
628 adapterList1=adapterList2=getAdapterList(b);
629 }
630
631 //Extension parameters
632
633 else if(a.equals("extendright") || a.equals("er") || a.equals("extend") || a.equals("extendright1") || a.equals("er1") || a.equals("extend1")){
634 extendRight1=Parse.parseIntKMG(b);
635 }else if(a.equals("extendright2") || a.equals("er2") || a.equals("extend2")){
636 extendRight2=Parse.parseIntKMG(b);
637 }else if(a.equals("extenditerations") || a.equals("iterations") || a.equals("ei") || a.equals("iters")){
638 extendIterations=Tools.max(1, (int)Parse.parseKMG(b));
639 }else if(a.equals("ecctadpole") || a.equals("ecct")){
640 eccTadpole=Parse.parseBoolean(b);
641 }else if(a.equals("eccbloom") || a.equals("eccb") || a.equals("ecccms")){
642 eccBloom=Parse.parseBoolean(b);
643 }else if(a.equals("exactkmercounts")){
644 forceExactKmerCounts=Parse.parseBoolean(b);
645 }else if(a.equals("bits") || a.equals("bloombits") || a.equals("cmsbits")){
646 bloomBits=Integer.parseInt(b);
647 }else if(a.equals("testmerge") || a.equals("testjunctions")){
648 testMerge=Parse.parseBoolean(b);
649 }else if(a.equals("testmergewidth")){
650 testMergeWidth=Integer.parseInt(b);
651 }else if(a.equals("testmergethresh")){
652 testMergeThresh=Integer.parseInt(b);
653 }else if(a.equals("testmergemult")){
654 testMergeMult=Parse.parseKMG(b);
655 }else if(a.equals("hashes") || a.equals("bloomhashes")){
656 bloomHashes=Integer.parseInt(b);
657 }else if(a.equals("shave") || a.equals("removedeadends")){
658 shave=Parse.parseBoolean(b);
659 }else if(a.equals("rinse") || a.equals("shampoo") || a.equals("removebubbles")){
660 rinse=Parse.parseBoolean(b);
661 }else if(a.equals("branchlower") || a.equals("branchlowerconst")){
662 branchLowerConst=Parse.parseIntKMG(b);
663 }else if(a.equals("branchmult2")){
664 branchMult2=Parse.parseIntKMG(b);
665 }else if(a.equals("branchmult1")){
666 branchMult1=Parse.parseIntKMG(b);
667 }else if(a.equals("mincount") || a.equals("mincov") || a.equals("mindepth") || a.equals("min")){
668 minCountSeed=minCountExtend=Parse.parseIntKMG(b);
669 }else if(a.equals("mindepthseed") || a.equals("mds") || a.equals("mincountseed") || a.equals("mcs")){
670 minCountSeed=Parse.parseIntKMG(b);
671 }else if(a.equals("mindepthextend") || a.equals("mde") || a.equals("mincountextend") || a.equals("mce")){
672 minCountExtend=Parse.parseIntKMG(b);
673 }else if(a.equals("ilb") || a.equals("ignoreleftbranches") || a.equals("ignoreleftjunctions") || a.equals("ibb") || a.equals("ignorebackbranches")){
674 extendThroughLeftJunctions=Parse.parseBoolean(b);
675 }else if(a.equals("rem") || a.equals("requireextensionmatch")){
676 requireExtensionMatch=Parse.parseBoolean(b);
677 }else if(a.equals("rsem") || a.equals("requirestrictextensionmatch")){
678 requireStrictExtensionMatch=Parse.parseBoolean(b);
679 }else if(a.equals("minapproxoverlaprem") || a.equals("minapproxoverlap")){
680 minApproxOverlapRem=Parse.parseIntKMG(b);
681 }
682
683 else if(a.equals("quantize") || a.equals("quantizesticky")){
684 quantizeQuality=Quantizer.parse(arg, a, b);
685 }
686
687 else if(a.equals("besteffort") || a.equals("forcemerge")){
688 MAX_RATIO=0.5f;
689 RATIO_MARGIN=1.1f;
690 MAX_MISMATCHES_R=500;
691 useEfilter=false;
692 pfilterRatio=0;
693 }
694
695 else if(KmerTableSet.isValidArgument(a)){
696 //Do nothing
697 }
698
699 else{
700 throw new RuntimeException("Unknown parameter "+args[i]);
701 }
702 }
703
704 if(adapterList1!=null || adapterList2!=null){
705 verifyAdapters=true;
706 }
707
708 if(requireStrictExtensionMatch){
709 requireExtensionMatch=true;
710 }
711
712 if(requireExtensionMatch && extendRight2<1){
713 outstream.println("Extend2 is defaulting to 50 because it was unset but r"+(requireStrictExtensionMatch ? "s" : "")+"em mode is being used.");
714 extendRight2=50;
715 }
716
717 if(ecco && !setMix){
718 outstream.println("Mergable and unmergable reads are all being sent to out because ecco=t. To override this, set mix=f.");
719 MIX_BAD_AND_GOOD=true;
720 }
721
722 // assert(!requireExtensionMatch || extendRight2>0) : "The requireExtensionMatch flag requires also setting the extend2 flag.\n"
723 // + "Suggested values are extend2=50 k=62.";
724
725 // assert(false) : ecco;
726 minInsert=Tools.max(minInsert, MIN_OVERLAPPING_BASES);
727 if(minInsert0<1){
728 minInsert0=(Tools.max((int)Math.ceil(minInsert*0.75), 5, MIN_OVERLAPPING_BASES_0));
729 int cap=(loose ? 50 : 35);
730 minInsert0=Tools.min(cap, minInsert0);
731 }
732 minInsert0=Tools.min(minInsert, minInsert0);
733
734 if(MATE_BY_OVERLAP && !useFlatMode && !useRatioMode){
735 outstream.println("\n*** WARNING! Both flat and ratio mode were disabled; using ratio mode. ***\n");
736 useRatioMode=true;
737 }
738
739 loglog=(outCardinality==null && !parser.loglog ? null : CardinalityTracker.makeTracker(2048, 31, -1, 0));
740
741 {//Process parser fields
742 Parser.processQuality();
743
744 qtrimLeft=parser.qtrimLeft;
745 qtrimRight=parser.qtrimRight;
746 trimq=(parser.trimq2!=null ? parser.trimq2 : new float[] {parser.trimq});
747 trimE=parser.trimE2();
748 qtrim1=parser.qtrim1;
749 qtrim2=(parser.qtrim2 || (parser.trimq2!=null && parser.trimq2.length>1));
750 if(qtrim1==false && qtrim2==false){
751 qtrim1=((qtrimLeft||qtrimRight)&&trimq[0]>=0);
752 }
753 minAvgQuality=parser.minAvgQuality;
754 minAvgQualityBases=parser.minAvgQualityBases;
755 minReadLength=Tools.max(1, parser.minReadLength);
756 maxReadLength=(parser.maxReadLength<0 ? Integer.MAX_VALUE : parser.maxReadLength);
757 // untrim=parser.untrim;
758
759 forceTrimModulo=parser.forceTrimModulo;
760 forceTrimLeft=parser.forceTrimLeft;
761 forceTrimRight=parser.forceTrimRight;
762 forceTrimRight2=parser.forceTrimRight2;
763 }
764 // parseCustom=FASTQ.PARSE_CUSTOM;
765 // if(parseCustom){FASTQ.PARSE_CUSTOM_WARNING=false;}
766 if(verbose){
767 // assert(false) : "verbose flag is static final; recompile to change it.";
768 // BBMergeOverlapper.verbose=true;
769 }
770
771 if(trimByOverlap){
772 join=false;
773 }
774
775 if(!mm0set){
776 MAX_MISMATCHES0=MAX_MISMATCHES+(loose ? 2 : 0);
777 }
778
779 if(MAX_MISMATCHES0<MAX_MISMATCHES){
780 MAX_MISMATCHES0=MAX_MISMATCHES+(loose ? 2 : 0);
781 outstream.println("MAX_MISMATCHES0 was set to "+MAX_MISMATCHES0+" to remain >=MAX_MISMATCHES");
782 }
783
784 if(MISMATCH_MARGIN>MAX_MISMATCHES){
785 MISMATCH_MARGIN=MAX_MISMATCHES;
786 outstream.println("MISMATCH_MARGIN was set to "+MISMATCH_MARGIN+" to remain >=MAX_MISMATCHES");
787 }
788
789 if(recalibrateQuality){CalcTrueQuality.initializeMatrices();}
790
791 if(in2==null && in1!=null && in1.contains("#") && !new File(in1).exists()){
792 in2=in1.replaceFirst("#", "2");
793 in1=in1.replaceFirst("#", "1");
794 }
795
796 if(out2==null && out1!=null && out1.contains("#")){
797 out2=out1.replaceFirst("#", "2");
798 out1=out1.replaceFirst("#", "1");
799 }
800
801 if(outb2==null && outb1!=null && outb1.contains("#")){
802 outb2=outb1.replaceFirst("#", "2");
803 outb1=outb1.replaceFirst("#", "1");
804 }
805
806 if(extendRight1>0 || extendRight2>0 || useKFilter || eccTadpole || forceExactKmerCounts){
807
808 final long mem=Shared.memAvailable();
809 if(Shared.memAvailable()<2000000000L){
810 System.err.println("\n***** WARNING *****\nUsing kmer counts uses a lot of memory, but only "+(mem/(1024*1024))+"MB is available.");
811 System.err.println("If this process crashes, run bbmerge-auto.sh instead of bbmerge.sh, or set the -Xmx flag.\n");
812 }
813
814 ArrayList<String> list=new ArrayList<String>();
815 {
816 StringBuilder sb=new StringBuilder("in=");
817 sb.append(in1);
818 if(extra.size()>0){
819 for(String s : extra){
820 sb.append(',').append(s);
821 }
822 }
823 list.add(sb.toString());
824 }
825 if(in2!=null){list.add("in2="+in2);}
826 list.add("branchlower="+branchLowerConst);
827 list.add("branchmult1="+branchMult1);
828 list.add("branchmult2="+branchMult2);
829 list.add("mincountseed="+minCountSeed);
830 list.add("mincountextend="+minCountExtend);
831 list.add("minprob="+minProb);
832 list.add("k="+kmerLength);
833 list.add("prealloc="+prealloc);
834 list.add("prefilter="+prefilter);
835 if(maxReads>0 && maxReads<Long.MAX_VALUE){
836 list.add("reads="+maxReads);
837 }
838
839 list.add("ecctail="+eccTail);
840 list.add("eccpincer="+eccPincer);
841 list.add("eccreassemble="+eccReassemble);
842 if(filterMemoryOverride>0){list.add("filtermemory="+filterMemoryOverride);}
843
844 tadpole=Tadpole.makeTadpole(list.toArray(new String[0]), false);
845 bloomFilter=null;
846 corrector=null;
847 }else if(eccBloom || testMerge){
848 assert(kmerLength<32) : "Bloom filter kmer length must be in the range of 1-31.";
849 Timer t=new Timer(outstream, true);
850 KmerCountAbstract.CANONICAL=true;
851 tadpole=null;
852 bloomFilter=new BloomFilter(in1, in2, extra, kmerLength, kmerLength, bloomBits, bloomHashes, 1,
853 true, false, false, 0.9f);
854 corrector=new BloomFilterCorrector(bloomFilter, kmerLength, kmerLength);
855 t.stop("Filter creation: \t\t");
856 outstream.println(bloomFilter.filter.toShortString());
857 }else{
858 tadpole=null;
859 bloomFilter=null;
860 corrector=null;
861 }
862
863 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, outb1, outb2, outinsert, ihist, outCardinality, outAdapter)){
864 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+
865 out1+", "+out2+", "+outb1+", "+outb2+", "+outinsert+", "+ihist+"\n");
866 }
867 in1=Tools.fixExtension(in1);
868 in2=Tools.fixExtension(in2);
869 if(!Tools.testInputFiles(false, true, in1, in2)){
870 throw new RuntimeException("\nCan't read some input files.\n");
871 }
872 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2, outb1, outb2, outinsert, ihist)){
873 throw new RuntimeException("\nSome file names were specified multiple times.\n");
874 }
875
876 if(in2!=null){
877 assert(!in1.equalsIgnoreCase(in2));
878 FASTQ.TEST_INTERLEAVED=false;
879 FASTQ.FORCE_INTERLEAVED=false;
880 }else{
881 FASTQ.TEST_INTERLEAVED=true;
882 FASTQ.FORCE_INTERLEAVED=true;
883 }
884
885 if(THREADS<1){THREADS=Shared.threads();}
886
887 useMEEfilter=maxExpectedErrors>0;
888
889 Read.VALIDATE_IN_CONSTRUCTOR=(THREADS<16);
890 if(netFile==null) {net0=null;}
891 else if(!netFile.equals(defaultNetFile)) {net0=CellNetParser.load(netFile);}
892 }
893
894 void process(){
895 Timer ttotal=new Timer();
896 ttotal.start();
897
898 if(tadpole!=null){
899 if(extendRight1>0 || extendRight2>0 || eccTadpole) {
900 MAKE_VECTOR=BBMergeOverlapper.MAKE_VECTOR=false;//Currently incompatible...
901 }
902
903 Timer tload=new Timer();
904 Tadpole.showSpeed=false;
905 KmerTableSet.showSpeed=false;
906 long kmers=tadpole.loadKmers(tload);
907 tload.stop();
908 outstream.println();
909
910 if(shave || rinse){
911 tload.start();
912 long removed=tadpole.shaveAndRinse(tload, shave, rinse, true);
913 tload.stop();
914 outstream.println();
915 }
916
917 // outstream.println("Loaded "+kmers+" kmers in "+tload);
918 }
919
920 runPhase(join, maxReads, false);
921
922 double stdev=0;
923 if(histTotal!=null){
924 stdev=Tools.standardDeviationHistogram(histTotal);
925 }
926
927 final long sum=correctCountTotal+incorrectCountTotal;
928 final double divp=100d/readsProcessedTotal;
929 final double div2=100d/sum;
930
931 writeHistogram(ihist, sum*divp);
932
933 if(outAdapter!=null){
934 assert(findAdapterSequence);
935 long count=atrack.writeAdapterConsensus(outAdapter);
936 outstream.println("Adapters counted: "+count);
937 }
938
939 if(outCardinality!=null){
940 ReadWrite.writeString(loglog.cardinality()+"\n", outCardinality);
941 }
942
943 ttotal.stop();
944 outstream.println("Total time: "+ttotal+"\n");
945
946 outstream.println("Pairs: \t"+readsProcessedTotal);
947 outstream.println("Joined: \t"+sum+String.format((sum<10000 ? " " : " ")+"\t%.3f%%", sum*divp));
948 outstream.println("Ambiguous: \t"+ambiguousCountTotal+String.format((ambiguousCountTotal<10000 ? " " : " ")+"\t%.3f%%", ambiguousCountTotal*divp));
949 outstream.println("No Solution: \t"+noSolutionCountTotal+String.format((noSolutionCountTotal<10000 ? " " : " ")+"\t%.3f%%", noSolutionCountTotal*divp));
950 if(minInsert>0){outstream.println("Too Short: \t"+tooShortCountTotal+String.format((tooShortCountTotal<10000 ? " " : " ")+"\t%.3f%%", tooShortCountTotal*divp));}
951 if(maxReadLength<Integer.MAX_VALUE){outstream.println("Too Long: \t"+tooLongCountTotal+String.format((tooLongCountTotal<10000 ? " " : " ")+"\t%.3f%%", tooLongCountTotal*divp));}
952
953 if(extendRight1>0 || extendRight2>0){
954 double dive=100d/extensionsAttempted;
955 outstream.println("Fully Extended: \t"+fullyExtendedTotal+String.format((fullyExtendedTotal<10000 ? " " : " ")+"\t%.3f%%", fullyExtendedTotal*dive));
956 outstream.println("Partly Extended: \t"+partlyExtendedTotal+String.format((partlyExtendedTotal<10000 ? " " : " ")+"\t%.3f%%", partlyExtendedTotal*dive));
957 outstream.println("Not Extended: \t"+notExtendedTotal+String.format((notExtendedTotal<10000 ? " " : " ")+"\t%.3f%%", notExtendedTotal*dive));
958 }
959
960 if(adapterList1!=null || adapterList2!=null){
961 double diva=100d/(readsProcessedTotal*2);
962 outstream.println("Adapters Expected: \t"+adaptersExpected+String.format((adaptersExpected<10000 ? " " : " ")+"\t%.3f%%", adaptersExpected*diva));
963 outstream.println("Adapters Found: \t"+adaptersFound+String.format((adaptersFound<10000 ? " " : " ")+"\t%.3f%%", adaptersFound*diva));
964 }
965
966 if(ecco){
967 outstream.println("Errors Corrected: \t"+errorsCorrectedTotal);
968 }
969
970 if(loglog!=null){
971 outstream.println("Unique "+loglog.k+"-mers: \t"+loglog.cardinality());
972 }
973
974 if(parseCustom){
975 outstream.println();
976 outstream.println("Correct: \t"+correctCountTotal+String.format((correctCountTotal<10000 ? " " : " ")+"\t%.4f%%", correctCountTotal*divp)+Tools.format(" \t%.4f%% of merged", correctCountTotal*div2));
977 outstream.println("Incorrect: \t"+incorrectCountTotal+String.format((incorrectCountTotal<10000 ? " " : " ")+"\t%.5f%%", incorrectCountTotal*divp)+Tools.format(" \t%.5f%% of merged", incorrectCountTotal*div2));
978 double FPRate=incorrectCountTotal/(double)readsProcessedTotal;
979 double FNRate=unmergedOverlappingTotal/(double)readsProcessedTotal;
980 double snr=Tools.max(correctCountTotal, 0.001)/(Tools.max(incorrectCountTotal, 0.001));
981 double snrDB=Tools.mid(-20, 80, 10*Math.log10(snr));
982 outstream.println("SNR: \t"+Tools.format("%.3f dB", snrDB));
983 outstream.println("FPR: \t"+Tools.format("%.4f%%", FPRate*100));
984 outstream.println("FNR: \t"+Tools.format("%.4f%%", FNRate*100));
985 outstream.println();
986 outstream.println("Avg Insert Correct: \t"+Tools.format("%.1f", (insertSumCorrectTotal)*1d/(correctCountTotal)));
987 outstream.println("Avg Insert Incorrect:\t"+Tools.format("%.1f", (insertSumIncorrectTotal)*1d/(incorrectCountTotal)));
988 }
989
990 outstream.println("\nAvg Insert: \t"+Tools.format("%.1f", (insertSumCorrectTotal+insertSumIncorrectTotal)*1d/(correctCountTotal+incorrectCountTotal)));
991 outstream.println("Standard Deviation: \t"+Tools.format("%.1f", stdev));
992 outstream.println("Mode: \t"+Tools.calcModeHistogram(histTotal));
993
994 outstream.println();
995 outstream.println("Insert range: \t"+insertMinTotal+" - "+insertMaxTotal);
996 outstream.println("90th percentile: \t"+Tools.percentileHistogram(histTotal, .9));
997 outstream.println("75th percentile: \t"+Tools.percentileHistogram(histTotal, .75));
998 outstream.println("50th percentile: \t"+Tools.percentileHistogram(histTotal, .5));
999 outstream.println("25th percentile: \t"+Tools.percentileHistogram(histTotal, .25));
1000 outstream.println("10th percentile: \t"+Tools.percentileHistogram(histTotal, .1));
1001 }
1002
1003 public static void writeHistogram(String fname, double percentMerged){
1004 if(fname==null){return;}
1005 StringBuilder sb=new StringBuilder();
1006
1007 if(showHistStats){
1008 sb.append("#Mean\t"+Tools.format("%.3f", Tools.averageHistogram(histTotal))+"\n");
1009 sb.append("#Median\t"+Tools.percentileHistogram(histTotal, 0.5)+"\n");
1010 sb.append("#Mode\t"+Tools.calcModeHistogram(histTotal)+"\n");
1011 sb.append("#STDev\t"+Tools.format("%.3f", Tools.standardDeviationHistogram(histTotal))+"\n");
1012 sb.append("#PercentOfPairs\t"+Tools.format("%.3f", percentMerged)+"\n");
1013 }
1014 sb.append("#InsertSize\tCount\n");
1015 for(int i=0; i<histTotal.length && i<=insertMaxTotal; i+=bin){
1016 int x=0;
1017 int y=0;
1018 for(int j=i; j<i+bin && j<histTotal.length; j++){
1019 x+=histTotal[j];
1020 y++;
1021 }
1022 x=(x+bin-1)/y;
1023 if(x>0 || !NONZERO_ONLY){
1024 sb.append(i+"\t"+x+"\n");
1025 }
1026 }
1027 ReadWrite.writeStringInThread(sb, fname);
1028 }
1029
1030 // private static String toAdapterSequence(LongList[] lists, boolean trimPolyA){
1031 // StringBuilder adapter=new StringBuilder();
1032 // long max=0;
1033 // int lastBase=-1;
1034 // for(int i=0; true; i++){
1035 // long a=lists[0].get(i);
1036 // long c=lists[1].get(i);
1037 // long g=lists[2].get(i);
1038 // long t=lists[3].get(i);
1039 // long sum=(a+c+g+t);
1040 // max=Tools.max(max, sum);
1041 // if(sum==0 || (sum<10 && sum<=max/1000) || (max>100 && sum<8)){break;}
1042 // long thresh=(max>100 ? 4+(sum*2)/3 : (sum*2)/3);
1043 // if(a>thresh){
1044 // adapter.append('A');
1045 // lastBase=i;
1046 // }else if(c>thresh){
1047 // adapter.append('C');
1048 // lastBase=i;
1049 // }else if(g>thresh){
1050 // adapter.append('G');
1051 // lastBase=i;
1052 // }else if(t>thresh){
1053 // adapter.append('T');
1054 // lastBase=i;
1055 // }else{
1056 // adapter.append('N');
1057 // }
1058 // }
1059 // if(lastBase<0){return "N";}
1060 //
1061 // String trimmed=trimPoly(adapter.toString(), 'N');
1062 // if(trimPolyA){
1063 // trimmed=trimPoly(trimmed, 'G');
1064 // trimmed=trimPoly(trimmed, 'A');
1065 // }
1066 //
1067 // if(lastBase>=0){
1068 // char A=(trimPolyA ? 'A' : 'N');
1069 // while(lastBase>=0 && (adapter.charAt(lastBase)=='N' || adapter.charAt(lastBase)==A)){lastBase--;}
1070 // }
1071 //
1072 // if(lastBase<0){return "N";}
1073 // return adapter.substring(0, lastBase+1);
1074 // }
1075 //
1076 // private static String trimPoly(String adapter, char trim){
1077 // int lastBase=-1;
1078 // for(int i=0; i<adapter.length(); i++){
1079 // char c=adapter.charAt(i);
1080 // if(AminoAcid.isFullyDefined(c)){
1081 // lastBase=i;
1082 // }
1083 // }
1084 //
1085 // int aCount=0;
1086 // int nCount=0;
1087 // int count=0;
1088 // if(lastBase>=0){
1089 // while(lastBase>=0){
1090 // char c=adapter.charAt(lastBase);
1091 // if(c=='N'){nCount++;}
1092 // else if(c==trim){aCount++;}
1093 // else{break;}
1094 // count++;
1095 // lastBase--;
1096 // }
1097 // }
1098 //
1099 // if(lastBase<0){return "N";}
1100 // if(count==nCount || (aCount>3)){
1101 // return adapter.substring(0, lastBase+1);
1102 // }
1103 // return adapter;
1104 // }
1105
1106
1107 public void runPhase(boolean join, long maxReads, boolean perfectonly){
1108
1109 Timer talign=new Timer();
1110
1111 ConcurrentReadOutputStream rosgood=null;
1112 ConcurrentReadOutputStream rosbad=null;
1113 ConcurrentReadOutputStream rosinsert=null;
1114
1115 if(out1!=null){
1116 if(join==true){
1117 if(out2==null){outstream.println("Writing mergable reads merged.");}
1118 else{
1119 outstream.println("WARNING: 2 output files specified even though 'merge=true'. out2 will be ignored.");
1120 out2=null;
1121 }
1122 }else{
1123 if(out2==null){outstream.println("Writing mergable reads interleaved.");}
1124 else{outstream.println("Writing mergable reads unmerged in two files.");}
1125 }
1126
1127 final FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1128 final FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1129 assert(!ff1.samOrBam()) : "Sam files need reference info for the header.";
1130
1131 final int buff=Tools.max(16, 2*THREADS);
1132 rosgood=ConcurrentReadOutputStream.getStream(ff1, ff2, null, null, buff, null, false);
1133 rosgood.start();
1134 }
1135
1136 if(outb1!=null){
1137
1138 final FileFormat ff1=FileFormat.testOutput(outb1, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1139 final FileFormat ff2=FileFormat.testOutput(outb2, FileFormat.FASTQ, null, true, overwrite, append, ordered);
1140 assert(!ff1.samOrBam()) : "Sam files need reference info for the header.";
1141
1142 final int buff=Tools.max(16, 2*THREADS);
1143 rosbad=ConcurrentReadOutputStream.getStream(ff1, ff2, null, null, buff, null, false);
1144 rosbad.start();
1145 }
1146
1147 if(outinsert!=null){
1148 final int buff=Tools.max(16, 2*THREADS);
1149
1150 String out1=outinsert.replaceFirst("#", "1");
1151
1152 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1));
1153
1154 ReadStreamWriter.HEADER=header();
1155 final FileFormat ff=FileFormat.testOutput(out1, FileFormat.ATTACHMENT, ".info", true, overwrite, append, ordered);
1156 rosinsert=ConcurrentReadOutputStream.getStream(ff, null, null, null, buff, null, false);
1157 rosinsert.start();
1158 }
1159
1160
1161 if(rosgood!=null || rosbad!=null || rosinsert!=null){
1162 outstream.println("Started output threads.");
1163 }
1164
1165 final ConcurrentReadInputStream cris;
1166 {
1167 FileFormat ff1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
1168 FileFormat ff2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true);
1169 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
1170 cris.setSampleRate(samplerate, sampleseed);
1171 if(verbose){outstream.println("Started cris");}
1172 cris.start(); //4567
1173 }
1174 boolean paired=cris.paired();
1175 // assert(paired);//Fails on empty files.
1176 if(verbose){outstream.println("Paired: "+paired);}
1177
1178 talign.start();
1179
1180
1181 MateThread[] pta=new MateThread[THREADS];
1182 for(int i=0; i<pta.length; i++){
1183 pta[i]=new MateThread(cris, rosgood, rosbad, rosinsert, join, trimByOverlap);
1184 pta[i].start();
1185 }
1186
1187 resetCounters();
1188
1189 for(int i=0; i<pta.length; i++){
1190 MateThread ct=pta[i];
1191 synchronized(ct){
1192 while(ct.isAlive()){
1193 try {
1194 ct.join(1000);
1195 } catch (InterruptedException e) {
1196 // TODO Auto-generated catch block
1197 e.printStackTrace();
1198 }
1199 }
1200
1201 readsProcessedTotal+=ct.pairsProcessed;
1202 basesProcessedTotal+=ct.basesProcessed;
1203 matedCountTotal+=ct.matedCount;
1204 correctCountTotal+=ct.correctCount;
1205 unmergedOverlappingTotal+=ct.unmergedOverlappingCount;
1206 ambiguousCountTotal+=ct.ambiguousCount;
1207 tooShortCountTotal+=ct.tooShortCount;
1208 tooLongCountTotal+=ct.tooLongCount;
1209 incorrectCountTotal+=ct.incorrectCount;
1210 noSolutionCountTotal+=ct.noSolutionCount;
1211 insertSumCorrectTotal+=ct.insertSumCorrect;
1212 insertSumIncorrectTotal+=ct.insertSumIncorrect;
1213
1214 errorsCorrectedTotal+=ct.errorsCorrectedT;
1215
1216 fullyExtendedTotal+=ct.fullyExtendedT;
1217 partlyExtendedTotal+=ct.partlyExtendedT;
1218 notExtendedTotal+=ct.notExtendedT;
1219 extensionsAttempted+=ct.extensionsAttemptedT;
1220
1221 adaptersExpected+=ct.adaptersExpectedT;
1222 adaptersFound+=ct.adaptersFoundT;
1223
1224 insertMinTotal=Tools.min(ct.insertMin, insertMinTotal);
1225 insertMaxTotal=Tools.max(ct.insertMax, insertMaxTotal);
1226
1227 // outstream.println(ct.insertMin+", "+ct.insertMax);
1228
1229 if(ct.hist!=null){
1230 for(int h=0; h<ct.hist.length; h++){
1231 histTotal[h]+=ct.hist[h];
1232 }
1233 }
1234
1235 if(findAdapterSequence){
1236 atrack.merge(ct.atrackT);
1237 }
1238 }
1239 }
1240
1241 // outstream.println("Finished reading");
1242 errorState|=ReadWrite.closeStreams(cris, rosgood, rosbad, rosinsert);
1243
1244 talign.stop();
1245 // outstream.println("Align time: "+talign);
1246 }
1247
1248 public static final float mergeableFraction(String fname1, String fname2, long numReads, float samplerate){
1249 long[] hist=makeInsertHistogram(fname1, fname2, numReads, samplerate);
1250 if(hist==null || hist.length<2){return 0;}
1251 long sum=shared.Vector.sum(hist);
1252 return sum<1 ? 0 : (sum-hist[0])/(float)sum;
1253 }
1254
1255 public static final long[] makeInsertHistogram(String fname1, String fname2, long numReads, float samplerate){
1256 assert(fname1!=null);
1257 final ConcurrentReadInputStream cris;
1258 {
1259 FileFormat ff1=FileFormat.testInput(fname1, FileFormat.FASTQ, null, true, true);
1260 FileFormat ff2=FileFormat.testInput(fname2, FileFormat.FASTQ, null, true, true);
1261 if(ff1.stdio()){return null;}
1262 assert(!ff1.stdio()) : "Standard in is not allowed as input when calculating insert size distributions for files.";
1263 cris=ConcurrentReadInputStream.getReadInputStream(numReads, true, ff1, ff2);
1264 cris.setSampleRate(samplerate, 1);
1265 if(verbose){outstream.println("Started cris");}
1266 cris.start(); //4567
1267 if(!cris.paired()){
1268 ReadWrite.closeStreams(cris);
1269 return null;
1270 }
1271 }
1272
1273 ListNum<Read> ln=cris.nextList();
1274 ArrayList<Read> reads=(ln!=null ? ln.list : null);
1275
1276 if(reads!=null && !reads.isEmpty()){
1277 Read r=reads.get(0);
1278 assert(r.mate!=null);
1279 }
1280
1281 LongList ll=new LongList(500);
1282 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
1283
1284 for(Read r1 : reads){
1285 int x=findOverlapLoose(r1, r1.mate, false);
1286 if(x>0){ll.increment(x, 1);}
1287 else{ll.increment(0, 1);}
1288 }
1289 cris.returnList(ln);
1290 ln=cris.nextList();
1291 reads=(ln!=null ? ln.list : null);
1292 }
1293 cris.returnList(ln);
1294 ReadWrite.closeStreams(cris);
1295 return ll.toArray();
1296 }
1297
1298 /** Returns the insert size as calculated by overlap, or -1 */
1299 public static final int findOverlapUStrict(final Read r1, final Read r2, boolean ecc){
1300 final float maxRatio=0.045f;
1301 final float ratioMargin=12f;
1302 final float ratioOffset=0.5f;
1303
1304 final float efilterRatio=2f;
1305 final float efilterOffset=0.03f;
1306 final float pfilterRatio=0.03f;
1307
1308 final int minOverlap=14;
1309 final int minOverlap0=3;
1310 final int minInsert=35;
1311 final int minInsert0=20;
1312 final int entropy=56;
1313 final float minSecondRatio=0.16f;
1314
1315 // final int ratioMinOverlapReduction=4;
1316
1317 final int x=findOverlap(r1, r2, ecc,
1318 minOverlap, minOverlap0, minInsert, minInsert0, entropy,
1319 maxRatio, minSecondRatio, ratioMargin, ratioOffset,
1320 efilterRatio, efilterOffset, pfilterRatio);
1321 return x;
1322 }
1323
1324 /** Returns the insert size as calculated by overlap, or -1 */
1325 public static final int findOverlapVStrict(final Read r1, final Read r2, boolean ecc){
1326 final float maxRatio=0.05f;
1327 final float ratioMargin=12f;
1328 final float ratioOffset=0.5f;
1329
1330 final float efilterRatio=2f;
1331 final float efilterOffset=0.05f;
1332 final float pfilterRatio=0.008f;
1333
1334 final int minOverlap=12;
1335 final int minOverlap0=4;
1336 final int minInsert=35;
1337 final int minInsert0=25;
1338 final int entropy=52;
1339 final float minSecondRatio=0.16f;
1340
1341 // final int ratioMinOverlapReduction=4;
1342
1343 final int x=findOverlap(r1, r2, ecc,
1344 minOverlap, minOverlap0, minInsert, minInsert0, entropy,
1345 maxRatio, minSecondRatio, ratioMargin, ratioOffset,
1346 efilterRatio, efilterOffset, pfilterRatio);
1347 return x;
1348 }
1349
1350 public static final Read tryToMerge(final Read r1, final Read r2) {
1351 if(r2==null) {return null;}
1352 int insert=findOverlapStrict(r1, r2, false);
1353 if(insert<1){return null;}
1354 r2.reverseComplement();
1355 Read r3=r1.joinRead(insert);
1356 r2.reverseComplement();
1357 return r3;
1358 }
1359
1360 /** Returns the insert size as calculated by overlap, or -1 */
1361 public static final int findOverlapStrict(final Read r1, final Read r2, boolean ecc){
1362 final float maxRatio=0.075f;
1363 final float ratioMargin=7.5f;
1364 final float ratioOffset=0.55f;
1365
1366 final float efilterRatio=4f;
1367 final float efilterOffset=0.05f;
1368 final float pfilterRatio=0.0008f;
1369
1370 final int minOverlap=11;
1371 final int minOverlap0=5;
1372 final int minInsert=35;
1373 final int minInsert0=25;
1374 final int entropy=42;
1375 final float minSecondRatio=0.12f;
1376
1377 // final int ratioMinOverlapReduction=4;
1378
1379 final int x=findOverlap(r1, r2, ecc,
1380 minOverlap, minOverlap0, minInsert, minInsert0, entropy,
1381 maxRatio, minSecondRatio, ratioMargin, ratioOffset,
1382 efilterRatio, efilterOffset, pfilterRatio);
1383 return x;
1384 }
1385
1386 /** Returns the insert size as calculated by overlap, or -1 */
1387 public static final int findOverlapLoose(final Read r1, final Read r2, boolean ecc){
1388 final float maxRatio=0.11f;
1389 final float ratioMargin=4.7f;
1390 final float ratioOffset=0.45f;
1391
1392 final float efilterRatio=8f;
1393 final float efilterOffset=0.55f;
1394 final float pfilterRatio=0.00002f;
1395
1396 final int minOverlap=5;
1397 final int minOverlap0=6;
1398 final int minInsert=16;
1399 final int minInsert0=16;
1400 final int entropy=30;
1401 final float minSecondRatio=0.1f;
1402
1403 // final int ratioMinOverlapReduction=2;
1404
1405 final int x=findOverlap(r1, r2, ecc,
1406 minOverlap, minOverlap0, minInsert, minInsert0, entropy,
1407 maxRatio, minSecondRatio, ratioMargin, ratioOffset,
1408 efilterRatio, efilterOffset, pfilterRatio);
1409 return x;
1410 }
1411
1412 /** Returns the insert size as calculated by overlap, or -1 */
1413 public static final int findOverlap(final Read r1, final Read r2, final boolean ecc,
1414 int minOverlap, final int minOverlap0, final int minInsert, final int minInsert0, final int entropy,
1415 final float maxRatio, final float minSecondRatio, final float ratioMargin, final float ratioOffset,
1416 final float efilterRatio, final float efilterOffset, final float pfilterRatio){
1417
1418 assert(r1!=null && r2!=null);
1419 if(!r1.validated()){r1.validate(true);}
1420 if(!r2.validated()){r2.validate(true);}
1421
1422 final int len1=r1.length(), len2=r2.length();
1423 final int minlen=Tools.min(len1, len2);
1424
1425 if(minlen<MIN_OVERLAPPING_BASES || minlen<minInsert){
1426 return -1;
1427 }
1428
1429 int[] rvector=localRvector.get();
1430 if(rvector==null){
1431 rvector=KillSwitch.allocInt1D(5);
1432 localRvector.set(rvector);
1433 }
1434
1435 r2.reverseComplement();
1436
1437 int bestInsert=-1;
1438 int bestBad=999999;
1439 boolean ambig, tooShort=false;
1440
1441 if(USE_MAPPING && r1.chrom==r2.chrom && r1.start<r1.stop && r1.mapped() && r2.mapped()){
1442 bestBad=0;
1443 bestInsert=Read.insertSizeMapped(r1, r2, false);
1444 ambig=false;
1445 }else{
1446 if(entropy>0){
1447 int a=BBMergeOverlapper.calcMinOverlapByEntropy(r1.bases, 3, null, entropy);
1448 int b=BBMergeOverlapper.calcMinOverlapByEntropy(r2.bases, 3, null, entropy);
1449 minOverlap=Tools.max(MIN_OVERLAPPING_BASES, Tools.max(a, b));
1450 }else{minOverlap=MIN_OVERLAPPING_BASES;}
1451 if(verbose){outstream.println("minOverlap: "+minOverlap);}
1452
1453 rvector[4]=0;
1454
1455 int x=BBMergeOverlapper.mateByOverlapRatio(r1, r2, null, null, rvector, minOverlap0, minOverlap,
1456 minInsert0, minInsert, maxRatio, minSecondRatio, ratioMargin, ratioOffset, 0.95f, 0.95f, false);
1457 bestInsert=x;
1458 bestBad=rvector[2];
1459 ambig=(x>-1 ? rvector[4]==1 : false);
1460 }
1461
1462 //TODO: Crucial! This line can vastly reduce merge rate, particularly if quality values are inaccurate.
1463 if(bestInsert>0 && !ambig && r1.quality!=null && r2.quality!=null){
1464 float bestExpected=BBMergeOverlapper.expectedMismatches(r1, r2, bestInsert);
1465 if((bestExpected+efilterOffset)*efilterRatio<bestBad){ambig=true;}
1466 if(verbose){outstream.println("Result after efilter: \tinsert="+bestInsert+", bad="+bestBad+", ambig="+ambig);}
1467 }
1468
1469 //TODO: Crucial! This line can vastly reduce merge rate, particularly if quality values are inaccurate.
1470 if(pfilterRatio>0 && bestInsert>0 && !ambig && r1.quality!=null && r2.quality!=null){
1471 float probability=BBMergeOverlapper.probability(r1, r2, bestInsert);
1472 if(probability<pfilterRatio){bestInsert=-1;}
1473 if(verbose){outstream.println("Result after pfilter: \tinsert="+bestInsert+", bad="+bestBad+", ambig="+ambig);}
1474 }
1475
1476 if(staticAdapterList!=null && bestInsert>0 && (bestInsert<len1 || bestInsert<len2)){
1477 boolean foundAdapter=verifyAdaptersStatic(r1, r2, bestInsert);
1478 if(!foundAdapter){
1479 bestInsert=RET_NO_SOLUTION;
1480 assert(r1.quality==null || (r1.quality.length==r1.bases.length && r2.quality.length==r2.bases.length));
1481 r2.reverseComplement();
1482 return RET_NO_SOLUTION;
1483 }
1484 }
1485
1486 tooShort=(!ambig && bestInsert>0 && bestInsert<minInsert);
1487
1488 if(ecc && bestInsert>-1 && !ambig && !tooShort){
1489 int errors=errorCorrectWithInsert(r1, r2, bestInsert);
1490 }
1491
1492 if(r2!=null){r2.reverseComplement();}
1493 if(!ambig && bestInsert>-1){r1.setInsert(bestInsert);}
1494
1495 return ambig ? -1 : bestInsert;
1496 }
1497
1498 public static int errorCorrectWithInsert(Read r1, Read r2, int insert){
1499 if(insert>=r1.length()+r2.length()){return 0;}
1500 assert(insert>0);
1501 Read joined=r1.joinRead(insert);
1502
1503 if(joined!=null && joined.length()>0){
1504 final int lenj=joined.length();
1505 final int lim1=Tools.min(joined.length(), r1.length());
1506 final int lim2=lenj-Tools.min(r2.length(), lenj);
1507
1508 final byte[] old1=r1.bases, old2=r2.bases;
1509 r1.errors=r2.errors=0;
1510
1511 r1.bases=KillSwitch.copyOfRange(joined.bases, 0, lim1);
1512 for(int i=0; i<r1.bases.length; i++){//count errors
1513 if(old1[i]!=r1.bases[i] && AminoAcid.isFullyDefined(r1.bases[i])){r1.errors++;}
1514 }
1515 if(r1.quality!=null){
1516 if(changeQuality){
1517 r1.quality=KillSwitch.copyOfRange(joined.quality, 0, lim1);
1518 }else{
1519 r1.quality=KillSwitch.copyOfRange(r1.quality, 0, lim1);
1520 }
1521 }
1522
1523 r2.bases=KillSwitch.copyOfRange(joined.bases, lim2, lenj);
1524 for(int i=0, j=(old2.length-r2.bases.length); i<r2.bases.length; i++, j++){//count errors
1525 if(old2[j]!=r2.bases[i] && AminoAcid.isFullyDefined(r2.bases[i])){r2.errors++;}
1526 }
1527 if(r2.quality!=null){
1528 if(changeQuality){
1529 r2.quality=KillSwitch.copyOfRange(joined.quality, lim2, lenj);
1530 }else{
1531 r2.quality=KillSwitch.copyOfRange(r2.quality, 0, r2.bases.length);
1532 }
1533 }
1534 }else{
1535 return 0;
1536 }
1537 return r1.errors+r2.errors;
1538 }
1539
1540 public static int countErrors(Read r1, Read r2, Read joined){
1541 if(joined==null){return 0;}
1542 final int insert=joined.length();
1543 if(insert<1 || insert>=r1.length()+r2.length()){return 0;}
1544
1545 final int lenj=joined.length();
1546
1547 int e1=0, e2=0;
1548 final byte[] bases1=r1.bases, bases2=r2.bases, basesj=joined.bases;
1549 for(int i=0; i<bases1.length && i<lenj; i++){//count errors
1550 if(bases1[i]!=basesj[i] && AminoAcid.isFullyDefined(basesj[i])){e1++;}
1551 }
1552 for(int i=0, j=lenj-bases2.length; i<bases2.length && j<lenj; i++, j++){//count errors
1553 if(j>=0 && bases2[i]!=basesj[j] && AminoAcid.isFullyDefined(basesj[j])){e2++;}
1554 }
1555 return e1+e2;
1556 }
1557
1558 /** Assumes both reads are in original orientation */
1559 public static int countErrors(Read r1, Read r2, final int insert){
1560 return countErrors(r1.bases, r2.bases, insert);
1561 }
1562
1563 /** Assumes both reads are in original orientation */
1564 public static int countErrors(byte[] bases1, byte[] bases2, final int insert){
1565 if(insert<1 || bases1==null || bases2==null){return 0;}
1566 if(insert>=bases1.length+bases2.length){return 0;}
1567
1568 int offset1=(insert>=bases1.length ? insert-bases1.length : 0);
1569 int offset2=(insert>=bases2.length ? bases2.length-1 : insert-1);
1570
1571 int errors=0;
1572 // int overlap=0;
1573 for(int i=offset1, j=offset2; i<bases1.length && j>=0; i++, j--) {
1574 byte a=bases1[i], b=bases2[j];
1575 errors+=(a==AminoAcid.baseToComplementExtended[b] ? 0 : 1);
1576 // overlap++;
1577 }
1578
1579 // catch (Exception e) {
1580 // System.err.println(e);
1581 // assert(false) : insert+", "+overlap+", "+
1582 // errors+", "+bases1.length+", "+offset1+", "+offset2;
1583 //Should typically be true... reads that mostly mismatch shouldn't merge
1584 // assert(errors*2<overlap+1) : insert+", "+overlap+", "+
1585 // errors+", "+bases1.length+", "+offset1+", "+offset2;
1586 return errors;
1587 }
1588
1589 public static String header(){
1590 if(TAG_CUSTOM) {
1591 String i="##mo\tr1ee\tr2ee\talen\tblen\tbi\tbo\tbb\tbg\tbr\tbbi"+
1592 "\tsbi\tsbo\tsbb\tsbg\tsbr\tsbbi\trr\tbadr\tgoodr\tovr\tbe\tpr";
1593 // String o="truth\tgoal\tmerged";
1594 // String o="goal";
1595 String o="truth";
1596 final int inputs=Tools.tabPattern.split(i).length;
1597 final int outputs=Tools.tabPattern.split(o).length;
1598 return "#dims\t"+inputs+"\t"+outputs+"\n"+i+"\t"+o+"\n";
1599 }else {
1600 return "#id\tnumericID\tinsert\tstatus\tmismatches\n";
1601 }
1602 }
1603
1604 private static void qtrim(Read r1, Read r2, int iter){
1605 if(false /*untrim*/){
1606 TrimRead.trim(r1, qtrimLeft, qtrimRight, trimq[iter], trimE[iter], 1);
1607 TrimRead.trim(r2, qtrimLeft, qtrimRight, trimq[iter], trimE[iter], 1);
1608 }else{
1609 TrimRead.trimFast(r1, qtrimLeft, qtrimRight, trimq[iter], trimE[iter], 1);
1610 TrimRead.trimFast(r2, qtrimLeft, qtrimRight, trimq[iter], trimE[iter], 1);
1611 }
1612 }
1613
1614 public static final ArrayList<byte[]> getAdapterList(String name){
1615 if(name==null){return null;}
1616 ArrayList<byte[]> alb;
1617 if(name.equalsIgnoreCase("default") || (name.equalsIgnoreCase("adapters") && !new File(name).exists())){
1618 alb=new ArrayList<byte[]>(defaultAdapters.length);
1619 for(String s : defaultAdapters){alb.add(s.getBytes());}
1620 }else{
1621 alb=Tools.toAdapterList(name, maxAdapterLength);
1622 }
1623 return alb;
1624 }
1625
1626 private static boolean verifyAdaptersStatic(Read r1, Read r2, int bestInsert){
1627
1628 if(staticAdapterList==null){return true;}
1629 final int minAdapterOverlap=3;
1630 final int len1=r1.length(), len2=r2.length();
1631 if(Tools.max(len1, len2)-minAdapterOverlap<bestInsert){return true;}
1632
1633 int good=0, bad=0, invalid=0;
1634 final float minAdapterRatio=0.6f;
1635 {
1636 final int adapterLen=len1-bestInsert;
1637 if(good<1 && adapterLen>=minAdapterOverlap){
1638 if(adapterLen>=minAdapterOverlap){
1639 for(byte[] adapter : staticAdapterList){
1640 int aiv=adapterIsValid(r1, adapter, bestInsert, minAdapterOverlap, minAdapterRatio);
1641 if(aiv==2){good++; break;}
1642 else if(aiv==1){invalid++;}
1643 else{bad++;}
1644 }
1645 }
1646 }
1647 }
1648 {
1649 final int adapterLen=len2-bestInsert;
1650 if(good<1 && adapterLen>=minAdapterOverlap){
1651 if(adapterLen>=minAdapterOverlap){
1652 r2.reverseComplement();
1653 for(byte[] adapter : staticAdapterList){
1654 int aiv=adapterIsValid(r2, adapter, bestInsert, minAdapterOverlap, minAdapterRatio);
1655 if(aiv==2){good++; break;}
1656 else if(aiv==1){invalid++;}
1657 else{bad++;}
1658 }
1659 r2.reverseComplement();
1660 }
1661 }
1662 }
1663 if(good>0){
1664 return true;
1665 }else if(bad>0){
1666 return false;
1667 }else if(invalid>0 && strict){
1668 return false;
1669 }
1670 return true;
1671 }
1672
1673 /** Returns 0=bad, 1=unknown, 2=good */
1674 private static int adapterIsValid(final Read r, final byte[] adapter, final int insert,
1675 final int minAdapterOverlap, final float minAdapterRatio){
1676 // assert(false) : insert+", "+minAdapterOverlap;
1677 // outstream.println("Comparing adapter.");
1678
1679 final byte[] bases=r.bases;
1680 final int limit=Tools.min(adapter.length, bases.length-insert);
1681 final int badLimit=Tools.max(2, limit-(int)(minAdapterRatio*limit));
1682
1683 // assert(false) : limit+", "+minAdapterOverlap+", "+insert+", "+bases.length+", "+adapter.length;
1684
1685 // int shortBadLimit=1+(int)Math.ceil(minAdapterOverlap*(1-minAdapterRatio));
1686 // outstream.println("limit="+limit);
1687 if(limit<minAdapterOverlap && limit<=badLimit){
1688 // assert(false);
1689 return 1;
1690 }
1691
1692 // StringBuilder sb1=new StringBuilder();
1693 // StringBuilder sb2=new StringBuilder();
1694
1695 int good=0, bad=0, nocall=0;
1696 for(int i=0, j=insert; i<limit; i++, j++){
1697 byte a=adapter[i], b=bases[j];
1698 // sb1.append((char)a);
1699 // sb2.append((char)b);
1700 if(a=='N' || b=='N'){
1701 nocall++;
1702 }else if(a==b){
1703 good++;
1704 }else{
1705 bad++;
1706 if(bad>badLimit){return 0;}
1707 }
1708 }
1709 // assert(false) : good+", "+bad+", "+nocall;
1710 final int overlap=bad+good;
1711 if(overlap<minAdapterOverlap){
1712 return 1;
1713 }
1714 // final int minGood=(int)minAdapterRatio*overlap;
1715 final int minGood=(int)Math.ceil(minAdapterRatio*overlap);
1716 final int ret=(good>=minGood ? 2 : 0);
1717 // assert(ret==2) : "\n"+sb1+"\n"+sb2+"\n"
1718 // + "ratio="+ratio+", good="+good+", bad="+bad+", nocall="+nocall+", limit="+limit+", overlap="+overlap+"\n"
1719 // + "(good/overlap)="+good+"/"+overlap+"="+(good/overlap);
1720 // outstream.println("Returning "+ret+" for ratio "+ratio);
1721 return ret;
1722 }
1723
1724 private class MateThread extends Thread{
1725
1726
1727 public MateThread(ConcurrentReadInputStream cris_, ConcurrentReadOutputStream rosgood_, ConcurrentReadOutputStream rosbad_, ConcurrentReadOutputStream rosi_,
1728 boolean joinReads_, boolean trimByOverlap_) {
1729 cris=cris_;
1730 rosgood=rosgood_;
1731 rosbad=rosbad_;
1732 rosi=rosi_;
1733 joinReads=joinReads_;
1734 trimReadsByOverlap=trimByOverlap_;
1735 kmerT=(tadpole==null || tadpole.k()<32 ? null : new Kmer(tadpole.k()));
1736 net=(net0==null ? null : net0.copy(false));
1737
1738 if(useEntropy){
1739 kmerCounts=new short[1<<(2*entropyK)];
1740 }else{
1741 kmerCounts=null;
1742 }
1743 }
1744
1745
1746 @Override
1747 public void run(){
1748 processReads();
1749 }
1750
1751 private void processReads() {
1752 assert(USE_MAPPING || MATE_BY_OVERLAP);
1753
1754 ListNum<Read> ln=cris.nextList();
1755 ArrayList<Read> reads=(ln!=null ? ln.list : null);
1756
1757 if(reads!=null && !reads.isEmpty()){
1758 Read r=reads.get(0);
1759 assert(r.mate!=null);
1760 }
1761
1762 final byte[][] originals=((tadpole!=null || qtrimRight || qtrimLeft) &&
1763 (rosbad!=null || (rosgood!=null && (!join || MIX_BAD_AND_GOOD)))) ? new byte[4][] : null;
1764 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
1765
1766 ArrayList<Read> listg=(rosgood==null /*&& rosi==null*/ ? null : new ArrayList<Read>(reads.size()));
1767 ArrayList<Read> listb=(rosbad==null ? null : new ArrayList<Read>(reads.size()));
1768
1769 if(loglog!=null){
1770 for(Read r1 : reads){loglog.hash(r1);}
1771 }
1772
1773 for(Read r1 : reads){
1774 int bestInsert=findOverlapInThread(r1, originals, listg, listb);
1775 }
1776
1777 if(rosgood!=null){
1778 if(quantizeQuality) {Quantizer.quantize(listg);}
1779 rosgood.add(listg, ln.id);
1780 }
1781 if(rosi!=null){
1782 //This prints both merged and unmerged reads
1783
1784 if(TRAINING) {
1785 for(Read r1 : reads){
1786 assert(false); //Maybe nothing needs doing here
1787 }
1788 }else {
1789 // for(Read r1 : reads){//Legacy outinsert support
1790 // StringBuilder sb=new StringBuilder(40);
1791 // sb.append(r1.id==null ? r1.numericID+"" : r1.id).append('\t');
1792 // sb.append(r1.numericID).append('\t');
1793 // final int bestInsert=r1.insert();
1794 // sb.append(bestInsert>=0 ? bestInsert : -1);
1795 // sb.append('\t');
1796 //
1797 // if(bestInsert==RET_NO_SOLUTION){sb.append('F');}//Failed
1798 // else if(bestInsert==RET_AMBIG){sb.append('A');} //Ambiguous
1799 // else if(bestInsert==RET_SHORT){sb.append('S');} //Short
1800 // else{
1801 // if(r1.errors>0){sb.append('I');}//Imperfect
1802 // else{sb.append('P');}//Perfect
1803 // sb.append('\t');
1804 // sb.append(r1.errors);
1805 // }
1806 // r1.obj=sb;
1807 // }
1808 }
1809 // for(Read r : reads) {
1810 // ByteBuilder bb=(ByteBuilder) r.obj;
1811 // if(bb.length()<150 || bb.len
1812 // }
1813 rosi.add(reads, ln.id);
1814 }
1815 if(rosbad!=null){
1816 if(quantizeQuality) {Quantizer.quantize(listb);}
1817 rosbad.add(listb, ln.id);
1818 }
1819
1820 // outstream.println("returning list");
1821 cris.returnList(ln);
1822 // outstream.println("fetching list");
1823 ln=cris.nextList();
1824 reads=(ln!=null ? ln.list : null);
1825 // outstream.println("reads: "+(reads==null ? "null" : reads.size()));
1826 }
1827 cris.returnList(ln);
1828 }
1829
1830 private int findOverlapInThread(final Read r1, final byte[][] originals, ArrayList<Read> listg, ArrayList<Read> listb){
1831
1832 final Read r2=r1.mate;
1833 final int trueSize=parseCustom ? parseInsert(r1, r2) : -1;
1834 final int initialLen1=r1.length(), initialLen2=r2.length();
1835 final int minReadLen=Tools.min(initialLen1, initialLen2), lenSum=initialLen1+initialLen2;
1836 final int trueOverlap=Tools.min(trueSize, minReadLen, lenSum-trueSize);
1837
1838 if(originals!=null){
1839 if(eccTadpole && false){
1840 originals[0]=r1.bases;
1841 originals[1]=r1.quality;
1842 originals[2]=r2.bases;
1843 originals[3]=r2.quality;
1844 }else{
1845 originals[0]=(r1.bases==null ? null : r1.bases.clone());
1846 originals[1]=(r1.quality==null ? null : r1.quality.clone());
1847 originals[2]=(r2.bases==null ? null : r2.bases.clone());
1848 originals[3]=(r2.quality==null ? null : r2.quality.clone());
1849 }
1850 }
1851 assert(r1.quality==null || (r1.quality.length==r1.bases.length && r2.quality.length==r2.bases.length));
1852
1853 final int bestInsert=processReadPair(r1, r2);
1854 assert(r1.quality==null || (r1.quality.length==r1.bases.length && r2.quality.length==r2.bases.length));
1855 if(verbose){outstream.println("trueSize="+trueSize+", bestInsert="+bestInsert);}
1856
1857 Read joined=null;
1858
1859 // System.err.println(r2.obj);
1860
1861 if(ecco){
1862 if(r1.length()>initialLen1){
1863 TrimRead.trimByAmount(r1, 0, r1.length()-initialLen1, 1);
1864 }
1865 if(r2.length()>initialLen2){
1866 TrimRead.trimByAmount(r2, 0, r2.length()-initialLen2, 1);
1867 }
1868 }
1869
1870 if(bestInsert>0){//Decided to merge
1871 if(trueOverlap>0 && trueOverlap<=8 && EXEMPT_SHORT_OVERLAPS_FROM_STATS) {
1872 //Temporarily ignore for purpose of training
1873 }else
1874 if(bestInsert==trueSize){
1875 correctCount++;
1876 insertSumCorrect+=bestInsert;
1877 }else{
1878 incorrectCount++;
1879 insertSumIncorrect+=bestInsert;
1880 }
1881
1882 r1.setInsert(bestInsert);
1883 insertMin=Tools.min(bestInsert, insertMin);
1884 insertMax=Tools.max(bestInsert, insertMax);
1885 hist[Tools.min(bestInsert, hist.length-1)]++;
1886 if(joinReads){
1887 r2.reverseComplement();
1888 joined=r1.joinRead(bestInsert);
1889 r2.reverseComplement();
1890 assert(joined.length()==bestInsert);
1891
1892 if(trimNonOverlapping){
1893 final int maxLen=Tools.max(initialLen1, initialLen2);
1894 if(bestInsert>=maxLen){//left trim originals, rl trim fused
1895 final int overlap=initialLen1+initialLen2-bestInsert;
1896 TrimRead.trimByAmount(joined, r1.length()-overlap, r2.length()-overlap, 1);
1897 }else{//right trim originals, no trim fused
1898 //Do nothing
1899 }
1900 }
1901
1902 }else if(ecco){
1903 r2.reverseComplement();
1904 errorCorrectWithInsert(r1, r2, bestInsert);
1905 r2.reverseComplement();
1906 errorsCorrectedT+=(r1.errors+r2.errors);
1907
1908 if(trimNonOverlapping){
1909 final int maxLen=Tools.max(initialLen1, initialLen2);
1910 if(bestInsert>=maxLen){//left trim originals, rl trim fused
1911 final int overlap=initialLen1+initialLen2-bestInsert;
1912 TrimRead.trimByAmount(r1, r1.length()-overlap, 0, 1);
1913 TrimRead.trimByAmount(r2, r2.length()-overlap, 0, 1);
1914 }else{//right trim originals, no trim fused
1915 final int overlap=bestInsert;
1916 if(r1.length()==overlap && r2.length()==overlap){
1917 //Do nothing, assuming they've already been trimmed.
1918 }else{
1919 TrimRead.trimByAmount(r1, 0, r1.length()-bestInsert, 1);
1920 TrimRead.trimByAmount(r2, 0, r2.length()-bestInsert, 1);
1921 }
1922 }
1923 }
1924
1925 }
1926 }else{
1927 if(bestInsert==RET_AMBIG){ambiguousCount++;}
1928 else if(bestInsert==RET_SHORT){tooShortCount++;}
1929 else if(bestInsert==RET_LONG){tooLongCount++;}
1930 else if(bestInsert==RET_NO_SOLUTION){noSolutionCount++;}
1931
1932 if(trueSize<initialLen1+initialLen2 && trueSize>0) {unmergedOverlappingCount++;}
1933 }
1934
1935 r1.setInsert(bestInsert);
1936
1937 if(findAdapterSequence && bestInsert>0 && bestInsert<r1.length()){
1938 storeAdapterSequence(r1, bestInsert);
1939 //r2.reverseComplement();
1940 storeAdapterSequence(r2, bestInsert);
1941 //outstream.println(new String(r2.bases));
1942 //r2.reverseComplement();
1943 }
1944
1945 if(originals!=null && (!ecco || bestInsert<1)){
1946 r1.bases=originals[0];
1947 r1.quality=originals[1];
1948 r2.bases=originals[2];
1949 r2.quality=originals[3];
1950 }
1951
1952 if(trimReadsByOverlap && bestInsert>0){
1953 int trimLim=bestInsert-1;
1954 if(trimLim<r1.length()){
1955 if(verbose){outstream.println("Overlap right trimming r1 to "+0+", "+(trimLim));}
1956 int x=TrimRead.trimToPosition(r1, 0, trimLim, 1);
1957 if(verbose){outstream.println("Trimmed "+x+" bases: "+new String(r1.bases));}
1958 }
1959 if(trimLim<r2.length()){
1960 if(verbose){outstream.println("Overlap right trimming r2 to "+0+", "+(trimLim));}
1961 int x=TrimRead.trimToPosition(r2, 0, trimLim, 1);
1962 if(verbose){outstream.println("Trimmed "+x+" bases: "+new String(r2.bases));}
1963 }
1964 }
1965
1966 if(parseCustom) {
1967
1968 final boolean fp=(bestInsert>0 && bestInsert!=trueSize);
1969 final boolean fn=(bestInsert<1 && trueOverlap>0);
1970 final boolean tp=(bestInsert>0 && bestInsert==trueSize);
1971 final boolean tn=(bestInsert<1 && trueOverlap<1);
1972
1973 assert((fp ? 1 : 0)+(fn ? 1 : 0)+(tp ? 1 : 0)+(tn ? 1 : 0)==1) :
1974 fp+", "+fn+", "+tp+", "+tn+", "+bestInsert+", "+trueOverlap+", "+trueSize+", "+(initialLen1+initialLen2);
1975 final boolean correct=(bestInsert==trueSize);
1976 if(MAKE_VECTOR) {
1977 FloatList fl=r2.fetchVector();
1978 if(fl.size==23) {fl.add((tp || fn) ? 1 : 0);}
1979 // assert(false) : fl;
1980 }
1981 if(TAG_CUSTOM) {
1982 ByteBuilder bb=r1.fetchBB();
1983 // bb.append("_tr").append(correct ? 1 : 0);
1984
1985 // if(correct) {//truth
1986 // bb.append(1);
1987 // }else {
1988 // bb.append(0);
1989 // }
1990 if(tp || fn) {//truth
1991 bb.append(1);
1992 }else {
1993 bb.append(0);
1994 }
1995
1996 if(trueOverlap>0 && trueOverlap<8 && EXEMPT_SHORT_OVERLAPS_FROM_STATS) {
1997 r1.nullifyObj();
1998 }
1999 }
2000
2001 if(ONLY_OUTPUT_INCORRECT && correct){
2002 if(TAG_CUSTOM) {r1.nullifyObj();}
2003 return bestInsert;
2004 }
2005
2006 // false, 231, 58, 231, 289
2007 assert(fn==(trueSize<initialLen1+initialLen2 && trueSize>0 && bestInsert<=0)) :
2008 fn+", "+bestInsert+", "+trueOverlap+", "+trueSize+", "+(initialLen1+initialLen2);
2009
2010 if((OUTPUT_FALSE_POSITIVE && fp) || (OUTPUT_FALSE_NEGATIVE && fn) ||
2011 (OUTPUT_TRUE_POSITIVE && tp) || (OUTPUT_TRUE_NEGATIVE && tn)){
2012 //Print
2013 }else{
2014 if(TAG_CUSTOM) {r1.nullifyObj();}
2015 return bestInsert;
2016 }
2017 }
2018
2019 if(bestInsert>0 || MIX_BAD_AND_GOOD){
2020 if(listg!=null){
2021 if(joined!=null){
2022 listg.add(joined);
2023 }else{
2024 listg.add(r1);
2025 }
2026 }
2027 }else if(listb!=null){
2028 listb.add(r1);
2029 }
2030 return bestInsert;
2031 }
2032
2033 private final int preprocess(final Read r1, final Read r2, boolean qtrim){
2034 assert(r1!=null);
2035 if(!r1.validated()){r1.validate(true);}
2036 if(r2==null){return RET_BAD;}
2037 if(!r2.validated()){r2.validate(true);}
2038
2039 if(iupacToN){
2040 if(r1!=null){r1.convertUndefinedTo((byte)'N');}
2041 if(r2!=null){r2.convertUndefinedTo((byte)'N');}
2042 }
2043
2044 if(recalibrateQuality){
2045 CalcTrueQuality.recalibrate(r1);
2046 CalcTrueQuality.recalibrate(r2);
2047 }
2048
2049 pairsProcessed++;
2050 basesProcessed+=r1.pairLength();
2051
2052 if(forceTrimLeft>0 || forceTrimRight>0 || forceTrimModulo>0 || forceTrimRight2>0){
2053 if(r1!=null && !r1.discarded()){
2054 final int len=r1.length();
2055 final int a=forceTrimLeft>0 ? forceTrimLeft : 0;
2056 final int b0=forceTrimModulo>0 ? len-1-len%forceTrimModulo : len;
2057 final int b1=forceTrimRight>0 ? forceTrimRight : len;
2058 final int b2=forceTrimRight2>0 ? len-1-forceTrimRight2 : len;
2059 final int b=Tools.min(b0, b1, b2);
2060 final int x=TrimRead.trimToPosition(r1, a, b, 1);
2061 }
2062 if(r2!=null && !r2.discarded()){
2063 final int len=r2.length();
2064 final int a=forceTrimLeft>0 ? forceTrimLeft : 0;
2065 final int b0=forceTrimModulo>0 ? len-1-len%forceTrimModulo : len;
2066 final int b1=forceTrimRight>0 ? forceTrimRight : len;
2067 final int b2=forceTrimRight2>0 ? len-1-forceTrimRight2 : len;
2068 final int b=Tools.min(b0, b1, b2);
2069 final int x=TrimRead.trimToPosition(r2, a, b, 1);
2070 }
2071 }
2072
2073 if(qtrim){qtrim(r1, r2, 0);}
2074
2075 if(tadpole!=null && extendRight1>0){
2076 extendAndMerge(r1, r2, extendRight1, 1, false, extendRvec);
2077 }
2078
2079 final int len1=r1.length(), len2=r2.length(); //Validated; these cannot be null.
2080
2081 if(len1<minReadLength && len2<minReadLength){
2082 return RET_BAD;
2083 }else if(len1<2 || len2<2){
2084 return RET_AMBIG;
2085 }
2086
2087 if(r1.quality!=null || r2.quality!=null){
2088 if(minAvgQuality>0){
2089 if(r1.avgQuality(false, minAvgQualityBases)<minAvgQuality || r2.avgQuality(false, minAvgQualityBases)<minAvgQuality){
2090 //Failed quality filter
2091 return RET_BAD;
2092 }
2093 }
2094 if(useMEEfilter && useQuality){
2095 int maxBasesToConsider=Tools.min(Tools.max(len1, len2), len1+len2-minInsert);
2096 if(r1.expectedTipErrors(false, maxBasesToConsider)>maxExpectedErrors || r2.expectedTipErrors(false, maxBasesToConsider)>maxExpectedErrors){
2097 //Failed MEEFilter
2098 return RET_BAD;
2099 }
2100 }
2101 }
2102 return 1;
2103 }
2104
2105 private final int extendAndMerge(Read r1, Read r2, int amt, int iters, boolean merge, int[] extendRvec){
2106 assert(iters>0);
2107 assert(merge || iters==1);
2108
2109 extendRvec[0]=extendRvec[1]=0;
2110
2111 int sum1=0, sum2=0, attempted=0;
2112 int bestInsert=RET_AMBIG;
2113 for(int i=0; i<iters && (bestInsert==RET_AMBIG || bestInsert==RET_NO_SOLUTION); i++){
2114
2115 int e1=(sum1==attempted ? extendRead(r1, amt) : 0);
2116 r2.reverseComplement();
2117 int e2=(sum2==attempted ? extendRead(r2, amt) : 0);
2118 r2.reverseComplement();
2119
2120 attempted+=amt;
2121 sum1+=e1;
2122 sum2+=e2;
2123
2124 if(merge){
2125 if(e1>0 || e2>0){
2126 bestInsert=processReadPair_inner(r1, r2);
2127 }else{
2128 break;
2129 }
2130 }
2131 }
2132 //Todo: un-extend.
2133
2134 extensionsAttemptedT+=2;
2135
2136 if(sum1==attempted){fullyExtendedT++;}
2137 else if(sum1>0){partlyExtendedT++;}
2138 else{notExtendedT++;}
2139
2140 if(sum2==attempted){fullyExtendedT++;}
2141 else if(sum2>0){partlyExtendedT++;}
2142 else{notExtendedT++;}
2143
2144 extendRvec[0]=sum1;
2145 extendRvec[1]=sum2;
2146
2147 return bestInsert;
2148 }
2149
2150 private final int extendRead(Read r, int amt){
2151 bbT.clear();
2152 bbT.append(r.bases);
2153 final int initialLen=r.length();
2154 final int extension=tadpole.extendToRight2(bbT, leftCounts, rightCounts, amt, false);
2155
2156 // extensionsAttemptedT++;
2157 // if(extension==amt){
2158 // fullyExtendedT++;
2159 // }else if(extension>0){
2160 // partlyExtendedT++;
2161 // }else{
2162 // notExtendedT++;
2163 // }
2164
2165 if(extension>0){
2166 r.bases=bbT.toBytes();
2167 if(r.quality!=null){
2168 r.quality=KillSwitch.copyOf(r.quality, r.bases.length);
2169 for(int i=initialLen; i<r.quality.length; i++){
2170 r.quality[i]=qfake;
2171 }
2172 }
2173 }
2174 return extension;
2175 }
2176
2177 private final int mateByOverlap_ratioMode(Read r1, Read r2, int minOverlap){
2178 assert(useRatioMode);
2179 int min0=MIN_OVERLAPPING_BASES_0-MIN_OVERLAPPING_BASES_RATIO_REDUCTION;
2180 int min=minOverlap-MIN_OVERLAPPING_BASES_RATIO_REDUCTION;
2181 int x=-1;
2182 rvector[4]=0;
2183
2184 float ratioMargin=RATIO_MARGIN;
2185 float maxRatio=MAX_RATIO;
2186 float minSecondRatio=MIN_SECOND_RATIO;
2187
2188 boolean overlapped=false;
2189 // assert(false) : overlapUsingQuality+", "+(r1.quality!=null)+", "+(r2.quality!=null);
2190 if(overlapUsingQuality && r1.quality!=null && r2.quality!=null){
2191 overlapped=true;
2192 x=BBMergeOverlapper.mateByOverlapRatio(r1, r2, aprob, bprob, rvector,
2193 min0, min, minInsert0, minInsert, maxRatio, minSecondRatio, ratioMargin, RATIO_OFFSET, 0.95f, 0.95f, true);
2194 if(verbose){outstream.println("Result from ratiomode1: \tinsert="+x+", bad="+rvector[2]+", ambig="+(rvector[4]==1));}
2195 }
2196 if(((!TAG_CUSTOM) || !overlapUsingQuality) && (!overlapped || (overlapWithoutQuality && (x<0 || rvector[4]==1)))){
2197 int x2=BBMergeOverlapper.mateByOverlapRatio(r1, r2, aprob, bprob, rvector, min0, min,
2198 minInsert0, minInsert, maxRatio, minSecondRatio, ratioMargin, RATIO_OFFSET, 0.95f, 0.95f, false);
2199 if(verbose){outstream.println("Result from ratiomode2: \tinsert="+x+", bad="+rvector[2]+", ambig="+(rvector[4]==1));}
2200 x=x2;
2201 // if(x<0 || (x2>0 && rvector[4]==0)) { //Basically I want to keep the old info if it still didn't overlap...
2202 }
2203 return x;
2204 }
2205
2206 private final int mateByOverlap_flatMode(Read r1, Read r2, int minOverlap){
2207 final int len1=r1.length(), len2=r2.length();
2208 boolean ambigNM=false;
2209 int bestInsertNM=-1;
2210 int bestBadNM=999999;
2211
2212 assert(QUAL_ITERS>0);
2213 final int maxQualIters=(r1.quality==null || r2.quality==null ? 1 : QUAL_ITERS);
2214 final int maxTrims=(r1.quality==null || r2.quality==null ? 0 : TRIM_ON_OVERLAP_FAILURE);
2215
2216 for(int i=0; i<maxQualIters && bestInsertNM<0 /*&& !ambigNM*/; i++){
2217
2218 int x=BBMergeOverlapper.mateByOverlap(r1, r2, aprob, bprob, rvector, MIN_OVERLAPPING_BASES_0-i, minOverlap+i,
2219 minInsert0, MISMATCH_MARGIN, MAX_MISMATCHES0, MAX_MISMATCHES, (byte)(MIN_QUALITY-2*i));
2220 if(x>-1){
2221 bestInsertNM=x;
2222 bestBadNM=rvector[2];
2223 ambigNM=(rvector[4]==1);
2224 break;
2225 }
2226 }
2227
2228
2229 if(loose && bestInsertNM<0){//TODO check for estimated number of overlap errors
2230 int x=BBMergeOverlapper.mateByOverlap(r1, r2, aprob, bprob, rvector, MIN_OVERLAPPING_BASES_0-1, minOverlap+2,
2231 minInsert0, MISMATCH_MARGIN, MAX_MISMATCHES0+1, MAX_MISMATCHES+1, MIN_QUALITY-1);
2232 if(x>-1){
2233 bestInsertNM=x;
2234 bestBadNM=rvector[2];
2235 ambigNM=(rvector[4]==1);
2236 }
2237 }
2238
2239 for(int trims=0, q=(int)trimq[0]; trims<maxTrims && !qtrim1 && bestInsertNM<0 /*&& !ambigNM*/; trims++, q+=8){
2240 float e=QualityTools.PROB_ERROR[q];
2241 int tr1=TrimRead.trimFast(r1, false, true, q, e, 1+len1*4/10); //r1.length());
2242 int tr2=TrimRead.trimFast(r2, true, false, q, e, 1+len2*4/10); //r2.length());
2243 if(tr1>0 || tr2>0){
2244 int x=BBMergeOverlapper.mateByOverlap(r1, r2, aprob, bprob, rvector, MIN_OVERLAPPING_BASES_0-1, minOverlap,
2245 minInsert0, MISMATCH_MARGIN, MAX_MISMATCHES0, MAX_MISMATCHES, MIN_QUALITY);
2246 if(x>-1){
2247 bestInsertNM=x;
2248 bestBadNM=rvector[2];
2249 ambigNM=(rvector[4]==1);
2250 trims=maxTrims;
2251 }
2252 }
2253 }
2254 if(verbose){outstream.println("Result from flatmode: \tinsert="+bestInsertNM+", bad="+bestBadNM+", ambig="+ambigNM);}
2255
2256 rvector[0]=bestInsertNM;
2257 rvector[2]=bestBadNM;
2258 rvector[4]=(ambigNM ? 1 : 0);
2259 return bestInsertNM;
2260 }
2261
2262 private final int calcMinOverlapFromEntropy(final Read r1, final Read r2){
2263 if(!useEntropy){return MIN_OVERLAPPING_BASES;}
2264 final int minOverlap;
2265 if(loose){
2266 final int len1=r1.length(), len2=r2.length();
2267 int a=BBMergeOverlapper.calcMinOverlapByEntropy(r1.bases, entropyK, kmerCounts, minEntropyScore);
2268 int b=BBMergeOverlapper.calcMinOverlapByEntropy(r2.bases, entropyK, kmerCounts, minEntropyScore);
2269 float errorRate=r1.expectedErrors(false, len1)/len1+r2.expectedErrors(false, len2)/len2;
2270 minOverlap=(int)(Tools.max(MIN_OVERLAPPING_BASES, Tools.max(a, b))*(1+Tools.min(0.04f, errorRate)*4f));
2271 }else{
2272 int a=BBMergeOverlapper.calcMinOverlapByEntropyTail(r1.bases, entropyK, kmerCounts, minEntropyScore);
2273 int b=BBMergeOverlapper.calcMinOverlapByEntropyHead(r2.bases, entropyK, kmerCounts, minEntropyScore);
2274 minOverlap=Tools.max(MIN_OVERLAPPING_BASES, Tools.max(a, b));
2275 }
2276 return minOverlap;
2277 }
2278
2279 private final int lookForAdapters(final Read r1, final Read r2){
2280 assert(lowercaseAdapters);
2281 if(!lowercaseAdapters){return -1;}
2282 if(!Tools.isLowerCase(r1.bases[r1.length()-1]) || !Tools.isLowerCase(r2.bases[0])){return -1;}
2283
2284 final int lower1=r1.trailingLowerCase(), lower2=r2.leadingLowerCase();
2285
2286 final int upper1=r1.length()-lower1, upper2=r2.length()-lower2;
2287 final int newlen=Tools.min(upper1, upper2);
2288 int good=0, bad=0;
2289
2290 for(int i=0; i<newlen; i++){
2291 byte a=r1.bases[i];
2292 byte b=r2.bases[i+lower2];
2293 if(a!='N' && b!='N'){
2294 if(a==b){good++;}
2295 else{bad++;}
2296 }
2297 }
2298 if(bad*4<=good){
2299 rvector[0]=newlen;
2300 rvector[2]=bad;
2301 rvector[4]=0;
2302 return newlen;
2303 }
2304 return -1;
2305 }
2306
2307 private final int mateByOverlap(Read r1, Read r2){
2308 final int len1=r1.length(), len2=r2.length();
2309 assert(r1.fetchObject()==null);
2310 final ByteBuilder bb=(TAG_CUSTOM ? new ByteBuilder(32) : null);
2311 if(bb!=null) {r1.setObj(bb);}
2312 if(MAKE_VECTOR && r2.obj==null) {
2313 if(r2.obj==null) {r2.setObj(new FloatList(24));}
2314 else{((FloatList)r2.obj).clear();}
2315 }
2316 final FloatList vector=(FloatList) r2.obj;
2317
2318 final int minOverlap=calcMinOverlapFromEntropy(r1, r2);
2319 if(verbose){outstream.println("\nminOverlap: "+minOverlap);}
2320 if(TAG_CUSTOM || MAKE_VECTOR){
2321 int maxBasesToConsider=Tools.min(Tools.max(len1, len2), len1+len2-minInsert);
2322 float r1ee=r1.expectedTipErrors(false, maxBasesToConsider);
2323 float r2ee=r2.expectedTipErrors(false, maxBasesToConsider);
2324 if(TAG_CUSTOM) {
2325 bb.append(minOverlap*0.1f, 1).tab();
2326 bb.append(Tools.format("%.4f\t%.4f\t", r1ee, r2ee));
2327 }
2328 if(MAKE_VECTOR) {
2329 vector.add(minOverlap*0.1f); //mo
2330 vector.add(r1ee);
2331 vector.add(r2ee);
2332 }
2333 }
2334 // //TODO: Currently this is not used for anything.
2335 // final int bestInsertAD;
2336 // final int bestBadAD;
2337 // if(lowercaseAdapters){
2338 // bestInsertAD=lookForAdapters(r2, r2);
2339 // bestBadAD=(bestInsertAD>=0 ? rvector[2] : 0);
2340 // }
2341
2342 if(aprob==null || aprob.length<Tools.max(len1, len2)){aprob=new float[Tools.max(len1, len2)];}
2343 if(bprob==null || bprob.length<Tools.max(len1, len2)){bprob=new float[Tools.max(len1, len2)];}
2344
2345 final boolean ambigRM;
2346 final int bestBadRM, bestInsertRM;
2347 if(useRatioMode){
2348 bestInsertRM=mateByOverlap_ratioMode(r1, r2, minOverlap);
2349 // assert(!TAG_CUSTOM || bestInsertRM>0) : bestInsertRM;
2350 bestBadRM=rvector[2];
2351 ambigRM=(bestInsertRM>-1 ? rvector[4]==1 : false);
2352 // assert(false) : bestBadRM+", "+bestInsertRM+", "+Arrays.toString(rvector);
2353 }else{
2354 bestInsertRM=-1;
2355 bestBadRM=0;
2356 ambigRM=false;
2357 }
2358 if(verbose){System.err.println("A: "+ambigRM+", "+bestInsertRM);}
2359 final boolean ambigNM;
2360 final int bestInsertNM, bestBadNM;
2361 if(useFlatMode && ((!requireRatioMatch && (bestInsertRM<0 || ambigRM)) ||
2362 (requireRatioMatch && (bestInsertRM>0 && !ambigRM)))){
2363 bestInsertNM=mateByOverlap_flatMode(r1, r2, minOverlap);
2364 bestBadNM=rvector[2];
2365 ambigNM=(bestInsertNM>-1 ? rvector[4]==1 : false);
2366 if(verbose){System.err.println("A1: "+bestInsertNM);}
2367 }else{
2368 ambigNM=false;
2369 bestInsertNM=-1;
2370 bestBadNM=99999;
2371 if(verbose){System.err.println("A2: "+bestInsertNM);}
2372 }
2373
2374 boolean ambig;
2375 int bestBad, bestInsert;
2376 if(requireRatioMatch && useFlatMode && useRatioMode){
2377 ambig=ambigRM || ambigNM;
2378 bestBad=bestBadRM;
2379 bestInsert=(bestInsertNM==bestInsertRM ? bestInsertNM : -1);
2380
2381 if(verbose){outstream.println("Result after rrm: \tinsert="+bestInsertNM+", bad="+bestBadNM+", ambig="+ambigNM);}
2382 if(verbose){System.err.println("A3: "+bestInsert);}
2383 }else if(useRatioMode && bestInsertRM>-1 && !ambigRM){
2384 ambig=ambigRM;
2385 bestBad=bestBadRM;
2386 bestInsert=bestInsertRM;
2387 if(verbose){System.err.println("A4: "+bestInsert);}
2388 }else{
2389 ambig=ambigNM;
2390 bestBad=bestBadNM;
2391 bestInsert=bestInsertNM;
2392 if(verbose){System.err.println("A5: "+bestInsert);}
2393 }
2394 if(verbose){System.err.println("B: "+ambig+", "+bestInsert+", "+bestInsertRM);}
2395
2396 if((TAG_CUSTOM || MAKE_VECTOR) && bestInsert<0){bestInsert=bestInsertRM;}
2397
2398 if(bestBad>MAX_MISMATCHES_R){ambig=true;}
2399 if(verbose){System.err.println("B2: "+ambig+", "+bestInsert+", "+bestBad+", "+MAX_MISMATCHES_R);}
2400
2401 if((!TAG_CUSTOM && !MAKE_VECTOR) || ONLY_OUTPUT_FALSE_POSITIVE){
2402 if(ambig){return RET_AMBIG;}
2403 else if(bestInsert<0){return RET_NO_SOLUTION;}
2404 }
2405 // assert(false) : vector.size;
2406 //TODO: Crucial! This block can vastly reduce merge rate, particularly if quality values are inaccurate.
2407 if(useQuality && r1.quality!=null && r2.quality!=null){
2408 if(useEfilter && bestInsert>0 && (!ambig || TAG_CUSTOM || MAKE_VECTOR)){
2409 float bestExpected=BBMergeOverlapper.expectedMismatches(r1, r2, bestInsert);
2410 if((bestExpected+efilterOffset)*efilterRatio<bestBad){ambig=true;}
2411
2412 if(verbose){outstream.println("Result after efilter: \tinsert="+bestInsert+", bad="+bestBad+", ambig="+ambig);}
2413 if(TAG_CUSTOM){
2414 // bb.append("_be=f");
2415 bb.append(bestExpected, 4).tab();
2416 }
2417 if(MAKE_VECTOR){
2418 vector.add(bestExpected); //be
2419 }
2420 }
2421 if(verbose){System.err.println("C: "+ambig+", "+bestInsert);}
2422
2423 if(pfilterRatio>0 && bestInsert>0 && (!ambig || TAG_CUSTOM || MAKE_VECTOR)){
2424 float probability=BBMergeOverlapper.probability(r1, r2, bestInsert);
2425 if(probability<pfilterRatio && ((!TAG_CUSTOM && !MAKE_VECTOR) || ONLY_OUTPUT_FALSE_POSITIVE)){bestInsert=-1;}
2426 if(verbose){outstream.println("Result after pfilter: \tinsert="+bestInsert+", bad="+bestBad+", ambig="+ambig);}
2427 double p=Math.sqrt(probability)+0.0000015;
2428 if(TAG_CUSTOM){
2429 bb.append(p, 6).tab();
2430 }
2431 if(MAKE_VECTOR){
2432 vector.add((float)p);//pr
2433 }
2434 }else if(MAKE_VECTOR) {
2435 vector.add(0.1f);//For some reason this gets left off occasionally...
2436 }
2437 if(verbose){System.err.println("D: "+ambig+", "+bestInsert);}
2438 }
2439 if(verbose){System.err.println("E: "+ambig+", "+bestInsert);}
2440
2441 //TODO: Uncomment.
2442 // if(TAG_CUSTOM && !ONLY_OUTPUT_FALSE_POSITIVE) {
2443 // assert(!TAG_CUSTOM || bestInsert>0) : bestInsert;
2444 // return bestInsert;
2445 // }
2446 //
2447 // if(ambig){return RET_AMBIG;}
2448 r1.errors=bestBad;
2449
2450 if(MAKE_VECTOR && bestInsert>0 && r2.obj()!=null) {
2451 FloatList list=r2.fetchVector();
2452 if(list.size!=23) {
2453 System.err.println("\n"+r1.numericID+", "+r1.obj());
2454 System.err.println("*"+list.size+", "+parseCustom+", "+r1.numericID+", "+list);
2455 assert(false);
2456 }else {
2457 // System.err.println(list.size+", "+parseCustom+", "+r1.numericID+", "+list);
2458 // assert((list.size()==23 && !parseCustom) || (list.size()==24 && parseCustom)) :
2459 // list.size+", "+parseCustom+", "+r1.numericID+", "+list;
2460 assert(list.size()==23) :
2461 list.size+", "+parseCustom+", "+r1.numericID+", "+list;
2462 net.applyInput(list);
2463 float result=net.feedForward();
2464 // System.err.println(list);
2465 // System.err.println(r1.obj);
2466
2467 // System.err.println("\n"+r1.numericID+", "+r1.obj());
2468 // System.err.println(r1.numericID+", "+list);
2469 // System.err.println(result);
2470
2471 // if(parseCustom){
2472 // final int trueSize=parseCustom ? parseInsert(r1, r2) : -1;
2473 // final int initialLen1=r1.length(), initialLen2=r2.length();
2474 // final int minReadLen=Tools.min(initialLen1, initialLen2), lenSum=initialLen1+initialLen2;
2475 // final int trueOverlap=Tools.min(trueSize, minReadLen, lenSum-trueSize);
2476 //
2477 // System.err.println(r1.numericID+", "+result+", "+netCutoff+", "+
2478 // (trueOverlap>0)+", "+trueOverlap);
2479 // }
2480
2481 if(result<netCutoff){
2482 return RET_AMBIG;
2483 }
2484 }
2485 }
2486
2487 return bestInsert>0 ? bestInsert : RET_NO_SOLUTION;
2488 }
2489
2490 private final int parseInsert(Read r1, Read r2){
2491 int trueSize=-1;
2492 if(r1.id.startsWith("SYN")){
2493 CustomHeader h=new CustomHeader(r1.id, 0);
2494 trueSize=h.insert;
2495 }else if(r1.id.startsWith("insert=")){
2496 trueSize=GradeMergedReads.parseInsert(r1.id);
2497 }else{
2498 r1.setMapped(true);
2499 r2.setMapped(true);
2500 trueSize=Read.insertSizeMapped(r1, r2, false);
2501 assert(trueSize>0) : "Can't parse insert size.";
2502 }
2503 if(verbose){outstream.println("True Insert: "+trueSize);}
2504 // r1.setInsert(trueSize);
2505 return trueSize;
2506 }
2507
2508 private boolean verifyAdapters(Read r1, Read r2, int bestInsert){
2509 final int minAdapterOverlap=3;
2510 final int len1=r1.length(), len2=r2.length();
2511 if(Tools.max(len1, len2)-minAdapterOverlap<bestInsert){return true;}
2512
2513 int good=0, bad=0, invalid=0;
2514 final float minAdapterRatio=0.6f;
2515 {
2516 final int adapterLen=len1-bestInsert;
2517 if(adapterList1!=null && good<1 && adapterLen>=minAdapterOverlap){
2518 if(adapterLen>=minAdapterOverlap){
2519 adaptersExpectedT++;
2520 for(byte[] adapter : adapterList1){
2521 int aiv=adapterIsValid(r1, adapter, bestInsert, minAdapterOverlap, minAdapterRatio);
2522 if(aiv==2){good++; break;}
2523 else if(aiv==1){invalid++;}
2524 else{bad++;}
2525 }
2526 }
2527 }
2528 }
2529 {
2530 final int adapterLen=len2-bestInsert;
2531 if(adapterList2!=null && good<1 && adapterLen>=minAdapterOverlap){
2532 if(adapterLen>=minAdapterOverlap){
2533 adaptersExpectedT++;
2534 r2.reverseComplement();
2535 for(byte[] adapter : adapterList2){
2536 int aiv=adapterIsValid(r2, adapter, bestInsert, minAdapterOverlap, minAdapterRatio);
2537 if(aiv==2){good++; break;}
2538 else if(aiv==1){invalid++;}
2539 else{bad++;}
2540 }
2541 r2.reverseComplement();
2542 }
2543 }
2544 }
2545 if(good>0){
2546 adaptersFoundT+=good;
2547 return true;
2548 }else if(bad>0){
2549 return false;
2550 }else if(invalid>0 && strict){
2551 return false;
2552 }
2553 return true;
2554 }
2555
2556 /**
2557 *
2558 * @param r1 Read1
2559 * @param r2 Read2
2560 * @return A return code (RET_)
2561 */
2562 private final int processReadPair(final Read r1, final Read r2){
2563 final int initialLen1=r1.length(), initialLen2=r2.length();
2564 {
2565 final int x=preprocess(r1, r2, (qtrim1 && !qtrim2));
2566 if(!TAG_CUSTOM && !MAKE_VECTOR && x<0){return x;}
2567 }
2568
2569 r2.reverseComplement();
2570
2571 byte[] qual1=r1.quality, qual2=r2.quality;
2572 if(!useQuality){//strip qualities
2573 r1.quality=r2.quality=null;
2574 }
2575
2576 final int bestInsert0=processReadPair_inner(r1, r2);
2577 int bestInsert=bestInsert0;
2578 assert(!TAG_CUSTOM || ONLY_OUTPUT_FALSE_POSITIVE || MAKE_VECTOR || bestInsert>0) : bestInsert;
2579 if(qtrim2){
2580 for(int iter=0; iter<trimq.length && bestInsert<0; iter++){
2581 r1.quality=qual1;
2582 r2.quality=qual2;
2583 // r2.reverseComplement();
2584 // qtrim(r1, r2);
2585 // r2.reverseComplement();
2586
2587 TrimRead.trimFast(r1, qtrimLeft, qtrimRight, trimq[iter], trimE[iter], 1);
2588 TrimRead.trimFast(r2, qtrimRight, qtrimLeft, trimq[iter], trimE[iter], 1);//Reversed because read is rcomped
2589
2590 qual1=r1.quality;
2591 qual2=r2.quality;
2592 bestInsert=processReadPair_inner(r1, r2);
2593 }
2594 }
2595
2596 //assert(false) : bestInsert+", "+r1.length()+", "+r2.length();
2597 final boolean foundAdapter;
2598 // final ByteBuilder bb=(TAG_CUSTOM ? r1.fetchBB() : null);
2599 if(verifyAdapters && bestInsert>0 && (extendRight1<1 || bestInsert<initialLen1 || bestInsert<initialLen2)){
2600 foundAdapter=verifyAdapters(r1, r2, bestInsert);
2601 // if(TAG_CUSTOM) {bb.append(foundAdapter ? "fa_1" : "fa_0");}
2602 if(!foundAdapter){
2603 if(!useQuality){//restore qualities
2604 restoreQualities(r1, r2, qual1, qual2);
2605 }
2606 assert(r1.quality==null || (r1.quality.length==r1.bases.length && r2.quality.length==r2.bases.length));
2607 r2.reverseComplement();
2608 return RET_NO_SOLUTION;
2609 }
2610 }else{
2611 foundAdapter=false;
2612 // if(TAG_CUSTOM) {bb.append("fa_0.5");}
2613 }
2614
2615 //Kmer processing - correction and extension
2616 if(tadpole!=null){
2617
2618 //Correction
2619 boolean corrected=false;
2620 if(eccTadpole /*&& !requireExtensionMatch*/ && (bestInsert==RET_AMBIG || bestInsert==RET_NO_SOLUTION)){
2621 int c1=tadpole.errorCorrect(r1);
2622 int c2=tadpole.errorCorrect(r2);
2623 corrected=true;
2624 if(c1>0 || c2>0){
2625 bestInsert=processReadPair_inner(r1, r2);
2626 }
2627 }
2628
2629 //Extension
2630 if(extendRight2>0 && (requireExtensionMatch || bestInsert==RET_AMBIG || bestInsert==RET_NO_SOLUTION)
2631 && !(requireStrictExtensionMatch && bestInsert<1)){
2632 final int lengthSum=r1.pairLength();
2633 final int approxMaxOverlappingInsert=lengthSum-minApproxOverlapRem;
2634 final int minExt=Tools.min(12, extendRight2*2);
2635 int bestInsertE=extendAndMerge(r1, r2, extendRight2, extendIterations, true, extendRvec);
2636 int extension1=extendRvec[0], extension2=extendRvec[1];
2637 int extension=extension1+extension2;
2638
2639 // assert(r1.length()==150+extension1) : extension1+", "+r1.length();
2640
2641 //If extension failed, try correction and extend again
2642 if(eccTadpole && requireExtensionMatch && !corrected && extension<=extendRight2/* *2 */ &&
2643 (extension==0 || (!strict && bestInsert<0 && bestInsertE<0) || (bestInsert>0 && bestInsertE==bestInsert))){
2644 int c1=0, c2=0;
2645 if(extension1==0){c1=tadpole.errorCorrect(r1);}
2646 if(extension2==0){c2=tadpole.errorCorrect(r2);}
2647
2648 //If there were any corrections
2649 if(c1>0 || c2>0){
2650 //Un-extend r1
2651 if(extension1>0){TrimRead.trimToPosition(r1, 0, r1.length()-extension1-1, 1);}
2652 //Un-extend r2
2653 if(extension2>0){TrimRead.trimToPosition(r2, extension2, r2.length()-1, 1);}
2654
2655 //Retry extension
2656 bestInsertE=extendAndMerge(r1, r2, extendRight2, extendIterations, true, extendRvec);
2657 extension1=extendRvec[0];
2658 extension2=extendRvec[1];
2659 extension=extension1+extension2;
2660 }
2661 }
2662
2663 // if(extension==0 && eccTadpole && !corrected){
2664 // int c1=tadpole.errorCorrect(r1);
2665 // int c2=tadpole.errorCorrect(r2);
2666 // corrected=true;
2667 // if(c1>0 || c2>0){
2668 // bestInsertE=extendAndMerge(r1, r2, extendRight2, extendIterations, true, extendRvec);
2669 // extension=extendRvec[0]+extendRvec[1];
2670 // }
2671 // }
2672
2673 if(requireExtensionMatch && extension>0){
2674 if(bestInsert!=bestInsertE){
2675 if(bestInsert>0){bestInsert=RET_AMBIG;}//There was an unextended overlap, not matching extended overlap
2676 else if(!requireStrictExtensionMatch && bestInsertE>0){//Extended had an overlap, but unextended did not
2677 if(bestInsertE>approxMaxOverlappingInsert && extension>=minExt){//Use only if the extended overlap was too long to see before
2678 bestInsert=bestInsertE;
2679 }
2680 }
2681 }
2682 }else if(bestInsertE>0){
2683 assert(bestInsert<0);
2684 bestInsert=bestInsertE;
2685 }
2686 }
2687
2688 if(testMerge && bestInsert>0 && bestInsert>=r1.length()+testMergeWidth && bestInsert>=r2.length()+testMergeWidth){
2689 Read merged=r1.joinRead(bestInsert);
2690 if(!tadpole.mergeOK(merged, initialLen1, initialLen2, mergeOKBitsetT, countList, kmerT, testMergeWidth, testMergeThresh, testMergeMult)){
2691 bestInsert=RET_NO_SOLUTION;
2692 }
2693 }
2694 }else if(bloomFilter!=null){
2695 if(eccBloom && (bestInsert==RET_AMBIG || bestInsert==RET_NO_SOLUTION)){
2696 int c1=corrector.errorCorrect(r1);
2697 int c2=corrector.errorCorrect(r2);
2698 if(c1>0 || c2>0){
2699 bestInsert=processReadPair_inner(r1, r2);
2700 }
2701 }
2702
2703 if(testMerge && bestInsert>0 && bestInsert>=r1.length()+testMergeWidth && bestInsert>=r2.length()+testMergeWidth){
2704 Read merged=r1.joinRead(bestInsert);
2705 if(!corrector.mergeOK(merged, initialLen1, initialLen2, kmers, testMergeWidth, testMergeThresh, testMergeMult)){bestInsert=RET_NO_SOLUTION;}
2706 }
2707 }
2708
2709 if(verifyAdapters && !foundAdapter && bestInsert>0 && (extendRight1<1 || bestInsert<initialLen1 || bestInsert<initialLen2)){
2710 boolean x=verifyAdapters(r1, r2, bestInsert);
2711 if(!x){bestInsert=RET_NO_SOLUTION;}
2712 }
2713
2714 // assert(bestInsert<0 || bestInsert>=50) : bestInsert+", "+foundAdapter;
2715
2716 if(useKFilter && bestInsert>kmerLength){
2717 Read joined=r1.joinRead(bestInsert);
2718 if(useKFilter){
2719 int cov1=BBMergeOverlapper.minCoverage(r1, tadpole, kmerLength, filterCutoff+1);
2720 int cov2=(cov1>filterCutoff ? BBMergeOverlapper.minCoverage(r2, tadpole, kmerLength, filterCutoff+1) : cov1);
2721 if(cov1>filterCutoff && cov2>filterCutoff){
2722 int cov=BBMergeOverlapper.minCoverage(joined, tadpole, kmerLength, filterCutoff);
2723 if(cov<filterCutoff){bestInsert=RET_NO_SOLUTION;}
2724 if(verbose){outstream.println("Result after kfilter: \tinsert="+bestInsert);}
2725 }
2726 }
2727 }
2728
2729 if(!useQuality){//restore qualities
2730 restoreQualities(r1, r2, qual1, qual2);
2731 }
2732 r2.reverseComplement();
2733 assert(r1.quality==null || (r1.quality.length==r1.bases.length && r2.quality.length==r2.bases.length));
2734 return bestInsert;
2735 }
2736
2737 private void restoreQualities(Read r1, Read r2, byte[] qual1, byte[] qual2){
2738 final int len1=r1.length(), len2=r2.length();
2739 r1.quality=qual1;
2740 r2.quality=qual2;
2741 final byte qf=Shared.FAKE_QUAL;
2742 if(qual1.length!=len1){
2743 r1.quality=Arrays.copyOf(qual1, len1);
2744 for(int i=len1; i<r1.quality.length; i++){
2745 r1.quality[i]=qf;
2746 }
2747 }
2748 if(qual2.length!=len2){
2749 r2.reverseComplement();
2750 r2.quality=Arrays.copyOf(qual2, len2);
2751 for(int i=len2; i<r2.quality.length; i++){
2752 r2.quality[i]=qf;
2753 }
2754 r2.reverseComplement();
2755 }
2756 }
2757
2758 /**
2759 *
2760 * @param r1 Read1
2761 * @param r2 Read2
2762 * @return A return code (RET_)
2763 */
2764 private final int processReadPair_inner(final Read r1, final Read r2){
2765 int bestInsert=-1;
2766 boolean ambig;
2767
2768 if(USE_MAPPING && r1.chrom==r2.chrom && r1.start<r1.stop && ((r1.mapped() || r1.synthetic())
2769 && (r2.mapped() || r2.synthetic()))){
2770 bestInsert=r1.insert();
2771 ambig=false;
2772 }else{
2773 if(MATE_BY_OVERLAP){
2774 bestInsert=mateByOverlap(r1, r2);
2775 assert(!TAG_CUSTOM || ONLY_OUTPUT_FALSE_POSITIVE || MAKE_VECTOR || bestInsert>0) : bestInsert;
2776 ambig=(bestInsert==RET_AMBIG);
2777 }else{
2778 ambig=false;
2779 bestInsert=-1;
2780 }
2781 }
2782
2783 if((TAG_CUSTOM) && !ONLY_OUTPUT_FALSE_POSITIVE) {return bestInsert;}
2784 if(ambig && !MAKE_VECTOR){return RET_AMBIG;}
2785 else if(bestInsert>0){
2786 if(bestInsert<minInsert){return RET_SHORT;}
2787 else if(bestInsert>maxReadLength){return RET_LONG;}
2788 return bestInsert;
2789 }
2790 else{return RET_NO_SOLUTION;}
2791 }
2792
2793 private void storeAdapterSequence(Read r, int insert){
2794 atrackT.storeAdapterSequence(r, insert);
2795 // if(ignorePhixAdapters){
2796 // if(looksLikePhix(r, insert)){return;}
2797 // }
2798 //
2799 // LongList[] lists=adapterCountsT[r.pairnum()];
2800 // byte[] bases=r.bases;
2801 //
2802 // for(int i=insert, j=0; i<bases.length; i++, j++){
2803 // byte b=bases[i];
2804 // int num=AminoAcid.baseToNumber[b];
2805 // if(num>=0){
2806 // lists[num].increment(j);
2807 // }
2808 // }
2809 }
2810
2811 private boolean looksLikePhix(Read r, int insert){
2812 return looksLikePhix(r.bases, insert) || looksLikePhix(r.mate.bases, insert);
2813 }
2814
2815 private boolean looksLikePhix(byte[] bases, int insert){
2816 int len=bases.length-insert;
2817 if(len<phixPrefix.length){return false;}
2818 for(int i=insert, j=0; i<bases.length && j<phixPrefix.length; i++, j++){
2819 byte b=bases[i];
2820 if(b!='N' && b!=phixPrefix[j]){
2821 return false;
2822 }
2823 }
2824 outstream.println(new String(bases).substring(insert));
2825 outstream.println(new String(phixPrefix));
2826 return true;
2827 }
2828
2829 /*--------------------------------------------------------------*/
2830
2831 // final LongList[][] adapterCountsT=new LongList[2][4];
2832 final AdapterTracker atrackT=new AdapterTracker();
2833
2834 private final BitSet mergeOKBitsetT=new BitSet(400);
2835 private final Kmer kmerT;
2836 private IntList countList=new IntList();
2837 private LongList kmers=new LongList();
2838
2839 final byte qfake=Shared.FAKE_QUAL;
2840
2841 private final int[] rvector=KillSwitch.allocInt1D(5);
2842 private final int[] extendRvec=KillSwitch.allocInt1D(2);
2843
2844 private final int[] rightCounts=KillSwitch.allocInt1D(4);
2845 private final int[] leftCounts=(extendThroughLeftJunctions ? null : new int[4]);
2846
2847 private final ByteBuilder bbT=new ByteBuilder();
2848
2849 final long[] hist=new long[histlen];
2850 final short[] kmerCounts;
2851
2852 private float[] aprob, bprob;
2853
2854 long errorsCorrectedT=0;
2855
2856 long pairsProcessed=0;
2857 long basesProcessed=0;
2858 long matedCount=0;
2859 long correctCount=0;
2860 long unmergedOverlappingCount=0;
2861 long ambiguousCount=0;
2862 long tooShortCount=0;
2863 long tooLongCount=0;
2864 long incorrectCount=0;
2865 long noSolutionCount=0;
2866 long insertSumCorrect=0;
2867 long insertSumIncorrect=0;
2868 int insertMax=0;
2869 int insertMin=999999999;
2870
2871 long fullyExtendedT=0;
2872 long partlyExtendedT=0;
2873 long notExtendedT=0;
2874 long extensionsAttemptedT=0;
2875
2876 long adaptersExpectedT=0;
2877 long adaptersFoundT=0;
2878
2879 private final ConcurrentReadInputStream cris;
2880 private final ConcurrentReadOutputStream rosgood;
2881 private final ConcurrentReadOutputStream rosbad;
2882 private final ConcurrentReadOutputStream rosi;
2883
2884 private final boolean joinReads;
2885 private final boolean trimReadsByOverlap;
2886
2887 private final CellNet net;
2888 }
2889
2890 /*--------------------------------------------------------------*/
2891
2892 public static void resetCounters(){
2893
2894 Arrays.fill(histTotal, 0);
2895
2896 readsProcessedTotal=0;
2897 basesProcessedTotal=0;
2898 matedCountTotal=0;
2899 correctCountTotal=0;
2900 ambiguousCountTotal=0;
2901 tooShortCountTotal=0;
2902 tooLongCountTotal=0;
2903 incorrectCountTotal=0;
2904 noSolutionCountTotal=0;
2905 insertSumCorrectTotal=0;
2906 insertSumIncorrectTotal=0;
2907 fullyExtendedTotal=0;
2908 partlyExtendedTotal=0;
2909 notExtendedTotal=0;
2910 extensionsAttempted=0;
2911 adaptersExpected=0;
2912 adaptersFound=0;
2913
2914 insertMinTotal=999999999;
2915 insertMaxTotal=0;
2916 }
2917
2918 private static synchronized void loadNet(String fname) {
2919 if(fname==null) {
2920 netFile=null;
2921 net0=null;
2922 return;
2923 }
2924 if(netFile!=null && netFile.equals(fname) && net0!=null){
2925 return;
2926 }
2927 netFile=fname;
2928 net0=CellNetParser.load(netFile);
2929 netCutoff=(setCutoff ? netCutoff : net0.cutoff);
2930 }
2931
2932 /*--------------------------------------------------------------*/
2933
2934 private String in1;
2935 private String in2;
2936
2937 private ArrayList<String> extra=new ArrayList<String>();
2938
2939 private String out1=null;
2940 private String out2=null;
2941 private String outb1=null;
2942 private String outb2=null;
2943 private String outinsert=null;
2944 private String ihist=null;
2945 private String outAdapter=null;
2946 private String outCardinality=null;
2947
2948 /** List of R1 adapters to look for to verify a short-insert overlap */
2949 private ArrayList<byte[]> adapterList1;
2950 /** List of R2 adapters to look for to verify a short-insert overlap */
2951 private ArrayList<byte[]> adapterList2;
2952 /** Require short inserts to have adapter sequence at the expected location */
2953 private boolean verifyAdapters=false;
2954
2955 final CardinalityTracker loglog;
2956
2957 private long maxReads=-1;
2958 private boolean join=true;
2959 private boolean ecco=false;
2960 private boolean trimByOverlap=false;
2961
2962 private float pfilterRatio=0.00004f;
2963 private float efilterRatio=6f;
2964 private float efilterOffset=0.05f;
2965 private boolean useEfilter=true;
2966 private boolean useMEEfilter=false;
2967
2968 private boolean ordered=false;
2969 private boolean overlapUsingQuality=false;
2970 private boolean overlapWithoutQuality=true;
2971 private boolean useKFilter=false;
2972 private int filterCutoff=1;
2973 private int kmerLength=31;
2974 private boolean prealloc=false;
2975 private int prefilter=0;
2976 private long filterMemoryOverride=0;
2977 private boolean eccTail=false;
2978 private boolean eccPincer=false;
2979 private boolean eccReassemble=true;
2980
2981 private boolean useEntropy=true;
2982 private int entropyK=3;
2983 private int minEntropyScore=39;//30 loose;//39 normal;//44 strict;
2984
2985 private long sampleseed=-1;
2986 private float samplerate=1;
2987
2988 private long errorsCorrectedTotal=0;
2989
2990 private boolean findAdapterSequence=false;
2991 private boolean ignorePhixAdapters=false;
2992
2993 private final AdapterTracker atrack=new AdapterTracker();
2994
2995 private final Tadpole tadpole;
2996 private int extendRight1=0;
2997 private int extendRight2=0;
2998 private int extendIterations=1;
2999 private boolean eccTadpole=false;
3000 private boolean shave=false;
3001 private boolean rinse=false;
3002
3003 private final BloomFilter bloomFilter;
3004 private final BloomFilterCorrector corrector;
3005
3006 private boolean forceExactKmerCounts=false;
3007 private boolean testMerge=false;
3008 private boolean eccBloom=false;
3009 private int bloomBits=2;
3010 private int bloomHashes=3;
3011 int testMergeWidth=4;
3012 long testMergeMult=80L;
3013 int testMergeThresh=3;
3014
3015 private boolean requireExtensionMatch=false;
3016 private boolean requireStrictExtensionMatch=false;
3017 private int minApproxOverlapRem=26;
3018
3019 private boolean extendThroughLeftJunctions=true;
3020 private int minCountSeed=3, minCountExtend=2;
3021 private float branchMult1=20;
3022 private float branchMult2=3;
3023 private float minProb=0.5f;
3024 private int branchLowerConst=3;
3025
3026 private boolean MATE_BY_OVERLAP=true;
3027 private boolean MIX_BAD_AND_GOOD=false;
3028 private boolean ONLY_OUTPUT_INCORRECT=false;
3029
3030 private boolean OUTPUT_FALSE_POSITIVE=true;
3031 private boolean OUTPUT_FALSE_NEGATIVE=true;
3032 private boolean OUTPUT_TRUE_POSITIVE=true;
3033 private boolean OUTPUT_TRUE_NEGATIVE=true;
3034
3035 private boolean quantizeQuality=false;
3036
3037 /*--------------------------------------------------------------*/
3038
3039 private static ThreadLocal<int[]> localRvector=new ThreadLocal<int[]>();
3040
3041 static boolean errorState=false;
3042
3043 private static boolean showFullArgs=true;
3044
3045 /** Recalibrate quality scores using matrices */
3046 static boolean recalibrateQuality=false;
3047 static boolean useQuality=true;
3048 static boolean qtrimRight=false;
3049 static boolean qtrimLeft=false;
3050 // static boolean untrim=false;
3051 static float[] trimq=new float[] {6};
3052 static float[] trimE=QualityTools.phredToProbError(trimq);
3053 static float minAvgQuality=0;
3054 static int minAvgQualityBases=0;
3055 static float maxExpectedErrors=0;
3056 static int minReadLength=1;
3057 static int maxReadLength=-1;
3058 static int minInsert=15;
3059 static int minInsert0=-1;
3060 static boolean qtrim1=false;
3061 static boolean qtrim2=false;
3062 static int TRIM_ON_OVERLAP_FAILURE=1;
3063 static int QUAL_ITERS=3;
3064 static boolean parseCustom=false;
3065 static int maxAdapterLength=21;
3066
3067 static boolean trimNonOverlapping=false;
3068
3069 /** For adapter output */
3070 static boolean trimPolyA=true;
3071
3072 static int forceTrimLeft;
3073 static int forceTrimRight;
3074 static int forceTrimRight2;
3075 /** Trim right bases of the read modulo this value.
3076 * e.g. forceTrimModulo=50 would trim the last 3bp from a 153bp read. */
3077 static int forceTrimModulo;
3078
3079 public static boolean strict=false;
3080 static boolean vstrict=false;
3081 static boolean ustrict=false;
3082 static boolean xstrict=false;
3083 static boolean loose=false;
3084 static boolean vloose=false;
3085 static boolean uloose=false;
3086 static boolean xloose=false;
3087 static boolean fast=false;
3088
3089 /** If true, interpret lowercase bases as adapter sequence */
3090 static boolean lowercaseAdapters=false;
3091
3092 private static final int histlen=2000;
3093 static long[] histTotal=new long[histlen];
3094 static int bin=1;
3095
3096 static long readsProcessedTotal=0;
3097 static long basesProcessedTotal=0;
3098 static long matedCountTotal=0;
3099 static long correctCountTotal=0;
3100 static long unmergedOverlappingTotal=0;
3101 static long ambiguousCountTotal=0;
3102 static long tooShortCountTotal=0;
3103 static long tooLongCountTotal=0;
3104 static long incorrectCountTotal=0;
3105 static long noSolutionCountTotal=0;
3106 static long insertSumCorrectTotal=0;
3107 static long insertSumIncorrectTotal=0;
3108 static long fullyExtendedTotal=0;
3109 static long partlyExtendedTotal=0;
3110 static long notExtendedTotal=0;
3111 static long extensionsAttempted=0;
3112 static long adaptersExpected=0;
3113 static long adaptersFound=0;
3114
3115 static int insertMinTotal=999999999;
3116 static int insertMaxTotal=0;
3117
3118 private static int MIN_OVERLAPPING_BASES=11;
3119 private static int MIN_OVERLAPPING_BASES_0=8;
3120 private static int MISMATCH_MARGIN=2;
3121 private static int MIN_OVERLAPPING_BASES_RATIO_REDUCTION=3;
3122
3123 /** Skip alignment and calculate insert from mapping info */
3124 protected static boolean USE_MAPPING=false;
3125 private static boolean NONZERO_ONLY=true;
3126 private static boolean showHistStats=true;
3127 static boolean TRAINING=false;
3128
3129 static boolean useRatioMode=true;
3130 static boolean useFlatMode=false;
3131 static boolean requireRatioMatch=false;
3132 static int MAX_MISMATCHES_R=20;
3133 static float MAX_RATIO=0.09f;
3134 static float RATIO_MARGIN=5.5f;
3135 static float RATIO_OFFSET=0.55f;
3136 static float MIN_SECOND_RATIO=0.1f;
3137
3138 public static int MAX_MISMATCHES=3;
3139 public static int MAX_MISMATCHES0=3;
3140 public static byte MIN_QUALITY=10;
3141
3142 public static final int RET_NO_SOLUTION=-1;
3143 public static final int RET_AMBIG=-2;
3144 public static final int RET_BAD=-3;
3145 public static final int RET_SHORT=-4;
3146 public static final int RET_LONG=-5;
3147
3148 private static boolean overwrite=true;
3149 private static boolean append=false;
3150 private static final boolean verbose=false;
3151 static final boolean TAG_CUSTOM=false;
3152 static boolean MAKE_VECTOR=false;
3153 private static String defaultNetFile=Data.findPath("?bbmerge.bbnet", false);
3154 static String netFile=defaultNetFile;
3155 static CellNet net0=CellNetParser.load(netFile, false);//False in case the net file is missing
3156 static float netCutoff=(net0==null ? 0.5f : net0.cutoff);
3157 private static boolean setCutoff=false;
3158 private static boolean ONLY_OUTPUT_FALSE_POSITIVE=false;
3159 private static boolean ONLY_OUTPUT_FALSE_NEGATIVE=false;
3160
3161 //TODO: Remove after NN is trained
3162 private static boolean EXEMPT_SHORT_OVERLAPS_FROM_STATS=false;
3163
3164 private static boolean iupacToN=false;
3165
3166 public static boolean changeQuality=true;
3167
3168 static PrintStream outstream=System.err;
3169
3170 private static int THREADS=-1;
3171 // private static String version="9.02";
3172
3173 private static final byte[] phixPrefix="AGATCGGAAGAGCG".getBytes();
3174
3175 private static final String[] defaultAdapters={
3176 "AGATCGGAAGAGCACA", "AATGATACGGCGACCA", "GATCGGAAGAGCACAC", "CTGTCTCTTATACACA",
3177 "GACGCTGCCGACGA", "CCGAGCCCACGAGAC", "CTGATGGCGCGAGGGA", "CTGAGCGGGCTGGCAA",
3178 "GATCGGAAGAGCGTCG", "GATCGTCGGACTGTAG", "CCTTGGCACCCGAGAA", "CCACGGGAACGTGGTG",
3179 "TGGAATTCTCGGGTGC", "TCGGACTGTAGAACTC", "AGATCGGAAGAGCGGT"
3180 };
3181
3182 public static ArrayList<byte[]> staticAdapterList=getAdapterList("default");
3183
3184 }