Debian Codegraph @

current/stream/SiteScore.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.Comparator;
7
8 import align2.GapTools;
9 import align2.MSA;
10 import dna.AminoAcid;
11 import dna.ChromosomeArray;
12 import dna.Data;
13 import shared.Shared;
14 import shared.Tools;
15 import structures.ByteBuilder;
16
17
18
19 public final class SiteScore implements Comparable<SiteScore>, Cloneable, Serializable{
20
21 /**
22 *
23 */
24 private static final long serialVersionUID = -8096245242590075081L;
25
26 public SiteScore(int chrom_, byte strand_, int start_, int stop_, int hits_, int quickScore_){
27 start=start_;
28 stop=stop_;
29 hits=hits_;
30 quickScore=quickScore_;
31 score=quickScore_;
32 chrom=chrom_;
33 strand=strand_;
34 // assert(chrom_>=0) : this.toText()+"\nchrom_="+chrom_+", strand_="+strand_+", start_="+start_+", stop_="+stop_+", hits_="+hits_+", quickScore_="+quickScore_;
35 assert(start_<=stop_) : this.toText()+"\nchrom_="+chrom_+", strand_="+strand_+", start_="+start_+", stop_="+stop_+", hits_="+hits_+", quickScore_="+quickScore_;
36 }
37
38 public SiteScore(int chrom_, byte strand_, int start_, int stop_, int hits_, int quickScore_, boolean rescued_, boolean perfect_){
39 start=start_;
40 stop=stop_;
41 hits=hits_;
42 quickScore=quickScore_;
43 score=quickScore_;
44 chrom=chrom_;
45 strand=strand_;
46 rescued=rescued_;
47 perfect=perfect_;
48 semiperfect=perfect;
49 assert(start_<=stop_) : this.toText();
50 }
51
52 @Override
53 public int compareTo(SiteScore other) {
54 int x=other.score-score;
55 if(x!=0){return x;}
56
57 x=other.slowScore-slowScore;
58 if(x!=0){return x;}
59
60 x=other.pairedScore-pairedScore;
61 if(x!=0){return x;}
62
63 x=other.quickScore-quickScore;
64 if(x!=0){return x;}
65
66 x=chrom-other.chrom;
67 if(x!=0){return x;}
68
69 x=start-other.start;
70 return x;
71 }
72
73 @Override
74 public boolean equals(Object other){
75 return compareTo((SiteScore)other)==0;
76 }
77
78 @Override
79 public int hashCode() {
80 assert(false) : "This class should not be hashed.";
81 return super.hashCode();
82 }
83
84 @Override
85 public String toString(){
86 return toText().toString();
87 }
88
89 // 9+2+1+9+9+1+1+4+4+4+4+gaps
90 public CharSequence toText(){
91 StringBuilder sb=new StringBuilder(53+(gaps==null ? 0 : gaps.length*10));
92 sb.append(chrom);
93 sb.append(',');
94 sb.append(strand);
95 sb.append(',');
96 sb.append(start);
97 sb.append(',');
98 sb.append(stop);
99 sb.append(',');
100 sb.append((rescued ? 1 : 0));
101 sb.append(',');
102 sb.append((semiperfect ? 1 : 0));
103 sb.append((perfect ? 1 : 0));
104 sb.append(',');
105 sb.append(hits);
106 sb.append(',');
107 sb.append(quickScore);
108 sb.append(',');
109 sb.append(slowScore);
110 sb.append(',');
111 sb.append(pairedScore);
112 sb.append(',');
113 sb.append(score);
114
115 if(gaps!=null){
116 sb.append(',');
117 for(int i=0; i<gaps.length; i++){
118 if(i>0){sb.append('~');}
119 sb.append(gaps[i]);
120 }
121 }
122
123 if(match!=null){
124 if(gaps==null){sb.append(',');}
125 sb.append(',');
126 final char[] buffer=Shared.getTLCB(match.length);
127 for(int i=0; i<match.length; i++){buffer[i]=(char)match[i];}
128 sb.append(buffer, 0, match.length);
129 }
130
131 return sb;
132 // chrom+","+strand+","+start+","+stop+","+(rescued ? 1 : 0)+","+
133 // (perfect ? 1 : 0)+","+quickScore+","+slowScore+","+pairedScore+","+score;
134 }
135
136 // 9+2+1+9+9+1+1+4+4+4+4+gaps
137 public ByteBuilder toBytes(ByteBuilder sb){
138 if(sb==null){sb=new ByteBuilder(53+(gaps==null ? 0 : gaps.length*10));}
139 sb.append(chrom);
140 sb.append(',');
141 sb.append((int)strand);
142 sb.append(',');
143 sb.append(start);
144 sb.append(',');
145 sb.append(stop);
146 sb.append(',');
147 sb.append((rescued ? 1 : 0));
148 sb.append(',');
149 sb.append((semiperfect ? 1 : 0));
150 sb.append((perfect ? 1 : 0));
151 sb.append(',');
152 sb.append(hits);
153 sb.append(',');
154 sb.append(quickScore);
155 sb.append(',');
156 sb.append(slowScore);
157 sb.append(',');
158 sb.append(pairedScore);
159 sb.append(',');
160 sb.append(score);
161
162 if(gaps!=null){
163 sb.append(',');
164 for(int i=0; i<gaps.length; i++){
165 if(i>0){sb.append('~');}
166 sb.append(gaps[i]);
167 }
168 }
169
170 if(match!=null){
171 if(gaps==null){sb.append(',');}
172 sb.append(',');
173 sb.append(match);
174 }
175
176 return sb;
177 // chrom+","+strand+","+start+","+stop+","+(rescued ? 1 : 0)+","+
178 // (perfect ? 1 : 0)+","+quickScore+","+slowScore+","+pairedScore+","+score;
179 }
180
181 public boolean isSemiPerfect(byte[] bases){
182 if(bases.length!=stop-start+1){return false;}
183 byte[] ref=Data.getChromosome(chrom).array;
184
185 //This block handles cases where the read runs outside the reference
186 //Of course, padding the reference with 'N' would be better, but...
187 int readStart=0;
188 int readStop=bases.length;
189 final int refStop=start+bases.length;
190 int maxNoref=bases.length/2;
191
192 if(start<0){
193 readStart=0-start;
194 }
195 if(refStop>ref.length){
196 int dif=(refStop-ref.length);
197 readStop-=dif;
198 }
199
200 for(int i=readStart; i<readStop; i++){
201 byte c=bases[i];
202 byte r=ref[start+i];
203
204 // assert(Tools.isUpperCase(c) && Tools.isUpperCase(r));
205 if(c=='N'){return false;}
206 if(c!=r){
207 maxNoref--;
208 if(maxNoref<0 || r!='N'){return false;}
209 }
210 }
211 return true;
212 }
213
214 public boolean isPerfect(byte[] bases){
215 if(bases.length!=stop-start+1 || start<0){return false;}
216 byte[] ref=Data.getChromosome(chrom).array;
217 if(stop>=ref.length){return false;}
218
219 for(int i=0; i<bases.length; i++){
220 byte c=bases[i];
221 byte r=ref[start+i];
222 assert(Tools.isUpperCase(c) && Tools.isUpperCase(r)) : "Lowercase letters detected: ref="+(char)r+", read="+(char)c+"\n"+new String(bases)+"\n"+
223 "Please re-run with the 'tuc=t' flag (touppercase=true).";
224
225 if((c!=r /* && (Tools.toUpperCase(c)!=Tools.toUpperCase(r))*/) || c=='N'){
226 return false;
227 }
228 }
229 return true;
230 }
231
232
233 public boolean setPerfectFlag(int maxScore, byte[] bases){
234 if(maxScore==slowScore){
235 assert(isPerfect(bases));
236 return perfect=semiperfect=true;
237 }
238 return setPerfect(bases, false);
239 }
240
241 /** Sets "perfect" and "semiperfect" flags */
242 public boolean setPerfect(byte[] bases){return setPerfect(bases, false);}
243
244 /** Sets "perfect" and "semiperfect" flags, optionally assuming "perfect" flag is correct. */
245 public boolean setPerfect(byte[] bases, boolean assumePerfectCorrect){
246 if(bases.length!=stop-start+1){
247 assert(!perfect || !assumePerfectCorrect) : perfect+", "+toString()+", "+
248 new String(Data.getChromosome(chrom).array, Tools.max(0, start), (Tools.min(Data.chromLengths[chrom], stop)-start));
249 perfect=false;
250 semiperfect=false;
251 assert(Read.CHECKSITE(this, bases, 0)) : new String(bases)+"\n"+this+"\n"; //123
252 return perfect;
253 }
254 byte[] ref=Data.getChromosome(chrom).array;
255
256 perfect=semiperfect=true;
257 int refloc=start, readloc=0, N=0, max=Tools.min(stop, ref.length-1), nlimit=bases.length/2;
258 if(start<0){
259 N-=start;
260 readloc-=start;
261 refloc-=start;
262 assert(!perfect || !assumePerfectCorrect);
263 perfect=false;
264 }
265 if(stop>=ref.length){
266 N+=(stop-ref.length+1);
267 assert(!perfect || !assumePerfectCorrect);
268 perfect=false;
269 }
270 if(N>nlimit){
271 perfect=semiperfect=false;
272 assert(Read.CHECKSITE(this, bases, 0)); //123
273 return perfect;
274 }
275
276 final byte bn=(byte)'N';
277 for(; refloc<=max; refloc++, readloc++){
278 final byte c=bases[readloc];
279 final byte r=ref[refloc];
280 assert(Tools.isUpperCase(r) && Tools.isUpperCase(c)) :
281 "\nAn input read appears to contain a non-upper-case base. Please rerun with the 'touppercase' flag.\n"+
282 "ref base = "+r+", read base = "+c+", TO_UPPER_CASE = "+Read.TO_UPPER_CASE+"\n"+(bases.length<=500 ? new String(bases) : "")+"\n";
283 if(c!=r || c==bn){
284 perfect=false;
285 if(c==bn){semiperfect=false;}
286 if(r!=bn || (N=N+1)>nlimit){
287 semiperfect=false;
288 assert(Read.CHECKSITE(this, bases, 0)); //123
289 return semiperfect;
290 }
291 }
292 }
293
294 semiperfect=(semiperfect && (N<=nlimit));
295 perfect=(perfect && semiperfect && (N==0));
296 assert(Read.CHECKSITE(this, bases, 0)); //123
297 return perfect;
298 }
299
300 public final boolean overlaps(SiteScore ss){
301 return chrom==ss.chrom && strand==ss.strand && overlap(start, stop, ss.start, ss.stop);
302 }
303 public final boolean overlaps(SiteScore ss, boolean ignoreStrand){
304 return chrom==ss.chrom && (ignoreStrand || strand==ss.strand) && overlap(start, stop, ss.start, ss.stop);
305 }
306 private static boolean overlap(int a1, int b1, int a2, int b2){
307 assert(a1<=b1 && a2<=b2) : a1+", "+b1+", "+a2+", "+b2;
308 return a2<=b1 && b2>=a1;
309 }
310
311 public static String header() {
312 return "chrom,strand,start,stop,rescued,semiperfect+perfect,hits,quickScore,slowScore,pairedScore,score,match";
313 }
314
315 public static SiteScore fromText(String s){
316 // System.err.println("Trying to make a SS from "+s);
317 String line[]=s.split(",");
318
319 SiteScore ss;
320
321 assert(line.length>=11 && line.length<=13) : "\n"+line.length+"\n"+s+"\n"+Arrays.toString(line)+"\n";
322 int chrom=Byte.parseByte(line[0].charAt(0)=='*' ? line[0].substring(1) : line[0]);
323 byte strand=Byte.parseByte(line[1]);
324 int start=Integer.parseInt(line[2]);
325 int stop=Integer.parseInt(line[3]);
326 boolean rescued=Integer.parseInt(line[4])==1;
327 // [1, 1, 9397398, 9398220, 0, 00, 20, 8701, 9084, 0, 9084, 9397398~9397471~9398145~9398220]
328 int p=Integer.parseInt(line[5], 2);
329 // assert(false) : line[5]+"->"+p;
330 boolean perfect=(p&1)==1;
331 boolean semiperfect=(p&2)==2;
332 int hits=Integer.parseInt(line[6]);
333 int quickScore=Integer.parseInt(line[7]);
334 int swscore=Integer.parseInt(line[8]);
335 int pairedScore=Integer.parseInt(line[9]);
336 int score=Integer.parseInt(line[10]);
337 ss=new SiteScore(chrom, strand, start, stop, hits, quickScore, rescued, perfect);
338 ss.setScore(score);
339 ss.setSlowPairedScore(swscore, pairedScore);
340 ss.semiperfect=semiperfect;
341
342 if(line.length>11){
343 if(line[11]!=null && line[11].length()>0){
344 String[] gstring=line[11].split("~");
345 ss.gaps=new int[gstring.length];
346 for(int i=0; i<gstring.length; i++){
347 ss.gaps[i]=Integer.parseInt(gstring[i]);
348 }
349 }
350 }
351
352 if(line.length>12){
353 ss.match=line[12].getBytes();
354 }
355
356 return ss;
357 }
358
359 public boolean positionalMatch(SiteScore b, boolean testGaps){
360 // return chrom==b.chrom && strand==b.strand && start==b.start && stop==b.stop;
361 if(chrom!=b.chrom || strand!=b.strand || start!=b.start || stop!=b.stop){
362 return false;
363 }
364 if(!testGaps || (gaps==null && b.gaps==null)){return true;}
365 if((gaps==null) != (b.gaps==null)){return false;}
366 if(gaps.length!=b.gaps.length){return false;}
367 for(int i=0; i<gaps.length; i++){
368 if(gaps[i]!=b.gaps[i]){return false;}
369 }
370 return true;
371 }
372
373 public byte[] getScaffoldName(boolean requireSingleScaffold){
374 byte[] name=null;
375 if(!requireSingleScaffold || Data.isSingleScaffold(chrom, start, stop)){
376 int idx=Data.scaffoldIndex(chrom, (start+stop)/2);
377 name=Data.scaffoldNames[chrom][idx];
378 // int scaflen=Data.scaffoldLengths[chrom][idx];
379 // a1=Data.scaffoldRelativeLoc(chrom, start, idx);
380 // b1=a1-start1+stop1;
381 }
382 return name;
383 }
384
385 public static class PositionComparator implements Comparator<SiteScore>{
386
387 private PositionComparator(){}
388
389 @Override
390 public int compare(SiteScore a, SiteScore b) {
391 if(a.chrom!=b.chrom){return a.chrom-b.chrom;}
392 if(a.start!=b.start){return a.start-b.start;}
393 if(a.stop!=b.stop){return a.stop-b.stop;}
394 if(a.strand!=b.strand){return a.strand-b.strand;}
395 if(a.score!=b.score){return b.score-a.score;}
396 if(a.slowScore!=b.slowScore){return b.slowScore-a.slowScore;}
397 if(a.quickScore!=b.quickScore){return b.quickScore-a.quickScore;}
398 if(a.perfect!=b.perfect){return a.perfect ? -1 : 1;}
399 if(a.rescued!=b.rescued){return a.rescued ? 1 : -1;}
400 return 0;
401 }
402
403 public void sort(ArrayList<SiteScore> list){
404 if(list==null || list.size()<2){return;}
405 Shared.sort(list, this);
406 }
407
408 public void sort(SiteScore[] list){
409 if(list==null || list.length<2){return;}
410 Arrays.sort(list, this);
411 }
412
413 }
414
415 public SiteScore copy(){
416 SiteScore ss2=this.clone();
417 if(gaps!=null){ss2.gaps=ss2.gaps.clone();}
418 return ss2;
419 }
420
421 @Override
422 public SiteScore clone(){
423 try {
424 return (SiteScore)super.clone();
425 } catch (CloneNotSupportedException e) {
426 // TODO Auto-generated catch block
427 e.printStackTrace();
428 }
429 throw new RuntimeException();
430 }
431
432 public boolean isInBounds(){
433 ChromosomeArray cha=Data.getChromosome(chrom);
434 return (start>=0 && stop<=cha.maxIndex);
435 }
436
437 public boolean matchContainsXY(){
438 if(match==null || match.length<1){return false;}
439 final byte a=match[0], b=match[match.length-1];
440 return (a=='X' ||a=='Y' || b=='X' || b=='Y');
441 }
442
443 public boolean matchContainsAB(){
444 if(match==null || match.length<1){return false;}
445 final byte a=match[0], b=match[match.length-1];
446 return (a=='A' ||a=='B' || b=='A' || b=='B');
447 }
448
449 public boolean matchContainsC(){
450 if(match==null || match.length<1){return false;}
451 final byte a=match[0], b=match[match.length-1];
452 return (a=='C' || b=='C');
453 }
454
455 public boolean isCorrect(int chrom_, byte strand_, int start_, int stop_, int thresh){
456 if(chrom_!=chrom || strand_!=strand){return false;}
457 if(thresh<=0){return start_==start && stop_==stop;}
458 return Tools.absdif(start_, start)<=thresh || Tools.absdif(stop_, stop)<=thresh;
459 }
460
461 public int leftPaddingNeeded(int tiplen, int maxIndel){
462 if(match==null || match.length<1){return 0;}
463
464 int neutral=0, insertion=0, deletion=0, xy=0;
465 {
466 int mloc=0;
467 for(; mloc<match.length; mloc++){
468 byte c=match[mloc];
469 if(c=='I'){insertion++;}
470 else if(c=='X' || c=='Y'){xy++;}
471 else if(c=='D'){return insertion+xy;}
472 else{
473 neutral++;
474 if(mloc>=tiplen){break;}
475 }
476 }
477 }
478
479 if(insertion>maxIndel || xy>0 || match[0]=='I'){return insertion+xy;}
480 return 0;
481 }
482
483 public int rightPaddingNeeded(int tiplen, int maxIndel){
484 if(match==null || match.length<1){return 0;}
485 final int lastIndex=match.length-1;
486
487 int neutral=0, insertion=0, deletion=0, xy=0;
488 {
489 int mloc=lastIndex;
490 for(int min=lastIndex-tiplen; mloc>=0; mloc--){
491 byte c=match[mloc];
492 if(c=='I'){insertion++;}
493 else if(c=='X' || c=='Y'){xy++;}
494 else if(c=='D'){return insertion+xy;}
495 else{
496 neutral++;
497 if(mloc>=tiplen){break;}
498 }
499 }
500 }
501
502 if(insertion>maxIndel || xy>0 || match[lastIndex]=='I'){return insertion+xy;}
503 return 0;
504 }
505
506 /** Assumes bases are rcomped as needed */
507 public int unclip(byte[] bases, byte[] rbases){
508 int unclipped=0;
509 if(match==null || match.length<1){return unclipped;}
510 assert(lengthsAgree());
511
512 for(int mpos=0, bpos=0, rpos=start; mpos<match.length && rpos<rbases.length; mpos++, bpos++, rpos++){
513 if(match[mpos]!='C'){break;}
514 if(rpos>=0){
515 byte b=bases[bpos];
516 byte r=rbases[rpos];
517
518 if(!AminoAcid.isFullyDefined(b) || !AminoAcid.isFullyDefined(r)){match[mpos]='N';}
519 else if(b==r){match[mpos]='m';}
520 else{match[mpos]='S';}
521 unclipped++;
522 }
523 }
524 assert(lengthsAgree());
525
526 for(int mpos=match.length-1, bpos=bases.length-1, rpos=stop; mpos>=0 && rpos>=0; mpos--, bpos--, rpos--){
527 if(match[mpos]!='C'){break;}
528 if(rpos<rbases.length){
529 byte b=bases[bpos];
530 byte r=rbases[rpos];
531 if(b=='N' || r=='N'){match[mpos]='N';}
532 else if(b==r){match[mpos]='m';}
533 else{match[mpos]='S';}
534 unclipped++;
535 }
536 }
537 assert(lengthsAgree());
538
539 return unclipped;
540 }
541
542 /** Simply replaces terminal 'I', 'X', and 'Y' with 'C' and adjusts length
543 * TODO: Also clip out-of-bounds. */
544 public int clipTipIndels(int rlen){
545 int clipped=0;
546 if(match==null || match.length<1){return clipped;}
547 assert(lengthsAgree());
548
549 for(int mpos=0, rpos=start; mpos<match.length; mpos++){
550 final byte m=match[mpos];
551 if(m=='C'){
552 //Do nothing
553 rpos++;
554 }else if(m=='m' || m=='S'){
555 break;
556 }else{
557 if(m=='I'){
558 start--;
559 }else if(m=='X'){
560 rpos++;
561 }else if(m=='Y'){//Should not happen
562 start--;
563 }else if(m=='D'){
564 //Do nothing
565 }else if(rpos>=0){
566 break;
567 }else{
568 assert(m=='N') : (char)m+"\n"+mpos+", "+rpos+"\n"+this;
569 rpos++;
570 }
571 clipped++;
572 match[mpos]='C';
573 }
574 }
575 assert(clipped==0 || lengthsAgree());
576
577 for(int mpos=match.length-1, rpos=stop; mpos>=0; mpos--){
578 final byte m=match[mpos];
579 if(m=='C'){
580 //Do nothing
581 rpos--;
582 }else if(m=='m' || m=='S'){
583 break;
584 }else{
585 if(m=='I'){
586 stop++;
587 }else if(m=='X'){//Should not happen
588 assert(false);
589 rpos--;
590 }else if(m=='Y'){
591 stop++;
592 }else if(m=='D'){
593 //Do nothing
594 }else if(rpos<rlen){
595 break;
596 }else{
597 assert(m=='N') : (char)m+"\n"+mpos+", "+rpos+"\n"+this;
598 rpos--;
599 }
600 clipped++;
601 match[mpos]='C';
602 }
603 }
604 assert(clipped==0 || lengthsAgree());
605
606 return clipped;
607 }
608
609 // /** Simply replaces terminal 'I', 'X', and 'Y' with 'C' and adjusts length
610 // * TODO: Also clip out-of-bounds. */
611 // public int clipTipIndels(int rlen){
612 // int clipped=0;
613 // if(match==null || match.length<1){return clipped;}
614 // assert(lengthsAgree());
615 //
616 // for(int mpos=0, rpos=start; mpos<match.length; mpos++){
617 // final byte m=match[mpos];
618 // if(m=='I'){
619 // start++;
620 // }else if(m=='X' || m=='Y' || m=='D'){
621 // //Do nothing
622 // }else{
623 // break;
624 // }
625 // clipped++;
626 // match[mpos]='C';
627 // }
628 // assert(clipped==0 || lengthsAgree());
629 //
630 // for(int mpos=match.length-1, rpos=stop; mpos>=0; mpos--){
631 // final byte m=match[mpos];
632 // if(m=='I'){
633 // start++;
634 // }else if(m=='X' || m=='Y' || m=='D'){
635 // //Do nothing
636 // }else{
637 // break;
638 // }
639 // clipped++;
640 // match[mpos]='C';
641 // }
642 // assert(clipped==0 || lengthsAgree());
643 //
644 // return clipped;
645 // }
646
647 public boolean clipTipIndels(byte[] bases, byte[] basesM, int tiplen, int maxIndel, MSA msa){
648 return this.plus() ? clipTipIndels(bases, tiplen, maxIndel, msa) : clipTipIndels(basesM, tiplen, maxIndel, msa);
649 }
650
651 public boolean clipTipIndels(byte[] bases, int tiplen, int maxIndel, MSA msa){
652 if(match==null || match.length<maxIndel){return false;}
653 if(verbose){
654 System.err.println("Calling clipTipIndels:\n"+new String(match));
655 System.err.println("slowScore="+slowScore+", pairedScore="+pairedScore);
656 }
657 assert(lengthsAgree());
658 boolean left=clipLeftTipIndel(bases, tiplen, maxIndel);
659 assert(lengthsAgree());
660 boolean right=clipRightTipIndel(bases, tiplen, maxIndel);
661 assert(lengthsAgree());
662
663 if(verbose){System.err.println("left="+left+", right="+right+", match="+new String(match));}
664 if(left || right){
665 unclip(bases);
666 assert(lengthsAgree());
667 int oldScore=slowScore;
668 if(verbose){System.err.println("oldScore="+oldScore+", slowScore="+slowScore+", pairedScore="+pairedScore+", newPairedScore="+(pairedScore+(slowScore-oldScore)));}
669 setSlowScore(msa.score(match));
670 setScore(score+(slowScore-oldScore));
671 this.setPerfect(bases);
672 }
673 if(verbose){System.err.println("After clipTipIndels:\n"+new String(match));}
674 return left | right;
675 }
676
677 public boolean clipLeftTipIndel(byte[] bases, int tiplen, int maxIndel){
678 if(match==null || match.length<maxIndel){return false;}
679 if(match[0]=='C' || match[0]=='Y' || match[0]=='X'){return false;}
680
681 int neutral=0, insertion=0, deletion=0;
682 {
683 int mloc=0;
684 for(; mloc<match.length; mloc++){
685 byte c=match[mloc];
686 if(c=='I'){insertion++;}
687 else if(c=='D'){deletion++;}
688 else{
689 neutral++;
690 if(mloc>=tiplen){break;}
691 }
692 }
693 while(mloc>=0 && match[mloc]=='m'){mloc--; neutral--;}
694 }
695 if(insertion<=maxIndel && deletion<=4*maxIndel){return false;}
696 assert(mappedLength()==matchLength() || matchContainsXY()) :
697 "start="+start+", stop="+stop+", maplen="+mappedLength()+", matchlen="+matchLength()+"\n"+new String(match)+"\n"+new String(bases)+"\n\n"+this;
698
699 int sum=neutral+insertion+deletion;
700 if(deletion>0){
701 byte[] temp=new byte[match.length-deletion];
702 int i=0, j=0;
703 for(; i<sum; i++){
704 byte c=match[i];
705 if(c=='D'){
706 //Do nothing
707 }else{
708 temp[j]=match[i];
709 j++;
710 }
711 }
712 for(; i<match.length; i++, j++){
713 temp[j]=match[i];
714 }
715 assert(i==match.length && j==temp.length) : i+", "+j+", "+match.length+", "+temp.length+"\n"+new String(match)+"\n"+new String(bases)+"\n"+this+"\n";
716 match=temp; //Be sure to percolate this to the read!
717 }
718
719 sum=neutral+insertion;
720 for(int i=0; i<sum; i++){
721 match[i]='C';
722 }
723
724 final int dif=(insertion-deletion);
725 incrementStart(-dif);
726 assert(mappedLength()==matchLength() || matchContainsXY());
727
728 return true;
729 }
730
731 public boolean clipRightTipIndel(final byte[] bases, final int tiplen, final int maxIndel){
732 if(match==null || match.length<maxIndel){return false;}
733 final int lastIndex=match.length-1;
734 if(match[lastIndex]=='C' || match[lastIndex]=='Y' || match[lastIndex]=='X'){return false;}
735
736 if(verbose){System.err.println("mappedLength="+mappedLength()+", matchLength()="+matchLength());}
737
738 int neutral=0, insertion=0, deletion=0;
739 {
740 int mloc=lastIndex;
741 for(int min=lastIndex-tiplen; mloc>=0; mloc--){
742 byte c=match[mloc];
743 if(c=='I'){insertion++;}
744 else if(c=='D'){deletion++;}
745 else{
746 neutral++;
747 if(mloc<=min){break;}
748 }
749 }
750 while(mloc<match.length && match[mloc]=='m'){mloc++; neutral--;}
751 }
752 if(insertion<=maxIndel && deletion<=4*maxIndel){return false;}
753 assert(mappedLength()==matchLength() || matchContainsXY()) : mappedLength()+", "+matchLength()+"\n"+new String(match)+"\n"+new String(bases);
754
755 int sum=neutral+insertion+deletion;
756 final int limit=match.length-sum;
757 if(deletion>0){
758 byte[] temp=new byte[match.length-deletion];
759 int i=0, j=0;
760 for(; i<limit; i++, j++){
761 temp[j]=match[i];
762 }
763 for(; i<match.length; i++){
764 byte c=match[i];
765 if(c=='D'){
766 //Do nothing
767 }else{
768 temp[j]=match[i];
769 j++;
770 }
771 }
772 assert(i==match.length && j==temp.length) : i+", "+j+", "+match.length+", "+temp.length+
773 "\n"+new String(match)+"\n"+new String(temp)+"\n"+new String(bases)+"\n"+this+"\n";
774 match=temp; //Be sure to percolate this to the read!
775 }
776
777 sum=neutral+insertion;
778 for(int i=limit; i<match.length; i++){
779 match[i]='C';
780 }
781
782
783 if(verbose){System.err.println("Final: "+new String(match));}
784 final int dif=(insertion-deletion);
785 if(verbose){System.err.println("mappedLength="+mappedLength()+", matchLength()="+matchLength()+", dif="+dif);}
786 incrementStop(dif);
787 assert(mappedLength()==matchLength() || matchContainsXY()) : mappedLength()+", "+matchLength()+", "+neutral+", "+insertion+", "+deletion+", "+dif;
788
789 return true;
790 }
791
792 public boolean unclip(final byte[] bases){
793 if(match==null || match.length<1){return false;}
794 if(verbose){System.err.println("Calling unclip on "+new String(match));}
795 {
796 byte first=match[0], last=match[match.length-1];
797 // if(first=='X' || last=='Y'){return false;}
798 if(first!='C' && last!='C'){
799 if(verbose){System.err.println("No unclipping needed.");}
800 return false;
801 }
802 }
803 assert(lengthsAgree()) : new String(bases)+"\n"+this;
804 final ChromosomeArray ca=Data.getChromosome(chrom);
805 for(int rloc=start, cloc=0, mloc=0; mloc<match.length; mloc++){
806 final byte m=match[mloc];
807
808 if(m=='C'){
809 final byte c=bases[cloc];
810 final byte r=ca.get(rloc);
811 if(!AminoAcid.isFullyDefined(c) || !AminoAcid.isFullyDefined(r)){
812 match[mloc]='N';
813 }else{
814 match[mloc]=(byte)(c==r ? 'm' : 'S');
815 }
816 rloc++;
817 cloc++;
818 }else if(m=='m' || m=='N' || m=='S'){
819 rloc++;
820 cloc++;
821 }else if(m=='X' || m=='Y'){
822 rloc++;
823 cloc++;
824 }else if(m=='I'){
825 cloc++;
826 }else if(m=='D'){
827 rloc++;
828 }else{
829 throw new RuntimeException("Unsupported symbol: ASCII "+(int)m);
830 }
831 }
832 if(verbose){System.err.println("After unclip: "+new String(match));}
833 assert(lengthsAgree()) : new String(bases)+"\n"+this;
834 return true;
835 }
836
837 /** TODO: Test
838 * Attempt to extend match/N symbols where there are X and Y symbols
839 * */
840 public boolean fixXY(byte[] bases, boolean nullifyOnFailure, MSA msa){
841 if(verbose && match!=null){System.err.println("Calling fixXY:\n"+new String(match));}
842 if(!matchContainsXY()){return true;}
843 if(verbose){System.err.println("lengthsAgree: "+this.lengthsAgree());}
844
845 boolean disable=false;
846 if(disable){
847 if(nullifyOnFailure){
848 match=null;
849 }
850 return false;
851 }
852
853 // if(match==null || match.length<1){return false;} //Already covered
854 final ChromosomeArray ca=Data.getChromosome(chrom);
855 // final int tip=3;
856 boolean success=true;
857 final float maxSubRate=0.4f;
858 final int maxSubs=5;
859
860 {//Process left side
861 if(verbose){System.err.println("Processing left side. Success="+success+", start="+start+", stop="+stop+", match=\n"+new String(match));}
862 int mloc=0;
863 while(mloc<match.length && (match[mloc]=='X' || match[mloc]=='Y')){mloc++;}
864 if(mloc>=match.length || mloc>=bases.length){success=false;}
865 else if(mloc>0){
866 mloc--;//Location of last X or Y on left side
867 final int numX=mloc+1;
868 int rloc=start+mloc, cloc=mloc;
869 int subs=0, firstSub=-1;
870 while(mloc>=0){
871 byte m=match[mloc];
872 byte c=bases[cloc];
873 byte r=ca.get(rloc);
874 assert(m=='X' || m=='Y') : (char)m+", "+mloc+", "+(char)c+", "+(char)r+"\n"+new String(bases)+"\n"+this.toString();
875 if(r=='N' || c=='N'){match[mloc]='N';}
876 else if(c==r){match[mloc]='m';}
877 // else if(mloc<=tip){match[mloc]='S';}
878 else{
879 match[mloc]='S';
880 subs++;
881 if(subs==1){firstSub=mloc;}
882 }
883 // else{
884 // if(verbose){System.err.println("A: Set success to false.");}
885 // success=false;
886 // break;
887 // }
888 mloc--;
889 rloc--;
890 cloc--;
891 }
892 if(success && mappedLength()!=matchLength()){incrementStart(-numX);}
893 if(subs>maxSubs && subs>numX*maxSubRate){
894 if(verbose){System.err.println("Failed to correct alignment; clipping left side of read.");}
895 for(int i=0; i<=firstSub; i++){
896 match[i]='C';
897 }
898 if(!lengthsAgree()){
899 assert(false);
900 incrementStart(firstSub+1);
901 assert(lengthsAgree());
902 }
903 }
904 }
905 if(verbose){System.err.println("Finished left side. Success="+success+", start="+start+", stop="+stop+", match=\n"+new String(match));}
906 if(verbose){System.err.println("lengthsAgree: "+this.lengthsAgree());}
907 }
908
909 if(success){//Process right side
910 if(verbose){System.err.println("Processing right side. Success="+success+", start="+start+", stop="+stop+", match=\n"+new String(match));}
911 int mloc=match.length-1;
912 while(mloc>=0 && (match[mloc]=='X' || match[mloc]=='Y')){mloc--;}
913 int dif=match.length-1-mloc;
914 if(mloc<0){
915 if(verbose){System.err.println("B: Set success to false.");}
916 success=false;
917 }
918 else if(dif>0){
919 mloc++;//Location of first X or Y on right side
920 final int numX=match.length-mloc;
921 int rloc=stop-dif+1, cloc=bases.length-dif;
922 int subs=0, firstSub=-1;
923 if(cloc<0){
924 if(verbose){System.err.println("C: Set success to false.");}
925 success=false;
926 }else{
927 // final int tip2=match.length-tip;
928 while(mloc<match.length){
929 byte m=match[mloc];
930 byte c=bases[cloc];
931 byte r=ca.get(rloc);
932 assert(m=='X' || m=='Y') : (char)m+", "+mloc+", "+(char)c+", "+(char)r+"\n"+new String(bases)+"\n"+this.toString();
933 if(r=='N' || c=='N'){match[mloc]='N';}
934 else if(c==r){match[mloc]='m';}
935 // else if(mloc>=tip2){match[mloc]='S';}
936 else{
937 match[mloc]='S';
938 subs++;
939 if(subs==1){firstSub=mloc;}
940 }
941 // else{
942 // if(verbose){System.err.println("D: Set success to false.");}
943 // success=false;
944 // break;
945 // }
946 mloc++;
947 rloc++;
948 cloc++;
949 }
950 }
951 if(success){
952 if(verbose){System.err.println("A: Start="+start+", stop="+stop+", numX="+numX+", lengthsAgree()="+lengthsAgree());}
953 if(mappedLength()!=matchLength()){incrementStop(numX);}
954 if(verbose){System.err.println("B: Start="+start+", stop="+stop+", numX="+numX+", lengthsAgree()="+lengthsAgree());}
955 if(subs>maxSubs && subs>numX*maxSubRate){
956 if(verbose){System.err.println("Failed to correct alignment; clipping right side of read.");}
957 for(int i=firstSub; i<match.length; i++){
958 match[i]='C';
959 }
960 int clipped=match.length-firstSub+1;
961 if(!lengthsAgree()){
962 assert(false);
963 incrementStop(-clipped);
964 assert(lengthsAgree());
965 }
966 if(verbose){System.err.println("C: Start="+start+", stop="+stop+", numX="+numX+", lengthsAgree()="+lengthsAgree());}
967 }
968 if(verbose){System.err.println("mappedLength()="+mappedLength()+", matchLength()="+matchLength()+", numX="+numX);}
969 }
970 }
971 if(verbose){System.err.println("Finished right side. Success="+success+", start="+start+", stop="+stop+", match=\n"+new String(match));}
972 if(verbose){System.err.println("lengthsAgree: "+this.lengthsAgree());}
973 }
974
975 success=success && !matchContainsXY()/* && mappedLength()==matchLength()*/;
976 if(!success){
977 if(verbose){System.err.println("E: Set success to false.");}
978 if(nullifyOnFailure){match=null;}
979 }else{
980 if(verbose){System.err.println("E: Success!");}
981 }
982
983 if(match!=null){
984 int oldScore=slowScore;
985 setSlowScore(msa.score(match));
986 setScore(score+(slowScore-oldScore));
987 }
988 if(verbose){System.err.println("lengthsAgree: "+this.lengthsAgree());}
989
990 setPerfect(bases); //Fixes a rare bug
991 return success;
992 }
993
994 public boolean lengthsAgree(){
995 return match==null ? true : matchLength()==mappedLength();
996 }
997
998 public int mappedLength(){
999 return stop-start+1;
1000 }
1001
1002 public int matchLength(){
1003 assert(match!=null);
1004 return Read.calcMatchLength(match);
1005 }
1006
1007 // public boolean plus(){return strand()==Gene.PLUS;}
1008 // public boolean minus(){return strand()==Gene.MINUS;}
1009 //
1010 // public final byte strand(){return (byte)(flags&strandMask);}
1011 // public boolean rescued(){return (flags&rescuedMask)!=0;}
1012 // public boolean perfect(){return (flags&perfectMask)!=0;}
1013 // public boolean semiperfect(){return (flags&semiperfectMask)!=0;}
1014 //
1015 // public final int setStrand(int x){
1016 // assert(x==0 || x==1);
1017 // if(x==0){flags=(flags&~strandMask);}
1018 // else{flags=(flags|strandMask);}
1019 // assert(strand()==x);
1020 // return x;
1021 // }
1022 // public boolean setRescued(boolean b){
1023 // if(b){flags=(flags|rescuedMask);}
1024 // else{flags=(flags&~rescuedMask);}
1025 // assert(rescued()==b);
1026 // return b;
1027 // }
1028 // public boolean setPerfect(boolean b){
1029 // if(b){flags=(flags|semiperfectMask);}
1030 // else{flags=(flags&~semiperfectMask);}
1031 // assert(perfect()==b);
1032 // return b;
1033 // }
1034 // public boolean setSemiperfect(boolean b){
1035 // if(b){flags=(flags|semiperfectMask);}
1036 // else{flags=(flags&~semiperfectMask);}
1037 // assert(semiperfect()==b);
1038 // return b;
1039 // }
1040
1041 public boolean plus(){return strand==Shared.PLUS;}
1042 public boolean minus(){return strand==Shared.MINUS;}
1043 public boolean perfect(){return perfect;}
1044 public boolean semiperfect(){return semiperfect;}
1045 public boolean rescued(){return rescued;}
1046 public byte strand(){return strand;}
1047
1048 public final byte strand;
1049 public boolean rescued=false;
1050 public boolean perfect=false;
1051 public boolean semiperfect=false;
1052
1053 public void setPerfect(){
1054 perfect=semiperfect=true;
1055 gaps=null;
1056 }
1057 public void incrementStart(int x){setStart(start+x);}
1058 public void incrementStop(int x){setStop(stop+x);}
1059 public void setLimits(int a, int b){
1060 start=a;
1061 stop=b;
1062 if(gaps!=null){
1063 gaps[0]=a;
1064 gaps[gaps.length-1]=b;
1065 if(!CHECKGAPS()){gaps=GapTools.fixGaps(this);}
1066 assert(CHECKGAPS()) : Arrays.toString(gaps);
1067 }
1068 }
1069
1070 //Seems to be no longer needed after a change to calculating Y symbols.
1071 @Deprecated
1072 public void fixLimitsXY(){
1073 // if(match==null || match.length<1){return;}
1074 // int x=0, y=0;
1075 // for(int i=0; i<match.length; i++){
1076 // if(match[i]=='X'){x++;}else{break;}
1077 // }
1078 // for(int i=match.length-1; i>=0; i--){
1079 // if(match[i]=='Y'){y++;}else{break;}
1080 // }
1081 //// if((x!=0 || y!=0) && !lengthsAgree()){
1082 //// setLimits(start-x, stop+y);
1083 //// }
1084 // if((y!=0)){
1085 //// setLimits(start, stop+y);
1086 // }
1087 }
1088
1089 public void setStart(int a){
1090 start=a;
1091 if(gaps!=null){
1092 gaps[0]=a;
1093 if(gaps[0]>gaps[1]){
1094 gaps=GapTools.fixGaps(this);
1095 }
1096 assert(CHECKGAPS()) : Arrays.toString(gaps);
1097 }
1098 }
1099 public void setStop(int b){
1100 stop=b;
1101 if(gaps!=null){
1102 gaps[gaps.length-1]=b;
1103 if(gaps.length-1>gaps.length-2){gaps=GapTools.fixGaps(this);}
1104 assert(CHECKGAPS()) : Arrays.toString(gaps);
1105 }
1106 }
1107 public boolean CHECKGAPS(){
1108 if(gaps==null){return true;}
1109 if(gaps.length==0 || ((gaps.length&1)==1)){return false;}
1110 for(int i=1; i<gaps.length; i++){
1111 if(gaps[i-1]>gaps[i]){return false;}
1112 }
1113 return gaps[0]==start && gaps[gaps.length-1]==stop;
1114 }
1115
1116 public int start(){return start;}
1117 public int stop(){return stop;}
1118 public void setSlowScore(int x){
1119 // assert(x!=-1);
1120 if(verbose){System.err.println("Before setSlowScore: x="+x+", quick="+quickScore+", slow="+slowScore+", paired="+pairedScore);}
1121 // assert(slowScore<=0 || pairedScore<=0 || pairedScore>=slowScore) : "x="+x+", quick="+quickScore+", slow="+slowScore+", paired="+pairedScore+"\n"+this; //Correct, but temporarily disabled for stability
1122 if(x<=0){
1123 pairedScore=slowScore=x;
1124 }else if(pairedScore<=0){
1125 slowScore=x;
1126 }else{
1127 assert(pairedScore>=slowScore) : this;
1128 if(pairedScore>0){
1129 if(slowScore>0){
1130 pairedScore=x+(pairedScore-slowScore);
1131 }else{
1132 pairedScore=x+1;
1133 }
1134 }
1135 }
1136 slowScore=x;
1137 if(verbose){System.err.println("After setSlowScore: "+this);}
1138 // assert(pairedScore<=0 || pairedScore>=slowScore) : "quick="+quickScore+", slow="+slowScore+", paired="+pairedScore+"\n"+this; //Correct, but temporarily disabled for stability
1139 }
1140 public void setPairedScore(int x){
1141 // assert(x==0 || slowScore<=0 || x>=slowScore) : "x="+x+", quick="+quickScore+", slow="+slowScore+", paired="+pairedScore+"\n"+this; //Correct, but temporarily disabled for stability
1142 pairedScore=x;
1143 // assert(slowScore<=0 || pairedScore<=0 || pairedScore>=slowScore) : "x="+x+", quick="+quickScore+", slow="+slowScore+", paired="+pairedScore+"\n"+this; //Correct, but temporarily disabled for stability
1144 }
1145 public void setSlowPairedScore(int x, int y){
1146 // assert(slowScore<=0 || pairedScore<=0 || pairedScore>=slowScore) : "x="+x+", quick="+quickScore+", slow="+slowScore+", paired="+pairedScore+"\n"+this; //Correct, but temporarily disabled for stability
1147 slowScore=x;
1148 pairedScore=y;
1149 // assert(pairedScore<=0 || pairedScore>=slowScore) : this; //Correct, but temporarily disabled for stability
1150 }
1151 public void setScore(int x){
1152 score=x;
1153 }
1154
1155 public int start;
1156 public int stop;
1157 public int quickScore;
1158 public int score;
1159 public int slowScore;
1160 public int pairedScore;
1161 public int hits;
1162 public final int chrom;
1163
1164 public long flags; //TODO Use this instead of fields
1165
1166 public int[] gaps; //Limits of large gaps
1167 public byte[] match;
1168
1169
1170 public static final PositionComparator PCOMP=new PositionComparator();
1171 public static final long strandMask=(1L<<0);
1172 public static final long rescuedMask=(1L<<1);
1173 public static final long perfectMask=(1L<<2);
1174 public static final long semiperfectMask=(1L<<3);
1175 public static boolean verbose=false;
1176
1177 }