Debian Codegraph @

current/jgi/MergeBarcodes.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7
8 import fileIO.ByteFile;
9 import fileIO.ByteFile1;
10 import fileIO.ByteFile2;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import shared.Parse;
14 import shared.Parser;
15 import shared.PreParser;
16 import shared.Shared;
17 import shared.Timer;
18 import shared.Tools;
19 import stream.ConcurrentGenericReadInputStream;
20 import stream.ConcurrentReadInputStream;
21 import stream.ConcurrentReadOutputStream;
22 import stream.FASTQ;
23 import stream.FastaReadInputStream;
24 import stream.Read;
25 import structures.ListNum;
26 import tracker.ReadStats;
27
28 /**
29 * @author Brian Bushnell
30 * @date Sep 11, 2012
31 *
32 */
33 public class MergeBarcodes {
34
35 public static void main(String[] args){
36 Timer t=new Timer();
37 MergeBarcodes x=new MergeBarcodes(args);
38 HashMap<String, Read> map=x.loadBarcodes();
39 x.mergeWithMap(t, map);
40
41 //Close the print stream if it was redirected
42 Shared.closeStream(x.outstream);
43 }
44
45 public MergeBarcodes(String[] args){
46
47 {//Preparse block for help, config files, and outstream
48 PreParser pp=new PreParser(args, getClass(), false);
49 args=pp.args;
50 outstream=pp.outstream;
51 }
52
53 boolean setInterleaved=false; //Whether it was explicitly set.
54
55 Shared.capBuffers(4);
56 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
57 ReadWrite.setZipThreads(Shared.threads());
58
59
60 Parser parser=new Parser();
61 for(int i=0; i<args.length; i++){
62 String arg=args[i];
63 String[] split=arg.split("=");
64 String a=split[0].toLowerCase();
65 String b=split.length>1 ? split[1] : null;
66
67 if(parser.parse(arg, a, b)){
68 //do nothing
69 }else if(a.equals("verbose")){
70 verbose=Parse.parseBoolean(b);
71 ByteFile1.verbose=verbose;
72 ByteFile2.verbose=verbose;
73 stream.FastaReadInputStream.verbose=verbose;
74 ConcurrentGenericReadInputStream.verbose=verbose;
75 stream.FastqReadInputStream.verbose=verbose;
76 ReadWrite.verbose=verbose;
77 }else if(a.equals("barcode") || a.equals("bar") || a.equals("index")){
78 inbar=b;
79 }else if(a.equals("addslash")){
80 addslash=Parse.parseBoolean(b);
81 }else if(a.equals("addcolon")){
82 addcolon=Parse.parseBoolean(b);
83 }else if(a.equals("rcompmate") || a.equals("rcm")){
84 reverseComplementMate=Parse.parseBoolean(b);
85 outstream.println("Set RCOMPMATE to "+reverseComplementMate);
86 }else if(a.equals("rcomp") || a.equals("rc")){
87 reverseComplement=Parse.parseBoolean(b);
88 outstream.println("Set RCOMP to "+reverseComplement);
89 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
90 parser.in1=arg;
91 }else{
92 outstream.println("Unknown parameter "+args[i]);
93 assert(false) : "Unknown parameter "+args[i];
94 // throw new RuntimeException("Unknown parameter "+args[i]);
95 }
96 }
97
98 {//Process parser fields
99 Parser.processQuality();
100
101 maxReads=parser.maxReads;
102
103 overwrite=ReadStats.overwrite=parser.overwrite;
104 append=ReadStats.append=parser.append;
105
106 setInterleaved=parser.setInterleaved;
107
108 in1=parser.in1;
109 in2=parser.in2;
110 qfin1=parser.qfin1;
111 qfin2=parser.qfin2;
112
113 out1=parser.out1;
114 out2=parser.out2;
115 qfout1=parser.qfout1;
116 qfout2=parser.qfout2;
117
118 extin=parser.extin;
119 extout=parser.extout;
120 }
121
122 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
123 in2=in1.replace("#", "2");
124 in1=in1.replace("#", "1");
125 }
126 if(out1!=null && out2==null && out1.indexOf('#')>-1){
127 out2=out1.replace("#", "2");
128 out1=out1.replace("#", "1");
129 }
130 if(in2!=null){
131 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
132 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
133 }
134
135 assert(FastaReadInputStream.settingsOK());
136
137 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
138 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
139 ByteFile.FORCE_MODE_BF2=true;
140 }
141
142 if(out1==null){
143 if(out1==null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
144 if(!parser.setOut){
145 System.err.println("No output stream specified. To write to stdout, please specify 'out=stdout.fq' or similar.");
146 // out1="stdout";
147 }
148 }
149
150 if(!setInterleaved){
151 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
152 if(in2!=null){ //If there are 2 input streams.
153 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
154 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
155 }else{ //There is one input stream.
156 if(out2!=null){
157 FASTQ.FORCE_INTERLEAVED=true;
158 FASTQ.TEST_INTERLEAVED=false;
159 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
160 }
161 }
162 }
163
164 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
165 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
166
167 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
168 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
169 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
170 }
171
172 assert(inbar!=null) : "Must specify a barcode file.";
173 ffbar=FileFormat.testInput(inbar, FileFormat.FASTQ, extin, true, true);
174
175 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
176 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
177
178 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
179 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
180 }
181
182 public HashMap<String, Read> loadBarcodes(){
183 return loadBarcodes(outstream, ffbar, maxReads);
184 }
185
186 public static HashMap<String, Read> loadBarcodes(PrintStream outstream, FileFormat ffbar, long maxReads){
187
188 Timer t=new Timer();
189
190 final boolean oldForceInterleaved=FASTQ.FORCE_INTERLEAVED;
191 final boolean oldTestInterleaved=FASTQ.TEST_INTERLEAVED;
192
193 FASTQ.FORCE_INTERLEAVED=false;
194 FASTQ.TEST_INTERLEAVED=false;
195
196 HashMap<String, Read> map=new HashMap<String, Read>(0x10000-1);
197
198 final ConcurrentReadInputStream cris;
199 {
200 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffbar, null, null, null);
201 if(verbose){outstream.println("Started cris for barcodes");}
202 cris.start(); //4567
203 }
204 // final boolean paired=cris.paired();
205 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
206
207 long readsProcessed=0;
208 long basesProcessed=0;
209
210 {
211
212 ListNum<Read> ln=cris.nextList();
213 ArrayList<Read> reads=(ln!=null ? ln.list : null);
214
215 // outstream.println("Fetched "+reads);
216
217 if(reads!=null && !reads.isEmpty()){
218 Read r=reads.get(0);
219 assert((r.mate!=null)==cris.paired());
220 }
221
222 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
223
224 for(int idx=0; idx<reads.size(); idx++){
225 final Read r1=reads.get(idx);
226 final Read r2=r1.mate;
227
228 if(r1.id.indexOf(' ')>=0){r1.id=r1.id.split(" ")[0];}
229
230 final int initialLength1=r1.length();
231 final int initialLength2=(r1.mateLength());
232
233 {
234 readsProcessed++;
235 basesProcessed+=initialLength1;
236 }
237 if(r2!=null){
238 readsProcessed++;
239 basesProcessed+=initialLength2;
240 }
241
242 map.put(r1.id, r1);
243 }
244
245 cris.returnList(ln);
246 ln=cris.nextList();
247 reads=(ln!=null ? ln.list : null);
248 }
249 if(ln!=null){
250 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
251 }
252 }
253
254 boolean errorState=false;
255 errorState|=ReadWrite.closeStream(cris);
256
257 t.stop();
258
259 double rpnano=readsProcessed/(double)(t.elapsed);
260 double bpnano=basesProcessed/(double)(t.elapsed);
261
262 String rpstring=Tools.padKMB(readsProcessed, 8);
263 String bpstring=Tools.padKMB(basesProcessed, 8);
264
265 outstream.println("Loaded barcodes.");
266 outstream.println("Time: \t"+t);
267 outstream.println("Barcodes Processed: "+rpstring+" \t"+Tools.format("%.2fk reads/sec", rpnano*1000000));
268 outstream.println("Bases Processed: "+bpstring+" \t"+Tools.format("%.2fm bases/sec", bpnano*1000));
269 outstream.println();
270
271 if(errorState){
272 throw new RuntimeException("MergeBarcodes encountered an error; the output may be corrupt.");
273 }
274
275 FASTQ.FORCE_INTERLEAVED=oldForceInterleaved;
276 FASTQ.TEST_INTERLEAVED=oldTestInterleaved;
277
278 return map;
279 }
280
281 void mergeWithMap(Timer t, HashMap<String, Read> map){
282
283 final ConcurrentReadInputStream cris;
284 {
285 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
286 if(verbose){outstream.println("Started cris");}
287 cris.start(); //4567
288 }
289 boolean paired=cris.paired();
290 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
291
292 final ConcurrentReadOutputStream ros;
293 if(out1!=null){
294 final int buff=4;
295
296 if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
297 outstream.println("Writing interleaved.");
298 }
299
300 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
301 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
302
303 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
304 ros.start();
305 }else{ros=null;}
306
307 long readsProcessed=0;
308 long basesProcessed=0;
309 long barcodesFound=0;
310 long barcodesNotFound=0;
311 final StringBuilder prefix=new StringBuilder();
312
313 {
314
315 ListNum<Read> ln=cris.nextList();
316 ArrayList<Read> reads=(ln!=null ? ln.list : null);
317
318 // outstream.println("Fetched "+reads);
319
320 if(reads!=null && !reads.isEmpty()){
321 Read r=reads.get(0);
322 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
323 }
324
325 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
326
327 for(int idx=0; idx<reads.size(); idx++){
328 final Read r1=reads.get(idx);
329 final Read r2=r1.mate;
330
331 final int initialLength1=r1.length();
332 final int initialLength2=(r1.mateLength());
333
334 {
335 readsProcessed++;
336 basesProcessed+=initialLength1;
337 if(reverseComplement){r1.reverseComplement();}
338 }
339 if(r2!=null){
340 readsProcessed++;
341 basesProcessed+=initialLength2;
342 if(reverseComplement || reverseComplementMate){r2.reverseComplement();}
343 }
344
345 String key=r1.id;
346 if(key.indexOf(' ')>=0){key=key.split(" ")[0];}
347 Read bar=map.remove(key);
348 if(bar!=null){
349 for(byte b : bar.bases){prefix.append((char)b);}
350 prefix.append('_');
351 for(byte b : bar.quality){prefix.append((char)(b+33));}
352 prefix.append('_');
353 r1.id=prefix+r1.id;
354 barcodesFound++;
355 if(r2!=null){
356 r2.id=prefix+r2.id;
357 barcodesFound++;
358 }
359 prefix.setLength(0);
360 }else{
361 barcodesNotFound++;
362 if(r2!=null){barcodesNotFound++;}
363 }
364 }
365
366 final ArrayList<Read> listOut=reads;
367
368 if(ros!=null){ros.add(listOut, ln.id);}
369
370 cris.returnList(ln);
371 ln=cris.nextList();
372 reads=(ln!=null ? ln.list : null);
373 }
374 if(ln!=null){
375 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
376 }
377 }
378
379 errorState|=ReadStats.writeAll();
380
381 errorState|=ReadWrite.closeStreams(cris, ros);
382
383 t.stop();
384
385 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
386 outstream.println("Barcodes Found: \t"+barcodesFound+" reads ("+Tools.format("%.2f",barcodesFound*100.0/readsProcessed)+"%)");
387 outstream.println("Barcodes Not Found: \t"+barcodesNotFound+" reads ("+Tools.format("%.2f",barcodesNotFound*100.0/readsProcessed)+"%)");
388
389 if(errorState){
390 throw new RuntimeException("ReformatReads terminated in an error state; the output may be corrupt.");
391 }
392 }
393
394 /*--------------------------------------------------------------*/
395
396 /*--------------------------------------------------------------*/
397
398 private String inbar=null;
399
400 private String in1=null;
401 private String in2=null;
402
403 private String qfin1=null;
404 private String qfin2=null;
405
406 private String out1=null;
407 private String out2=null;
408
409 private String qfout1=null;
410 private String qfout2=null;
411
412 private String extin=null;
413 private String extout=null;
414
415 /*--------------------------------------------------------------*/
416
417 private boolean reverseComplementMate=false;
418 private boolean reverseComplement=false;
419 /** Add /1 and /2 to read names */
420 private boolean addslash=false;
421 /** Add 1: and 2: to read names */
422 private boolean addcolon=false;
423
424 private long maxReads=-1;
425
426 /*--------------------------------------------------------------*/
427
428 private final FileFormat ffbar;
429
430 private final FileFormat ffin1;
431 private final FileFormat ffin2;
432
433 private final FileFormat ffout1;
434 private final FileFormat ffout2;
435
436
437 /*--------------------------------------------------------------*/
438
439 private PrintStream outstream=System.err;
440 public static boolean verbose=false;
441 public boolean errorState=false;
442 private boolean overwrite=true;
443 private boolean append=false;
444
445 }