Debian Codegraph @

current/stream/SamLine.java

raw symbols SCIP
1 package stream;
2
3 import java.io.Serializable;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6
7 import dna.AminoAcid;
8 import dna.ChromosomeArray;
9 import dna.Data;
10 import dna.Gene;
11 import dna.ScafLoc;
12 import shared.KillSwitch;
13 import shared.LineParser1;
14 import shared.Parse;
15 import shared.Shared;
16 import shared.Tools;
17 import structures.ByteBuilder;
18 import var2.ScafMap;
19 import var2.Scaffold;
20
21
22 public class SamLine implements Serializable {
23
24 // 426_647_582 161 chr1 10159 0 26M9H chr3 170711991 0 TCCCTAACCCTAACCCTAACCTAACC IIFIIIIIIIIIIIIIIIIIICH2<> RG:Z:20110708003021394 NH:i:3 CM:i:2 SM:i:1 CQ:Z:A9?(BB?:<A?>=>B67=:7A);.%8'%))/%*%' CS:Z:G12002301002301002301023010200000003 XS:A:+
25
26 // 1 QNAME String [!-?A-~]f1,255g Query template NAME
27 // 2 FLAG Int [0,216-1] bitwise FLAG
28 // 3 RNAME String \*|[!-()+-<>-~][!-~]* Reference sequence NAME
29 // 4 POS Int [0,229-1] 1-based leftmost mapping POSition
30 // 5 MAPQ Int [0,28-1] MAPping Quality
31 // 6 CIGAR String \*|([0-9]+[MIDNSHPX=])+ CIGAR string
32 // 7 RNEXT String \*|=|[!-()+-<>-~][!-~]* Ref. name of the mate/next fragment
33 // 8 PNEXT Int [0,229-1] Position of the mate/next fragment
34 // 9 TLEN Int [-229+1,229-1] observed Template LENgth
35 // 10 SEQ String \*|[A-Za-z=.]+ fragment SEQuence
36 // 11 QUAL String [!-~]+ ASCII of Phred-scaled base QUALity+33
37
38
39 // FCB062MABXX:1:1101:1177:2115#GGCTACAA 147 chr11 47765857 29 90M = 47765579 -368 CCTCTGTGGCCCGGGTTGGAGTGCAGTGTCATGATCATGGCTCGCTGTAGCTACACCCTTCTGAGCTCAAGCAATCCTCCCACCTCTCCC ############################################################A@@><D<AAAB<=A2BD/BC<7:<4<%679 XT:A:M NM:i:5 SM:i:29 AM:i:29 XM:i:5 XO:i:0 XG:i:0 MD:Z:7T4A15G26A30A3
40 // FCB062MABXX:1:1101:1193:2122#GGCTACAA 77 * 0 0 * * 0 0 TATATATGTGCTATGTACAGCATTGGAATTCACACCCTACACTTTCAAAAGNGAGCCCTAAATAAATGTTAGATCGGAAGAGCACACGTC FCFCFDDDADDEDEBDAEDFEDEFFGGFGGHEEFHHHHHHEDDDEDFFEFB#CBBA@B8BGGFGEEEC>DGGGDFBGGGGHHHHH9<@##
41
42
43 /*--------------------------------------------------------------*/
44 /*---------------- Initialization ----------------*/
45 /*--------------------------------------------------------------*/
46
47 /**
48 *
49 */
50 private static final long serialVersionUID = -4180486051387471116L;
51
52 public SamLine(String s){//TODO: Change to LineParser version
53 this(s.split("\t"));
54 }
55
56 public SamLine(SamLine sl){
57 setFrom(sl);
58 }
59
60 // /** Prevents references to original string, in case of e.g. very long MD tags. */
61 // public SamLine toSamLine(String s){
62 // String[] split=s.split("\t");
63 // split[0]=new String(split[0]);
64 // split[5]=new String(split[5]);
65 // split[9]=new String(split[9]);
66 // split[10]=new String(split[10]);
67 // for(int i=11; i<split.length; i++){
68 // split[i]=new String(split[i]);
69 // }
70 // return new SamLine(split);
71 // }
72
73 private void setFrom(SamLine sl){
74 qname=sl.qname;
75 flag=sl.flag;
76 rname=sl.rname;
77 rnameS=sl.rnameS;
78 pos=sl.pos;
79 mapq=sl.mapq;
80 cigar=sl.cigar;
81 rnext=sl.rnext;
82 pnext=sl.pnext;
83 tlen=sl.tlen;
84 seq=sl.seq;
85 qual=sl.qual;
86 optional=sl.optional;
87 }
88
89
90 public SamLine(Read r1, int fragNum){
91
92 if(verbose){
93 System.err.println("new SamLine for read with match "+(r1.match==null ? "null" : new String(r1.match)));
94 }
95
96 Read r2=r1.mate;
97 final boolean perfect=r1.perfect();
98
99 if(Data.scaffoldLocs==null && r1.samline!=null){
100 assert(SET_FROM_OK) : "Sam format cannot be used as input to this program when no genome build is loaded.\n" +
101 "Please index the reference first and rerun with e.g. 'build=1', or use a different input format.";
102 setFrom(r1.samline);
103 return;
104 }
105
106 // qname=r.id.replace(' ', '_').replace('\t', '_');
107 // qname=r.id.split("\\s+")[0];
108 qname=r1.id.replace('\t', '_');
109 // if(!KEEP_NAMES && qname.length()>2 && r2!=null){
110 // if(qname.endsWith("/1") || qname.endsWith("/2") || qname.endsWith(" 1") || qname.endsWith(" 2")){}
111 // }
112
113 if(!KEEP_NAMES && qname.length()>2 && r2!=null){
114 char c=qname.charAt(qname.length()-2);
115 int num=(qname.charAt(qname.length()-1))-'1';
116 if((num==0 || num==1) && (c==' ' || c=='/')){qname=qname.substring(0, qname.length()-2);}
117 // if(r.pairnum()==num && (c==' ' || c=='/')){qname=qname.substring(0, qname.length()-2);}
118 }
119 // flag=Integer.parseInt(s[1]);
120
121 int idx1=-1, idx2=-1;
122 int chrom1=-1, chrom2=-1;
123 int start1=-1, start2=-1, a1=0, a2=0;
124 int stop1=-1, stop2=-1, b1=0, b2=0;
125 int scaflen=0, scafloc=0, scaflen2=0;
126 byte[] name1=bytestar, name2=bytestar;
127 if(r1.mapped()){
128 assert(r1.chrom>=0) : r1.chrom+", "+r1.start+", "+r1.stop;
129 chrom1=r1.chrom;
130 start1=r1.start;
131 stop1=r1.stop;
132 if(Data.isSingleScaffold(chrom1, start1, stop1)){
133 assert(Data.scaffoldLocs!=null) : "\n\n"+r1+"\n\n"+r1.obj+"\n\n";
134 idx1=Data.scaffoldIndex(chrom1, (start1+stop1)/2);
135 name1=Data.scaffoldNames[chrom1][idx1];
136 scaflen=Data.scaffoldLengths[chrom1][idx1];
137 scafloc=Data.scaffoldLocs[chrom1][idx1];
138 a1=Data.scaffoldRelativeLoc(chrom1, start1, idx1);
139 b1=a1-start1+stop1;
140 }else{
141 if(verbose){System.err.println("------------- Found multi-scaffold alignment! -------------");}
142 r1.setMapped(false);
143 r1.setPaired(false);
144 r1.match=null;
145 if(r2!=null){r2.setPaired(false);}
146 }
147 }
148 if(r2!=null && r2.mapped()){
149 chrom2=r2.chrom;
150 start2=r2.start;
151 stop2=r2.stop;
152 if(Data.isSingleScaffold(chrom2, start2, stop2)){
153 idx2=Data.scaffoldIndex(chrom2, (start2+stop2)/2);
154 name2=Data.scaffoldNames[chrom2][idx2];
155 scaflen2=Data.scaffoldLengths[chrom2][idx2];
156 a2=Data.scaffoldRelativeLoc(chrom2, start2, idx2);
157 b2=a2-start2+stop2;
158 }else{
159 if(verbose){System.err.println("------------- Found multi-scaffold alignment for r2! -------------");}
160 r2.setMapped(false);
161 r2.setPaired(false);
162 r2.match=null;
163 if(r1!=null){r1.setPaired(false);}
164 }
165 }
166
167 final boolean sameScaf=(r2!=null && idx1>-1 && idx1==idx2 && r1.chrom==r2.chrom);
168 flag=makeFlag(r1, r2, fragNum, sameScaf);
169
170 rname=r1.mapped() ? name1 : ((r2!=null && r2.mapped()) ? name2 : null);
171
172 {
173 int pos0, pos0_mate; //start pos
174 int pos1, pos1_mate; //stop pos
175
176 if(r1.mapped()){
177 // int leadingClip=countLeadingClip(cigar);
178 int clip=countLeadingClip(r1.match);
179 int clippedIndels=countLeadingIndels(a1, r1.match);
180 int tclip=countTrailingClip(r1.match);
181 int tclippedIndels=countTrailingIndels(b1, scaflen, r1.match);
182
183 if(verbose){
184 System.err.println("leadingClip="+clip);
185 System.err.println("clippedDels="+clippedIndels);
186 }
187 pos0=(a1+1)+clip+clippedIndels;
188 pos1=(b1+1)-tclip-tclippedIndels;
189 if(pos1>scaflen){pos1=scaflen;}
190
191 if(pos0<1){
192 //This is necessary to prevent mapped reads from having POS less than 1.
193 pos0=1;
194 }
195 assert(pos1>=pos0) : pos0+", "+pos1+"\n"+r1+"\n"+r2+"\n";
196
197 }else{
198 pos0=0;
199 pos1=0;
200 }
201
202 if(r2!=null && r2.mapped()){
203 int clip=countLeadingClip(r2.match);
204 int clippedIndels=countLeadingIndels(a2, r2.match);
205 int tclip=countTrailingClip(r2.match);
206 int tclippedIndels=countTrailingIndels(b2, scaflen, r2.match);
207 if(verbose){
208 System.err.println("leadingClip="+clip);
209 System.err.println("clippedDels="+clippedIndels);
210 }
211 pos0_mate=(a2+1)+clip+clippedIndels;
212 pos1_mate=(b2+1)-tclip-tclippedIndels;
213 if(pos1_mate>scaflen){pos1=scaflen;}
214
215 if(pos0_mate<1){
216 //This is necessary to prevent mapped reads from having POS less than 1.
217 pos0_mate=1;
218 }
219 assert(!sameScaf || pos1_mate>=pos0_mate) : pos0_mate+", "+pos1_mate+", "+scaflen+"\n"+r1+"\n"+r2+"\n";
220
221 }else{
222 pos0_mate=0;
223 pos1_mate=0;
224 }
225
226 if(r2==null){
227 pos=pos0;
228 pnext=pos0_mate;
229 tlen=0;
230 assert(((pos>0 && r1.mapped()) || (pos==0 && !r1.mapped())) && pnext==0);
231 }else{
232 if(r1.mapped() && r2.mapped()){
233 pos=pos0;
234 pnext=pos0_mate;
235 if(sameScaf){
236 // tlen=1+(Data.max(r.stop, r2.stop)-Data.min(r.start, r2.start));
237 tlen=1+(Data.max(pos1, pos1_mate)-Data.min(pos0, pos0_mate));
238 }else{
239 tlen=0;
240 }
241 assert(pos>0) : pos+"\n"+r1+"\n"+r2;
242 assert(pnext>0) : pnext+"\n"+r1+"\n"+r2;
243 }else if(r1.mapped() && !r2.mapped()){
244 pos=pos0;
245 pnext=pos0;
246 tlen=0;
247 assert(pos>0 && pnext>0);
248 }else if(!r1.mapped() && r2.mapped()){
249 pos=pos0_mate;
250 pnext=pos0_mate;
251 tlen=0;
252 assert(pos>0 && pnext>0);
253 }else if(!r1.mapped() && !r2.mapped()){
254 pos=pos0;
255 pnext=pos0_mate;
256 tlen=0;
257 assert(pos==0 && pnext==0);
258 }else{assert(false);}
259 }
260
261 assert(pos>=0) : "Negative coordinate "+pos+" for read:\n\n"+r1+"\n\n"+r2+"\n\n"+this+"\n\na1="+a1+", a2="+a2+
262 ", pos0="+pos0+", pos0_mate="+pos0_mate+", clip="+countLeadingClip(cigar, true, false)+", clipM="+countLeadingClip(r1.match);
263 assert(pnext>=0) : "Negative coordinate "+pnext+" for mate:\n\n"+r1+"\n\n"+r2+"\n\n"+this+"\n\na1="+a1+", a2="+a2+
264 ", pos0="+pos0+", pos0_mate="+pos0_mate+", clip="+countLeadingClip(cigar, true, false);
265 }
266
267 mapq=toMapq(r1, null);
268
269 if(verbose){
270 System.err.println("Making cigar for "+(r1.match==null ? "null" : new String(r1.match)));
271 }
272
273 final boolean inbounds=!r1.mapped() ? false : (a1>=0 && b1<scaflen);
274 final boolean inbounds2=(r2==null ? true : !r2.mapped() ? false : (a2>=0 && b2<scaflen2));
275 if(r1.bases!=null && r1.mapped() && r1.match!=null){
276 if(VERSION>1.3f){
277 if(inbounds && perfect && !r1.containsNonM()){//r.containsNonM() should be unnecessary... it's there in case of clipping...
278 cigar=(r1.length()+"=");
279 // System.err.println("SETTING cigar14="+cigar);
280 //
281 // byte[] match=r.match;
282 // if(r.shortmatch()){match=Read.toLongMatchString(match);}
283 // cigar=toCigar13(match, a1, b1, scaflen, r.bases);
284 // System.err.println("RESETTING cigar14="+cigar+" from toCigar14("+new String(Read.toShortMatchString(match))+", "+a1+", "+b1+", "+scaflen+", "+r.bases+")");
285 }else{
286 byte[] match=r1.match;
287 if(r1.shortmatch()){match=Read.toLongMatchString(match);}
288 cigar=toCigar14(match, a1, b1, scaflen, r1.bases);
289 // System.err.println("CALLING toCigar14("+Read.toShortMatchString(match)+", "+a1+", "+b1+", "+scaflen+", "+r.bases+")");
290 }
291 }else{
292 if(inbounds && (perfect || !r1.containsNonNMS())){
293 cigar=(r1.length()+"M");
294 // System.err.println("SETTING cigar13="+cigar);
295 //
296 // byte[] match=r.match;
297 // if(r.shortmatch()){match=Read.toLongMatchString(match);}
298 // cigar=toCigar13(match, a1, b1, scaflen, r.bases);
299 // System.err.println("RESETTING cigar13="+cigar+" from toCigar13("+new String(Read.toShortMatchString(match))+", "+a1+", "+b1+", "+scaflen+", "+r.bases+")");
300 }else{
301 byte[] match=r1.match;
302 if(r1.shortmatch()){match=Read.toLongMatchString(match);}
303 cigar=toCigar13(match, a1, b1, scaflen, r1.bases);
304 // System.err.println("CALLING toCigar13("+Read.toShortMatchString(match)+", "+a1+", "+b1+", "+scaflen+", "+r.bases+")");
305 }
306 }
307 }
308
309 if(verbose){
310 System.err.println("cigar="+cigar);
311 }
312
313 // assert(false);
314
315 // assert(primary() || cigar.equals(stringstar)) : cigar;
316 // if(pos<0){pos=0;cigar=null;rname=bytestar;mapq=0;flag|=0x4;}
317
318 // assert(false) : "\npos="+pos+"\ncigar='"+cigar+"'\nVERSION="+VERSION+"\na1="+a1+", b1="+b1+"\n\n"+r.toString();
319
320 // rnext=(r2==null ? stringstar : (r.mapped() && !r2.mapped()) ? "chr"+Gene.chromCodes[r.chrom] : "chr"+Gene.chromCodes[r2.chrom]);
321 rnext=((r2==null || (!r1.mapped() && !r2.mapped())) ? bytestar : (r1.mapped() && r2.mapped()) ? (sameScaf ? byteequals : name2) : byteequals);
322
323 assert(rnext!=byteequals || name1==name2 || name1==bytestar || name2==bytestar) :
324 new String(rname)+", "+new String(rnext)+", "+new String(name1)+", "+new String(name2)+"\n"+r1+"\n"+r2;
325
326 // assert(r1.pairnum()==0) : r1.mapped()+", "+r2.mapped()+"fragNum="+fragNum+
327 // "\nname1="+new String(name1)+"\nname2="+new String(name2)+"\nrname="+new String(rname)+"\nrnext="+new String(rnext)+
328 // "\nname1="+name1+"\nname2="+name2+"\nrname="+rname+"\nrnext="+rnext+"\nidx1="+idx1+"\nidx2="+idx2;
329
330 if(Data.scaffoldPrefixes){
331 if(rname!=null && rname!=bytestar){
332 int k=Tools.indexOf(rname, (byte)'$');
333 rname=KillSwitch.copyOfRange(rname, k+1, rname.length);
334 }
335 if(rnext!=null && rnext!=bytestar){
336 int k=Tools.indexOf(rnext, (byte)'$');
337 rnext=KillSwitch.copyOfRange(rnext, k+1, rnext.length);
338 }
339 }
340
341 // if(r2==null || r.stop<=r2.start){
342 // //plus sign
343 // }else if(r2.stop<=r.start){
344 // //minus sign
345 // tlen=-tlen;
346 // }else{
347 // //They overlap... a lot. Physically shorter than read length.
348 // if(r.start<=r2.start){
349 //
350 // }else{
351 // tlen=-tlen;
352 // }
353 // }
354 //This version is less technically correct (does not account for very short insert reads) but probably more in line with what is expected
355 if(r2==null || r1.start<r2.start || (r1.start==r2.start && r1.pairnum()==0)){
356 //plus sign
357 }else{
358 //minus sign
359 tlen=-tlen;
360 }
361
362 // if(r.secondary()){
363 //// seq=qual=stringstar;
364 // seq=qual=bytestar;
365 // }else{
366 // if(r.strand()==Gene.PLUS){
367 //// seq=new String(r.bases);
368 // seq=r.bases.clone();
369 // if(r.quality==null){
370 //// qual=stringstar;
371 // qual=bytestar;
372 // }else{
373 //// StringBuilder q=new StringBuilder(r.quality.length);
374 //// for(byte b : r.quality){
375 //// q.append((char)(b+33));
376 //// }
377 //// qual=q.toString();
378 // qual=new byte[r.quality.length];
379 // for(int i=0, j=qual.length-1; i<qual.length; i++, j--){
380 // qual[i]=(byte)(r.quality[j]+33);
381 // }
382 // }
383 // }else{
384 //// seq=new String(AminoAcid.reverseComplementBases(r.bases));
385 // seq=AminoAcid.reverseComplementBases(r.bases);
386 // if(r.quality==null){
387 //// qual=stringstar;
388 // qual=bytestar;
389 // }else{
390 //// StringBuilder q=new StringBuilder(r.quality.length);
391 //// for(int i=r.quality.length-1; i>=0; i--){
392 //// q.append((char)(r.quality[i]+33));
393 //// }
394 //// qual=q.toString();
395 // qual=new byte[r.quality.length];
396 // for(int i=0, j=qual.length-1; i<qual.length; i++, j--){
397 // qual[i]=(byte)(r.quality[j]+33);
398 // }
399 // }
400 // }
401 // }
402
403 if(r1.secondary() && SECONDARY_ALIGNMENT_ASTERISKS){
404 // seq=qual=bytestar;
405 seq=qual=null;
406 }else{
407 seq=r1.bases;
408 if(r1.quality==null){
409 // qual=bytestar;
410 qual=null;
411 }else{
412 qual=r1.quality;
413 }
414 }
415
416 trimNames();
417 optional=makeOptionalTags(r1, r2, perfect, scafloc, scaflen, inbounds, inbounds2);
418 // assert(r.pairnum()==1) : "\n"+r.toText(false)+"\n"+this+"\n"+r2;
419 }
420
421 public SamLine(String[] s){
422 assert(!s[0].startsWith("@")) : "Tried to make a SamLine from a header: "+s[0];
423 assert(s.length>=11) : "\nNot all required fields are present: "+s.length+"\nline='"+Arrays.toString(s)+"'\n";
424 if(s.length<11){
425 System.err.println("Invalid SamLine: "+Arrays.toString(s));
426 return;
427 }
428 qname=s[0];
429 flag=Integer.parseInt(s[1]);
430 if(RNAME_AS_BYTES){
431 rname=s[2].getBytes();
432 }else{
433 rnameS=s[2];
434 }
435 pos=Integer.parseInt(s[3]);
436 // try {
437 // Integer.parseInt(s[4]);
438 // } catch (NumberFormatException e) {
439 // System.err.println(Arrays.toString(s));
440 // }
441 mapq=Tools.isDigit(s[4].charAt(0)) ? Integer.parseInt(s[4]) : 99; //Added for non-compliant mappers that put * here
442 cigar=s[5];
443 rnext=s[6].getBytes();
444 pnext=(s[7].charAt(0)=='*' ? 0 : Integer.parseInt(s[7]));
445 tlen=Tools.isDigit(s[8].charAt(0)) ? Integer.parseInt(s[8]) : 0; //Added for non-compliant mappers that put * here
446 // seq=s[9];
447 // qual=s[10];
448 seq=(s[9].equals(stringstar) ? null : s[9].getBytes());
449 qual=(s[10].equals(stringstar) ? null : s[10].getBytes());
450
451 if(mapped() && strand()==Shared.MINUS){
452 if(seq!=bytestar){AminoAcid.reverseComplementBasesInPlace(seq);}
453 if(qual!=bytestar){Tools.reverseInPlace(qual);}
454 }
455
456 if(qual!=null && qual!=bytestar){
457 for(int i=0; i<qual.length; i++){qual[i]-=33;}
458 }
459
460 if(!PARSE_OPTIONAL || s.length<=11){return;}
461
462 if(PARSE_OPTIONAL_MD_ONLY){
463 optional=new ArrayList<String>(1);
464 for(int i=11; i<s.length; i++){
465 if(s[i].startsWith("MD:")){
466 mdTag=s[i].substring(3).getBytes();
467 optional.add(s[i]);
468 break;
469 }
470 }
471 }else{
472 optional=new ArrayList<String>(s.length-11);
473 for(int i=11; i<s.length; i++){
474 if(s[i].startsWith("MD:")){
475 mdTag=s[i].substring(3).getBytes();
476 }
477 optional.add(s[i]);
478 }
479 }
480
481 trimNames();
482 }
483
484 public SamLine(LineParser1 lp){
485 assert(!lp.startsWith('@')) : "Tried to make a SamLine from a header: "+lp.toString();
486
487 if(PARSE_0){qname=lp.parseString(0);}
488 flag=lp.parseInt(1);
489 if(PARSE_2){
490 if(RNAME_AS_BYTES){
491 rname=(lp.termEquals('*', 2)) ? null : lp.parseByteArray(2);
492 }else {
493 rnameS=(lp.termEquals('*', 2)) ? null : lp.parseString(2);
494 }
495 }
496 pos=lp.parseInt(3);
497 mapq=lp.parseInt(4);
498 if(PARSE_5){cigar=lp.parseString(5);}
499 if(PARSE_6){rnext=lp.parseByteArray(6);}
500 if(PARSE_7){pnext=lp.parseInt(7);}
501 if(PARSE_8){tlen=lp.parseInt(8);}
502 seq=lp.parseByteArray(9);
503 if(PARSE_10){qual=lp.parseByteArray(10);}
504
505 assert((seq==bytestar)==(Tools.equals(seq, bytestar)));
506 assert((qual==bytestar)==(Tools.equals(qual, bytestar)));
507
508 if(mapped() && strand()==Shared.MINUS && FLIP_ON_LOAD){
509 if(seq!=bytestar){AminoAcid.reverseComplementBasesInPlace(seq);}
510 if(qual!=bytestar){Tools.reverseInPlace(qual);}
511 }
512
513 if(qual!=null && qual!=bytestar){
514 for(int i=0; i<qual.length; i++){qual[i]-=33;}
515 }
516
517 if(PARSE_OPTIONAL && lp.terms()>11) {
518 if(PARSE_OPTIONAL_MD_ONLY){
519 optional=new ArrayList<String>(1);
520 for(int i=11, terms=lp.terms(); i<terms; i++) {
521 if(lp.termStartsWith("MD:", i)){
522 String s=lp.parseString(i);
523 optional.add(s);
524 lp.incrementA(3);
525 mdTag=lp.parseByteArrayFromCurrentField();
526 }
527 }
528 }else{
529 optional=new ArrayList<String>(lp.terms()-11);
530 for(int i=11, terms=lp.terms(); i<terms; i++) {
531 String s=lp.parseString(i);
532 optional.add(s);
533 }
534 }
535 }
536
537 trimNames();
538 }
539
540 //TODO: Should be replaced by LineParser
541 public SamLine(byte[] s){
542 assert(s[0]!='@') : "Tried to make a SamLine from a header: "+new String(s);
543
544 int a=0, b=0;
545
546 while(b<s.length && s[b]!='\t'){b++;}
547 assert(b>a) : "Missing field 0: "+new String(s);
548 if(PARSE_0){qname=(b==a+1 && s[a]=='*' ? null : new String(s, a, b-a));}
549 b++;
550 a=b;
551
552 while(b<s.length && s[b]!='\t'){b++;}
553 assert(b>a) : "Missing field 1: "+new String(s);
554 flag=Parse.parseInt(s, a, b);
555 b++;
556 a=b;
557
558 while(b<s.length && s[b]!='\t'){b++;}
559 assert(b>a) : "Missing field 2: "+new String(s);
560 if(PARSE_2){
561 if(RNAME_AS_BYTES){
562 rname=(b==a+1 && s[a]=='*' ? null : KillSwitch.copyOfRange(s, a, b));
563 }else{
564 rnameS=(b==a+1 && s[a]=='*' ? null : new String(s, a, b-a));
565 }
566 }
567 b++;
568 a=b;
569
570 while(b<s.length && s[b]!='\t'){b++;}
571 assert(b>a) : "Missing field 3: "+new String(s);
572 pos=Parse.parseInt(s, a, b);
573 b++;
574 a=b;
575
576 while(b<s.length && s[b]!='\t'){b++;}
577 assert(b>a) : "Missing field 4: "+new String(s);
578 mapq=Parse.parseInt(s, a, b);
579 b++;
580 a=b;
581
582 while(b<s.length && s[b]!='\t'){b++;}
583 assert(b>a) : "Missing field 5: "+new String(s);
584 if(PARSE_5){cigar=(b==a+1 && s[a]=='*' ? null : new String(s, a, b-a));}
585 b++;
586 a=b;
587
588 while(b<s.length && s[b]!='\t'){b++;}
589 assert(b>a) : "Missing field 6: "+new String(s);
590 if(PARSE_6){rnext=(b==a+1 && s[a]=='*' ? null : KillSwitch.copyOfRange(s, a, b));}
591 b++;
592 a=b;
593
594 while(b<s.length && s[b]!='\t'){b++;}
595 assert(b>a) : "Missing field 7: "+new String(s);
596 if(PARSE_7){pnext=(b==a+1 && s[a]=='*' ? 0 :Parse.parseInt(s, a, b));}
597 b++;
598 a=b;
599
600 while(b<s.length && s[b]!='\t'){b++;}
601 assert(b>a) : "Missing field 8: "+new String(s);
602 if(PARSE_8){tlen=Parse.parseInt(s, a, b);}
603 b++;
604 a=b;
605
606 while(b<s.length && s[b]!='\t'){b++;}
607 assert(b>a) : "Missing field 9: "+new String(s);
608 // seq=new String(s, a, b-a);
609 seq=(b==a+1 && s[a]=='*' ? null : KillSwitch.copyOfRange(s, a, b));
610 b++;
611 a=b;
612
613 while(b<s.length && s[b]!='\t'){b++;}
614 assert(b>a) : "Missing field 10: "+new String(s);
615 // qual=new String(s, a, b-a);
616 if(PARSE_10){qual=(b==a+1 && s[a]=='*' ? null : KillSwitch.copyOfRange(s, a, b));}
617 b++;
618 a=b;
619
620 assert((seq==bytestar)==(Tools.equals(seq, bytestar)));
621 assert((qual==bytestar)==(Tools.equals(qual, bytestar)));
622
623 if(mapped() && strand()==Shared.MINUS && FLIP_ON_LOAD){
624 if(seq!=bytestar){AminoAcid.reverseComplementBasesInPlace(seq);}
625 if(qual!=bytestar){Tools.reverseInPlace(qual);}
626 }
627
628 if(qual!=null && qual!=bytestar){
629 for(int i=0; i<qual.length; i++){qual[i]-=33;}
630 }
631
632 if(PARSE_OPTIONAL && b<s.length) {
633 if(PARSE_OPTIONAL_MD_ONLY) {
634 optional=new ArrayList<String>(1);
635 while(b<s.length){
636 while(b<s.length && s[b]!='\t'){b++;}
637 if(b>a){
638 if(b>=a+3 && s[a]=='M' && s[a+1]=='D' && s[a+2]==':'){
639 String x=new String(s, a, b-a);
640 optional.add(x);
641 return;
642 }
643 }else{
644 //Empty field
645 }
646 b++;
647 a=b;
648 }
649 }else if(PARSE_OPTIONAL_MATEQ_ONLY) {
650 optional=new ArrayList<String>(1);
651 while(b<s.length){
652 while(b<s.length && s[b]!='\t'){b++;}
653 if(b>a){
654 if(b>=a+3 && s[a]=='Y' && s[a+1]=='Q' && s[a+2]==':'){
655 String x=new String(s, a, b-a);
656 optional.add(x);
657 return;
658 }
659 }else{
660 //Empty field
661 }
662 b++;
663 a=b;
664 }
665 }else{
666 optional=new ArrayList<String>(4);
667 while(b<s.length){
668 while(b<s.length && s[b]!='\t'){b++;}
669 if(b>a){
670 String x=new String(s, a, b-a);
671 optional.add(x);
672 }else{
673 //Empty field
674 }
675 b++;
676 a=b;
677 }
678 }
679 }
680
681 trimNames();
682 }
683
684 public void trimNames(){
685 // System.err.println();
686 // System.err.println("rname= "+new String(rname));
687 // System.err.println("qname= "+new String(qname));
688 if(Shared.TRIM_RNAME){
689 if(RNAME_AS_BYTES){
690 setRname(Tools.trimToWhitespace(rname()));
691 setRnext(Tools.trimToWhitespace(rnext()));
692 }else{
693 setRname(Tools.trimToWhitespace(rnameS()));
694 setRnext(Tools.trimToWhitespace(rnext()));
695 }
696 }
697 if(Shared.TRIM_READ_COMMENTS){
698 qname=(Tools.trimToWhitespace(qname));
699 }
700 // System.err.println("rname2="+new String(rname));
701 // System.err.println("qname2="+new String(qname));
702 // assert(false) : Shared.TRIM_RNAME+", "+Shared.TRIM_READ_COMMENTS+", "+new String(rname)+", "+qname;
703 }
704
705 public static final int parseFlagOnly(byte[] s){
706 assert(s!=null && s.length>0) : "Blank line.";
707 if(s[0]=='@'){return -1;}
708
709 int a=0, b=0;
710
711 while(b<s.length && s[b]!='\t'){b++;}
712 assert(b>a) : "Missing field 0: "+new String(s);
713 b++;
714 a=b;
715
716 while(b<s.length && s[b]!='\t'){b++;}
717 assert(b>a) : "Missing field 1: "+new String(s);
718 int flag=Parse.parseInt(s, a, b);
719 return flag;
720 }
721
722 public static final String parseNameOnly(byte[] s){
723 assert(s!=null && s.length>0) : "Blank line.";
724 if(s[0]=='@'){return null;}
725
726 int a=0, b=0;
727
728 while(b<s.length && s[b]!='\t'){b++;}
729 assert(b>a) : "Missing field 0: "+new String(s);
730 String qname=(b==a+1 && s[a]=='*' ? null : new String(s, a, b-a));
731 return qname;
732 }
733
734 /*--------------------------------------------------------------*/
735 /*---------------- Cigar ----------------*/
736 /*--------------------------------------------------------------*/
737
738 public static String toCigar13(byte[] match, int readStart, int readStop, long reflen, byte[] bases){
739 if(match==null || readStart==readStop){return null;}
740 ByteBuilder sb=new ByteBuilder(8);
741 int count=0;
742 char mode='=';
743 char lastMode='=';
744
745 int refloc=readStart;
746
747 int cigarlen=0; //for debugging
748 int opcount=0; //for debugging
749
750 for(int mpos=0; mpos<match.length; mpos++){
751
752 byte m=match[mpos];
753
754 boolean sfdflag=false;
755 if(SOFT_CLIP && (refloc<0 || refloc>=reflen)){
756 mode='S'; //soft-clip out-of-bounds
757 if(m!='I'){refloc++;}
758 if(m=='D'){sfdflag=true;} //Don't add soft-clip count for deletions!
759 }else if(m=='m' || m=='s' || m=='S' || m=='N' || m=='B'){//Little 's' is for a match classified as a sub to improve the affine score.
760 mode='M';
761 refloc++;
762 }else if(m=='I' || m=='X' || m=='Y'){
763 mode='I';
764 }else if(m=='D'){
765 mode='D';
766 refloc++;
767 }else if(m=='C'){
768 mode='S';
769 refloc++;
770 }else{
771 throw new RuntimeException("Invalid match string character '"+(char)m+"' = "+m+" (ascii). " +
772 "Match string should be in long format here.");
773 }
774
775 if(mode!=lastMode){
776 if(count>0){//Prevents an initial length-0 match
777 sb.append(count);
778 // sb.append(lastMode);
779 if(lastMode=='D' && count>INTRON_LIMIT){sb.append('N');}
780 else{sb.append(lastMode);}
781 if(lastMode!='D'){cigarlen+=count;}
782 opcount+=count;
783 }
784 count=0;
785 lastMode=mode;
786 }
787
788 count++;
789 if(sfdflag){count--;}
790 }
791 sb.append(count);
792 if(mode=='D' && count>INTRON_LIMIT){sb.append('N');}
793 else{sb.append(mode);}
794 if(mode!='D'){cigarlen+=count;}
795 opcount+=count;
796
797 assert(bases==null || cigarlen==bases.length) : "\n(cigarlen = "+cigarlen+") != (bases.length = "+(bases==null ? -1 : bases.length)+")\n" +
798 "cigar = "+sb+"\nmatch = "+new String(match)+"\nbases = "+new String(bases)+"\n";
799
800 return sb.toString();
801 }
802
803 public static String toCigar13(String cigar14) {
804 if(cigar14==null){return null;}
805 final int len=cigar14.length();
806
807 int current=0;
808 int mcount=0;
809 ByteBuilder sb=new ByteBuilder(len);
810
811 for(int i=0; i<len; i++){
812 char b=cigar14.charAt(i);
813 if(Tools.isDigit(b)){
814 current=(10*current)+(b-'0');
815 }else{
816 if(b=='X' || b=='=' || b=='M'){
817 mcount+=current;
818 }else{
819 if(mcount>0){
820 sb.append(mcount);
821 sb.append('M');
822 mcount=0;
823 }
824 sb.append(current);
825 sb.append(b);
826 }
827 current=0;
828 }
829 }
830 assert(current==0);
831 if(mcount>0){
832 sb.append(mcount);
833 sb.append('M');
834 mcount=0;
835 }
836 return sb.toString();
837 }
838
839
840 public static String toCigar14(byte[] match, int readStart, int readStop, long reflen, byte[] bases){
841 // assert(false) : readStart+", "+readStop+", "+reflen;
842 if(match==null || readStart==readStop){return null;}
843 ByteBuilder sb=new ByteBuilder(8);
844 int count=0;
845 char mode='=';
846 char lastMode='=';
847
848 int refloc=readStart;
849
850 int cigarlen=0; //for debugging
851 int opcount=0; //for debugging
852
853 for(int mpos=0; mpos<match.length; mpos++){
854
855 byte m=match[mpos];
856
857 boolean sfdflag=false;
858 if(SOFT_CLIP && (refloc<0 || refloc>=reflen)){
859 mode='S'; //soft-clip out-of-bounds
860 if(m!='I'){refloc++;}
861 if(m=='D'){sfdflag=true;} //Don't add soft-clip count for deletions!
862 }else if(m=='m' || m=='s'){//Little 's' is for a match classified as a sub to improve the affine score.
863 mode='=';
864 refloc++;
865 }else if(m=='S' || m=='V'){
866 mode='X';
867 refloc++;
868 }else if(m=='I' || m=='X' || m=='Y'){
869 mode='I';
870 }else if(m=='D'){
871 mode='D';
872 refloc++;
873 }else if(m=='C'){
874 mode='S';
875 refloc++;
876 }else if(m=='N' || m=='B'){
877 mode='M';
878 refloc++;
879 }else{
880 throw new RuntimeException("Invalid match string character '"+(char)m+"' = "+m+" (ascii). " +
881 "Match string should be in long format here.");
882 }
883
884 if(mode!=lastMode){
885 if(count>0){//Prevents an initial length-0 match
886 sb.append(count);
887 if(lastMode=='D' && count>INTRON_LIMIT){sb.append('N');}
888 else{sb.append(lastMode);}
889 if(lastMode!='D'){cigarlen+=count;}
890 opcount+=count;
891 }
892 count=0;
893 lastMode=mode;
894 }
895
896 count++;
897 if(sfdflag){count--;}
898 }
899 sb.append(count);
900 if(mode=='D' && count>INTRON_LIMIT){
901 sb.append('N');
902 }else{
903 sb.append(mode);
904 }
905 if(mode!='D'){cigarlen+=count;}
906 opcount+=count;
907
908 assert(bases==null || cigarlen==bases.length) : "\n(cigarlen = "+cigarlen+") != (bases.length = "+(bases==null ? -1 : bases.length)+")\n" +
909 "cigar = "+sb+"\nmatch = "+new String(match)+"\nbases = "+new String(bases)+"\n";
910
911 return sb.toString();
912 }
913
914 public boolean cigarContainsOnlyME() {
915 if(cigar==null || cigar.length()==0){return false;}
916 for(int i=0; i<cigar.length(); i++){
917 char c=cigar.charAt(i);
918 if(Character.isDigit(c) || c=='M' || c=='='){
919 //do nothing;
920 }else{
921 return false;
922 }
923 }
924 return true;
925 }
926
927 public int calcCigarLength(boolean includeSoftClip, boolean includeHardClip){
928 return calcCigarLength(cigar, includeSoftClip, includeHardClip);
929 }
930
931 public int calcCigarReadLength(boolean includeSoftClip, boolean includeHardClip){
932 return calcCigarReadLength(cigar, includeSoftClip, includeHardClip);
933 }
934
935 /** Reference length of cigar string */
936 public static int calcCigarLength(String cigar, boolean includeSoftClip, boolean includeHardClip){
937 if(cigar==null){return 0;}
938 int len=0;
939 int current=0;
940 for(int i=0; i<cigar.length(); i++){
941 char c=cigar.charAt(i);
942 if(Tools.isDigit(c)){
943 current=(current*10)+(c-'0');
944 }else{
945 if(c=='M' || c=='=' || c=='X' || c=='D' || c=='N'){
946 len+=current;
947 }else if(c=='S'){
948 if(includeSoftClip){len+=current;}
949 }else if (c=='H'){
950 //In this case, the base string is the wrong length since letters were truncated.
951 //Therefore, the bases cannot be used for calling variations after mapping.
952 //Hard clipping messes up original location verification.
953 //Therefore... len+=current would be best in practice, but for GRADING purposes, leaving it disabled is best.
954
955 if(includeHardClip){len+=current;}
956 }else if(c=='I'){
957 //do nothing
958 }else if(c=='P'){
959 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
960 //'P' is currently poorly defined
961 }else{
962 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
963 }
964 current=0;
965 }
966 }
967 return len;
968 }
969
970 /** Reference length of cigar string */
971 public static int calcCigarReadLength(String cigar, boolean includeSoftClip, boolean includeHardClip){
972 if(cigar==null){return 0;}
973 int len=0;
974 int current=0;
975 for(int i=0; i<cigar.length(); i++){
976 char c=cigar.charAt(i);
977 if(Tools.isDigit(c)){
978 current=(current*10)+(c-'0');
979 }else{
980 if(c=='M' || c=='=' || c=='X' || c=='I'){
981 len+=current;
982 }else if(c=='S'){
983 if(includeSoftClip){len+=current;}
984 }else if (c=='H'){
985 //In this case, the base string is the wrong length since letters were truncated.
986 //Therefore, the bases cannot be used for calling variations after mapping.
987 //Hard clipping messes up original location verification.
988 //Therefore... len+=current would be best in practice, but for GRADING purposes, leaving it disabled is best.
989
990 if(includeHardClip){len+=current;}
991 }else if(c=='D' || c=='N'){
992 //do nothing
993 }else if(c=='P'){
994 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
995 //'P' is currently poorly defined
996 }else{
997 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
998 }
999 current=0;
1000 }
1001 }
1002 return len;
1003 }
1004
1005 /** Number of query bases in cigar string */
1006 public static int calcCigarBases(String cigar, boolean includeSoftClip, boolean includeHardClip){
1007 if(cigar==null){return 0;}
1008 int len=0;
1009 int current=0;
1010 for(int i=0; i<cigar.length(); i++){
1011 char c=cigar.charAt(i);
1012 if(Tools.isDigit(c)){
1013 current=(current*10)+(c-'0');
1014 }else{
1015 if(c=='M' || c=='=' || c=='X' || c=='I'){
1016 len+=current;
1017 }else if(c=='D' || c=='N'){
1018 //do nothing
1019 }else if (c=='H'){
1020 if(includeHardClip){len+=current;}
1021 }else if(c=='S'){
1022 if(includeSoftClip){len+=current;}
1023 }else if(c=='P'){
1024 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
1025 //'P' is currently poorly defined
1026 }else{
1027 throw new RuntimeException("Unhandled cigar symbol: "+c+"\n"+cigar+"\n");
1028 }
1029 current=0;
1030 }
1031 }
1032 return len;
1033 }
1034
1035 /** Length of clipped initial bases. Used to calculate correct start location of clipped reads. */
1036 public static int countLeadingClip(String cigar, boolean includeSoftClip, boolean includeHardClip){
1037 if(cigar==null || (!includeSoftClip && !includeHardClip)){return 0;}
1038 int len=0;
1039 int current=0;
1040 for(int i=0; i<cigar.length(); i++){
1041 char c=cigar.charAt(i);
1042 if(Tools.isLetter(c) || c=='='){
1043 if(c=='H'){
1044 if(includeHardClip){
1045 len+=current;
1046 }
1047 }else if(c=='S'){
1048 if(includeSoftClip){
1049 len+=current;
1050 }
1051 }else{
1052 break;
1053 }
1054 current=0;
1055 }else{
1056 current=(current*10)+(c-'0');
1057 }
1058 }
1059 return len;
1060 }
1061
1062 /** Length of clipped final bases. Used to calculate correct stop location of clipped reads. */
1063 public static int countTrailingClip(String cigar, boolean includeSoftClip, boolean includeHardClip){
1064 if(cigar==null || (!includeSoftClip && !includeHardClip)){return 0;}
1065 int len=0;
1066 if(includeHardClip){len+=countTrailingHardClip(cigar);}
1067 int last=cigar.lastIndexOf('S');
1068
1069 int mult=1;
1070 int i;
1071 for(i=last-1; i>=0; i--){
1072 char c=cigar.charAt(i);
1073 if(Tools.isLetter(c) || c=='='){
1074 break;
1075 }
1076 len+=(len+(c-'0')*mult);
1077 mult*=10;
1078 }
1079 if(i<0){return 0;}
1080 return len;
1081 }
1082
1083 /** Length of clipped final bases. Used to calculate correct stop location of clipped reads. */
1084 public static int countTrailingHardClip(String cigar){
1085 if(cigar==null){return 0;}
1086 int last=cigar.lastIndexOf('H');
1087
1088 int mult=1, len=0;
1089 int i;
1090 for(i=last-1; i>=0; i--){
1091 char c=cigar.charAt(i);
1092 if(Tools.isLetter(c) || c=='='){
1093 break;
1094 }
1095 len+=(len+(c-'0')*mult);
1096 mult*=10;
1097 }
1098 if(i<0){return 0;}
1099 return len;
1100 }
1101
1102 public static int countMdSubs(String mdTag){
1103 assert(mdTag!=null);
1104
1105 final int NORMAL=0, SUB=1, DEL=2;
1106 int dels=0, subs=0, normals=0;
1107
1108 if(mdTag!=null){
1109 int current=0;
1110 int mode=NORMAL;
1111 int i=0;
1112 if(mdTag.startsWith("MD:Z:")){i=5;}
1113 for(final int max=mdTag.length(); i<max; i++){
1114 char c=mdTag.charAt(i);
1115 if(Tools.isDigit(c)){
1116 current=(current*10)+(c-'0');
1117 mode=NORMAL;
1118 }else{
1119 if(current>0){
1120 if(mode==NORMAL){normals+=current;}
1121 else{assert(false) : mode+", "+current;}
1122 current=0;
1123 }
1124 if(c=='^'){mode=DEL;}
1125 else if(mode==DEL){
1126 dels++;
1127 }else if(mode==NORMAL || mode==SUB){
1128 mode=SUB;
1129 subs++;
1130 }
1131 }
1132 }
1133 }
1134 return subs;
1135 }
1136
1137 /** Length of clipped initial bases. */
1138 public static int countLeadingClip(byte[] match){
1139 if(match==null || match.length<1 || match[0]!='C'){return 0;}
1140 int clips=0;
1141 int current=0;
1142 for(int mloc=0; mloc<match.length; mloc++){
1143 byte b=match[mloc];
1144 if(Tools.isDigit(b)){
1145 current=current*10+(b-'0');
1146 }else{
1147 if(current>0){
1148 clips=clips+current-1;
1149 }
1150 current=0;
1151 if(b!='C'){break;}
1152 clips++;
1153 }
1154 }
1155 if(current>0){
1156 clips=clips+current-1;
1157 }
1158 return clips;
1159 }
1160
1161 /** Length of match string portion describing clipped initial bases. */
1162 public static int countLeadingClip2(byte[] match){
1163 if(match==null || match.length<1 || match[0]!='C'){return 0;}
1164 int mloc=0;
1165 for(; mloc<match.length; mloc++){
1166 byte b=match[mloc];
1167 if(b!='C' && !Tools.isDigit(b)){return mloc;}
1168 }
1169 return match.length;
1170 }
1171
1172 /** Length of clipped trailing bases. */
1173 public static int countTrailingClip(byte[] match){
1174 if(match==null){return 0;}
1175 int clips=0;
1176 for(int mloc=match.length-1; mloc>=0; mloc--){
1177 byte b=match[mloc];
1178 assert(!Tools.isDigit(b)) : new String(match);
1179 if(b=='C'){
1180 clips++;
1181 }else{
1182 break;
1183 }
1184 }
1185 return clips;
1186 }
1187
1188 /** Length of clipped (out of bounds) initial insertions and deletions. */
1189 public static int countLeadingIndels(int rloc, byte[] match){
1190 if(match==null || rloc>=0){return 0;}
1191 int dels=0;
1192 int inss=0;
1193 int cloc=0;
1194 for(int mloc=0; mloc<match.length && rloc<0; mloc++){
1195 byte b=match[mloc];
1196 assert(!Tools.isDigit(b));
1197 if(b=='D'){
1198 dels++;
1199 rloc++;
1200 }else if(b=='I'){
1201 inss++;
1202 cloc++;
1203 }else{
1204 rloc++;
1205 cloc++;
1206 }
1207 }
1208 return dels-inss;
1209 }
1210
1211 /** Length of clipped (out of bounds) trialing insertions and deletions. */
1212 public static int countTrailingIndels(int rloc, int rlen, byte[] match){
1213 if(match==null || rloc>=0){return 0;}
1214 int dels=0;
1215 int inss=0;
1216 int cloc=0;
1217 for(int mloc=match.length; mloc>=0 && rloc>=rlen; mloc--){
1218 byte b=match[mloc];
1219 assert(!Tools.isDigit(b));
1220 if(b=='D'){
1221 dels++;
1222 rloc--;
1223 }else if(b=='I'){
1224 inss++;
1225 cloc--;
1226 }else{
1227 rloc--;
1228 cloc--;
1229 }
1230 }
1231 return dels-inss;
1232 }
1233
1234 public int mappedNonClippedBases() {
1235 if(!mapped() || cigar==null){return 0;}
1236
1237 int len=0;
1238 int current=0;
1239 for(int i=0; i<cigar.length(); i++){
1240 char c=cigar.charAt(i);
1241 if(Tools.isDigit(c)){
1242 current=(current*10)+(c-'0');
1243 }else{
1244 if(c=='M' || c=='='){
1245 len+=current;
1246 }else if(c=='X'){
1247 len+=current;
1248 }else if(c=='D' || c=='N'){
1249
1250 }else if(c=='I'){
1251 len+=current;
1252 }else if(c=='S' || c=='H' || c=='P'){
1253
1254 }
1255 current=0;
1256 }
1257 }
1258 return len;
1259 }
1260
1261 /**
1262 * @param cigar
1263 * @return Max consecutive match, sub, del, ins, or clip symbols
1264 */
1265 public static final int[] cigarToMdsiMax(String cigar) {
1266 if(cigar==null){return null;}
1267 int[] msdic=KillSwitch.allocInt1D(5);
1268
1269 int current=0;
1270 for(int i=0; i<cigar.length(); i++){
1271 char c=cigar.charAt(i);
1272 if(Tools.isDigit(c)){
1273 current=(current*10)+(c-'0');
1274 }else{
1275 if(c=='M' || c=='='){
1276 msdic[0]=Tools.max(msdic[0], current);
1277 }else if(c=='X'){
1278 msdic[1]=Tools.max(msdic[1], current);
1279 }else if(c=='D' || c=='N'){
1280 msdic[2]=Tools.max(msdic[2], current);
1281 }else if(c=='I'){
1282 msdic[3]=Tools.max(msdic[3], current);
1283 }else if(c=='S' || c=='H' || c=='P'){
1284 msdic[4]=Tools.max(msdic[4], current);
1285 }
1286 current=0;
1287 }
1288 }
1289 return msdic;
1290 }
1291
1292 public float calcIdentity() {
1293 assert(cigar!=null);
1294 int match=0, other=0;
1295
1296 int current=0;
1297 for(int i=0; i<cigar.length(); i++){
1298 char c=cigar.charAt(i);
1299 if(Tools.isDigit(c)){
1300 current=(current*10)+(c-'0');
1301 }else{
1302 if(c=='='){
1303 match+=current;
1304 }else if(c=='M'){
1305
1306 }else if(c=='X'){
1307 other+=current;
1308 }else if(c=='D'){
1309 other+=current;
1310 }else if(c=='N'){
1311
1312 }else if(c=='I'){
1313 other+=current;
1314 }else if(c=='S' || c=='H' || c=='P'){
1315
1316 }
1317 current=0;
1318 }
1319 }
1320 return match/(float)Tools.max(match+other, 1);
1321 }
1322
1323 public int countSubs() {
1324 if(cigar==null){return 0;}
1325
1326 int current=0;
1327 int subs=0;
1328 for(int i=0; i<cigar.length(); i++){
1329 char c=cigar.charAt(i);
1330 if(Tools.isDigit(c)){
1331 current=(current*10)+(c-'0');
1332 }else{
1333 if(c=='X'){
1334 subs+=current;
1335 }
1336 current=0;
1337 }
1338 }
1339 return subs;
1340 }
1341
1342 /**
1343 * @param cigar
1344 * @return Total number of match, sub, del, ins, or clip symbols
1345 */
1346 public static final int[] cigarToMsdic(String cigar) {
1347 if(cigar==null){return null;}
1348 int[] msdic=KillSwitch.allocInt1D(5);
1349
1350 int current=0;
1351 for(int i=0; i<cigar.length(); i++){
1352 char c=cigar.charAt(i);
1353 if(Tools.isDigit(c)){
1354 current=(current*10)+(c-'0');
1355 }else{
1356 if(c=='M' || c=='='){
1357 msdic[0]+=current;
1358 }else if(c=='X'){
1359 msdic[1]+=current;
1360 }else if(c=='D' || c=='N'){
1361 msdic[2]+=current;
1362 }else if(c=='I'){
1363 msdic[3]+=current;
1364 }else if(c=='S' || c=='H' || c=='P'){
1365 msdic[4]+=current;
1366 }
1367 current=0;
1368 }
1369 }
1370 return msdic;
1371 }
1372
1373 /**
1374 * @param allowM Allow M symbols in the cigar string
1375 * @return Match string of this cigar string when possible, otherwise null.
1376 * Takes into account MD tag and bases, but not reference (other than in MD tag).
1377 */
1378 public final byte[] toShortMatch(boolean allowM) {
1379 if(cigar==null || cigar.equals(stringstar)){return null;}
1380 if(allowM){return cigarToShortMatch_old(cigar, allowM);}
1381
1382 // System.err.println("\nInput: cigar="+cigar+", MD="+mdTag());//123
1383
1384 final boolean fixMatchSubs;
1385 final boolean fixMatchNs;
1386 boolean foundE=false;
1387 boolean foundX=false;
1388 boolean foundM=false;
1389 // System.err.println("Block 1.");//123
1390 {
1391 int current=0, total=0;
1392 for(int i=0; i<cigar.length(); i++){
1393 char c=cigar.charAt(i);
1394
1395 if(Tools.isDigit(c)){
1396 current=(current*10)+(c-'0');
1397 }else{
1398
1399 if(c=='H'){
1400 current=0; //Information destroyed
1401 }else if(c=='P'){
1402 return null; //Undefined symbol
1403 }
1404 foundE|=(c=='=');
1405 foundX|=(c=='X');
1406 foundM|=(c=='M');
1407
1408 total+=current;
1409 current=0;
1410 }
1411 }
1412 if(total<1){return null;}
1413 fixMatchSubs=(!allowM && foundM && !foundX && !foundE);//Note: allowM already exited.
1414 fixMatchNs=(FIX_MATCH_NS && foundX && !foundM); //Means no-calls are possibly marked as X, which is technically OK.
1415
1416 // System.err.println("allowM="+allowM);//123
1417 // System.err.println("foundE="+foundE);//123
1418 // System.err.println("foundX="+foundX);//123
1419 // System.err.println("foundM="+foundM);//123
1420 }
1421
1422 // System.err.println("Block 2.");//123
1423 final String mdTag;
1424 final int mdSubs;
1425 final byte[] refBases;
1426
1427 //1) if fixMatch, grab MD tag
1428 //2) if MD and no subs, return
1429 //3) grab ref bases
1430
1431 if(fixMatchSubs || fixMatchNs){
1432 final String md0=mdTag();
1433 mdSubs=(md0==null ? -1 : countMdSubs(md0));
1434 if(mdSubs==0 && !fixMatchNs){
1435 refBases=null;
1436 mdTag=null;
1437 }else{
1438 mdTag=md0;
1439 if(mdTag!=null && PREFER_MDTAG){
1440 refBases=null;
1441 }else{
1442 ScafMap map=ScafMap.defaultScafMap();
1443 assert(!fixMatchSubs || mdTag!=null || map!=null) : "TODO: Encountered a read with 'M' in cigar string but no MD tag and no ScafMap loaded.\n"
1444 + "This can normally be resolved by adding the flag ref=file, where file is the fasta file to which the reads were mapped.\n\n"+this;
1445 if(map==null){
1446 refBases=null;
1447 }else{
1448 Scaffold scaf=map.getScaffold(rnameS());
1449 assert(!fixMatchSubs || mdTag!=null || scaf!=null) : "Encountered a read with 'M' in cigar string but no scaffold loaded for "+rnameS();
1450 if(scaf==null){
1451 refBases=null;
1452 }else{
1453 refBases=scaf.bases;
1454 assert(!fixMatchSubs || mdTag!=null || refBases!=null) : "Encountered a read with 'M' in cigar string but no ref bases loaded for "+rnameS();
1455 if(fixMatchSubs && refBases==null && mdTag==null){
1456 return null;
1457 }
1458 }
1459 }
1460 }
1461 }
1462 }else{
1463 mdSubs=-1;
1464 mdTag=null;
1465 refBases=null;
1466 }
1467
1468 // System.err.println("mdTag="+mdTag);//123
1469 // System.err.println("mdSubs="+mdSubs);//123
1470
1471 char mSymbol=((foundX || foundE || !foundM) ? 'N' : mdSubs>=0 ? 'm' : 'N');
1472
1473 // System.err.println("Block 3.");//123
1474 final byte[] match0;
1475 {
1476 ByteBuilder sb=new ByteBuilder(cigar.length());
1477 int current=0;
1478 for(int cpos=0, max=cigar.length(); cpos<max; cpos++){
1479 char c=cigar.charAt(cpos);
1480 if(Tools.isDigit(c)){
1481 current=(current*10)+(c-'0');
1482 }else{
1483 if(c=='='){
1484 sb.append('m');
1485 if(current>1){sb.append(current);}
1486 }else if(c=='X'){
1487 sb.append('S');
1488 if(current>1){sb.append(current);}
1489 }else if(c=='D' || c=='N'){
1490 sb.append('D');
1491 if(current>1){sb.append(current);}
1492 }else if(c=='I'){
1493 sb.append('I');
1494 if(current>1){sb.append(current);}
1495 }else if(c=='S'){
1496 sb.append('C');
1497 if(current>1){sb.append(current);}
1498 }else if(c=='M'){
1499 sb.append(mSymbol);
1500 if(current>1){sb.append(current);}
1501 }
1502 current=0;
1503 }
1504 }
1505 match0=(sb.array.length==sb.length() ? sb.array : sb.toBytes());
1506 // System.err.println("match="+new String(match0));//123
1507 }
1508
1509 // System.err.println("Block 4.");//123
1510
1511 if((!fixMatchSubs || mdSubs==0) && (!fixMatchNs || seq==null || refBases==null)){return match0;}
1512 assert(((mdTag!=null || refBases!=null) && fixMatchSubs && mdSubs!=0) || fixMatchNs /*|| noCalls>0*/) :
1513 (mdTag!=null)+", "+(refBases!=null)+", "+(fixMatchSubs)+", "+(mdSubs!=0)+", "+fixMatchNs/*+", "+(noCalls)*/;
1514
1515 // assert(false) : mdTag+", "+refBases+", "+processMD+", "+mdSubs+"\n"+this;
1516
1517 // System.err.println("processMD="+processMD+", mdSubs="+mdSubs+", mdTag="+mdTag);//123
1518
1519 final byte[] bases;
1520 if(refBases!=null){
1521 // bases=(strand()==1) ? AminoAcid.reverseComplementBases(seq) : seq;//Why not reverse in place?
1522 if(strand()==1){AminoAcid.reverseComplementBasesInPlace(seq);}
1523 bases=seq;
1524 }else{bases=null;}
1525
1526 // System.err.println("Block 5.");//123
1527 final byte[] longmatch=Read.toLongMatchString(match0);
1528
1529 // final int noCalls=((foundE || foundX) && foundM ? 1 : seq==null ? -1 : Read.countNocalls(seq));
1530
1531 // System.err.println("Block 6");//123
1532
1533 if(mdTag!=null && (refBases==null || PREFER_MDTAG)){
1534 // System.err.println("match="+new String(longmatch));//123
1535
1536 final int noCalls=seq==null ? -1 : Read.countNocalls(seq);
1537 if(noCalls>0 && bases!=null && refBases==null){//Not necessary if ref sequence is present
1538 int bpos=0;
1539 for(int mpos=0; mpos<longmatch.length; mpos++){
1540 final byte m=longmatch[mpos];
1541 if(m=='C'){
1542 bpos++;
1543 }else if(m=='m' || m=='s' || m=='S' || m=='N'){
1544 if(!AminoAcid.isFullyDefined(bases[bpos])){longmatch[mpos]='N';}
1545 bpos++;
1546 }else if(m=='I' || m=='X' || m=='Y'){
1547 bpos++;
1548 }else if(m=='D'){
1549 //do nothing
1550 }else{
1551 assert(false) : m;
1552 }
1553 }
1554 }
1555
1556 final MDWalker walker=new MDWalker(mdTag, cigar, longmatch, this);
1557
1558 walker.fixMatch(bases);
1559 }else
1560 if(refBases!=null){
1561 final int refStart=start(true, false);
1562 fixMatch(bases, refBases, longmatch, refStart, false);
1563 }
1564
1565 // else if(refBases!=null){
1566 // final int refStart=start(true, false);
1567 // fixMatch(bases, refBases, longmatch, refStart, false);
1568 // }
1569 else{
1570 assert(false) : "Fallthorugh.";
1571 }
1572
1573 final byte[] match=Read.toShortMatchString(longmatch);
1574
1575 if(bases!=null && strand()==1){AminoAcid.reverseComplementBasesInPlace(seq);}
1576
1577 // System.err.println("Block 7.");//123
1578 // System.err.println("Returning "+new String(match));//123
1579 return match;
1580 }
1581
1582 /** Requires longmatch.
1583 * Replaces M */
1584 public static void fixMatch(byte[] call, byte[] ref, byte[] match, int refstart, boolean unClip){
1585 for(int mpos=0, rpos=refstart, cpos=0; mpos<match.length; mpos++){
1586 assert(cpos>=0 && cpos<call.length) : "\n"+new String(match)+"\n"+new String(call)+"\n"+mpos+", "+cpos;
1587 final byte m=match[mpos];
1588
1589 if(rpos<0 || rpos>=ref.length){
1590 if(m=='I'){
1591 assert(false) : "Insertion off scaffold end: "+refstart+", "+ref.length+"\n"+new String(call)+"\n"+new String(match);
1592 cpos++;
1593 }else if(m=='D'){
1594 assert(false) : "Deletion off scaffold end: "+refstart+", "+ref.length+"\n"+new String(call)+"\n"+new String(match);
1595 rpos++;
1596 }else{
1597 match[mpos]='C';
1598 rpos++;
1599 cpos++;
1600 }
1601 }else if(m=='m' || m=='S' || m=='N' || m=='s' || (m=='C' && unClip)){
1602 final byte c=Tools.toUpperCase(call[cpos]);
1603 final byte r=Tools.toUpperCase(ref[rpos]);
1604 final boolean defined=(AminoAcid.isFullyDefined(c) && AminoAcid.isFullyDefined(r));
1605 if(!defined){
1606 match[mpos]='N';
1607 }else if(c==r){
1608 match[mpos]='m';
1609 }else{
1610 match[mpos]='S';
1611 }
1612 rpos++;
1613 cpos++;
1614 }else if(m=='C'){ //Do nothing for clipped call
1615 rpos++;
1616 cpos++;
1617 }else if(m=='I' || m=='X' || m=='Y'){
1618 cpos++;
1619 }else if(m=='D'){
1620 rpos++;
1621 }else{
1622 assert(false) : Character.toString((char)m);
1623 }
1624 }
1625 }
1626
1627 /**
1628 * @param cigar
1629 * @return Match string of this cigar string when possible, otherwise null
1630 */
1631 public static final byte[] cigarToShortMatch_old(String cigar, boolean allowM) {
1632
1633 int current=0;
1634 ByteBuilder sb=new ByteBuilder(cigar.length());
1635
1636 for(int i=0; i<cigar.length(); i++){
1637 char c=cigar.charAt(i);
1638 if(Tools.isDigit(c)){
1639 current=(current*10)+(c-'0');
1640 }else{
1641 if(c=='='){
1642 sb.append('m');
1643 if(current>1){sb.append(current);}
1644 }else if(c=='X'){
1645 sb.append('S');
1646 if(current>1){sb.append(current);}
1647 }else if(c=='D' || c=='N'){
1648 sb.append('D');
1649 if(current>1){sb.append(current);}
1650 }else if(c=='I'){
1651 sb.append('I');
1652 if(current>1){sb.append(current);}
1653 }else if(c=='S'){
1654 sb.append('C');
1655 if(current>1){sb.append(current);}
1656 }else if(c=='M'){
1657 if(!allowM){return null;}
1658 // sb.append('B');
1659 sb.append('N');
1660 if(current>1){sb.append(current);}
1661 }
1662 current=0;
1663 }
1664 }
1665
1666 if(sb.array.length==sb.length()){return sb.array;}
1667 return sb.toBytes();
1668 }
1669
1670 /*--------------------------------------------------------------*/
1671 /*---------------- Tags ----------------*/
1672 /*--------------------------------------------------------------*/
1673
1674 public static String makeStopTag(int pos, int seqLength, String cigar, boolean perfect){
1675 // return "YS:i:"+(pos+((cigar==null || perfect) ? seqLength : -countLeadingClip(cigar, false)+calcCigarLength(cigar, false))-1); //123456789
1676 return "YS:i:"+(pos+((cigar==null || perfect) ? seqLength : calcCigarLength(cigar, true, false))-1);
1677 }
1678
1679 public static String makeLengthTag(int pos, int seqLength, String cigar, boolean perfect){
1680 if(cigar==null || perfect){return "YL:Z:"+seqLength+","+seqLength;}
1681 return "YL:Z:"+(seqLength-countLeadingClip(cigar, true, false))+","+calcCigarLength(cigar, false, false);
1682 }
1683
1684 public static String makeIdentityTag(byte[] match, boolean perfect){
1685 if(perfect){return "YI:f:100";}
1686 float f=Read.identity(match);
1687 return Tools.format("YI:f:%.2f", (100*f));
1688 }
1689
1690 public static String makeScoreTag(int score){
1691 return "YR:i:"+score;
1692 }
1693
1694 public String matchTag(){
1695 if(optional==null){return null;}
1696 for(String s : optional){
1697 if(s.startsWith("X2:Z:")){
1698 return s;
1699 }
1700 }
1701 return null;
1702 }
1703
1704 private String makeXSTag(Read r){
1705 if(r.mapped() && cigar!=null && cigar.indexOf('N')>=0){
1706 // System.err.println("For read "+r.pairnum()+" mapped to strand "+r.strand());
1707 boolean plus=(r.strand()==Shared.PLUS); //Assumes secondstrand=false
1708 // System.err.println("plus="+plus);
1709 if(r.pairnum()!=0){plus=!plus;}
1710 // System.err.println("plus="+plus);
1711 if(XS_SECONDSTRAND){plus=!plus;}
1712 // System.err.println("plus="+plus);
1713 return (plus ? XSPLUS : XSMINUS);
1714 }else{
1715 return null;
1716 }
1717 }
1718
1719 public static String makeMdTag(int chrom, int refstart, byte[] match, byte[] call, int scafloc, int scaflen){
1720 if(match==null || chrom<0){return null;}
1721 ByteBuilder md=new ByteBuilder(8);
1722 md.append("MD:Z:");
1723
1724 ChromosomeArray cha=Data.getChromosome(chrom);
1725
1726 final int scafstop=scafloc+scaflen;
1727
1728 byte prevM='?';
1729 int count=0;
1730 int dels=0;
1731 boolean prevSub=false;
1732 for(int mpos=0, rpos=refstart, cpos=0; mpos<match.length; mpos++){
1733 assert(cpos>=0 && cpos<call.length) : "\n"+new String(match)+"\n"+new String(call)+"\n"+mpos+", "+cpos+", "+dels+", "+INTRON_LIMIT;
1734 final byte c=call[cpos];
1735 final byte m=match[mpos];
1736
1737 if(prevM=='D' && m!='D'){
1738 if(dels<=INTRON_LIMIT){//Otherwise, ignore it
1739 md.append(count);
1740 count=0;
1741 md.append('^');
1742 for(int i=rpos-dels; i<rpos; i++){
1743 md.append((char)cha.get(i));
1744 }
1745 dels=0;
1746 }
1747 }
1748
1749 if(m=='C' || rpos<scafloc || rpos>=scafstop){ //Do nothing for clipped bases
1750 rpos++;
1751 if(m!='D'){cpos++;}
1752 }else if(m=='m' || m=='s'){
1753 count++;
1754 rpos++;
1755 cpos++;
1756 }else if(m=='S'){
1757 if(count>0 || !prevSub){md.append(count);}
1758 md.append((char)cha.get(rpos));
1759
1760 count=0;
1761 rpos++;
1762 cpos++;
1763 prevSub=true;
1764 }else if(m=='N'){
1765
1766 final byte r=cha.get(rpos);
1767
1768 if(c==r){//Act like match
1769 count++;
1770 rpos++;
1771 cpos++;
1772 }else{//Act like sub
1773 if(count>0 || !prevSub){md.append(count);}
1774 md.append((char)r);
1775
1776 count=0;
1777 rpos++;
1778 cpos++;
1779 prevSub=true;
1780 }
1781 }else if(m=='I' || m=='X' || m=='Y'){
1782 cpos++;
1783 // count++;
1784 }else if(m=='D'){
1785 // if(prevM!='D'){
1786 // md.append(count);
1787 // count=0;
1788 // md.append('^');
1789 // }
1790 // md.append((char)cha.get(rpos));
1791
1792 rpos++;
1793 dels++;
1794 }
1795 prevM=m;
1796
1797 }
1798 // if(count>0){
1799 md.append(count);
1800 // }
1801
1802 return md.toString();
1803 }
1804
1805 public static int calcLeftClip(String cig, String id){
1806 if(cig==null){return 0;}
1807 int len=0;
1808 for(int i=0; i<cig.length(); i++){
1809 char c=cig.charAt(i);
1810 if(Tools.isDigit(c)){
1811 len=len*10+(c-'0');
1812 }else{
1813 assert(c!='S' || i<cig.length()-1);//ban entirely soft-clipped reads
1814 return (c=='S') ? len : 0;
1815 }
1816 }
1817 return 0;
1818 }
1819
1820 public static int calcRightClip(String cig, String id){
1821 if(cig==null || cig.length()<1 || cig.charAt(cig.length()-1)!='S'){return 0;}
1822 int pos=cig.length()-2;
1823 for(; pos>=0 && Tools.isDigit(cig.charAt(pos)); pos--){}
1824
1825 assert(pos>0) : cig+", id="+id+", pos="+pos;//ban entirely soft-clipped reads
1826
1827 int len=0;
1828 for(int i=pos+1; i<cig.length(); i++){
1829 char c=cig.charAt(i);
1830 if(Tools.isDigit(c)){
1831 len=len*10+(c-'0');
1832 }else{
1833 return (c=='S') ? len : 0;
1834 }
1835 }
1836 return len;
1837 }
1838
1839 public ArrayList<String> makeOptionalTags(Read r, Read r2, boolean perfect, int scafloc, int scaflen, boolean inbounds, boolean inbounds2){
1840 if(NO_TAGS){return null;}
1841 final boolean mapped=r.mapped();
1842 if(!mapped && READGROUP_ID==null && !MAKE_CUSTOM_TAGS && !MAKE_TIME_TAG){return null;}
1843
1844 ArrayList<String> optionalTags=new ArrayList<String>(8);
1845
1846 if(mapped){
1847 if(!r.secondary() && r.ambiguous() && MAKE_XT_TAG){optionalTags.add("XT:A:R");} //Not sure what do do for secondary alignments
1848
1849 // int nm=r.length();
1850 // int dels=0;
1851
1852 int nm=0;
1853
1854 // //Only works for cigar strings in format 1.4+
1855 // if(perfect){nm=0;}else if(cigar!=null){
1856 // int len=0;
1857 // for(int i=0; i<cigar.length(); i++){
1858 // char c=cigar.charAt(i);
1859 // if(Tools.isDigit(c)){
1860 // len=len*10+(c-'0');
1861 // }else{
1862 // if(c=='X' || c=='I' || c=='D' || c=='M'){
1863 // nm+=len;
1864 // }
1865 // len=0;
1866 // }
1867 // }
1868 //// System.err.println("\nRead "+r.id+": nm="+nm+"\n"+cigar+"\n"+new String(r.match));
1869 // System.err.println("\nRead "+r.id+": nm="+nm);
1870 // }
1871
1872 if(perfect){nm=0;}else if(r.match!=null){
1873 nm=0;
1874 int leftclip=calcLeftClip(cigar, r.id), rightclip=calcRightClip(cigar, r.id);
1875 final int from=leftclip, to=r.length()-rightclip;
1876 int delsCurrent=0;
1877 for(int i=0, cpos=0; i<r.match.length; i++){
1878 final byte b=r.match[i];
1879
1880 // System.err.println("i="+i+", cpos="+cpos+", from="+from+", ")
1881
1882 if(cpos>=from && cpos<to){
1883 if(b=='I' || b=='S' || b=='N' || b=='X' || b=='Y'){nm++;}
1884
1885 if(b=='D'){delsCurrent++;}
1886 else{
1887 if(delsCurrent<=INTRON_LIMIT){nm+=delsCurrent;}
1888 delsCurrent=0;
1889 }
1890 }
1891 if(b!='D'){cpos++;}
1892 }
1893 if(delsCurrent<=INTRON_LIMIT){nm+=delsCurrent;}
1894 // assert(false) : nm+", "+dels+", "+delsCurrent+", "+r.length()+", "+r.match.length;
1895
1896 // assert(false) : "rlen="+r.length()+", nm="+nm+", dels="+delsCurrent+", intron="+INTRON_LIMIT+", inbound1="+inbounds+", ib2="+inbounds2+"\n"+new String(r.match);
1897
1898 // System.err.println("\nRead "+r.id+": left="+leftclip+", right="+rightclip+", nm="+nm+"\n"+cigar+"\n"+new String(r.match));
1899
1900 }
1901
1902 if(MAKE_NM_TAG){
1903 if(perfect){optionalTags.add("NM:i:0");}
1904 else if(r.match!=null){optionalTags.add("NM:i:"+(nm));}
1905 }
1906 if(MAKE_SM_TAG){optionalTags.add("SM:i:"+mapq);}
1907 if(MAKE_AM_TAG){optionalTags.add("AM:i:"+Data.min(mapq, r2==null ? mapq : (r2.mapped() ? Data.max(1, r2.mapScore/r2.length()) : 0)));}
1908
1909 if(MAKE_TOPHAT_TAGS){
1910 optionalTags.add("AS:i:0");
1911 if(cigar==null || cigar.indexOf('N')<0){
1912 optionalTags.add("XN:i:0");
1913 }else{
1914 }
1915 optionalTags.add("XM:i:0");
1916 optionalTags.add("XO:i:0");
1917 optionalTags.add("XG:i:0");
1918 if(cigar==null || cigar.indexOf('N')<0){
1919 optionalTags.add("YT:Z:UU");
1920 }else{
1921 }
1922 optionalTags.add("NH:i:1");
1923 }else if(MAKE_XM_TAG){//XM tag. For bowtie compatibility; unfortunately it is poorly defined.
1924 int x=0;
1925 if(r.discarded() || (!r.ambiguous() && !mapped)){
1926 x=0;//TODO: See if the flag needs to be present in this case.
1927 }else if(mapped){
1928 x=1;
1929 if(r.numSites()>0 && r.numSites()>0){
1930 int z=r.topSite().score;
1931 for(int i=1; i<r.sites.size(); i++){
1932 SiteScore ss=r.sites.get(i);
1933 if(ss!=null && ss.score==z){x++;}
1934 }
1935 }
1936 if(r.ambiguous()){x=Tools.max(x, 2);}
1937 }
1938 if(x>=0){optionalTags.add("XM:i:"+x);}
1939 }
1940
1941 //XS tag
1942 if(MAKE_XS_TAG){
1943 String xs=makeXSTag(r);
1944 if(xs!=null){
1945 optionalTags.add(xs);
1946 assert(r2==null || r.pairnum()!=r2.pairnum());
1947 // assert(r2==null || !r2.mapped() || r.strand()==r2.strand() || makeXSTag(r2)==xs) :
1948 // "XS problem:\n"+r+"\n"+r2+"\n"+xs+"\n"+makeXSTag(r2)+"\n";
1949 }
1950 }
1951
1952 if(MAKE_MD_TAG){
1953 String md=makeMdTag(r.chrom, r.start, r.match, r.bases, scafloc, scaflen);
1954 if(md!=null){optionalTags.add(md);}
1955 }
1956
1957 if(r.mapped() && MAKE_NH_TAG){
1958 if(ReadStreamWriter.OUTPUT_SAM_SECONDARY_ALIGNMENTS && r.numSites()>1){
1959 optionalTags.add("NH:i:"+r.sites.size());
1960 }else{
1961 optionalTags.add("NH:i:1");
1962 }
1963 }
1964
1965 if(MAKE_STOP_TAG && (perfect || (r.match!=null && r.bases!=null))){optionalTags.add(makeStopTag(pos, r.length(), cigar, perfect));}
1966
1967 if(MAKE_LENGTH_TAG && (perfect || (r.match!=null && r.bases!=null))){optionalTags.add(makeLengthTag(pos, r.length(), cigar, perfect));}
1968
1969 if(MAKE_IDENTITY_TAG && (perfect || r.match!=null)){optionalTags.add(makeIdentityTag(r.match, perfect));}
1970
1971 if(MAKE_MATEQ_TAG && r.mateMapped()){
1972 optionalTags.add("YQ:i:"+toMapq(r.mate, null));
1973 optionalTags.add(makeIdentityTag(r.mate.match, r.mate.perfect()).replace('I', 'J'));
1974 }
1975
1976 if(MAKE_SCORE_TAG && r.mapped()){optionalTags.add(makeScoreTag(r.mapScore));}
1977
1978 if(MAKE_INSERT_TAG && r2!=null){
1979 if((r.mapped() && r.paired()) || r.originalSite!=null){
1980 optionalTags.add("X8:Z:"+r.insertSizeMapped(false)+(r.originalSite==null ? "" : ","+r.insertSizeOriginalSite()));
1981 }
1982 }
1983 if(MAKE_CORRECTNESS_TAG){
1984 final SiteScore ss0=r.originalSite;
1985 if(ss0!=null){
1986 optionalTags.add("X9:Z:"+(ss0.isCorrect(r.chrom, r.strand(), r.start, r.stop, 0) ? "T" : "F"));
1987 }
1988 }
1989 }
1990
1991 if(READGROUP_ID!=null){
1992 assert(READGROUP_TAG!=null);
1993 optionalTags.add(READGROUP_TAG);
1994 }
1995
1996 if(MAKE_CUSTOM_TAGS){
1997 int sites=r.numSites() + (r.originalSite==null ? 0 : 1);
1998 if(sites>0){
1999 ByteBuilder sb=new ByteBuilder();
2000 sb.append("X1:Z:");
2001 if(r.sites!=null){
2002 for(SiteScore ss : r.sites){
2003 sb.append('$');
2004 sb.append(ss.toText());
2005 }
2006 }
2007 if(r.originalSite!=null){
2008 sb.append('$');
2009 sb.append('*');
2010 sb.append(r.originalSite.toText());
2011 }
2012 optionalTags.add(sb.toString());
2013 }
2014
2015 if(mapped){
2016 if(r.match!=null){
2017 byte[] match=r.match;
2018 if(!r.shortmatch()){
2019 match=Read.toShortMatchString(match);
2020 }
2021 optionalTags.add("X2:Z:"+new String(match));
2022 }
2023
2024 optionalTags.add("X3:i:"+r.mapScore);
2025 }
2026 optionalTags.add("X5:Z:"+r.numericID);
2027 optionalTags.add("X6:i:"+(r.flags|(r.match==null ? 0 : Read.SHORTMATCHMASK)));
2028 if(r.copies>1){optionalTags.add("X7:i:"+r.copies);}
2029 }
2030
2031 if(MAKE_TIME_TAG){
2032 assert(r.obj!=null && r.obj.getClass()==Long.class) : r.obj;
2033 optionalTags.add("X0:i:"+(r.obj==null ? 0 : r.obj));
2034 }
2035
2036 if(MAKE_BOUNDS_TAG){
2037 String a=(r.mapped() ? inbounds ? "I" : "O" : "U");
2038 if(r2==null){
2039 optionalTags.add("XB:Z:"+a);
2040 }else{
2041 String b=(r2.mapped() ? inbounds2 ? "I" : "O" : "U");
2042 optionalTags.add("XB:Z:"+a+b);
2043 }
2044 }
2045
2046 return optionalTags;
2047 }
2048
2049 /*--------------------------------------------------------------*/
2050 /*---------------- ? ----------------*/
2051 /*--------------------------------------------------------------*/
2052
2053 /** Length of read bases */
2054 public int length(){
2055 assert((seq!=null && (seq.length!=1 || seq[0]!='*')) || cigar!=null) :
2056 "This program requires bases or a cigar string for every sam line. Problem line:\n"+this+"\n";
2057 return seq==null ? calcCigarBases(cigar, true, false) : seq.length;
2058 }
2059
2060 // public int length(boolean includeSoftClip){
2061 // assert((seq!=null && (seq.length!=1 || seq[0]!='*')) || cigar!=null) :
2062 // "This program requires bases or a cigar string for every sam line. Problem line:\n"+this+"\n";
2063 // return seq==null ? calcCigarBases(cigar, includeSoftClip, false) : seq.length;
2064 // }
2065
2066 public static int toMapq(Read r, SiteScore ss){
2067 assert(r!=null);
2068 int score=(ss==null ? r.mapScore : ss.slowScore);
2069 return toMapq(score, r.length(), r.mapped(), r.ambiguous());
2070 }
2071
2072 public static int toMapq(int score, int length, boolean mapped, boolean ambig){
2073 if(!mapped || length<1){return 0;}
2074
2075 if(ambig && PENALIZE_AMBIG){
2076 float max=3;
2077 float adjusted=(score*max)/(100f*length);
2078 return Tools.max(1, (int)Math.round(adjusted));
2079 }else{
2080 float score2=(score-length*40)*1.6f;
2081 float max=1.5f*((float)Tools.log2(length))+36;
2082 float adjusted=(score2*max)/(100f*length);
2083 return Tools.max(4, (int)Math.round(adjusted));
2084 }
2085 }
2086
2087
2088 public Read parseName(){
2089 try {
2090 String[] answer=qname.split("_");
2091 long id=Long.parseLong(answer[0]);
2092 int trueChrom=Gene.toChromosome(answer[1]);
2093 byte trueStrand=Byte.parseByte(answer[2]);
2094 int trueLoc=Integer.parseInt(answer[3]);
2095 int trueStop=Integer.parseInt(answer[4]);
2096 // for(int i=0; i<quals.length; i++){quals[i]-=33;}
2097 // Read r=new Read(seq.getBytes(), trueChrom, trueStrand, trueLoc, trueStop, qname, quals, false, id);
2098 Read r=new Read(seq, qual, qname, id, trueStrand, trueChrom, trueLoc, trueStop);
2099 return r;
2100 } catch (NumberFormatException e) {
2101 // TODO Auto-generated catch block
2102 e.printStackTrace();
2103 return null;
2104 }
2105 }
2106
2107 public long parseNumericId(){
2108 // return Long.parseLong(qname.substring(0, qname.indexOf('_')));
2109 return Long.parseLong(qname.split("_")[1]);
2110 }
2111
2112 public Read toRead(boolean parseCustom){
2113 return toRead(parseCustom, false);
2114 }
2115
2116 public Read toRead(boolean parseCustom, boolean includeHardClip){
2117
2118 SiteScore originalSite=null;
2119 long numericId_=0;
2120 boolean synthetic=false;
2121
2122 if(parseCustom){
2123
2124
2125 CustomHeader h=new CustomHeader(qname, pairnum());
2126
2127 numericId_=h.id;
2128 int trueChrom=h.bbchrom;
2129 byte trueStrand=(byte)h.strand;
2130 int trueLoc=h.bbstart;
2131 int trueStop=h.bbstop();
2132
2133 originalSite=new SiteScore(trueChrom, trueStrand, trueLoc, trueStop, 0, 0);
2134 synthetic=true;
2135
2136 // try {
2137 // String[] answer=qname.split("_");
2138 // numericId_=Long.parseLong(answer[0]);
2139 // int trueChrom=Gene.toChromosome(answer[1]);
2140 // byte trueStrand=Byte.parseByte(answer[2]);
2141 // int trueLoc=Integer.parseInt(answer[3]);
2142 // int trueStop=Integer.parseInt(answer[4]);
2143 //
2144 // originalSite=new SiteScore(trueChrom, trueStrand, trueLoc, trueStop, 0, 0);
2145 // synthetic=true;
2146 //
2147 // } catch (NumberFormatException e) {
2148 // System.err.println("Failed to parse "+qname);
2149 // } catch (NullPointerException e) {
2150 // System.err.println("Bad read with no name.");
2151 // return null;
2152 // }
2153 }
2154 // assert(false) : originalSite;
2155
2156
2157 if(Data.GENOME_BUILD>=0){
2158
2159 }
2160
2161 int chrom_=-1;
2162 byte strand_=strand();
2163 int start_=start(true, includeHardClip);
2164 int stop_=stop(start_, true, includeHardClip);
2165 assert(start_<=stop_) : start_+", "+stop_+"\n"+this+"\n";
2166
2167 if(Data.GENOME_BUILD>=0){
2168 ScafLoc sc=null;
2169 if(RNAME_AS_BYTES){
2170 if(rname!=null && (rname.length!=1 || rname[0]!='*')){
2171 sc=Data.getScafLoc(rname);
2172 assert(sc!=null) : "Can't find scaffold in reference with name "+new String(rname)+"\n"+this;
2173 }
2174 }else{
2175 if(rnameS!=null && (rnameS.length()!=1 || rnameS.charAt(0)!='*')){
2176 sc=Data.getScafLoc(rnameS);
2177 assert(sc!=null) : "Can't find scaffold in reference with name "+new String(rnameS)+"\n"+this;
2178 }
2179 }
2180 if(sc!=null){
2181 chrom_=sc.chrom;
2182 start_+=sc.loc;
2183 stop_+=sc.loc;
2184 }
2185 }
2186
2187 //// byte[] quals=(qual==null || (qual.length()==1 && qual.charAt(0)=='*')) ? null : qual.getBytes();
2188 //// byte[] quals=(qual==null || (qual.length==1 && qual[0]=='*')) ? null : qual.clone();
2189 // byte[] quals=(qual==null || (qual.length==1 && qual[0]=='*')) ? null : qual;
2190 // byte[] bases=seq==null ? null : seq.clone();
2191 // if(strand_==Gene.MINUS){//Minus-mapped SAM lines have bases and quals reversed
2192 // AminoAcid.reverseComplementBasesInPlace(bases);
2193 // Tools.reverseInPlace(quals);
2194 // }
2195 // Read r=new Read(bases, chrom_, strand_, start_, stop_, qname, quals, cs_, numericId_);
2196
2197 final Read r;
2198 {
2199 byte[] seqX=(seq==null || (seq.length==1 && seq[0]=='*')) ? null : seq;
2200 byte[] qualX=(qual==null || (qual.length==1 && qual[0]=='*')) ? null : qual;
2201 String qnameX=(qname==null || qname.equals(stringstar)) ? null : qname;
2202 r=new Read(seqX, qualX, qnameX, numericId_, strand_, chrom_, start_, stop_);
2203 }
2204
2205 r.setMapped(mapped());
2206 r.setSynthetic(synthetic);
2207 // r.setPairnum(pairnum()); //TODO: Enable after fixing assertions that this will break in read input streams.
2208 if(originalSite!=null){
2209 r.originalSite=originalSite;
2210 }
2211
2212 r.mapScore=mapq;
2213 r.setSecondary(!primary());
2214
2215 // if(mapped()){
2216 // r.list=new ArrayList<SiteScore>(1);
2217 // r.list.add(new SiteScore(r.chrom, r.strand(), r.start, r.stop, 0));
2218 // }
2219
2220 // System.out.println(optional);
2221 if(optional!=null){
2222 for(String s : optional){
2223 if(s.equals("XT:A:R")){
2224 r.setAmbiguous(true);
2225 }else if(s.startsWith("X1:Z:")){
2226 // System.err.println("Found X1 tag!\t"+s);
2227 String[] split=s.split("\\$");
2228 // assert(false) : Arrays.toString(split);
2229 ArrayList<SiteScore> list=new ArrayList<SiteScore>(3);
2230
2231 for(int i=1; i<split.length; i++){
2232 // System.err.println("Processing ss\t"+split[i]);
2233 String s2=split[i];
2234 SiteScore ss=SiteScore.fromText(s2);
2235 if(s2.charAt(0)=='*'){
2236 r.originalSite=ss;
2237 }else{
2238 list.add(ss);
2239 }
2240 }
2241 // System.err.println("List size = "+list.size());
2242 if(list.size()>0){r.sites=list;}
2243 }else if(s.startsWith("X2:Z:")){
2244 String s2=s.substring(5);
2245 r.match=s2.getBytes();
2246 }else if(s.startsWith("X3:i:")){
2247 String s2=s.substring(5);
2248 // r.mapScore=Integer.parseInt(s2); //Messes up generation of ROC curve
2249 }else if(s.startsWith("X5:Z:")){
2250 String s2=s.substring(5);
2251 r.numericID=Long.parseLong(s2);
2252 }else if(s.startsWith("X6:i:")){
2253 String s2=s.substring(5);
2254 r.flags=Integer.parseInt(s2);
2255 }else if(s.startsWith("X7:i:")){
2256 String s2=s.substring(5);
2257 r.copies=Integer.parseInt(s2);
2258 }else{
2259 // System.err.println("Unknown SAM field:"+s);
2260 }
2261 }
2262 }
2263 // assert(false) : CONVERT_CIGAR_TO_MATCH;
2264 if(r.match==null && cigar!=null && (CONVERT_CIGAR_TO_MATCH || cigar.indexOf('=')>=0)){
2265 // r.match=cigarToShortMatch(cigar, true);
2266 r.match=toShortMatch(false);
2267
2268 if(r.match!=null){
2269 r.setShortMatch(true);
2270 if(Tools.indexOf(r.match, (byte)'B')>=0){
2271 boolean success=r.fixMatchB();
2272 // if(!success){r.match=null;}
2273 // assert(false) : new String(r.match);
2274 }
2275 // assert(false) : new String(r.match);
2276 }
2277 // assert(false) : new String(r.match);
2278 // System.err.println(">\n"+cigar+"\n"+(r.match==null ? "null" : new String(r.match)));
2279 }
2280 // assert(false) : new String(r.match);
2281
2282 // System.err.println("Resulting read: "+r.toText());
2283
2284 return r;
2285
2286 }
2287
2288 /*--------------------------------------------------------------*/
2289 /*---------------- toString ----------------*/
2290 /*--------------------------------------------------------------*/
2291
2292 /** Aproximate length of result of SamLine.toText() */
2293 public int textLength(){
2294 int len=11; //11 tabs
2295 len+=(3+9+3+9);
2296 len+=(tlen>999 ? 9 : 3);
2297
2298 len+=(qname==null ? 1 : qname.length());
2299 len+=rnameLen();
2300 len+=(rnext==null ? 1 : rnext.length);
2301 len+=(cigar==null ? 1 : cigar.length());
2302 len+=(seq==null ? 1 : seq.length);
2303 len+=(qual==null ? 1 : qual.length);
2304
2305 if(optional!=null){
2306 len+=optional.size();
2307 for(String s : optional){len+=s.length();}
2308 }
2309 return len;
2310 }
2311
2312 public ByteBuilder toText(){return toBytes((ByteBuilder)null);}
2313
2314 public ByteBuilder toBytes(ByteBuilder bb){
2315
2316 final int buflen=Tools.max(rnameLen(), (rnext==null ? 1 : rnext.length), (seq==null ? 1 : seq.length), (qual==null ? 1 : qual.length));
2317
2318 if(bb==null){bb=new ByteBuilder(textLength()+4);}
2319 if(qname==null){bb.append('*').tab();}else{bb.append(qname).tab();}
2320 bb.append(flag).tab();
2321 if(RNAME_AS_BYTES){
2322 assert(!(rname==null && rnameS!=null));
2323 appendTo(bb, rname).tab();
2324 }else{
2325 assert(!(rname!=null && rnameS==null)) : RNAME_AS_BYTES+", "+rname+", "+rnameS;
2326 appendTo(bb, rnameS).tab();
2327 }
2328 bb.append(pos).tab();
2329 bb.append(mapq).tab();
2330 if(cigar==null){bb.append('*');}
2331 else{bb.append(cigar);}
2332 bb.tab();
2333 appendTo(bb, rnext).tab();
2334 bb.append(pnext).tab();
2335 bb.append(tlen).tab();
2336
2337 if(mapped() && strand()==Shared.MINUS){
2338 appendReverseComplemented(bb, seq).tab();
2339 appendQualReversed(bb, qual);
2340 }else{
2341 appendTo(bb, seq).tab();
2342 appendQual(bb, qual);
2343 }
2344
2345 if(optional!=null){
2346 for(String s : optional){
2347 bb.tab().append(s);
2348 }
2349 }
2350 return bb;
2351 }
2352
2353 @Override
2354 public String toString(){return toBytes(null).toString();}
2355
2356 private static ByteBuilder appendTo(ByteBuilder sb, byte[] a){
2357 if(a==null || a==bytestar || (a.length==1 && a[0]=='*')){return sb.append('*');}
2358 return sb.append(a);
2359 }
2360
2361 private static ByteBuilder appendTo(ByteBuilder sb, String a){
2362 if(a==null || a==stringstar || (a.length()==1 && a.charAt(0)=='*')){return sb.append('*');}
2363 return sb.append(a);
2364 }
2365
2366 private static ByteBuilder appendReverseComplemented(ByteBuilder sb, byte[] a){
2367 if(a==null || a==bytestar || (a.length==1 && a[0]=='*')){return sb.append('*');}
2368
2369 sb.ensureExtra(a.length);
2370 byte[] buffer=sb.array;
2371 int i=sb.length;
2372 for(int j=a.length-1; j>=0; i++, j--){buffer[i]=AminoAcid.baseToComplementExtended[a[j]];}
2373 sb.length+=a.length;
2374
2375 return sb;
2376 }
2377
2378 private static ByteBuilder appendQual(ByteBuilder sb, byte[] a){
2379 if(a==null || a==bytestar || (a.length==1 && a[0]=='*')){return sb.append('*');}
2380
2381 sb.ensureExtra(a.length);
2382 byte[] buffer=sb.array;
2383 int i=sb.length;
2384 for(int j=0; j<a.length; i++, j++){buffer[i]=(byte)(a[j]+33);}
2385 sb.length+=a.length;
2386
2387 return sb;
2388 }
2389
2390 private static ByteBuilder appendQualReversed(ByteBuilder sb, byte[] a){
2391 if(a==null || a==bytestar || (a.length==1 && a[0]=='*')){return sb.append('*');}
2392
2393 sb.ensureExtra(a.length);
2394 byte[] buffer=sb.array;
2395 int i=sb.length;
2396 for(int j=a.length-1; j>=0; i++, j--){buffer[i]=(byte)(a[j]+33);}
2397 sb.length+=a.length;
2398
2399 return sb;
2400 }
2401
2402 /** Assumes a custom name including original location */
2403 public byte[] originalContig(){
2404 // assert(PARSE_CUSTOM);
2405 int loc=-1;
2406 int count=0;
2407 for(int i=0; i<qname.length() && loc==-1; i++){
2408 if(qname.charAt(i)=='_'){
2409 count++;
2410 if(count==6){loc=i;}
2411 }
2412 }
2413 if(loc==-1){
2414 return null;
2415 }
2416 return qname.substring(loc+1).getBytes();
2417 }
2418
2419
2420 /*--------------------------------------------------------------*/
2421 /*---------------- Flag ----------------*/
2422 /*--------------------------------------------------------------*/
2423
2424 // Bit Description
2425 // 0x1 template having multiple fragments in sequencing
2426 // 0x2 each fragment properly aligned according to the aligner
2427 // 0x4 fragment unmapped
2428 // 0x8 next fragment in the template unmapped
2429 // 0x10 SEQ being reverse complemented
2430 // 0x20 SEQ of the next fragment in the template being reversed
2431 // 0x40 the first fragment in the template
2432 // 0x80 the last fragment in the template
2433 // 0x100 secondary alignment
2434 // 0x200 not passing quality controls
2435 // 0x400 PCR or optical duplicate
2436 // 0x800 supplementary alignment
2437
2438
2439 public static int makeFlag(Read r, Read r2, int fragNum, boolean sameScaf){
2440 int flag=0;
2441 if(r2!=null){
2442 flag|=0x1;
2443
2444 if(r.mapped() && r.valid() && r.match!=null &&
2445 (r2==null || (sameScaf && r.paired() && r2.mapped() && r2.valid() && r2.match!=null))){flag|=0x2;}
2446 if(fragNum==0){flag|=0x40;}
2447 if(fragNum>0){flag|=0x80;}
2448 }
2449 if(!r.mapped()){flag|=0x4;}
2450 if(r2!=null && !r2.mapped()){flag|=0x8;}
2451 if(r.strand()==Shared.MINUS){flag|=0x10;}
2452 if(r2!=null && r2.strand()==Shared.MINUS){flag|=0x20;}
2453 if(r.secondary()){flag|=0x100;}
2454 if(r.discarded()){flag|=0x200;}
2455 return flag;
2456 }
2457
2458 public boolean hasCigar() {
2459 return cigar!=null && cigar.length()>0 && cigar.charAt(0)!='*';
2460 }
2461
2462 /** contains a cigar with X or = symbols */
2463 public boolean hasCigarXE() {
2464 if(cigar==null || cigar.length()<1 || cigar.charAt(0)=='*') {return false;}
2465 for(int i=0; i<cigar.length(); i++) {
2466 char c=cigar.charAt(i);
2467 if(c=='=' || c=='X') {return true;}
2468 }
2469 return false;
2470 }
2471
2472 public boolean hasMate(){
2473 return (flag&0x1)==0x1;
2474 }
2475
2476 public boolean properPair(){
2477 return (flag&0x2)==0x2;
2478 }
2479
2480 public static boolean mapped(int flag){
2481 return (flag&0x4)!=0x4;
2482 }
2483
2484 public static byte strand(int flag){
2485 return ((flag&0x10)==0x10 ? (byte)1 : (byte)0);
2486 }
2487
2488 public boolean mapped(){
2489 return (flag&0x4)!=0x4;
2490 // 0x4 fragment unmapped
2491 // 0x8 next fragment in the template unmapped
2492 }
2493
2494 public boolean nextMapped(){
2495 return (flag&0x8)!=0x8;
2496 // 0x4 fragment unmapped
2497 // 0x8 next fragment in the template unmapped
2498 }
2499
2500 public byte strand(){
2501 return ((flag&0x10)==0x10 ? (byte)1 : (byte)0);
2502 }
2503
2504 public byte mateStrand(){return nextStrand();}
2505 public byte nextStrand(){
2506 return ((flag&0x20)==0x20 ? (byte)1 : (byte)0);
2507 }
2508
2509 public boolean firstFragment(){
2510 return (flag&0x40)==0x40;
2511 }
2512
2513 public boolean lastFragment(){
2514 return (flag&0x80)==0x80;
2515 }
2516
2517 public int pairnum(){
2518 return firstFragment() ? 0 : lastFragment() ? 1 : 0;
2519 }
2520
2521 public boolean primary(){return (flag&0x100)==0;}
2522 public void setPrimary(boolean b){
2523 if(b){
2524 flag=flag|0x100;
2525 }else{
2526 flag=flag&~0x100;
2527 }
2528 }
2529
2530 public boolean discarded(){
2531 return (flag&0x200)==0x200;
2532 }
2533
2534 public boolean duplicate(){
2535 return (flag&0x400)==0x400;
2536 }
2537
2538 public boolean supplementary(){
2539 return (flag&0x800)==0x800;
2540 }
2541
2542 public boolean leftmost(){
2543 if(!pairedOnSameChrom() || tlen==0){return true;}
2544 return tlen>0;
2545 }
2546
2547 /*--------------------------------------------------------------*/
2548 /*---------------- ? ----------------*/
2549 /*--------------------------------------------------------------*/
2550
2551 // /** Assumes rname is an integer. */
2552 // public int chrom(){
2553 // if(Data.GENOME_BUILD<0){return -1;}
2554 // HashMap sc
2555 // }
2556
2557 public boolean ambiguous() {return mapped() && mapq<4;}
2558
2559 /** Assumes rname is an integer. */
2560 public int chrom_old(){
2561 assert(false);
2562 if(!Tools.isDigit(rname[0]) && !Tools.isDigit(rname[rname.length-1])){
2563 if(warning){
2564 warning=false;
2565 System.err.println("Warning - sam lines need a chrom field.");
2566 }
2567 return -1;
2568 }
2569 assert(Shared.anomaly || '*'==rname[0] || (Tools.isDigit(rname[0]) && Tools.isDigit(rname[rname.length-1]))) :
2570 "This is no longer correct, considering that sam lines are named by scaffold. They need a chrom field.\n"+new String(rname);
2571 if(rname==null || Arrays.equals(rname, bytestar) || !(Tools.isDigit(rname[0]) && Tools.isDigit(rname[rname.length-1]))){return -1;}
2572 //return Gene.toChromosome(new String(rname));
2573 //return Integer.parseInt(new String(rname)));
2574 final byte z='0';
2575 int x=rname[0]-z;
2576 for(int i=1; i<rname.length; i++){
2577 x=(x*10)+(rname[i]-z);
2578 }
2579 return x;
2580 }
2581
2582 /** Returns the zero-based starting location of this read on the sequence. */
2583 public int start(boolean includeSoftClip, boolean includeHardClip){
2584 int x=countLeadingClip(cigar, includeSoftClip, includeHardClip);
2585 return pos-1-x;
2586 }
2587
2588 /** Returns the zero-based stop location of this read on the sequence. */
2589 public int stop(int start, boolean includeSoftClip, boolean includeHardClip){
2590 if(!mapped() || cigar==null || cigar.charAt(0)=='*'){
2591 // return -1;
2592 return start+(seq==null ? 0 : Tools.max(0, seq.length-1));
2593 }
2594 int r=start+calcCigarLength(cigar, includeSoftClip, includeHardClip)-1;
2595
2596 // assert(false) : start+", "+r+", "+calcCigarLength(cigar, includeHardClip);
2597 // System.err.println("start= "+start+", stop="+r);
2598 return r;
2599 }
2600
2601 public int stop2(final int start, final boolean includeSoftClip, final boolean includeHardClip){
2602 if(mapped() && cigar!=null && cigar.charAt(0)!='*'){return stop(start, includeSoftClip, includeHardClip);}
2603 // return (seq==null ? -1 : start()+seq.length());
2604 return (seq==null ? -1 : start+seq.length);
2605 }
2606
2607 public long numericId(){
2608 return 0;
2609 }
2610
2611 /** This includes half-mapped pairs. */
2612 public boolean pairedOnSameChrom(){
2613 // assert(false) : (rname==null ? "nullX" : new String(rname))+", "+
2614 // (rnext==null ? "nullX" : new String(rnext))+", "+Tools.equals(rnext, byteequals)+", "+Arrays.equals(rname, rnext)+"\n"+this;
2615 if(RNAME_AS_BYTES){
2616 return Tools.equals(rnext, byteequals) || Arrays.equals(rname, rnext) || (/*pairnum()==1 &&*/ Tools.equals(rname, byteequals));
2617 }else{
2618 return Tools.equals(rnext, byteequals) || Tools.equals(rnameS, rnext) || (/*pairnum()==1 &&*/ stringequals.equals(rnameS));
2619 }
2620 }
2621
2622 /** Assumes a custom name including original location */
2623 public int originalContigStart(){
2624 // assert(PARSE_CUSTOM);
2625 int loc=-1;
2626 int count=0;
2627 for(int i=0; i<qname.length() && loc==-1; i++){
2628 if(qname.charAt(i)=='_'){
2629 count++;
2630 if(count==5){loc=i;}
2631 }
2632 }
2633 if(loc==-1){
2634 return -1;
2635 }
2636
2637 int sum=0;
2638 int mult=1;
2639 for(int i=loc+1; i<qname.length(); i++){
2640 char c=qname.charAt(i);
2641 if(!Tools.isDigit(c)){
2642 if(i==loc+1 && c=='-'){mult=-1;}
2643 else{break;}
2644 }else{
2645 sum=(sum*10)+(c-'0');
2646 }
2647 }
2648 return sum*mult;
2649 }
2650
2651 /*--------------------------------------------------------------*/
2652 /*---------------- Getters ----------------*/
2653 /*--------------------------------------------------------------*/
2654
2655 public int rnameLen(){
2656 return (rname==null ? rnameS==null ? 1 : rnameS.length() : rname.length);
2657 }
2658
2659 public byte[] rname(){
2660 assert(RNAME_AS_BYTES);
2661 return rname;
2662 }
2663 public byte[] rnext(){return rnext;}
2664
2665 public void setRname(byte[] x){assert(RNAME_AS_BYTES);rname=x;}
2666 public void setRnext(byte[] x){rnext=x;}
2667
2668 public void setRname(String x){assert(!RNAME_AS_BYTES);rnameS=x;}
2669 public void setRnext(String x){rnext=(x==null ? null : x.getBytes());}
2670
2671 public String rnameS(){return rnameS!=null ? rnameS : rname==null ? null : new String(rname);}
2672 public String rnextS(){return rnext==null ? null : new String(rnext);}
2673
2674 public String rnamePrefix() {
2675 return (rnameS!=null ? toPrefix(rnameS) : toPrefix(rname));
2676 }
2677
2678 private static String toPrefix(String s) {
2679 for(int i=0; i<s.length(); i++) {
2680 if(Character.isWhitespace(s.charAt(i))) {
2681 return s.substring(0, i);
2682 }
2683 }
2684 return s;
2685 }
2686
2687 private static String toPrefix(byte[] s) {
2688 for(int i=0; i<s.length; i++) {
2689 if(Character.isWhitespace(s[i])) {
2690 return new String(s, 0, i);
2691 }
2692 }
2693 return new String(s);
2694 }
2695
2696 /*--------------------------------------------------------------*/
2697 /*---------------- Fields ----------------*/
2698 /*--------------------------------------------------------------*/
2699
2700 public String findTag(String prefix) {
2701 if(optional==null){return null;}
2702 for(String s : optional){
2703 if(s.startsWith(prefix)){return s;}
2704 }
2705 return null;
2706 }
2707
2708 public String mdTag(){return findTag("MD:Z:");}
2709 public String mateqTag(){return findTag("YQ:i:");}
2710 public int parseIntFlag(String prefix) {
2711 String tag=findTag(prefix);
2712 return tag==null ? Integer.MIN_VALUE : Parse.parseInt(tag, 5);
2713 }
2714 public float parseFloatFlag(String prefix) {
2715 String tag=findTag(prefix);
2716 return tag==null ? -1 : Parse.parseFloat(tag, 5);
2717 }
2718 public int mateq() {return parseIntFlag("YQ:i:");}
2719 public float mateID() {return parseFloatFlag("YJ:f:");}
2720
2721 public int setScafnum(ScafMap scafMap) {
2722 assert(scafnum<0);
2723
2724 String name=null;
2725 if(mapped() || (rname!=null && rname!=byteequals && rname!=bytestar)){
2726 name=rnameS();
2727 }else if(nextMapped() && rnext!=null && rnext!=byteequals && rnext!=bytestar){
2728 name=new String(rnext);
2729 }
2730 if(name!=null){scafnum=scafMap.getNumber(name);}
2731 return scafnum;
2732 }
2733
2734 public long countBytes(){
2735 long sum=76;
2736 sum+=(cigar==null ? 0 : cigar.length()*2+16);
2737 sum+=(optional==null ? 0 : optional.size()*32+16);
2738 sum+=(rname==null ? 0 : rname.length+16);
2739 sum+=(rnext==null ? 0 : rnext.length+16);
2740 return sum;
2741 }
2742
2743 public String qname;
2744 public int flag;
2745 public int pos;
2746 public int mapq;
2747 public String cigar;
2748 public int pnext;
2749 public int tlen;
2750 public byte[] seq;
2751 public byte[] qual;
2752 public ArrayList<String> optional;
2753 public byte[] mdTag;
2754
2755 public Object obj;
2756 public int scafnum=-1;
2757
2758 /*--------------------------------------------------------------*/
2759 /*---------------- Private Fields ----------------*/
2760 /*--------------------------------------------------------------*/
2761
2762 private byte[] rname;
2763 private byte[] rnext;
2764
2765 private String rnameS;
2766
2767 /*--------------------------------------------------------------*/
2768 /*---------------- Static Fields ----------------*/
2769 /*--------------------------------------------------------------*/
2770
2771 private static final String stringstar="*";
2772 private static final String stringequals="=";
2773 private static final byte[] bytestar=new byte[] {(byte)'*'};
2774 private static final byte[] byteequals=new byte[] {(byte)'='};
2775 private static final String XSPLUS="XS:A:+", XSMINUS="XS:A:-";
2776 // private static final double inv100=0.01d;
2777 // private static float minratio=0.4f;
2778
2779 private static boolean warning=System.getProperty("user.dir").contains("/bushnell/");
2780
2781 /*--------------------------------------------------------------*/
2782 /*---------------- Public Static Fields ----------------*/
2783 /*--------------------------------------------------------------*/
2784
2785 public static boolean makeReadgroupTags(){
2786 return READGROUP_ID!=null || READGROUP_CN!=null || READGROUP_DS!=null || READGROUP_DT!=null ||
2787 READGROUP_FO!=null || READGROUP_KS!=null || READGROUP_LB!=null || READGROUP_PG!=null ||
2788 READGROUP_PI!=null || READGROUP_PL!=null || READGROUP_PU!=null || READGROUP_SM!=null ||
2789 READGROUP_TAG!=null;
2790 }
2791
2792 public static boolean makeOtherTags(){
2793 if(NO_TAGS){return false;}
2794 return MAKE_AM_TAG || MAKE_NM_TAG || MAKE_SM_TAG || MAKE_XM_TAG || MAKE_XS_TAG || MAKE_AS_TAG ||
2795 MAKE_NH_TAG || MAKE_TOPHAT_TAGS || MAKE_IDENTITY_TAG || MAKE_SCORE_TAG || MAKE_STOP_TAG || MAKE_LENGTH_TAG ||
2796 MAKE_CUSTOM_TAGS || MAKE_INSERT_TAG || MAKE_CORRECTNESS_TAG || MAKE_TIME_TAG || MAKE_BOUNDS_TAG || MAKE_MATEQ_TAG;
2797 }
2798
2799 public static boolean makeAnyTags(){
2800 return makeReadgroupTags() || makeOtherTags();
2801 }
2802
2803 public static String READGROUP_ID=null;
2804 public static String READGROUP_CN=null;
2805 public static String READGROUP_DS=null;
2806 public static String READGROUP_DT=null;
2807 public static String READGROUP_FO=null;
2808 public static String READGROUP_KS=null;
2809 public static String READGROUP_LB=null;
2810 public static String READGROUP_PG=null;
2811 public static String READGROUP_PI=null;
2812 public static String READGROUP_PL=null;
2813 public static String READGROUP_PU=null;
2814 public static String READGROUP_SM=null;
2815
2816 public static String READGROUP_TAG=null;
2817
2818 /** Turn this off for RNAseq or long indels */
2819 public static boolean MAKE_MD_TAG=false;
2820
2821 public static boolean NO_TAGS=false;
2822
2823 public static boolean MAKE_AM_TAG=true;
2824 public static boolean MAKE_NM_TAG=true;
2825 public static boolean MAKE_SM_TAG=false;
2826 public static boolean MAKE_XM_TAG=false;
2827 public static boolean MAKE_XS_TAG=false;
2828 public static boolean MAKE_XT_TAG=true;
2829 public static boolean MAKE_AS_TAG=false; //TODO: Alignment score from aligner
2830 public static boolean MAKE_NH_TAG=false;
2831 public static boolean MAKE_TOPHAT_TAGS=false;
2832 public static boolean XS_SECONDSTRAND=false;
2833 public static boolean MAKE_IDENTITY_TAG=false;
2834 public static boolean MAKE_SCORE_TAG=false;
2835 public static boolean MAKE_STOP_TAG=false;
2836 public static boolean MAKE_LENGTH_TAG=false;
2837 public static boolean MAKE_CUSTOM_TAGS=false;
2838 public static boolean MAKE_INSERT_TAG=false;
2839 public static boolean MAKE_CORRECTNESS_TAG=false;
2840 public static boolean MAKE_TIME_TAG=false;
2841 public static boolean MAKE_BOUNDS_TAG=false;
2842 public static boolean MAKE_MATEQ_TAG=false;
2843
2844 public static boolean PENALIZE_AMBIG=true;
2845 public static boolean CONVERT_CIGAR_TO_MATCH=true;
2846 public static boolean SOFT_CLIP=true;
2847 public static boolean SECONDARY_ALIGNMENT_ASTERISKS=true;
2848 /** OK to use the "setFrom" function which uses the old SamLine instead of translating the read, if a genome is not loaded. */
2849 public static boolean SET_FROM_OK=false;
2850 /** For paired reads, keep original names rather than changing read2's name to match read1 */
2851 public static boolean KEEP_NAMES=false;
2852 public static float VERSION=1.4f;
2853 /** Tells program when to use 'N' rather than 'D' in cigar strings */
2854 public static int INTRON_LIMIT=Integer.MAX_VALUE;
2855 public static boolean RNAME_AS_BYTES=true;//Effect on speed is negligible for pileup...
2856
2857 /** Prefer MD tag over reference for translating cigar strings to match */
2858 public static boolean PREFER_MDTAG=false;
2859 /** Determine whether cigar X means match N or S.
2860 * This makes sam loading substantially slower. */
2861 public static boolean FIX_MATCH_NS=false;
2862
2863 public static boolean setxs=false;
2864 public static boolean setintron=false;
2865
2866 // /** SSAHA2 incorrectly calculates the start position of reads with soft-clipped starts, and needs this enabled. */
2867 // public static boolean SUBTRACT_LEADING_SOFT_CLIP=true;
2868 /** Sort header scaffolds in alphabetical order to be more compatible with Tophat */
2869 public static boolean SORT_SCAFFOLDS=false;
2870
2871 /** qname */
2872 public static boolean PARSE_0=true;
2873 /** rname */
2874 public static boolean PARSE_2=true;
2875 /** cigar */
2876 public static boolean PARSE_5=true;
2877 /** rnext */
2878 public static boolean PARSE_6=true;
2879 /** pnext */
2880 public static boolean PARSE_7=true;
2881 /** tlen */
2882 public static boolean PARSE_8=true;
2883 /** qual */
2884 public static boolean PARSE_10=true;
2885 public static boolean PARSE_OPTIONAL=true;
2886 public static boolean PARSE_OPTIONAL_MD_ONLY=false;
2887 public static boolean PARSE_OPTIONAL_MATEQ_ONLY=false;
2888
2889 public static boolean FLIP_ON_LOAD=true;
2890
2891 public static boolean verbose=false;
2892
2893 }