Debian Codegraph @

current/stream/Read.java

raw symbols SCIP
1 package stream;
2
3 import java.io.Serializable;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.HashSet;
7
8 import align2.GapTools;
9 import align2.QualityTools;
10 import dna.AminoAcid;
11 import dna.ChromosomeArray;
12 import dna.Data;
13 import shared.KillSwitch;
14 import shared.Shared;
15 import shared.Tools;
16 import shared.TrimRead;
17 import structures.ByteBuilder;
18 import structures.FloatList;
19 import ukmer.Kmer;
20
21 public final class Read implements Comparable<Read>, Cloneable, Serializable{
22
23 /**
24 *
25 */
26 private static final long serialVersionUID = -1026645233407290096L;
27
28 public static void main(String[] args){
29 byte[] a=args[0].getBytes();
30 System.out.println(new String(a));
31 byte[] b=toShortMatchString(a);
32 System.out.println(new String(b));
33 byte[] c=toLongMatchString(b);
34 System.out.println(new String(c));
35 byte[] d=toLongMatchString(c);
36 System.out.println(new String(d));
37 // byte[] e=toShortMatchString(b);
38 // System.out.println(new String(e));
39
40 }
41
42 public Read(byte[] bases_, byte[] quals_, long id_){
43 this(bases_, quals_, Long.toString(id_), id_);
44 }
45
46 public Read(byte[] bases_, byte[] quals_, String name_, long id_){
47 this(bases_, quals_, name_, id_, 0, -1, -1, -1);
48 }
49
50 public Read(byte[] bases_, byte[] quals_, String name_, long id_, int flag_){
51 this(bases_, quals_, name_, id_, flag_, -1, -1, -1);
52 }
53
54 public Read(byte[] s_, byte[] quals_, long id_, int chrom_, int start_, int stop_, byte strand_){
55 this(s_, quals_, Long.toString(id_), id_, (int)strand_, chrom_, start_, stop_);
56 }
57
58 // public Read(byte[] bases_, byte[] quals_, String id_, long numericID_, byte strand_, int chrom_, int start_, int stop_){
59 // this(bases_, quals_, id_, numericID_, (int)strand_, chrom_, start_, stop_);
60 // assert(strand_==0 || strand_==1);
61 // assert(start_<=stop_) : chrom_+", "+start_+", "+stop_+", "+numericID_;
62 // }
63
64 /** Note that strand can be used as flag */
65 public Read(byte[] bases_, byte[] quals_, String id_, long numericID_, int flags_, int chrom_, int start_, int stop_){
66 flags=flags_&~VALIDATEDMASK;
67 bases=bases_;
68 quality=quals_;
69
70 chrom=chrom_;
71 start=start_;
72 stop=stop_;
73
74 id=id_;
75 numericID=numericID_;
76
77 // assert(amino()) : Shared.AMINO_IN;//123
78 if(VALIDATE_IN_CONSTRUCTOR){validate(true);}
79 }
80
81 /*--------------------------------------------------------------*/
82 /*---------------- Validation ----------------*/
83 /*--------------------------------------------------------------*/
84
85 public boolean validate(final boolean processAssertions){
86 assert(!validated());
87
88 // if(false){//This causes problems with error-corrected PacBio reads.
89 // boolean x=(quality==null || quality.length<1 || quality[0]<=80 || !FASTQ.DETECT_QUALITY || FASTQ.IGNORE_BAD_QUALITY);
90 // if(!x){
91 // if(processAssertions){
92 // KillSwitch.kill("Quality value ("+quality[0]+") appears too high.\n"+Arrays.toString(quality)+
93 // "\n"+Arrays.toString(bases)+"\n"+numericID+"\n"+id+"\n"+FASTQ.ASCII_OFFSET);
94 // }
95 // return false;
96 // }
97 // }
98
99 if(bases==null){
100 quality=null; //I could require this to be true
101 if(FIX_HEADER){fixHeader(processAssertions);}
102 setValidated(true);
103 return true;
104 }
105
106 validateQualityLength(processAssertions);
107
108 final boolean passesJunk;
109
110 // assert(false) : SKIP_SLOW_VALIDATION+","+VALIDATE_BRANCHLESS+","+JUNK_MODE;
111 if(SKIP_SLOW_VALIDATION){
112 passesJunk=true;
113 }else if(!aminoacid()){
114 if(U_TO_T){uToT();}
115 if(VALIDATE_BRANCHLESS){
116 passesJunk=validateCommonCase_branchless(processAssertions);
117 }else{
118 passesJunk=validateCommonCase(processAssertions);
119 }
120 }else{
121 // if(U_TO_T){uToT();} This is amino, so...
122 fixCase();
123 passesJunk=validateJunk(processAssertions);
124 if(CHANGE_QUALITY){fixQuality();}
125 }
126
127 if(FIX_HEADER){fixHeader(processAssertions);}
128
129 setValidated(true);
130
131 return true;
132 }
133
134
135
136 public boolean checkQuality(){
137 if(quality==null){return true;}
138 for(int i=0; quality!=null && i<bases.length; i++){
139 if((bases[i]=='N')!=(quality[i]<1)){
140 assert(false) : (char)bases[i]+", "+quality[i]+", "+i+", "+CHANGE_QUALITY+", "+MIN_CALLED_QUALITY+"\n"+toFastq();
141 return false;
142 }
143 }
144 return true;
145 }
146
147 private void uToT(){
148 if(bases==null){return;}
149 for(int i=0; i<bases.length; i++){
150 bases[i]=AminoAcid.uToT[bases[i]];
151 }
152 }
153
154 private void tToU(){
155 if(bases==null){return;}
156 for(int i=0; i<bases.length; i++){
157 bases[i]=AminoAcid.tToU[bases[i]];
158 }
159 }
160
161 private boolean validateJunk(boolean processAssertions){
162 assert(bases!=null);
163 if(JUNK_MODE==IGNORE_JUNK){return true;}
164 final byte nocall;
165 final byte[] toNum;
166 final boolean aa=aminoacid();
167 if(aa){
168 nocall='X';
169 toNum=AminoAcid.acidToNumberExtended;
170 }else{
171 nocall='N';
172 toNum=AminoAcid.baseToNumberExtended;
173 }
174 for(int i=0; i<bases.length; i++){
175 byte b=bases[i];
176 int num=toNum[b];
177 // System.err.println(Character.toString(b)+" -> "+num);
178 if(num<0){
179 if(JUNK_MODE==FIX_JUNK){
180 bases[i]=nocall;
181 }else if(JUNK_MODE==FLAG_JUNK){
182 setJunk(true);
183 return false;
184 }else{
185 if(processAssertions){
186 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
187 + "The character with ASCII code "+b+" appeared where "+(aa ? "an amino acid" : "a base")+" was expected"
188 + (b>31 && b<127 ? ": '"+Character.toString((char)b)+"'\n" : ".\n")
189 + "Sequence #"+numericID+"\n"
190 + "Sequence ID '"+id+"'\n"
191 + "Sequence: "+Tools.toStringSafe(bases)+"\n"
192 + "Flags: "+Long.toBinaryString(flags)+"\n\n"
193 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
194 }
195 setJunk(true);
196 return false;
197 }
198 }
199 }
200 return true;
201 }
202
203 private void validateQualityLength(boolean processAssertions){
204 if(quality==null || quality.length==bases.length){return;}
205 if(TOSS_BROKEN_QUALITY){
206 quality=null;
207 setDiscarded(true);
208 setJunk(true);
209 }else if(NULLIFY_BROKEN_QUALITY){
210 quality=null;
211 setJunk(true);
212 }else if(FLAG_BROKEN_QUALITY){
213 setJunk(true);
214 }else{
215 boolean x=false;
216 assert(x=processAssertions);
217 if(x){
218 KillSwitch.kill("\nMismatch between length of bases and qualities for read "+numericID+" (id="+id+").\n"+
219 "# qualities="+quality.length+", # bases="+bases.length+"\n\n"+
220 FASTQ.qualToString(quality)+"\n"+new String(bases)+"\n\n"
221 + "This can be bypassed with the flag 'tossbrokenreads' or 'nullifybrokenquality'");
222 }
223 }
224 }
225
226 private void fixQuality(){
227 if(quality==null || !CHANGE_QUALITY){return;}
228
229 final byte[] toNumber=aminoacid() ? AminoAcid.acidToNumber : AminoAcid.baseToNumber;
230
231 for(int i=0; i<quality.length; i++){
232 byte b=bases[i];
233 byte q=quality[i];
234 quality[i]=capQuality(q, b);
235 // if(toNumber[b]>=0){
236 // if(q<MIN_CALLED_QUALITY){
237 // quality[i]=MIN_CALLED_QUALITY;
238 // }else if(q>MAX_CALLED_QUALITY){
239 // quality[i]=MAX_CALLED_QUALITY;
240 // }
241 // }else{
242 // quality[i]=0;
243 // }
244 }
245 }
246
247 private void fixCase(){
248 if(bases==null || (!DOT_DASH_X_TO_N && !TO_UPPER_CASE && !LOWER_CASE_TO_N)){return;}
249 final boolean aa=aminoacid();
250
251 final byte[] caseMap, ddxMap;
252 if(!aa){
253 caseMap=TO_UPPER_CASE ? AminoAcid.toUpperCase : LOWER_CASE_TO_N ? AminoAcid.lowerCaseToNocall : null;
254 ddxMap=DOT_DASH_X_TO_N ? AminoAcid.dotDashXToNocall : null;
255 }else{
256 caseMap=TO_UPPER_CASE ? AminoAcid.toUpperCase : LOWER_CASE_TO_N ? AminoAcid.lowerCaseToNocallAA : null;
257 ddxMap=DOT_DASH_X_TO_N ? AminoAcid.dotDashXToNocallAA : null;
258 }
259
260 // assert(false) : (AminoAcid.toUpperCase==caseMap)+", "+ddxMap;
261
262 if(DOT_DASH_X_TO_N){
263 if(TO_UPPER_CASE || LOWER_CASE_TO_N){
264 for(int i=0; i<bases.length; i++){
265 byte b=bases[i];
266 bases[i]=caseMap[ddxMap[b]];
267 }
268 }else{
269 for(int i=0; i<bases.length; i++){
270 byte b=bases[i];
271 bases[i]=ddxMap[b];
272 }
273 }
274 }else{
275 if(TO_UPPER_CASE || LOWER_CASE_TO_N){
276 for(int i=0; i<bases.length; i++){
277 byte b=bases[i];
278 bases[i]=caseMap[b];
279 }
280 }else{
281 assert(false);
282 }
283 }
284 }
285
286 private boolean validateCommonCase_branchless(boolean processAssertions){
287
288 assert(!aminoacid());
289 assert(bases!=null);
290
291 if(TO_UPPER_CASE || LOWER_CASE_TO_N){fixCase();}
292
293 final byte nocall='N';
294 final byte[] toNum=AminoAcid.baseToNumber;
295 final byte[] map=(DOT_DASH_X_TO_N && IUPAC_TO_N ? AminoAcid.baseToACGTN :
296 DOT_DASH_X_TO_N ? AminoAcid.dotDashXToNocall : IUPAC_TO_N ? AminoAcid.iupacToNocall : null);
297
298 if(JUNK_MODE==IGNORE_JUNK){
299 if(quality!=null && CHANGE_QUALITY){
300 if(DOT_DASH_X_TO_N || IUPAC_TO_N){
301 for(int i=0; i<bases.length; i++){
302 final byte b=map[bases[i]];
303 final byte q=quality[i];
304 final int num=toNum[b];
305 bases[i]=b;
306 quality[i]=(num>=0 ? qMap[q] : 0);
307 }
308 }else{
309 for(int i=0; i<bases.length; i++){
310 final byte b=bases[i];
311 final byte q=quality[i];
312 final int num=toNum[b];
313 quality[i]=(num>=0 ? qMap[q] : 0);
314 }
315 }
316 }else if(DOT_DASH_X_TO_N || IUPAC_TO_N){
317 for(int i=0; i<bases.length; i++){
318 byte b=map[bases[i]];
319 bases[i]=b;
320 }
321 }
322 return true;
323 }
324
325 int junkOr=0;
326 // int iupacOr=0;
327 final byte[] toNumE=AminoAcid.baseToNumberExtended;
328
329 // asdf
330
331 if(DOT_DASH_X_TO_N || IUPAC_TO_N){
332 if(quality!=null && CHANGE_QUALITY){
333 for(int i=0; i<bases.length; i++){
334 final byte b=map[bases[i]];
335 final byte q=quality[i];
336 final int numE=toNumE[b];
337 final int num=toNum[b];
338 junkOr|=numE;
339 // iupacOr|=num;
340 bases[i]=b;
341 quality[i]=(num>=0 ? qMap[q] : 0);
342 }
343 }else{
344 for(int i=0; i<bases.length; i++){
345 final byte b=map[bases[i]];
346 final int numE=toNumE[b];
347 // final int num=toNum[b];
348 junkOr|=numE;
349 // iupacOr|=num;
350 bases[i]=b;
351 }
352 }
353 }else{
354 if(quality!=null && CHANGE_QUALITY){
355 for(int i=0; i<bases.length; i++){
356 final byte b=bases[i];
357 final byte q=quality[i];
358 final int numE=toNumE[b];
359 final int num=toNum[b];
360 junkOr|=numE;
361 // iupacOr|=num;
362 quality[i]=(num>=0 ? qMap[q] : 0);
363 }
364 }else{
365 for(int i=0; i<bases.length; i++){
366 final byte b=bases[i];
367 final int numE=toNumE[b];
368 // final int num=toNum[b];
369 junkOr|=numE;
370 // iupacOr|=num;
371 }
372 }
373 }
374
375 // System.err.println(junkOr+", "+JUNK_MODE);
376
377 //Common case
378 if(junkOr>=0){return true;}
379 // if(junkOr>=0 && (JUNK_MODE!=FIX_JUNK_AND_IUPAC || iupacOr>=0)){return true;}
380 //
381 // assert(junkOr<0 || (JUNK_MODE==FIX_JUNK_AND_IUPAC && iupacOr<0));
382
383 //TODO: I could disable VALIDATE_BRANCHLESS here, if it's not final
384 //VALIDATE_BRANCHLESS=false;
385 if(JUNK_MODE==FIX_JUNK){
386 for(int i=0; i<bases.length; i++){
387 byte b=bases[i];
388 final int numE=toNumE[b];
389
390 if(numE<0){
391 bases[i]=nocall;
392 if(quality!=null){quality[i]=0;}
393 }
394 }
395 return true;
396 }else if(JUNK_MODE==FLAG_JUNK){
397 setJunk(true);
398 return false;
399 }else if(JUNK_MODE==FIX_JUNK_AND_IUPAC){
400 for(int i=0; i<bases.length; i++){
401 byte b=bases[i];
402 final byte c=AminoAcid.baseToACGTN[b];
403 bases[i]=c;
404 }
405 return true;
406 }else{
407 if(processAssertions){
408 int i=0;
409 for(; i<bases.length; i++){
410 if(toNumE[bases[i]]<0){break;}
411 }
412 byte b=bases[i];
413 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
414 + "The character with ASCII code "+b+" appeared where a base was expected"
415 + (b>31 && b<127 ? ": '"+Character.toString((char)b)+"'\n" : ".\n")
416 + "Sequence #"+numericID+"\n"
417 + "Sequence ID: '"+id+"'\n"
418 + "Sequence: '"+Tools.toStringSafe(bases)+"'\n\n"
419 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
420 }
421 setJunk(true);
422 return false;
423 }
424 }
425
426 private boolean validateCommonCase(boolean processAssertions){
427
428 assert(!aminoacid());
429 assert(bases!=null);
430
431 if(TO_UPPER_CASE || LOWER_CASE_TO_N){fixCase();}
432
433 final byte nocall='N';
434 final byte[] toNum=AminoAcid.baseToNumber;
435 final byte[] ddxMap=AminoAcid.dotDashXToNocall;
436
437 if(JUNK_MODE==IGNORE_JUNK){
438 if(quality!=null && CHANGE_QUALITY){
439 if(DOT_DASH_X_TO_N){
440 for(int i=0; i<bases.length; i++){
441 final byte b=ddxMap[bases[i]];
442 final byte q=quality[i];
443 final int num=toNum[b];
444 bases[i]=b;
445 quality[i]=(num>=0 ? qMap[q] : 0);
446 }
447 }else{
448 for(int i=0; i<bases.length; i++){
449 final byte b=bases[i];
450 final byte q=quality[i];
451 final int num=toNum[b];
452 quality[i]=(num>=0 ? qMap[q] : 0);
453 }
454 }
455 }else if(DOT_DASH_X_TO_N){
456 for(int i=0; i<bases.length; i++){
457 byte b=ddxMap[bases[i]];
458 bases[i]=b;
459 }
460 }
461 }else if(DOT_DASH_X_TO_N){
462 final byte[] toNumE=AminoAcid.baseToNumberExtended;
463 if(quality!=null && CHANGE_QUALITY){
464 for(int i=0; i<bases.length; i++){
465 byte b=ddxMap[bases[i]];
466 final byte q=quality[i];
467 final int numE=toNumE[b];
468
469 if(numE<0){
470 if(JUNK_MODE==FIX_JUNK){
471 b=nocall;
472 }else if(JUNK_MODE==FLAG_JUNK){
473 setJunk(true);
474 return false;
475 }else{
476 if(processAssertions){
477 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
478 + "The character with ASCII code "+bases[1]+" appeared where a base was expected.\n"
479 + "Sequence #"+numericID+"\n"
480 + "Sequence ID '"+id+"'\n"
481 + "Sequence: "+Tools.toStringSafe(bases)+"\n\n"
482 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
483 }
484 setJunk(true);
485 return false;
486 }
487 }
488
489 final int num=toNum[b];
490 bases[i]=b;
491 quality[i]=(num>=0 ? qMap[q] : 0);
492 }
493 }else{
494 for(int i=0; i<bases.length; i++){
495 byte b=ddxMap[bases[i]];
496 final int numE=toNumE[b];
497
498 if(numE<0){
499 if(JUNK_MODE==FIX_JUNK){
500 b=nocall;
501 }else if(JUNK_MODE==FLAG_JUNK){
502 setJunk(true);
503 return false;
504 }else{
505 if(processAssertions){
506 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
507 + "The character with ASCII code "+bases[1]+" appeared where a base was expected.\n"
508 + "Sequence #"+numericID+"\n"
509 + "Sequence ID '"+id+"'\n"
510 + "Sequence: "+Tools.toStringSafe(bases)+"\n\n"
511 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
512 }
513 setJunk(true);
514 return false;
515 }
516 }
517
518 bases[i]=b;
519 }
520 }
521 }else{
522 final byte[] toNumE=AminoAcid.baseToNumberExtended;
523 if(quality!=null && CHANGE_QUALITY){
524 for(int i=0; i<bases.length; i++){
525 byte b=bases[i];
526 final byte q=quality[i];
527 final int numE=toNumE[b];
528
529 if(numE<0){
530 if(JUNK_MODE==FIX_JUNK){
531 bases[i]=b=nocall;
532 }else if(JUNK_MODE==FLAG_JUNK){
533 setJunk(true);
534 return false;
535 }else{
536 if(processAssertions){
537 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
538 + "The character with ASCII code "+bases[1]+" appeared where a base was expected.\n"
539 + "Sequence #"+numericID+"\n"
540 + "Sequence ID '"+id+"'\n"
541 + "Sequence: "+Tools.toStringSafe(bases)+"\n\n"
542 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
543 }
544 setJunk(true);
545 return false;
546 }
547 }
548
549 final int num=toNum[b];
550 bases[i]=b;
551 quality[i]=(num>=0 ? qMap[q] : 0);
552 }
553 }else{
554 for(int i=0; i<bases.length; i++){
555 byte b=bases[i];
556 final int numE=toNumE[b];
557
558 if(numE<0){
559 if(JUNK_MODE==FIX_JUNK){
560 bases[i]=b=nocall;
561 }else if(JUNK_MODE==FLAG_JUNK){
562 setJunk(true);
563 return false;
564 }else{
565 if(processAssertions){
566 KillSwitch.kill("\nAn input file appears to be misformatted:\n"
567 + "The character with ASCII code "+bases[1]+" appeared where a base was expected.\n"
568 + "Sequence #"+numericID+"\n"
569 + "Sequence ID '"+id+"'\n"
570 + "Sequence: "+Tools.toStringSafe(bases)+"\n\n"
571 + "This can be bypassed with the flag 'tossjunk', 'fixjunk', or 'ignorejunk'");
572 }
573 setJunk(true);
574 return false;
575 }
576 }
577 }
578 }
579 }
580 return true;
581 }
582
583 private final void fixHeader(boolean processAssertions){
584 id=Tools.fixHeader(id, ALLOW_NULL_HEADER, processAssertions);
585 }
586
587 /*--------------------------------------------------------------*/
588 /*---------------- Various ----------------*/
589 /*--------------------------------------------------------------*/
590
591
592 private static final int absdif(int a, int b){
593 return a>b ? a-b : b-a;
594 }
595
596 /** Returns true if these reads are identical, allowing at most n no-calls and m mismatches of max quality q*/
597 public boolean isDuplicateByBases(Read r, int nmax, int mmax, byte qmax, boolean banSameQualityMismatch){
598 return isDuplicateByBases(r, nmax, mmax, qmax, banSameQualityMismatch, false);
599 }
600
601
602
603 /** Returns true if these reads are identical, allowing at most n no-calls and m mismatches of max quality q*/
604 public boolean isDuplicateByBases(Read r, int nmax, int mmax, byte qmax, boolean banSameQualityMismatch, boolean allowDifferentLength){
605 int n=0, m=0;
606 assert(r.length()==bases.length) : "Merging different-length reads is supported but seems to be not useful.";
607 if(!allowDifferentLength && r.length()!=bases.length){return false;}
608 int minLen=Tools.min(bases.length, r.length());
609 for(int i=0; i<minLen; i++){
610 byte b1=bases[i];
611 byte b2=r.bases[i];
612 if(b1=='N' || b2=='N'){
613 n++;
614 if(n>nmax){return false;}
615 }else if(b1!=b2){
616 m++;
617 if(m>mmax){return false;}
618 if(quality[i]>qmax && r.quality[i]>qmax){return false;}
619 if(banSameQualityMismatch && quality[i]==r.quality[i]){return false;}
620 }
621 }
622 return true;
623 }
624
625 public boolean isDuplicateByMapping(Read r, boolean bothEnds, boolean checkAlignment){
626 if(bases.length!=r.length()){
627 return isDuplicateByMappingDifferentLength(r, bothEnds, checkAlignment);
628 }
629 assert(this!=r && mate!=r);
630 assert(!bothEnds || bases.length==r.length());
631 if(!mapped() || !r.mapped()){return false;}
632 // if(chrom==-1 && start==-1){return false;}
633 if(chrom<1 && start<1){return false;}
634
635 // if(chrom!=r.chrom || strand()!=r.strand() || start!=r.start){return false;}
636 //// if(mate==null && stop!=r.stop){return false;} //For unpaired reads, require both ends match
637 // if(stop!=r.stop){return false;} //For unpaired reads, require both ends match
638 // return true;
639
640 if(chrom!=r.chrom || strand()!=r.strand()){return false;}
641 if(bothEnds){
642 if(start!=r.start || stop!=r.stop){return false;}
643 }else{
644 if(strand()==Shared.PLUS){
645 if(start!=r.start){return false;}
646 }else{
647 if(stop!=r.stop){return false;}
648 }
649 }
650 if(checkAlignment){
651 if(perfect() && r.perfect()){return true;}
652 if(match!=null && r.match!=null){
653 if(match.length!=r.match.length){return false;}
654 for(int i=0; i<match.length; i++){
655 byte a=match[i];
656 byte b=r.match[i];
657 if(a!=b){
658 if((a=='D') != (b=='D')){return false;}
659 if((a=='I' || a=='X' || a=='Y') != (b=='I' || b=='X' || b=='Y')){return false;}
660 }
661 }
662 }
663 }
664 return true;
665 }
666
667 public boolean isDuplicateByMappingDifferentLength(Read r, boolean bothEnds, boolean checkAlignment){
668 assert(this!=r && mate!=r);
669 assert(bases.length!=r.length());
670 if(bothEnds){return false;}
671 // assert(!bothEnds || bases.length==r.length());
672 if(!mapped() || !r.mapped()){return false;}
673 // if(chrom==-1 && start==-1){return false;}
674 if(chrom<1 && start<1){return false;}
675
676 // if(chrom!=r.chrom || strand()!=r.strand() || start!=r.start){return false;}
677 //// if(mate==null && stop!=r.stop){return false;} //For unpaired reads, require both ends match
678 // if(stop!=r.stop){return false;} //For unpaired reads, require both ends match
679 // return true;
680
681 if(chrom!=r.chrom || strand()!=r.strand()){return false;}
682
683 if(strand()==Shared.PLUS){
684 if(start!=r.start){return false;}
685 }else{
686 if(stop!=r.stop){return false;}
687 }
688
689 if(checkAlignment){
690 if(perfect() && r.perfect()){return true;}
691 if(match!=null && r.match!=null){
692 int minLen=Tools.min(match.length, r.match.length);
693 for(int i=0; i<minLen; i++){
694 byte a=match[i];
695 byte b=r.match[i];
696 if(a!=b){
697 if((a=='D') != (b=='D')){return false;}
698 if((a=='I' || a=='X' || a=='Y') != (b=='I' || b=='X' || b=='Y')){return false;}
699 }
700 }
701 }
702 }
703 return true;
704 }
705
706 public void merge(Read r, boolean mergeVectors, boolean mergeN){mergePrivate(r, mergeVectors, mergeN, true);}
707
708 private void mergePrivate(Read r, boolean mergeVectors, boolean mergeN, boolean mergeMate){
709 assert(r!=this);
710 assert(r!=this.mate);
711 assert(r!=r.mate);
712 assert(this!=this.mate);
713 assert(r.mate==null || r.mate.mate==r);
714 assert(this.mate==null || this.mate.mate==this);
715 assert(r.mate==null || r.numericID==r.mate.numericID);
716 assert(mate==null || numericID==mate.numericID);
717 mergeN=(mergeN||mergeVectors);
718
719 assert(r.length()==bases.length) : "Merging different-length reads is supported but seems to be not useful.";
720
721 if((mergeN || mergeVectors) && bases.length<r.length()){
722 int oldLenB=bases.length;
723 start=Tools.min(start, r.start);
724 stop=Tools.max(stop, r.stop);
725 mapScore=Tools.max(mapScore, r.mapScore);
726
727 bases=KillSwitch.copyOfRange(bases, 0, r.length());
728 quality=KillSwitch.copyOfRange(quality, 0, r.quality.length);
729 for(int i=oldLenB; i<bases.length; i++){
730 bases[i]='N';
731 quality[i]=0;
732 }
733 match=null;
734 r.match=null;
735 }
736
737 copies+=r.copies;
738
739
740 // if(numericID==11063941 || r.numericID==11063941 || numericID==8715632){
741 // System.err.println("***************");
742 // System.err.println(this.toText()+"\n");
743 // System.err.println(r.toText()+"\n");
744 // System.err.println(mergeVectors+", "+mergeN+", "+mergeMate+"\n");
745 // }
746
747 boolean pflag1=perfect();
748 boolean pflag2=r.perfect();
749
750 final int minLenB=Tools.min(bases.length, r.length());
751
752 if(mergeN){
753 if(quality==null){
754 for(int i=0; i<minLenB; i++){
755 byte b=r.bases[i];
756 if(bases[i]=='N' && b!='N'){bases[i]=b;}
757 }
758 }else{
759 for(int i=0; i<minLenB; i++){
760 final byte b1=bases[i];
761 final byte b2=r.bases[i];
762 final byte q1=Tools.max((byte)0, quality[i]);
763 final byte q2=Tools.max((byte)0, r.quality[i]);
764 if(b1==b2){
765 if(b1=='N'){
766 //do nothing
767 }else if(mergeVectors){
768 //merge qualities
769 // quality[i]=(byte) Tools.min(40, q1+q2);
770 if(q1>=q2){
771 quality[i]=(byte) Tools.min(48, q1+1+q2/4);
772 }else{
773 quality[i]=(byte) Tools.min(48, q2+1+q1/4);
774 }
775 }
776 }else if(b1=='N'){
777 bases[i]=b2;
778 quality[i]=q2;
779 }else if(b2=='N'){
780 //do nothing
781 }else if(mergeVectors){
782 if(q1<1 && q2<1){
783 //Special case - e.g. Illumina calls bases at 0 quality.
784 //Possibly best to keep the matching allele if one matches the ref.
785 //But for now, do nothing.
786 //This was causing problems changing perfect match strings into imperfect matches.
787 }else if(q1==q2){
788 assert(b1!=b2);
789 bases[i]='N';
790 quality[i]=0;
791 }else if(q1>q2){
792 bases[i]=b1;
793 quality[i]=(byte)(q1-q2/2);
794 }else{
795 bases[i]=b2;
796 quality[i]=(byte)(q2-q1/2);
797 }
798 assert(quality[i]>=0 && quality[i]<=48);
799 }
800 }
801 }
802 }
803
804 //TODO:
805 //Note that the read may need to be realigned after merging, so the match string may be rendered incorrect.
806
807 if(mergeN && match!=null){
808 if(r.match==null){match=null;}
809 else{
810 if(match.length!=r.match.length){match=null;}
811 else{
812 boolean ok=true;
813 for(int i=0; i<match.length && ok; i++){
814 byte a=match[i], b=r.match[i];
815 if(a!=b){
816 if((a=='m' || a=='S') && b=='N'){
817 //do nothing;
818 }else if(a=='N' && (b=='m' || b=='S')){
819 match[i]=b;
820 }else{
821 ok=false;
822 }
823 }
824 }
825 if(!ok){match=null;}
826 }
827 }
828 }
829
830 if(mergeMate && mate!=null){
831 mate.mergePrivate(r.mate, mergeVectors, mergeN, false);
832 assert(copies==mate.copies);
833 }
834 assert(copies>1);
835
836 assert(r!=this);
837 assert(r!=this.mate);
838 assert(r!=r.mate);
839 assert(this!=this.mate);
840 assert(r.mate==null || r.mate.mate==r);
841 assert(this.mate==null || this.mate.mate==this);
842 assert(r.mate==null || r.numericID==r.mate.numericID);
843 assert(mate==null || numericID==mate.numericID);
844 }
845
846 @Override
847 public String toString(){return toText(false).toString();}
848
849 public ByteBuilder toSites(){return toSites((ByteBuilder)null);}
850
851 public ByteBuilder toSites(ByteBuilder sb){
852 if(numSites()==0){
853 if(sb==null){sb=new ByteBuilder(2);}
854 sb.append('.');
855 }else{
856 if(sb==null){sb=new ByteBuilder(sites.size()*20);}
857 int appended=0;
858 for(SiteScore ss : sites){
859 if(appended>0){sb.append('\t');}
860 if(ss!=null){
861 ss.toBytes(sb);
862 appended++;
863 }
864 }
865 if(appended==0){sb.append('.');}
866 }
867 return sb;
868 }
869
870 public ByteBuilder toInfo(){
871 if(obj==null){return new ByteBuilder();}
872 if(obj.getClass()==ByteBuilder.class){return (ByteBuilder)obj;}
873 return new ByteBuilder(obj.toString());
874 }
875
876 public ByteBuilder toInfo(ByteBuilder bb){
877 if(obj==null){return bb;}
878 if(obj.getClass()==ByteBuilder.class){return bb.append((ByteBuilder)obj);}
879 return bb.append(obj.toString());
880 }
881
882 public ByteBuilder toFastq(){
883 return FASTQ.toFASTQ(this, (ByteBuilder)null);
884 }
885
886 public ByteBuilder toFastq(ByteBuilder bb){
887 return FASTQ.toFASTQ(this, bb);
888 }
889
890 public ByteBuilder toFasta(){return toFasta(Shared.FASTA_WRAP);}
891 public ByteBuilder toFasta(ByteBuilder bb){return toFasta(Shared.FASTA_WRAP, bb);}
892
893 public ByteBuilder toFasta(int wrap){
894 return toFasta(wrap, (ByteBuilder)null);
895 }
896
897 public ByteBuilder toFasta(int wrap, ByteBuilder bb){
898 if(wrap<1){wrap=Integer.MAX_VALUE;}
899 int len=(id==null ? Tools.stringLength(numericID) : id.length())+(bases==null ? 0 : bases.length+bases.length/wrap)+5;
900 if(bb==null){bb=new ByteBuilder(len+1);}
901 bb.append('>');
902 if(id==null){bb.append(numericID);}
903 else{bb.append(id);}
904 if(bases!=null){
905 int pos=0;
906 while(pos<bases.length-wrap){
907 bb.append('\n');
908 bb.append(bases, pos, wrap);
909 pos+=wrap;
910 }
911 if(pos<bases.length){
912 bb.append('\n');
913 bb.append(bases, pos, bases.length-pos);
914 }
915 }
916 return bb;
917 }
918
919 public ByteBuilder toSam(){
920 return toSam((ByteBuilder)null);
921 }
922
923 public ByteBuilder toSam(ByteBuilder bb){
924 SamLine sl=new SamLine(this, pairnum());
925 // System.err.println("Called toSam on read "+id+"; num="+numericID+", pairnum="+pairnum()+"; result="+sl.toString());
926 return sl.toBytes(bb);
927 }
928
929 public static CharSequence header(){
930
931 StringBuilder sb=new StringBuilder();
932 sb.append("id");
933 sb.append('\t');
934 sb.append("numericID");
935 sb.append('\t');
936 sb.append("chrom");
937 sb.append('\t');
938 sb.append("strand");
939 sb.append('\t');
940 sb.append("start");
941 sb.append('\t');
942 sb.append("stop");
943 sb.append('\t');
944
945 sb.append("flags");
946 sb.append('\t');
947
948 sb.append("copies");
949 sb.append('\t');
950
951 sb.append("errors,fixed");
952 sb.append('\t');
953 sb.append("mapScore");
954 sb.append('\t');
955 sb.append("length");
956 sb.append('\t');
957
958 sb.append("bases");
959 sb.append('\t');
960 sb.append("quality");
961 sb.append('\t');
962
963 sb.append("insert");
964 sb.append('\t');
965 {
966 //These are not really necessary...
967 sb.append("avgQual");
968 sb.append('\t');
969 }
970
971 sb.append("match");
972 sb.append('\t');
973 sb.append("SiteScores: "+SiteScore.header());
974 return sb;
975 }
976
977 public ByteBuilder toText(boolean okToCompressMatch){
978 return toText(okToCompressMatch, (ByteBuilder)null);
979 }
980
981 public ByteBuilder toText(boolean okToCompressMatch, ByteBuilder bb){
982
983 final byte[] oldmatch=match;
984 final boolean oldshortmatch=this.shortmatch();
985 if(COMPRESS_MATCH_BEFORE_WRITING && !shortmatch() && okToCompressMatch){
986 match=toShortMatchString(match);
987 setShortMatch(true);
988 }
989
990 if(bb==null){bb=new ByteBuilder();}
991 bb.append(id);
992 bb.tab();
993 bb.append(numericID);
994 bb.tab();
995 bb.append(chrom);
996 bb.tab();
997 bb.append(Shared.strandCodes2[strand()]);
998 bb.tab();
999 bb.append(start);
1000 bb.tab();
1001 bb.append(stop);
1002 bb.tab();
1003
1004 for(int i=maskArray.length-1; i>=0; i--){
1005 bb.append(flagToNumber(maskArray[i]));
1006 }
1007 bb.tab();
1008
1009 bb.append(copies);
1010 bb.tab();
1011
1012 bb.append(errors);
1013 bb.tab();
1014 bb.append(mapScore);
1015 bb.tab();
1016
1017 if(bases==null){bb.append('.');}
1018 else{bb.append(bases);}
1019 bb.tab();
1020
1021 // int qualSum=0;
1022 // int qualMin=99999;
1023
1024 if(quality==null){
1025 bb.append('.');
1026 }else{
1027 bb.ensureExtra(quality.length);
1028 for(int i=0, j=bb.length; i<quality.length; i++, j++){
1029 byte q=quality[i];
1030 bb.array[j]=(byte)(q+ASCII_OFFSET);
1031 // qualSum+=q;
1032 // qualMin=Tools.min(q, qualMin);
1033 }
1034 bb.length+=quality.length;
1035 }
1036 bb.tab();
1037
1038 if(insert<1){bb.append('.');}else{bb.append(insert);};
1039 bb.tab();
1040
1041 if(true || quality==null){
1042 bb.append('.');
1043 bb.tab();
1044 }else{
1045 // //These are not really necessary...
1046 // sb.append(qualSum/quality.length);
1047 // sb.append('\t');
1048 }
1049
1050 if(match==null){bb.append('.');}
1051 else{bb.append(match);}
1052 bb.tab();
1053
1054 if(gaps==null){
1055 bb.append('.');
1056 }else{
1057 for(int i=0; i<gaps.length; i++){
1058 if(i>0){bb.append('~');}
1059 bb.append(gaps[i]);
1060 }
1061 }
1062
1063 if(sites!=null && sites.size()>0){
1064
1065 assert(absdif(start, stop)<3000 || (gaps==null) == (sites.get(0).gaps==null)) :
1066 "\n"+this.numericID+"\n"+Arrays.toString(gaps)+"\n"+sites.toString()+"\n";
1067
1068 for(SiteScore ss : sites){
1069 bb.tab();
1070 if(ss==null){
1071 bb.append((byte[])null);
1072 }else{
1073 ss.toBytes(bb);
1074 }
1075 bb.append(ss==null ? "null" : ss.toText());
1076 }
1077 }
1078
1079 if(originalSite!=null){
1080 bb.tab();
1081 bb.append('*');
1082 originalSite.toBytes(bb);
1083 }
1084
1085 match=oldmatch;
1086 setShortMatch(oldshortmatch);
1087
1088 return bb;
1089 }
1090
1091 public static Read fromText(String line){
1092 if(line.length()==1 && line.charAt(0)=='.'){return null;}
1093
1094 String[] split=line.split("\t");
1095
1096 // if(split.length<17){
1097 // throw new RuntimeException("Error parsing read from text.\n\n" +
1098 // "This may be caused be attempting to parse the wrong format.\n" +
1099 // "Please ensure that the file extension is correct:\n" +
1100 // "\tFASTQ should end in .fastq or .fq\n" +
1101 // "\tFASTA should end in .fasta or .fa, .fas, .fna, .ffn, .frn, .seq, .fsa\n" +
1102 // "\tSAM should end in .sam\n" +
1103 // "\tNative format should end in .txt or .bread\n" +
1104 // "If a file is compressed, there must be a compression extension after the format extension:\n" +
1105 // "\tgzipped files should end in .gz or .gzip\n" +
1106 // "\tzipped files should end in .zip and have only 1 file per archive\n" +
1107 // "\tbz2 files should end in .bz2\n");
1108 // }
1109
1110 final String id=new String(split[0]);
1111 long numericID=Long.parseLong(split[1]);
1112 int chrom=Byte.parseByte(split[2]);
1113 // byte strand=Byte.parseByte(split[3]);
1114 int start=Integer.parseInt(split[4]);
1115 int stop=Integer.parseInt(split[5]);
1116
1117 int flags=Integer.parseInt(split[6], 2);
1118
1119 int copies=Integer.parseInt(split[7]);
1120
1121 int errors;
1122 int errorsCorrected;
1123 if(split[8].indexOf(',')>=0){
1124 String[] estring=split[8].split(",");
1125 errors=Integer.parseInt(estring[0]);
1126 errorsCorrected=Integer.parseInt(estring[1]);
1127 }else{
1128 errors=Integer.parseInt(split[8]);
1129 errorsCorrected=0;
1130 }
1131
1132 int mapScore=Integer.parseInt(split[9]);
1133
1134 byte[] basesOriginal=split[10].getBytes();
1135 byte[] qualityOriginal=(split[11].equals(".") ? null : split[11].getBytes());
1136
1137 if(qualityOriginal!=null){
1138 for(int i=0; i<qualityOriginal.length; i++){
1139 byte b=qualityOriginal[i];
1140 b=(byte) (b-ASCII_OFFSET);
1141 assert(b>=-1) : b;
1142 qualityOriginal[i]=b;
1143 }
1144 }
1145
1146 int insert=-1;
1147 if(!split[12].equals(".")){insert=Integer.parseInt(split[12]);}
1148
1149 byte[] match=null;
1150 if(!split[14].equals(".")){match=split[14].getBytes();}
1151 int[] gaps=null;
1152 if(!split[15].equals(".")){
1153
1154 String[] gstring=split[16].split("~");
1155 gaps=new int[gstring.length];
1156 for(int i=0; i<gstring.length; i++){
1157 gaps[i]=Integer.parseInt(gstring[i]);
1158 }
1159 }
1160
1161 // assert(false) : split[16];
1162
1163 Read r=new Read(basesOriginal, qualityOriginal, id, numericID, flags, chrom, start, stop);
1164 r.match=match;
1165 r.errors=errors;
1166 r.mapScore=mapScore;
1167 r.copies=copies;
1168 r.gaps=gaps;
1169 r.insert=insert;
1170
1171 int firstScore=(ADD_BEST_SITE_TO_LIST_FROM_TEXT) ? 17 : 18;
1172
1173 int scores=split.length-firstScore;
1174
1175 int mSites=0;
1176 for(int i=firstScore; i<split.length; i++){
1177 if(split[i].charAt(0)!='*'){mSites++;}
1178 }
1179
1180 //This can be disabled to handle very old text format.
1181 if(mSites>0){r.sites=new ArrayList<SiteScore>(mSites);}
1182 for(int i=firstScore; i<split.length; i++){
1183 SiteScore ss=SiteScore.fromText(split[i]);
1184 if(split[i].charAt(0)=='*'){r.originalSite=ss;}
1185 else{r.sites.add(ss);}
1186 }
1187
1188 if(DECOMPRESS_MATCH_ON_LOAD && r.shortmatch()){
1189 r.toLongMatchString(true);
1190 }
1191
1192 assert(r.numSites()==0 || absdif(r.start, r.stop)<3000 || (r.gaps==null) == (r.topSite().gaps==null)) :
1193 "\n"+r.numericID+", "+r.chrom+", "+r.strand()+", "+r.start+", "+r.stop+", "+Arrays.toString(r.gaps)+"\n"+r.sites+"\n"+line+"\n";
1194
1195 return r;
1196 }
1197
1198 /** Inflates gaps between contigs in a scaffold. */
1199 public void inflateGaps(int minGapIn, int minGapOut) {
1200 assert(minGapIn>0);
1201 if(!containsNocalls()){return;}
1202 final ByteBuilder bbb=new ByteBuilder();
1203 final ByteBuilder bbq=(quality==null ? null : new ByteBuilder());
1204
1205 int gap=0;
1206 for(int i=0; i<bases.length; i++){
1207 byte b=bases[i];
1208 byte q=(quality==null ? 0 : quality[i]);
1209 if(b=='N'){
1210 gap++;
1211 }else{
1212 while(gap>=minGapIn && gap<minGapOut){
1213 gap++;
1214 bbb.append('N');
1215 if(bbq!=null){bbq.append(0);}
1216 }
1217 gap=0;
1218 }
1219 bbb.append(b);
1220 if(bbq!=null){bbq.append(q);}
1221 }
1222
1223 while(gap>=minGapIn && gap<minGapOut){//Handle trailing bases
1224 gap++;
1225 bbb.append('N');
1226 if(bbq!=null){bbq.append(0);}
1227 }
1228
1229 assert(bbb.length()>=bases.length);
1230 if(bbb.length()>bases.length){
1231 bases=bbb.toBytes();
1232 if(bbq!=null){quality=bbq.toBytes();}
1233 }
1234 }
1235
1236 public ArrayList<Read> breakAtGaps(final boolean agp, final int minContig){
1237 ArrayList<Read> list=new ArrayList<Read>();
1238 byte prev='N';
1239 int lastN=-1, lastBase=-1;
1240 int contignum=1;
1241 long feature=1;
1242 ByteBuilder bb=(agp ? new ByteBuilder() : null);
1243 assert(obj==null);
1244 for(int i=0; i<bases.length; i++){
1245 final byte b=bases[i];
1246 if(b=='N'){
1247 if(prev!='N'){
1248 final int start=lastN+1, stop=i;
1249 byte[] b2=KillSwitch.copyOfRange(bases, start, stop);
1250 byte[] q2=(quality==null ? null : KillSwitch.copyOfRange(quality, start, stop));
1251 Read r=new Read(b2, q2, id+"_c"+contignum, numericID);
1252 if(r.length()>=minContig){list.add(r);}
1253 contignum++;
1254
1255 if(bb!=null){
1256 bb.append(id).append('\t');
1257 bb.append(start+1).append('\t');
1258 bb.append(stop).append('\t');
1259 bb.append(feature).append('\t');
1260 feature++;
1261 bb.append('W').append('\t');
1262 bb.append(r.id).append('\t');
1263 bb.append(1).append('\t');
1264 bb.append(r.length()).append('\t');
1265 bb.append('+').append('\n');
1266 }
1267 }
1268 lastN=i;
1269 }else{
1270 if(bb!=null && prev=='N' && lastBase>=0){
1271 bb.append(id).append('\t');
1272 bb.append(lastBase+2).append('\t');
1273 bb.append(i).append('\t');
1274 bb.append(feature).append('\t');
1275 feature++;
1276 bb.append('N').append('\t');
1277 bb.append((i-lastBase-1)).append('\t');
1278 bb.append("scaffold").append('\t');
1279 bb.append("yes").append('\t');
1280 bb.append("paired-ends").append('\n');
1281 }
1282 lastBase=i;
1283 }
1284 prev=b;
1285 }
1286 if(prev!='N'){
1287 final int start=lastN+1, stop=bases.length;
1288 byte[] b2=KillSwitch.copyOfRange(bases, start, stop);
1289 byte[] q2=(quality==null ? null : KillSwitch.copyOfRange(quality, start, stop));
1290 Read r=new Read(b2, q2, id+"_c"+contignum, numericID);
1291 if(r.length()>=minContig){list.add(r);}
1292 contignum++;
1293
1294 if(bb!=null){
1295 bb.append(id).append('\t');
1296 bb.append(start+1).append('\t');
1297 bb.append(stop).append('\t');
1298 bb.append(feature).append('\t');
1299 feature++;
1300 bb.append('W').append('\t');
1301 bb.append(r.id).append('\t');
1302 bb.append(1).append('\t');
1303 bb.append(r.length()).append('\t');
1304 bb.append('+').append('\n');
1305 }
1306 }else{
1307 if(bb!=null && prev=='N' && lastBase>=0){
1308 bb.append(id).append('\t');
1309 bb.append(lastBase+2).append('\t');
1310 bb.append(bases.length).append('\t');
1311 bb.append(feature).append('\t');
1312 feature++;
1313 bb.append('N').append('\t');
1314 bb.append((bases.length-lastBase-1)).append('\t');
1315 bb.append("scaffold").append('\t');
1316 bb.append("yes").append('\t');
1317 bb.append("paired-ends").append('\n');
1318 }
1319 lastBase=bases.length;
1320 }
1321 if(bb!=null){obj=bb.toBytes();}
1322 return list;
1323 }
1324
1325 /** Reverse-complements the read. */
1326 public Read reverseComplement() {
1327 AminoAcid.reverseComplementBasesInPlace(bases);
1328 Tools.reverseInPlace(quality);
1329 setStrand(strand()^1);
1330 return this;
1331 }
1332
1333 /** Complements the read. */
1334 public void complement() {
1335 AminoAcid.reverseComplementBasesInPlace(bases);
1336 }
1337
1338 @Override
1339 public int compareTo(Read o) {
1340 if(chrom!=o.chrom){return chrom-o.chrom;}
1341 if(start!=o.start){return start-o.start;}
1342 if(stop!=o.stop){return stop-o.stop;}
1343 if(strand()!=o.strand()){return strand()-o.strand();}
1344 return 0;
1345 }
1346
1347 public SiteScore toSite(){
1348 assert(start<=stop) : this.toText(false);
1349 SiteScore ss=new SiteScore(chrom, strand(), start, stop, 0, 0, rescued(), perfect());
1350 if(paired()){
1351 ss.setSlowPairedScore(mapScore-1, mapScore);
1352 }else{
1353 ss.setSlowPairedScore(mapScore, 0);
1354 }
1355 ss.setScore(mapScore);
1356 ss.gaps=gaps;
1357 ss.match=match;
1358 originalSite=ss;
1359 return ss;
1360 }
1361
1362 public SiteScore topSite(){
1363 final SiteScore ss=(sites==null || sites.isEmpty()) ? null : sites.get(0);
1364 assert(sites==null || sites.isEmpty() || ss!=null) : "Top site is null for read "+this;
1365 return ss;
1366 }
1367
1368 public int numSites(){
1369 return (sites==null ? 0 : sites.size());
1370 }
1371
1372 public SiteScore makeOriginalSite(){
1373 originalSite=toSite();
1374 return originalSite;
1375 }
1376
1377 public void setFromSite(SiteScore ss){
1378 assert(ss!=null);
1379 chrom=ss.chrom;
1380 setStrand(ss.strand);
1381 start=ss.start;
1382 stop=ss.stop;
1383 mapScore=ss.slowScore;
1384 setRescued(ss.rescued);
1385 gaps=ss.gaps;
1386 setPerfect(ss.perfect);
1387
1388 match=ss.match;
1389
1390 if(gaps!=null){
1391 gaps=ss.gaps=GapTools.fixGaps(start, stop, gaps, Shared.MINGAP);
1392 // gaps[0]=Tools.min(gaps[0], start);
1393 // gaps[gaps.length-1]=Tools.max(gaps[gaps.length-1], stop);
1394 }
1395 }
1396
1397 // public static int[] fixGaps(int a, int b, int[] gaps, int minGap){
1398 //// System.err.println("fixGaps input: "+a+", "+b+", "+Arrays.toString(gaps)+", "+minGap);
1399 // int[] r=GapTools.fixGaps(a, b, gaps, minGap);
1400 //// System.err.println("fixGaps output: "+Arrays.toString(r));
1401 // return r;
1402 // }
1403
1404 public void setFromOriginalSite(){
1405 setFromSite(originalSite);
1406 }
1407 public void setFromTopSite(){
1408 final SiteScore ss=topSite();
1409 if(ss==null){
1410 clearSite();
1411 setMapped(false);
1412 return;
1413 }
1414 setMapped(true);
1415 setFromSite(ss);
1416 }
1417
1418 public void setFromTopSite(boolean randomIfAmbiguous, boolean primary, int maxPairDist){
1419 final SiteScore ss0=topSite();
1420 if(ss0==null){
1421 clearSite();
1422 setMapped(false);
1423 return;
1424 }
1425 setMapped(true);
1426
1427 if(sites.size()==1 || !randomIfAmbiguous || !ambiguous()){
1428 setFromSite(ss0);
1429 return;
1430 }
1431
1432 if(primary || mate==null || !mate.mapped() || !mate.paired()){
1433 int count=1;
1434 for(int i=1; i<sites.size(); i++){
1435 SiteScore ss=sites.get(i);
1436 if(ss.score<ss0.score || (ss0.perfect && !ss.perfect) || (ss0.semiperfect && !ss.semiperfect)){break;}
1437 count++;
1438 }
1439
1440 int x=(int)(numericID%count);
1441 if(x>0){
1442 SiteScore ss=sites.get(x);
1443 sites.set(0, ss);
1444 sites.set(x, ss0);
1445 }
1446 setFromSite(sites.get(0));
1447 return;
1448 }
1449
1450 // assert(false) : "TODO: Proper strand orientation, and more.";
1451 //TODO: Also, this code appears to sometimes duplicate sitescores(?)
1452 // for(int i=0; i<list.size(); i++){
1453 // SiteScore ss=list.get(i);
1454 // if(ss.chrom==mate.chrom && Tools.min(Tools.absdifUnsigned(ss.start, mate.stop), Tools.absdifUnsigned(ss.stop, mate.start))<=maxPairDist){
1455 // list.set(0, ss);
1456 // list.set(i, ss0);
1457 // setFromSite(ss);
1458 // return;
1459 // }
1460 // }
1461
1462 //If unsuccessful, recur unpaired.
1463
1464 this.setPaired(false);
1465 mate.setPaired(false);
1466 setFromTopSite(randomIfAmbiguous, true, maxPairDist);
1467 }
1468
1469 public void clearPairMapping(){
1470 clearMapping();
1471 if(mate!=null){mate.clearMapping();}
1472 }
1473
1474 public void clearMapping(){
1475 clearSite();
1476 match=null;
1477 sites=null;
1478 setMapped(false);
1479 setPaired(false);
1480 if(mate!=null){mate.setPaired(false);}
1481 }
1482
1483 public void clearSite(){
1484 chrom=-1;
1485 setStrand(0);
1486 start=-1;
1487 stop=-1;
1488 // errors=0;
1489 mapScore=0;
1490 gaps=null;
1491 }
1492
1493
1494 public void clearAnswers(boolean clearMate) {
1495 // assert(mate==null || (pairnum()==0 && mate.pairnum()==1)) : pairnum()+", "+mate.pairnum();
1496 clearSite();
1497 match=null;
1498 sites=null;
1499 flags=(flags&(SYNTHMASK|PAIRNUMMASK|SWAPMASK));
1500 if(clearMate && mate!=null){
1501 mate.clearSite();
1502 mate.match=null;
1503 mate.sites=null;
1504 mate.flags=(mate.flags&(SYNTHMASK|PAIRNUMMASK|SWAPMASK));
1505 }
1506 // assert(mate==null || (pairnum()==0 && mate.pairnum()==1)) : pairnum()+", "+mate.pairnum();
1507 }
1508
1509
1510 public boolean isBadPair(boolean requireCorrectStrands, boolean sameStrandPairs, int maxdist){
1511 if(mate==null || paired()){return false;}
1512 if(!mapped() || !mate.mapped()){return false;}
1513 if(chrom!=mate.chrom){return true;}
1514
1515 {
1516 int inner;
1517 if(start<=mate.start){inner=mate.start-stop;}
1518 else{inner=start-mate.stop;}
1519 if(inner>maxdist){return true;}
1520 }
1521 // if(absdif(start, mate.start)>maxdist){return true;}
1522 if(requireCorrectStrands){
1523 if((strand()==mate.strand())!=sameStrandPairs){return true;}
1524 }
1525 if(!sameStrandPairs){
1526 if(strand()==Shared.PLUS && mate.strand()==Shared.MINUS){
1527 if(start>=mate.stop){return true;}
1528 }else if(strand()==Shared.MINUS && mate.strand()==Shared.PLUS){
1529 if(mate.start>=stop){return true;}
1530 }
1531 }
1532 return false;
1533 }
1534
1535 public int countMismatches(){
1536 assert(match!=null);
1537 int x=0;
1538 for(byte b : match){
1539 if(b=='S'){x++;}
1540 }
1541 return x;
1542 }
1543
1544 /**
1545 * @param k
1546 * @return Number of valid kmers
1547 */
1548 public int numValidPairKmers(int k) {
1549 return numValidKmers(k)+(mate==null ? 0 : mate.numValidKmers(k));
1550 }
1551
1552 /**
1553 * @param k
1554 * @return Number of valid kmers
1555 */
1556 public int numValidKmers(int k) {
1557 if(bases==null){return 0;}
1558 int len=0, counted=0;
1559 for(int i=0; i<bases.length; i++){
1560 byte b=bases[i];
1561 long x=AminoAcid.baseToNumber[b];
1562 if(x<0){len=0;}else{len++;}
1563 if(len>=k){counted++;}
1564 }
1565 return counted;
1566 }
1567
1568 /**
1569 * @param match string
1570 * @return Total number of match, sub, del, ins, or clip symbols
1571 */
1572 public static final int[] matchToMsdicn(byte[] match) {
1573 if(match==null || match.length<1){return null;}
1574 int[] msdicn=KillSwitch.allocInt1D(6);
1575
1576 byte mode='0', c='0';
1577 int current=0;
1578 for(int i=0; i<match.length; i++){
1579 c=match[i];
1580 if(Tools.isDigit(c)){
1581 current=(current*10)+(c-'0');
1582 }else{
1583 if(mode==c){
1584 current=Tools.max(current+1, 2);
1585 }else{
1586 current=Tools.max(current, 1);
1587
1588 if(mode=='m'){
1589 msdicn[0]+=current;
1590 }else if(mode=='S'){
1591 msdicn[1]+=current;
1592 }else if(mode=='D'){
1593 msdicn[2]+=current;
1594 }else if(mode=='I'){
1595 msdicn[3]+=current;
1596 }else if(mode=='C' || mode=='X' || mode=='Y'){
1597 msdicn[4]+=current;
1598 }else if(mode=='N' || mode=='R'){
1599 msdicn[5]+=current;
1600 }
1601 mode=c;
1602 current=0;
1603 }
1604 }
1605 }
1606 if(current>0 || !Tools.isDigit(c)){
1607 current=Tools.max(current, 1);
1608 if(mode=='m'){
1609 msdicn[0]+=current;
1610 }else if(mode=='S'){
1611 msdicn[1]+=current;
1612 }else if(mode=='D'){
1613 msdicn[2]+=current;
1614 }else if(mode=='I'){
1615 msdicn[3]+=current;
1616 }else if(mode=='C' || mode=='X' || mode=='Y'){
1617 msdicn[4]+=current;
1618 }else if(mode=='N' || mode=='R'){
1619 msdicn[5]+=current;
1620 }
1621 }
1622 return msdicn;
1623 }
1624
1625
1626 /**
1627 * @param match string
1628 * @return Ref length of match string
1629 */
1630 public static final int calcMatchLength(byte[] match) {
1631 if(match==null || match.length<1){return 0;}
1632
1633 byte mode='0', c='0';
1634 int current=0;
1635 int len=0;
1636 for(int i=0; i<match.length; i++){
1637 c=match[i];
1638 if(Tools.isDigit(c)){
1639 current=(current*10)+(c-'0');
1640 }else{
1641 if(mode==c){
1642 current=Tools.max(current+1, 2);
1643 }else{
1644 current=Tools.max(current, 1);
1645
1646 if(mode=='m'){
1647 len+=current;
1648 }else if(mode=='S'){
1649 len+=current;
1650 }else if(mode=='D'){
1651 len+=current;
1652 }else if(mode=='I'){ //Do nothing
1653 //len+=current;
1654 }else if(mode=='C'){
1655 len+=current;
1656 }else if(mode=='X'){ //Not sure about this case, but adding seems fine
1657 len+=current;
1658 // assert(false) : new String(match);
1659 }else if(mode=='Y'){ //Do nothing
1660 //len+=current;
1661 // assert(false) : new String(match);
1662 }else if(mode=='N' || mode=='R'){
1663 len+=current;
1664 }
1665 mode=c;
1666 current=0;
1667 }
1668 }
1669 }
1670 if(current>0 || !Tools.isDigit(c)){
1671 current=Tools.max(current, 1);
1672 if(mode=='m'){
1673 len+=current;
1674 }else if(mode=='S'){
1675 len+=current;
1676 }else if(mode=='D'){
1677 len+=current;
1678 }else if(mode=='I'){ //Do nothing
1679 //len+=current;
1680 }else if(mode=='C'){
1681 len+=current;
1682 }else if(mode=='X'){ //Not sure about this case, but adding seems fine
1683 len+=current;
1684 assert(false) : new String(match);
1685 }else if(mode=='Y'){ //Do nothing
1686 //len+=current;
1687 // assert(false) : new String(match);
1688 }else if(mode=='N' || mode=='R'){
1689 len+=current;
1690 }
1691 }
1692 return len;
1693 }
1694
1695 public final float identity() {return identity(match);}
1696
1697 public static final float identity(byte[] match) {
1698 if(FLAT_IDENTITY){
1699 return identityFlat(match, true);
1700 }else{
1701 return identitySkewed(match, true, true, false, false);
1702 }
1703 }
1704
1705 public final boolean hasLongInsertion(int maxlen){
1706 return hasLongInsertion(match, maxlen);
1707 }
1708
1709 public final boolean hasLongDeletion(int maxlen){
1710 return hasLongDeletion(match, maxlen);
1711 }
1712
1713 public static final boolean hasLongInsertion(byte[] match, int maxlen){
1714 if(match==null || match.length<maxlen){return false;}
1715 byte prev='0';
1716 int len=0;
1717 for(byte b : match){
1718 if(b=='I' || b=='X' || b=='Y'){
1719 if(b==prev){len++;}
1720 else{len=1;}
1721 if(len>maxlen){return true;}
1722 }else{
1723 len=0;
1724 }
1725 prev=b;
1726 }
1727 return false;
1728 }
1729
1730 public static final boolean hasLongDeletion(byte[] match, int maxlen){
1731 if(match==null || match.length<maxlen){return false;}
1732 byte prev='0';
1733 int len=0;
1734 for(byte b : match){
1735 if(b=='D'){
1736 if(b==prev){len++;}
1737 else{len=1;}
1738 if(len>maxlen){return true;}
1739 }else{
1740 len=0;
1741 }
1742 prev=b;
1743 }
1744 return false;
1745 }
1746
1747 public int mappedNonClippedBases() {
1748 if(!mapped() || match==null || bases==null){return 0;}
1749
1750 int len=0;
1751 byte mode='0', c='0';
1752 int current=0;
1753 for(int i=0; i<match.length; i++){
1754 c=match[i];
1755 if(Tools.isDigit(c)){
1756 current=(current*10)+(c-'0');
1757 }else{
1758 if(mode==c){
1759 current=Tools.max(current+1, 2);
1760 }else{
1761 current=Tools.max(current, 1);
1762
1763 if(mode=='D' || mode=='C' || mode=='X' || mode=='Y' || mode=='d'){
1764
1765 }else{
1766 len+=current;
1767 }
1768 mode=c;
1769 current=0;
1770 }
1771 }
1772 }
1773 if(current>0 || !Tools.isDigit(c)){
1774 current=Tools.max(current, 1);
1775 if(mode=='D' || mode=='C' || mode=='X' || mode=='Y' || mode=='d'){
1776
1777 }else{
1778 len+=current;
1779 }
1780 mode=c;
1781 current=0;
1782 }
1783 return len;
1784 }
1785
1786 /**
1787 * Handles short or long mode.
1788 * @param match string
1789 * @return Identity based on number of match, sub, del, ins, or N symbols
1790 */
1791 public static final float identityFlat(byte[] match, boolean penalizeN) {
1792 // assert(false) : new String(match);
1793 if(match==null || match.length<1){return 0;}
1794
1795 int good=0, bad=0, n=0;
1796
1797 byte mode='0', c='0';
1798 int current=0;
1799 for(int i=0; i<match.length; i++){
1800 c=match[i];
1801 if(Tools.isDigit(c)){
1802 current=(current*10)+(c-'0');
1803 }else{
1804 if(mode==c){
1805 current=Tools.max(current+1, 2);
1806 }else{
1807 current=Tools.max(current, 1);
1808
1809 if(mode=='m'){
1810 good+=current;
1811 // System.out.println("G: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1812 }else if(mode=='R' || mode=='N'){
1813 n+=current;
1814 }else if(mode=='C' || mode=='V'){
1815 //Do nothing
1816 //I assume this is clipped because it went off the end of a scaffold, and thus is irrelevant to identity
1817 }else if(mode!='0'){
1818 assert(mode=='S' || mode=='D' || mode=='I' || mode=='X' || mode=='Y' || mode=='i' || mode=='d') : (char)mode;
1819 if(mode!='D' || current<SamLine.INTRON_LIMIT){
1820 bad+=current;
1821 }
1822 // System.out.println("B: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1823 }
1824 mode=c;
1825 current=0;
1826 }
1827 }
1828 }
1829 if(current>0 || !Tools.isDigit(c)){
1830 current=Tools.max(current, 1);
1831 if(mode=='m'){
1832 good+=current;
1833 }else if(mode=='R' || mode=='N'){
1834 n+=current;
1835 }else if(mode=='C' || mode=='V'){
1836 //Do nothing
1837 //I assume this is clipped because it went off the end of a scaffold, and thus is irrelevant to identity
1838 }else if(mode!='0'){
1839 assert(mode=='S' || mode=='I' || mode=='X' || mode=='Y') : (char)mode;
1840 if(mode!='D' || current<SamLine.INTRON_LIMIT){
1841 bad+=current;
1842 }
1843 // System.out.println("B: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1844 }
1845 }
1846
1847
1848 float good2=good+n*(penalizeN ? 0.25f : 0);
1849 float bad2=bad+n*(penalizeN ? 0.75f : 0);
1850 float r=good2/Tools.max(good2+bad2, 1);
1851 // assert(false) : new String(match)+"\nmode='"+(char)mode+"', current="+current+", good="+good+", bad="+bad;
1852
1853 // System.out.println("match="+new String(match)+"\ngood="+good+", bad="+bad+", r="+r);
1854 // System.out.println(Arrays.toString(matchToMsdicn(match)));
1855
1856 return r;
1857 }
1858
1859 /**
1860 * Handles short or long mode.
1861 * @param match string
1862 * @return Identity based on number of match, sub, del, ins, or N symbols
1863 */
1864 public static final float identitySkewed(byte[] match, boolean penalizeN, boolean sqrt, boolean log, boolean single) {
1865 // assert(false) : new String(match);
1866 if(match==null || match.length<1){return 0;}
1867
1868 int good=0, bad=0, n=0;
1869
1870 byte mode='0', c='0';
1871 int current=0;
1872 for(int i=0; i<match.length; i++){
1873 c=match[i];
1874 if(Tools.isDigit(c)){
1875 current=(current*10)+(c-'0');
1876 }else{
1877 if(mode==c){
1878 current=Tools.max(current+1, 2);
1879 }else{
1880 current=Tools.max(current, 1);
1881
1882 if(mode=='m'){
1883 good+=current;
1884 // System.out.println("G: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1885 }else if(mode=='D'){
1886 if(current<SamLine.INTRON_LIMIT){
1887 int x;
1888
1889 if(sqrt){x=(int)Math.ceil(Math.sqrt(current));}
1890 else if(log){x=(int)Math.ceil(Tools.log2(current));}
1891 else{x=1;}
1892
1893 bad+=(Tools.min(x, current));
1894 }
1895
1896 // System.out.println("D: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad+", x="+x);
1897 }else if(mode=='R' || mode=='N'){
1898 n+=current;
1899 }else if(mode=='C' || mode=='V'){
1900 //Do nothing
1901 //I assume this is clipped because it went off the end of a scaffold, and thus is irrelevant to identity
1902 }else if(mode!='0'){
1903 assert(mode=='S' || mode=='I' || mode=='X' || mode=='Y' || mode=='i' || mode=='d') : (char)mode;
1904 bad+=current;
1905 // System.out.println("B: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1906 }
1907 mode=c;
1908 current=0;
1909 }
1910 }
1911 }
1912 if(current>0 || !Tools.isDigit(c)){
1913 current=Tools.max(current, 1);
1914 if(mode=='m'){
1915 good+=current;
1916 }else if(mode=='R' || mode=='N'){
1917 n+=current;
1918 }else if(mode=='C' || mode=='V'){
1919 //Do nothing
1920 //I assume this is clipped because it went off the end of a scaffold, and thus is irrelevant to identity
1921 }else if(mode!='0'){
1922 assert(mode=='S' || mode=='I' || mode=='X' || mode=='Y') : (char)mode;
1923 if(mode!='D' || current<SamLine.INTRON_LIMIT){
1924 bad+=current;
1925 }
1926 // System.out.println("B: mode="+(char)mode+", c="+(char)c+", current="+current+", good="+good+", bad="+bad);
1927 }
1928 }
1929
1930
1931 float good2=good+n*(penalizeN ? 0.25f : 0);
1932 float bad2=bad+n*(penalizeN ? 0.75f : 0);
1933 float r=good2/Tools.max(good2+bad2, 1);
1934 // assert(false) : new String(match)+"\nmode='"+(char)mode+"', current="+current+", good="+good+", bad="+bad;
1935
1936 // System.out.println("match="+new String(match)+"\ngood="+good+", bad="+bad+", r="+r);
1937 // System.out.println(Arrays.toString(matchToMsdicn(match)));
1938
1939 return r;
1940 }
1941
1942 public boolean failsChastity(){
1943 return failsChastity(true);
1944 }
1945
1946 public boolean failsChastity(boolean processAssertions){
1947 if(id==null){return false;}
1948 int space=id.indexOf(' ');
1949 if(space<0 || space+5>id.length()){return false;}
1950 char a=id.charAt(space+1);
1951 char b=id.charAt(space+2);
1952 char c=id.charAt(space+3);
1953 char d=id.charAt(space+4);
1954
1955 if(a=='/'){
1956 if(b<'1' || b>'4' || c!=':'){
1957 if(!processAssertions){return false;}
1958 KillSwitch.kill("Strangely formatted read. Please disable chastityfilter with the flag chastityfilter=f. id:"+id);
1959 }
1960 return d=='Y';
1961 }else{
1962 if(processAssertions){
1963 assert(a=='1' || a=='2' || a=='3' || a=='4') : id;
1964 assert(b==':') : id;
1965 assert(d==':');
1966 }
1967 if(a<'1' || a>'4' || b!=':' || d!=':'){
1968 if(!processAssertions){return false;}
1969 KillSwitch.kill("Strangely formatted read. Please disable chastityfilter with the flag chastityfilter=f. id:"+id);
1970 }
1971 return c=='Y';
1972 }
1973 }
1974
1975 public boolean failsBarcode(HashSet<String> set, boolean failIfNoBarcode){
1976 if(id==null){return false;}
1977
1978 final int loc=id.lastIndexOf(':');
1979 final int loc2=Tools.max(id.indexOf(' '), id.indexOf('/'));
1980 if(loc<0 || loc<=loc2 || loc>=id.length()-1){
1981 return failIfNoBarcode;
1982 }
1983
1984 if(set==null){
1985 for(int i=loc+1; i<id.length(); i++){
1986 char c=id.charAt(i);
1987 boolean ok=(c=='+' || AminoAcid.isFullyDefined(c));
1988 if(!ok){return true;}
1989 }
1990 return false;
1991 }else{
1992 String code=id.substring(loc+1);
1993 return !set.contains(code);
1994 }
1995 }
1996
1997 public String barcode(boolean failIfNoBarcode){
1998 return headerToBarcode(id, failIfNoBarcode);
1999 }
2000
2001 /**
2002 * Parse the barcode from an Illumina header.
2003 * @param failIfNoBarcode Terminate the JVM if no barcode is present.
2004 * @return The barcode
2005 */
2006 public static String headerToBarcode(String id, boolean failIfNoBarcode){
2007
2008 if(id==null){
2009 if(failIfNoBarcode && Shared.EA()){
2010 KillSwitch.kill("Encountered a read header without a barcode:\n"+id+"\n");
2011 }
2012 return null;
2013 }
2014
2015 final int loc=id.lastIndexOf(':');
2016 final int loc2=Tools.max(id.indexOf(' '), id.indexOf('/'));
2017 if(loc<0 || loc<=loc2 || loc>=id.length()-1){
2018 if(failIfNoBarcode && Shared.EA()){
2019 KillSwitch.kill("Encountered a read header without a barcode:\n"+id+"\n");
2020 }
2021 return null;
2022 }
2023
2024 //This section allows for comments after the barcode
2025 final int bcStart=loc+1;
2026 int bcStop=id.indexOf(' ', bcStart);
2027 bcStop=(bcStop>=0 ? bcStop : id.indexOf('\t', bcStart));
2028 String code;
2029 if(bcStop<0) {
2030 code=id.substring(bcStart);
2031 }else {
2032 code=id.substring(bcStart, bcStop);
2033 }
2034
2035 return code;
2036 }
2037
2038 /**
2039 * @return The rname of this Read's SamLine, if present and mapped.
2040 */
2041 public String rnameS() {
2042 if(samline==null || !samline.mapped()){return null;}
2043 return samline.rnameS();
2044 }
2045
2046 /** Average based on summing quality scores */
2047 public double avgQuality(boolean countUndefined, int maxBases){
2048 return AVERAGE_QUALITY_BY_PROBABILITY ? avgQualityByProbabilityDouble(countUndefined, maxBases) : avgQualityByScoreDouble(maxBases);
2049 }
2050
2051 /** Average based on summing quality scores */
2052 public int avgQualityInt(boolean countUndefined, int maxBases){
2053 return AVERAGE_QUALITY_BY_PROBABILITY ? avgQualityByProbabilityInt(countUndefined, maxBases) : avgQualityByScoreInt(maxBases);
2054 }
2055
2056 /** Average based on summing error probabilities */
2057 public int avgQualityByProbabilityInt(boolean countUndefined, int maxBases){
2058 if(bases==null || bases.length==0){return 0;}
2059 return avgQualityByProbabilityInt(bases, quality, countUndefined, maxBases);
2060 }
2061
2062 /** Average based on summing error probabilities */
2063 public double avgQualityByProbabilityDouble(boolean countUndefined, int maxBases){
2064 if(bases==null || bases.length==0){return 0;}
2065 return avgQualityByProbabilityDouble(bases, quality, countUndefined, maxBases);
2066 }
2067
2068 /** Average based on summing error probabilities */
2069 public double probabilityErrorFree(boolean countUndefined, int maxBases){
2070 if(bases==null || bases.length==0){return 0;}
2071 return probabilityErrorFree(bases, quality, countUndefined, maxBases);
2072 }
2073
2074 /** Average based on summing error probabilities */
2075 public static int avgQualityByProbabilityInt(byte[] bases, byte[] quality, boolean countUndefined, int maxBases){
2076 if(quality==null){return 40;}
2077 if(quality.length==0){return 0;}
2078 float e=expectedErrors(bases, quality, countUndefined, maxBases);
2079 final int div=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2080 float p=e/div;
2081 return QualityTools.probErrorToPhred(p);
2082 }
2083
2084 /** Average based on summing error probabilities */
2085 public static double avgQualityByProbabilityDouble(byte[] bases, byte[] quality, boolean countUndefined, int maxBases){
2086 if(quality==null){return 40;}
2087 if(quality.length==0){return 0;}
2088 float e=expectedErrors(bases, quality, countUndefined, maxBases);
2089 final int div=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2090 float p=e/div;
2091 return QualityTools.probErrorToPhredDouble(p);
2092 }
2093
2094 /** Average based on summing quality scores */
2095 public int avgQualityByScoreInt(int maxBases){
2096 if(bases==null || bases.length==0){return 0;}
2097 if(quality==null){return 40;}
2098 int x=0, limit=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2099 for(int i=0; i<limit; i++){
2100 byte b=quality[i];
2101 x+=(b<0 ? 0 : b);
2102 }
2103 return x/limit;
2104 }
2105
2106 /** Average based on summing quality scores */
2107 public double avgQualityByScoreDouble(int maxBases){
2108 if(bases==null || bases.length==0){return 0;}
2109 if(quality==null){return 40;}
2110 int x=0, limit=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2111 for(int i=0; i<limit; i++){
2112 byte b=quality[i];
2113 x+=(b<0 ? 0 : b);
2114 }
2115 return x/(double)limit;
2116 }
2117
2118 /** Used by BBMap tipsearch. */
2119 public int avgQualityFirstNBases(int n){
2120 if(bases==null || bases.length==0){return 0;}
2121 if(quality==null || n<1){return 40;}
2122 assert(quality!=null);
2123 int x=0;
2124 if(n>quality.length){return 0;}
2125 for(int i=0; i<n; i++){
2126 byte b=quality[i];
2127 x+=(b<0 ? 0 : b);
2128 }
2129 return x/n;
2130 }
2131
2132 /** Used by BBMap tipsearch. */
2133 public int avgQualityLastNBases(int n){
2134 if(bases==null || bases.length==0){return 0;}
2135 if(quality==null || n<1){return 40;}
2136 assert(quality!=null);
2137 int x=0;
2138 if(n>quality.length){return 0;}
2139 for(int i=bases.length-n; i<bases.length; i++){
2140 byte b=quality[i];
2141 x+=(b<0 ? 0 : b);
2142 }
2143 return x/n;
2144 }
2145
2146 /** Used by BBDuk. */
2147 public int minQuality(){
2148 byte min=41;
2149 if(bases!=null && quality!=null){
2150 for(byte q : quality){
2151 min=Tools.min(min, q);
2152 }
2153 }
2154 return min;
2155 }
2156
2157 /** Used by BBMap tipsearch. */
2158 public byte minQualityFirstNBases(int n){
2159 if(bases==null || bases.length==0){return 0;}
2160 if(quality==null || n<1){return 41;}
2161 assert(quality!=null && n>0);
2162 if(n>quality.length){return 0;}
2163 byte x=quality[0];
2164 for(int i=1; i<n; i++){
2165 byte b=quality[i];
2166 if(b<x){x=b;}
2167 }
2168 return x;
2169 }
2170
2171 /** Used by BBMap tipsearch. */
2172 public byte minQualityLastNBases(int n){
2173 if(bases==null || bases.length==0){return 0;}
2174 if(quality==null || n<1){return 41;}
2175 assert(quality!=null && n>0);
2176 if(n>quality.length){return 0;}
2177 byte x=quality[bases.length-n];
2178 for(int i=bases.length-n; i<bases.length; i++){
2179 byte b=quality[i];
2180 if(b<x){x=b;}
2181 }
2182 return x;
2183 }
2184
2185 public boolean containsNonM(){
2186 assert(match!=null && valid());
2187 for(int i=0; i<match.length; i++){
2188 byte b=match[i];
2189 assert(b!='M');
2190 if(b>'9' && b!='m'){return true;}
2191 }
2192 return false;
2193 }
2194
2195 public boolean containsNonNM(){
2196 assert(match!=null && valid());
2197 for(int i=0; i<match.length; i++){
2198 byte b=match[i];
2199 assert(b!='M');
2200 if(b>'9' && b!='m' && b!='N'){return true;}
2201 }
2202 return false;
2203 }
2204
2205 public boolean containsVariants(){
2206 assert(match!=null && valid()) : (match==null)+", "+(valid())+"\n"+samline+"\n";
2207 for(int i=0; i<match.length; i++){
2208 byte b=match[i];
2209 assert(b!='M');
2210 if(b>'9' && b!='m' && b!='N' && b!='C'){return true;}
2211 }
2212 return false;
2213 }
2214
2215 public boolean containsClipping(){
2216 assert(match!=null && valid()) : (match==null)+", "+(valid())+"\n"+samline+"\n";
2217 if(match.length<1){return false;}
2218 if(match[0]=='C'){return true;}
2219 for(int i=match.length-1; i>0; i--){
2220 if(match[i]=='C'){return true;}
2221 if(match[i]>'9'){break;}
2222 }
2223 return false;
2224 }
2225
2226 public int countAlignedBases() {
2227 return countAlignedBases(match);
2228 }
2229
2230 public static int countAlignedBases(byte[] match) {
2231 //Short version; correct but slow
2232 // int[] sym=countMatchSymbols(match);
2233 // return sym[0]+sym[1]+sym[4];
2234
2235 //Long version; faster
2236 int msi=0;
2237 int current=0;
2238 byte last='?';
2239 for(byte b : match){
2240 if(Tools.isDigit(b)){
2241 current=current*10+b-'0';
2242 }else{
2243 current=Tools.max(current, 1);
2244 if(last=='m' || last=='S' || last=='I'){
2245 msi+=current;
2246 }
2247 else{
2248 //Ignore
2249 assert(last=='?' || last=='C' || last=='N' || last=='D') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2250 }
2251 current=0;
2252 last=b;
2253 }
2254 }
2255 current=Tools.max(current, 1);
2256 if(last=='m' || last=='S' || last=='I'){
2257 msi+=current;
2258 }
2259 else{
2260 //Ignore
2261 assert(last=='?' || last=='C' || last=='N' || last=='D') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2262 }
2263 current=0;
2264 return msi;
2265 }
2266
2267 //This ignores N and clip, and counts each deletion event as a single error
2268 public int countErrors(){
2269 return countErrors(match);
2270 }
2271
2272 //This ignores N and clip, and counts each deletion event as a single error
2273 public static int countErrors(byte[] match){
2274 int m=0, S=0, C=0, N=0, I=0, D=0;
2275 int current=0;
2276 byte last='?';
2277 for(byte b : match){
2278 if(Tools.isDigit(b)){
2279 current=current*10+b-'0';
2280 }else{
2281 current=Tools.max(current, 1);
2282 if(last=='m'){
2283 m+=current;
2284 }else if(last=='S'){
2285 S+=current;
2286 }else if(last=='C'){
2287 C+=current;
2288 }else if(last=='N'){
2289 N+=current;
2290 }else if(last=='I'){
2291 I+=current;
2292 }else if(last=='D'){
2293 D++;
2294 }else{
2295 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2296 }
2297 current=0;
2298 last=b;
2299 }
2300 }
2301 current=Tools.max(current, 1);
2302 if(last=='m'){
2303 m+=current;
2304 }else if(last=='S'){
2305 S+=current;
2306 }else if(last=='C'){
2307 C+=current;
2308 }else if(last=='N'){
2309 N+=current;
2310 }else if(last=='I'){
2311 I+=current;
2312 }else if(last=='D'){
2313 D++;
2314 }else{
2315 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2316 }
2317 current=0;
2318 int errors=S+I+D;
2319 // if(errors>30) {System.err.println(errors+": "+new String(match));}
2320 return errors;
2321 }
2322
2323 /**
2324 * @return {m,S,C,N,I,D};
2325 */
2326 public int[] countMatchSymbols(){
2327 return countMatchSymbols(match);
2328 }
2329
2330 /**
2331 * @return {m,S,C,N,I,D};
2332 */
2333 public static int[] countMatchSymbols(byte[] match){
2334 int m=0, S=0, C=0, N=0, I=0, D=0;
2335 int current=0;
2336 byte last='?';
2337 for(byte b : match){
2338 if(Tools.isDigit(b)){
2339 current=current*10+b-'0';
2340 }else{
2341 current=Tools.max(current, 1);
2342 if(last=='m'){
2343 m+=current;
2344 }else if(last=='S'){
2345 S+=current;
2346 }else if(last=='C'){
2347 C+=current;
2348 }else if(last=='N'){
2349 N+=current;
2350 }else if(last=='I'){
2351 I+=current;
2352 }else if(last=='D'){
2353 D+=current;
2354 }else{
2355 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2356 }
2357 current=0;
2358 last=b;
2359 }
2360 }
2361 current=Tools.max(current, 1);
2362 if(last=='m'){
2363 m+=current;
2364 }else if(last=='S'){
2365 S+=current;
2366 }else if(last=='C'){
2367 C+=current;
2368 }else if(last=='N'){
2369 N+=current;
2370 }else if(last=='I'){
2371 I+=current;
2372 }else if(last=='D'){
2373 D+=current;
2374 }else{
2375 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2376 }
2377 current=0;
2378 return new int[] {m,S,C,N,I,D};
2379 }
2380
2381 /**
2382 * Here, consecutive symbols are collapsed, so mmmDDDmmmm would yield 2 m and 1 D.
2383 * @return {m,S,C,N,I,D};
2384 */
2385 public static int[] countMatchEvents(byte[] match){
2386 int m=0, S=0, C=0, N=0, I=0, D=0;
2387 int current=0;
2388 byte last='?';
2389 for(byte b : match){
2390 if(Tools.isDigit(b)){
2391 current=current*10+b-'0';
2392 }else{
2393 current=Tools.max(current, 1);
2394 if(last=='m'){
2395 m++;
2396 }else if(last=='S'){
2397 S++;
2398 }else if(last=='C'){
2399 C++;
2400 }else if(last=='N'){
2401 N++;
2402 }else if(last=='I'){
2403 I++;
2404 }else if(last=='D'){
2405 D++;
2406 }else{
2407 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2408 }
2409 current=0;
2410 last=b;
2411 }
2412 }
2413 current=Tools.max(current, 1);
2414 if(last=='m'){
2415 m++;
2416 }else if(last=='S'){
2417 S++;
2418 }else if(last=='C'){
2419 C++;
2420 }else if(last=='N'){
2421 N++;
2422 }else if(last=='I'){
2423 I++;
2424 }else if(last=='D'){
2425 D++;
2426 }else{
2427 assert(last=='?') : "Unhandled symbol "+(char)last+"\n"+new String(match);
2428 }
2429 current=0;
2430 return new int[] {m,S,C,N,I,D};
2431 }
2432
2433 public boolean containsNonNMXY(){
2434 assert(match!=null && valid());
2435 for(int i=0; i<match.length; i++){
2436 byte b=match[i];
2437 assert(b!='M');
2438 if(b>'9' && b!='m' && b!='N' && b!='X' && b!='Y'){return true;}
2439 }
2440 return false;
2441 }
2442
2443 public boolean containsSDI(){
2444 assert(match!=null && valid());
2445 for(int i=0; i<match.length; i++){
2446 byte b=match[i];
2447 assert(b!='M');
2448 if(b=='S' || b=='s' || b=='D' || b=='I'){return true;}
2449 }
2450 return false;
2451 }
2452
2453 public boolean containsNonNMS(){
2454 assert(match!=null && valid());
2455 for(int i=0; i<match.length; i++){
2456 byte b=match[i];
2457 assert(b!='M');
2458 if(b>'9' && b!='m' && b!='s' && b!='N' && b!='S'){return true;}
2459 }
2460 return false;
2461 }
2462
2463 public boolean containsConsecutiveS(int num){
2464 assert(match!=null && valid() && !shortmatch());
2465 int cnt=0;
2466 for(int i=0; i<match.length; i++){
2467 byte b=match[i];
2468 assert(b!='M');
2469 if(b=='S'){
2470 cnt++;
2471 if(cnt>=num){return true;}
2472 }else{
2473 cnt=0;
2474 }
2475 }
2476 return false;
2477 }
2478
2479 public boolean containsIndels(){
2480 assert(match!=null && valid());
2481 for(int i=0; i<match.length; i++){
2482 byte b=match[i];
2483 if(b=='I' || b=='D' || b=='X' || b=='Y'){return true;}
2484 }
2485 return false;
2486 }
2487
2488 public int countSubs(){
2489 assert(match!=null && valid()) : (match!=null)+", "+valid()+", "+shortmatch();
2490 return countSubs(match);
2491 }
2492
2493 public boolean containsInMatch(char c){
2494 assert(match!=null && valid());
2495 for(int i=0; i<match.length; i++){
2496 byte b=match[i];
2497 if(b==c){return true;}
2498 }
2499 return false;
2500 }
2501
2502 public boolean containsNocalls(){
2503 for(int i=0; i<bases.length; i++){
2504 byte b=bases[i];
2505 if(b=='N'){return true;}
2506 }
2507 return false;
2508 }
2509
2510 public int countNocalls(){
2511 return countNocalls(bases);
2512 }
2513
2514 public int longestHomopolymer(){
2515 return longestHomopolymer(bases);
2516 }
2517
2518 public static int countSubs(byte[] match){
2519 int S=0;
2520 int current=0;
2521 byte last='?';
2522 for(byte b : match){
2523 if(Tools.isDigit(b)){
2524 current=current*10+b-'0';
2525 }else{
2526 if(last=='S'){S+=Tools.max(1, current);}
2527 current=0;
2528 last=b;
2529 }
2530 }
2531 if(last=='S'){S+=Tools.max(1, current);}
2532 // assert(S==0) : S+"\t"+new String(match);
2533 return S;
2534 // int x=0;
2535 // assert(match!=null);
2536 // for(int i=0; i<match.length; i++){
2537 // byte b=match[i];
2538 // if(b=='S'){x++;}
2539 // assert(!Tools.isDigit(b));
2540 // }
2541 // return x;
2542 }
2543
2544 public static int countVars(byte[] match){
2545 return countVars(match, true, true, true);
2546 }
2547
2548 public static int countVars(byte[] match, boolean sub, boolean ins, boolean del){
2549 int S=0, I=0, D=0;
2550 int current=0;
2551 byte last='?';
2552 for(byte b : match){
2553 if(Tools.isDigit(b)){
2554 current=current*10+b-'0';
2555 }else{
2556 if(last=='S'){S+=Tools.max(1, current);}
2557 else if(last=='I'){I++;}
2558 else if(last=='D'){D++;}
2559 current=0;
2560 last=b;
2561 }
2562 }
2563 if(last=='S'){S+=Tools.max(1, current);}
2564 else if(last=='I'){I++;}
2565 else if(last=='D'){D++;}
2566 return (sub ? S : 0)+(ins ? I : 0)+(del ? D : 0);
2567 }
2568
2569 public static boolean containsSubs(byte[] match){
2570 int x=0;
2571 assert(match!=null);
2572 for(int i=0; i<match.length; i++){
2573 byte b=match[i];
2574 if(b=='S'){return true;}
2575 }
2576 return false;
2577 }
2578
2579 public static boolean containsVars(byte[] match){
2580 int x=0;
2581 assert(match!=null);
2582 for(int i=0; i<match.length; i++){
2583 byte b=match[i];
2584 if(b=='S' || b=='I' || b=='D'){return true;}
2585 }
2586 return false;
2587 }
2588
2589 public static int countNocalls(byte[] match){
2590 int n=0;
2591 for(int i=0; i<match.length; i++){
2592 byte b=match[i];
2593 if(b=='N'){n++;}
2594 }
2595 return n;
2596 }
2597
2598 public static int countUndefined(byte[] bases){
2599 return countUndefined(bases, 0, bases.length-1);
2600 }
2601
2602 public static int countUndefined(byte[] bases, int from, int to){
2603 int n=0;
2604 if(bases==null) {return 0;}
2605 for(int i=from; i<=to; i++){
2606 n+=(AminoAcid.isFullyDefined(bases[i]) ? 0 : 1);
2607 }
2608 return n;
2609 }
2610
2611 public static int longestHomopolymer(byte[] bases){
2612 return longestHomopolymer(bases, 0, bases.length-1);
2613 }
2614
2615 public static int longestHomopolymer(byte[] bases, int from, int to){
2616 int max=0, streak=0;
2617 if(bases==null) {return 0;}
2618 for(int i=from, prev=-1; i<=to; i++){
2619 final byte b=bases[i];
2620 if(b==prev && AminoAcid.isFullyDefined(b)) {
2621 streak++;
2622 }else {
2623 max=Tools.max(max, streak);
2624 streak=1;
2625 prev=b;
2626 }
2627 }
2628 return Tools.max(max, streak);
2629 }
2630
2631 public static int countInsertions(byte[] match){
2632 int n=0;
2633 for(int i=0; i<match.length; i++){
2634 byte b=match[i];
2635 if(b=='I'){n++;}
2636 }
2637 return n;
2638 }
2639
2640 public static int countDeletions(byte[] match){
2641 int n=0;
2642 for(int i=0; i<match.length; i++){
2643 byte b=match[i];
2644 if(b=='D'){n++;}
2645 }
2646 return n;
2647 }
2648
2649 public static int countInsertionEvents(byte[] match){
2650 int n=0;
2651 byte prev='N';
2652 for(int i=0; i<match.length; i++){
2653 byte b=match[i];
2654 if(b=='I' && prev!=b){n++;}
2655 prev=b;
2656 }
2657 return n;
2658 }
2659
2660 public static int countDeletionEvents(byte[] match){
2661 int n=0;
2662 byte prev='N';
2663 for(int i=0; i<match.length; i++){
2664 byte b=match[i];
2665 if(b=='D' && prev!=b){n++;}
2666 prev=b;
2667 }
2668 return n;
2669 }
2670
2671 public boolean containsNonACGTN(){
2672 if(bases==null){return false;}
2673 for(byte b : bases){
2674 if(AminoAcid.baseToNumberACGTN[b]<0){return true;}
2675 }
2676 return false;
2677 }
2678
2679 public boolean containsUndefined(){
2680 if(bases==null){return false;}
2681 final byte[] symbolToNumber=AminoAcid.symbolToNumber(amino());
2682 for(byte b : bases){
2683 if(symbolToNumber[b]<0){return true;}
2684 }
2685 return false;
2686 }
2687
2688 public boolean containsLowercase(){
2689 if(bases==null){return false;}
2690 for(byte b : bases){
2691 if(Tools.isLowerCase(b)){return true;}
2692 }
2693 return false;
2694 }
2695
2696 public int countUndefined(){
2697 if(bases==null){return 0;}
2698 final byte[] symbolToNumber=AminoAcid.symbolToNumber(amino());
2699 int n=0;
2700 for(byte b : bases){
2701 n+=(symbolToNumber[b]>=0 ? 0 : 1);
2702 // if(symbolToNumber[b]<0){n++;}
2703 }
2704 return n;
2705 }
2706
2707 public boolean hasMinConsecutiveBases(final int min){
2708 if(bases==null){return min<=0;}
2709 final byte[] symbolToNumber=AminoAcid.symbolToNumber(amino());
2710 int len=0;
2711 for(byte b : bases){
2712 if(symbolToNumber[b]<0){len=0;}
2713 else{
2714 len++;
2715 if(len>=min){return true;}
2716 }
2717 }
2718 return false;
2719 }
2720
2721
2722 /**
2723 * @return The number of occurrences of the rarest base.
2724 */
2725 public int minBaseCount(){
2726 if(bases==null){return 0;}
2727 int a=0, c=0, g=0, t=0;
2728 for(byte b : bases){
2729 if(b=='A'){a++;}
2730 else if(b=='C'){c++;}
2731 else if(b=='G'){g++;}
2732 else if(b=='T'){t++;}
2733 }
2734 return Tools.min(a, c, g, t);
2735 }
2736
2737 public boolean containsXY(){
2738 assert(match!=null && valid());
2739 return containsXY(match);
2740 }
2741
2742 public static boolean containsXY(byte[] match){
2743 if(match==null){return false;}
2744 for(int i=0; i<match.length; i++){
2745 byte b=match[i];
2746 if(b=='X' || b=='Y'){return true;}
2747 }
2748 return false;
2749 }
2750
2751 public boolean containsXY2(){
2752 if(match==null || match.length<1){return false;}
2753 boolean b=(match[0]=='X' || match[match.length-1]=='Y');
2754 assert(!valid() || b==containsXY());
2755 return b;
2756 }
2757
2758 public boolean containsXYC(){
2759 if(match==null || match.length<1){return false;}
2760 boolean b=(match[0]=='X' || match[match.length-1]=='Y');
2761 assert(!valid() || b==containsXY());
2762 return b || match[0]=='C' || match[match.length-1]=='C';
2763 }
2764
2765 /** Replaces 'B' in match string with 'S', 'm', or 'N' */
2766 public boolean fixMatchB(){
2767 assert(match!=null);
2768 final ChromosomeArray ca;
2769 if(Data.GENOME_BUILD>=0){
2770 ca=Data.getChromosome(chrom);
2771 }else{
2772 ca=null;
2773 }
2774 boolean originallyShort=shortmatch();
2775 if(originallyShort){match=toLongMatchString(match);}
2776 int mloc=0, cloc=0, rloc=start;
2777 for(; mloc<match.length; mloc++){
2778 byte m=match[mloc];
2779
2780 if(m=='B'){
2781 byte r=(ca==null ? (byte)'?' : ca.get(rloc));
2782 byte c=bases[cloc];
2783 if(r=='N' || c=='N'){
2784 match[mloc]='N';
2785 }else if(r==c || Tools.toUpperCase(r)==Tools.toUpperCase(c)){
2786 match[mloc]='m';
2787 }else{
2788 if(ca==null){
2789 if(originallyShort){
2790 match=toShortMatchString(match);
2791 }
2792 for(int i=0; i<match.length; i++){
2793 if(match[i]=='B'){match[i]='N';}
2794 }
2795 return false;
2796 }
2797 match[mloc]='S';
2798 }
2799 cloc++;
2800 rloc++;
2801 }else if(m=='m' || m=='S' || m=='N' || m=='s' || m=='C'){
2802 cloc++;
2803 rloc++;
2804 }else if(m=='D'){
2805 rloc++;
2806 }else if(m=='I' || m=='X' || m=='Y'){
2807 cloc++;
2808 }
2809 }
2810 if(originallyShort){match=toShortMatchString(match);}
2811 return true;
2812 }
2813
2814 public float expectedTipErrors(boolean countUndefined, int maxBases){
2815 return expectedTipErrors(bases, quality, countUndefined, maxBases);
2816 }
2817
2818 public float expectedErrorsIncludingMate(boolean countUndefined){
2819 float a=expectedErrors(countUndefined, length());
2820 float b=(mate==null ? 0 : mate.expectedErrors(countUndefined, mate.length()));
2821 return a+b;
2822 }
2823
2824 public float expectedErrors(boolean countUndefined, int maxBases){
2825 return expectedErrors(bases, quality, countUndefined, maxBases);
2826 }
2827
2828 public static float probabilityErrorFree(byte[] bases, byte[] quality, boolean countUndefined, int maxBases){
2829 if(quality==null){return 0;}
2830 final int limit=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2831 final float[] array=QualityTools.PROB_CORRECT;
2832 assert(array[0]>0 && array[0]<1);
2833 float product=1;
2834 for(int i=0; i<limit; i++){
2835 byte b=bases[i];
2836 byte q=quality[i];
2837 if(AminoAcid.isFullyDefined(b)){
2838 product*=array[q];
2839 }else if(countUndefined){
2840 return 0;
2841 }
2842 }
2843 return product;
2844 }
2845
2846 public static float expectedErrors(byte[] bases, byte[] quality, boolean countUndefined, int maxBases){
2847 if(quality==null){return 0;}
2848 final int limit=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2849 final float[] array=QualityTools.PROB_ERROR;
2850 assert(array[0]>0 && array[0]<1);
2851 float sum=0;
2852 for(int i=0; i<limit; i++){
2853 byte b=bases[i];
2854 boolean d=AminoAcid.isFullyDefined(b);
2855 //assert((quality[i]==0)==d) : "Q="+quality[i]+" for base "+(char)b;
2856 if(d || countUndefined){
2857 byte q=(d ? quality[i] : 0);
2858 sum+=array[q];
2859 }
2860 }
2861 return sum;
2862 }
2863
2864 /** Runs backwards instead of forwards */
2865 public static float expectedTipErrors(byte[] bases, byte[] quality, boolean countUndefined, int maxBases){
2866 if(quality==null){return 0;}
2867 final int limit;
2868 {
2869 final int limit0=(maxBases<1 ? quality.length : Tools.min(maxBases, quality.length));
2870 limit=quality.length-limit0;
2871 }
2872 final float[] array=QualityTools.PROB_ERROR;
2873 assert(array[0]>0 && array[0]<1);
2874 float sum=0;
2875 for(int i=quality.length-1; i>=limit; i--){
2876 byte b=bases[i];
2877 byte q=quality[i];
2878 if(AminoAcid.isFullyDefined(b)){
2879 sum+=array[q];
2880 }else{
2881 assert(q==0);
2882 if(countUndefined){sum+=0.75f;}
2883 }
2884 }
2885 return sum;
2886 }
2887
2888 public int estimateErrors() {
2889 if(quality==null){return 0;}
2890 assert(match!=null) : this.toText(false);
2891
2892 int count=0;
2893 for(int ci=0, mi=0; ci<bases.length && mi<match.length; mi++){
2894
2895 // byte b=bases[ci];
2896 byte q=quality[ci];
2897 byte m=match[mi];
2898 if(m=='m' || m=='s' || m=='N'){
2899 ci++;
2900 }else if(m=='X' || m=='Y'){
2901 ci++;
2902 count++;
2903 }else if(m=='I'){
2904 ci++;
2905 }else if(m=='D'){
2906
2907 }else if(m=='S'){
2908 ci++;
2909 if(q<19){
2910 count++;
2911 }
2912 }
2913
2914 }
2915 return count;
2916 }
2917
2918 /** {M, S, D, I, N, splice} */
2919 public int[] countErrors(int minSplice) {
2920 assert(match!=null) : this.toText(false);
2921 int m=0;
2922 int s=0;
2923 int d=0;
2924 int i=0;
2925 int n=0;
2926 int splice=0;
2927
2928 byte prev=' ';
2929 int streak=0;
2930 minSplice=Tools.max(minSplice, 1);
2931
2932 for(int pos=0; pos<match.length; pos++){
2933 final byte b=match[pos];
2934
2935 if(b==prev){streak++;}else{streak=1;}
2936
2937 if(b=='m'){
2938 m++;
2939 }else if(b=='N' || b=='C'){
2940 n++;
2941 }else if(b=='X' || b=='Y'){
2942 i++;
2943 }else if(b=='I'){
2944 i++;
2945 }else if(b=='D'){
2946 d++;
2947 if(streak==minSplice){splice++;}
2948 }else if(b=='S'){
2949 s++;
2950 }else{
2951 if(Tools.isDigit(b) && shortmatch()){
2952 System.err.println("Warning! Found read in shortmatch form during countErrors():\n"+this); //Usually caused by verbose output.
2953 if(mate!=null){System.err.println("mate:\n"+mate.id+"\t"+new String(mate.bases));}
2954 System.err.println("Stack trace: ");
2955 new Exception().printStackTrace();
2956 match=toLongMatchString(match);
2957 setShortMatch(false);
2958 return countErrors(minSplice);
2959 }else{
2960 throw new RuntimeException("\nUnknown symbol "+(char)b+":\n"+new String(match)+"\n"+this+"\nshortmatch="+this.shortmatch());
2961 }
2962 }
2963
2964 prev=b;
2965 }
2966
2967 // assert(i==0) : i+"\n"+this+"\n"+new String(match)+"\n"+Arrays.toString(new int[] {m, s, d, i, n, splice});
2968
2969 return new int[] {m, s, d, i, n, splice};
2970 }
2971
2972 public static boolean isShortMatchString(byte[] match){
2973 byte last=' ';
2974 int streak=0;
2975 for(int i=0; i<match.length; i++){
2976 byte b=match[i];
2977 if(Tools.isDigit(b)){return true;}
2978 if(b==last){
2979 streak++;
2980 if(streak>3){return true;}
2981 }else{
2982 streak=0;
2983 last=b;
2984 }
2985 }
2986 return false;
2987 }
2988
2989 public void toShortMatchString(boolean doAssertion){
2990 if(shortmatch()){
2991 assert(!doAssertion);
2992 return;
2993 }
2994 match=toShortMatchString(match);
2995 setShortMatch(true);
2996 }
2997
2998 public static byte[] toShortMatchString(byte[] match){
2999 if(match==null){return null;}
3000 assert(match.length>0);
3001 ByteBuilder sb=new ByteBuilder(10);
3002
3003 byte prev=match[0];
3004 int count=1;
3005 for(int i=1; i<match.length; i++){
3006 byte m=match[i];
3007 assert(Tools.isLetter(m) || m==0) : new String(match);
3008 if(m==0){System.err.println("Warning! Converting empty match string to short form.");}
3009 if(m==prev){count++;}
3010 else{
3011 sb.append(prev);
3012 if(count>1){sb.append(count);}
3013 // else if(count==2){sb.append(prev);}
3014 prev=m;
3015 count=1;
3016 }
3017 }
3018 sb.append(prev);
3019 if(count>1){sb.append(count);}
3020 // else if(count==2){sb.append(prev);}
3021
3022 byte[] r=sb.toBytes();
3023 return r;
3024 }
3025
3026 public void toLongMatchString(boolean doAssertion){
3027 if(!shortmatch()){
3028 assert(!doAssertion);
3029 return;
3030 }
3031 match=toLongMatchString(match);
3032 setShortMatch(false);
3033 }
3034
3035 public static byte[] toLongMatchString(byte[] shortmatch){
3036 if(shortmatch==null){return null;}
3037 assert(shortmatch.length>0);
3038
3039 int count=0;
3040 int current=0;
3041 for(int i=0; i<shortmatch.length; i++){
3042 byte m=shortmatch[i];
3043 if(Tools.isLetter(m)){
3044 count++;
3045 count+=(current>0 ? current-1 : 0);
3046 current=0;
3047 }else{
3048 assert(Tools.isDigit(m));
3049 current=(current*10)+(m-48); //48 == '0'
3050 }
3051 }
3052 count+=(current>0 ? current-1 : 0);
3053
3054
3055 byte[] r=new byte[count];
3056 current=0;
3057 byte lastLetter='?';
3058 int j=0;
3059 for(int i=0; i<shortmatch.length; i++){
3060 byte m=shortmatch[i];
3061 if(Tools.isLetter(m)){
3062 while(current>1){
3063 r[j]=lastLetter;
3064 current--;
3065 j++;
3066 }
3067 current=0;
3068
3069 r[j]=m;
3070 j++;
3071 lastLetter=m;
3072 }else{
3073 assert(Tools.isDigit(m));
3074 current=(current*10)+(m-48); //48 == '0'
3075 }
3076 }
3077 while(current>1){
3078 r[j]=lastLetter;
3079 current--;
3080 j++;
3081 }
3082
3083 assert(r[r.length-1]>0);
3084 return r;
3085 }
3086
3087 public String parseCustomRname(){
3088 assert(id.startsWith("SYN")) : "Can't parse header "+id;
3089 return new CustomHeader(id, pairnum()).rname;
3090 }
3091
3092 public FloatList fetchVector() {
3093 FloatList x=(FloatList)obj;
3094 return x;
3095 }
3096
3097 public ByteBuilder fetchBB() {
3098 ByteBuilder x=(ByteBuilder)obj;
3099 return x;
3100 }
3101
3102 public Object obj() {return obj;}
3103
3104 public Object setObj(Object x) {
3105 assert(x!=null);
3106 Object old=obj;
3107 assert(old==null) : obj.getClass()+", "+x.getClass(); //Just a warning. This should probably not happen.
3108 obj=x;
3109 return obj;
3110 }
3111
3112 public Object nullifyObj() {
3113 Object old=obj;
3114 obj=null;
3115 return old;
3116 }
3117
3118 public Object nullifyObject() {
3119 Object old=obj;
3120 obj=null;
3121 return old;
3122 }
3123
3124 public Object setObjNull() {
3125 return nullifyObject();
3126 }
3127
3128 public TrimRead fetchTrimRead() {
3129 return (TrimRead)obj;
3130 }
3131
3132 public Class getObjectClass() {
3133 return obj==null ? null : obj.getClass();
3134 }
3135
3136 public Object fetchObject() {
3137 return obj;
3138 }
3139
3140 /** Bases of the read. */
3141 public byte[] bases;
3142
3143 /** Quality of the read. */
3144 public byte[] quality;
3145
3146 /** Alignment string. E.G. mmmmDDDmmm would have 4 matching bases, then a 3-base deletion, then 3 matching bases. */
3147 public byte[] match;
3148
3149 public int[] gaps;
3150
3151 public String name() {return id;}
3152 public String id;
3153 public long numericID;
3154 public int chrom;
3155 public int start;
3156 public int stop;
3157
3158 public int copies=1;
3159
3160 /** Errors detected */
3161 public int errors=0;
3162
3163 /** Alignment score from BBMap. Assumed to max at approx 100*bases.length */
3164 public int mapScore=0;
3165
3166 public ArrayList<SiteScore> sites;
3167 public SiteScore originalSite; //Origin site for synthetic reads
3168 public Object obj=null;//Don't set this to a SamLine; it's for other things.
3169 public SamLine samline=null;
3170 public Read mate;
3171
3172 public int flags;
3173
3174 /** -1 if invalid. TODO: Currently not retained through most processes. */
3175 private int insert=-1;
3176
3177 /** A random number for deterministic usage.
3178 * May decrease speed in multithreaded applications.
3179 */
3180 public double rand=-1;
3181
3182 public long time(){
3183 assert(obj!=null && obj.getClass()==Long.class) : obj;
3184 return ((Long)obj).longValue();
3185 }
3186 /** Number of bases in this pair, including the mate if present. */
3187 public int pairLength(){return length()+mateLength();}
3188 /** Number of bases in this pair, including the mate if present. */
3189 public int numPairKmers(int k){return numKmers(k)+numMateKmers(k);}
3190 /** Number of reads in this pair. Returns 1 if the read has no mate, and 2 if it does. */
3191 public int pairCount(){return 1+mateCount();}
3192 public int pairMappedCount(){return (mapped() ? 1 : 0)+(mate==null || !mate.mapped() ? 0 : 1);}
3193 public int length(){return bases==null ? 0 : bases.length;}
3194 public int numKmers(int k){return bases==null ? 0 : Tools.max(0, bases.length-k+1);}
3195 public int qlength(){return quality==null ? 0 : quality.length;}
3196 public int mateLength(){return mate==null ? 0 : mate.length();}
3197 public int numMateKmers(int k){return mate==null ? 0 : mate.numKmers(k);}
3198 public String mateId(){return mate==null ? null : mate.id;}
3199 public int mateCount(){return mate==null ? 0 : 1;}
3200 public boolean mateMapped(){return mate==null ? false : mate.mapped();}
3201 public boolean eitherMapped(){return mapped() || mateMapped();}
3202 public long countMateBytes(){return mate==null ? 0 : mate.countBytes();}
3203 public long countMateFastqBytes(){return mate==null ? 0 : mate.countFastqBytes();}
3204 /** Number of bytes this read pair uses in memory, approximately */
3205 public long countPairBytes(){return countBytes()+(mate==null ? 0 : mate.countBytes());}
3206
3207 /** Number of bytes this read uses in memory, approximately */
3208 public long countBytes(){
3209 long sum=144; //Approximate per-read overhead
3210 sum+=(bases==null ? 0 : bases.length+16);
3211 sum+=(quality==null ? 0 : quality.length+16);
3212 sum+=(id==null ? 0 : id.length()*2+16);
3213 sum+=(match==null ? 0 : match.length+16);
3214 sum+=(samline==null ? 0 : samline.countBytes());
3215 sum+=(obj==null ? 0 : 32);
3216 return sum;
3217 }
3218
3219 /** Number of bytes this read uses in on disk in Fastq format */
3220 public long countFastqBytes(){
3221 long sum=6;//4 newlines, +, @
3222 sum+=(bases==null ? 0 : bases.length);
3223 sum+=(quality==null ? 0 : quality.length);
3224 sum+=(id==null ? 0 : id.length());
3225 return sum;
3226 }
3227
3228 public int countLeading(final char base){return countLeft((byte)base);}
3229 public int countTrailing(final char base){return countRight((byte)base);}
3230 public int countLeft(final char base){return countLeft((byte)base);}
3231 public int countRight(final char base){return countRight((byte)base);}
3232
3233 public int countLeft(final byte base){
3234 for(int i=0; i<bases.length; i++){
3235 final byte b=bases[i];
3236 if(b!=base){return i;}
3237 }
3238 return bases.length;
3239 }
3240
3241 public int countRight(final byte base){
3242 for(int i=bases.length-1; i>=0; i--){
3243 final byte b=bases[i];
3244 if(b!=base){return bases.length-i-1;}
3245 }
3246 return bases.length;
3247 }
3248
3249 public boolean untrim(){
3250 if(obj==null || obj.getClass()!=TrimRead.class){return false;}
3251 ((TrimRead)obj).untrim();
3252 obj=null;
3253 return true;
3254 }
3255
3256 public int trailingLowerCase(){
3257 for(int i=bases.length-1; i>=0;){
3258 if(Tools.isLowerCase(bases[i])){
3259 i--;
3260 }else{
3261 return bases.length-i-1;
3262 }
3263 }
3264 return bases.length;
3265 }
3266 public int leadingLowerCase(){
3267 for(int i=0; i<bases.length; i++){
3268 if(!Tools.isLowerCase(bases[i])){return i;}
3269 }
3270 return bases.length;
3271 }
3272
3273 public char strandChar(){return Shared.strandCodes2[strand()];}
3274 public byte strand(){return (byte)(flags&1);}
3275 public boolean mapped(){return (flags&MAPPEDMASK)==MAPPEDMASK;}
3276 public boolean paired(){return (flags&PAIREDMASK)==PAIREDMASK;}
3277 public boolean synthetic(){return (flags&SYNTHMASK)==SYNTHMASK;}
3278 public boolean ambiguous(){return (flags&AMBIMASK)==AMBIMASK;}
3279 public boolean perfect(){return (flags&PERFECTMASK)==PERFECTMASK;}
3280 // public boolean semiperfect(){return perfect() ? true : list!=null && list.size()>0 ? list.get(0).semiperfect : false;} //TODO: This is a hack. Add a semiperfect flag.
3281 public boolean rescued(){return (flags&RESCUEDMASK)==RESCUEDMASK;}
3282 public boolean discarded(){return (flags&DISCARDMASK)==DISCARDMASK;}
3283 public boolean invalid(){return (flags&INVALIDMASK)==INVALIDMASK;}
3284 public boolean swapped(){return (flags&SWAPMASK)==SWAPMASK;}
3285 public boolean shortmatch(){return (flags&SHORTMATCHMASK)==SHORTMATCHMASK;}
3286 public boolean insertvalid(){return (flags&INSERTMASK)==INSERTMASK;}
3287 public boolean hasAdapter(){return (flags&ADAPTERMASK)==ADAPTERMASK;}
3288 public boolean secondary(){return (flags&SECONDARYMASK)==SECONDARYMASK;}
3289 public boolean aminoacid(){return (flags&AAMASK)==AAMASK;}
3290 public boolean amino(){return (flags&AAMASK)==AAMASK;}
3291 public boolean junk(){return (flags&JUNKMASK)==JUNKMASK;}
3292 public boolean validated(){return (flags&VALIDATEDMASK)==VALIDATEDMASK;}
3293 public boolean tested(){return (flags&TESTEDMASK)==TESTEDMASK;}
3294 public boolean invertedRepeat(){return (flags&IRMASK)==IRMASK;}
3295 public boolean trimmed(){return (flags&TRIMMEDMASK)==TRIMMEDMASK;}
3296
3297 /** For paired ends: 0 for read1, 1 for read2 */
3298 public int pairnum(){return (flags&PAIRNUMMASK)>>PAIRNUMSHIFT;}
3299 public boolean valid(){return !invalid();}
3300
3301 public boolean getFlag(int mask){return (flags&mask)==mask;}
3302 public int flagToNumber(int mask){return (flags&mask)==mask ? 1 : 0;}
3303
3304 public void setFlag(int mask, boolean b){
3305 flags=(flags&~mask);
3306 if(b){flags|=mask;}
3307 }
3308
3309 public void setStrand(int b){
3310 assert(b==1 || b==0);
3311 flags=(flags&(~1))|b;
3312 }
3313
3314 /** For paired ends: 0 for read1, 1 for read2 */
3315 public void setPairnum(int b){
3316 // System.err.println("Setting pairnum to "+b+" for "+id);
3317 // assert(!id.equals("2_chr1_0_1853883_1853982_1845883_ecoli_K12") || b==1);
3318 assert(b==1 || b==0);
3319 flags=(flags&(~PAIRNUMMASK))|(b<<PAIRNUMSHIFT);
3320 // assert(pairnum()==b);
3321 }
3322
3323 public void setPaired(boolean b){
3324 flags=(flags&~PAIREDMASK);
3325 if(b){flags|=PAIREDMASK;}
3326 }
3327
3328 public void setSynthetic(boolean b){
3329 flags=(flags&~SYNTHMASK);
3330 if(b){flags|=SYNTHMASK;}
3331 }
3332
3333 public void setAmbiguous(boolean b){
3334 flags=(flags&~AMBIMASK);
3335 if(b){flags|=AMBIMASK;}
3336 }
3337
3338 public boolean setPerfectFlag(int maxScore){
3339 final SiteScore ss=topSite();
3340 if(ss==null){
3341 setPerfect(false);
3342 }else{
3343 assert(ss.slowScore<=maxScore) : maxScore+", "+ss.slowScore+", "+ss.toText();
3344
3345 if(ss.slowScore==maxScore || ss.perfect){
3346 assert(testMatchPerfection(true)) : "\n"+ss+"\n"+maxScore+"\n"+this+"\n"+mate+"\n";
3347 setPerfect(true);
3348 }else{
3349 boolean flag=testMatchPerfection(false);
3350 setPerfect(flag);
3351 assert(flag || !ss.perfect) : "flag="+flag+", ss.perfect="+ss.perfect+"\nmatch="+new String(match)+"\n"+this.toText(false);
3352 assert(!flag || ss.slowScore>=maxScore) : "\n"+ss+"\n"+maxScore+"\n"+this+"\n"+mate+"\n";
3353 }
3354 }
3355 return perfect();
3356 }
3357
3358 private boolean testMatchPerfection(boolean returnIfNoMatch){
3359 if(match==null){return returnIfNoMatch;}
3360 boolean flag=(match.length==bases.length);
3361 if(shortmatch()){
3362 flag=(match.length==0 || match[0]=='m');
3363 for(int i=0; i<match.length && flag; i++){flag=(match[i]=='m' || Tools.isDigit(match[i]));}
3364 }else{
3365 for(int i=0; i<match.length && flag; i++){flag=(match[i]=='m');}
3366 }
3367 for(int i=0; i<bases.length && flag; i++){flag=(bases[i]!='N');}
3368 return flag;
3369 }
3370
3371 /**
3372 * @return GC fraction
3373 */
3374 public float gc() {
3375 if(bases==null || bases.length<1){return 0;}
3376 int at=0, gc=0;
3377 for(byte b : bases){
3378 int x=AminoAcid.baseToNumber[b];
3379 if(x>-1){
3380 if(x==0 || x==3){at++;}
3381 else{gc++;}
3382 }
3383 }
3384 if(gc<1){return 0;}
3385 return gc*1f/(at+gc);
3386 }
3387
3388 /**
3389 * @param swapFrom
3390 * @param swapTo
3391 * @return number of swaps
3392 */
3393 public int swapBase(byte swapFrom, byte swapTo) {
3394 if(bases==null){return 0;}
3395 int swaps=0;
3396 for(int i=0; i<bases.length; i++){
3397 if(bases[i]==swapFrom){
3398 bases[i]=swapTo;
3399 swaps++;
3400 }
3401 }
3402 return swaps;
3403 }
3404
3405 /**
3406 * @param remap Table of new values
3407 */
3408 public void remap(byte[] remap) {
3409 if(bases==null){return;}
3410 for(int i=0; i<bases.length; i++){
3411 bases[i]=remap[bases[i]];
3412 }
3413 }
3414
3415 /**
3416 * @param remap Table of new values
3417 */
3418 public int remapAndCount(byte[] remap) {
3419 if(bases==null){return 0;}
3420 int swaps=0;
3421 for(int i=0; i<bases.length; i++){
3422 byte a=bases[i];
3423 byte b=remap[a];
3424 if(a!=b){
3425 bases[i]=b;
3426 swaps++;
3427 }
3428 }
3429 return swaps;
3430 }
3431
3432 public int convertUndefinedTo(byte b){
3433 if(bases==null){return 0;}
3434 int changed=0;
3435 for(int i=0; i<bases.length; i++){
3436 if(b<0 || AminoAcid.baseToNumberACGTN[bases[i]]<0){
3437 changed++;
3438 bases[i]=b;
3439 if(quality!=null){quality[i]=0;}
3440 }
3441 }
3442 return changed;
3443 }
3444
3445 public void swapBasesWithMate(){
3446 if(mate==null){
3447 assert(false);
3448 return;
3449 }
3450 byte[] temp=bases;
3451 bases=mate.bases;
3452 mate.bases=temp;
3453 temp=quality;
3454 quality=mate.quality;
3455 mate.quality=temp;
3456 }
3457
3458 public int insert(){
3459 return insertvalid() ? insert : -1;
3460 }
3461
3462 public int insertSizeMapped(boolean ignoreStrand){
3463 return insertSizeMapped(this, mate, ignoreStrand);
3464 }
3465
3466 public static int insertSizeMapped(Read r1, Read r2, boolean ignoreStrand){
3467 // assert(false) : ignoreStrand+", "+(r2==null)+", "+(r1.mapped())+", "+(r2.mapped())+", "+(r1.strand()==r2.strand())+", "+r1.strand()+", "+r2.strand();
3468 if(ignoreStrand || r2==null || !r1.mapped() || !r2.mapped() || r1.strand()==r2.strand()){return insertSizeMapped_Unstranded(r1, r2);}
3469 return insertSizeMapped_PlusLeft(r1, r2);
3470 }
3471
3472 /** TODO: This is not correct when the insert is shorter than a read's bases with same-strand reads */
3473 public static int insertSizeMapped_PlusLeft(Read r1, Read r2){
3474 if(r1.strand()>r2.strand()){return insertSizeMapped_PlusLeft(r2, r1);}
3475 if(r1.strand()==r2.strand() || r1.start>r2.stop){return insertSizeMapped_Unstranded(r2, r1);} //So r1 is always on the left.
3476 // if(!mapped() || !mate.mapped()){return 0;}
3477 if(r1.chrom!=r2.chrom){return 0;}
3478 if(r1.start==r1.stop || r2.start==r2.stop){return 0;} //???
3479
3480 int a=r1.length();
3481 int b=r2.length();
3482 int mid=r2.start-r1.stop-1;
3483 if(-mid>=a+b){return insertSizeMapped_Unstranded(r1, r2);} //Not properly oriented; plus read is to the right of minus read
3484 return mid+a+b;
3485 }
3486
3487 public static int insertSizeMapped_Unstranded(Read r1, Read r2){
3488 if(r2==null){return r1.start==r1.stop ? 0 : r1.stop-r1.start+1;}
3489
3490 if(r1.start>r2.start){return insertSizeMapped_Unstranded(r2, r1);} //So r1 is always on the left side.
3491
3492 // if(!mapped() || !mate.mapped()){return 0;}
3493 if(r1.start==r1.stop || r2.start==r2.stop){return 0;} //???
3494
3495 if(r1.chrom!=r2.chrom){return 0;}
3496 int a=r1.length();
3497 int b=r2.length();
3498 if(false && Tools.overlap(r1.start, r1.stop, r2.start, r2.stop)){
3499 //This does not handle very short inserts
3500 return Tools.max(r1.stop, r2.stop)-Tools.min(r1.start, r2.start)+1;
3501
3502 }else{
3503 if(r1.start<r2.start){
3504 int mid=r2.start-r1.stop-1;
3505 // assert(false) : mid+", "+a+", "+b;
3506 // if(-mid>a && -mid>b){return Tools.min(a, b);} //Strange situation, no way to guess insert size
3507 if(-mid>=a+b){return 0;} //Strange situation, no way to guess insert size
3508 return mid+a+b;
3509 }else{
3510 assert(r1.start==r2.start);
3511 return Tools.min(a, b);
3512 }
3513 }
3514 }
3515
3516 public int insertSizeOriginalSite(){
3517 if(mate==null){
3518 // System.err.println("A: "+(originalSite==null ? "null" : (originalSite.stop-originalSite.start+1)));
3519 return (originalSite==null ? -1 : originalSite.stop-originalSite.start+1);
3520 }
3521
3522 final SiteScore ssa=originalSite, ssb=mate.originalSite;
3523 final int x;
3524 if(ssa==null || ssb==null){
3525 // System.err.println("B: 0");
3526 x=0;
3527 }else{
3528 x=insertSize(ssa, ssb, bases.length, mate.length());
3529 }
3530
3531 assert(pairnum()>=mate.pairnum() || x==mate.insertSizeOriginalSite());
3532 return x;
3533 }
3534
3535 public static int insertSize(SiteScore ssa, SiteScore ssb, int lena, int lenb){
3536 return insertSize(ssa.chrom, ssb.chrom, ssa.start, ssb.start, ssa.stop, ssb.stop, lena, lenb);
3537 }
3538
3539 public static int insertSize(int chroma, int chromb, int starta, int startb, int stopa, int stopb, int lena, int lenb){
3540
3541 final int x;
3542
3543 // if(mate==null || ){return bases==null ? 0 : bases.length;}
3544 if(chroma!=chromb){x=0;}
3545 else{
3546
3547 if(Tools.overlap(starta, stopa, startb, stopb)){
3548 x=Tools.max(stopa, stopb)-Tools.min(starta, startb)+1;
3549 // System.err.println("C: "+x);
3550 }else{
3551 if(starta<=startb){
3552 int mid=startb-stopa-1;
3553 // assert(false) : mid+", "+a+", "+b;
3554 x=mid+lena+lenb;
3555 // System.err.println("D: "+x);
3556 }else{
3557 int mid=starta-stopb-1;
3558 // assert(false) : mid+", "+a+", "+b;
3559 x=mid+lena+lenb;
3560 // System.err.println("E: "+x);
3561 }
3562 }
3563 }
3564 return x;
3565 }
3566
3567 public Read subRead(int from, int to){
3568 Read r=this.clone();
3569 r.bases=KillSwitch.copyOfRange(bases, from, to);
3570 r.quality=(quality==null ? null : KillSwitch.copyOfRange(quality, from, to));
3571 r.mate=null;
3572 // assert(Tools.indexOf(r.bases, (byte)'J')<0);
3573 return r;
3574 }
3575
3576 public Read joinRead(){
3577 if(insert<1 || mate==null || !insertvalid()){return this;}
3578 assert(insert>9 || bases.length<20) : "Perhaps old read format is being used? This appears to be a quality value, not an insert.\n"+this+"\n\n"+mate+"\n";
3579 return joinRead(this, mate, insert);
3580 }
3581
3582 public Read joinRead(int x){
3583 if(x<1 || mate==null){return this;}
3584 //assert(x>9 || bases.length<20) : "Perhaps old read format is being used? This appears to be a quality value, not an insert.\n"+this+"\n\n"+mate+"\n";
3585 return joinRead(this, mate, x);
3586 }
3587
3588 public static Read joinRead(Read a, Read b, int insert){
3589 assert(a!=null && b!=null && insert>0);
3590 final int lengthSum=a.length()+b.length();
3591 final int overlap=Tools.min(insert, lengthSum-insert);
3592
3593 // System.err.println(insert);
3594 final byte[] bases=new byte[insert], abases=a.bases, bbases=b.bases;
3595 final byte[] aquals=a.quality, bquals=b.quality;
3596 final byte[] quals=(aquals==null || bquals==null ? null : new byte[insert]);
3597 assert(aquals==null || (aquals.length==abases.length && bquals.length==bbases.length));
3598
3599 int mismatches=0;
3600
3601 int start, stop;
3602
3603 if(overlap<=0){//Simple join in which there is no overlap
3604 int lim=insert-b.length();
3605 if(quals==null){
3606 for(int i=0; i<a.length(); i++){
3607 bases[i]=abases[i];
3608 }
3609 for(int i=a.length(); i<lim; i++){
3610 bases[i]='N';
3611 }
3612 for(int i=0; i<b.length(); i++){
3613 bases[i+lim]=bbases[i];
3614 }
3615 }else{
3616 for(int i=0; i<a.length(); i++){
3617 bases[i]=abases[i];
3618 quals[i]=aquals[i];
3619 }
3620 for(int i=a.length(); i<lim; i++){
3621 bases[i]='N';
3622 quals[i]=0;
3623 }
3624 for(int i=0; i<b.length(); i++){
3625 bases[i+lim]=bbases[i];
3626 quals[i+lim]=bquals[i];
3627 }
3628 }
3629
3630 start=Tools.min(a.start, b.start);
3631 // stop=start+insert-1;
3632 stop=Tools.max(a.stop, b.stop);
3633
3634 // }else if(insert>=a.length() && insert>=b.length()){ //Overlapped join, proper orientation
3635 // final int lim1=a.length()-overlap;
3636 // final int lim2=a.length();
3637 // for(int i=0; i<lim1; i++){
3638 // bases[i]=abases[i];
3639 // quals[i]=aquals[i];
3640 // }
3641 // for(int i=lim1, j=0; i<lim2; i++, j++){
3642 // assert(false) : "TODO";
3643 // bases[i]='N';
3644 // quals[i]=0;
3645 // }
3646 // for(int i=lim2, j=overlap; i<bases.length; i++, j++){
3647 // bases[i]=bbases[j];
3648 // quals[i]=bquals[j];
3649 // }
3650 }else{ //reads go off ends of molecule.
3651 if(quals==null){
3652 for(int i=0; i<a.length() && i<bases.length; i++){
3653 bases[i]=abases[i];
3654 }
3655 for(int i=bases.length-1, j=b.length()-1; i>=0 && j>=0; i--, j--){
3656 byte ca=bases[i], cb=bbases[j];
3657 if(ca==0 || ca=='N'){
3658 bases[i]=cb;
3659 }else if(ca==cb){
3660 }else{
3661 bases[i]=(ca>=cb ? ca : cb);
3662 if(ca!='N' && cb!='N'){mismatches++;}
3663 }
3664 }
3665 }else{
3666 for(int i=0; i<a.length() && i<bases.length; i++){
3667 bases[i]=abases[i];
3668 quals[i]=aquals[i];
3669 }
3670 for(int i=bases.length-1, j=b.length()-1; i>=0 && j>=0; i--, j--){
3671 byte ca=bases[i], cb=bbases[j];
3672 byte qa=quals[i], qb=bquals[j];
3673 if(ca==0 || ca=='N'){
3674 bases[i]=cb;
3675 quals[i]=qb;
3676 }else if(cb==0 || cb=='N'){
3677 //do nothing
3678 }else if(ca==cb){
3679 quals[i]=(byte)Tools.min((Tools.max(qa, qb)+Tools.min(qa, qb)/4), MAX_MERGE_QUALITY);
3680 }else{
3681 bases[i]=(qa>qb ? ca : qa<qb ? cb : (byte)'N');
3682 quals[i]=(byte)(Tools.max(qa, qb)-Tools.min(qa, qb));
3683 if(ca!='N' && cb!='N'){mismatches++;}
3684 }
3685 }
3686 }
3687
3688 if(a.strand()==0){
3689 start=a.start;
3690 // stop=start+insert-1;
3691 stop=b.stop;
3692 }else{
3693 stop=a.stop;
3694 // start=stop-insert+1;
3695 start=b.start;
3696 }
3697 if(start>stop){
3698 start=Tools.min(a.start, b.start);
3699 stop=Tools.max(a.stop, b.stop);
3700 }
3701 }
3702 // assert(mismatches>=countMismatches(a, b, insert, 999));
3703 // System.err.println(mismatches);
3704 if(a.chrom==0 || start==stop || (!a.mapped() && !a.synthetic())){start=stop=a.chrom=0;}
3705
3706 // System.err.println(bases.length+", "+start+", "+stop);
3707
3708 Read r=new Read(bases, null, a.id, a.numericID, a.flags, a.chrom, start, stop);
3709 r.quality=quals; //This prevents quality from getting capped.
3710 if(a.chrom==0 || start==stop || (!a.mapped() && !a.synthetic())){r.setMapped(true);}
3711 r.setInsert(insert);
3712 r.setPaired(false);
3713 r.copies=a.copies;
3714 r.mapScore=a.mapScore+b.mapScore;
3715 if(overlap<=0){
3716 r.mapScore=a.mapScore+b.mapScore;
3717 r.errors=a.errors+b.errors;
3718 //TODO r.gaps=?
3719 }else{//Hard to calculate
3720 r.mapScore=(int)((a.mapScore*(long)a.length()+b.mapScore*(long)b.length())/insert);
3721 r.errors=a.errors;
3722 }
3723
3724
3725 assert(r.insertvalid()) : "\n\n"+a.toText(false)+"\n\n"+b.toText(false)+"\n\n"+r.toText(false)+"\n\n";
3726 assert(r.insert()==r.length()) : r.insert()+"\n\n"+a.toText(false)+"\n\n"+b.toText(false)+"\n\n"+r.toText(false)+"\n\n";
3727 // assert(false) : "\n\n"+a.toText(false)+"\n\n"+b.toText(false)+"\n\n"+r.toText(false)+"\n\n";
3728
3729 //TODO: Triggered by BBMerge in useratio mode for some reason.
3730 // assert(Shared.anomaly || (a.insertSizeMapped(false)>0 == r.insertSizeMapped(false)>0)) :
3731 // "\n"+r.length()+"\n"+r.insert()+"\n"+r.insertSizeMapped(false)+"\n"+a.insert()+"\n"+a.insertSizeMapped(false)+
3732 // "\n\n"+a.toText(false)+"\n\n"+b.toText(false)+"\n\n"+r.toText(false)+"\n\n";
3733
3734 return r;
3735 }
3736
3737 /**
3738 * @param minlen
3739 * @param maxlen
3740 * @return A list of read fragments
3741 */
3742 public ArrayList<Read> split(int minlen, int maxlen) {
3743 int len=bases==null ? 0 : bases.length;
3744 if(len<minlen){return null;}
3745 int parts=(len+maxlen-1)/maxlen;
3746 ArrayList<Read> subreads=new ArrayList<Read>(parts);
3747 if(len<=maxlen){
3748 subreads.add(this);
3749 }else{
3750 float ideal=Tools.max(minlen, len/(float)parts);
3751 int actual=(int)ideal;
3752 assert(false) : "TODO"; //Some assertion goes here, I forget what
3753 for(int i=0; i<parts; i++){
3754 int a=i*actual;
3755 int b=(i+1)*actual;
3756 if(b>bases.length){b=bases.length;}
3757 // if(b-a<)
3758 byte[] subbases=KillSwitch.copyOfRange(bases, a, b);
3759 byte[] subquals=(quality==null ? null : KillSwitch.copyOfRange(quality, a, b+1));
3760 Read r=new Read(subbases, subquals, id+"_"+i, numericID, flags);
3761 subreads.add(r);
3762 }
3763 }
3764 return subreads;
3765 }
3766
3767 /** Generate and return an array of canonical kmers for this read */
3768 public long[] toKmers(final int k, final int gap, long[] kmers, boolean makeCanonical, Kmer longkmer) {
3769 if(gap>0){throw new RuntimeException("Gapped reads: TODO");}
3770 if(k>31){return toLongKmers(k, kmers, makeCanonical, longkmer);}
3771 if(bases==null || bases.length<k+gap){return null;}
3772
3773 final int arraylen=bases.length-k+1;
3774 if(kmers==null || kmers.length!=arraylen){kmers=new long[arraylen];}
3775 Arrays.fill(kmers, -1);
3776
3777 final int shift=2*k;
3778 final int shift2=shift-2;
3779 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
3780 long kmer=0, rkmer=0;
3781 int len=0;
3782
3783 for(int i=0; i<bases.length; i++){
3784 byte b=bases[i];
3785 long x=AminoAcid.baseToNumber[b];
3786 long x2=AminoAcid.baseToComplementNumber[b];
3787 kmer=((kmer<<2)|x)&mask;
3788 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
3789 if(x<0){len=0; rkmer=0;}else{len++;}
3790 if(len>=k){
3791 kmers[i-k+1]=makeCanonical ? Tools.max(kmer, rkmer) : kmer;
3792 }
3793 }
3794 return kmers;
3795 }
3796
3797 // /** Generate and return an array of canonical kmers for this read */
3798 // public long[] toKmers(final int k, final int gap, long[] kmers, boolean makeCanonical, Kmer longkmer) {
3799 // if(gap>0){throw new RuntimeException("Gapped reads: TODO");}
3800 // if(k>31){return toLongKmers(k, kmers, makeCanonical, longkmer);}
3801 // if(bases==null || bases.length<k+gap){return null;}
3802 //
3803 // final int kbits=2*k;
3804 // final long mask=(kbits>63 ? -1L : ~((-1L)<<kbits));
3805 //
3806 // int len=0;
3807 // long kmer=0;
3808 // final int arraylen=bases.length-k+1;
3809 // if(kmers==null || kmers.length!=arraylen){kmers=new long[arraylen];}
3810 // Arrays.fill(kmers, -1);
3811 //
3812 // for(int i=0; i<bases.length; i++){
3813 // byte b=bases[i];
3814 // int x=AminoAcid.baseToNumber[b];
3815 // if(x<0){
3816 // len=0;
3817 // kmer=0;
3818 // }else{
3819 // kmer=((kmer<<2)|x)&mask;
3820 // len++;
3821 //
3822 // if(len>=k){
3823 // kmers[i-k+1]=kmer;
3824 // }
3825 // }
3826 // }
3827 //
3828 //// System.out.println(new String(bases));
3829 //// System.out.println(Arrays.toString(kmers));
3830 //
3831 // if(makeCanonical){
3832 // this.reverseComplement();
3833 // len=0;
3834 // kmer=0;
3835 // for(int i=0, j=bases.length-1; i<bases.length; i++, j--){
3836 // byte b=bases[i];
3837 // int x=AminoAcid.baseToNumber[b];
3838 // if(x<0){
3839 // len=0;
3840 // kmer=0;
3841 // }else{
3842 // kmer=((kmer<<2)|x)&mask;
3843 // len++;
3844 //
3845 // if(len>=k){
3846 // assert(kmer==AminoAcid.reverseComplementBinaryFast(kmers[j], k));
3847 // kmers[j]=Tools.max(kmers[j], kmer);
3848 // }
3849 // }
3850 // }
3851 // this.reverseComplement();
3852 //
3853 //// System.out.println(Arrays.toString(kmers));
3854 // }
3855 //
3856 //
3857 // return kmers;
3858 // }
3859
3860 /** Generate and return an array of canonical kmers for this read */
3861 public long[] toLongKmers(final int k, long[] kmers, boolean makeCanonical, Kmer kmer) {
3862 assert(k>31) : k;
3863 assert(makeCanonical);
3864 if(bases==null || bases.length<k){return null;}
3865 kmer.clear();
3866
3867 final int arraylen=bases.length-k+1;
3868 if(kmers==null || kmers.length!=arraylen){kmers=new long[arraylen];}
3869 Arrays.fill(kmers, -1);
3870
3871 for(int i=0; i<bases.length; i++){
3872 byte b=bases[i];
3873 kmer.addRight(b);
3874 if(!AminoAcid.isFullyDefined(b)){kmer.clear();}
3875 if(kmer.len>=k){
3876 kmers[i-k+1]=kmer.xor();
3877 }
3878 }
3879
3880 return kmers;
3881 }
3882
3883 // /** Generate and return an array of canonical kmers for this read */
3884 // public long[] toLongKmers(final int k, long[] kmers, boolean makeCanonical, Kmer longkmer) {
3885 // assert(k>31) : k;
3886 // if(bases==null || bases.length<k){return null;}
3887 //
3888 // final int kbits=2*k;
3889 // final long mask=Long.MAX_VALUE;
3890 //
3891 // int len=0;
3892 // long kmer=0;
3893 // final int arraylen=bases.length-k+1;
3894 // if(kmers==null || kmers.length!=arraylen){kmers=new long[arraylen];}
3895 // Arrays.fill(kmers, -1);
3896 //
3897 //
3898 // final int tailshift=k%32;
3899 // final int tailshiftbits=tailshift*2;
3900 //
3901 // for(int i=0; i<bases.length; i++){
3902 // byte b=bases[i];
3903 // int x=AminoAcid.baseToNumber[b];
3904 // if(x<0){
3905 // len=0;
3906 // kmer=0;
3907 // }else{
3908 // kmer=Long.rotateLeft(kmer, 2);
3909 // kmer=kmer^x;
3910 // len++;
3911 //
3912 // if(len>=k){
3913 // long x2=AminoAcid.baseToNumber[bases[i-k]];
3914 // kmer=kmer^(x2<<tailshiftbits);
3915 // kmers[i-k+1]=kmer;
3916 // }
3917 // }
3918 // }
3919 // if(makeCanonical){
3920 // this.reverseComplement();
3921 // len=0;
3922 // kmer=0;
3923 // for(int i=0, j=bases.length-1; i<bases.length; i++, j--){
3924 // byte b=bases[i];
3925 // int x=AminoAcid.baseToNumber[b];
3926 // if(x<0){
3927 // len=0;
3928 // kmer=0;
3929 // }else{
3930 // kmer=Long.rotateLeft(kmer, 2);
3931 // kmer=kmer^x;
3932 // len++;
3933 //
3934 // if(len>=k){
3935 // long x2=AminoAcid.baseToNumber[bases[i-k]];
3936 // kmer=kmer^(x2<<tailshiftbits);
3937 // kmers[j]=mask&(Tools.max(kmers[j], kmer));
3938 // }
3939 // }
3940 // }
3941 // this.reverseComplement();
3942 // }else{
3943 // assert(false) : "Long kmers should be made canonical here because they cannot be canonicized later.";
3944 // }
3945 //
3946 // return kmers;
3947 // }
3948
3949 public static final boolean CHECKSITES(Read r, byte[] basesM){
3950 return CHECKSITES(r.sites, r.bases, basesM, r.numericID, true);
3951 }
3952
3953 public static final boolean CHECKSITES(Read r, byte[] basesM, boolean verifySorted){
3954 return CHECKSITES(r.sites, r.bases, basesM, r.numericID, verifySorted);
3955 }
3956
3957 public static final boolean CHECKSITES(ArrayList<SiteScore> list, byte[] basesP, byte[] basesM, long id){
3958 return CHECKSITES(list, basesP, basesM, id, true);
3959 }
3960
3961 public static final boolean CHECKSITES(ArrayList<SiteScore> list, byte[] basesP, byte[] basesM, long id, boolean verifySorted){
3962 return true; //Temporarily disabled
3963 // if(list==null || list.isEmpty()){return true;}
3964 // SiteScore prev=null;
3965 // for(int i=0; i<list.size(); i++){
3966 // SiteScore ss=list.get(i);
3967 // if(ss.strand==Gene.MINUS && basesM==null && basesP!=null){basesM=AminoAcid.reverseComplementBases(basesP);}
3968 // byte[] bases=(ss.strand==Gene.PLUS ? basesP : basesM);
3969 // if(verbose){System.err.println("Checking site "+i+": "+ss);}
3970 // boolean b=CHECKSITE(ss, bases, id);
3971 // assert(b) : id+"\n"+new String(basesP)+"\n"+ss+"\n";
3972 // if(verbose){System.err.println("Checked site "+i+" = "+ss+"\nss.p="+ss.perfect+", ss.sp="+ss.semiperfect);}
3973 // if(!b){
3974 //// System.err.println("Error at SiteScore "+i+": ss.p="+ss.perfect+", ss.sp="+ss.semiperfect);
3975 // return false;
3976 // }
3977 // if(verifySorted && prev!=null && ss.score>prev.score){
3978 // if(verbose){System.err.println("verifySorted failed.");}
3979 // return false;
3980 // }
3981 // prev=ss;
3982 // }
3983 // return true;
3984 }
3985
3986 /** Makes sure 'bases' is for correct strand. */
3987 public static final boolean CHECKORDER(ArrayList<SiteScore> list){
3988 if(list==null || list.size()<2){return true;}
3989 SiteScore prev=list.get(0);
3990 for(int i=0; i<list.size(); i++){
3991 SiteScore ss=list.get(i);
3992 if(ss.score>prev.score){return false;}
3993 prev=ss;
3994 }
3995 return true;
3996 }
3997
3998 /** Makes sure 'bases' is for correct strand. */
3999 public static final boolean CHECKSITE(SiteScore ss, byte[] basesP, byte[] basesM, long id){
4000 return CHECKSITE(ss, ss.plus() ? basesP : basesM, id);
4001 }
4002
4003 /** Make sure 'bases' is for correct strand! */
4004 public static final boolean CHECKSITE(SiteScore ss, byte[] bases, long id){
4005 return true; //Temporarily disabled
4006 // if(ss==null){return true;}
4007 //// System.err.println("Checking site "+ss+"\nss.p="+ss.perfect+", ss.sp="+ss.semiperfect+", bases="+new String(bases));
4008 // if(ss.perfect){assert(ss.semiperfect) : ss+"\n"+new String(bases);}
4009 // if(ss.gaps!=null){
4010 // if(ss.gaps[0]!=ss.start || ss.gaps[ss.gaps.length-1]!=ss.stop){return false;}
4011 //// assert(ss.gaps[0]==ss.start && ss.gaps[ss.gaps.length-1]==ss.stop);
4012 // }
4013 //
4014 // if(!(ss.pairedScore<1 || (ss.slowScore<=0 && ss.pairedScore>ss.quickScore ) || ss.pairedScore>ss.slowScore)){
4015 // System.err.println("Site paired score violation: "+ss.quickScore+", "+ss.slowScore+", "+ss.pairedScore);
4016 // return false;
4017 // }
4018 //
4019 // final boolean xy=ss.matchContainsXY();
4020 // if(bases!=null){
4021 //
4022 // final boolean p0=ss.perfect;
4023 // final boolean sp0=ss.semiperfect;
4024 // final boolean p1=ss.isPerfect(bases);
4025 // final boolean sp1=(p1 ? true : ss.isSemiPerfect(bases));
4026 //
4027 // assert(p0==p1 || (xy && p1)) : p0+"->"+p1+", "+sp0+"->"+sp1+", "+ss.isSemiPerfect(bases)+
4028 // "\nnumericID="+id+"\n"+new String(bases)+"\n\n"+Data.getChromosome(ss.chrom).getString(ss.start, ss.stop)+"\n\n"+ss+"\n\n";
4029 // assert(sp0==sp1 || (xy && sp1)) : p0+"->"+p1+", "+sp0+"->"+sp1+", "+ss.isSemiPerfect(bases)+
4030 // "\nnumericID="+id+"\n"+new String(bases)+"\n\n"+Data.getChromosome(ss.chrom).getString(ss.start, ss.stop)+"\n\n"+ss+"\n\n";
4031 //
4032 //// ss.setPerfect(bases, false);
4033 //
4034 // assert(p0==ss.perfect) :
4035 // p0+"->"+ss.perfect+", "+sp0+"->"+ss.semiperfect+", "+ss.isSemiPerfect(bases)+"\nnumericID="+id+"\n\n"+new String(bases)+"\n\n"+
4036 // Data.getChromosome(ss.chrom).getString(ss.start, ss.stop)+"\n"+ss+"\n\n";
4037 // assert(sp0==ss.semiperfect) :
4038 // p0+"->"+ss.perfect+", "+sp0+"->"+ss.semiperfect+", "+ss.isSemiPerfect(bases)+"\nnumericID="+id+"\n\n"+new String(bases)+"\n\n"+
4039 // Data.getChromosome(ss.chrom).getString(ss.start, ss.stop)+"\n"+ss+"\n\n";
4040 // if(ss.perfect){assert(ss.semiperfect);}
4041 // }
4042 // if(ss.match!=null && ss.matchLength()!=ss.mappedLength()){
4043 // if(verbose){System.err.println("Returning false because matchLength!=mappedLength:\n"+ss.matchLength()+", "+ss.mappedLength()+"\n"+ss);}
4044 // return false;
4045 // }
4046 // return true;
4047 }
4048
4049 public void setPerfect(boolean b){
4050 flags=(flags&~PERFECTMASK);
4051 if(b){flags|=PERFECTMASK;}
4052 }
4053
4054 public void setRescued(boolean b){
4055 flags=(flags&~RESCUEDMASK);
4056 if(b){flags|=RESCUEDMASK;}
4057 }
4058
4059 public void setMapped(boolean b){
4060 flags=(flags&~MAPPEDMASK);
4061 if(b){flags|=MAPPEDMASK;}
4062 }
4063
4064 public void setPairDiscarded(boolean b){
4065 setDiscarded(b);
4066 if(mate!=null) {mate.setDiscarded(b);}
4067 }
4068 public void setDiscarded(boolean b){
4069 flags=(flags&~DISCARDMASK);
4070 if(b){flags|=DISCARDMASK;}
4071 }
4072
4073 public void setInvalid(boolean b){
4074 flags=(flags&~INVALIDMASK);
4075 if(b){flags|=INVALIDMASK;}
4076 }
4077
4078 public void setSwapped(boolean b){
4079 flags=(flags&~SWAPMASK);
4080 if(b){flags|=SWAPMASK;}
4081 }
4082
4083 public void setShortMatch(boolean b){
4084 flags=(flags&~SHORTMATCHMASK);
4085 if(b){flags|=SHORTMATCHMASK;}
4086 }
4087
4088 public void setInsertValid(boolean b){
4089 flags=(flags&~INSERTMASK);
4090 if(b){flags|=INSERTMASK;}
4091 }
4092
4093 public void setHasAdapter(boolean b){
4094 flags=(flags&~ADAPTERMASK);
4095 if(b){flags|=ADAPTERMASK;}
4096 }
4097
4098 public void setSecondary(boolean b){
4099 flags=(flags&~SECONDARYMASK);
4100 if(b){flags|=SECONDARYMASK;}
4101 }
4102
4103 public void setAminoAcid(boolean b){
4104 flags=(flags&~AAMASK);
4105 if(b){flags|=AAMASK;}
4106 }
4107
4108 public void setJunk(boolean b){
4109 flags=(flags&~JUNKMASK);
4110 if(b){flags|=JUNKMASK;}
4111 }
4112
4113 public void setValidated(boolean b){
4114 flags=(flags&~VALIDATEDMASK);
4115 if(b){flags|=VALIDATEDMASK;}
4116 }
4117
4118 public void setTested(boolean b){
4119 flags=(flags&~TESTEDMASK);
4120 if(b){flags|=TESTEDMASK;}
4121 }
4122
4123 public void setInvertedRepeat(boolean b){
4124 flags=(flags&~IRMASK);
4125 if(b){flags|=IRMASK;}
4126 }
4127
4128 public void setTrimmed(boolean b){
4129 flags=(flags&~TRIMMEDMASK);
4130 if(b){flags|=TRIMMEDMASK;}
4131 }
4132
4133 public void setInsert(int x){
4134 if(x<1){x=-1;}
4135 // assert(x==-1 || x>9 || length()<20) : x+", "+length(); //Invalid assertion for synthetic reads.
4136 insert=x;
4137 setInsertValid(x>0);
4138 if(mate!=null){
4139 mate.insert=x;
4140 mate.setInsertValid(x>0);
4141 }
4142 }
4143
4144 private static int[] makeMaskArray(int max) {
4145 int[] r=new int[max+1];
4146 for(int i=0; i<r.length; i++){r[i]=(1<<i);}
4147 return r;
4148 }
4149
4150
4151
4152 public static byte[] getFakeQuality(int len){
4153 if(len>=QUALCACHE.length){
4154 byte[] r=KillSwitch.allocByte1D(len);
4155 Arrays.fill(r, (byte)30);
4156 return r;
4157 }
4158 if(QUALCACHE[len]==null){
4159 synchronized(QUALCACHE){
4160 if(QUALCACHE[len]==null){
4161 QUALCACHE[len]=KillSwitch.allocByte1D(len);
4162 Arrays.fill(QUALCACHE[len], (byte)30);
4163 }
4164 }
4165 }
4166 return QUALCACHE[len];
4167 }
4168
4169 public byte[] getScaffoldName(boolean requireSingleScaffold){
4170 byte[] name=null;
4171 if(mapped()){
4172 if(!requireSingleScaffold || Data.isSingleScaffold(chrom, start, stop)){
4173 int idx=Data.scaffoldIndex(chrom, (start+stop)/2);
4174 name=Data.scaffoldNames[chrom][idx];
4175 // int scaflen=Data.scaffoldLengths[chrom][idx];
4176 // a1=Data.scaffoldRelativeLoc(chrom, start, idx);
4177 // b1=a1-start1+stop1;
4178 }
4179 }
4180 return name;
4181 }
4182
4183 public void bisulfite(boolean AtoG, boolean CtoT, boolean GtoA, boolean TtoC){
4184 for(int i=0; i<bases.length; i++){
4185 final int x=AminoAcid.baseToNumber[bases[i]];
4186 if(x==0 && AtoG){bases[i]='G';}
4187 else if(x==1 && CtoT){bases[i]='T';}
4188 else if(x==2 && GtoA){bases[i]='A';}
4189 else if(x==3 && TtoC){bases[i]='C';}
4190 }
4191 }
4192
4193 public Read copy(){
4194 Read r=clone();
4195 r.bases=(r.bases==null ? null : r.bases.clone());
4196 r.quality=(r.quality==null ? null : r.quality.clone());
4197 r.match=(r.match==null ? null : r.match.clone());
4198 r.gaps=(r.gaps==null ? null : r.gaps.clone());
4199 r.originalSite=(r.originalSite==null ? null : r.originalSite.clone());
4200 r.sites=(ArrayList<SiteScore>) (r.sites==null ? null : r.sites.clone());
4201 r.mate=null;
4202
4203 if(r.sites!=null){
4204 for(int i=0; i<r.sites.size(); i++){
4205 r.sites.set(i, r.sites.get(i).clone());
4206 }
4207 }
4208 return r;
4209 }
4210
4211 @Override
4212 public Read clone(){
4213 try {
4214 return (Read) super.clone();
4215 } catch (CloneNotSupportedException e) {
4216 // TODO Auto-generated catch block
4217 e.printStackTrace();
4218 }
4219 throw new RuntimeException();
4220 }
4221
4222 /**
4223 * @return This protein in canonical nucleotide space.
4224 */
4225 public Read aminoToNucleic() {
4226 assert(aminoacid()) : "This read is not flagged as an amino acid sequence.";
4227 Read r=this.clone();
4228 r.setAminoAcid(false);
4229 r.bases=AminoAcid.toNTs(r.bases);
4230 if(quality!=null){
4231 byte[] ntquals=new byte[r.quality.length*3];
4232 for(int i=0; i<quality.length; i++){
4233 byte q=quality[i];
4234 byte q2=(byte)Tools.min(q+5, MAX_CALLED_QUALITY);
4235 ntquals[i]=ntquals[i+1]=ntquals[i+2]=q2;
4236 }
4237 r.quality=ntquals;
4238 }
4239 return r;
4240 }
4241
4242 private static final byte[][] QUALCACHE=new byte[1000][];
4243
4244
4245 public static final int STRANDMASK=1;
4246 public static final int MAPPEDMASK=(1<<1);
4247 public static final int PAIREDMASK=(1<<2);
4248 public static final int PERFECTMASK=(1<<3);
4249 public static final int AMBIMASK=(1<<4);
4250 public static final int RESCUEDMASK=(1<<5);
4251 // public static final int COLORMASK=(1<<6); //TODO: Change to semiperfectmask?
4252 public static final int SYNTHMASK=(1<<7);
4253 public static final int DISCARDMASK=(1<<8);
4254 public static final int INVALIDMASK=(1<<9);
4255 public static final int SWAPMASK=(1<<10);
4256 public static final int SHORTMATCHMASK=(1<<11);
4257
4258 public static final int PAIRNUMSHIFT=12;
4259 public static final int PAIRNUMMASK=(1<<PAIRNUMSHIFT);
4260
4261 public static final int INSERTMASK=(1<<13);
4262 public static final int ADAPTERMASK=(1<<14);
4263 public static final int SECONDARYMASK=(1<<15);
4264 public static final int AAMASK=(1<<16);
4265 public static final int JUNKMASK=(1<<17);
4266 public static final int VALIDATEDMASK=(1<<18);
4267 public static final int TESTEDMASK=(1<<19);
4268 public static final int IRMASK=(1<<20);
4269 public static final int TRIMMEDMASK=(1<<21);
4270
4271 private static final int[] maskArray=makeMaskArray(22); //Be sure this is big enough for all flags!
4272
4273 public static boolean TO_UPPER_CASE=false;
4274 public static boolean LOWER_CASE_TO_N=false;
4275 public static boolean DOT_DASH_X_TO_N=false;
4276 public static boolean AVERAGE_QUALITY_BY_PROBABILITY=true;
4277 public static boolean FIX_HEADER=false;
4278 public static boolean ALLOW_NULL_HEADER=false;
4279 public static boolean SKIP_SLOW_VALIDATION=false;
4280 public static final boolean VALIDATE_BRANCHLESS=true;
4281
4282 public static final int IGNORE_JUNK=0;
4283 public static final int FLAG_JUNK=1;
4284 public static final int FIX_JUNK=2;
4285 public static final int CRASH_JUNK=3;
4286 public static final int FIX_JUNK_AND_IUPAC=4;
4287 public static int JUNK_MODE=CRASH_JUNK;
4288 public static boolean IUPAC_TO_N=false;
4289
4290 public static boolean U_TO_T=false;
4291 public static boolean COMPRESS_MATCH_BEFORE_WRITING=true;
4292 public static boolean DECOMPRESS_MATCH_ON_LOAD=true; //Set to false for some applications, like sorting, perhaps
4293
4294 public static boolean ADD_BEST_SITE_TO_LIST_FROM_TEXT=true;
4295 public static boolean NULLIFY_BROKEN_QUALITY=false;
4296 public static boolean TOSS_BROKEN_QUALITY=false;
4297 public static boolean FLAG_BROKEN_QUALITY=false;
4298 public static boolean FLAT_IDENTITY=true;
4299 public static boolean VALIDATE_IN_CONSTRUCTOR=true;
4300
4301 public static boolean verbose=false;
4302
4303 /*--------------------------------------------------------------*/
4304
4305 /** Offset for quality scores, normally 33, or 64 for some old Illumina data */
4306 private static final byte ASCII_OFFSET=33;
4307
4308 /** Allow quality scores to be changed, typically for corrupt Illumina data */
4309 public static boolean CHANGE_QUALITY=true; //Cap all quality values between MIN_CALLED_QUALITY and MAX_CALLED_QUALITY
4310
4311 /** Minimum allowed quality score for called (ACGT) bases */
4312 private static byte MIN_CALLED_QUALITY=2;
4313
4314 /** Maximum allowed quality score for called (ACGT) bases */
4315 private static byte MAX_CALLED_QUALITY=50; //TODO: Find, replace, and test all instances of 41 (old value).
4316
4317 /** Maximum allowed quality score for merged reads, which otherwise would normally be very high */
4318 public static byte MAX_MERGE_QUALITY=50;
4319 public static byte[] qMap=makeQmap(MIN_CALLED_QUALITY, MAX_CALLED_QUALITY);
4320
4321 public static byte MIN_CALLED_QUALITY(){return MIN_CALLED_QUALITY;}
4322 public static byte MAX_CALLED_QUALITY(){return MAX_CALLED_QUALITY;}
4323
4324 public static void setMaxCalledQuality(int x){
4325 x=Tools.mid(1, x, 93);
4326 if(x!=MAX_CALLED_QUALITY){
4327 MAX_CALLED_QUALITY=(byte)x;
4328 qMap=makeQmap(MIN_CALLED_QUALITY, MAX_CALLED_QUALITY);
4329 }
4330 }
4331
4332 public static void setMinCalledQuality(int x){
4333 x=Tools.mid(0, x, 93);
4334 if(x!=MIN_CALLED_QUALITY){
4335 MIN_CALLED_QUALITY=(byte)x;
4336 qMap=makeQmap(MIN_CALLED_QUALITY, MAX_CALLED_QUALITY);
4337 }
4338 }
4339
4340 public static byte capQuality(long q){
4341 return (byte)Tools.mid(MIN_CALLED_QUALITY, q, MAX_CALLED_QUALITY);
4342 }
4343
4344 public static byte capQuality(byte q){
4345 return qMap[q];
4346 }
4347
4348 public static byte capQuality(byte q, byte b){
4349 return AminoAcid.isFullyDefined(b) ? qMap[q] : 0;
4350 }
4351
4352 private static byte[] makeQmap(byte min, byte max){
4353 byte[] r=(qMap==null ? new byte[128] : qMap);
4354 for(int i=0; i<r.length; i++){
4355 r[i]=(byte) Tools.mid(min, i, max);
4356 }
4357 return r;
4358 }
4359 }