Debian Codegraph @

current/bloom/ErrorCorrect.java

raw symbols SCIP
1 package bloom;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.BitSet;
6
7 import dna.AminoAcid;
8 import dna.Data;
9 import fileIO.FileFormat;
10 import fileIO.ReadWrite;
11 import shared.KillSwitch;
12 import shared.Parse;
13 import shared.Parser;
14 import shared.PreParser;
15 import shared.Timer;
16 import shared.Tools;
17 import stream.ConcurrentReadInputStream;
18 import stream.ConcurrentReadOutputStream;
19 import stream.Read;
20 import structures.ListNum;
21 import tracker.ReadStats;
22
23 /**
24 * @author Brian Bushnell
25 * @date Aug 20, 2012
26 *
27 */
28 public class ErrorCorrect extends Thread{
29
30 public static void main(String[] args){
31
32 {//Preparse block for help, config files, and outstream
33 PreParser pp=new PreParser(args, new Object() { }.getClass().getEnclosingClass(), false);
34 args=pp.args;
35 //outstream=pp.outstream;
36 }
37
38 String reads1=args[0];
39 String reads2=(args.length>1 ? args[1] : null);
40
41 int k=23;
42 int cbits=4;
43 int hashes=1;
44 int thresh1=1;
45 int thresh2=2;
46 int matrixbits=34;
47 long maxReads=-1;
48 int buildpasses=1;
49 long tablereads=-1; //How many reads to process when building the hashtable
50 int buildStepsize=4;
51 String output=null;
52 boolean ordered=true;
53 boolean overwrite=true;
54 boolean append=false;
55
56 for(int i=2; i<args.length; i++){
57 final String arg=args[i];
58 final String[] split=arg.split("=");
59 String a=split[0].toLowerCase();
60 String b=split.length>1 ? split[1] : null;
61
62 if(Parser.parseZip(arg, a, b)){
63 //do nothing
64 }else if(Parser.parseQuality(arg, a, b)){
65 //do nothing
66 }else if(a.equals("k") || a.equals("kmer")){
67 k=Integer.parseInt(b);
68 }else if(a.startsWith("cbits") || a.startsWith("cellbits")){
69 cbits=Integer.parseInt(b);
70 }else if(a.equals("initialthresh") || a.equals("thresh1")){
71 thresh1=Integer.parseInt(b);
72 }else if(a.equals("thresh") || a.equals("thresh2")){
73 thresh2=Integer.parseInt(b);
74 }else if(a.startsWith("matrixbits")){
75 matrixbits=Integer.parseInt(b);
76 }else if(a.startsWith("hashes") || a.startsWith("multihash")){
77 hashes=Integer.parseInt(b);
78 }else if(a.startsWith("maxerrors")){
79 ERROR_CORRECTION_LIMIT=Integer.parseInt(b);
80 }else if(a.startsWith("passes")){
81 buildpasses=Integer.parseInt(b);
82 }else if(a.startsWith("stepsize") || a.startsWith("buildstepsize")){
83 buildStepsize=Integer.parseInt(b);
84 }else if(a.equals("threads") || a.equals("t")){
85 System.err.println("Can't change threadcount for this class."); //THREADS=Integer.parseInt(b);
86 }else if(a.startsWith("reads") || a.startsWith("maxreads")){
87 maxReads=Parse.parseKMG(b);
88 }else if(a.startsWith("tablereads")){
89 tablereads=Parse.parseKMG(b);
90 }else if(a.startsWith("build") || a.startsWith("genome")){
91 Data.setGenome(Integer.parseInt(b));
92 Data.sysout.println("Set genome to "+Data.GENOME_BUILD);
93 }else if(a.equals("outputinfo") || a.startsWith("info")){
94 OUTPUT_INFO=Parse.parseBoolean(b);
95 }else if(a.startsWith("out")){
96 output=b;
97 }else if(a.startsWith("verbose")){
98 KCountArray.verbose=Parse.parseBoolean(b);
99 // verbose=KCountArray.verbose=Parse.parseBoolean(b);
100 }else if(a.equals("ordered") || a.equals("ord")){
101 ordered=Parse.parseBoolean(b);
102 }else if(a.equals("append") || a.equals("app")){
103 append=ReadStats.append=Parse.parseBoolean(b);
104 }else if(a.equals("overwrite") || a.equals("ow")){
105 overwrite=Parse.parseBoolean(b);
106 }else{
107 throw new RuntimeException("Unknown parameter "+args[i]);
108 }
109 }
110
111 {//Process parser fields
112 Parser.processQuality();
113 }
114
115 KCountArray kca=makeTable(reads1, reads2, k, cbits, hashes, buildpasses, matrixbits, tablereads, buildStepsize, thresh1, thresh2);
116
117 detect(reads1, reads2, kca, k, thresh2, maxReads, output, ordered, append, overwrite);
118 }
119
120 //Only called by main...
121 public static KCountArray makeTable(String reads1, String reads2, int k, int cbits, int hashes, int buildpasses, int matrixbits,
122 long maxreads, int stepsize, int thresh1, int thresh2){
123
124 Timer thash=new Timer();
125
126 KmerCount6.maxReads=maxreads;
127 int kbits=2*k;
128 matrixbits=Tools.min(kbits, matrixbits);
129
130 thash.start();
131 // Data.sysout.println("kbits="+(kbits)+" -> "+(1L<<kbits)+", matrixbits="+(matrixbits)+" -> "+(1L<<matrixbits)+", cbits="+cbits+", gap="+gap+", hashes="+hashes);
132 KCountArray kca=KCountArray.makeNew(1L<<matrixbits, cbits, hashes);
133
134 if(buildpasses==1){
135
136 KmerCount6.count(reads1, reads2, k, cbits, true, kca);
137 kca.shutdown();
138
139 }else{
140 assert(buildpasses>1);
141 KCountArray trusted=null;
142 for(int i=1; i<buildpasses; i++){
143 boolean conservative=i>2;// /*or, alternately, (trusted==null || trusted.capacity()>0.3)
144 int step=(stepsize==1 ? 1 : stepsize+i%2);
145 // if(!conservative){step=(step+3)/4;}
146 if(!conservative){step=Tools.min(3, (step+3)/4);}
147
148 KmerCount6.count(reads1, reads2, k, cbits, true, kca, trusted, maxreads, thresh1, step, conservative);
149
150 kca.shutdown();
151 Data.sysout.println("Trusted: \t"+kca.toShortString());
152 trusted=kca;
153 kca=KCountArray.makeNew(1L<<matrixbits, cbits, hashes);
154
155 }
156
157 KmerCount6.count(reads1, reads2, k, cbits, true, kca, trusted, maxreads, thresh2, stepsize, true);
158
159 kca.shutdown();
160 }
161
162
163 thash.stop();
164 // Data.sysout.println(kca.toString());
165 Data.sysout.println("Table : \t"+kca.toShortString());
166 Data.sysout.println("Hash time: \t"+thash);
167 return kca;
168 }
169
170 public static void detect(String reads1, String reads2, KCountArray kca, int k, int thresh, long maxReads, String output, boolean ordered, boolean append, boolean overwrite) {
171
172
173 final ConcurrentReadInputStream cris;
174 {
175 FileFormat ff1=FileFormat.testInput(reads1, FileFormat.FASTQ, null, true, true);
176 FileFormat ff2=FileFormat.testInput(reads2, FileFormat.FASTQ, null, true, true);
177 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
178 }
179 assert(cris!=null) : reads1;
180
181 cris.start();
182 if(verbose){System.err.println("Started cris");}
183 boolean paired=cris.paired();
184 if(verbose){System.err.println("Paired: "+paired);}
185
186 ConcurrentReadOutputStream ros=null;
187 if(output!=null){
188 String out1=output.replaceFirst("#", "1"), out2=null;
189
190 if(cris.paired()){
191 if(output.contains("#")){
192 out2=output.replaceFirst("#", "2");
193 }else{
194 System.err.println("Writing interleaved.");
195 }
196 }
197
198 final int buff=(!ordered ? 8 : Tools.max(16, 2*THREADS));
199
200 FileFormat ff1=FileFormat.testOutput(out1, FileFormat.FASTQ, OUTPUT_INFO ? ".info" : null, true, overwrite, append, ordered);
201 FileFormat ff2=FileFormat.testOutput(out2, FileFormat.FASTQ, OUTPUT_INFO ? ".info" : null, true, overwrite, append, ordered);
202 ros=ConcurrentReadOutputStream.getStream(ff1, ff2, buff, null, true);
203
204 assert(!ff1.sam()) : "Sam files need reference info for the header.";
205 }
206
207
208 if(ros!=null){
209 ros.start();
210 Data.sysout.println("Started output threads.");
211 }
212
213 detect(cris, kca, k, thresh, maxReads, ros);
214
215 ReadWrite.closeStreams(cris, ros);
216 if(verbose){System.err.println("Closed stream");}
217 }
218
219 public static void detect(ConcurrentReadInputStream cris, KCountArray kca, int k, int thresh, long maxReads, ConcurrentReadOutputStream ros) {
220 Timer tdetect=new Timer();
221 tdetect.start();
222
223 ListNum<Read> ln=cris.nextList();
224 ArrayList<Read> reads=(ln!=null ? ln.list : null);
225
226 long covered=0;
227 long uncovered=0;
228
229 long coveredFinal=0;
230 long uncoveredFinal=0;
231
232 long fullyCorrected=0;
233 long failed=0;
234
235 long totalBases=0;
236 long totalReads=0;
237
238
239 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
240 for(Read r : reads){
241 Read r2=r.mate;
242 {
243
244 // if(r.numericID==23){verbose=true;}
245
246 totalReads++;
247 if(verbose){System.err.println();}
248 totalBases+=r.length();
249 // BitSet bs=detectErrors(r, kca, k, thresh);
250 BitSet bs=detectErrorsBulk(r, kca, k, thresh, 1);
251 if(verbose){System.err.println(toString(bs, r.length()));}
252 // Data.sysout.println(toString(detectErrorsTips(r, kca, k, thresh), r.length()));
253 if(verbose){System.err.println(toString(detectErrors(r, kca, k, thresh), r.length()-k+1));}
254 if(bs==null){//No errors, or can't detect errors
255 assert(false);
256 }else{
257 int x=bs.cardinality();
258 covered+=x;
259 uncovered+=(r.length()-x);
260 if(x<r.length()){
261 bs=correctErrors(r, kca, k, thresh, bs, ERROR_CORRECTION_LIMIT, MAX_ERROR_BURST);
262 }
263 int y=bs.cardinality();
264 coveredFinal+=y;
265 uncoveredFinal+=(r.length()-y);
266 if(x<r.length()){
267 if(y==r.length()){
268 fullyCorrected++;
269 }else{
270 failed++;
271 }
272 }
273 }
274 }
275 if(r2!=null){
276 totalReads++;
277 totalBases+=r2.length();
278 // BitSet bs=detectErrors(r2, kca, k, thresh);
279 BitSet bs=detectErrorsBulk(r2, kca, k, thresh, 1);
280 if(verbose){System.err.println(toString(bs, r2.length()));}
281 // Data.sysout.println(toString(detectErrorsTips(r2, kca, k, thresh), r2.length()));
282 if(verbose){System.err.println(toString(detectErrors(r2, kca, k, thresh), r2.length()-k+1));}
283 if(bs==null){//No errors, or can't detect errors
284 }else{
285 int x=bs.cardinality();
286 covered+=x;
287 uncovered+=(r2.length()-x);
288 if(x<r2.length()){
289 bs=correctErrors(r2, kca, k, thresh, bs, ERROR_CORRECTION_LIMIT, MAX_ERROR_BURST);
290 }
291 int y=bs.cardinality();
292 coveredFinal+=y;
293 uncoveredFinal+=(r2.length()-y);
294 if(x<r2.length()){
295 if(y==r2.length()){
296 fullyCorrected++;
297 }else{
298 failed++;
299 }
300 }
301 }
302 }
303 }
304
305 if(ros!=null){ //Important to send all lists to output, even empty ones, to keep list IDs straight.
306 if(DONT_OUTPUT_BAD_READS){removeBad(reads);}
307 for(Read r : reads){
308 if(r!=null){
309 r.samline=null;
310 assert(r.bases!=null);
311 if(r.sites!=null && r.sites.isEmpty()){r.sites=null;}
312 }
313 }
314 // System.err.println("Adding list of length "+readlist.size());
315 ros.add(reads, ln.id);
316 }
317
318 cris.returnList(ln);
319 //System.err.println("fetching list");
320 ln=cris.nextList();
321 reads=(ln!=null ? ln.list : null);
322 }
323 if(verbose){System.err.println("Finished reading");}
324 cris.returnList(ln);
325 if(verbose){System.err.println("Returned list");}
326
327 tdetect.stop();
328 Data.sysout.println("Detect time: \t"+tdetect);
329 Data.sysout.println("Total reads: \t"+totalReads);
330 Data.sysout.println("Total bases: \t"+totalBases);
331 Data.sysout.println("Reads Corrected:\t"+fullyCorrected);
332 Data.sysout.println("Reads Failed: \t"+failed);
333
334 Data.sysout.println("\n - before correction - ");
335 Data.sysout.println("Covered: \t"+covered);
336 Data.sysout.println("Uncovered: \t"+uncovered);
337
338 Data.sysout.println("\n - after correction - ");
339 Data.sysout.println("Covered: \t"+coveredFinal);
340 Data.sysout.println("Uncovered: \t"+uncoveredFinal);
341 }
342
343 /** Sets a 1 bit at start of each kmer with count at least thresh */
344 public static BitSet detectErrors(final Read r, final KCountArray kca, final int k, final int thresh){
345
346 final int kbits=2*k;
347 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
348 final byte[] bases=r.bases;
349
350 int bslen=r.length()-k+1;
351 if(bslen<1){return null;} //Read is too short to detect errors
352 BitSet bs=new BitSet(bslen);
353
354 int len=0;
355 long kmer=0;
356 for(int i=0; i<bases.length; i++){
357 byte b=bases[i];
358 int x=AminoAcid.baseToNumber[b];
359 if(x<0){
360 len=0;
361 kmer=0;
362 }else{
363 kmer=((kmer<<2)|x)&mask;
364 len++;
365
366 if(len>=k){
367 int count=kca.read(kmer);
368 if(count>=thresh){
369 bs.set(i+1-k);
370 }
371 }
372 }
373 }
374
375 return bs;
376 }
377
378 /** Sets a 1 bit for every base covered by a kmer with count at least thresh */
379 public static BitSet detectErrorsBulk(final Read r, final KCountArray kca, final int k, final int thresh, final int stepsize){
380
381 final int kbits=2*k;
382 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
383 final byte[] bases=r.bases;
384
385 if(r.bases==null || r.length()<k){return null;} //Read is too short to detect errors
386 BitSet bs=new BitSet(r.length());
387 final int setlen=k;
388
389 int len=0;
390 long kmer=0;
391 for(int i=0; i<bases.length; i++){
392 byte b=bases[i];
393 int x=AminoAcid.baseToNumber[b];
394 if(x<0){
395 len=0;
396 kmer=0;
397 }else{
398 kmer=((kmer<<2)|x)&mask;
399 len++;
400
401 if(len>=k && ((len-k)%stepsize==0 || i==bases.length-1)){
402 int count=kca.read(kmer);
403 if(count>=thresh){
404 bs.set(i+1-setlen, i+1);
405 }
406 }
407 }
408 }
409 r.errors=bs.cardinality()-r.length();
410
411 return bs;
412 }
413
414 /** Sets 1 for all bases.
415 * Then clears all bits covered by incorrect kmers. */
416 public static BitSet detectTrusted(final Read r, final KCountArray kca, final int k, final int thresh, final int detectStepsize){
417
418 final int kbits=2*k;
419 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
420 final byte[] bases=r.bases;
421
422 if(r.bases==null || r.length()<k){return null;} //Read is too short to detect errors
423 BitSet bs=new BitSet(r.length());
424 bs.set(0, r.length());
425 final int setlen=k;
426
427 int len=0;
428 long kmer=0;
429 for(int i=0; i<bases.length; i++){
430 byte b=bases[i];
431 int x=AminoAcid.baseToNumber[b];
432 if(x<0){
433 len=0;
434 kmer=0;
435 }else{
436 kmer=((kmer<<2)|x)&mask;
437 len++;
438
439 if(len>=k && (i%detectStepsize==0 || i==bases.length-1)){
440 int count=kca.read(kmer);
441 if(count<thresh){
442 bs.clear(i+1-setlen, i+1);
443 // bs.clear(i+1-setlen+detectStepsize, i+1-detectStepsize);
444 // bs.clear(i+k/2-detectStepsize, i+k/2+detectStepsize);
445 // bs.clear(i+k/2);
446 }
447 }
448 }
449 }
450 // assert(bases.length==r.length());
451 return bs;
452 }
453
454 public static BitSet detectErrorsTips(final Read r, final KCountArray kca, final int k, final int thresh){
455
456 final int kbits=2*k;
457 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
458 final byte[] bases=r.bases;
459
460 if(r.bases==null || r.length()<k){return null;} //Read is too short to detect errors
461 BitSet bs=new BitSet(r.length());
462 final int setlen=k;
463
464 int len=0;
465 long kmer=0;
466 for(int i=0; i<bases.length; i++){
467 byte b=bases[i];
468 int x=AminoAcid.baseToNumber[b];
469 if(x<0){
470 len=0;
471 kmer=0;
472 }else{
473 kmer=((kmer<<2)|x)&mask;
474 len++;
475
476 if(len>=k){
477 int count=kca.read(kmer);
478 if(count>=thresh){
479 bs.set(i+1-setlen);
480 bs.set(i);
481 }
482 }
483 }
484 }
485 return bs;
486 }
487
488
489 /** Assumes bulk mode was used; e.g., any '0' bit is covered by no correct kmers */
490 public static BitSet correctErrors(final Read r, final KCountArray kca, final int k, final int thresh, BitSet bs, final int maxCorrections, final int maxBurst){
491
492 assert(!OUTPUT_INFO) : "TODO: Outputting correction data is not yet supported.";
493
494 int corrections=0; //Alternately, corrections=r.errorsCorrected
495 r.errors=0;
496
497 if(bs.cardinality()==0){//Cannot be corrected
498 r.errors=r.length();
499 return bs;
500 }
501
502 // verbose=!bs.get(0);
503 if(verbose){
504 Data.sysout.println();
505 Data.sysout.println(toString(bs, r.length()));
506 Data.sysout.println(toString(detectErrorsTips(r, kca, k, thresh), r.length()));
507 Data.sysout.println(toString(detectErrors(r, kca, k, thresh), r.length()-k+1));
508 }
509
510
511 int lastloc=-99;
512 int burst=1;
513 while(!bs.get(0) && corrections<maxCorrections){//While the read starts with a '0', correct from the right.
514 // Data.sysout.println("Could not correct.");
515 // return bs;
516 int errorLoc=bs.nextSetBit(0)-1;//Location to left of first '1'
517 if(Tools.absdif(errorLoc,lastloc)<=BURST_THRESH){burst++;}
518 else{burst=1;}
519 lastloc=errorLoc;
520 boolean success=(burst<=MAX_ERROR_BURST) && correctFromRight(r, kca, k, thresh, bs, errorLoc);
521 if(success){
522 corrections++;
523 bs=detectErrorsBulk(r, kca, k, thresh, 1);
524 if(verbose){System.err.println(">\n"+toString(bs, r.length()));}
525 }else{
526 r.errors=r.length()-bs.cardinality();
527 // r.errorsCorrected+=corrections;
528 if(verbose){System.err.println("Could not correct.");}
529 r.bases[errorLoc]='N';
530 r.quality[errorLoc]=0;
531 return bs;
532 }
533 }
534
535 burst=1;
536 while(bs.cardinality()<r.length() && corrections<maxCorrections){
537 if(bs.get(0)){//First bit is a "1", can correct from the left
538 int errorLoc=bs.nextClearBit(0);//Location to left of first '0'
539 if(Tools.absdif(errorLoc,lastloc)<=BURST_THRESH){burst++;}
540 else{burst=1;}
541 lastloc=errorLoc;
542 boolean success=(burst<=MAX_ERROR_BURST) && correctFromLeft(r, kca, k, thresh, bs, errorLoc);
543 if(success){
544 corrections++;
545 bs=detectErrorsBulk(r, kca, k, thresh, 1);
546 if(verbose){System.err.println(">\n"+toString(bs, r.length()));}
547 }else{
548 r.errors=r.length()-bs.cardinality();
549 // r.errorsCorrected+=corrections;
550 r.bases[errorLoc]='N';
551 r.quality[errorLoc]=0;
552 if(verbose){System.err.println("Could not correct.");}
553 return bs;
554 }
555 }
556 }
557
558 r.errors=r.length()-bs.cardinality();
559 // r.errorsCorrected+=corrections;
560 assert(corrections<=maxCorrections);
561 return bs;
562 }
563
564
565 /**
566 * @param r
567 * @param kca
568 * @param k
569 * @param thresh
570 * @param bs
571 * @param errorLoc
572 * @return
573 */
574 private static boolean correctFromLeft(Read r, KCountArray kca, int k, int thresh, BitSet bs, int error) {
575 final int kbits=2*k;
576 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
577 final int setlen=k;
578 final int startLoc=error-(setlen)+1;
579 final byte oldBase=r.bases[error];
580 final byte[] bases=r.bases;
581
582 final int minAdvance=Tools.min(MIN_ADVANCE, bases.length-error);
583
584 long kmer=0;
585 int len=0;
586 for(int i=startLoc; i<error; i++){
587 byte b=bases[i];
588 int x=AminoAcid.baseToNumber[b];
589 if(x<0){
590 len=0;
591 kmer=0;
592 throw new RuntimeException("Can't correct from left!\nerror="+error+"\n"+toString(bs, bases.length)+"\n"+new String(bases)+"\nreadID: "+r.numericID);
593 }else{
594 kmer=((kmer<<2)|x)&mask;
595 len++;
596 }
597 }
598 assert(len==setlen-1) : setlen+", "+len+", "+error+", "+startLoc;
599
600 int[] counts=KillSwitch.allocInt1D(4);
601 int[] dists=KillSwitch.allocInt1D(4);
602 int maxLoc=Tools.min(bases.length-1, error+setlen-1);
603 if(!bs.get(error+1)){maxLoc=Tools.min(maxLoc, error+9);}
604 else{
605 for(int i=error+2; i<=maxLoc; i++){
606 if(!bs.get(i)){
607 maxLoc=i-1;
608 break;
609 }
610 }
611 }
612
613 if(verbose){System.err.println("correctFromLeft. Error = "+error+", maxloc="+maxLoc);}
614 for(int bnum=0; bnum<4; bnum++){
615 byte c=AminoAcid.numberToBase[bnum];
616 bases[error]=c;
617 if(verbose){System.err.println("Considering "+(char)c);}
618 long key=kmer;
619 for(int loc=error; loc<=maxLoc; loc++){
620 c=bases[loc];
621 int x=AminoAcid.baseToNumber[c];
622 if(x<0){
623 if(verbose){System.err.println("break: N");}
624 break;
625 }
626 key=((key<<2)|x)&mask;
627 int count=kca.read(key);
628 if(count<thresh){
629 if(verbose){System.err.println("break: count="+count);}
630 break;
631 }
632 dists[bnum]++;
633 counts[bnum]+=count;
634 }
635 }
636 bases[error]=oldBase;
637
638 //Note: I could require both to be the same, to decrease false-positives
639
640 final int muid=maxUniqueIndex(dists);
641 Arrays.sort(dists);
642 final int advance=dists[3];
643 final int delta=dists[3]-dists[2];
644 // if(advance<minAdvance){return false;}
645 if(delta<minAdvance){return false;}
646
647 int best=(muid<0 ? maxUniqueIndex(counts) : muid);
648
649 if(verbose){System.err.println("Best="+best+": "+Arrays.toString(dists)+" \t"+Arrays.toString(counts));}
650 if(best<0){return false;}
651 byte bestC=AminoAcid.numberToBase[best];
652 if(bestC==oldBase){return false;}
653 bases[error]=bestC;
654
655 r.quality[error]=(byte)Tools.min(10, 3+delta);
656
657 return true;
658 }
659
660
661
662 /**
663 * @param r
664 * @param kca
665 * @param k
666 * @param thresh
667 * @param bs
668 * @param errorLoc
669 * @return
670 */
671 private static boolean correctFromRight(Read r, KCountArray kca, int k, int thresh, BitSet bs, int error) {
672 final int kbits=2*k;
673 final int shift=kbits-2;
674 final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
675 final int setlen=k;
676 final int stopLoc=error+(setlen)-1;
677 final byte oldBase=r.bases[error];
678 final byte[] bases=r.bases;
679
680 final int minAdvance=Tools.min(MIN_ADVANCE, error+1);
681
682 long kmer=0;
683 int len=0;
684
685 for(int i=error+1; i<=stopLoc; i++){
686 byte b=bases[i];
687 int x=AminoAcid.baseToNumber[b];
688 if(x<0){
689 len=0;
690 kmer=0;
691 throw new RuntimeException("Can't correct from right!\nerror="+error+"\n"+toString(bs, bases.length)+"\n"+new String(bases));
692 }else{
693 kmer=((kmer<<2)|x)&mask;
694 len++;
695 }
696 // Data.sysout.print((char)b);
697 }
698 kmer<<=2;
699
700 if(verbose){
701 Data.sysout.println();
702 String s=Long.toBinaryString(kmer);
703 while(s.length()<kbits){s="0"+s;}
704 Data.sysout.println("kmer = \t"+s);
705 }
706 assert(len==setlen-1) : setlen+", "+len+", "+error+", "+stopLoc;
707
708 int[] counts=KillSwitch.allocInt1D(4);
709 int[] dists=KillSwitch.allocInt1D(4);
710 int minLoc=Tools.max(0, error-setlen+1);
711 if(error==0 || !bs.get(error-1)){minLoc=Tools.max(minLoc, error-9);}
712 else{
713 for(int i=error-2; i>=minLoc; i--){
714 if(!bs.get(i)){
715 minLoc=i+1;
716 break;
717 }
718 }
719 }
720
721 if(verbose){
722 Data.sysout.println("correctFromRight. Error = "+error+", minloc="+minLoc);
723 Data.sysout.println(new String(r.bases));
724 }
725 for(int bnum=0; bnum<4; bnum++){
726 byte c=AminoAcid.numberToBase[bnum];
727 bases[error]=c;
728 if(verbose){System.err.println("Considering "+(char)c);}
729 long key=kmer;
730 for(int loc=error; loc>=minLoc; loc--){
731 c=bases[loc];
732 int x=AminoAcid.baseToNumber[c];
733 if(x<0){
734 if(verbose){System.err.println("break: N");}
735 break;
736 }
737 key=((key>>2)|(((long)x)<<shift))&mask;
738 // {
739 // String s=Long.toBinaryString(key);
740 // while(s.length()<kbits){s="0"+s;}
741 // Data.sysout.println("mask="+Long.toBinaryString(mask)+", shift="+shift+", c="+c+", x="+x+", key = \t"+s);
742 // }
743 int count=kca.read(key);
744 if(count<thresh){
745 if(verbose){System.err.println("break: count="+count);}
746 break;
747 }
748 dists[bnum]++;
749 counts[bnum]+=count;
750 }
751 }
752 bases[error]=oldBase;
753
754 //Note: I could require both to be the same, to decrease false-positives
755
756 final int muid=maxUniqueIndex(dists);
757 Arrays.sort(dists);
758 final int advance=dists[3];
759 final int delta=dists[3]-dists[2];
760 // if(advance<minAdvance){return false;}
761 if(delta<minAdvance){return false;}
762
763 int best=(muid<0 ? maxUniqueIndex(counts) : muid);
764
765 if(verbose){System.err.println("Best="+best+": "+Arrays.toString(dists)+" \t"+Arrays.toString(counts));}
766 if(best<0){return false;}
767 byte bestC=AminoAcid.numberToBase[best];
768 if(bestC==oldBase){return false;}
769 bases[error]=bestC;
770
771 r.quality[error]=(byte)Tools.min(10, 3+delta);
772
773 return true;
774 }
775
776
777 /** returns index of highest value, if unique; else a negative number */
778 private static int maxUniqueIndex(int[] array){
779 int max=array[0];
780 int maxIndex=0;
781 for(int i=1; i<array.length; i++){
782 if(array[i]>max){
783 max=array[i];
784 maxIndex=i;
785 }else if(max==array[i]){
786 maxIndex=-1;
787 }
788 }
789 return maxIndex;
790 }
791
792 public static final String toString(BitSet bs, int len){
793 // assert(verbose);
794 StringBuilder sb=new StringBuilder(len);
795 for(int i=0; i<len; i++){sb.append(bs.get(i) ? '1' : '0');}
796 return sb.toString();
797 }
798
799 private static void removeBad(ArrayList<Read> list){
800
801 for(int i=0; i<list.size(); i++){
802 Read r=list.get(i);
803 if(r.errors>0){
804 if(r.mate==null || r.mate.errors>0){
805 list.set(i, null);
806 }
807 }
808 }
809
810 }
811
812 public static boolean verbose=false;
813 /** Bails out if a read still has errors after correcting this many. */
814 public static int ERROR_CORRECTION_LIMIT=6;
815 /** Max allowed number of nearby corrections.
816 * A long error burst indicates the read simply has low coverage, and is not being corrected correctly. */
817 public static int MAX_ERROR_BURST=3;
818 /** Bursts have at most this distance between errors. E.G. '1' means errors are adjacent. */
819 public static int BURST_THRESH=2;
820 /** Withhold uncorrectable reads from output. */
821 public static boolean DONT_OUTPUT_BAD_READS=false;
822 /** Do not correct an error if it is at most this far from the next error. Instead, bail out. */
823 public static int MIN_ADVANCE=1;
824
825 /** Number of threads used for error correction. Does not control number of threads for creating the hash table.
826 * Additionally, up to 2 threads are used for reading and up to 2 for writing. For this (singlethreaded) class, the number does nothing. */
827 public static final int THREADS=1;
828
829 /** Output correction data instead of the corrected read */
830 public static boolean OUTPUT_INFO=false;
831
832
833 }