Debian Codegraph @

current/stream/FASTQ.java

raw symbols SCIP
1 package stream;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9
10 import dna.AminoAcid;
11 import dna.Data;
12 import dna.Gene;
13 import fileIO.ByteFile;
14 import fileIO.ReadWrite;
15 import fileIO.TextFile;
16 import shared.KillSwitch;
17 import shared.Shared;
18 import shared.Tools;
19 import structures.ByteBuilder;
20
21
22 public class FASTQ {
23
24 // public static boolean isInterleaved(String fname){
25 // if(!TEST_INTERLEAVED && !FORCE_INTERLEAVED){return false;}
26 // assert(tf.is!=System.in && !tf.name.equals("stdin") && !tf.name.startsWith("stdin."));
27 // if(tf.is!=System.in && !tf.name.equals("stdin") && !tf.name.startsWith("stdin.")){return FORCE_INTERLEAVED;}
28 // String s=null;
29 //
30 // String[] oct=new String[8];
31 // }
32
33 // public static boolean isInterleaved_old(String fname){
34 //// assert(false) : TEST_INTERLEAVED+", "+FORCE_INTERLEAVED;
35 // if(!TEST_INTERLEAVED && !FORCE_INTERLEAVED){
36 // testQuality(fname);
37 // return false;
38 // }
39 // assert(!fname.equals("stdin") && !fname.startsWith("stdin."));
40 // if(fname.equals("stdin") || fname.startsWith("stdin.")){return FORCE_INTERLEAVED;}
41 //// TextFile tf=new TextFile(fname);
42 //// assert(tf.is!=System.in);
43 //// if(tf.is==System.in){return FORCE_INTERLEAVED;}
44 //
45 // String[] oct=new String[8];
46 // int cntr=0;
47 //
48 // {
49 // InputStream is=ReadWrite.getInputStream(fname, false, false);
50 // BufferedReader br=new BufferedReader(new InputStreamReader(is));
51 // try {
52 // for(String s=br.readLine(); s!=null && cntr<8; s=br.readLine()){
53 // oct[cntr]=s;
54 // cntr++;
55 // }
56 // } catch (IOException e) {
57 // // TODO Auto-generated catch block
58 // e.printStackTrace();
59 // }
60 // }
61 //
62 // if(oct[0]==null){return false;}
63 //
64 // testQuality(oct);
65 //
66 // if(cntr<8){return false;}
67 //// assert(false);
68 // assert(oct[0]==null || oct[0].startsWith("@")) : "Does not appear to be a valid FASTQ file:\n"+new String(oct[0]);
69 // assert(oct[2]==null || oct[2].startsWith("+")) : "Does not appear to be a valid FASTQ file:\n"+new String(oct[2]);
70 // assert(oct[4]==null || oct[4].startsWith("@")) : "Does not appear to be a valid FASTQ file:\n"+new String(oct[4]);
71 // assert(oct[6]==null || oct[6].startsWith("+")) : "Does not appear to be a valid FASTQ file:\n"+new String(oct[6]);
72 //
73 // if(FORCE_INTERLEAVED){return true;}
74 // if(PARSE_CUSTOM && fname.contains("_interleaved.f")){
75 // return true;
76 // }
77 //
78 // return testPairNames(oct[0], oct[4]);
79 // }
80
81 private static String[] getFirstTwoFastaHeaders(String fname){
82 if(fname==null){return null;}
83 if(fname.equalsIgnoreCase("stdin") || fname.toLowerCase().startsWith("stdin.")){return null;}
84
85 String[] headers=new String[2];
86 int cntr=0;
87
88 {
89 InputStream is=ReadWrite.getInputStream(fname, false, false);
90 BufferedReader br=new BufferedReader(new InputStreamReader(is));
91 try {
92 for(String s=br.readLine(); s!=null && cntr<2; s=br.readLine()){
93 if(s.startsWith(">")){
94 headers[cntr]=s;
95 cntr++;
96 }
97 }
98 } catch (IOException e) {
99 // TODO Auto-generated catch block
100 e.printStackTrace();
101 }
102 }
103 return headers;
104 }
105
106 public static byte testQuality(String fname){
107 if(fname==null){return ASCII_OFFSET;}
108 if(!DETECT_QUALITY || fname.equalsIgnoreCase("stdin") || fname.toLowerCase().startsWith("stdin.")){return ASCII_OFFSET;}
109
110 ArrayList<String> oct=fileIO.FileFormat.getFirstOctet(fname);
111 return testQuality(oct);
112 }
113
114 public static boolean isInterleaved(final String fname, final boolean allowIdentical){
115 if(!DETECT_QUALITY && !TEST_INTERLEAVED){return FORCE_INTERLEAVED;}
116 final ArrayList<String> oct=fileIO.FileFormat.getFirstOctet(fname);
117 if(oct==null){return FORCE_INTERLEAVED;}
118
119 if(DETECT_QUALITY){testQuality(oct);}
120 if(TEST_INTERLEAVED){return testInterleaved(oct, fname, allowIdentical);}
121 return FORCE_INTERLEAVED;
122 }
123
124 public static boolean testInterleaved(ArrayList<String> oct, String fname, boolean allowIdentical){
125 if(oct==null || oct.size()<8){return false;}
126 for(String s : oct){
127 if(s==null){return false;}
128 }
129
130 assert(oct.get(0).startsWith("@")) : "File "+fname+"\ndoes not appear to be a valid FASTQ file:\n"+new String(oct.get(0));
131 assert(oct.get(2).startsWith("+")) : "File "+fname+"\ndoes not appear to be a valid FASTQ file:\n"+new String(oct.get(2));
132 assert(oct.get(4).startsWith("@")) : "File "+fname+"\ndoes not appear to be a valid FASTQ file:\n"+new String(oct.get(4));
133 assert(oct.get(6).startsWith("+")) : "File "+fname+"\ndoes not appear to be a valid FASTQ file:\n"+new String(oct.get(6));
134
135 if(FORCE_INTERLEAVED){return true;}
136 if(PARSE_CUSTOM && fname.contains("_interleaved.")){return true;}
137
138 boolean b=testPairNames(oct.get(0), oct.get(4), allowIdentical);
139 return b;
140 }
141
142 public static boolean testInterleavedFasta(String fname, boolean allowIdentical){
143 String[] headers=getFirstTwoFastaHeaders(fname);
144 return testInterleavedFasta(headers, fname, allowIdentical);
145 }
146
147 private static boolean testInterleavedFasta(String[] headers, String fname, boolean allowIdentical){
148 if(headers==null || headers.length<2){return false;}
149 for(int i=0; i<headers.length; i++){
150 if(headers[i]==null){return false;}
151 }
152
153 assert(headers[0]==null || headers[0].startsWith(">")) : "File "+fname+"\ndoes not appear to be a valid FASTA file:\n"+new String(headers[0]);
154 assert(headers[1]==null || headers[1].startsWith(">")) : "File "+fname+"\ndoes not appear to be a valid FASTA file:\n"+new String(headers[0]);
155
156 if(FORCE_INTERLEAVED){return true;}
157 if(PARSE_CUSTOM && fname.contains("_interleaved.")){return true;}
158
159 return testPairNames(headers[0], headers[1], allowIdentical);
160 }
161
162 public static byte testQuality(ArrayList<String> oct){
163 if(SET_QIN || oct==null || oct.size()<4 || oct.get(0)==null){return ASCII_OFFSET;}
164 if(verbose){System.err.println("testQuality()");}
165 int qflips=0;
166 int onlyValidA33=0;
167 for(int k=0; k<2; k++){
168 final int a=1+4*k, b=3+4*k;
169 if(oct.size()<b || oct.get(a)==null || oct.get(b)==null){break;}
170 byte[] bases=oct.get(a).getBytes();
171 byte[] quals=oct.get(b).getBytes();
172 // assert(false) : Arrays.toString(quals);
173 if(verbose){System.err.println(Arrays.toString(quals));}
174
175 if(DETECT_QUALITY && bases.length>=MIN_LENGTH_TO_FORCE_ASCII_33){
176 if(ASCII_OFFSET==33){
177 //do nothing
178 }else{
179 if(warnQualityChange){System.err.println("Changed from ASCII-64 to ASCII-33 due to read of length "+bases.length+" while prescanning.");}
180 ASCII_OFFSET=33;
181 SET_QIN=true;
182 }
183 DETECT_QUALITY=false;
184 }
185
186 for(int i=0; i<quals.length; i++){
187 final byte q0=quals[i];
188 if(q0<33){onlyValidA33++;}
189
190 int q=q0-ASCII_OFFSET; //Convert from ASCII33 to native.
191 if(verbose){System.err.println(q);}
192 if(DETECT_QUALITY){
193 if(ASCII_OFFSET==33 && (q>QUAL_THRESH || (bases[i]=='N' && (q==31 || q==33)))){
194 if(warnQualityChange && qflips<4){
195 System.err.println("Changed from ASCII-33 to ASCII-64 on input quality "+(char)q0+" (Q"
196 +(q)+") for base "+(char)(bases[i])+" at lines "+a+" and "+b+", position "+i+" while prescanning."
197 //+Character.toString((char)(q+ASCII_OFFSET))
198 );
199 }
200 qflips++;
201 ASCII_OFFSET=64;
202 if(DETECT_QUALITY_OUT){ASCII_OFFSET_OUT=64;}
203 for(int j=0; j<=i; j++){
204 quals[j]=(byte)(quals[j]-31);
205 }
206 }else if(ASCII_OFFSET==64 && (q<-5)){
207 if(warnQualityChange && qflips<4){
208 System.err.println("Changed from ASCII-64 to ASCII-33 on input quality "+(char)q0+" (Q"
209 +(q)+") for base "+(char)(bases[i])+" at lines "+a+" and "+b+", position "+i+" while prescanning.");
210 }
211 ASCII_OFFSET=33;
212 if(DETECT_QUALITY_OUT){ASCII_OFFSET_OUT=33;}
213 qflips++;
214 for(int j=0; j<=i; j++){
215 quals[j]=(byte)(quals[j]+31);
216 }
217 }
218 }
219 assert(q>=-5 || IGNORE_BAD_QUALITY) : "ASCII encoding for quality (currently ASCII-"+ASCII_OFFSET+") appears to be wrong for input quality "
220 +(q+ASCII_OFFSET)+" for base "+(char)(bases[i])+" at lines "+a+" and "+b+", position "+i+". Please manually set qin=33 or qin=64.\n"
221 +oct.get(k)+"\n"+oct.get(k+3)+"\n"+Arrays.toString(oct.get(k+3).getBytes());
222 assert(qflips<2 || IGNORE_BAD_QUALITY) : "Failed to auto-detect quality coding; quitting. Please manually set qin=33 or qin=64.";
223 if(DETECT_QUALITY && qflips==2){
224 if(warnQualityChange){System.err.println("WARNING: Quality scores are outside of the normal range (0-41). Assuming ASCII-33.\n");}
225 DETECT_QUALITY=false;
226 ASCII_OFFSET=33;
227 if(DETECT_QUALITY_OUT){ASCII_OFFSET_OUT=33;}
228 // warnQualityChange=false;
229 }
230 }
231 }
232
233 if(onlyValidA33>0){ASCII_OFFSET=33;}
234 return ASCII_OFFSET;
235 }
236
237 public static boolean testPairNames(Read r1, Read r2, boolean allowIdentical){
238 if(r1==null || r2==null){return false;}
239 boolean b=testPairNames(r1.id, r2.id, allowIdentical);
240 // assert(b==testPairNames_old(r1.id, r2.id, allowIdentical)) : b+"\n"+r1.id+"\n"+r2.id;
241 // assert(false);
242 return b;
243 }
244
245 public static boolean testPairNames(String id1, String id2, boolean allowIdentical){
246
247 final int len1=id1.length();
248 final int len2=id2.length();
249 if(len1!=len2){return false;} //Can happen in PacBio names, but never Illumina
250 final int idxSlash1=id1.lastIndexOf('/');
251 final int idxSlash2=id2.lastIndexOf('/');
252 final int idxSpace1=id1.indexOf(' ');
253 final int idxSpace2=id2.indexOf(' ');
254
255 // System.out.println("idxSlash1="+idxSlash1+", idxSlash2="+idxSlash2+", idxSpace1="+idxSpace1+", idxSpace2="+idxSpace2);
256
257 // System.err.println("A:");
258
259 if(idxSpace1==idxSpace2 && idxSpace1>0 && len1>=idxSpace1+3 && len2>=idxSpace2+3){
260 if(id1.charAt(idxSpace1+1)=='1' && id1.charAt(idxSpace1+2)==':' && id2.charAt(idxSpace2+1)=='2' && id2.charAt(idxSpace2+2)==':'){
261 for(int i=0; i<idxSpace1; i++){
262 if(id1.charAt(i)!=id2.charAt(i)){
263 return false;
264 }
265 }
266 // System.err.println("B");
267 return true;
268 }
269 }
270 // assert(false) : idxSpace1+", "+idxSpace2+", "+len1+", "+len2+"; "+(idxSpace1==idxSpace2)+", "+(idxSpace1>1)+", "+(len1>=idxSpace1+3)+", "+(len2>=idxSpace2+3);
271
272 if(idxSlash1==idxSlash2 && idxSlash1>0 && len1>=idxSlash1+2 && len2>=idxSlash2+2){
273 if(id1.charAt(idxSlash1+1)=='1' && id2.charAt(idxSlash2+1)=='2'){
274 for(int i=0; i<idxSlash1; i++){
275 if(id1.charAt(i)!=id2.charAt(i)){
276 return false;
277 }
278 }
279 //Here we try to weed out PacBio, which will differ after the last slash:
280 for(int i=idxSlash1+2; i<len1; i++){
281 if(id1.charAt(i)!=id2.charAt(i)){
282 return false;
283 }
284 }
285 // System.err.println("C");
286 return true;
287 }
288 }
289
290 // System.err.println("D");
291 return (allowIdentical && id1.equals(id2));
292 }
293
294 @Deprecated
295 public static boolean testPairNames_old(String id1, String id2, boolean allowIdentical){
296
297 if(id1==null || id2==null){return false;}
298
299 final int idxSlash1=id1.lastIndexOf('/');
300 final int idxSlash2=id2.lastIndexOf('/');
301 final int idxSpace1=id1.indexOf(' ');
302 final int idxSpace2=id2.indexOf(' ');
303
304 if(allowIdentical && idxSlash1<0 && idxSpace1<0){
305 return id1.equals(id2);
306 }
307
308 // System.out.println("idxSlash1="+idxSlash1+", idxSlash2="+idxSlash2+", idxSpace1="+idxSpace1+", idxSpace2="+idxSpace2);
309 if(idxSlash1==idxSlash2 && idxSlash1>1){
310 // System.out.println("A");
311 String[] split1=id1.split("/");
312 String[] split2=id2.split("/");
313 // System.out.println(Arrays.toString(split1));
314 // System.out.println(Arrays.toString(split2));
315
316 if(split1.length>1 && split2.length>1 && split1[0].equals(split2[0])){
317 // System.out.println("B");
318 if(split1[split1.length-1].contains(" ")){
319 split1[split1.length-1]=split1[split1.length-1].split(" ")[0];
320 // System.out.println("B1: "+Arrays.toString(split1));
321 }
322 if(split2[split2.length-1].contains(" ")){
323 split2[split2.length-1]=split2[split2.length-1].split(" ")[0];
324 // System.out.println("B2: "+Arrays.toString(split2));
325 }
326 if(split1[split1.length-1].equals("1") && split2[split2.length-1].equals("2")){
327 // System.out.println("B3");
328 return true;
329 }
330 }
331 }
332
333 if(idxSpace1==idxSpace2 && idxSpace1>=0){
334 // System.out.println("C");
335 if(idxSpace1==idxSpace2 && idxSpace1>1){
336 // System.out.println("D");
337 String[] split1=id1.split(" ");
338 String[] split2=id2.split(" ");
339 // System.out.println(Arrays.toString(split1));
340 // System.out.println(Arrays.toString(split2));
341
342 if(split1.length>1 && split2.length>1 && split1[0].equals(split2[0])){
343 // System.out.println("E");
344 if(split1[1].startsWith("1:") && split2[1].startsWith("2:")){return true;}
345 }
346 }
347 }
348 return false;
349 }
350
351 private static int fastqLength(Read r){
352 int len=6; //newlines, @, +
353 len+=(r.id==null ? Tools.stringLength(r.numericID) : r.id.length());
354 len+=r.length();
355 len+=(r.quality==null ? 0 : r.quality.length);
356 return len;
357 }
358
359 public static ByteBuilder toFASTQ(Read r, ByteBuilder bb){
360 int len=fastqLength(r);
361 final String id;
362 final byte[] bases=r.bases, quals=r.quality;
363 if(TAG_CUSTOM && (r.chrom>-1 && r.stop>-1)){
364 id=CustomHeader.toString(r);
365 if(id!=null){len+=id.length();}
366 }else{
367 id=r.id;
368 }
369 if(bb==null){bb=new ByteBuilder(len);}
370 else{bb.ensureExtra(len);}
371
372 bb.append('@');
373 if(id==null){bb.append(r.numericID);}
374 else{bb.append(id);}
375 bb.nl();
376
377 // if(bases!=null){for(byte b : bases){sb.append((char)b);}}
378 // sb.append('\n');
379 // sb.append('+');
380 // sb.append('\n');
381 // if(quals!=null){for(byte b : quals){sb.append((char)(b+ASCII_OFFSET_OUT));}}
382
383 if(bases==null){
384 bb.nl().append('+').append('\n');
385 if(verbose){System.err.println("A:\n"+bb);}
386 }else{
387 bb.append(bases);
388 bb.nl().append('+').append('\n');
389 if(verbose){System.err.println("B:\n"+bb);}
390 if(quals==null){
391 final byte q=(byte)(Shared.FAKE_QUAL+ASCII_OFFSET_OUT);
392 final int blen=bases.length;
393 bb.ensureExtra(blen);
394 for(int i=0, j=bb.length; i<blen; i++, j++){
395 bb.array[j]=(AminoAcid.isFullyDefined(bases[i]) ? q : ASCII_OFFSET_OUT);
396 }
397 bb.length+=blen;
398 if(verbose){System.err.println("C:\n"+bb);}
399 }else{
400 bb.ensureExtra(quals.length);
401 for(int i=0, j=bb.length; i<quals.length; i++, j++){
402 byte q=quals[i];
403 bb.array[j]=(byte)(q+ASCII_OFFSET_OUT);
404 }
405 bb.length+=quals.length;
406 if(verbose){System.err.println("D:\n"+bb);}
407 }
408 }
409 if(verbose){System.err.println("E:\n"+bb);}
410
411 // sb.append('\n');
412 return bb;
413 }
414
415 // public static StringBuilder toFASTQ(Read r, StringBuilder sb){
416 // int len=fastqLength(r);
417 // final String id;
418 // final byte[] bases=r.bases, quals=r.quality;
419 // if(TAG_CUSTOM && (r.chrom>-1 && r.stop>-1)){
420 // id=customID(r);
421 // if(id!=null){len+=id.length();}
422 // }else{
423 // id=r.id;
424 // }
425 // if(sb==null){sb=new StringBuilder(len);}
426 // else{sb.ensureCapacity(len);}
427 //
428 // sb.append('@');
429 // if(id==null){sb.append(r.numericID);}
430 // else{sb.append(id);}
431 // sb.append('\n');
432 //
433 //// if(bases!=null){for(byte b : bases){sb.append((char)b);}}
434 //// sb.append('\n');
435 //// sb.append('+');
436 //// sb.append('\n');
437 //// if(quals!=null){for(byte b : quals){sb.append((char)(b+ASCII_OFFSET_OUT));}}
438 //
439 // if(bases==null){
440 // sb.append('\n').append('+').append('\n');
441 // }else{
442 // char[] buffer=Shared.getTLCB(bases.length);
443 // for(int i=0; i<bases.length; i++){buffer[i]=(char)bases[i];}
444 // sb.append(buffer, 0, bases.length);
445 // sb.append('\n').append('+').append('\n');
446 // if(quals==null){
447 // final char q=(char)(30+ASCII_OFFSET_OUT);
448 // final int blen=bases.length;
449 // for(int i=0; i<blen; i++){buffer[i]=q;}
450 // sb.append(buffer, 0, blen);
451 // }else{
452 // for(int i=0; i<quals.length; i++){buffer[i]=(char)(quals[i]+ASCII_OFFSET_OUT);}
453 // sb.append(buffer, 0, quals.length);
454 // }
455 // }
456 //
457 //// sb.append('\n');
458 // return sb;
459 // }
460
461
462 public static Read[] toReads(TextFile tf, int maxReadsToReturn, long numericID, boolean interleaved){
463 ArrayList<Read> list=toReadList(tf, maxReadsToReturn, numericID, interleaved);
464 assert(list.size()<=maxReadsToReturn);
465 return list.toArray(new Read[list.size()]);
466 }
467
468 public static final String makeId(String s){
469 if(s==null || s.length()<1){return null;}
470 char c=s.charAt(0);
471 int start=0, stop=s.length();
472 if(c=='@' || c=='>'){start=1;}
473 if(Shared.TRIM_READ_COMMENTS){
474 for(int i=start; i<stop; i++){
475 if(Character.isWhitespace(s.charAt(i))){
476 stop=i;
477 break;
478 }
479 }
480 }
481 return stop<=start ? null : start==0 && stop==s.length() ? s : s.substring(start, stop);
482 }
483
484 public static final String makeId(byte[] s){
485 if(s==null || s.length<1){return null;}
486 byte c=s[0];
487 int start=0, stop=s.length;
488 if(c=='@' || c=='>'){start=1;}
489 if(Shared.TRIM_READ_COMMENTS){
490 for(int i=start; i<stop; i++){
491 if(Character.isWhitespace(s[i])){
492 stop=i;
493 break;
494 }
495 }
496 }
497 String id=null;
498 if(stop>start){
499 try {
500 id=new String(s, start, stop-start);
501 } catch (OutOfMemoryError e) {
502 KillSwitch.memKill(e);
503 }
504 }
505 return id;
506 }
507
508 public static ArrayList<Read> toReadList(TextFile tf, int maxReadsToReturn, long numericID, boolean interleaved){
509 String s=null;
510 ArrayList<Read> list=new ArrayList<Read>(Data.min(16384, maxReadsToReturn));
511
512 String[] quad=new String[4];
513
514 int cntr=0;
515 int added=0;
516
517 Read prev=null;
518
519 for(s=tf.nextLine(); s!=null && added<maxReadsToReturn; s=tf.nextLine()){
520 quad[cntr]=s;
521 cntr++;
522 if(cntr==4){
523 assert(quad[0].startsWith("@")) : "\nError in "+tf.name+", line "+tf.lineNum+"\n"+quad[0]+"\n"+quad[1]+"\n"+quad[2]+"\n"+quad[3]+"\n";
524 assert(quad[2].startsWith("+")) : "\nError in "+tf.name+", line "+tf.lineNum+"\n"+quad[0]+"\n"+quad[1]+"\n"+quad[2]+"\n"+quad[3]+"\n";
525
526 // if(quad[0].startsWith("@HW") || quad[0].startsWith("@FC")){ascii_offset=66;} //TODO: clumsy
527
528 final String id=makeId(quad[0]);
529
530 Read r=null;
531
532 byte[] bases=quad[1].getBytes();
533 byte[] quals=quad[3].getBytes();
534
535 if(DETECT_QUALITY && bases.length>=MIN_LENGTH_TO_FORCE_ASCII_33){
536 if(ASCII_OFFSET==33){
537 //do nothing
538 }else{
539
540 if(warnQualityChange){
541 if(numericID<1){
542 System.err.println("Changed from ASCII-64 to ASCII-33 due to read of length "+bases.length+".");
543 }else{
544 warnQualityChange=false;
545 System.err.println("Warning! Changed from ASCII-64 to ASCII-33 due to read of length "+bases.length+".");
546 System.err.println("Up to "+numericID+" prior reads may have been generated with incorrect qualities.");
547 System.err.println("If this is a problem you may wish to re-run with the flag 'qin=33' or 'qin=64'.");
548 }
549 }
550 ASCII_OFFSET=33;
551 }
552 DETECT_QUALITY=false;
553 // System.err.println("A: "+numericID+": "+bases.length);
554 }
555
556 // assert(false) : Arrays.toString(quals);
557 for(int i=0; i<quals.length; i++){
558 quals[i]-=ASCII_OFFSET; //Convert from ASCII33 to native.
559 if(DETECT_QUALITY && ASCII_OFFSET==33 && (quals[i]>QUAL_THRESH /*|| (bases[i]=='N' && quals[i]>20)*/)){
560
561 // System.err.println("B: "+numericID+": "+bases.length);
562 if(warnQualityChange){
563 if(numericID<1){
564 System.err.println("Changed from ASCII-33 to ASCII-64 on input "+((char)quals[i])+": "+quals[i]+" -> "+(quals[i]-31));
565 // assert(false) : FASTQ.DETECT_QUALITY+", "+FASTQ.IGNORE_BAD_QUALITY+", "+FASTQ.ASCII_OFFSET;
566 }else{
567 warnQualityChange=false;
568 System.err.println("Warning! Changed from ASCII-33 to ASCII-64 on input "+((char)quals[i])+": "+quals[i]+" -> "+(quals[i]-31));
569 System.err.println("Up to "+numericID+" prior reads may have been generated with incorrect qualities.");
570 System.err.println("If this is a problem you may wish to re-run with the flag 'qin=33' or 'qin=64'.");
571 }
572 }
573 ASCII_OFFSET=64;
574 for(int j=0; j<=i; j++){
575 quals[j]=(byte)(quals[j]-31);
576 }
577 }
578 assert(quals[i]>=-5) : "\n"+quad[0]+"\n"+quad[3];
579 }
580 // assert(false) : Arrays.toString(quals);
581 // assert(false) : new String(quad[0]);
582 if(PARSE_CUSTOM && quad[0]!=null && quad[0].indexOf('_')>0){
583 String[] answer=quad[0].split("_");
584 if(answer.length>=5){
585 try {
586 int trueChrom=Gene.toChromosome(answer[1]);
587 byte trueStrand=Byte.parseByte(answer[2]);
588 int trueLoc=Integer.parseInt(answer[3]);
589 int trueStop=Integer.parseInt(answer[4]);
590 r=new Read(bases, quals, id, numericID, trueStrand, trueChrom, trueLoc, trueStop);
591 r.setSynthetic(true);
592 } catch (NumberFormatException e) {}
593 }
594 }
595 if(r==null){
596 r=new Read(bases, quals, id, numericID);
597 }
598
599 cntr=0;
600
601 if(interleaved){
602 if(prev==null){prev=r;}
603 else{
604 prev.mate=r;
605 r.mate=prev;
606 r.setPairnum(1);
607 list.add(prev);
608 added++;
609 numericID++;
610 prev=null;
611 }
612 }else{
613 list.add(r);
614 added++;
615 numericID++;
616 }
617
618
619 if(added>=maxReadsToReturn){break;}
620
621 // System.out.println(r.chrom+", "+r.strand+", "+r.loc);
622 // assert(false);
623 }
624 }
625 assert(list.size()<=maxReadsToReturn);
626 return list;
627 }
628
629 public static ArrayList<Read> toReadList(final ByteFile bf, final int maxReadsToReturn, long numericID, final boolean interleaved, final int flag){
630 ArrayList<Read> list=new ArrayList<Read>(Data.min(8192, maxReadsToReturn));
631 final byte[][] quad=new byte[4][];
632
633 int cntr=0, added=0;
634
635 if(interleaved){
636 Read prev=null;
637 for(byte[] s=bf.nextLine(); s!=null; s=bf.nextLine()){
638 quad[cntr]=s;
639 cntr++;
640 if(cntr==4){
641 cntr=0;
642 final Read r=quadToRead_slow(quad, false, bf, numericID, flag);
643
644 if(prev==null){prev=r;}
645 else{
646 prev.mate=r;
647 r.mate=prev;
648 r.setPairnum(1);
649 list.add(prev);
650 added++;
651 numericID++;
652 prev=null;
653 if(added>=maxReadsToReturn){break;}
654 }
655 }
656 }
657
658 if(!PAIR_READS){
659 for(Read r : list) {r.mate=null;}
660 }else if(FLIP_R2){
661 for(Read r : list) {r.mate.reverseComplement();}
662 }
663
664 }else{
665
666 //Prevents problems with PacBio's weird quality numbers. Usually.
667 if(DETECT_QUALITY && numericID==0){//first read
668 for(byte[] s=bf.nextLine(); s!=null; s=bf.nextLine()){
669 if(cntr==1 && s.length>=MIN_LENGTH_TO_FORCE_ASCII_33){//Chances of ASCII-64 are vanishingly small
670 // SET_QIN=true;
671 DETECT_QUALITY=false;
672 ASCII_OFFSET=33;
673 }
674 quad[cntr]=s;
675 cntr++;
676 if(cntr==4){
677 cntr=0;
678 final Read r=quadToRead_slow(quad, false, bf, numericID, flag);
679
680 list.add(r);
681 added++;
682 numericID++;
683 if(added>=maxReadsToReturn){return list;}
684 }
685 }
686 }
687
688 for(byte[] s=bf.nextLine(); s!=null; s=bf.nextLine()){
689 quad[cntr]=s;
690 cntr++;
691 if(cntr==4){
692 cntr=0;
693 final Read r=quadToRead_slow(quad, false, bf, numericID, flag);
694
695 list.add(r);
696 added++;
697 numericID++;
698 if(added>=maxReadsToReturn){break;}
699 }
700 }
701 }
702 assert(list.size()<=maxReadsToReturn);
703 return list;
704 }
705
706 public static byte[][] scarfToQuad(final byte[] scarf, byte[][] quad){
707
708 int a=-1, b=-1;
709 final byte colon=':';
710 for(int i=scarf.length-1; i>=0; i--){
711 if(scarf[i]==colon){
712 if(b<0){b=i;}
713 else{
714 assert(a<0);
715 a=i;
716 break;
717 }
718 }
719 }
720 if(a<0 || b<0){
721 throw new RuntimeException("Misformatted scarf line: "+new String(scarf));
722 }
723 if(quad==null){quad=new byte[4][];}
724 quad[0]=KillSwitch.copyOfRange(scarf, 0, a);
725 quad[1]=KillSwitch.copyOfRange(scarf, a+1, b);
726 quad[3]=KillSwitch.copyOfRange(scarf, b+1, scarf.length);
727 return quad;
728 }
729
730 public static Read quadToRead_slow(final byte[][] quad, boolean scarf, ByteFile bf, long numericID, final int flag){
731
732 if(verbose){
733 System.err.println("\nASCII offset is "+ASCII_OFFSET);
734 System.err.println("quad:");
735 System.err.println(new String(quad[0]));
736 System.err.println(new String(quad[1]));
737 System.err.println(new String(quad[2]));
738 System.err.println(new String(quad[3]));
739 }
740
741 assert(scarf || (quad[0].length>0 && quad[0][0]==(byte)'@')) : "\nError in "+bf.name()+", line "+bf.lineNum()+", with these 4 lines:\n"+
742 new String(quad[0])+"\n"+new String(quad[1])+"\n"+new String(quad[2])+"\n"+new String(quad[3])+"\n";
743 assert(scarf || (quad[0].length>0 && quad[2].length>0 && quad[2][0]==(byte)'+')) : "\nError in "+bf.name()+", line "+bf.lineNum()+", with these 4 lines:\n"+
744 new String(quad[0])+"\n"+new String(quad[1])+"\n"+new String(quad[2])+"\n"+new String(quad[3])+"\n";
745
746 // if(quad[0].startsWith("@HW") || quad[0].startsWith("@FC")){ascii_offset=66;} //TODO: clumsy
747
748 Read r=null;
749
750 final String id=makeId(quad[0]);
751 final byte[] bases=quad[1];
752 final byte[] quals=quad[3];
753
754 // System.err.println("\n"+new String(quad[0])+"\n"+new String(quad[1])+"\n"+new String(quad[2])+"\n"+new String(quad[3])+"\n");
755 // assert(false) : numericID;
756
757 // assert(false) : Arrays.toString(quals);
758 for(int i=0; i<quals.length; i++){
759 quals[i]-=ASCII_OFFSET; //Convert from ASCII33 to native.
760 if(DETECT_QUALITY && ASCII_OFFSET==33 && (quals[i]>QUAL_THRESH /*|| (bases[i]=='N' && quals[i]>20)*/)){
761 if(warnQualityChange){
762 if(numericID<1){
763 System.err.println("Changed from ASCII-33 to ASCII-64 on input "+((char)quals[i])+": "+quals[i]+" -> "+(quals[i]-31));
764 // assert(false) : FASTQ.DETECT_QUALITY+", "+FASTQ.IGNORE_BAD_QUALITY+", "+FASTQ.ASCII_OFFSET;
765 }else{
766 warnQualityChange=false;
767 System.err.println("Warning! Changed from ASCII-33 to ASCII-64 on input "+((char)quals[i])+": "+quals[i]+" -> "+(quals[i]-31));
768 System.err.println("Up to "+numericID+" prior reads may have been generated with incorrect qualities.");
769 System.err.println("If this is a problem you may wish to re-run with the flag 'qin=33' or 'qin=64'.");
770 errorState=true;
771 }
772 }
773 ASCII_OFFSET=64;
774 for(int j=0; j<=i; j++){
775 quals[j]=(byte)(quals[j]-31);
776 }
777 }
778 if(quals[i]<0){
779
780 if(IGNORE_BAD_QUALITY || quals[i]>=-5){
781 //Do nothing
782 }else if(SET_QIN){
783 if(!negativeFive){
784 System.err.println("\n***WARNING***: The ASCII quality encoding offset ("+ASCII_OFFSET+") may not be set correctly."
785 + "\nProblematic read number "+numericID+": "+new String(quad[0])+"\n");
786 errorState=true;
787 negativeFive=true;
788 }
789 }else{
790 if(!negativeFive){
791 {
792 for(int j=0; j<quals.length; j++){quals[j]=Tools.max(quals[j], ASCII_OFFSET);}
793 System.err.println("\nThe ASCII quality encoding offset ("+ASCII_OFFSET+") is not set correctly, or the reads are corrupt; quality value below -5.\n" +
794 "Please re-run with the flag 'qin=33', 'ignorebadquality', or '-da'.\nProblematic read number "+numericID+":\n" +
795
796 "\n"+new String(quad[0])+"\n"+new String(quad[1])+"\n"+new String(quad[2])+"\n"+new String(quad[3])+"\n");
797 System.err.println("Offset="+ASCII_OFFSET);
798 }
799 }
800
801 if(EA && !SET_QIN){KillSwitch.kill();}
802 // assert(false);
803 errorState=true;
804 negativeFive=true;
805 }
806 quals[i]=0;
807 }
808 // assert(false);
809 // assert(quals[i]>=-5) : "The ASCII quality encoding level is not set correctly. Quality value below -5:" +
810 // "\n"+new String(quad[0])+"\n"+new String(quad[1])+"\n"+new String(quad[2])+"\n"+new String(quad[3]);
811 }
812 // assert(false) : Arrays.toString(quals);
813 // assert(false) : PARSE_CUSTOM+"\n"+new String(quad[0]);
814 if(PARSE_CUSTOM){
815
816 if(PARSE_NEW){
817 CustomHeader h=new CustomHeader(id);
818 r=new Read(bases, quals, id, numericID, h.strand, h.bbchrom, h.bbstart, h.bbstop());
819 r.setSynthetic(true);
820 r.setInsert(h.insert);
821 r.makeOriginalSite();
822 }else{
823 if(quad[0]!=null && Tools.indexOf(quad[0], (byte)'_')>0){
824 String temp=new String(quad[0]);
825 if(temp.endsWith(" /1") || temp.endsWith(" /2")){temp=temp.substring(0, temp.length()-3);}
826 String[] answer=temp.split("_");
827
828 if(answer.length>=5){
829 try {
830 int trueChrom=Gene.toChromosome(answer[1]);
831 byte trueStrand=Byte.parseByte(answer[2]);
832 int trueLoc=Integer.parseInt(answer[3]);
833 int trueStop=Integer.parseInt(answer[4]);
834 r=new Read(bases, quals, id, numericID, trueStrand, trueChrom, trueLoc, trueStop);
835 r.setSynthetic(true);
836 } catch (NumberFormatException e) {
837 PARSE_CUSTOM=false;
838 if(PARSE_CUSTOM_WARNING){
839 System.err.println("Turned off PARSE_CUSTOM because could not parse "+new String(quad[0]));
840 }
841 }
842 }else{
843 PARSE_CUSTOM=false;
844 if(PARSE_CUSTOM_WARNING){
845 System.err.println("Turned off PARSE_CUSTOM because answer="+Arrays.toString(answer));
846 }
847 }
848 }else{
849 PARSE_CUSTOM=false;
850 if(PARSE_CUSTOM_WARNING){
851 System.err.println("Turned off PARSE_CUSTOM because quad[0]="+new String(quad[0])+", index="+Tools.indexOf(quad[0], (byte)'_'));
852 }
853 }
854 }
855 }
856 if(r==null){
857 try {
858 r=new Read(bases, quals, id, numericID, flag);
859 } catch (OutOfMemoryError e) {
860 KillSwitch.memKill(e);
861 }
862 }
863 return r;
864 }
865
866 /** Should be faster, but is slower */
867 public static Read quadToRead_fast(final byte[][] quad, final ByteFile bf, final long numericID, final int flag){
868
869 final byte offset=ASCII_OFFSET;
870 final byte[] header=quad[0];
871 final byte[] bases=quad[1];
872 final byte[] quals=quad[3];
873 final String id=makeId(header);
874
875 if(header==null || header.length<1 || header[0]!=(byte)'@'){return quadToRead_slow(quad, false, bf, numericID, flag);}
876
877 // boolean over=false;
878 // int negative=0;
879 boolean bad=false;
880 for(int i=0; i<quals.length; i++){
881 final byte q=(byte)(quals[i]-offset);
882 quals[i]=q;
883 // if(q<0 || (DETECT_QUALITY && ASCII_OFFSET==33 && q>QUAL_THRESH)){return null;}
884 bad|=(q<0 || (DETECT_QUALITY && ASCII_OFFSET==33 && q>QUAL_THRESH));
885 // negative=quals[i]|negative;
886 // over|=quals[i]>QUAL_THRESH;
887 }
888 if(bad/*over || negative<0*/){
889 FAST_FAILED=true;
890 for(int i=0; i<quals.length; i++){quals[i]+=offset;}
891 return quadToRead_slow(quad, false, bf, numericID, flag);
892 }
893
894 Read r=null;
895 try {
896 r=new Read(bases, quals, id, numericID, flag);
897 } catch (OutOfMemoryError e) {
898 KillSwitch.memKill(e);
899 }
900 return r;
901 }
902
903 public static ArrayList<Read> toScarfReadList(ByteFile tf, int maxReadsToReturn, long numericID, boolean interleaved){
904 byte[] s=null;
905 ArrayList<Read> list=new ArrayList<Read>(Data.min(16384, maxReadsToReturn));
906
907 byte[][] quad=new byte[4][];
908
909 int added=0;
910
911 Read prev=null;
912
913 for(s=tf.nextLine(); s!=null && added<maxReadsToReturn; s=tf.nextLine()){
914 scarfToQuad(s, quad);
915 Read r=quadToRead_slow(quad, true, tf, numericID, 0);
916
917 if(interleaved){
918 if(prev==null){prev=r;}
919 else{
920 prev.mate=r;
921 r.mate=prev;
922 r.setPairnum(1);
923 list.add(prev);
924 added++;
925 numericID++;
926 prev=null;
927 }
928 }else{
929 list.add(r);
930 added++;
931 numericID++;
932 }
933
934
935 if(added>=maxReadsToReturn){break;}
936 }
937 assert(list.size()<=maxReadsToReturn);
938 return list;
939 }
940
941 public static String qualToString(byte[] quals){
942 byte[] q2=KillSwitch.allocByte1D(quals.length);
943 for(int i=0; i<quals.length; i++){
944 q2[i]=(byte)(quals[i]+ASCII_OFFSET);
945 }
946 return new String(q2);
947 }
948
949 /** Return true if this has detected an error */
950 public static boolean errorState(){return errorState;}
951 public static boolean setErrorState(boolean b){return errorState=b;}
952
953 private static boolean errorState=false;
954 private static boolean negativeFive=false;
955
956 private static synchronized long incr(){return incr++;}
957 private static long incr=10000000000L;
958
959 public static boolean PARSE_CUSTOM=false;
960 public static boolean PARSE_NEW=true;
961 public static boolean PARSE_CUSTOM_WARNING=true;
962 public static boolean TAG_CUSTOM=false;
963 public static boolean TAG_CUSTOM_SIMPLE=false;
964 public static boolean DELETE_OLD_NAME=false;
965 public static byte ASCII_OFFSET=33;
966 public static byte ASCII_OFFSET_OUT=33;
967
968 /** Autodetect interleaving based on read names */
969 public static boolean TEST_INTERLEAVED=true;
970 public static boolean TEST_BARCODE=false;
971
972 /** Override autodetection and treat input as interleaved */
973 public static boolean FORCE_INTERLEAVED=false;
974 public static boolean DETECT_QUALITY=true;
975 public static boolean DETECT_QUALITY_OUT=true;
976 public static boolean ADD_PAIRNUM_TO_CUSTOM_ID=true;
977 public static boolean ADD_SLASH_PAIRNUM_TO_CUSTOM_ID=false;
978 public static boolean SPACE_SLASH=false;
979 public static boolean FAST_FAILED=false;
980 public static boolean SHRINK_HEADERS=false;
981
982 public static boolean PAIR_READS=true;
983 public static boolean FLIP_R2=false;
984
985 public static final int MIN_LENGTH_TO_FORCE_ASCII_33=200;
986 public static final int QUAL_THRESH=54;
987 public static boolean IGNORE_BAD_QUALITY=false;
988 public static boolean SET_QIN=false;
989 public static boolean verbose=false;
990
991 public static boolean warnQualityChange=true;
992
993 private static boolean EA=Shared.EA();
994
995 }