Debian Codegraph @

current/barcode/CountBarcodes2.java

raw symbols SCIP
1 package barcode;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.HashMap;
8 import java.util.HashSet;
9 import java.util.LinkedHashMap;
10 import java.util.LinkedHashSet;
11 import java.util.Map.Entry;
12
13 import barcode.stub.PCRMatrixProb;
14 import fileIO.ByteFile;
15 import fileIO.ByteStreamWriter;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import fileIO.TextFile;
19 import hiseq.IlluminaHeaderParser2;
20 import shared.LineParser;
21 import shared.LineParser1;
22 import shared.Parse;
23 import shared.Parser;
24 import shared.PreParser;
25 import shared.Shared;
26 import shared.Timer;
27 import shared.Tools;
28 import stream.ConcurrentReadInputStream;
29 import stream.FASTQ;
30 import stream.FastaReadInputStream;
31 import stream.Read;
32 import structures.ByteBuilder;
33 import structures.ListNum;
34 import structures.LongPair;
35 import tracker.ReadStats;
36
37 /**
38 * Counts barcodes in a fastq file and produces a summary.
39 *
40 * Sample command:
41 * countbarcodes2.sh pcrmatrix type=hdist in=sub005.fq.gz ow expected=expected.txt -Xmx31g t=32
42 * countbarcodes2.sh pcrmatrix type=hdist in=sub005.fq.gz ow expected=expected.txt -Xmx31g t=32
43 * outcontam=contam2.txt quantset=quantset.txt
44 *
45 * @author Brian Bushnell
46 * @date June 20, 2014
47 *
48 */
49 public class CountBarcodes2 {
50
51 /*--------------------------------------------------------------*/
52 /*---------------- Initialization ----------------*/
53 /*--------------------------------------------------------------*/
54
55 /**
56 * Code entrance from the command line.
57 * @param args Command line arguments
58 */
59 public static void main(String[] args){
60 //Start a timer immediately upon code entrance.
61 Timer t=new Timer();
62
63 //Create an instance of this class
64 CountBarcodes2 x=new CountBarcodes2(args);
65
66 //Run the object
67 x.process(t);
68
69 //Close the print stream if it was redirected
70 Shared.closeStream(x.outstream);
71 }
72
73 /**
74 * Constructor.
75 * @param args Command line arguments
76 */
77 public CountBarcodes2(String[] args){
78
79 {//Preparse block for help, config files, and outstream
80 PreParser pp=new PreParser(args, getClass(), false);
81 args=pp.args;
82 outstream=pp.outstream;
83 }
84
85 //Set shared static variables prior to parsing
86 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
87 ReadWrite.setZipThreads(Shared.threads());
88 Shared.capBuffers(4); //Only for singlethreaded programs
89
90 {//Parse the arguments
91 final Parser parser=parse(args);
92 Parser.processQuality();
93
94 maxReads=parser.maxReads;
95 overwrite=ReadStats.overwrite=parser.overwrite;
96 append=ReadStats.append=parser.append;
97 setInterleaved=parser.setInterleaved;
98
99 if(parser.in1!=null) {
100 for(String s : parser.in1.split(",")) {
101 in1.add(s);
102 }
103 }
104 if(parser.in2!=null) {
105 for(String s : parser.in2.split(",")) {
106 in2.add(s);
107 }
108 }
109 extin=parser.extin;
110
111 out1=parser.out1;
112 extout=parser.extout;
113 }
114
115 PCRMatrix.postParseStatic();
116 doPoundReplacement(); //Replace # with 1 and 2
117 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
118 fixExtensions(); //Add or remove .gz or .bz2 as needed
119 checkFileExistence(); //Ensure files can be read and written
120 checkStatics(); //Adjust file-related static fields as needed for this program
121
122 //Create output FileFormat objects
123 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, extout, true, overwrite, append, false);
124
125 //Create input FileFormat objects
126 for(String s : in1) {
127 ffin1.add(FileFormat.testInput(s, FileFormat.FASTQ, extin, true, true));
128 }
129 for(String s : in2) {
130 ffin2.add(FileFormat.testInput(s, FileFormat.FASTQ, extin, true, true));
131 }
132 }
133
134 /*--------------------------------------------------------------*/
135 /*---------------- Initialization Helpers ----------------*/
136 /*--------------------------------------------------------------*/
137
138 /** Parse arguments from the command line */
139 private Parser parse(String[] args){
140
141 //Create a parser object
142 Parser parser=new Parser();
143
144 //Set any necessary Parser defaults here
145 //parser.foo=bar;
146
147 //Parse each argument
148 for(int i=0; i<args.length; i++){
149 String arg=args[i];
150
151 //Break arguments into their constituent parts, in the form of "a=b"
152 String[] split=arg.split("=");
153 String a=split[0].toLowerCase();
154 String b=split.length>1 ? split[1] : null;
155 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
156
157 if(a.equals("verbose")){
158 verbose=Parse.parseBoolean(b);
159 }else if(a.equals("expected") || a.equals("valid") || a.equals("names") ||
160 a.equals("barcodes") || a.equals("expectedbarcodes")){
161 expectedBarcodesFile=b;
162 }else if(a.equals("delimiter")){
163 delimiter=(b==null ? -1 : (byte)b.charAt(0));
164 barcodesPerRead=(delimiter<0 ? 1 : 2);
165 }else if(a.equals("out") || a.equals("counts")){
166 parser.out1=b;
167 }else if(a.equals("countsin")){
168 countsIn=b;
169 }else if(a.equals("mincount") || a.equals("mincounta") || a.equals("mincountf")){
170 minCountA=Long.parseLong(b);
171 }else if(a.equals("mincountr")){
172 minCountR=Long.parseLong(b);
173 }else if(a.equals("mincount0")){
174 minCount0=Long.parseLong(b);
175 }else if(a.equals("mincountpercent") || a.equals("mincountpercentile")){
176 minCountPercentile=Float.parseFloat(b);
177 }else if(a.equals("pcrmatrix") || a.equals("usematrix") || a.equals("matrix")){
178 useMatrix=Parse.parseBoolean(b);
179 }else if(a.equals("client") || a.equals("server") || a.equals("useserver")){
180 useServer=Parse.parseBoolean(b);
181 }
182
183 else if(a.equals("probsout") || a.equals("outprobs")){
184 probsOut=b;
185 }else if(a.equals("accuracyout") || a.equals("outaccuracy")){
186 accuracyOut=b;
187 }else if(a.equals("mapout") || a.equals("outmap")){
188 mapOut=b;
189 }else if(a.equals("barcodesout") || a.equals("outbarcodes")){
190 barcodesOut=b;
191 }else if(a.equals("contamout") || a.equals("outcontam")){
192 contamOut=b;
193 }else if(a.equals("transitions") || a.equals("errors") || a.equals("substitutions")){
194 transitionsOut=b;
195 }else if(a.equals("matrixout") || a.equals("countmatrix") || a.equals("outmatrix")){
196 matrixOut=b;
197 }else if(a.equalsIgnoreCase("printStats")) {
198 printStats=Parse.parseBoolean(b);
199 }else if(a.equalsIgnoreCase("excludeUnknownInAccuracy")) {
200 excludeUnknownInAccuracy=Parse.parseBoolean(b);
201 }
202
203 else if(a.equals("quantifysource")){
204 quantifySource=Parse.parseBoolean(b);
205 }else if(a.equals("quantifysink")){
206 quantifySource=!Parse.parseBoolean(b);
207 }else if(a.equals("quantset")){
208 quantSetFile=b;
209 }
210
211 else if(a.equals("parse_flag_goes_here")){
212 long fake_variable=Parse.parseKMG(b);
213 //Set a variable here
214 }else if(PCRMatrix.parseStatic(arg, a, b)){
215 //Flag was captured by PCRMatrix; do nothing
216 }else if(parser.parse(arg, a, b)){
217 //Flag was captured by the parser; do nothing
218 }else if(b==null && new File(arg).exists()){
219 in1.add(arg);
220 }else{
221 outstream.println("Unknown parameter "+args[i]);
222 assert(false) : "Unknown parameter "+args[i];
223 }
224 }
225
226 return parser;
227 }
228
229 /** Replace # with 1 and 2 in headers */
230 private void doPoundReplacement(){
231 //Do input file # replacement
232 if(in2.isEmpty()) {
233 for(int i=0; i<in1.size(); i++) {
234 String s=in1.get(i);
235 if(s.indexOf('#')>-1 && !new File(s).exists()){
236 String a=s.replace("#", "1");
237 String b=s.replace("#", "2");
238 in1.set(i, a);
239 in2.add(b);
240 }
241 }
242 }
243
244 //Ensure there is an input file
245 if(in1.isEmpty() && countsIn==null){
246 throw new RuntimeException("Error - at least one input file is required.");
247 }
248 }
249
250 /** Add or remove .gz or .bz2 as needed */
251 private void fixExtensions(){
252 in1=Tools.fixExtension(in1);
253 in2=Tools.fixExtension(in2);
254 }
255
256 /** Ensure files can be read and written */
257 private void checkFileExistence(){
258 //Ensure output files can be written
259 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
260 outstream.println((out1==null)+", "+out1);
261 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out1+"\n");
262 }
263
264 ArrayList<String> temp=new ArrayList<String>();
265 temp.addAll(in1);
266 temp.addAll(in2);
267 if(expectedBarcodesFile!=null) {temp.add(expectedBarcodesFile);}
268
269
270 //Ensure input files can be read
271 if(!Tools.testInputFiles(false, true, temp.toArray(new String[0]))){
272 throw new RuntimeException("\nCan't read some input files.\n");
273 }
274
275 if(out1!=null) {temp.add(out1);}
276 //Ensure that no file was specified multiple times
277 if(!Tools.testForDuplicateFiles(true, temp.toArray(new String[0]))){
278 throw new RuntimeException("\nSome file names were specified multiple times.\n");
279 }
280 }
281
282 /** Make sure interleaving agrees with number of input and output files */
283 private void adjustInterleaving(){
284 //Adjust interleaved detection based on the number of input files
285 if(!in2.isEmpty()){
286 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
287 FASTQ.FORCE_INTERLEAVED=false; //FASTQ.TEST_INTERLEAVED=false; interferes with barcode detection
288 }
289 }
290
291 /** Adjust file-related static fields as needed for this program */
292 private static void checkStatics(){
293 //Adjust the number of threads for input file reading
294 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
295 ByteFile.FORCE_MODE_BF2=true;
296 }
297
298 assert(FastaReadInputStream.settingsOK());
299 }
300
301 /*--------------------------------------------------------------*/
302 /*---------------- Outer Methods ----------------*/
303 /*--------------------------------------------------------------*/
304
305 /** Create read streams and process all data */
306 void process(Timer t){
307
308 //Reset counters
309 readsProcessed=0;
310 basesProcessed=0;
311
312 //Process the read stream
313 if(countsIn==null) {
314 for(int i=0; i<ffin1.size(); i++){
315 processInner(ffin1.get(i), (ffin2.size()<=i ? null : ffin2.get(i)));
316 }
317 }else {
318 processCounts(countsIn);
319 }
320
321 if(calcStats) {
322 if(bs.barcodesPerRead>1) {
323 bs.leftStats=bs.makeLeft();
324 bs.rightStats=bs.makeRight();
325 bs.leftStats.calcStats();
326 bs.rightStats.calcStats();
327 }
328 bs.calcStats();
329
330 if(printStats) {
331 String s=bs.toStats("Barcodes");
332 System.err.println(s);
333 if(bs.leftStats!=null){
334 System.err.println(bs.leftStats.toStats("\nBarcode1"));
335 }
336 if(bs.rightStats!=null){
337 System.err.println(bs.rightStats.toStats("\nBarcode2"));
338 }
339 }
340 }
341
342 if(ffout1!=null){
343 bs.printToFile(ffout1, minCount0);
344 }
345
346 if(transitionsOut!=null) {
347 ByteBuilder bb=bs.printTransitions();
348 ReadWrite.writeString(bb, transitionsOut);
349 }
350
351 if(matrixOut!=null || probsOut!=null || accuracyOut!=null ||
352 mapOut!=null || barcodesOut!=null || useMatrix) {
353 assert(!bs.expectedCodeList.isEmpty()) :
354 "For matrix output expected barcodes are required.";
355 Timer t2=new Timer();
356
357 final Collection<Barcode> counts=bs.codeMap.values();
358 if(minCountPercentile>0) {
359 long thresh=BarcodeCounter.barcodeCountPercentile(counts, minCountPercentile);
360 }
361
362 final HashMap<String, String> assignmentMap;
363 {//New code block for using server
364
365 if(PCRMatrix.matrixType0==PCRMatrix.PROB_TYPE && PCRMatrixProb.clientside()
366 && !setUseServer && !useServer) {
367 useServer=true;
368 }
369 if(useServer) {
370 System.err.println("Using client-server mode for barcode analysis.");
371 DemuxData dd=new DemuxData(bs.length1, bs.length2, bs.delimiter);
372 dd.codeCounts=counts;
373 dd.expectedList=new LinkedHashSet<String>(bs.expectedCodeMap.keySet());
374 DemuxClient client=new DemuxClient();
375 assignmentMap=client.getMap(dd, verboseClient);
376 t2.stop("Assignment Time:\t\t");
377 if(mapOut!=null) {
378 PCRMatrix.printAssignmentMapStatic(assignmentMap,
379 mapOut, counts, overwrite, append);
380 }
381 }else {
382 PCRMatrix pcrMatrix=PCRMatrix.create(bs.length1, bs.length2, bs.delimiter);
383 assert(bs.expectedCodeList!=null && !bs.expectedCodeList.isEmpty());
384 pcrMatrix.populateExpected(bs.expectedCodeMap.keySet());
385 pcrMatrix.populateSplitCodes();
386 pcrMatrix.initializeData();
387 pcrMatrix.refine(counts, minCountR);
388 // pcrMatrix.verbose=true;
389 assignmentMap=pcrMatrix.makeAssignmentMap(counts, minCountA);
390 t2.stop("Assignment Time:\t\t");
391 if(mapOut!=null) {
392 pcrMatrix.printAssignmentMap(assignmentMap,
393 mapOut, counts, overwrite, append);
394 }
395
396 if(contamOut==null) {//Otherwise yield will be printed later
397 // long processed=0;
398 // for(Barcode b : counts) {processed+=b.count();}
399 // System.err.println("totalBarcodes="+totalBarcodes+
400 // ", pcrMatrix.totalAssignedToExpected="+pcrMatrix.totalAssignedToExpected);
401 double yield=pcrMatrix.totalAssignedToExpected/(double)totalBarcodes;
402 outstream.println(String.format("Total Yield: \t\t%.4f", yield));
403 }
404
405 if(matrixOut!=null) {
406 ByteBuilder bb=pcrMatrix.toBytes(null);
407 ReadWrite.writeString(bb, matrixOut);
408 }
409
410 if(probsOut!=null) {
411 ByteBuilder bb=pcrMatrix.toBytesProb(null);
412 ReadWrite.writeString(bb, probsOut);
413 }
414
415 if(accuracyOut!=null) {
416 ByteBuilder bb=pcrMatrix.toAccuracy(null, excludeUnknownInAccuracy);
417 ReadWrite.writeString(bb, accuracyOut);
418 }
419
420 // pcrMatrix=null;
421 }
422 }
423
424 if(barcodesOut!=null) {
425 ByteStreamWriter bsw=new ByteStreamWriter(barcodesOut, overwrite, append, true);
426 bsw.start();
427 ArrayList<Barcode> list=Barcode.summateAssignments(assignmentMap, bs.expectedCodeList, bs.codeMap);
428 for(Barcode b : list) {
429 bsw.print(b.name).tab().print(b.frequency, 5).tab().print(b.count()).nl();
430 }
431 bsw.poisonAndWait();
432 }
433
434 //This block requires headers are tagged with correct barcode,
435 //using rename.sh suffix="correctbarcode" for each Seal-binned library.
436 if(contamOut!=null) {
437 contamMap=new LinkedHashMap<String, LongPair>(2*bs.expectedCodeList.size());
438 for(Barcode bc : bs.expectedCodeList) {
439 if(bc.expected==1 && !bc.isHomopolymer('G')) {
440 contamMap.put(bc.name, new LongPair());
441 }
442 }
443 HashSet<String> quantSet=null;
444 if(quantSetFile!=null) {
445 quantSet=new HashSet<String>();
446 for(String s : TextFile.toStringLines(quantSetFile)) {
447 quantSet.add(s);
448 }
449 }
450
451 IlluminaHeaderParser2.PARSE_COMMENT=true;
452 long[] sum=new long[5];
453 for(int i=0; i<ffin1.size(); i++){
454 long[] ret=processContam(ffin1.get(i), assignmentMap, contamMap, quantSet, PCRMatrix.byTile);
455 Tools.add(sum, ret);
456 }
457 long processed=sum[0];
458 long numAssignedToBarcode=sum[1];
459 long numAssignedToValid=sum[2];
460 long correct=sum[3];
461 long incorrect=sum[4];
462
463 long good=0, bad=0;
464 double logsum=0;
465 double logsumD=0;
466 double logsumN=0;
467 for(Entry<String, LongPair> e : contamMap.entrySet()) {
468 if(quantSet==null || quantSet.contains(e.getKey())) {
469 LongPair lp=e.getValue();
470 good+=lp.a;
471 bad+=lp.b;
472 logsumD+=Math.log(Tools.max(1.0, (lp.a+lp.b)));
473 if(lp.b>0) {
474 logsumN+=Math.log(lp.b);
475 double ppm=lp.b*1000000.0/Tools.max(1.0, (lp.a+lp.b));
476 logsum+=Math.log(ppm);
477 // System.err.println("log="+Math.log(ppm)+", sum="+logsum);
478 }
479 }
480 }
481 assert(good==correct);
482 final int denominator=(quantSet==null ? contamMap.size() : quantSet.size());
483 double avgppm=bad*1000000.0/(double)(good+bad);
484 double geoavg=Math.exp(logsum/denominator);
485 double geoavgD=Math.exp(logsumD/denominator);
486 double geoavgN=Math.exp(logsumN/denominator);
487 double geoavg2=1000000*geoavgN/geoavgD;
488 double yield=numAssignedToValid/(double)processed;
489 double cyield=good/(double)processed;
490 double iyield=bad/(double)processed;
491 outstream.println(String.format("Contam Avg PPM: \t%.2f", avgppm));
492 outstream.println(String.format("Contam Geo Avg: \t%.2f", geoavg));
493 outstream.println(String.format("Contam Geo Avg2:\t%.2f", geoavg2));
494
495 outstream.println(String.format("Total Yield: \t%.4f", yield));
496 outstream.println(String.format("Correct Yield: \t%.4f", cyield));
497 outstream.println(String.format("Incorrect Yield:\t%.7f", iyield));
498 // System.err.println("geoavg="+geoavg+", logsum="+logsum+", contamMap.size()="+contamMap.size());
499 ByteStreamWriter bsw=new ByteStreamWriter(contamOut, overwrite, append, true);
500 bsw.start();
501 bsw.print("#Total\t").println(good+bad);
502 bsw.print("#Good\t").println(good);
503 bsw.print("#Bad\t").println(bad);
504 bsw.print("#AvgPPM\t").println(avgppm, 2);
505 bsw.print("#GeoPPM\t").println(geoavg, 2);
506 bsw.print("#TotalYield\t").println(yield, 5);
507 bsw.print("#CorrectYield\t").println(cyield, 5);
508 bsw.println("#Code\tGood\tBad\tPPM");
509 for(Entry<String, LongPair> e : contamMap.entrySet()) {
510 String key=e.getKey();
511 LongPair lp=e.getValue();
512 double ppm=lp.b*1000000.0/Tools.max(1.0, (lp.a+lp.b));
513 bsw.print(key).tab().print(lp.a).tab().print(lp.b).tab().println(ppm, 2);
514 }
515 bsw.poisonAndWait();
516 }
517 }
518
519 if(verbose){outstream.println("Finished; closing streams.");}
520
521 //Write anything that was accumulated by ReadStats
522 errorState|=ReadStats.writeAll();
523
524 //Report timing and results
525 t.stop();
526 outstream.println();
527 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
528
529 //Throw an exception of there was an error in a thread
530 if(errorState){
531 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
532 }
533 }
534
535 /*--------------------------------------------------------------*/
536 /*---------------- Inner Methods ----------------*/
537 /*--------------------------------------------------------------*/
538
539 private ConcurrentReadInputStream makeCris(FileFormat ff1, FileFormat ff2, boolean printPaired){
540 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2,
541 null, null);
542 cris.start(); //Start the stream
543 if(verbose){outstream.println("Started cris");}
544 boolean paired=cris.paired();
545 if(printPaired && !ff1.samOrBam()){
546 outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));
547 }
548 return cris;
549 }
550
551 /** Iterate through the reads */
552 void processCounts(final String countsFile){
553
554 ByteFile bf=ByteFile.makeByteFile(countsFile, true);
555 LineParser lp=new LineParser1('\t');
556
557 byte[] line=bf.nextLine();
558 while(line!=null && Tools.startsWith(line, '#')) {line=bf.nextLine();}
559 assert(line!=null) : "Empty counts file.";
560 {
561 lp.set(line);
562 byte[] code=lp.parseByteArray(0);
563 delimiter=Barcode.delimiter(code);
564 barcodesPerRead=delimiter>0 ? 2 : 1;
565
566 //TODO: This does not take tile into account. EDIT: Should be fine now
567 final int bcLen1, bcLen2;
568 if(barcodesPerRead==1) {
569 bcLen1=code.length-Tools.trailingDigits(code);
570 bcLen2=0;
571 }else {
572 bcLen1=Tools.indexOf(code, delimiter);
573 bcLen2=code.length-bcLen1-1-Tools.trailingDigits(code);
574 }
575 // assert(false) : bcLen1+", "+bcLen2+", "+PCRMatrix.byTile;
576 assert(bs==null); //Otherwise why call this, unless you have multiple counts files
577 if(bs==null) {
578 bs=new BarcodeStats(delimiter, barcodesPerRead, extin);
579 bs.length1=bcLen1;
580 bs.length2=bcLen2;
581 if(expectedBarcodesFile!=null) {
582 bs.loadBarcodeList(expectedBarcodesFile, delimiter, false, false);
583 }
584 }
585 }
586
587 for(; line!=null; line=bf.nextLine()) {
588 lp.set(line);
589 final String prefix=lp.parseString(0);
590 final String code;
591 final int count=lp.parseInt(1);
592 final int tile;
593 if(PCRMatrix.byTile) {
594 int digits=Tools.trailingDigits(prefix);
595 assert(digits>0);
596 int idx=prefix.length()-digits;
597 code=new String(line, 0, idx);
598 tile=Parse.parseInt(prefix, idx);
599 assert(tile>0);
600 // assert(false) : digits+", "+idx+", "+line.length+", '"+new String(code)+"'";
601 }else {
602 code=prefix;
603 tile=0;
604 }
605 // assert(false) : new String(code)+", "+tile+", "+count+", "+new String(line);
606 totalBarcodes+=count;
607 if(count>=minCount0) {
608 bs.increment(code, count, tile);
609 }
610 }
611
612
613 //Close the read streams
614 errorState|=bf.close();
615
616 //Do anything necessary after processing
617
618 }
619
620 /** Iterate through the reads */
621 void processInner(final FileFormat ff1, final FileFormat ff2){
622
623 //Do anything necessary prior to processing
624
625 //Create a read input stream
626 final ConcurrentReadInputStream cris=makeCris(ff1, ff2, true);
627
628 if(bs==null) {
629 if(delimiter<0) {
630 delimiter=(byte)ff1.barcodeDelimiter();
631 barcodesPerRead=ff1.barcodesPerRead();
632 }
633 bs=new BarcodeStats(delimiter, barcodesPerRead, extin);
634 if(expectedBarcodesFile!=null) {
635 bs.loadBarcodeList(expectedBarcodesFile, delimiter, false, false);
636 }
637 }
638 if(bs.length1<1 && bs.length2<1) {
639 bs.length1=ff1.barcodeLength(1);
640 bs.length2=ff1.barcodeLength(2);
641 }
642 readFile(cris);
643
644 //Close the read streams
645 errorState|=ReadWrite.closeStreams(cris);
646
647 //Do anything necessary after processing
648
649 }
650
651 /** Iterate through the reads */
652 long[] processContam(FileFormat ff, HashMap<String, String> assignmentMap,
653 HashMap<String, LongPair> counts, HashSet<String> quantSet, boolean addTile){
654
655 //Do anything necessary prior to processing
656
657 //Create a read input stream
658 final ConcurrentReadInputStream cris=makeCris(ff, null, false);
659
660 //Grab the first ListNum of reads
661 ListNum<Read> ln=cris.nextList();
662
663 long processed=0, numAssignedToBarcode=0, numAssignedToValid=0, correct=0, incorrect=0;
664
665 //As long as there is a nonempty read list...
666 while(ln!=null && ln.size()>0){
667 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
668
669 for(Read r : ln) {
670 processed++;
671 ihp.parse(r);
672 final String barcode=ihp.barcode();
673 assert(barcode!=null) : r.id;
674 // totalBarcodes++; //This should already be handled when reading counts or the reads
675 final int tile=ihp.tile();
676 String key=(addTile ? barcode+tile : barcode);
677 String assigned=assignmentMap.get(key);
678 final String actual=ihp.extra();
679 if(assigned!=null) {
680 numAssignedToBarcode++;
681 if(counts.containsKey(assigned)) {numAssignedToValid++;}
682 }
683 if(actual!=null) {
684 if(quantifySource) {
685 LongPair lp=counts.get(actual);
686 if(lp==null) {
687 assert(false) : "Missing key "+actual+" in:\t"+counts.keySet();
688 lp=new LongPair();
689 counts.put(actual, lp);
690 }
691 if(lp!=null) {
692 if(assigned==null || (quantSet!=null && !quantSet.contains(actual))) {}//Do nothing
693 else if(assigned.equals(actual)) {lp.a++;correct++;}
694 else {lp.b++;incorrect++;}
695 }
696 }else {//Quantify sink
697 LongPair lp=(assigned==null ? null : counts.get(assigned));
698 if(assigned==null) {}//do nothing - it was not assigned to anything
699 else if(actual==null) {} //do nothing - we don't know where it was supposed to go
700 else if((quantSet!=null && !quantSet.contains(assigned))) {} //do nothing
701 else if(lp==null) {//do nothing - it was assigned to a dummy barcode like GGGGGGGG
702 assert(Barcode.isHomopolymer(assigned)) :
703 r.id+" -> "+assigned+"\n"+counts.keySet()+"\n";
704 }else if(quantSet==null || (quantSet.contains(assigned))){
705 if(assigned.equals(actual)) {lp.a++;correct++;}
706 else {lp.b++;incorrect++;}
707 }
708 }
709 }
710 }
711
712 cris.returnList(ln);
713
714 //Fetch a new list
715 ln=cris.nextList();
716 }
717
718 //Notify the input stream that the final list was used
719 if(ln!=null){
720 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
721 }
722
723 //Close the read streams
724 errorState|=ReadWrite.closeStreams(cris);
725
726 //Do anything necessary after processing
727 return new long[] {processed, numAssignedToBarcode, numAssignedToValid, correct, incorrect};
728 }
729
730 void readFile(final ConcurrentReadInputStream cris) {
731 {
732 //Grab the first ListNum of reads
733 ListNum<Read> ln=cris.nextList();
734
735 //Check to ensure pairing is as expected
736 if(ln!=null && !ln.isEmpty()){
737 Read r=ln.get(0);
738 assert(r.samline!=null || (r.mate!=null)==cris.paired());
739 }
740
741 //As long as there is a nonempty read list...
742 while(ln!=null && ln.size()>0){
743 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
744
745 processList(ln, cris);
746
747 //Fetch a new list
748 ln=cris.nextList();
749 }
750
751 //Notify the input stream that the final list was used
752 if(ln!=null){
753 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
754 }
755 }
756 }
757
758 /**
759 * Process a list of Reads.
760 * @param ln The list.
761 * @param cris Read Input Stream
762 * @param ros Read Output Stream for reads that will be retained
763 */
764 void processList(ListNum<Read> ln, final ConcurrentReadInputStream cris){
765
766 //Grab the actual read list from the ListNum
767 final ArrayList<Read> reads=ln.list;
768
769 //Loop through each read in the list
770 for(int idx=0; idx<reads.size(); idx++){
771 final Read r1=reads.get(idx);
772 final Read r2=r1.mate;
773
774 //Validate reads in worker threads
775 if(!r1.validated()){r1.validate(true);}
776 if(r2!=null && !r2.validated()){r2.validate(true);}
777
778 //Track the initial length for statistics
779 final int initialLength1=r1.length();
780 final int initialLength2=r1.mateLength();
781
782 //Increment counters
783 readsProcessed+=r1.pairCount();
784 basesProcessed+=initialLength1+initialLength2;
785
786 {
787 //Reads are processed in this block.
788 processReadPair(r1, r2);
789 }
790 }
791
792 //Notify the input stream that the list was used
793 cris.returnList(ln);
794 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
795 }
796
797
798 /**
799 * Process a single read pair.
800 * @param r1 Read 1
801 * @param r2 Read 2 (may be null)
802 * @return True if the reads should be kept, false if they should be discarded.
803 */
804 void processReadPair(final Read r1, final Read r2){
805 ihp.parse(r1);
806 String code=ihp.barcode();
807 if(code==null){return;}
808 totalBarcodes++;
809 int tile=0;
810 if(PCRMatrix.byTile) {
811 tile=ihp.tile();
812 assert(tile>1000 && tile<3000);//For Illumina
813 }
814 bs.increment(code, 1, tile);
815 }
816
817 /*--------------------------------------------------------------*/
818 /*---------------- Fields ----------------*/
819 /*--------------------------------------------------------------*/
820
821 /** Primary input file path */
822 private ArrayList<String> in1=new ArrayList<String>();
823 /** Secondary input file path */
824 private ArrayList<String> in2=new ArrayList<String>();
825
826 /** Expected Barcodes */
827 private String expectedBarcodesFile=null;
828
829 /** Pre-counted barcodes */
830 private String countsIn=null;
831 private long minCount0=0;
832 private long minCountR=4;
833 private long minCountA=4;
834 private float minCountPercentile=0.0f;
835
836 /** Primary output file path */
837 private String out1=null;
838
839 /** Override input file extension */
840 private String extin=null;
841 /** Override output file extension */
842 private String extout=null;
843
844 private String transitionsOut=null;
845 private String matrixOut=null;
846 private String probsOut=null;
847 private String accuracyOut=null;
848 private String mapOut=null;
849 private String barcodesOut=null;
850 private String contamOut=null;
851 private String quantSetFile=null;
852 private boolean quantifySource=false;
853 private boolean excludeUnknownInAccuracy=true;
854
855 private boolean useServer=false;
856 private boolean setUseServer=false;
857
858 /** Whether interleaved was explicitly set. */
859 private boolean setInterleaved=false;
860
861 private HashMap<String, LongPair> contamMap;
862
863 private BarcodeStats bs;
864 private boolean calcStats=true;
865 private boolean printStats=true;
866
867 byte delimiter=-1;
868 int barcodesPerRead=-1;
869
870 // private PCRMatrix pcrMatrix;
871 private boolean useMatrix=false;
872
873 // private LineParserS2 lp=new LineParserS2(':');
874 private IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
875
876 /*--------------------------------------------------------------*/
877
878 long totalBarcodes=0;
879
880 /** Number of reads processed */
881 protected long readsProcessed=0;
882 /** Number of bases processed */
883 protected long basesProcessed=0;
884
885 /** Quit after processing this many input reads; -1 means no limit */
886 private long maxReads=-1;
887
888 /*--------------------------------------------------------------*/
889 /*---------------- Final Fields ----------------*/
890 /*--------------------------------------------------------------*/
891
892 /** Primary input file */
893 private final ArrayList<FileFormat> ffin1=new ArrayList<FileFormat>();
894 /** Secondary input file */
895 private final ArrayList<FileFormat> ffin2=new ArrayList<FileFormat>();
896
897 /** Primary output file */
898 private final FileFormat ffout1;
899
900 /*--------------------------------------------------------------*/
901 /*---------------- Common Fields ----------------*/
902 /*--------------------------------------------------------------*/
903
904 /** Print status messages to this output stream */
905 private PrintStream outstream=System.err;
906 /** Print verbose messages */
907 public static boolean verbose=false;
908 public static boolean verboseClient=true;
909 /** True if an error was encountered */
910 public boolean errorState=false;
911 /** Overwrite existing output files */
912 private boolean overwrite=true;
913 /** Append to existing output files */
914 private boolean append=false;
915
916 }