Debian Codegraph @

current/stream/FastaReadInputStream.java

raw symbols SCIP
1 package stream;
2
3 import java.io.InputStream;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6
7 import dna.Gene;
8 import fileIO.FileFormat;
9 import fileIO.ReadWrite;
10 import shared.KillSwitch;
11 import shared.Shared;
12 import shared.Timer;
13 import shared.Tools;
14
15 /**
16 * @author Brian Bushnell
17 * @date Feb 13, 2013
18 *
19 */
20 public class FastaReadInputStream extends ReadInputStream {
21
22 public static void main(String[] args){
23
24 int a=20, b=Integer.MAX_VALUE;
25 if(args.length>1){a=Integer.parseInt(args[1]);}
26 if(args.length>2){b=Integer.parseInt(args[2]);}
27 if(args.length>3){MIN_READ_LEN=Integer.parseInt(args[3]);}
28 if(args.length>4){TARGET_READ_LEN=Integer.parseInt(args[4]);}
29 if(TARGET_READ_LEN<1){
30 TARGET_READ_LEN=Integer.MAX_VALUE;
31 SPLIT_READS=false;
32 }else{
33 SPLIT_READS=true;
34 }
35
36 Timer t=new Timer();
37
38 FastaReadInputStream fris=new FastaReadInputStream(args[0], false, false, false, Shared.bufferData());
39 Read r=fris.next();
40 int i=0;
41
42 while(r!=null){
43 if(i<a){System.out.println("'"+r.toText(false)+"'");}
44 r=fris.next();
45 if(++i>=a){break;}
46 }
47 while(r!=null && i++<b){r=fris.next();}
48 t.stop();
49 System.out.println("Time: \t"+t);
50 }
51
52 public FastaReadInputStream(String fname, boolean interleaved_, boolean amino_, boolean allowSubprocess_, long maxdata){
53 this(FileFormat.testInput(fname, FileFormat.FASTA, FileFormat.FASTA, 0, allowSubprocess_, false, false), interleaved_, amino_, maxdata);
54 }
55
56 public FastaReadInputStream(FileFormat ff, boolean interleaved_, boolean amino_, long maxdata){
57 name=ff.name();
58 amino=amino_;
59 flag=(amino ? Read.AAMASK : 0);
60
61 if(!fileIO.FileFormat.hasFastaExtension(name) && !name.startsWith("stdin")){
62 System.err.println("Warning: Did not find expected fasta file extension for filename "+name);
63 }
64
65 interleaved=interleaved_;
66 allowSubprocess=ff.allowSubprocess();
67 minLen=MIN_READ_LEN;
68 maxLen=(SPLIT_READS ? (TARGET_READ_LEN>0 ? TARGET_READ_LEN : Integer.MAX_VALUE) : Integer.MAX_VALUE);
69 MAX_DATA=maxdata>0 ? maxdata : Shared.bufferData();
70
71 ins=open();
72
73 assert(settingsOK());
74 }
75
76 @Override
77 public Read next() {
78 if(!hasMore()){
79 if(verbose){System.err.println("hasMore() returned false; currentList="+
80 (currentList==null ? null : currentList.size())+", nextReadIndex="+nextReadIndex+", consumed="+consumed);}
81 return null;
82 }
83 Read r=currentList.set(nextReadIndex, null);
84 nextReadIndex++;
85 consumed++;
86 return r;
87 }
88
89 @Override
90 public ArrayList<Read> nextList() {
91 if(nextReadIndex!=0){throw new RuntimeException("'next' should not be used when doing blockwise access.");}
92 if(currentList==null || nextReadIndex>=currentList.size()){
93 boolean b=fillList();
94 }
95 ArrayList<Read> list=currentList;
96 currentList=null;
97 if(list==null || list.isEmpty()){
98 list=null;
99 }else{
100 consumed+=list.size();
101 }
102 return list;
103 }
104
105 @Override
106 public boolean hasMore() {
107 if(currentList==null || nextReadIndex>=currentList.size()){
108 if(open){
109 fillList();
110 }else{
111 // assert(generated>0) : "Was the file empty?";
112 }
113 }
114 return (currentList!=null && nextReadIndex<currentList.size());
115 }
116
117 @Override
118 public void restart() {
119 if(ins!=null){close();}
120 assert(ins==null);
121 // generated=0;
122 consumed=0;
123 nextReadIndex=0;
124 nextReadID=0;
125 currentList=null;
126 header=null;
127 bstart=0;
128 bstop=0;
129
130 currentSection=0;
131 if(ins==null){
132 ins=open();
133 }else{
134 assert(false) : "is should be null";
135 }
136 }
137
138 @Override
139 public final boolean close(){
140 synchronized(this){
141 if(!open){return false;}
142 open=false;
143 assert(ins!=null);
144
145 try {
146 if(ins!=System.in){
147 errorState|=ReadWrite.finishReading(ins, name, allowSubprocess);
148 }
149 } catch (Exception e) {
150 System.err.println("Some error occured: "+e);
151 errorState=true;
152 }
153
154 ins=null;
155 }
156 return false;
157 }
158
159 @Override
160 public boolean paired() {return interleaved;}
161
162 @Override
163 public void start() {}
164
165 private final boolean fillList(){
166 // assert(open);
167 if(!open){
168 currentList=null;
169 return false;
170 }
171 assert(currentList==null || nextReadIndex>=currentList.size());
172 nextReadIndex=0;
173 currentList=new ArrayList<Read>(BUF_LEN);
174
175 if(header==null){
176 header=nextHeader();
177 if(header==null){
178 currentList=null;
179 return false;
180 }
181 }
182 long len=0;
183 for(int i=0; i<BUF_LEN && len<MAX_DATA; i++){
184 Read r=generateRead(0);
185 if(r==null){break;}
186 currentList.add(r);
187 len+=r.length();
188 if(interleaved){
189 Read r2=generateRead(1);
190 if(r2==null){break;}
191 len+=r2.length();
192 r.mate=r2;
193 r2.mate=r;
194 }
195 nextReadID++;
196 if(verbose){System.err.println("Generated a read; i="+i+", BUF_LEN="+BUF_LEN);}
197 // if(i==1){assert(false) : r.numericID+", "+r.mate.numericID;}
198 }
199
200 return currentList.size()>0;
201 }
202
203 private final Read generateRead(int pairnum){
204 if(verbose){System.err.println("Called generateRead(); bstart="+bstart+", bstop="+bstop+", currentSection="+currentSection+", header="+header);}
205 assert(header!=null) : "Null header for fasta read - input file may be corrupt: "+name;
206 if(bstart<bstop && buffer[bstart]==carrot){
207 header=nextHeader();
208 currentSection=0;
209 }
210 if(header==null){
211 close();
212 return null;
213 }
214 byte[] bases=nextBases();
215
216 currentSection++;
217 while(bases==null){
218 // if(!open){return null;} //Should not be needed...
219 header=nextHeader();
220 if(header==null){
221 close();
222 return null;
223 }
224 bases=nextBases();
225 currentSection=1;
226 }
227 assert(bases!=null);
228 assert(bases.length>0);
229
230 byte[] quals=null;
231 if(FAKE_QUALITY){
232 quals=new byte[bases.length];
233 Arrays.fill(quals, (byte)(Shared.FAKE_QUAL));
234 }
235 // String hd=((currentSection==1 && !hitmax) ? header : header+"_"+currentSection);
236 String hd=((!FORCE_SECTION_NAME && currentSection==1 && bases.length<=maxLen) ? header : header+"_part_"+currentSection);
237 // assert(false) : FORCE_SECTION_NAME+", "+(currentSection==1)+", "+(bases.length<=maxLen)+", "+bases.length+", "+maxLen;
238 assert(currentSection==1 || bases.length>0) : "id="+hd+", section="+currentSection+", len="+bases.length+"\n"+new String(bases);
239 Read r=null;
240 if(FASTQ.PARSE_CUSTOM){//TODO: This appears to be legacy code from old custom header format, which won't work anymore
241 assert(false) : "TODO - this code for parsing custom headers of fasta files is obsolete.";
242 if(header!=null && header.indexOf('_')>0){
243 String temp=header;
244 if(temp.endsWith(" /1") || temp.endsWith(" /2")){temp=temp.substring(0, temp.length()-3);}
245 String[] answer=temp.split("_");
246
247 if(answer.length>=5){
248 try {
249 int trueChrom=Gene.toChromosome(answer[1]);
250 byte trueStrand=Byte.parseByte(answer[2]);
251 int trueLoc=Integer.parseInt(answer[3]);
252 int trueStop=Integer.parseInt(answer[4]);
253 // r=new Read(bases, trueChrom, trueStrand, trueLoc, trueStop, hd, quals, nextReadID);
254 r=new Read(bases, quals, hd, nextReadID, (flag|trueStrand), trueChrom, trueLoc, trueStop);
255 r.setSynthetic(true);
256 } catch (NumberFormatException e) {
257 FASTQ.PARSE_CUSTOM=false;
258 System.err.println("Turned off PARSE_CUSTOM because could not parse "+new String(header));
259 }
260 }else{
261 FASTQ.PARSE_CUSTOM=false;
262 System.err.println("Turned off PARSE_CUSTOM because answer="+Arrays.toString(answer));
263 }
264 }else{
265 FASTQ.PARSE_CUSTOM=false;
266 System.err.println("Turned off PARSE_CUSTOM because header="+header+", index="+header.indexOf('_'));
267 }
268 }
269 if(r==null){
270 r=new Read(bases, quals, hd, nextReadID, flag);
271 }
272 r.setPairnum(pairnum);
273 if(verbose){System.err.println("Made read:\t"+(r.length()>1000 ? r.id : r.toString()));}
274 return r;
275 }
276
277 private String nextHeader(){
278 if(verbose){System.err.println("Called nextHeader(); bstart="+bstart+"; bstop="+bstop);}
279 assert(bstart>=bstop || buffer[bstart]=='>' || buffer[bstart]<=slashr) : bstart+", "+bstop+", '"+(char)buffer[bstart]+"'"+"\t"+name;
280 while(bstart<bstop && buffer[bstart]!='>'){bstart++;}
281 int x=bstart;
282 assert(bstart>=bstop || buffer[x]=='>') : bstart+", "+bstop+", '"+(char)buffer[x]+"'";
283 while(x<bstop && buffer[x]>slashr){x++;}
284 if(verbose){System.err.println("A: x="+x);}
285 if(x<bstop && (buffer[x]<=STX || buffer[x]==tab)){ //Handle deprecated 'SOH' symbol and tab
286 while(x<bstop && (buffer[x]>slashr || buffer[x]<=STX || buffer[x]==tab)){
287 if(buffer[x]==0x1){buffer[x]=carrot;}
288 x++;
289 }
290 }
291 if(verbose){System.err.println("B: x="+x);}
292 if(x>=bstop){
293 int fb=fillBuffer();
294 if(verbose){System.err.println("B: fb="+fb);}
295 if(fb<1){
296 if(verbose){System.err.println("Returning null from nextHeader()");}
297 return null;
298 }
299 x=0;
300 assert(bstart==0 && bstart<bstop && buffer[x]=='>') : "Improperly formatted fasta file; expecting '>' symbol.\n"+
301 (buffer[x]=='@' ? "If this is a fastq file, please rename it with a '.fastq' extension.\n" : "")+
302 bstart+", "+bstop+", "+(int)buffer[x]+", "+(char)buffer[x]; //Note: This assertion will fire if a fasta file starts with a newline.
303 while(x<bstop && buffer[x]>slashr){x++;}
304 if(x<bstop && (buffer[x]<=STX || buffer[x]==tab)){ //Handle deprecated 'SOH' symbol and tab
305 while(x<bstop && (buffer[x]>slashr || buffer[x]<=STX || buffer[x]==tab)){
306 if(buffer[x]==0x1){buffer[x]=carrot;}
307 x++;
308 }
309 }
310 }
311 if(verbose){System.err.println("C: x="+x);}
312 assert(x>=bstop || buffer[x]<=slashr);
313
314 int start=bstart+1, stop=x;
315 if(Shared.TRIM_READ_COMMENTS){
316 for(int i=start; i<stop; i++){
317 if(Character.isWhitespace(buffer[i])){
318 stop=i;
319 break;
320 }
321 }
322 }
323
324 String s=stop>start ? new String(buffer, start, stop-start) : "";
325 // String s=new String(buffer, bstart+1, x-(bstart+1));
326 if(verbose){System.err.println("Fetched header: '"+s+"'");}
327 bstart=x+1;
328
329 return s;
330 }
331
332 private byte[] nextBases(){
333 if(verbose){System.err.println("Called nextBases()");}
334 // assert(open) : "Attempting to read from a closed file. Current header: "+header;
335 if(bstart>=bstop){
336 int bytes=fillBuffer();
337 if(bytes<1 || !open){return null;}
338 }
339 int x=bstart;
340 int bases=0;
341
342 if(!(x>=bstop || buffer[x]!='>')){
343 handleNoSequence(x);
344 }
345
346 // assert(x>=bstop || buffer[x]!='>') :
347 // "A fasta header with no sequence was encountered. To discard such headers, please re-run with the -da flag.";
348 //"\n<START>"+new String(buffer, 0, Tools.min(x+1, buffer.length))+"<STOP>\n";
349
350 while(x<bstop && bases<maxLen && buffer[x]!='>'){
351 while(x<bstop && bases<maxLen && buffer[x]!='>'){
352 if(buffer[x]>slashr){bases++;}
353 x++;
354 }
355 assert(x==bstop || buffer[x]=='>' || bases==maxLen);
356 if(x==bstop && bases<maxLen){
357 int fb=fillBuffer();
358 if(fb<1){
359 x=bstop;
360 if(verbose){System.err.println("Broke loop when fb="+fb+"; bstart="+bstart+", bstop="+bstop);}
361 break;
362 }
363 x=bstart;
364 bases=0;
365 }
366 }
367
368 if(bases<minLen){
369
370 if(bases==0){handleNoSequence(x);}
371
372 // assert(open) : "Attempting to read from a closed file. Current header: "+header;
373 bstart=x;
374 if(verbose){System.err.println("Fetched "+bases+" bases; returning null. bstart="+bstart+", bstop="+bstop/*+"\n"+new String(buffer)*/);}
375 return null;
376 }
377
378 byte[] r=new byte[bases];
379
380 // if(Read.TO_UPPER_CASE){
381 // for(int i=bstart, j=0; j<bases; i++){
382 // assert(i<x);
383 // byte b=buffer[i];
384 // // if(verbose){System.err.println("grabbed base "+(char)b+" = "+b);}
385 // if(b>slashr){
386 // r[j]=(b<91 ? b : (byte)(b-32));//Convert to upper case
387 // // if(verbose){System.err.println("set to base "+(char)r[j]+" = "+r[j]);}
388 // j++;
389 // }
390 // }
391 // }else{
392 for(int i=bstart, j=0; j<bases; i++){
393 assert(i<x);
394 byte b=buffer[i];
395 if(b>slashr){
396 r[j]=b;
397 j++;
398 }
399 }
400 // }
401
402 if(verbose){System.err.println("Fetched "+bases+" bases, open="+open+":\n'"+(r.length>1000 ? "*LONG*" : new String(r))+"'");}
403
404 bstart=x;
405 return r;
406 }
407
408 private void handleNoSequence(int x){
409 if(currentSection>0){return;}//This section is spuriously entered for reads that are a multiple of the target read length when splitting.
410 if(WARN_IF_NO_SEQUENCE){
411 synchronized(getClass()){
412 if(reportedHeader==header){return;}
413 reportedHeader=header;
414 System.err.println("Warning: A fasta header with no sequence was encountered ("+currentSection+"):\n"+header+"\n");
415 if(WARN_FIRST_TIME_ONLY){WARN_IF_NO_SEQUENCE=false;}
416 }
417 }
418 assert(!ABORT_IF_NO_SEQUENCE) : "\n<START>"+new String(buffer, 0, Tools.min(x+1, buffer.length))+"<STOP>\n";
419 }
420
421 /** Fills buffer. Ensures that result will extend to the next caret or EOF. Returns number of bytes filled. */
422 private final int fillBuffer(){
423 // assert(open);
424 if(!open){return 0;}
425 if(verbose){System.err.println("fillBuffer() : bstart="+bstart+", bstop="+bstop);}
426 if(bstart<bstop){ //Shift end bytes to beginning
427 if(bstart>0){
428 // assert(bstart>0) : bstart+", "+bstop+", "+new String(buffer);
429 int extra=bstop-bstart;
430 for(int i=0; i<extra; i++, bstart++){
431 buffer[i]=buffer[bstart];
432 }
433 bstop=extra;
434 }
435 }else{
436 bstop=0;
437 }
438 if(verbose){System.err.println("After shift : bstart="+bstart+", bstop="+bstop);}
439
440 // assert(bstart>0 || buffer[0]=='>') : "bstart="+bstart+", bstop="+bstop+", buffer[0]='"+(char)buffer[0]+"'";
441 // assert(bstart<=bstop) : "bstart="+bstart+", bstop="+bstop+", buffer[0]='"+(char)buffer[0]+"'";
442
443 bstart=0;
444
445 int len=bstop;
446 int r=-1;
447 int sum=0;
448 boolean seenNewline=false;
449 while(len==bstop){//hit end of input without encountering a caret
450 if(bstop==buffer.length){
451 buffer=KillSwitch.copyOf(buffer, buffer.length*2L);
452 if(verbose){System.err.println("Resized to "+buffer.length);}
453 }
454 if(verbose){System.err.println("A: bstop="+bstop+", len="+len);}
455 try {
456 r=-1;
457 r=ins.read(buffer, bstop, buffer.length-bstop);
458 } catch (Exception e) {
459 //e.printStackTrace(); //This can happen sometimes when using a fixed number of reads.
460 }
461 if(verbose){System.err.println("B: r="+r);}
462 //if(verbose){System.err.println("r="+r);}
463 if(r>0){
464 sum+=r;
465 bstop=bstop+r;
466 if(bstop>0 && len==0){len=1;}//Probably to skip the first >
467
468 while(len<bstop && (buffer[len]!=carrot || !seenNewline)){//I need to see a caret after newline
469 seenNewline|=(buffer[len]=='\n');
470 len++;
471 }
472 if(verbose){System.err.println("C: bstop="+bstop+", len="+len+", seenNewline="+seenNewline/*+", seenCarrot="+seenCarrot*/);}
473 }else{
474 len=bstop;
475 if(verbose){System.err.println("D: bstop="+bstop+", len="+len);}
476 break;
477 }
478 }
479 if(verbose){System.err.println("E: bstop="+bstop+", len="+len+", r="+r);}
480
481 //Skip ';'-delimited comments
482 if(header==null && bstop>bstart && buffer[bstart]==';'){
483 if(sum==0){return sum;}
484 int lastsemi=bstart;
485 assert(nextReadID==0);
486 assert(bstart==0);
487 while(bstop>bstart && buffer[bstart]==';'){
488 while(bstop>bstart && (buffer[bstart]>slashr || buffer[bstart]<=STX || buffer[bstart]==tab)){bstart++;}
489 while(bstop>bstart && buffer[bstart]<=slashr){bstart++;}
490 }
491 if(bstart>=bstop){ //Overflowed buffer with comments; recur
492 bstart=lastsemi;
493 return fillBuffer();
494 }
495 }
496
497 assert(r==-1 || buffer[len]=='>');
498 if(verbose){System.err.println("After filling: bstart="+bstart+", bstop="+bstop+", len="+len+", r="+r+", sum="+sum);}
499 return sum;
500 }
501
502 private final InputStream open(){
503 if(open){
504 throw new RuntimeException("Attempt to open already-opened fasta file "+name);
505 }
506 open=true;
507 ins=ReadWrite.getInputStream(name, true, allowSubprocess);
508 bstart=0;
509 bstop=0;
510 // lasteol=-1;
511 return ins;
512 }
513
514 public boolean isOpen(){return open;}
515
516 /** Validate fasta settings for auto-shredding input.
517 * This is kind of obsolete legacy code for BBMap. */
518 public static final boolean settingsOK(){
519 if(MIN_READ_LEN>=Integer.MAX_VALUE-1){
520 throw new RuntimeException("Minimum FASTA read length is too long: "+MIN_READ_LEN);
521 }
522 if(MIN_READ_LEN<1){
523 throw new RuntimeException("Minimum FASTA read length is too short: "+MIN_READ_LEN);
524 }
525 if(SPLIT_READS){
526 if(TARGET_READ_LEN<1){
527 throw new RuntimeException("Target FASTA read length is too short: "+TARGET_READ_LEN);
528 }
529 if(MIN_READ_LEN>TARGET_READ_LEN){
530 throw new RuntimeException("Minimum FASTA read length is longer than maximum read length: "+MIN_READ_LEN+">"+TARGET_READ_LEN);
531 }
532 }
533 if(MIN_READ_LEN>=Integer.MAX_VALUE-1 || MIN_READ_LEN<1){return false;}
534 if(SPLIT_READS && (TARGET_READ_LEN<1 || MIN_READ_LEN>TARGET_READ_LEN)){return false;}
535 return true;
536 }
537
538 @Override
539 public String fname(){return name;}
540
541 public final String name;
542
543 private ArrayList<Read> currentList=null;
544 private String header=null;
545
546 private String reportedHeader=null;
547
548 private boolean open=false;
549 private byte[] buffer=new byte[16384];
550 private int bstart=0, bstop=0;
551 public InputStream ins;
552
553 private long consumed=0;
554 private long nextReadID=0;
555 private int nextReadIndex=0;
556 private int currentSection=0;
557
558 public final boolean allowSubprocess;
559 public final boolean interleaved;
560 public final boolean amino;
561 public final int flag;
562 private final int BUF_LEN=Shared.bufferLen();
563 private final long MAX_DATA;
564 private final int maxLen, minLen;
565
566
567 public static boolean verbose=false;
568 private static final byte slashr='\r', slashn='\n', carrot='>', space=' ', tab='\t', SOH=0x1, STX=0x2;
569
570 public static boolean SPLIT_READS=false;
571 public static int TARGET_READ_LEN=500;
572 public static int MIN_READ_LEN=1;
573 public static boolean FAKE_QUALITY=false;
574 public static boolean FORCE_SECTION_NAME=false;
575 public static boolean WARN_IF_NO_SEQUENCE=true;
576 public static boolean WARN_FIRST_TIME_ONLY=true;
577 public static boolean ABORT_IF_NO_SEQUENCE=false;
578
579 }