Debian Codegraph @

current/jgi/DemuxByName2.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.Arrays;
7 import java.util.BitSet;
8 import java.util.Collection;
9 import java.util.HashMap;
10 import java.util.HashSet;
11 import java.util.LinkedHashSet;
12 import java.util.Map.Entry;
13 import java.util.regex.Pattern;
14
15 import barcode.Barcode;
16 import barcode.BarcodeCounter;
17 import barcode.BarcodeStats;
18 import barcode.PCRMatrix;
19 import dna.AminoAcid;
20 import fileIO.ByteFile;
21 import fileIO.ByteStreamWriter;
22 import fileIO.FileFormat;
23 import fileIO.ReadWrite;
24 import hiseq.IlluminaHeaderParser2;
25 import shared.Parse;
26 import shared.Parser;
27 import shared.PreParser;
28 import shared.Shared;
29 import shared.Timer;
30 import shared.Tools;
31 import stream.BufferedMultiCros;
32 import stream.ConcurrentReadInputStream;
33 import stream.ConcurrentReadOutputStream;
34 import stream.FASTQ;
35 import stream.FastaReadInputStream;
36 import stream.Read;
37 import stream.SamLine;
38 import structures.ByteBuilder;
39 import structures.ListNum;
40 import tracker.ReadStats;
41
42
43 /**
44 * This class is designed to handle very large numbers of output files
45 * with a fixed number of file handles. An example use case is demultiplexing
46 * Illumina Novaseq runs.
47 *
48 * @author Brian Bushnell
49 * @date May 1, 2019
50 *
51 */
52 public class DemuxByName2 {
53
54 /** Code entrance from the command line */
55 public static void main(String[] args){
56
57 //Capture values of static variables that might be modified in case this is called by another class.
58 final int oldCap=Shared.numBuffers(), oldZipThreads=ReadWrite.MAX_ZIP_THREADS(), oldZl=ReadWrite.ZIPLEVEL;
59
60 //External compressor selection
61 final boolean oldPigz=ReadWrite.USE_PIGZ, oldUnpigz=ReadWrite.USE_UNPIGZ;
62 final boolean oldBgzip=ReadWrite.USE_BGZIP, oldPreferBgzip=ReadWrite.PREFER_BGZIP;
63
64 //Preserve quality scores even for reads with with incorrect quality scores
65 final boolean oldCQ=Read.CHANGE_QUALITY;
66
67 //Create and start a timer, for statistics
68 Timer t=new Timer();
69
70 //Create the demultiplexer object
71 DemuxByName2 demultiplexer=new DemuxByName2(args);
72
73 //Process all data
74 demultiplexer.process(t);
75
76 //Restore values of static variables.
77 Shared.setBuffers(oldCap);
78 ReadWrite.ZIPLEVEL=oldZl;
79 ReadWrite.USE_PIGZ=oldPigz;
80 ReadWrite.USE_BGZIP=oldBgzip;
81 ReadWrite.PREFER_BGZIP=oldPreferBgzip;
82 ReadWrite.USE_UNPIGZ=oldUnpigz;
83 ReadWrite.setZipThreads(oldZipThreads);
84 Read.CHANGE_QUALITY=oldCQ;
85
86 //Close the print stream if it was redirected
87 Shared.closeStream(demultiplexer.outstream);
88 }
89
90 /*--------------------------------------------------------------*/
91 /*---------------- Initialization ----------------*/
92 /*--------------------------------------------------------------*/
93
94 /**
95 * Constructor.
96 * @param args Command line arguments
97 */
98 public DemuxByName2(String[] args){
99
100 {//Preparse block for help, config files, and outstream
101 PreParser pp=new PreParser(args, getClass(), false);
102 args=pp.args;
103 outstream=pp.outstream;
104 }
105
106 //Set some static variables
107 Shared.capBuffers(4);
108 ReadWrite.USE_PIGZ=true;
109 ReadWrite.USE_UNPIGZ=true;
110 ReadWrite.setZipThreads(Shared.threads());
111 if(ReadWrite.MAX_ZIP_THREADS()>=8) {
112 ReadWrite.setZipThreadMult(8f/ReadWrite.MAX_ZIP_THREADS());
113 }
114 SamLine.SET_FROM_OK=true;
115
116 //Reduce default compression level to increase speed
117 //This automatically gets bumped up to 4 if pigz/bgzip is detected
118 ReadWrite.ZIPLEVEL=2;
119 Read.CHANGE_QUALITY=false;
120
121
122 {//Argument-parsing block
123
124 //Parse arguments
125 final Parser parser=parse(args);
126
127 //Process parser fields
128 //This is in the constructor rather than a function to allow final fields
129 Parser.processQuality();
130
131 maxReads=parser.maxReads;
132
133 overwrite=ReadStats.overwrite=parser.overwrite;
134 append=ReadStats.append=parser.append;
135 setInterleaved=parser.setInterleaved;
136 trackCardinality=parser.loglog;
137
138 in1=parser.in1;
139 in2=parser.in2;
140 qfin1=parser.qfin1;
141 qfin2=parser.qfin2;
142
143 out1=parser.out1;
144 out2=parser.out2;
145 qfout1=parser.qfout1;
146 qfout2=parser.qfout2;
147
148 extin=parser.extin;
149 extout=parser.extout;
150 }
151
152 PCRMatrix.postParseStatic();
153
154 //Ensure the input and output files are specified correctly
155 validate();
156
157 //Create FileFormat opjects for input files
158 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
159 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
160
161 if(useMatrix || mode==BARCODE_MODE) {
162 barcodeDelimiter=ffin1.barcodeDelimiter();
163 barcodeLength1=ffin1.barcodeLength(1);
164 barcodeLength2=ffin1.barcodeLength(2);
165 }
166
167 //If the input and output are in sam/bam format, print the sam header
168 if(ffin1!=null && out1!=null && ffin1.samOrBam()){
169 useSharedHeader=FileFormat.isSamOrBamFile(out1);
170 }
171
172 //Set up data structures
173 handleModeAndNames();
174 if(mapOut!=null) {BarcodeCounter.writeAssignmentMap(assignmentMap, mapOut, overwrite, append);}
175 }
176
177 /**
178 * Parse command-line arguments
179 * @param args Command-line arguments
180 * @return A Parser object with fields filled from the parameters
181 */
182 private Parser parse(final String[] args){
183
184 //Handles parsing of common flags
185 Parser parser=new Parser();
186 parser.overwrite=overwrite;
187
188 //Handles parsing of flags specific to this program
189 for(int i=0; i<args.length; i++){//Parsing loop
190 String arg=args[i];
191 String[] split=arg.split("=");
192 String a=split[0].toLowerCase();
193 String b=split.length>1 ? split[1] : null;
194
195 if(a.equals("verbose")){
196 verbose=Parse.parseBoolean(b);
197 BufferedMultiCros.verbose=verbose;
198 }else if(a.equals("verbosemcros")){
199 BufferedMultiCros.verbose=Parse.parseBoolean(b);
200 }else if(a.equals("names") || a.equals("name") || a.equals("affixes") || a.equals("expected")){
201 if(b!=null){
202 String[] x=b.split(",");
203 for(String s : x){
204 assignmentMap.put(s, s);
205 }
206 }
207 }else if(a.equals("chrom") || a.equals("chrommode") || a.equals("scaffold")){
208 if(Parse.parseBoolean(b)){mode=CHROM_MODE;}
209 }else if(a.equals("substringmode") || a.equals("substring")){
210 if(Parse.parseBoolean(b)){mode=SUBSTRING_MODE;}
211 }else if(a.equals("barcode") || a.equals("barcodemode") || a.equals("index")){
212 if(Parse.parseBoolean(b)){mode=BARCODE_MODE;}
213 }else if(a.equals("tile")){
214 if(Parse.parseBoolean(b)){mode=TILE_MODE;}
215 }else if(a.equals("perheader") || a.equals("persequence") || a.equals("header") || a.equals("headermode")){
216 if(Parse.parseBoolean(b)){mode=HEADER_MODE;}
217 }else if(a.equals("affix") || a.equals("affixmode")){
218 if(Parse.parseBoolean(b)){mode=AFFIX_MODE;}
219 }else if(a.equals("pcr") || a.equals("pcrmode") || a.equals("probability") || a.equals("prob")){
220 useMatrix=Parse.parseBoolean(b);
221 }else if(a.equals("hdistsum") || a.equals("pairhdist") || a.equals("hdistpair") || a.equals("sumhdist")){
222 hdistSum=Parse.parseBoolean(b);
223 PCRMatrix.parseStatic(arg, a, b);
224 }else if(a.equals("delimiter")){
225 delimiter=Parse.parseSymbol(b);
226 if(delimiter!=null && mode==AFFIX_MODE){mode=DELIMITER_MODE;}
227 }else if(a.equals("prefixmode") || a.equals("prefix") || a.equals("pm")){
228 prefixMode=Parse.parseBoolean(b);
229 }else if(a.equals("suffixmode") || a.equals("suffix") || a.equals("sm")){
230 prefixMode=!Parse.parseBoolean(b);
231 }else if(a.equals("column")){
232 column=Integer.parseInt(b);
233 assert(column>0 || column==-1) : "Column is 1-based; must be 1+ or else -1 to disable.";
234 column--;
235 }else if(a.equalsIgnoreCase("length") || a.equalsIgnoreCase("len") || a.equalsIgnoreCase("affixlength") || a.equalsIgnoreCase("affixlen")){
236 fixedLength=Integer.parseInt(b); //also set affix mode, perhaps
237 }else if(a.equalsIgnoreCase("stats") || a.equalsIgnoreCase("report") || a.equalsIgnoreCase("results")){
238 stats=b;
239 }else if(a.equalsIgnoreCase("minreadstodump") || a.equalsIgnoreCase("minreads")){
240 minReadsToDump=Parse.parseKMG(b);
241 }else if(a.equalsIgnoreCase("printRetireTime")){
242 printRetireTime=Parse.parseBoolean(b);
243 }else if(a.equals("hdist") || a.equals("hamming") ||
244 a.equals("hammingdistance") || a.equals("maxhdist")){
245 hdist=Integer.parseInt(b);
246 PCRMatrix.parseStatic(arg, a, b);
247 }else if(a.equals("outu") || a.equals("outu1")){
248 outu1=b;
249 }else if(a.equals("outu2")){
250 outu2=b;
251 }else if(a.equals("pattern")){
252 parser.out1=b;
253 }else if(a.equals("statsonly")){
254 statsOnly=Parse.parseBoolean(b);
255 }else if(a.equals("remap") || a.equals("replace")){
256 remap=Parse.parseRemap(b);
257 }
258
259 else if(a.equals("countsin")){
260 countsIn=b;
261 }else if(a.equals("countsout")){
262 countsOut=b;
263 }else if(a.equals("mincount0")){
264 minCount0=Long.parseLong(b);
265 }else if(a.equals("mincounta")){
266 minCountA=Long.parseLong(b);
267 }else if(a.equals("mincountr")){
268 minCountR=Long.parseLong(b);
269 }else if(a.equals("mapin")){
270 mapIn=b;
271 }else if(a.equals("mapout")){
272 mapOut=b;
273 }
274
275 else if(a.equals("rc1") || a.equals("rcindex1")){
276 rcIndex1=Parse.parseBoolean(b);
277 }else if(a.equals("rc2") || a.equals("rcindex2")){
278 rcIndex2=Parse.parseBoolean(b);
279 }
280
281 //Old version, allowed more complicated replacements
282 // else if(a.equals("replace")){
283 // if(b==null){
284 // replaceA=replaceB=null;
285 // }else{
286 // if(b.length()==2){
287 // replaceA=b.substring(0, 1);
288 // replaceB=b.substring(1);
289 // }else{
290 // String[] pair=b.split(",");
291 // replaceA=Parse.parseSymbol(pair[0]);
292 // replaceB=Parse.parseSymbol(pair[1]);
293 // }
294 // }
295 // }
296
297 else if(PCRMatrix.parseStatic(arg, a, b)){
298 //Flag was captured by PCRMatrix; do nothing
299 }else if(BufferedMultiCros.parseStatic(arg, a, b)){
300 //Flag was captured by BufferedMultiCros; do nothing
301 }else if(parser.parse(arg, a, b)){
302 //Flag was captured by the parser; do nothing
303 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
304 parser.in1=arg;
305 }else{
306 outstream.println("Unknown parameter "+args[i]);
307 assert(false) : "Unknown parameter "+args[i];
308 }
309 }
310
311 return parser;
312 }
313
314 /**
315 * Ensure input and output files are specified correctly,
316 * and that interleaved mode is consistent with the number of input files.
317 */
318 private void validate(){
319
320 //Validate patterns
321 assert(out1==null || out1.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
322 assert(out2==null || out2.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
323 assert(qfout1==null || qfout1.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
324 assert(qfout2==null || qfout2.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
325
326 //Perform # replacement for twin files
327 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
328 in2=in1.replace("#", "2");
329 in1=in1.replace("#", "1");
330 }
331 if(out1!=null && out2==null && out1.indexOf('#')>-1){
332 out2=out1.replace("#", "2");
333 out1=out1.replace("#", "1");
334 }
335 if(outu1!=null && outu2==null && outu1.indexOf('#')>-1){
336 outu2=outu1.replace("#", "2");
337 outu1=outu1.replace("#", "1");
338 }
339
340 //Disable interleaving if in2 is specified
341 if(in2!=null){
342 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
343 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
344 }
345
346 {//Perform various file validation
347 assert(FastaReadInputStream.settingsOK());
348 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
349 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
350
351 //ByteFile2 is multithreaded; only use it if there are plenty of threads
352 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
353 ByteFile.FORCE_MODE_BF2=true;
354 }
355
356 //Do some interleaving-detection logic if unspecified
357 if(!setInterleaved){
358 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
359 if(in2!=null){ //If there are 2 input streams.
360 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
361 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
362 }else{ //There is one input stream.
363 if(out2!=null){
364 FASTQ.FORCE_INTERLEAVED=true;
365 FASTQ.TEST_INTERLEAVED=false;
366 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
367 }
368 }
369 }
370
371 //If the user explicitly used the word "null", change it to null.
372 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
373 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
374
375 //Ensure output files have no duplicates and can be written
376 //Unfortunately, this does not prevent patterns expanding into a matching string
377 if(!Tools.testOutputFiles(overwrite, append, false, outu1, outu2, stats)){
378 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2+", "+outu1+", "+outu2+", "+stats);
379 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+", "+outu1+", "+outu2+", "+stats+"\n");
380 }
381
382 //This does not prevent expansion into a matching string
383 assert(out1==null || (!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1))) : "Input file and output file have same name.";
384 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
385 }
386 }
387
388 /**
389 * Perform necessary setup of variables and data structures
390 * related to the processing mode and the names table.
391 */
392 private void handleModeAndNames(){
393
394 //For length-1 delimiters, use a char instead of a String
395 assert(column<0 || delimiter!=null) : "Column may not be set if there is no delimiter.";
396 if(delimiter!=null){
397 if(delimiter.length()==1){
398 delimiterChar=delimiter.charAt(0);
399 }else if(delimiter.length()==2 && delimiter.charAt(0)=='\\'){
400 delimiterChar=delimiter.charAt(1);
401 }else{
402 delimiterChar=0;
403 }
404 delimiterPattern=Pattern.compile(delimiter);
405 }
406
407 int barcodeLength=0;
408
409 //Handle names
410 if(mapIn!=null) {
411 assignmentMap=BarcodeCounter.loadAssignmentMap(mapIn);
412 }else if(assignmentMap.isEmpty()){
413 assignmentMap=null;
414 }else{
415 {//Process names, because they can either be literals or filenames at this point
416 LinkedHashSet<String> set=new LinkedHashSet<String>(assignmentMap.keySet());
417 assignmentMap.clear();
418 set=BarcodeStats.loadBarcodeSet(set, (byte)barcodeDelimiter, rcIndex1, rcIndex2);
419 for(String key : set){assignmentMap.put(key, key);}
420 }
421 }
422
423 if(useMatrix) {
424 pcrMatrix=PCRMatrix.create(barcodeLength1, barcodeLength2, barcodeDelimiter);
425 assert(!assignmentMap.isEmpty());
426 assert(mapIn==null);
427 pcrMatrix.populateExpected(assignmentMap.keySet());
428 Timer t=new Timer();
429 final Collection<Barcode> counts;
430
431 System.err.print("Counting Barcodes:\t");
432 if(countsIn!=null) {counts=BarcodeCounter.loadCounts(countsIn, minCount0);}
433 else {
434 HashMap<String, Barcode> codeMap=BarcodeCounter.countBarcodes(ffin1, maxReads, PCRMatrix.byTile);
435 counts=codeMap.values();
436 if(countsOut!=null) {BarcodeCounter.writeCounts(counts, minCount0, countsOut, true, overwrite, append);}
437 }
438 t.stop("");
439 t.start();
440
441 pcrMatrix.populateSplitCodes();
442 pcrMatrix.initializeData();
443 pcrMatrix.refine(counts, minCountR);
444 // pcrMatrix.verbose=true;
445 assignmentMap=pcrMatrix.makeAssignmentMap(counts, minCountA);
446 pcrMatrix=null;
447 t.stop("Assignment Time:\t\t");
448 }
449
450 //Handle affix lengths
451 if(mode==AFFIX_MODE && assignmentMap!=null){
452
453 {//Find the lengths of all names to fill the lengthArray array
454 BitSet bs=new BitSet();//A set of observed affix lengths
455
456 //Add the fixed affix length, if present
457 if(fixedLength>0){bs.set(fixedLength);}
458
459 //Add the lengths of everything in the names set
460 for(String s : assignmentMap.keySet()){bs.set(s.length());}
461
462 //Put the set members into an array for faster access
463 lengthArray=new int[bs.cardinality()];
464 for(int i=0, bit=-1; i<lengthArray.length; i++){
465 bit=bs.nextSetBit(bit+1);
466 lengthArray[i]=bit;
467 }
468
469 //Sort and reverse so that the lengths are descending
470 Arrays.sort(lengthArray);
471 Tools.reverseInPlace(lengthArray);
472 }
473
474 assert((lengthArray.length>0 && lengthArray[0]>0)) :
475 "Must include at least one name, an affix length, or a delimiter.";
476
477 //If there are more than one length, disable the fixedLength mode
478 if(lengthArray!=null && lengthArray.length>1){fixedLength=-1;}
479 else if(lengthArray.length==1){
480 assert(fixedLength<1 || fixedLength==lengthArray[0]) :
481 "\nLength flag ("+fixedLength+") does not match detected name length of "+lengthArray[0]+
482 "\nPlease omit the length flag or set it correctly.\n";
483 fixedLength=lengthArray[0];
484 lengthArray=null;
485 }
486 }
487
488 //Populate names table with mutants for hamming distance
489 if(hdist>0 && assignmentMap.size()>0 && !useMatrix){
490 boolean oldMode=false;
491 if(oldMode) {
492 @SuppressWarnings("unused")
493 int numMutants=mutate_old(assignmentMap, hdist, outstream);
494 }else if(hdistSum){
495 mutateUnified(assignmentMap, hdist, outstream);
496 }else {
497 HashMap<String, String>[] maps=mutateDual(assignmentMap, hdist, barcodeDelimiter, outstream);
498 if(maps!=null) {
499 leftNames=maps[0];
500 rightNames=maps[1];
501 }
502 }
503 }
504
505 //Populate name list with keys from the name map
506 if(assignmentMap==null && !useMatrix){
507 nameList=null;
508 }else{
509 for(Entry<String, String> e : assignmentMap.entrySet()){
510 nameList.add(e.getKey());
511 }
512 }
513
514 //Ensure there are names in substring mode
515 if(mode==SUBSTRING_MODE){
516 assert(nameList!=null && !nameList.isEmpty()) :
517 "Empty names list is not allowed in substring mode.";
518 }
519
520 //Perform symbol replacements in output filenames
521 if(remap!=null && assignmentMap!=null && !assignmentMap.isEmpty()){
522 for(String key : nameList){
523 String old=assignmentMap.get(key);
524 String value=Tools.remap(remap, old);
525 if(!value.equals(old)){assignmentMap.put(key, value);}
526 }
527 }
528 }
529
530 /*--------------------------------------------------------------*/
531 /*---------------- Inner Methods ----------------*/
532 /*--------------------------------------------------------------*/
533
534 /**
535 * Primary method.
536 * Starts and stops I/O streams, processes the data, and prints results.
537 * @param t A timer that was already started.
538 */
539 void process(Timer t){
540
541 //Create stream for input reads
542 final ConcurrentReadInputStream cris=makeInputStream();
543
544 //Create streams for output reads other than unmatched
545 final BufferedMultiCros mcros=makeMatchedOutputStream(cris.paired());
546
547 //Create stream for unmatched output reads
548 final ConcurrentReadOutputStream rosu=makeUnmatchedOutputStream();
549
550 //Streams are set up, so process the reads
551 processInner(cris, mcros, rosu);
552 //At this point processing has finished.
553
554 //Close streams
555 cleanup(cris, mcros, rosu);
556
557 //Report statistics to file
558 if(stats!=null){printReport(mcros);}
559
560 if(printRetireTime) {
561 outstream.println("\n"+mcros.printRetireTime()+mcros.printCreateTime()+"\n");
562 }
563
564 //Stop the timer
565 t.stop();
566
567 //Print results
568 printResultsToScreen(t);
569
570 if(errorState){//Exit with a message and error code
571 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
572 }
573 }
574
575 /** Create and start the input stream (cris). */
576 private ConcurrentReadInputStream makeInputStream(){
577 //Stream for input reads
578 final ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, useSharedHeader, ffin1, ffin2, qfin1, qfin2);
579 if(verbose){outstream.println("Started cris");}
580 cris.start();
581
582 //Report whether the input is being processed as paired.
583 final boolean paired=cris.paired();
584 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
585 return cris;
586 }
587
588 /** Create and start the normal output streams (mcros). */
589 private BufferedMultiCros makeMatchedOutputStream(boolean pairedInput){
590 //Streams for output reads other than unmatched
591 final BufferedMultiCros mcros;
592 if(out1!=null){
593
594 mcros=BufferedMultiCros.make(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ);
595
596 //Set mcros fields not available in constructor
597 mcros.minReadsToDump=minReadsToDump;
598 mcros.trackCardinality=trackCardinality;
599
600 //Report output format
601 if(pairedInput && out2==null && (in1==null || !ffin1.samOrBam())){
602 outstream.println("Writing interleaved.");
603 }
604
605 //Start the mcros thread if necessary
606 if(mcros.threaded){mcros.start();}
607 }else{
608 mcros=null;
609 }
610 return mcros;
611 }
612
613 /** Create and start the unmatched output stream (rosu). */
614 private ConcurrentReadOutputStream makeUnmatchedOutputStream(){
615 //Stream for unmatched output reads
616 final ConcurrentReadOutputStream rosu;
617 if(outu1!=null){
618 //Number of output buffers; does not need to be high since access is single-threaded
619 final int buff=4;
620
621 FileFormat ffout1=FileFormat.testOutput(outu1, FileFormat.FASTQ, extout, true, overwrite, append, false);
622 FileFormat ffout2=(outu2==null ? null : FileFormat.testOutput(outu2, FileFormat.FASTQ, extout, true, overwrite, append, false));
623 rosu=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, true);
624 rosu.start();
625 }else{
626 rosu=null;
627 }
628
629 return rosu;
630 }
631
632 /**
633 * Process all reads.
634 * @param cris Input stream (required).
635 * @param mcros Matched read output stream (optional).
636 * @param rosu Unmatched read output stream (optional).
637 */
638 private void processInner(final ConcurrentReadInputStream cris, final BufferedMultiCros mcros, final ConcurrentReadOutputStream rosu) {
639
640 //Fetch the first list
641 ListNum<Read> ln=cris.nextList();
642 ArrayList<Read> reads=(ln!=null ? ln.list : null);
643
644 //Ensure pairing seems correct
645 if(reads!=null && !reads.isEmpty()){
646 Read r=reads.get(0);
647 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
648 }
649
650 //While there are more reads to process...
651 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
652
653 //List to accumulate unmatched reads
654 ArrayList<Read> unmatched=new ArrayList<Read>();
655
656 //For each read...
657 for(Read r : reads){
658
659 //Get the target file identifier
660 String name=getValue(r);
661 final int pairCount=r.pairCount(), pairLen=r.pairLength();
662 if(name!=null){
663 //Set the name so that the mcros will send it to the right place
664 r.obj=name;
665 readsOut+=pairCount;
666 basesOut+=pairLen;
667 }else{
668 //Send it to unmatched
669 unmatched.add(r);
670 readsUnmatched+=pairCount;
671 basesUnmatched+=pairLen;
672 }
673
674 readsProcessed+=pairCount;
675 basesProcessed+=pairLen;
676 }
677 if(rosu!=null){rosu.add(unmatched, ln.id);}//Send unmatched reads to rosu
678 if(mcros!=null){mcros.add(reads);}//Send matched reads to mcros
679
680 //Notify the input stream that the list has been processed
681 cris.returnList(ln);
682
683 //Fetch a new list
684 ln=cris.nextList();
685 reads=(ln!=null ? ln.list : null);
686 }
687
688 //Notify the input stream that this thread is done processing
689 if(ln!=null){
690 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
691 }
692 }
693
694 /**
695 * Finish writing and close streams.
696 * @param cris Input stream (required).
697 * @param mcros Matched read output stream (optional).
698 * @param rosu Unmatched read output stream (optional).
699 */
700 private void cleanup(final ConcurrentReadInputStream cris, final BufferedMultiCros mcros, final ConcurrentReadOutputStream rosu){
701
702 //Shut down mcros
703 if(mcros!=null){
704 mcros.close();
705 errorState|=mcros.errorState();
706 }
707
708 if(minReadsToDump>0 && mcros!=null){
709 //Dump the residual reads into the unmatched file
710 mcros.dumpResidual(rosu);
711
712 //Adjust statistics to reflect that residuals did not get demultiplexed
713 readsOut-=mcros.residualReads;
714 basesOut-=mcros.residualBases;
715 }
716
717 //errorState|=ReadStats.writeAll(); //Currently unused; allows tracking statistics.
718
719 //Shut down normal streams
720 errorState|=ReadWrite.closeStreams(cris, rosu);
721 }
722
723 /**
724 * @param t A Timer that has already been stopped
725 */
726 private void printResultsToScreen(Timer t) {
727 //Report statistics to screen
728 double rpnano=readsProcessed/(double)(t.elapsed);
729 double bpnano=basesProcessed/(double)(t.elapsed);
730
731 outstream.println("Time: "+t);
732 outstream.println("Reads Processed: "+readsProcessed+" \t"+Tools.format("%.2fk reads/sec", rpnano*1000000));
733 outstream.println("Bases Processed: "+basesProcessed+" \t"+Tools.format("%.2fm bases/sec", bpnano*1000));
734 outstream.println("Reads Out: "+readsOut);
735 outstream.println("Bases Out: "+basesOut);
736 outstream.println("Yield: "+String.format("%.5f", readsOut*1.0/readsProcessed));
737 }
738
739 /*--------------------------------------------------------------*/
740 /*---------------- Helper Methods ----------------*/
741 /*--------------------------------------------------------------*/
742
743 /**
744 * Generate mutants for all names according to the hamming distance
745 * @param names Map of names to mutate
746 * @param hdist Hamming distance
747 * @param outstream Report results here
748 * @return Number of mutants added (net)
749 */
750 private static int mutate_old(HashMap<String, String> names, int hdist, PrintStream outstream){
751
752 //Put the names in a list for iteration, to prevent concurrent modification of the table
753 ArrayList<String> list=new ArrayList<String>(names.size());
754 list.addAll(names.values());
755
756 //Number of mutants generated
757 int mutants=0;
758
759 //Set of colliding keys to be removed
760 final HashSet<String> collisions=new HashSet<String>();
761
762 //Generate the mutants
763 for(String name : list){
764 mutants+=addMutants_old(name.getBytes(), name, hdist, names, collisions);
765 }
766 outstream.println("Added "+mutants+" mutants to the initial "+list.size()+" names.");
767
768 //Remove original keys from collisions so that it only contains mutants
769 collisions.removeAll(list);
770
771 int removed=0;
772 if(!collisions.isEmpty()){//Remove colliding mutants from the name table
773 for(String key : collisions) {
774 names.remove(key);
775 removed++;
776 }
777 outstream.println("Removed "+removed+" collisions due to ambiguity.");
778 }
779
780 final int netChange=mutants-removed;
781 return netChange;
782 }
783
784 /**
785 * Generate mutants for one name, recursively
786 * @param keyArray Current key (name) as a byte array, to be modified
787 * @param value Name to which this key should map
788 * @param hdist Remaining Hamming distance
789 * @param names Names table to insert the mutants
790 * @param collisions Set of keys mapping to multiple values
791 * @return Number of mutants added
792 */
793 private static int addMutants_old(final byte[] keyArray, final String value, final int hdist, final HashMap<String, String> names, final HashSet<String> collisions){
794 assert(hdist>0);
795 int added=0;
796
797 //For each position in the array, change it to all possible values
798 for(int i=0; i<keyArray.length; i++){
799 final byte old=keyArray[i];
800 if(AminoAcid.isACGTN(old)){//Only mutate bases
801 for(byte b : symbols){
802 if(b!=old){
803 keyArray[i]=b;
804 {
805 String key=new String(keyArray);
806 String oldValue=names.get(key);
807 if(oldValue==null){
808 names.put(key, value);
809 added++;
810 // outstream.println("Added "+key+"->"+value+"; oldValue="+oldValue);
811 }else if(!oldValue.equals(value)){
812 // assert(value.equals(names.get(s))) : "Collision between "+value+" and "+names.get(s)+" for mutant "+s;
813 collisions.add(key);
814 // outstream.println("Collision for "+key+"->"+value+"; oldValue="+oldValue);
815 }
816 }
817 if(hdist>1){
818 //Recur on the mutant, with a reduced Hamming distance
819 added+=addMutants_old(keyArray, value, hdist-1, names, collisions);
820 }
821 }
822 }
823 //Restore the original value before moving to the next position
824 keyArray[i]=old;
825 }
826 }
827 return added;
828 }
829
830 //Easy mode for single barcodes or shared hdist
831 private static void mutateUnified(final HashMap<String, String> input, final int maxHDist, PrintStream outstream) {
832 if(maxHDist<1) {return;}
833 for(int hdist=1; hdist<=maxHDist; hdist++) {
834 addMutants(input);
835 }
836 }
837
838 //TODO: Seems to map mutants to themselves instead of to their targets
839 //Oh... this is just wrong. The key pairs need to stay associated. Only one pair can be mutated at a time.
840 @SuppressWarnings("unchecked")
841 private static HashMap<String, String>[] mutateDual(final HashMap<String, String> input, final int maxHDist, final int delimiter, PrintStream outstream) {
842 assert(maxHDist>0);
843
844 HashMap<String, String> left=new HashMap<String, String>(input.size()*2);
845 HashMap<String, String> right=new HashMap<String, String>(input.size()*2);
846 for(Entry<String, String> e : input.entrySet()) {
847 String key=e.getKey();
848 String value=e.getValue();
849 int pos=key.indexOf(delimiter);
850 assert(pos>0) : "Can't find delimiter '"+Character.toString(delimiter)+"' in "+key;
851 final String k1=key.substring(0, pos);
852 final String k2=key.substring(pos+1);
853 final String v1, v2;
854 if(key.equals(value)) {
855 v1=k1;
856 v2=k2;
857 }else {
858 v1=value.substring(0, pos);
859 v2=value.substring(pos+1);
860 }
861 //Here
862 left.put(k1, v1);
863 right.put(k2, v2);
864 }
865 for(int hdist=1; hdist<=maxHDist; hdist++) {
866 addMutants(left);
867 addMutants(right);
868 }
869 long total=left.size()*(long)(right.size());
870
871 assert(false) : left+"\n"+right;
872
873 if(total>1000000) {//For large sets return the twin sets
874 return new HashMap[] {left, right};
875 }
876
877 //For small sets use cross product
878 input.clear();
879 final ByteBuilder bbk=new ByteBuilder(), bbv=new ByteBuilder();
880 for(Entry<String, String> e1 : left.entrySet()) {
881 final String k1=e1.getKey(), v1=e1.getValue();
882 bbk.clear().append(k1).append((char)delimiter);
883 bbv.clear().append(v1).append((char)delimiter);
884 final int len=bbk.length();
885 for(Entry<String, String> e2 : right.entrySet()) {
886 final String k2=e2.getKey(), v2=e2.getValue();
887 final String key=bbk.setLength(len).append(k2).toString();
888 final String value=bbv.setLength(len).append(v2).toString();
889 String old=input.put(key, value);
890 assert(old==null);
891 }
892 }
893 return null;
894 }
895
896 private static void addMutants(final HashMap<String, String> input) {
897 final HashMap<String, String> output=new HashMap<String, String>();
898 for(Entry<String, String> e : input.entrySet()) {
899 String k=e.getKey();
900 String v=e.getValue();
901 addMutants2(k, v, output);
902 }
903 for(Entry<String, String> e : output.entrySet()) {
904 String k=e.getKey();
905 String v=e.getValue();
906 if(v.length()>0 && !input.containsKey(k)) {
907 input.put(k, v);
908 }
909 }
910 }
911
912 private static int addMutants2(final String k0, final String v0, final HashMap<String, String> map) {
913 byte[] bases=k0.getBytes();
914 int added=0, removed=0, collisions=0;
915 //For each position in the array, change it to all possible values
916 for(int i=0; i<bases.length; i++){
917 final byte old=bases[i];
918 if(AminoAcid.isACGTN(old)){//Only mutate bases
919 for(byte b : symbols){
920 if(b!=old){
921 bases[i]=b;
922 String key=new String(bases);
923 String oldValue=map.get(key);
924 if(oldValue==null){//Add to map
925 map.put(key, v0);
926 added++;
927 }else if(oldValue==empty) {
928 collisions++;
929 }else if(oldValue.equals(v0)) {
930 //do nothing
931 }else {//Remove value
932 map.put(key, empty);
933 removed++;
934 collisions++;
935 }
936 }
937 }
938 //Restore the original value before moving to the next position
939 bases[i]=old;
940 }
941 }
942 return added;
943 }
944
945 /** Returns the value this read maps to; meaning, the variable part of the output filename */
946 private String getValue(Read r){
947 final String key=getKey(r);
948 if(verbose){System.err.println("Got key "+key);}
949 if(key==null){return null;}
950
951 //Return the value this key maps to
952 if(assignmentMap!=null){
953 String name=assignmentMap.get(key);
954 if(name==null && leftNames!=null) {//This branch does not occur in matrix mode
955 int idx=key.indexOf(barcodeDelimiter);
956 assert(idx>=0);
957 String k1=key.substring(0, idx), k2=key.substring(idx+1);
958 String v1=leftNames.get(k1), v2=rightNames.get(k2);
959 if(v1!=null && v2!=null) {
960 name=v1+Character.toString(barcodeDelimiter)+v2;
961 }
962 }
963 if(verbose){System.err.println("Got value "+assignmentMap.get(key));}
964 return name;
965 }
966
967 //Return the value generated by remapping the key's symbols, if needed
968 final String value=(remap==null ? key : Tools.remap(remap, key));
969 if(verbose){System.err.println("Returning value "+value);}
970 return value;
971 }
972
973
974 private int hdist(String q, String r) {
975 return hdistSum ? Barcode.hdist(q, r) : Tools.max(Barcode.hdistL(q, r), Barcode.hdistR(q, r));
976 }
977
978 //TODO: Populate expectedList; currently this is unused.
979 //TODO: Decide to populate based on number of expected mutants.
980 public String findClosest(String q, int maxHDist, int clearzone) {
981 assert(!expectedList.isEmpty());
982
983 int hdist=q.length();
984 int hdist2=hdist;
985 String best=null;
986 for(String b : expectedList) {
987 final int d=hdist(q, b);
988 if(d<hdist2) {
989 hdist2=d;
990 if(d<hdist) {
991 hdist2=hdist;
992 best=b;
993 hdist=d;
994 }
995 }
996 }
997 if(hdist>maxHDist || hdist+clearzone>hdist2) {return null;}
998 return best;
999 }
1000
1001 /** Generates a key from the read header */
1002 private String getKey(Read r){
1003 final String id=r.id;
1004 final int idlen=id.length();
1005 final String key;
1006
1007 //Simplest case; every header is its own key
1008 if(mode==HEADER_MODE){return id;}
1009
1010 //Parse the barcode
1011 if(mode==BARCODE_MODE){
1012 ihp.parse(id);
1013 String bc=ihp.barcode();
1014 return (useMatrix && PCRMatrix.byTile) ? bc+ihp.tile() : bc;
1015 }
1016
1017 //Parse the tile
1018 if(mode==TILE_MODE){
1019 ihp.parse(id);
1020 return Integer.toString(ihp.tile());//This could be faster with an ArrayList<String> cache
1021 }
1022
1023 //Use mapping information
1024 if(mode==CHROM_MODE){return r.rnameS();}
1025
1026 //Return a prefix or suffix
1027 if(mode==AFFIX_MODE){
1028 if(fixedLength>0){//If there is a single fixed affix length, return the affix
1029 key=(id.length()<=fixedLength ? id : prefixMode ? id.substring(0, fixedLength) : id.substring(idlen-fixedLength));
1030 return key;
1031 }else{//Make a substring of each possible length and look it up in the hashmap
1032 for(int affixLen : lengthArray){
1033 final String sub=idlen>=affixLen ? prefixMode ? id.substring(0, affixLen) : id.substring(idlen-affixLen) : id;
1034 if(assignmentMap.containsKey(sub)){return sub;}
1035 }
1036 return null;
1037 }
1038 }
1039
1040 //Return a delimited substring
1041 if(mode==DELIMITER_MODE){
1042
1043 if(column>-1){//Use a split operation, which is slow
1044
1045 // String[] split=id.split(delimiter);
1046 String[] split=delimiterPattern.split(id);//Faster; uses a precompiled pattern
1047 assert(split.length>1) : "Delimiter '"+delimiter+"' was not found in name '"+id+"'";
1048
1049 int col=Tools.min(column, split.length-1);
1050 key=split[col];
1051 if(col!=column && !warned){
1052 outstream.println("*** WARNING! ***\n"
1053 + "Only "+(col+1)+" columns for record "+id+"\n"
1054 + "Further warnings will be suppressed.\n");
1055 warned=true;
1056 assert(errorState=true); //Change error state to true if assertions are enabled.
1057 }
1058 }else if(prefixMode){//Use a delimited prefix, which is fast
1059 //Find the first index of the delimiter, using the char when possible
1060 int idx=(delimiterChar>0 ? id.indexOf(delimiterChar) : id.indexOf(delimiter));
1061 assert(idx>=0) : "Delimiter\r\n" +
1062 " System.err.println(\"a\"); '"+delimiter+"' was not found in name '"+id+"'";
1063 key=id.substring(0, idx);
1064 }else{//Use a delimited suffix, which is fast
1065 //Find the last index of the delimiter, using the char when possible
1066 int idx=(delimiterChar>0 ? id.lastIndexOf(delimiterChar) : id.lastIndexOf(delimiter));
1067 assert(idx>=0) : "Delimiter '"+delimiter+"' was not found in name '"+id+"'";
1068 key=id.substring(idx+delimiter.length());
1069 }
1070 return key;
1071 }
1072
1073 //Substring mode requires brute-force matching and is very slow
1074 if(mode==SUBSTRING_MODE){
1075 if(nameList.size()>0){
1076 for(String s : nameList){
1077 if(id.contains(s)){return s;}
1078 }
1079 return null;
1080 }
1081 }
1082
1083 throw new RuntimeException("No mode is being used: "+mode); //Should be unreachable
1084 }
1085
1086 /**
1087 * Print statistics about demultiplexing to a file.
1088 * @param mcros Output stream, after processing is completely finished.
1089 */
1090 void printReport(BufferedMultiCros mcros){
1091 if(stats==null){return;}
1092
1093 //Make a writer for the stats file
1094 ByteStreamWriter bsw=new ByteStreamWriter(stats, overwrite, append, true);
1095 bsw.start();
1096
1097 {
1098 ByteBuilder bb=new ByteBuilder();
1099
1100 //Print the header
1101 bb.append("#ReadsIn\t").append(readsProcessed).nl();
1102 bb.append("#BasesIn\t").append(basesProcessed).nl();
1103 bb.append("#ReadsOut\t").append(readsOut).nl();
1104 bb.append("#BasesOut\t").append(basesOut).nl();
1105 bb.append("#Name\tReads\tBases"+(trackCardinality ? "\tCardinality" : "")+"\n");
1106
1107 //Print results of unmatched reads, which is not captured by the mcros
1108 if(assignmentMap!=null && !assignmentMap.isEmpty()){
1109 bb.append("Unmatched\t").append(readsUnmatched).tab().append(basesUnmatched).nl();
1110 }
1111 bsw.print(bb);
1112 }
1113
1114 if(mcros!=null){//Print results from the mcros
1115 ByteBuilder bb=mcros.report();
1116 bsw.print(bb);
1117 }
1118
1119 //Finish writing
1120 bsw.poisonAndWait();
1121 }
1122
1123 /*--------------------------------------------------------------*/
1124 /*---------------- Fields ----------------*/
1125 /*--------------------------------------------------------------*/
1126
1127 /** Primary input file */
1128 private String in1=null;
1129 /** Optional input file for read 2 of paired reads in twin files */
1130 private String in2=null;
1131
1132 /** Input qual file 1 */
1133 private String qfin1=null;
1134 /** Input qual file 2 */
1135 private String qfin2=null;
1136
1137 /** Output file pattern 1 */
1138 private String out1=null;
1139 /** Output file pattern 2 */
1140 private String out2=null;
1141
1142 /** Output qual file 1 */
1143 private String qfout1=null;
1144 /** Output qual file 2 */
1145 private String qfout2=null;
1146
1147 /** Unmatched read output file 1 */
1148 private String outu1=null;
1149 /** Unmatched read output file 2 */
1150 private String outu2=null;
1151
1152 /** File extension override for input files */
1153 private String extin=null;
1154 /** File extension override for output files */
1155 private String extout=null;
1156
1157 /** Pre-counted barcodes */
1158 private String countsIn=null;
1159 /** Output for barcode counts */
1160 private String countsOut=null;
1161
1162 /**
1163 * Ignore barcodes occuring fewer times than this.
1164 * Saves memory and speeds processing. */
1165 private long minCount0=0;
1166 private long minCountR=4;
1167 private long minCountA=4;
1168
1169 /** Premade assignment map */
1170 private String mapIn=null;
1171 /** Assignment map output */
1172 private String mapOut=null;
1173
1174 /*--------------------------------------------------------------*/
1175
1176 /** Primary input file */
1177 private final FileFormat ffin1;
1178
1179 /** Read 2 input file */
1180 private final FileFormat ffin2;
1181
1182 /*--------------------------------------------------------------*/
1183
1184 /** Input reads */
1185 long readsProcessed=0;
1186 long basesProcessed=0;
1187
1188 /** Demultiplexed output reads */
1189 long readsOut=0;
1190 long basesOut=0;
1191
1192 /** Output reads that did not get demultiplexed */
1193 long readsUnmatched=0;
1194 long basesUnmatched=0;
1195
1196 /** Stop after this many input reads */
1197 private long maxReads=-1;
1198
1199 /** File to print number of reads sent to each output file */
1200 private String stats=null;
1201
1202 /** For splitting headers on a symbol */
1203 private String delimiter=null;
1204
1205 /** For splitting headers faster if the delimiter is just one character */
1206 private char delimiterChar=0;
1207
1208 /** Precompiled pattern matching the delimiter */
1209 private Pattern delimiterPattern=null;
1210
1211 /** For replacing symbols in the filename */
1212 private byte[] remap=null;
1213
1214 /** If there is a delimiter, use this column after splitting.
1215 * Column is 1-based. */
1216 private int column=-1;
1217
1218 /** Use the prefix of a header. If false, use the suffix.
1219 * This is ignored if column is set. */
1220 private boolean prefixMode=true;
1221
1222 /** How to select a read's key; see static modes array */
1223 private int mode=AFFIX_MODE;
1224
1225 // /** Assume Illumina header format, and used the barcode. */
1226 // private boolean mode==BARCODE_MODE=false;
1227 //
1228 // /** Allow names to be any substring of a header */
1229 // private boolean substringMode=false;
1230 //
1231 // /** Demultiplex every sequence into its own file */
1232 // private boolean mode==HEADER_MODE=false;
1233 //
1234 // /** Demultiplex mapped reads into one file per reference sequence */
1235 // private boolean mode==CHROM_MODE=false;
1236
1237 /** Track per-output-file cardinality; may be slow */
1238 private boolean trackCardinality=false;
1239
1240 /** Prevents issuing warnings multiple times */
1241 private boolean warned=false;
1242
1243 private boolean printRetireTime=false;
1244
1245 /** Hamming distance for read indexes */
1246 private int hdist=0;
1247
1248 /**
1249 * Do not create files with under this many reads.
1250 * Increases memory usage since reads must be retained until processing is finished.
1251 * Upon running out of memory the program may go very slowly.
1252 */
1253 private long minReadsToDump=0;
1254
1255 /** Affix length if fixed */
1256 private int fixedLength=-1;
1257
1258 /** All possible affix lengths if there are multiple.
1259 * Basically, the lengths of everything in names. */
1260 private int[] lengthArray;
1261
1262 /**
1263 * A set of recognized names and the output names they map to.
1264 * The keys and values will be identical unless a Hamming distance is used.
1265 * This is only filled if explicit names are provided.
1266 */
1267 private HashMap<String, String> assignmentMap=new HashMap<String, String>();
1268
1269 private ArrayList<String> expectedList;
1270
1271 /** These are for dual barcodes and normally null unless
1272 * the mutant table would grow too big. */
1273 private HashMap<String, String> leftNames=null, rightNames=null;
1274
1275 /** Names in list form, for substring matching */
1276 private ArrayList<String> nameList=new ArrayList<String>();
1277
1278 /** Whether input file interleaving was explicitly set */
1279 private boolean setInterleaved=false;
1280
1281 // private IlluminaHeaderParser1 ihp1=new IlluminaHeaderParser1();
1282 private IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
1283
1284 /*--------------------------------------------------------------*/
1285
1286 private int barcodeDelimiter=0;
1287 private int barcodeLength1=0;
1288 private int barcodeLength2=0;
1289 private boolean rcIndex1=false;
1290 private boolean rcIndex2=false;
1291
1292 private PCRMatrix pcrMatrix;
1293 private boolean useMatrix=false;
1294 private boolean hdistSum=true;
1295
1296
1297 /*--------------------------------------------------------------*/
1298
1299 /** Print messages here */
1300 private PrintStream outstream=System.err;
1301
1302 /** True if errors were encountered */
1303 public boolean errorState=false;
1304
1305 /** Permission to overwrite existing files. */
1306 private boolean overwrite=true;
1307
1308 /**
1309 * Append to existing files rather than overwriting.
1310 * It is not advisable to set this flag for this class.
1311 * */
1312 private boolean append=false;
1313
1314 /** Retain header of sam/bam files. */
1315 private boolean useSharedHeader=false;
1316
1317 /*--------------------------------------------------------------*/
1318 /*---------------- Static Fields ----------------*/
1319 /*--------------------------------------------------------------*/
1320
1321 /** Operation mode for selection of key */
1322 public static final int AFFIX_MODE=1, DELIMITER_MODE=2, BARCODE_MODE=3,
1323 SUBSTRING_MODE=4, HEADER_MODE=5, CHROM_MODE=6, TILE_MODE=7;
1324
1325 /**
1326 * Symbols allowed to substitute for Hamming distance.
1327 * Hamming distance is intended for barcodes only.
1328 */
1329 private static final byte[] symbols={'A', 'C', 'G', 'T', 'N'};
1330
1331 private static final String empty="";
1332
1333 /** Verbose messages for debugging */
1334 public static boolean verbose=false;
1335
1336 public static boolean statsOnly=false;
1337
1338 }