Debian Codegraph @

current/barcode/CorrelateBarcodes.java

raw symbols SCIP
1 package barcode;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6
7 import fileIO.ByteFile;
8 import fileIO.ByteFile1;
9 import fileIO.ByteFile2;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import fileIO.TextStreamWriter;
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 June 20, 2014
31 *
32 */
33 public class CorrelateBarcodes {
34
35 public static void main(String[] args){
36 Timer t=new Timer();
37 CorrelateBarcodes x=new CorrelateBarcodes(args);
38 x.process(t);
39
40 //Close the print stream if it was redirected
41 Shared.closeStream(x.outstream);
42 }
43
44 public CorrelateBarcodes(String[] args){
45
46 {//Preparse block for help, config files, and outstream
47 PreParser pp=new PreParser(args, getClass(), false);
48 args=pp.args;
49 outstream=pp.outstream;
50 }
51
52 boolean setInterleaved=false; //Whether it was explicitly set.
53
54 Shared.capBuffers(4);
55 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
56 ReadWrite.setZipThreads(Shared.threads());
57
58
59 Parser parser=new Parser();
60 for(int i=0; i<args.length; i++){
61 String arg=args[i];
62 String[] split=arg.split("=");
63 String a=split[0].toLowerCase();
64 String b=split.length>1 ? split[1] : null;
65
66 if(parser.parse(arg, a, b)){
67 //do nothing
68 }else if(a.equals("verbose")){
69 verbose=Parse.parseBoolean(b);
70 ByteFile1.verbose=verbose;
71 ByteFile2.verbose=verbose;
72 stream.FastaReadInputStream.verbose=verbose;
73 ConcurrentGenericReadInputStream.verbose=verbose;
74 stream.FastqReadInputStream.verbose=verbose;
75 ReadWrite.verbose=verbose;
76 }else if(a.equals("outcor") || a.equals("cor")){
77 outcor=b;
78 }else if(a.equals("bqhist")){
79 bqhist=b;
80 }else if(a.equals("baqhist")){//average quality
81 aqhist=b;
82 }else if(a.equals("bmqhist")){//minimum quality
83 mqhist=b;
84 }else if(a.equals("mmq")){//minimum min quality cutoff
85 minBarcodeMinQuality=Integer.parseInt(b);
86 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
87 parser.in1=arg;
88 }else{
89 outstream.println("Unknown parameter "+args[i]);
90 assert(false) : "Unknown parameter "+args[i];
91 // throw new RuntimeException("Unknown parameter "+args[i]);
92 }
93 }
94
95 {//Process parser fields
96 Parser.processQuality();
97
98 maxReads=parser.maxReads;
99
100 overwrite=ReadStats.overwrite=parser.overwrite;
101 append=ReadStats.append=parser.append;
102
103 setInterleaved=parser.setInterleaved;
104
105 in1=parser.in1;
106 in2=parser.in2;
107 qfin1=parser.qfin1;
108 qfin2=parser.qfin2;
109
110 out1=parser.out1;
111 out2=parser.out2;
112
113 extin=parser.extin;
114 extout=parser.extout;
115
116 minBarcodeAverageQuality=parser.minAvgQuality;
117 }
118
119 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
120 in2=in1.replace("#", "2");
121 in1=in1.replace("#", "1");
122 }
123 if(out1!=null && out2==null && out1.indexOf('#')>-1){
124 out2=out1.replace("#", "2");
125 out1=out1.replace("#", "1");
126 }
127 if(in2!=null){
128 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
129 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
130 }
131
132 assert(FastaReadInputStream.settingsOK());
133
134 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
135 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
136 ByteFile.FORCE_MODE_BF2=true;
137 }
138
139 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
140
141 if(!setInterleaved){
142 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
143 if(in2!=null){ //If there are 2 input streams.
144 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
145 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
146 }else{ //There is one input stream.
147 if(out2!=null){
148 FASTQ.FORCE_INTERLEAVED=true;
149 FASTQ.TEST_INTERLEAVED=false;
150 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
151 }
152 }
153 }
154
155 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
156 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
157
158 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
159 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
160 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
161 }
162
163 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
164 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
165
166 ffcor=FileFormat.testOutput(outcor, FileFormat.TEXT, extout, true, overwrite, append, false);
167 ffaq=FileFormat.testOutput(aqhist, FileFormat.TEXT, extout, true, overwrite, append, false);
168 ffmq=FileFormat.testOutput(mqhist, FileFormat.TEXT, extout, true, overwrite, append, false);
169
170 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
171 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
172 }
173
174 void process(Timer t){
175
176
177 final ConcurrentReadInputStream cris;
178 {
179 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
180 if(verbose){outstream.println("Started cris");}
181 cris.start(); //4567
182 }
183 boolean paired=cris.paired();
184 // if(verbose){
185 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
186 // }
187
188 final ConcurrentReadOutputStream ros;
189 if(out1!=null){
190 final int buff=4;
191
192 if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
193 outstream.println("Writing interleaved.");
194 }
195
196 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
197 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
198
199 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, false);
200 ros.start();
201 }else{ros=null;}
202
203 long readsProcessed=0;
204 long basesProcessed=0;
205
206 long readsTossed=0;
207 long basesTossed=0;
208
209 ReadStats readstats=null;
210 ReadStats.COLLECT_QUALITY_STATS=(bqhist!=null);
211 if(ReadStats.COLLECT_QUALITY_STATS){
212 ReadStats.QUAL_HIST_FILE=bqhist;
213 readstats=new ReadStats();
214 }
215
216 // assert(false) : bqhist+", "+(ReadStats.COLLECT_QUALITY_STATS)+", "+(readstats==null);
217
218 {
219
220 ListNum<Read> ln=cris.nextList();
221 ArrayList<Read> reads=(ln!=null ? ln.list : null);
222
223 // outstream.println("Fetched "+reads);
224
225 if(reads!=null && !reads.isEmpty()){
226 Read r=reads.get(0);
227 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
228 }
229
230 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
231
232 for(int idx=0; idx<reads.size(); idx++){
233 final Read r1=reads.get(idx);
234 final Read r2=r1.mate;
235
236 final int initialLength1=r1.length();
237 final int initialLength2=(r1.mateLength());
238
239 final byte[] barbases, barquals;
240 {
241 String[] s=r1.id.split("_");
242 barbases=s[0].getBytes();
243 barquals=s[1].getBytes();
244 for(int i=0; i<barquals.length; i++){
245 barquals[i]-=33;
246 }
247 }
248
249 final int qbar=Read.avgQualityByProbabilityInt(barbases, barquals, true, 0);
250 final int minqbar=Tools.min(barquals);
251 aqhistArray[qbar]++;
252 mqhistArray[minqbar]++;
253
254 if(qbar<minBarcodeAverageQuality || minqbar<minBarcodeMinQuality){
255 r1.setDiscarded(true);
256 readsTossed++;
257 basesTossed+=(initialLength1+initialLength2);
258 if(r2!=null){readsTossed++;}
259 }
260
261 // System.err.println(new String(barquals)+" -> "+qbar);
262
263 {
264 readsProcessed++;
265 basesProcessed+=initialLength1;
266 final int q1=r1.avgQualityByProbabilityInt(true, 0);
267 qualCor1[q1][qbar]++;
268 }
269 if(r2!=null){
270 readsProcessed++;
271 basesProcessed+=initialLength2;
272 final int q2=r2.avgQualityByProbabilityInt(true, 0);
273 qualCor2[q2][qbar]++;
274 }
275
276 if(readstats!=null){
277 readstats.addToQualityHistogram(barquals, 0);
278 }
279
280 }
281
282 ArrayList<Read> listOut=reads;
283
284 if(ros!=null){
285 if(minBarcodeAverageQuality>0){
286 listOut=new ArrayList<Read>(reads.size());
287 for(Read r : reads){
288 if(!r.discarded()){listOut.add(r);}
289 }
290 }
291 ros.add(listOut, ln.id);
292 }
293
294 cris.returnList(ln);
295 ln=cris.nextList();
296 reads=(ln!=null ? ln.list : null);
297 }
298 if(ln!=null){
299 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
300 }
301 }
302
303 if(ffcor!=null){
304 TextStreamWriter tsw=new TextStreamWriter(ffcor);
305 tsw.start();
306 tsw.print("#Read1_Q\tBar_Q\tstdev\tcount\tRead2_Q\tBar_Q\tstdev\tcount\n");
307 for(int i=0; i<qualCor1.length; i++){
308 long[] array1=qualCor1[i], array2=qualCor2[i];
309 long sum1=shared.Vector.sum(array1), sum2=shared.Vector.sum(array2);
310 double avg1=Tools.averageHistogram(array1), avg2=Tools.averageHistogram(array2);
311 double dev1=Tools.standardDeviationHistogram(array1), dev2=Tools.standardDeviationHistogram(array2);
312 tsw.print(Tools.format("%d\t%.1f\t%.1f\t%d\t%d\t%.1f\t%.1f\t%d\n", i, avg1, dev1, sum1, i, avg2, dev2, sum2));
313 }
314 tsw.poisonAndWait();
315 errorState|=tsw.errorState;
316 }
317
318 if(aqhist!=null){
319 TextStreamWriter tsw=new TextStreamWriter(ffaq);
320 tsw.start();
321 tsw.print("#Quality\tcount\tfraction\n");
322 long sum=shared.Vector.sum(aqhistArray);
323 double mult=1.0/Tools.max(1, sum);
324 long y=0;
325 for(int i=0; i<aqhistArray.length; i++){
326 long x=aqhistArray[i];
327 tsw.print(Tools.format("%d\t%d\t%.5f\n", i, x, x*mult));
328 y+=x;
329 if(y==sum){break;}
330 }
331 tsw.poisonAndWait();
332 errorState|=tsw.errorState;
333 }
334
335 if(mqhist!=null){
336 TextStreamWriter tsw=new TextStreamWriter(ffmq);
337 tsw.start();
338 tsw.print("#Quality\tcount\tfraction\n");
339 long sum=shared.Vector.sum(mqhistArray);
340 double mult=1.0/Tools.max(1, sum);
341 long y=0;
342 for(int i=0; i<mqhistArray.length; i++){
343 long x=mqhistArray[i];
344 tsw.print(Tools.format("%d\t%d\t%.5f\n", i, x, x*mult));
345 y+=x;
346 if(y==sum){break;}
347 }
348 tsw.poisonAndWait();
349 errorState|=tsw.errorState;
350 }
351
352
353 if(readstats!=null){
354 errorState|=ReadStats.writeAll();
355 }
356
357 errorState|=ReadWrite.closeStreams(cris, ros);
358
359 t.stop();
360 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
361
362 if(minBarcodeAverageQuality>0){
363 outstream.println();
364 outstream.println("Reads Discarded: "+readsTossed+" \t"+Tools.format("%.3f%%",readsTossed*100.0/readsProcessed));
365 outstream.println("Reads Discarded: "+basesTossed+" \t"+Tools.format("%.3f%%",basesTossed*100.0/basesProcessed));
366 }
367
368 if(errorState){
369 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
370 }
371 }
372
373 /*--------------------------------------------------------------*/
374
375
376 /*--------------------------------------------------------------*/
377
378 private String in1=null;
379 private String in2=null;
380
381 private String qfin1=null;
382 private String qfin2=null;
383
384 private String out1=null;
385 private String out2=null;
386
387 private String extin=null;
388 private String extout=null;
389
390 private String outcor=null;
391 private String bqhist=null;
392 private String aqhist=null;
393 private String mqhist=null;
394
395 private float minBarcodeAverageQuality=0;
396 private int minBarcodeMinQuality=0;
397
398 private long[][] qualCor1=new long[50][50];
399 private long[][] qualCor2=new long[50][50];
400
401 private long[] aqhistArray=new long[100];
402 private long[] mqhistArray=new long[100];
403
404 /*--------------------------------------------------------------*/
405
406 private long maxReads=-1;
407
408 /*--------------------------------------------------------------*/
409
410 private final FileFormat ffin1;
411 private final FileFormat ffin2;
412
413 private final FileFormat ffcor;
414 private final FileFormat ffaq;
415 private final FileFormat ffmq;
416
417 private final FileFormat ffout1;
418 private final FileFormat ffout2;
419
420
421 /*--------------------------------------------------------------*/
422
423 private PrintStream outstream=System.err;
424 public static boolean verbose=false;
425 public boolean errorState=false;
426 private boolean overwrite=true;
427 private boolean append=false;
428
429 }