Debian Codegraph @

current/align2/TranslateColorspaceRead.java

raw symbols SCIP
1 package align2;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collections;
6
7 import dna.AminoAcid;
8 import dna.ChromosomeArray;
9 import dna.Data;
10 import shared.KillSwitch;
11 import shared.Shared;
12 import shared.Tools;
13 import stream.Read;
14 import stream.SiteScore;
15 import var.Variation;
16 import var.Varlet;
17
18 public final class TranslateColorspaceRead {
19
20 public TranslateColorspaceRead(MSA msa){
21 msaBS=msa;
22 }
23
24 private static CharSequence toString(byte[][] crbmq) {
25 StringBuilder sb=new StringBuilder();
26 for(int i=0; i<2; i++){
27 if(crbmq[i]==null){sb.append("null");}
28 else{
29 for(byte b : crbmq[i]){
30 if(b=='N'){sb.append('N');}
31 else{sb.append((char)(b+'0'));}
32 }
33 sb.append('\n');
34 }
35 }
36 sb.append(new String(crbmq[2]));
37 sb.append('\n');
38 sb.append(crbmq[3]==null ? "null" : new String(crbmq[3]));
39 sb.append('\n');
40 return sb;
41 }
42
43 private static String toStringCS(byte[] colors){
44 StringBuilder sb=new StringBuilder(colors.length);
45 for(byte b : colors){
46 if(b>3){sb.append((char)b);}
47 else{sb.append((char)(b+'0'));}
48 }
49 sb.append('\n');
50 return sb.toString();
51 }
52
53 public void realignByReversingRef(final Read r, final int padding, final boolean recur){
54 realignByReversingRef(r, msaBS, padding, recur);
55 }
56
57 /** This aligns a read with the reference, and generates the match string. */
58 public static void realignByReversingRef(final Read r, final MSA msa, int padding, final boolean recur){
59 if(r.shortmatch()){
60 r.match=null;
61 r.setShortMatch(false);
62 }
63 // assert(r.colorspace());
64 // assert(msa.colorspace);
65 padding=Tools.min(padding, (msa.maxColumns-r.length())/2-20);
66 padding=Tools.max(padding, 0);
67 final ChromosomeArray chacs=Data.getChromosome(r.chrom);
68 if(verbose){
69 System.err.println("Realigning.");
70 System.err.println("Original: "+r.start+", "+r.stop+", "+Shared.strandCodes[r.strand()]);
71 }
72
73 {
74 assert(r.stop>=r.start); //Otherwise this is pointless...
75 int a=r.length();
76 int b=r.stop-r.start+1;
77 if(b<a){
78 int c=Tools.min(r.length(), a-b+10)/2;
79 padding=Tools.max(padding, c+1);
80 }
81 }
82 padding=Tools.min(padding, r.length()+10);
83 padding=Tools.min(padding, (msa.maxColumns-Tools.max(r.length(), GapTools.calcGrefLen(r.start, r.stop, r.gaps)))/2-1);
84
85 // if(padding==4){System.err.print(".");}
86 // else{
87 // System.err.println("\npadding="+padding+", \trecur="+recur);
88 // if(padding>10){
89 // if(r.match!=null){System.err.print(new String(r.match));}
90 // if(padding>20){System.err.print("\t"+r.start+", "+r.stop+", "+(r.stop-r.start+1));}
91 // System.err.println();
92 // }
93 // }
94
95 final int maxQ=msa.maxQuality(r.length());
96 final int maxI=msa.maxImperfectScore(r.length());
97
98 if(r.strand()==Shared.PLUS){
99 assert(maxQ>maxI);
100
101 byte[][] matchR=new byte[1][];
102 if(r.match!=null && r.match.length==r.length()){
103 matchR[0]=r.match;
104 }else{
105 // System.err.println(new String(r.match));
106 matchR[0]=r.match=new byte[r.length()];
107 }
108 int scoreNoIndel=msa.scoreNoIndelsAndMakeMatchString(r.bases, chacs.array, r.start, matchR);
109 r.match=matchR[0];
110
111 if(scoreNoIndel>=maxI){
112 if(verbose){System.err.println("Quick match.");}
113 // assert(r.match[0]!='X') : r.toText(false);
114 // assert(r.match[r.match.length-1]!='X') : r.toText(false);
115 // assert(r.stop==r.start+r.length()-1);
116 r.stop=r.start+r.length()-1;
117 r.mapScore=scoreNoIndel;
118 }else{
119 if(verbose){System.err.println("Slow match.");}
120
121 // int minLoc=Tools.max(r.start-padding, chacs.minIndex);
122 int minLoc=Tools.max(r.start-padding, 0); //It's OK to be off the beginning as long as bases prior to the true start are 'N'
123 int maxLoc=Tools.min(r.stop+padding, chacs.maxIndex);
124
125 //These assertions are not too important... they indicate the read mapped off the end of the chromosome.
126 assert(minLoc<=r.start) : "\nchr"+r.chrom+": "+minLoc+", "+maxLoc+", "+r.start+", "+r.stop+
127 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+r.toText(false);
128 assert(maxLoc>=r.stop) : "\nchr"+r.chrom+": "+minLoc+", "+maxLoc+", "+r.start+", "+r.stop+
129 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+r.toText(false);
130
131 // System.err.println("Aligning:\n"+new String(r.bases)+"\n"+chacs.getString(minLoc, maxLoc));
132 int[] max=msa.fillLimited(r.bases, chacs.array, minLoc, maxLoc, scoreNoIndel, r.gaps);
133 // System.err.println(Arrays.toString(max));
134 r.match=msa.traceback(r.bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], r.gaps!=null);
135 // System.err.println(new String(r.match));
136 int[] score=msa.score(r.bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], r.gaps!=null);
137 // System.err.println(Arrays.toString(score));
138 r.start=score[1];
139 r.stop=score[2];
140 r.mapScore=score[0];
141 // System.err.println(Arrays.toString(score));
142 // assert(false);
143 }
144 }else{
145 assert(maxQ>maxI);
146
147 byte[][] matchR=new byte[1][];
148 if(r.match!=null && r.match.length==r.length()){
149 matchR[0]=r.match;
150 }else{
151 // System.err.println(new String(r.match));
152 matchR[0]=r.match=new byte[r.length()];
153 }
154
155 int scoreNoIndel=-9999;
156 if(r.length()==(r.stop-r.start+1)){
157
158 byte[] ref=chacs.getBytes(r.start, r.stop);
159 AminoAcid.reverseComplementBasesInPlace(ref);
160 scoreNoIndel=msa.scoreNoIndelsAndMakeMatchString(r.bases, ref, 0, matchR);
161 r.match=matchR[0];
162 }
163
164 if(scoreNoIndel>=maxI){
165 if(verbose){System.err.println("Quick match.");}
166 assert(r.match[0]!='X') : r.toText(false);
167 assert(r.match[r.match.length-1]!='X') : r.toText(false);
168 r.stop=r.start+r.length()-1;
169 r.mapScore=scoreNoIndel;
170 }else{
171 if(verbose){System.err.println("Slow match.");}
172
173 // int minLoc=Tools.max(r.start-padding, chacs.minIndex);
174 int minLoc=Tools.max(r.start-padding, 0); //It's OK to be off the beginning as long as bases prior to the true start are 'N'
175 int maxLoc=Tools.min(r.stop+padding, chacs.maxIndex);
176
177 //These assertions are not too important... they indicate the read mapped off the end of the chromosome.
178 assert(minLoc<=r.start) : "\nchr"+r.chrom+": "+minLoc+", "+maxLoc+", "+r.start+", "+r.stop+
179 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+r.toText(false);
180 assert(maxLoc>=r.stop) : "\nchr"+r.chrom+": "+minLoc+", "+maxLoc+", "+r.start+", "+r.stop+
181 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+r.toText(false);
182
183 byte[] ref=chacs.getBytes(minLoc, maxLoc);
184 // System.err.println("Aligning:\n"+new String(r.bases)+"\n"+new String(ref));
185 AminoAcid.reverseComplementBasesInPlace(ref);
186
187 // System.err.println("Aligning:\n"+new String(r.bases)+"\n"+new String(ref));
188 int[] max=msa.fillLimited(r.bases, ref, 0, ref.length-1, scoreNoIndel, r.gaps);
189 // System.err.println(Arrays.toString(max));
190 r.match=msa.traceback(r.bases, ref, 0, ref.length-1, max[0], max[1], max[2], r.gaps!=null);
191 // System.err.println(new String(r.match));
192 int[] score=msa.score(r.bases, ref, 0, ref.length-1, max[0], max[1], max[2], r.gaps!=null);
193 // System.err.println(Arrays.toString(score));
194 // System.err.println(Arrays.toString(score));
195 // assert(false);
196
197 int start2=minLoc+(ref.length-score[2]-1);
198 int stop2=maxLoc-(score[1]);
199
200 r.start=start2;
201 r.stop=stop2;
202 r.mapScore=score[0];
203 }
204 }
205 if(verbose){System.err.println("Final: "+r.start+", "+r.stop+", "+Shared.strandCodes[r.strand()]);}
206
207 if(recur && r.stop<chacs.maxIndex && r.start>0 && (r.match[0]=='X' || r.match[0]=='I' ||
208 r.match[r.match.length-1]=='Y' || r.match[r.match.length-1]=='X' || r.match[r.match.length-1]=='I')){
209 int xy=0;
210 for(int i=0; i<r.match.length; i++){
211 byte b=r.match[i];
212 if(b=='X' || b=='Y' || b=='I'){xy++;}
213 }
214 // System.err.println("xy = "+xy);
215 realignByReversingRef(r, msa, Tools.min(10+padding+2*xy, msa.maxColumns/2-r.length()-20), false);
216 }
217 // assert(r.mapScore>0) : padding+", "+recur+", "+r.mapScore+", "+r.strand()+", "+r.colorspace()+"\n"+r.toText(false);
218 // assert(r.match[0]!='X') : r.toText(false);
219 // assert(r.match[r.match.length-1]!='X') : r.toText(false);
220 }
221
222 public void realign_new(Read r, int padding, boolean recur, int minScore, boolean forbidIndels){
223 SiteScore ss=r.toSite();
224 TranslateColorspaceRead.realign_new(ss, r.bases, msaBS, padding, recur ? 1 : 0, minScore, forbidIndels, true, r.numericID);
225 r.setFromSite(ss);
226 }
227
228 /** For some reason realign was making the match string backwards... */
229 public static void realign_new(final SiteScore ss, final byte[] bases, final MSA msa, int padding, final int recur, int minValidScore,
230 boolean forbidIndels, boolean fixXY, final long id){
231 if(verbose){System.err.println("Calling realign_new on ss "+ss);}
232 if(ss.matchContainsXY()){ss.fixXY(bases, false, msa);} //This must run regardless of 'fixXY' or else an XY read could be semiperfect but not marked as such
233 ss.clipTipIndels(bases, 4, 10, msa);
234 if(verbose){System.err.println("After fixXY and clipTipIndels: "+ss);}
235 assert(Read.CHECKSITE(ss, bases, id));
236 // final byte[] bases=ss.plus() ? basesP : basesM;
237
238 if(verbose){System.err.println("Padding = "+padding+"; msa.maxColumns = "+msa.maxColumns+"; maplen = "+(ss.stop()-ss.start()+1)+"; gaps = "+Arrays.toString(ss.gaps));}
239
240 assert(padding>=0) : padding+", id="+id+", "+ss;
241 padding=Tools.min(padding, (msa.maxColumns-bases.length)/2-20);
242 if(verbose){System.err.println("Padding = "+padding);}
243 assert(padding>=0) : padding+", id="+id+", "+ss;
244 padding=Tools.max(padding, 0);
245 if(verbose){System.err.println("Padding = "+padding);}
246 assert(padding>=0) : padding+", id="+id+", "+ss;
247
248
249 final ChromosomeArray chacs=Data.getChromosome(ss.chrom);
250 if(verbose){
251 System.err.println("Realigning.");
252 System.err.println("Original: "+ss.start()+", "+ss.stop()+", "+Shared.strandCodes[ss.strand()]);
253 if(verbose){System.err.println("F. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
254 }
255 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
256
257
258 {
259 int expectedLen=GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps);
260 if(expectedLen>msa.maxColumns-20){
261 //TODO: Alternately, I could kill the site.
262 ss.setStop(ss.start()+Tools.min(bases.length+40, msa.maxColumns-20));
263 if(ss.gaps!=null){ss.gaps=GapTools.fixGaps(ss.start(), ss.stop(), ss.gaps, Shared.MINGAP);} //Still needed?
264 }
265 if(verbose){System.err.println("F. Estimated greflen2: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
266 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
267 }
268
269 if(ss.start()<0){ss.setStart(0);} //Prevents assertion errors. This change should be reset by the realignment so it shouldn't mattess.
270 if(ss.stop()>chacs.maxIndex){ss.setStop(chacs.maxIndex);} //Also to prevent a potential assertion error in unpadded references
271 assert(0<=ss.start()) : "\nchr"+ss.chrom+": ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
272 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
273 assert(chacs.maxIndex>=ss.stop()) : "\nchr"+ss.chrom+": ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
274 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
275 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
276
277 {
278 assert(ss.stop()>=ss.start()); //Otherwise this is pointless...
279 int a=bases.length;
280 int b=ss.stop()-ss.start()+1;
281 if(b<a){
282 int c=Tools.min(bases.length, a-b+10)/2;
283 padding=Tools.max(padding, c+1);
284 // if(verbose){System.err.println("Padding = "+padding);}
285 // assert(padding>=0) : padding;
286 }
287 }
288 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
289
290 if(verbose){System.err.println("Padding = "+padding);}
291
292 {
293 int oldPadding=padding;
294 padding=Tools.max(0, Tools.min(padding, (msa.maxColumns-Tools.max(bases.length, GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps)))/2-100));
295 if(forbidIndels){padding=0;}
296 if(verbose){
297 System.err.println("oldPadding="+oldPadding+", padding="+padding);
298 System.err.println("L. calcGrefLen1 = "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));
299 System.err.println("L. calcGrefLen2 = "+GapTools.calcGrefLen(ss.start()-oldPadding, ss.stop()+oldPadding, ss.gaps));
300 System.err.println("L. calcGrefLen3 = "+GapTools.calcGrefLen(ss.start()-padding, ss.stop()+padding, ss.gaps));
301 }
302
303
304 assert(padding>=0) : id+", "+padding;
305
306 // assert(GapTools.calcGrefLen(ss.start()-padding, ss.stop()+padding, ss.gaps)<msa.maxColumns) :
307 // oldPadding+", "+padding+", "+bases.length+", "+GapTools.calcGrefLen(ss.start()-padding, ss.stop()+padding, ss.gaps)+", "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps);
308 }
309 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
310
311 final int maxQ=msa.maxQuality(bases.length);
312 final int maxI=msa.maxImperfectScore(bases.length);
313
314 if(ss.strand()==Shared.PLUS){
315 assert(maxQ>maxI);
316
317 byte[][] matchR=new byte[1][];
318 if(ss.match!=null && ss.match.length==bases.length){
319 matchR[0]=ss.match;
320 }else{
321 // System.err.println(new String(ss.match));
322 matchR[0]=ss.match=new byte[bases.length];
323 }
324 int scoreNoIndel=msa.scoreNoIndelsAndMakeMatchString(bases, chacs.array, ss.start(), matchR);
325 ss.match=matchR[0];
326
327 assert(0<=ss.start()) : "\nchr"+ss.chrom+": ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
328 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
329 assert(chacs.maxIndex>=ss.stop()) : "\nchr"+ss.chrom+": ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
330 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
331
332 if(verbose){System.err.println("G. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
333 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
334
335 if(scoreNoIndel>=maxI || forbidIndels){
336 if(verbose){System.err.println("Quick match.");}
337 // assert(ss.match[0]!='X') : ss.toText();
338 // assert(ss.match[ss.match.length-1]!='X') : ss.toText();
339 // assert(ss.setStop()=ss.start()+bases.length-1);
340 ss.setStop(ss.start()+bases.length-1);
341 ss.setSlowScore(scoreNoIndel);
342 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
343 }else{
344 if(verbose){System.err.println("Slow match.");}
345
346 // int minLoc=Tools.max(ss.start()-padding, chacs.minIndex);
347 int minLoc=Tools.max(ss.start()-padding, 0); //It's OK to be off the beginning as long as bases prior to the true start are 'N'
348 int maxLoc=Tools.min(ss.stop()+padding, chacs.maxIndex);
349
350 if(verbose){System.err.println("minLoc = "+minLoc+", maxLoc = "+maxLoc);}
351 if(verbose){System.err.println("H. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
352 if(verbose){System.err.println("H. Estimated greflen2: "+GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));}
353
354 //These assertions are not too important... they indicate the read mapped off the end of the chromosome.
355 assert(minLoc<=ss.start()) : "\nchr"+ss.chrom+": minloc="+minLoc+", maxLoc="+maxLoc+", ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
356 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
357 assert(maxLoc>=ss.stop()) : "\nchr"+ss.chrom+": minloc="+minLoc+", maxLoc="+maxLoc+", ss.setStart()"+ss.start()+", ss.setStop()"+ss.stop()+", padding="+padding+
358 ", chacs.minIndex="+chacs.minIndex+", chacs.maxIndex="+chacs.maxIndex+"\nread:\n"+ss.toText();
359
360 // System.err.println("Aligning:\n"+new String(bases)+"\n"+chacs.getString(minLoc, maxLoc));
361
362 int[] max=null;
363 int[] score=null;
364 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
365 try {
366 if(verbose){
367 System.err.println("Calling fillLimited(bases, chacs, "+minLoc+", "+maxLoc+", "+
368 Tools.max(scoreNoIndel, minValidScore)+", "+(ss.gaps==null ? "null" : Arrays.toString(ss.gaps))+")");
369 }
370 max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
371 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
372 if(verbose){System.err.println("I. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
373
374 if(score!=null && score.length>6){
375 int[] oldArray=score.clone();
376 assert(score.length==8);
377 int extraPadLeft=score[6];
378 int extraPadRight=score[7];
379
380 if(ss.gaps==null){
381 assert(maxLoc-minLoc+1<=msa.maxColumns);
382 int newlen=(maxLoc-minLoc+1+extraPadLeft+extraPadRight);
383 if(newlen>=msa.maxColumns-80){
384 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
385 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
386 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
387 }else{
388 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
389 extraPadLeft=Tools.max(x, extraPadLeft);
390 extraPadRight=Tools.max(x, extraPadRight);
391 }
392 }else{
393 //TODO: In this case the alignment will probably be wrong.
394 int greflen=Tools.max(bases.length, GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));
395 int newlen=(greflen+1+extraPadLeft+extraPadRight);
396 if(newlen>=msa.maxColumns-80){
397 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
398 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
399 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
400 }else{
401 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
402 extraPadLeft=Tools.max(x, extraPadLeft);
403 extraPadRight=Tools.max(x, extraPadRight);
404 }
405 }
406
407 assert(extraPadLeft>=0 && extraPadRight>=0) : extraPadLeft+", "+extraPadRight+"\n"+id+", "+ss+", "+new String(bases);
408 minLoc=Tools.max(0, minLoc-extraPadLeft);
409 maxLoc=Tools.min(chacs.maxIndex, maxLoc+extraPadRight);
410
411 if(verbose){System.err.println("J. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
412 if(verbose){System.err.println("J. Estimated greflen2: "+GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));}
413 max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
414 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
415
416 if(score==null || score[0]<oldArray[0]){
417 if(!Shared.anomaly){System.err.println("Read "+id+": Padded match string alignment result was inferior. Triple-aligning. :(");}
418
419 if(ss.gaps==null){
420 assert(maxLoc-minLoc+1<=msa.maxColumns);
421 int newlen=(maxLoc-minLoc+1+extraPadLeft+extraPadRight);
422 if(newlen>=msa.maxColumns-80){
423 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
424 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
425 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
426 }else{
427 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
428 extraPadLeft=Tools.max(x, extraPadLeft);
429 extraPadRight=Tools.max(x, extraPadRight);
430 }
431 }else{
432 //TODO: In this case the alignment will probably be wrong.
433 int greflen=Tools.max(bases.length, GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));
434 int newlen=(greflen+1+extraPadLeft+extraPadRight);
435 if(newlen>=msa.maxColumns-80){
436 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
437 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
438 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
439 }else{
440 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
441 extraPadLeft=Tools.max(x, extraPadLeft);
442 extraPadRight=Tools.max(x, extraPadRight);
443 }
444 }
445
446 assert(extraPadLeft>=0 && extraPadRight>=0) : extraPadLeft+", "+extraPadRight+"\n"+id+", "+ss+", "+new String(bases);
447 minLoc=Tools.max(0, minLoc-extraPadLeft);
448 maxLoc=Tools.min(chacs.maxIndex, maxLoc+extraPadRight);
449
450 max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
451 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
452
453 if(minLoc>0 && maxLoc<chacs.maxIndex && (score==null || score[0]<oldArray[0])){
454 if(!Shared.anomaly){System.err.println("Still inferior.");}
455 minLoc=Tools.max(ss.start()-8, 0); //It's OK to be off the beginning as long as bases prior to the true start are 'N'
456 maxLoc=Tools.min(ss.stop()+8, chacs.maxIndex);
457 max=msa.fillUnlimited(bases, chacs.array, minLoc, maxLoc, ss.gaps);
458 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
459 }
460 }
461 }
462 } catch (Exception e) {
463 System.err.println("Caught exception:\n");
464 e.printStackTrace();
465 assert(false) : ss.toText();
466 }
467 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
468
469 if(max!=null){
470 ss.match=msa.traceback(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null);
471 ss.setLimits(score[1], score[2]);
472 if(verbose){System.err.println(ss.lengthsAgree()+", "+ss.start+", "+ss.stop);}
473 ss.fixLimitsXY();
474 if(verbose){System.err.println(ss.lengthsAgree()+", "+ss.start+", "+ss.stop);}
475 ss.setSlowScore(score[0]);
476 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
477 }else{
478 ss.setStop(ss.start()+bases.length-1);
479 ss.setSlowScore(scoreNoIndel);
480 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
481 }
482 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
483 }
484 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
485 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
486 }else{
487 assert(maxQ>maxI);
488
489 byte[][] matchR=new byte[1][];
490 if(ss.match!=null && ss.match.length==bases.length){
491 matchR[0]=ss.match;
492 }else{
493 matchR[0]=ss.match=new byte[bases.length];
494 }
495
496 int scoreNoIndel=msa.scoreNoIndelsAndMakeMatchString(bases, chacs.array, ss.start(), matchR);
497 ss.match=matchR[0];
498
499 if(scoreNoIndel>=maxI || forbidIndels){
500 if(verbose){System.err.println("Quick match.");}
501 assert(ss.match[0]!='X') : ss.toText();
502 assert(ss.match[ss.match.length-1]!='X') : ss.toText();
503 ss.setStop(ss.start()+bases.length-1);
504 ss.setSlowScore(scoreNoIndel);
505 assert(ss.lengthsAgree());
506 }else{
507 if(verbose){System.err.println("Slow match.");}
508
509 int minLoc=Tools.max(ss.start()-padding, 0); //It's OK to be off the beginning as long as bases prior to the true start are 'N'
510 int maxLoc=Tools.min(ss.stop()+padding, chacs.maxIndex);
511 if(verbose){System.err.println("Slow match "+minLoc+" ~ "+maxLoc);}
512 if(verbose){System.err.println("K. Estimated greflen: "+GapTools.calcGrefLen(ss.start(), ss.stop(), ss.gaps));}
513 if(verbose){System.err.println("K. Estimated greflen2: "+GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));}
514
515 //These assertions are not too important... they indicate the read mapped off the end of the chromosome.
516 assert(minLoc<=ss.start()) : "\nchr"+ss.chrom+": "+minLoc+", "+maxLoc+", "+ss.start()+", "+ss.stop()+
517 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+ss.toText();
518 assert(maxLoc>=ss.stop()) : "\nchr"+ss.chrom+": "+minLoc+", "+maxLoc+", "+ss.start()+", "+ss.stop()+
519 ", "+chacs.minIndex+", "+chacs.maxIndex+"\n"+ss.toText();
520
521 if(verbose){System.err.println("Aligning:\n"+new String(bases)+"\n"+chacs.getString(minLoc, maxLoc));}
522 int[] max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
523 if(verbose){System.err.println("Aligned3: {rows, maxC, maxS, max} = "+Arrays.toString(max));}
524 int[] score=null;
525 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
526
527 if(score!=null && score.length>6){
528 if(verbose){System.err.println("Entering condition because score="+Arrays.toString(score));}
529 int[] oldArray=score.clone();
530 assert(score.length==8);
531 int extraPadLeft=score[6];
532 int extraPadRight=score[7];
533
534 if(ss.gaps==null){
535 assert(maxLoc-minLoc+1<=msa.maxColumns);
536 int newlen=(maxLoc-minLoc+1+extraPadLeft+extraPadRight);
537 if(newlen>=msa.maxColumns-80){
538 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
539 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
540 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
541 }
542 }else{
543 //TODO: In this case the alignment will probably be wrong.
544 int greflen=Tools.max(bases.length, GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));
545 int newlen=(greflen+1+extraPadLeft+extraPadRight);
546 if(newlen>=msa.maxColumns-80){
547 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
548 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
549 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
550 }else{
551 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
552 extraPadLeft=Tools.max(x, extraPadLeft);
553 extraPadRight=Tools.max(x, extraPadRight);
554 }
555 }
556
557 minLoc=Tools.max(0, minLoc-extraPadLeft);
558 maxLoc=Tools.min(chacs.maxIndex, maxLoc+extraPadRight);
559 if(verbose){System.err.println("Set extraPadLeft="+extraPadLeft+", extraPadRight="+extraPadRight);}
560 if(verbose){System.err.println("Set minLoc="+minLoc+", maxLoc="+maxLoc);}
561
562 max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
563 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
564
565 if(score==null || score[0]<oldArray[0]){
566 if(!Shared.anomaly){System.err.println("Read "+id+": Padded match string alignment result was inferior. Triple-aligning. :(");}
567
568 if(ss.gaps==null){
569 assert(maxLoc-minLoc+1<=msa.maxColumns);
570 int newlen=(maxLoc-minLoc+1+extraPadLeft+extraPadRight);
571 if(newlen>=msa.maxColumns-80){
572 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
573 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
574 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
575 }else{
576 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
577 extraPadLeft=Tools.max(x, extraPadLeft);
578 extraPadRight=Tools.max(x, extraPadRight);
579 }
580 }else{
581 //TODO: In this case the alignment will probably be wrong.
582 int greflen=Tools.max(bases.length, GapTools.calcGrefLen(minLoc, maxLoc, ss.gaps));
583 int newlen=(greflen+1+extraPadLeft+extraPadRight);
584 if(newlen>=msa.maxColumns-80){
585 while(newlen>=msa.maxColumns-80 && extraPadLeft>extraPadRight){newlen--;extraPadLeft--;}
586 while(newlen>=msa.maxColumns-80 && extraPadLeft<extraPadRight){newlen--;extraPadRight--;}
587 while(newlen>=msa.maxColumns-80){newlen-=2;extraPadLeft--;extraPadRight--;}
588 }else{
589 int x=Tools.max(0, Tools.min(20, ((msa.maxColumns-newlen)/2)-40));
590 extraPadLeft=Tools.max(x, extraPadLeft);
591 extraPadRight=Tools.max(x, extraPadRight);
592 }
593 }
594
595 minLoc=Tools.max(0, minLoc-extraPadLeft);
596 maxLoc=Tools.min(chacs.maxIndex, maxLoc+extraPadRight);
597 max=msa.fillLimited(bases, chacs.array, minLoc, maxLoc, Tools.max(scoreNoIndel, minValidScore), ss.gaps);
598 score=(max==null ? null : msa.score(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null));
599 }
600 }
601
602
603 if(verbose){System.err.println(Arrays.toString(max));}
604 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases)+"\n"+ss;
605
606 if(max!=null){
607 ss.match=msa.traceback(bases, chacs.array, minLoc, maxLoc, max[0], max[1], max[2], ss.gaps!=null);
608 ss.setLimits(score[1], score[2]);
609 ss.fixLimitsXY();
610 ss.setSlowScore(score[0]);
611 if(verbose){System.err.println("Aligned4:\n"+new String(bases)+"\n"+chacs.getString(ss.start(), ss.stop())+"\n"+new String(ss.match));}
612 assert(ss.lengthsAgree()) : id+"\n"+new String(bases)+"\n"+ss;
613 }else{
614 assert(ss.match[0]!='X') : id+"\n"+new String(bases)+"\n"+ss;
615 assert(ss.match[ss.match.length-1]!='X' && ss.match[ss.match.length-1]!='Y') : id+"\n"+new String(bases)+"\n"+ss;
616 ss.setStop(ss.start()+bases.length-1);
617 ss.setSlowScore(scoreNoIndel);
618 assert(ss.lengthsAgree()) : id+"\n"+new String(bases)+"\n"+ss;
619 }
620 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases)+"\n"+ss;
621 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
622 }
623 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
624 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
625 }
626 if(verbose){System.err.println("Final: "+ss.start()+", "+ss.stop()+", "+Shared.strandCodes[ss.strand()]+", recur="+recur);}
627 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
628
629 final int leftPaddingNeeded=ss.leftPaddingNeeded(4, 5), rightPaddingNeeded=ss.rightPaddingNeeded(4, 5);
630 if(ss.stop()<chacs.maxIndex && ss.start()>0 && (leftPaddingNeeded>0 || rightPaddingNeeded>0)){
631 assert(ss.lengthsAgree()) : ss.matchLength()+", "+ss.mappedLength()+"\n\nss: "+ss+"\nbases: "+new String(bases);
632 if(recur>0){
633 ss.gaps=GapTools.fixGaps(ss.start(), ss.stop(), ss.gaps, Shared.MINGAP);
634
635 int p_temp=Tools.min(10+Tools.max(leftPaddingNeeded, rightPaddingNeeded), (msa.maxColumns-bases.length)/2-20);
636
637 if(verbose){System.err.println("re-calling realign_new.");}
638 realign_new(ss, bases, msa, p_temp, recur-1, minValidScore, forbidIndels, fixXY, id);
639 assert(ss.lengthsAgree());
640 }else{
641 if(verbose){System.err.println("Not recurring. fixXY="+fixXY);}
642 // int len1=Read.calcMatchLength(ss.match);
643 // int len2=ss.stop()-ss.start()+1;
644 if(fixXY && ss.matchContainsXY()){
645 ss.fixXY(bases, false, msa);
646 assert(ss.lengthsAgree());
647 }
648 assert(ss.gaps==null || (ss.gaps[0]==ss.start() && ss.gaps[ss.gaps.length-1]==ss.stop())) : id+"\n"+new String(bases); //123
649 }
650 }
651 ss.setPerfect(bases);
652 assert(Read.CHECKSITE(ss, bases, id));
653 }
654
655 private static final boolean checkArray(byte[] bases){
656 for(byte b : bases){
657 // assert(b>0) : Arrays.toString(bases);
658 if(b<=0){return false;}
659 }
660 return true;
661 }
662
663
664 public static byte[] translateQuality(byte[] qcs){
665 byte[] qbs=new byte[qcs.length+1];
666 qbs[0]=qcs[0];
667 qbs[qbs.length-1]=qcs[qcs.length-1];
668 for(int i=1; i<qcs.length; i++){
669 int x=Tools.min(qcs[i-1], qcs[i]);
670 int y=Tools.max(qcs[i-1], qcs[i]);
671 qbs[i]=(byte) ((3*x+y)/4);
672 }
673 return qbs;
674 }
675
676 private static int fixIndels(byte[][] crbmq, Read r){
677
678 byte[] colors=crbmq[0];
679 byte[] colorRef=crbmq[1];
680 byte[] baseRef=crbmq[2];
681 byte[] match=crbmq[3];
682 byte[] quality=crbmq[4];
683
684 for(int i=0; i<match.length; i++){
685 if(match[i]=='X' || match[i]=='Y'){
686 // assert(false) : "\n"+new String(colors)+"\n"+new String(colorRef)+"\n"+new String(baseRef)+"\n"+new String(match)+"\n";
687
688 assert(false) : "TODO: Truncate ends.\n"+toString(crbmq)+"\n";
689
690 match[i]='I';
691 // match[i]='S';
692 }
693 }
694
695 int fixed=0;
696
697 for(int loc=0, refloc=0, mloc=0; mloc<match.length; mloc++){
698 byte b=match[mloc];
699 boolean ok=true;
700 if(b=='S' || b== 'm' || b=='N'){
701 loc++;
702 refloc++;
703 }else if(b=='D'){
704 fixed++;
705 ok=fixDeletion(crbmq, mloc, r);
706 match=crbmq[3];
707 assert(ok);
708 }
709 // else if(b=='I' || b=='X' || b=='Y'){
710 // ok=fixInsertion(crbmq, mloc);
711 // assert(ok);
712 // }
713 else if(b=='I'){
714 fixed++;
715 ok=fixInsertion(crbmq, mloc);
716 match=crbmq[3];
717 // assert(ok);
718 }else{
719 assert(false) : ""+((char)b);
720 }
721 if(!ok){
722 return -1;
723 }
724 }
725
726 colors=crbmq[0];
727 colorRef=crbmq[1];
728 baseRef=crbmq[2];
729 match=crbmq[3];
730
731 assert(baseRef.length==colorRef.length+1);
732 if(colorRef.length>colors.length){
733 colorRef=Arrays.copyOf(colorRef, colors.length);
734 baseRef=Arrays.copyOf(baseRef, colorRef.length+1);
735 crbmq[1]=colorRef;
736 crbmq[2]=baseRef;
737 }
738
739 return fixed;
740 }
741
742 private static boolean fixDeletion(final byte[][] crbmq, int loc, Read r){
743
744 byte[] colors=crbmq[0];
745 byte[] colorRef=crbmq[1];
746 byte[] baseRef=crbmq[2];
747 byte[] match=crbmq[3];
748 byte[] quality=crbmq[4];
749
750 assert(match[loc]=='D') : loc;
751
752 int len=1;
753 for(int i=loc+1; i<match.length; i++){
754 byte b=match[i];
755 if(b=='D'){
756 len++;
757 }else{
758 break;
759 }
760 }
761 int b=loc+len-1;
762
763 //TODO
764 if(loc<=1 || b>match.length-2){return false;} //Indels on very ends need to be processed differently
765
766 //Deletion is from a to b, inclusive. Note that basespace coords are +1 from colorspace coords.
767
768 byte[] colorRef2=new byte[colorRef.length-len];
769 byte[] baseRef2=new byte[baseRef.length-len];
770 byte[] match2=new byte[match.length-len];
771
772 assert(loc<colorRef2.length) : "TODO: Seems odd... "+loc+", "+colorRef2.length+", "+match;
773 assert(baseRef2.length==colorRef2.length+1);
774
775 for(int i=0; i<=loc; i++){
776 colorRef2[i]=colorRef[i];
777 baseRef2[i]=baseRef[i];
778 match2[i]=match[i];
779 }
780
781 for(int i=loc+1; i<baseRef2.length; i++){
782 baseRef2[i]=baseRef[i+len];
783 }
784 for(int i=loc+1; i<colorRef2.length; i++){
785 colorRef2[i]=colorRef[i+len];
786 }
787 for(int i=loc+1; i<match2.length; i++){
788 match2[i]=match[i+len];
789 }
790
791
792 colorRef2[loc]=AminoAcid.baseToColor(baseRef2[loc], baseRef2[loc+1]);
793 if(colorRef2[loc]==colors[loc]){
794 match2[loc]='m';
795 }else{
796 assert(colorRef2[loc]!='N' && colors[loc]!='N') : "TODO\n"+r.toText(false)+"\n"+toString(crbmq)+"\n";
797 match2[loc]='S';
798 }
799
800 crbmq[1]=colorRef2;
801 crbmq[2]=baseRef2;
802 crbmq[3]=match2;
803 crbmq[4]=quality;
804
805 return true;
806 }
807
808 private static boolean fixInsertion(final byte[][] crbmq, int loc){
809
810 byte[] colors=crbmq[0];
811 byte[] colorRef=crbmq[1];
812 byte[] baseRef=crbmq[2];
813 byte[] match=crbmq[3];
814 byte[] quality=crbmq[4];
815
816 assert(match[loc]=='I');
817
818 int len=1;
819 for(int i=loc+1; i<match.length; i++){
820 byte b=match[i];
821 if(b=='I'){
822 len++;
823 }else{
824 break;
825 }
826 }
827 int b=loc+len-1;
828
829 byte[] colorRef2=new byte[colorRef.length+len];
830 byte[] baseRef2=new byte[baseRef.length+len];
831 byte[] match2=new byte[match.length]; //TODO: Unnecessary duplication\
832
833 //TODO
834 // if(b>match.length-2){return false;} //Indels on very ends need to be processed differently
835
836
837 //Deletion is from a to b, inclusive. Note that basespace coords are +1 from colorspace coords
838
839 assert(loc<colorRef2.length) : "TODO: Seems odd... "+loc+", "+colorRef2.length+", "+match;
840 assert(baseRef2.length==colorRef2.length+1);
841
842 //Fill first half
843 for(int i=0; i<loc; i++){
844 colorRef2[i]=colorRef[i];
845 baseRef2[i]=baseRef[i];
846 match2[i]=match[i];
847 }
848 baseRef2[loc]=baseRef[loc];
849
850 //Fill last half
851 for(int i=loc+1; i<colorRef.length; i++){
852 colorRef2[i+len]=colorRef[i];
853 }
854 for(int i=loc; i<baseRef.length; i++){
855 baseRef2[i+len]=baseRef[i];
856 }
857 for(int i=loc+1; i<match.length; i++){
858 match2[i]=match[i];
859 }
860
861 //Now, just fill in the inserted portion
862 if(verbose){
863 System.err.println("loc="+loc+", colorRef2="+colorRef2.length+", colors="+colors.length+", match2="+match2.length);
864 System.err.println("max="+Tools.min(loc+len, Tools.min(colorRef2.length, colors.length)-1));
865 }
866 for(int i=loc, max=Tools.min(loc+len, Tools.min(colorRef2.length, colors.length)-1); i<=max; i++){
867 colorRef2[i]=colors[i];
868 }
869 for(int i=loc, max=Tools.min(loc+len, match2.length-1); i<=max; i++){
870 match2[i]='m';
871 }
872
873
874
875 if(loc==0){
876 for(int i=(Tools.min(loc+len, colorRef.length-1)); i>=0; i--){
877 if(DISCARD_NOCALLED_INSERTIONS && colorRef2[i]=='N'){return false;} //Fail.
878
879 // if(colorRef2[i]=='N'){System.err.println("Keeping no-called insertion:\n"+toString(crbmq)+"\n");}
880
881 // assert(colorRef2[i]!='N') : "TODO\n"+toString(crbmq)+"\n";
882
883 // System.err.println(""+(char)AminoAcid.colorToBase(baseRef2[i-1], colorRef2[i-1]));
884 // System.err.println(""+(char)baseRef2[i-1]);
885 // System.err.println(""+(char)colorRef2[i-1]);
886 // System.err.println(new String(baseRef)+"\t"+new String(colorRef)+"\t"+new String(baseRef2)+"\t"+new String(colorRef2));
887 // System.err.println("loc="+loc+", i="+i);
888 baseRef2[i]=AminoAcid.colorToBase(baseRef2[i+1], colorRef2[i]);
889 }
890 }else{
891
892 for(int i=loc+1, max=loc+len; i<=max; i++){
893 if(DISCARD_NOCALLED_INSERTIONS && colorRef2[i-1]=='N'){return false;} //Fail.
894
895 // if(colorRef2[i-1]=='N'){System.err.println("Keeping no-called insertion:\n"+toString(crbmq)+"\n");}
896
897 // assert(colorRef2[i-1]!='N') : "TODO\n"+toString(crbmq)+"\n";
898
899 // System.err.println(""+(char)AminoAcid.colorToBase(baseRef2[i-1], colorRef2[i-1]));
900 // System.err.println(""+(char)baseRef2[i-1]);
901 // System.err.println(""+(char)colorRef2[i-1]);
902 // System.err.println(new String(baseRef)+"\t"+new String(colorRef)+"\t"+new String(baseRef2)+"\t"+new String(colorRef2));
903 // System.err.println("loc="+loc+", i="+i);
904 baseRef2[i]=AminoAcid.colorToBase(baseRef2[i-1], colorRef2[i-1]);
905 }
906 }
907
908
909 crbmq[1]=colorRef2;
910 crbmq[2]=baseRef2;
911 crbmq[3]=match2;
912 crbmq[4]=quality;
913
914 return true;
915 }
916
917
918 // private static int fixNocalls(final byte[][] crbmq){
919 // byte[] colors=crbmq[0];
920 // byte[] colorRef=crbmq[1];
921 // byte[] baseRef=crbmq[2];
922 //
923 // int fixedRef=0;
924 // int fixedCall=0;
925 // assert(colors.length==colorRef.length) : "\n"+Arrays.toString(colors)+"\n"+Arrays.toString(colorRef)+
926 // "\n"+new String(baseRef)+"\n"+new String(crbmq[3])+"\n";
927 // for(int i=0; i<colors.length; i++){
928 // if(colors[i]=='N' || colors[i]=='.'){
929 // colors[i]=colorRef[i];
930 // fixedCall++;
931 // }
932 // if(colorRef[i]=='N' || colorRef[i]=='.'){
933 // colorRef[i]=colors[i];
934 // fixedRef++;
935 // }
936 // }
937 //
938 // if(fixedRef>0){
939 // for(int i=1; i<colorRef.length; i++){
940 // if(baseRef[i]=='N'){
941 // baseRef[i]=AminoAcid.colorToBase(baseRef[i-1], colorRef[i-1]);
942 // }
943 // }
944 // for(int i=colorRef.length-2; i>=0; i--){
945 // if(baseRef[i]=='N'){
946 // baseRef[i]=AminoAcid.colorToBase(baseRef[i+1], colorRef[i+1]);
947 // }
948 // }
949 // }
950 // return fixedRef+fixedCall;
951 // }
952
953
954 private static int fixNocallsInline(final byte[][] crbmq, Read read){
955 byte[] colors=crbmq[0];
956 byte[] colorRef=crbmq[1];
957 byte[] baseRef=crbmq[2];
958 byte[] match=crbmq[3];
959
960 int fixedRef=0;
961 int fixedCall=0;
962
963 // boolean indels=false;
964 //
965 // int indexOfIndel=colors.length;
966 // for(int i=0; i<match.length; i++){
967 // if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
968 // indels=true;
969 // indexOfIndel=i;
970 // break;
971 // }
972 // }
973
974
975 for(int mi=0, ci=0, ri=0; mi<match.length; mi++){
976
977 assert(ci<colors.length) : "\n"+read.toText(false)+"\n"+toString(crbmq);
978
979 if(ri>=colorRef.length){
980 System.err.println("Failed fixNocallsInline for read "+read.numericID);
981 System.err.println(read.toText(false));
982 System.err.println(toString(crbmq));
983 return -1;
984 }
985
986 assert(ri<colorRef.length) : "\n"+read.toText(false)+"\n"+toString(crbmq);
987
988 final byte m=match[mi];
989 final byte c=colors[ci];
990 final byte r=colorRef[ri];
991
992
993 if(m=='m' || m=='S' || m=='N' || m=='X'){
994
995 if(c=='N' || c=='.'){
996 if(r!='N' && r!='.'){
997 colors[ci]=r;
998 fixedCall++;
999 // match[mi]='m';
1000 }
1001 }
1002 if(r=='N' || r=='.'){
1003 if(c!='N' && c!='.'){
1004 colorRef[ri]=c;
1005 fixedRef++;
1006 match[mi]='m';
1007 }
1008 }
1009 if(m=='X'){//Not sure about this
1010 if(c=='N' || c=='.'){
1011 match[mi]='N';
1012 }
1013 match[mi]='m';
1014 }
1015
1016 ci++;
1017 ri++;
1018 }else if(m=='D'){
1019 ri++;
1020 }else if(m=='I'){
1021 ci++;
1022 }else{
1023 assert(false) : "m="+(char)m+"\n"+read.toText(false)+"\n"+toString(crbmq);
1024 }
1025
1026 // assert(m!='Y') : "m="+(char)m+"\n"+read.toText(false)+"\n"+toString(crbmq);
1027 }
1028
1029 if(fixedRef>0){
1030 {//forward
1031
1032 for(int mi=0, ri=0; mi<match.length; mi++){
1033
1034 assert(ri<colorRef.length) : "\n"+read.toText(false)+"\n"+toString(crbmq);
1035
1036 byte m=match[mi];
1037 byte r=colorRef[ri];
1038
1039 if(m=='m' || m=='S' || m=='N'){
1040
1041 if(baseRef[ri]=='N'){
1042 baseRef[ri]=AminoAcid.colorToBase(baseRef[ri+1], r);
1043 }
1044 if(baseRef[ri+1]=='N'){
1045 baseRef[ri+1]=AminoAcid.colorToBase(baseRef[ri], r);
1046 }
1047 ri++;
1048 }else if(m=='D'){
1049 ri++;
1050 }else if(m=='I'){
1051 }else{
1052 assert(false) : "m="+(char)m+"\n"+read.toText(false)+"\n"+toString(crbmq);
1053 }
1054 }
1055 }
1056
1057
1058 {//reverse
1059
1060 for(int mi=match.length-1, ri=colorRef.length-1; mi>=0; mi--){
1061
1062 assert(ri>=0) : "\n"+read.toText(false)+"\n"+toString(crbmq);
1063
1064 byte m=match[mi];
1065 byte r=colorRef[ri];
1066
1067 if(m=='m' || m=='S' || m=='N'){
1068
1069 if(baseRef[ri]=='N'){
1070 baseRef[ri]=AminoAcid.colorToBase(baseRef[ri+1], r);
1071 }
1072 if(baseRef[ri+1]=='N'){
1073 baseRef[ri+1]=AminoAcid.colorToBase(baseRef[ri], r);
1074 }
1075 ri--;
1076 }else if(m=='D'){
1077 ri--;
1078 }else if(m=='I'){
1079 }else{
1080 assert(false) : "m="+(char)m+"\n"+read.toText(false)+"\n"+toString(crbmq);
1081 }
1082 }
1083 }
1084 }
1085 return fixedRef+fixedCall;
1086 }
1087
1088
1089 private static int fixNocalls(final byte[][] crbmq){
1090 byte[] colors=crbmq[0];
1091 byte[] colorRef=crbmq[1];
1092 byte[] baseRef=crbmq[2];
1093 byte[] match=crbmq[3];
1094
1095 int fixedRef=0;
1096 int fixedCall=0;
1097
1098 boolean indels=false;
1099
1100 int indexOfIndel=colors.length;
1101 for(int i=0; i<match.length; i++){
1102 if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1103 indels=true;
1104 indexOfIndel=i;
1105 break;
1106 }
1107 }
1108
1109 // assert(colors.length==colorRef.length) : "\n"+Arrays.toString(colors)+"\n"+Arrays.toString(colorRef)+
1110 // "\n"+new String(baseRef)+"\n"+new String(crbmq[3])+"\n";
1111 for(int i=0; i<indexOfIndel; i++){
1112 // if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1113 // indels=true;
1114 // break;
1115 // }
1116 if(colors[i]=='N' || colors[i]=='.'){
1117 if(colorRef[i]!='N' && colorRef[i]!='.'){
1118 colors[i]=colorRef[i];
1119 fixedCall++;
1120 assert(match[i]!='I' && match[i]!='D') : toString(crbmq);
1121 match[i]='m';
1122 }
1123 }
1124 if(colorRef[i]=='N' || colorRef[i]=='.'){
1125 if(colors[i]!='N' && colors[i]!='.'){
1126 colorRef[i]=colors[i];
1127 fixedRef++;
1128 assert(match[i]!='I' && match[i]!='D') : toString(crbmq);
1129 match[i]='m';
1130 }
1131 }
1132 }
1133
1134 assert(indels || colors.length==colorRef.length) : "\n"+toString(crbmq)+"\n";
1135
1136 if(fixedRef>0){
1137
1138 for(int i=1; i<indexOfIndel; i++){
1139 if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1140 assert(false);
1141 break;
1142 }
1143 if(baseRef[i]=='N'){
1144 baseRef[i]=AminoAcid.colorToBase(baseRef[i-1], colorRef[i-1]);
1145 }
1146 }
1147 if(!indels){
1148 for(int i=colorRef.length-2; i>=0; i--){
1149 if(baseRef[i]=='N'){
1150 baseRef[i]=AminoAcid.colorToBase(baseRef[i+1], colorRef[i+1]);
1151 }
1152 }
1153 }
1154 }
1155 return fixedRef+fixedCall;
1156 }
1157
1158
1159 private static int fixNocallsBackward(final byte[][] crbmq){
1160 byte[] colors=crbmq[0];
1161 byte[] colorRef=crbmq[1];
1162 byte[] baseRef=crbmq[2];
1163 byte[] match=crbmq[3];
1164
1165 int fixedRef=0;
1166 int fixedCall=0;
1167
1168 boolean indels=false;
1169
1170 int indexOfIndelCall=0;
1171 int indexOfIndelRef=0;
1172 int indexOfIndelMatch=0;
1173 for(int i=match.length-1; i>=0; i--){
1174 if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1175 indels=true;
1176 int safe=(match.length-1)-i;
1177 indexOfIndelMatch=i;
1178 indexOfIndelCall=colors.length-safe;
1179 indexOfIndelRef=colorRef.length-safe;
1180 // System.err.println("indexOfIndelMatch="+indexOfIndelMatch+
1181 // "\nindexOfIndelCall="+indexOfIndelCall+
1182 // "\nindexOfIndelRef="+indexOfIndelRef+
1183 // "\nsafe="+safe);
1184 break;
1185 }
1186 }
1187
1188 // assert(colors.length==colorRef.length) : "\n"+Arrays.toString(colors)+"\n"+Arrays.toString(colorRef)+
1189 // "\n"+new String(baseRef)+"\n"+new String(crbmq[3])+"\n";
1190 for(int i=colors.length-1, j=colorRef.length-1, k=match.length-1; i>=indexOfIndelCall; i--, j--, k--){
1191 // if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1192 // indels=true;
1193 // break;
1194 // }
1195 if(colors[i]=='N' || colors[i]=='.'){
1196 if(colorRef[j]!='N' && colorRef[j]!='.'){
1197 colors[i]=colorRef[j];
1198 fixedCall++;
1199 assert(match[k]!='I' && match[k]!='D') : "i="+i+", j="+j+", k="+k+"\n"+toString(crbmq);
1200 match[k]='m';
1201 }
1202 }
1203 if(colorRef[j]=='N' || colorRef[j]=='.'){
1204 if(colors[i]!='N' && colors[i]!='.'){
1205 colorRef[j]=colors[i];
1206 fixedRef++;
1207 assert(match[k]!='I' && match[k]!='D') : "i="+i+", j="+j+", k="+k+"\n"+toString(crbmq);
1208 match[k]='m';
1209 }
1210 }
1211 }
1212
1213 assert(indels || colors.length==colorRef.length) : "\n"+toString(crbmq)+"\n";
1214
1215 if(fixedRef>0){
1216 if(!indels){
1217 for(int i=1; i<colorRef.length; i++){
1218 if(baseRef[i]=='N'){baseRef[i]=AminoAcid.colorToBase(baseRef[i-1], colorRef[i-1]);}
1219 }
1220 }
1221 for(int i=colorRef.length-2; i>=indexOfIndelRef; i--){
1222 if(match[i]=='I' || match[i]=='X' || match[i]=='Y' || match[i]=='D'){
1223 assert(false);
1224 break;
1225 }
1226 if(baseRef[i]=='N'){
1227 baseRef[i]=AminoAcid.colorToBase(baseRef[i+1], colorRef[i+1]);
1228 }
1229 }
1230 }
1231 return fixedRef+fixedCall;
1232 }
1233
1234 public static boolean perfectMatch(final byte[] match){
1235 if(match==null){return false;}
1236 for(int i=0; i<match.length; i++){
1237 byte b=match[i];
1238 if(b!='m'){return false;}
1239 }
1240 return true;
1241 }
1242
1243 private static boolean containsIndels(final byte[] match){
1244 for(int i=0; i<match.length; i++){
1245 byte b=match[i];
1246 if(b=='I' || b=='D' || b=='X' || b=='Y'){return true;}
1247 }
1248 return false;
1249 }
1250
1251 private static boolean containsNocalls(final byte[] match){
1252 for(int i=0; i<match.length; i++){
1253 byte b=match[i];
1254 if(b=='N' || b=='X' || b=='Y'){return true;}
1255 }
1256 return false;
1257 }
1258
1259 private static boolean containsXY(final byte[] match){
1260 for(int i=0; i<match.length; i++){
1261 byte b=match[i];
1262 if(b=='X' || b=='Y'){return true;}
1263 }
1264 return false;
1265 }
1266
1267 //TODO: Add support for deletions
1268 /** thresh: Must see this many consecutive 'm' to stop. */
1269 private static int trimEnd(final byte[][] crbmq, int thresh, Read r){
1270
1271 byte[] colors=crbmq[0];
1272 byte[] colorRef=crbmq[1];
1273 byte[] baseRef=crbmq[2];
1274 byte[] match=crbmq[3];
1275 byte[] quality=crbmq[4];
1276
1277 // if(match[0]=='m' && match[match.length-1]=='m'){return 0;}
1278 {
1279 // byte a=match[0], b=match[1], c=match[match.length-1];
1280 // if(a=='m' && b=='m' && c=='m' || c=='S'){return 0;}
1281
1282 // System.err.println(new String(match));
1283 byte a=match[match.length-1], b=match[match.length-2];
1284
1285 // System.err.println("a="+(char)a+", b="+(char)b);
1286 // System.err.println("X");
1287 if((a=='m' || a=='D') && (b=='m')){return 0;}
1288 // System.err.println("Y");
1289 if((a=='m' || a=='D') && quality[quality.length-1]>=22 && quality[quality.length-2]>=22){return 0;}
1290 // System.err.println("Z");
1291 }
1292
1293 int last=match.length-1;
1294 int minBadIndex=last;
1295 int mcount=0;
1296
1297 int insertions=0;
1298
1299 while(last>1 && mcount<thresh){
1300 byte c=match[last];
1301 if(c=='m'){mcount++;}
1302 else if(match[last]=='S' || match[last]=='I' || match[last]=='N'
1303 || match[last]=='X'|| match[last]=='Y'){
1304 minBadIndex=last;
1305 mcount=0;
1306 if(match[last]=='I' || match[last]=='X'|| match[last]=='Y'){
1307 insertions++;
1308 }
1309 }else{
1310 break;
1311 }
1312 last--;
1313 }
1314
1315 final int trim=match.length-minBadIndex;
1316
1317 int trim2=insertions-trim;
1318
1319 colors=Arrays.copyOf(colors, colors.length-trim);
1320 if(trim2!=0){
1321 colorRef=Arrays.copyOf(colorRef, colorRef.length-trim+insertions);
1322 baseRef=Arrays.copyOf(baseRef, baseRef.length-trim+insertions);
1323 }
1324 match=Arrays.copyOf(match, match.length-trim);
1325 quality=Arrays.copyOf(quality, quality.length-trim);
1326
1327 crbmq[0]=colors;
1328 crbmq[1]=colorRef;
1329 crbmq[2]=baseRef;
1330 crbmq[3]=match;
1331 crbmq[4]=quality;
1332
1333 if(r.strand()==Shared.PLUS){
1334 r.stop-=(trim-insertions);
1335 }else{
1336 r.start+=(trim-insertions);
1337 }
1338
1339 // System.err.println(new String(match));
1340 return trim;
1341 }
1342
1343 /** thresh: Must see this many consecutive 'm' to stop. */
1344 private static int trimStart(final byte[][] crbmq, int thresh, Read r){
1345 assert(false) : "TODO";
1346 byte[] colors=crbmq[0];
1347 byte[] colorRef=crbmq[1];
1348 byte[] baseRef=crbmq[2];
1349 byte[] match=crbmq[3];
1350 byte[] quality=crbmq[4];
1351
1352 // if(match[0]=='m' && match[match.length-1]=='m'){return 0;}
1353 {
1354 byte a=match[0];
1355 if(a=='m'){return 0;}
1356 }
1357 if(match[0]=='S' || match[0]=='I' || match[0]=='N'
1358 || match[0]=='X'|| match[0]=='Y'){
1359 int last=match.length-1;
1360 int minBadIndex=last;
1361 int mcount=0;
1362
1363 int insertions=0;
1364
1365 while(last>1 && mcount<thresh){
1366 byte c=match[last];
1367 if(c=='m'){mcount++;}
1368 else if(match[last]=='S' || match[last]=='I' || match[last]=='N'
1369 || match[last]=='X'|| match[last]=='Y'){
1370 minBadIndex=last;
1371 mcount=0;
1372 if(match[last]=='I' || match[last]=='X'|| match[last]=='Y'){
1373 insertions++;
1374 }
1375 }else{
1376 break;
1377 }
1378 last--;
1379 }
1380
1381 final int trim=match.length-minBadIndex;
1382
1383 int trim2=insertions-trim;
1384
1385 colors=Arrays.copyOf(colors, colors.length-trim);
1386 if(trim2!=0){
1387 colorRef=Arrays.copyOf(colorRef, colorRef.length-trim+insertions);
1388 baseRef=Arrays.copyOf(baseRef, baseRef.length-trim+insertions);
1389 }
1390 match=Arrays.copyOf(match, match.length-trim);
1391 quality=Arrays.copyOf(quality, quality.length-trim);
1392
1393 crbmq[0]=colors;
1394 crbmq[1]=colorRef;
1395 crbmq[2]=baseRef;
1396 crbmq[3]=match;
1397 crbmq[4]=quality;
1398
1399 if(r.strand()==Shared.PLUS){
1400 r.stop-=(trim-insertions);
1401 }else{
1402 r.start+=(trim-insertions);
1403 }
1404
1405 return trim;
1406 }
1407 return 0;
1408 }
1409
1410
1411 // private static int trimStart(final byte[][] crbmq, Read r){
1412 //
1413 // byte[] colors=crbmq[0];
1414 // byte[] colorRef=crbmq[1];
1415 // byte[] baseRef=crbmq[2];
1416 // byte[] match=crbmq[3];
1417 // byte[] quality=crbmq[4];
1418 //
1419 // if(match[0]=='m' || match[0]=='S'){return 0;}
1420 //
1421 // int index=0;
1422 // int insertions=0;
1423 // while(index<match.length && (match[index]=='I' || match[index]=='X')){
1424 // if(match[index]=='I'){insertions++;}
1425 // index++;
1426 // }
1427 // if(index==0){return 0;}
1428 // System.err.println("*** "+r.toText(false));
1429 // System.err.println(toString(crbmq));
1430 //
1431 // int start2=index-insertions;
1432 //
1433 // colors=KillSwitch.copyOfRange(colors, index, colors.length);
1434 // if(start2!=0){
1435 // colorRef=KillSwitch.copyOfRange(colorRef, index-insertions, colorRef.length);
1436 // baseRef=KillSwitch.copyOfRange(baseRef, index-insertions, baseRef.length);
1437 // }
1438 // match=KillSwitch.copyOfRange(match, index, match.length);
1439 // quality=KillSwitch.copyOfRange(quality, index, quality.length);
1440 //
1441 //
1442 // crbmq[0]=colors;
1443 // crbmq[1]=colorRef;
1444 // crbmq[2]=baseRef;
1445 // crbmq[3]=match;
1446 // crbmq[4]=quality;
1447 //
1448 // System.err.println("\n"+toString(crbmq));
1449 //
1450 // if(r.strand()==Gene.PLUS){
1451 // r.start+=(index-insertions);
1452 // }else{
1453 // r.stop-=(index-insertions);
1454 // }
1455 //
1456 // return index;
1457 // }
1458
1459
1460 private static int fixSubs(final byte[][] crbmq){
1461
1462 byte[] colors=crbmq[0];
1463 byte[] colorRef=crbmq[1];
1464 byte[] baseRef=crbmq[2];
1465 byte[] match=crbmq[3];
1466 byte[] quality=crbmq[4];
1467
1468 assert(colors.length==colorRef.length) : "\n"+toString(crbmq);
1469 assert(colors.length==match.length) : "\n"+toString(crbmq);
1470 assert(colors.length==baseRef.length-1) : "\n"+toString(crbmq);
1471
1472 int first=match.length-1, last=0;
1473
1474 for(int i=0; i<match.length; i++){
1475 if(match[i]=='S'){
1476 first=Tools.min(first, i);
1477 last=Tools.max(last, i);
1478 }
1479 }
1480
1481 if(verbose){System.err.println("First="+first+", last="+last);}
1482
1483 if(first>last){return 0;} //No subs
1484
1485
1486 if(last>=colors.length-1 && first==0){
1487 return -1; //Cannot decode
1488 }else if(first>0){ //Go right only
1489 if(verbose){System.err.println("max="+Tools.min(last+1, colors.length));}
1490 for(int i=first, max=Tools.min(last+1, colors.length); i<max; i++){
1491 match[i]='m';
1492 if(colors[i-1]!='N' && baseRef[i-1]!='N'){
1493 baseRef[i]=AminoAcid.colorToBase(baseRef[i-1], colors[i-1]);
1494 }//else do nothing
1495 }
1496 if(last==match.length-1 && colors[last]!='N' && baseRef[last]!='N'){
1497 baseRef[last+1]=AminoAcid.colorToBase(baseRef[last], colors[last]);
1498 }
1499 }else if(first==0){ //Left only
1500 for(int i=last, min=Tools.max(0, first); i>=min; i--){
1501 match[i]='m';
1502 if(colors[i]!='N' && baseRef[i+1]!='N'){
1503 baseRef[i]=AminoAcid.colorToBase(baseRef[i+1], colors[i]);
1504 assert(baseRef[i]!='N') : i+", "+colors[i]+", "+(char)baseRef[i+1];
1505 }//else do nothing
1506 }
1507 }
1508
1509 return 1;
1510
1511 }
1512
1513
1514 private static int distToMismatch(byte[] colors, byte[] colorRef, int loc, int limit) {
1515 int min=limit+1;
1516 int left=Tools.max(0, loc-limit);
1517 int right=Tools.min(colors.length, loc+limit+1);
1518 for(int i=left; i<loc; i++){
1519 if(colors[i]!=colorRef[i]){
1520 min=Tools.min(min, loc-i);
1521 }
1522 }
1523 for(int i=loc+1; i<right; i++){
1524 if(colors[i]!=colorRef[i]){
1525 min=Tools.min(min, i-loc);
1526 }
1527 }
1528 return min;
1529 }
1530
1531
1532 public static boolean verifyMatchString2(Read r, boolean loud){
1533 int maxVars=0;
1534
1535 assert(r.mapped());
1536 assert(r.valid());
1537 if(r.match==null){return false;}
1538 if(r.match.length<r.length()){return false;}
1539
1540 byte last='m';
1541 for(int i=0; i<r.match.length; i++){
1542 byte b=r.match[i];
1543 if(b=='X' || b=='Y'){
1544 // assert(false) : read.toText(false);
1545 // b=r.match[i]='I';
1546 } //TODO: Should not be needed, if reads are trimmed...
1547
1548 if(b!='m' && b!=last){
1549 maxVars++;
1550 }
1551 last=b;
1552 }
1553
1554 if(maxVars==0){
1555 assert(r.match.length==r.length());
1556 return true;
1557 }
1558
1559 // byte[] original=Arrays.copyOf(call, call.length);
1560 if(r.strand()==Shared.MINUS){
1561 AminoAcid.reverseComplementBasesInPlace(r.bases);
1562 Tools.reverseInPlace(r.quality);
1563 }
1564
1565
1566 //assert(checkArray(call)) :
1567 // "\n"+new String(original)+"\n"+new String(Tools.reverseAndCopy(call))+"\n"+
1568 // "\n"+Arrays.toString(original)+"\n"+Arrays.toString(Tools.reverseAndCopy(call))+"\n";
1569
1570 // assert(false) : "TODO: ensure read is aligned with forward strand.";
1571
1572 ChromosomeArray cha=Data.getChromosome(r.chrom);
1573
1574
1575 boolean b=true;
1576 try{
1577 b=(verifyMatchString(r.bases, cha.array, r.match, r.start, loud));
1578 }catch(Exception e){
1579 System.err.println(e);
1580 System.err.println("This read failed verifyMatchString:\n"+r.toText(false)+"\n");
1581 b=true;//ignores the problem.
1582 }
1583
1584 if(r.strand()==Shared.MINUS){
1585 AminoAcid.reverseComplementBasesInPlace(r.bases);
1586 Tools.reverseInPlace(r.quality);
1587 }
1588 return b;
1589 }
1590
1591
1592 public static boolean verifyMatchString(byte[] call, byte[] ref, byte[] match, int rstart, boolean loud){
1593
1594 boolean ok=true;
1595 for(int ci=0, mi=0, ri=rstart; ok && mi<match.length; mi++){
1596 byte m=match[mi];
1597 byte c=(m=='D' ? (byte)'?' : call[ci]);
1598 // byte r=((m=='I' || m=='X' || m=='Y') ? (byte)'?' : ref[ri]);
1599 byte r=((m=='I' || m=='X' || m=='Y') ? (byte)'?' : ((ri>=0 && ri<ref.length) ? ref[ri] : (byte)'N'));
1600
1601 if(m=='m' || m=='s'){
1602 ok=c==r;
1603 ci++;
1604 ri++;
1605 }else if(m=='D'){
1606 ri++;
1607 }else if(m=='I' || m=='X' || m=='Y'){
1608 ci++;
1609 }else if(m=='S'){
1610 ok=c!=r;
1611 ci++;
1612 ri++;
1613 }else if(m=='N'){
1614 ok=(c=='N' || r=='N');
1615 ci++;
1616 ri++;
1617 }else{
1618 assert(false) : (char)m;
1619 }
1620
1621 }
1622
1623 if(!ok && loud){
1624 System.err.println("NOT OK!");
1625 if(call[0]<4){
1626 if(ref.length>400){
1627 System.err.println(toStringCS(KillSwitch.copyOfRange(ref, rstart, rstart+call.length))+" (ref)");
1628 }else{
1629 System.err.println(toStringCS(ref)+" (ref)");
1630 }
1631 System.err.println(toStringCS(call)+" (call)");
1632 System.err.println(new String(match));
1633 }else{
1634 if(ref.length>400){
1635 System.err.println(new String(KillSwitch.copyOfRange(ref, rstart, rstart+call.length))+" (ref)");
1636 }else{
1637 System.err.println(new String(ref)+" (ref)");
1638 }
1639 System.err.println(new String(call)+" (call)");
1640 System.err.println(new String(match));
1641 }
1642 }
1643
1644 if(!ok){
1645
1646 ok=true;
1647
1648 if(loud){System.err.println("Attempting to fix and skip error.");}
1649 for(int ci=0, mi=0, ri=rstart; mi<match.length; mi++){
1650 byte m=match[mi];
1651 byte c=(m=='D' ? (byte)'?' : call[ci]);
1652 // byte r=((m=='I' || m=='X' || m=='Y') ? (byte)'?' : ref[ri]);
1653 byte r=((m=='I' || m=='X' || m=='Y') ? (byte)'?' : ((ri>=0 && ri<ref.length) ? ref[ri] : (byte)'N'));
1654
1655 if(m=='m' || m=='s'){
1656 if(!AminoAcid.isFullyDefined(c) || !AminoAcid.isFullyDefined(r)){
1657 match[mi]='N';
1658 }else{
1659 ok=(ok && c==r);
1660 }
1661 ci++;
1662 ri++;
1663 }else if(m=='D'){
1664 ri++;
1665 }else if(m=='I' || m=='X' || m=='Y'){
1666 ci++;
1667 }else if(m=='S'){
1668 ok=(ok && c!=r);
1669 ci++;
1670 ri++;
1671 }else if(m=='N'){
1672 ok=(ok && (!AminoAcid.isFullyDefined(c) || !AminoAcid.isFullyDefined(r)));
1673 ci++;
1674 ri++;
1675 }else{
1676 assert(false) : (char)m;
1677 }
1678 }
1679
1680 if(call[0]<4){
1681 if(ref.length>400){
1682 System.err.println(toStringCS(KillSwitch.copyOfRange(ref, rstart, rstart+call.length))+" (ref)");
1683 }else{
1684 System.err.println(toStringCS(ref)+" (ref)");
1685 }
1686 System.err.println(toStringCS(call)+" (call)");
1687 System.err.println(new String(match));
1688 }else{
1689 if(ref.length>400){
1690 System.err.println(new String(KillSwitch.copyOfRange(ref, rstart, rstart+call.length))+" (ref)");
1691 }else{
1692 System.err.println(new String(ref)+" (ref)");
1693 }
1694 System.err.println(new String(call)+" (call)");
1695 System.err.println(new String(match));
1696 }
1697
1698
1699
1700 if(THROW_EXCEPTION_ON_VERIFY_FAILURE){
1701 System.err.println("Fixed successfully?\t"+ok);
1702 throw new RuntimeException("Failed VerifyMatchString()");
1703 }
1704
1705 }
1706
1707 return ok;
1708 }
1709
1710 //TODO: No-calls and no-ref are currently considered the same.
1711 /** When this is called, the match string should be plus-oriented */
1712 public ArrayList<Varlet> toVars(final Read read, final boolean CONDENSE, final boolean CONDENSE_SNPS, final boolean SPLIT_SUBS){
1713 assert(read.match!=null);
1714 byte[] match=read.match;
1715 byte[] quality=read.quality;
1716 byte[] call=read.bases;
1717
1718 if(quality==null){quality=Read.getFakeQuality(call.length);}
1719
1720 assert(checkArray(call));
1721
1722 int maxVars=0;
1723
1724 byte last='m';
1725 for(int i=0; i<match.length; i++){
1726 byte b=match[i];
1727 if(b=='X' || b=='Y'){
1728 // assert(false) : read.toText(false);
1729 b=match[i]='I';
1730 } //TODO: Should not be needed, if reads are trimmed...
1731
1732 if(b!='m' && b!=last){
1733 maxVars++;
1734 }
1735 last=b;
1736 }
1737
1738 if(maxVars==0){return null;}
1739
1740 // byte[] original=Arrays.copyOf(call, call.length);
1741 if(read.strand()==Shared.MINUS){
1742 AminoAcid.reverseComplementBasesInPlace(call);
1743 Tools.reverseInPlace(quality);
1744 }
1745
1746
1747 //assert(checkArray(call)) :
1748 // "\n"+new String(original)+"\n"+new String(Tools.reverseAndCopy(call))+"\n"+
1749 // "\n"+Arrays.toString(original)+"\n"+Arrays.toString(Tools.reverseAndCopy(call))+"\n";
1750
1751 // assert(false) : "TODO: ensure read is aligned with forward strand.";
1752
1753 ArrayList<Varlet> vars=new ArrayList<Varlet>(maxVars);
1754 ChromosomeArray cha=Data.getChromosome(read.chrom);
1755
1756 boolean vms=false;
1757 try {
1758 vms=verifyMatchString(call, cha.array, match, read.start, true);
1759 } catch (Exception e) {
1760 // TODO Auto-generated catch block
1761 e.printStackTrace();
1762 vms=false;
1763 System.err.println("in TranslateColorspace.toVars(), a read failed verification:\n"+read.toText(false)+"\n");
1764 }
1765
1766 if(verbose){
1767 System.err.println("Making vars:");
1768 System.err.println(new String(call));
1769 System.err.println(cha.getString(read.start, read.stop));
1770 System.err.println(new String(match));
1771
1772 }
1773
1774 int readQuality;
1775 {
1776 int totalQual=0;
1777 int minQual=quality[0];
1778 for(int i=0; i<quality.length; i++){
1779 totalQual+=quality[i];
1780 minQual=Tools.min(minQual, quality[i]);
1781 }
1782 readQuality=(totalQual+2*minQual)/(read.length()+2);
1783 }
1784 final float expectedErrors=read.expectedErrors(false, 0);
1785
1786 last='m';
1787 int callPos=0;
1788 int refPos=read.start;
1789
1790 //Make variations, then merge adjacent variations.
1791 for(int matchPos=0; matchPos<match.length; matchPos++){
1792
1793 if(match[matchPos]=='N'){
1794 byte a=call[callPos];
1795 byte b=cha.get(refPos);
1796 if(a!='N' && b=='N'){match[matchPos]='R';}
1797 }
1798
1799 final byte type=match[matchPos];
1800
1801 if(type=='m'){
1802 callPos++;
1803 refPos++;
1804 }else{
1805 byte m;
1806 int nCount=0; //"no-call": "N" in read
1807 int rCount=0; //"no-ref": "N" in ref but read is called
1808 int iCount=0;
1809 int dCount=0;
1810 int sCount=0;
1811
1812 //call string
1813 StringBuilder cs=new StringBuilder(8);
1814
1815 //ref string
1816 StringBuilder rs=new StringBuilder(8);
1817
1818 final int mstart=matchPos;
1819 final int cstart=callPos;
1820 final int rstart=refPos;
1821
1822 int qualSum=0;
1823 int qualMin=quality[callPos];
1824
1825 while(matchPos<match.length && (m=match[matchPos])==type){
1826
1827 //TODO: Not very good for deletions...
1828 qualSum+=quality[callPos];
1829 qualMin=Tools.min(qualMin, quality[callPos]);
1830
1831 if(m=='I'){
1832 iCount++;
1833 cs.append((char)call[callPos]);
1834 callPos++;
1835 }else if(m=='D'){
1836 dCount++;
1837 rs.append((char)cha.get(refPos));
1838 refPos++;
1839 }else if(m=='S'){
1840 sCount++;
1841 cs.append((char)call[callPos]);
1842 rs.append((char)cha.get(refPos));
1843 assert(call[callPos]!='N');
1844 assert(cha.get(refPos)!='N');
1845 callPos++;
1846 refPos++;
1847 if(SPLIT_SUBS){
1848 matchPos++;break;//Forces all subs to be split
1849 }
1850 }else if(m=='N'){
1851
1852 assert(call[callPos]=='N') : callPos+"\n"+new String(call)+"\n"+new String(match)+"\n"+cha.getString(read.start, read.stop)+"\n";
1853 nCount++;
1854 // cs.append((char)call[callPos]);
1855 cs.append('N');
1856 rs.append((char)cha.get(refPos));
1857 callPos++;
1858 refPos++;
1859
1860 //This block corrects for a rare situation when both no-calls and no-refs are mixed in a single 'N' block.
1861 {
1862 int x=matchPos+1;
1863 if(x<match.length && match[x]=='N'){
1864 byte a=call[callPos];
1865 byte b=cha.get(refPos);
1866 if(a!='N' && b=='N'){match[x]='R';}
1867 }
1868 }
1869
1870 }else if(m=='R'){
1871 assert(call[callPos]!='N');
1872 assert(cha.get(refPos)=='N');
1873 rCount++;
1874 cs.append((char)call[callPos]);
1875 rs.append((char)cha.get(refPos));
1876 callPos++;
1877 refPos++;
1878 matchPos++;break; //Output no-ref individually
1879 }else{
1880 System.err.println("Detected invalid decode for read "+read.numericID+":");
1881 System.err.println((char)m+"\n"+new String(rs)+"\n"+new String(cs)+"\n"+new String(match)+"\n"
1882 +new String(call)+"\n"+cha.getString(read.start, read.stop)+"\n"+read.toText(false)+"\n");
1883 return null;
1884 // assert(false) : (char)m+"\n"+new String(rs)+"\n"+new String(cs)+"\n"+new String(match)+"\n"
1885 // +new String(call)+"\n"+cha.getString(read.start, read.stop)+"\n"+read.toText(false)+"\n";
1886 }
1887 matchPos++;
1888 }
1889 matchPos--;
1890
1891 int mstop=matchPos;
1892
1893 int mlen=iCount+dCount+sCount+nCount+rCount;
1894
1895 int clen=iCount+sCount+nCount+rCount;
1896 int rlen=dCount+sCount+nCount+rCount;
1897
1898 Varlet v;
1899
1900 callPos=cstart+clen;
1901 refPos=rstart+rlen;
1902
1903 final int rstop=Tools.max(rstart, rstart+rlen-1);
1904 final int cstop=cstart+clen-1;
1905
1906 final byte varType;
1907
1908 if(rlen==0){
1909 varType=Variation.INS;
1910 if(verbose){System.err.println("Setting type INS: "+Variation.varTypeMap[varType]);}
1911 }else if(clen==0){varType=Variation.DEL;}
1912 else if(rCount>0){varType=Variation.NOREF;}
1913 else if(cs.charAt(0)=='N'){
1914 varType=Variation.NOCALL;
1915 if(verbose){System.err.println("Setting type NOCALL: "+Variation.varTypeMap[varType]);}
1916 }else if(mlen==1){varType=Variation.SNP;}
1917 else{varType=Variation.DELINS;}
1918
1919
1920 final int headDist, tailDist, endDist;
1921 {
1922 int cstart2=cstart, cstop2=cstop;
1923 if(varType==Variation.DEL){
1924 cstart2--;
1925 cstop2++;
1926 }
1927
1928 assert(cstop2>=cstart2) : Variation.varTypeMap[varType]+", "+cstop2+", "+cstart2+", "+clen+
1929 "\n'"+cs+"', '"+rs+"'\n"+new String(match);
1930 assert(cstop2<call.length);
1931
1932 if(read.strand()==Shared.PLUS){
1933 headDist=cstart2;
1934 tailDist=call.length-cstop2-1;
1935 }else{
1936 tailDist=cstart2;
1937 headDist=call.length-cstop2-1;
1938 }
1939 endDist=Tools.min(headDist, tailDist);
1940 assert(headDist>=0);
1941 assert(tailDist>=0);
1942 }
1943
1944
1945 int varQuality;
1946 if(varType==Variation.DEL){
1947 varQuality=((qualSum/mlen)+(qualMin))/2;
1948 }else{
1949 if(callPos<quality.length-1 && callPos>1){
1950 qualMin=Tools.min(quality[callPos-2], quality[callPos-2], quality[callPos-2], quality[callPos-2]);
1951 varQuality=(quality[callPos-2]+quality[callPos-1]+quality[callPos]+quality[callPos+1]+(qualMin))/5;
1952 }else if(callPos<quality.length && callPos>0){
1953 qualMin=Tools.min(quality[callPos-1], quality[callPos]);
1954 varQuality=qualMin;
1955 }else{
1956 varQuality=((qualSum/mlen)+(qualMin))/2;
1957 }
1958 }
1959
1960 if(verbose){
1961 System.err.println("mlen="+mlen+", rlen="+rlen+", clen="+clen+", varType="+Variation.varTypeMap[varType]+"\n"+
1962 ", cs="+cs+", nCount="+nCount+", rCount="+rCount+", iCount="+iCount+", dCount="+dCount+", sCount="+sCount);
1963 }
1964
1965 // assert(read.mapScore>0) : read.toText(false);
1966 v=new Varlet(read.chrom, read.strand(), rstart, rstop, mstart, mstop, varType, rs.toString(), cs.toString(),
1967 varQuality, readQuality, read.mapScore, read.errors, expectedErrors, (read.paired() ? 1 : 0), read.numericID,
1968 read.length(), read.start, read.stop, read.copies, headDist, tailDist, endDist,
1969 read.pairnum());
1970
1971 // if(v.varType==Variation.NOREF){System.err.print("R");}
1972
1973 if(v.varType==Variation.SNP){
1974 if(v.call.equals(v.ref)){
1975 System.err.println("\n"+read.toText(false));
1976 System.err.println("\n"+v.toText());
1977 System.err.println("\n"+read.strand());
1978 System.err.println("\n");
1979 System.err.println(cha.getString(read.start, read.stop));
1980 System.err.println(new String(call));
1981 System.err.println(new String(match));
1982 System.err.println("\n");
1983 assert(false);
1984 }
1985
1986 }
1987
1988 vars.add(v);
1989 }
1990 }
1991 //assert(checkArray(call));
1992
1993 // assert(read.numericID!=3448228) : CONDENSE+"\n"+vars;
1994
1995 // boolean fail=false;
1996 // {
1997 // int nr=0;
1998 // for(Variation v : vars){
1999 // if(v.varType==Variation.NOREF){
2000 // nr++;
2001 // fail=nr>0;
2002 // }
2003 // }
2004 // System.err.print(" "+nr);
2005 // }
2006 // if(fail){verbose=true;}
2007
2008 // if(read.numericID==3448228){verbose=true;}
2009
2010 //Optionally, merge nearby variations
2011 if(CONDENSE && vars.size()>1){
2012 boolean condense=false;
2013
2014 int mergeDistance=1; // 1 for adjacent, 2 for non-adjacent.
2015
2016 for(int i=1; i<vars.size() && !condense; i++){
2017 Varlet v1=vars.get(i-1);
2018 Varlet v2=vars.get(i);
2019 assert(v1.matchStop<v2.matchStart);
2020
2021 if(!v1.isNR_or_NC() && !v2.isNR_or_NC()){
2022 if(v1.endLoc>=v2.beginLoc){condense=true;} //To prevent overlapping variations
2023 else if(CONDENSE_SNPS || (v1.varType!=Variation.SNP && v2.varType!=Variation.SNP)){
2024 condense|=(v1.matchStop>=v2.matchStart-mergeDistance);
2025 }
2026 }
2027
2028 if(verbose){
2029 System.err.println("Compared\n"+v1+"\nand\n"+v2+"\ncondense="+condense+"\n"+v1.matchStart+", "+v2.matchStart+", "+mergeDistance);
2030 }
2031 }
2032
2033 // condense=false;
2034 if(condense){
2035 if(verbose){
2036 System.err.println("Condensing:");
2037 for(Varlet v : vars){
2038 System.err.println(v);
2039 }
2040 }
2041 ArrayList<Varlet> list2=new ArrayList<Varlet>(vars.size()-1);
2042 for(int i=vars.size()-2; i>=0; i--){
2043 Varlet prev=vars.get(i);
2044 // Varlet v=vars.get(i+1);
2045 Varlet v=vars.remove(i+1);
2046
2047
2048 boolean merge=(!v.isNR_or_NC() && !prev.isNR_or_NC() && (prev.matchStop>=v.matchStart-mergeDistance || prev.endLoc>=v.beginLoc));
2049 if(merge && !CONDENSE_SNPS && prev.endLoc<v.beginLoc){
2050 if(v.varType==Variation.SNP || prev.varType==Variation.SNP){
2051 merge=false;
2052 }
2053 }
2054
2055 byte varType;
2056
2057 if(merge){ //then merge.
2058
2059 // if(v.varType==prev.varType){
2060 // varType=v.varType;
2061 // }else{
2062 // varType=Variation.DELINS;
2063 // }
2064 varType=Variation.DELINS;
2065
2066 int midstart=prev.endLoc+1;
2067 int midstop=v.beginLoc-1;
2068
2069 if(prev.varType==Variation.INS){midstart--;}
2070
2071 String middle=(midstart>midstop ? "" : cha.getString(midstart, midstop));
2072
2073 String cs=(prev.call==null ? "" : prev.call)+middle+(v.call==null ? "" : v.call);
2074 String rs=(prev.ref==null ? "" : prev.ref)+middle+(v.ref==null ? "" : v.ref);
2075
2076 final int headDist=Tools.min(v.headDist, prev.headDist);
2077 final int tailDist=Tools.min(v.tailDist, prev.tailDist);
2078 final int endDist=Tools.min(v.endDist, prev.endDist);
2079
2080
2081 Varlet v2=new Varlet(read.chrom, read.strand(), prev.beginLoc, v.endLoc, prev.matchStart, v.matchStop, varType,
2082 rs, cs, (prev.avgVarQuality()+v.avgVarQuality())/2, readQuality, read.mapScore, read.errors, expectedErrors,
2083 (read.paired() ? 1 : 0), read.numericID, read.length(),
2084 read.start, read.stop, read.copies, headDist, tailDist, endDist, read.pairnum());
2085
2086 vars.remove(i); //prev
2087 vars.add(v2);
2088 }else{
2089 list2.add(v);
2090 }
2091 }
2092 assert(vars.size()==1);
2093 list2.add(vars.get(0));
2094 Collections.reverse(list2);
2095 vars=list2;
2096
2097 if(verbose){
2098 System.err.println("Condensed:");
2099 for(Varlet v : vars){
2100 System.err.println(v);
2101 }
2102 System.err.println();
2103 }
2104 }
2105 }
2106
2107 // {
2108 // int nr=0;
2109 // for(Variation v : vars){
2110 // if(v.varType==Variation.NOREF){
2111 // nr++;
2112 // }
2113 // }
2114 // System.err.println(" "+nr);
2115 // }
2116 //
2117 // assert(!fail);
2118
2119 // assert(read.numericID!=3448228) : CONDENSE+"\n"+vars;
2120
2121 //assert(checkArray(call));
2122 //Don't exit early and forget to undo this!
2123 if(read.strand()==Shared.MINUS){
2124 AminoAcid.reverseComplementBasesInPlace(call);
2125 Tools.reverseInPlace(quality);
2126 }
2127 //assert(checkArray(call));
2128 return vars;
2129 }
2130
2131
2132 public MSA msaBS;
2133
2134 public static boolean verbose=false;
2135
2136 public static boolean DISCARD_NOCALLED_INSERTIONS=false;
2137 public static boolean THROW_EXCEPTION_ON_VERIFY_FAILURE=true; //Throws an exception when "verify match string" fails
2138
2139 }