Debian Codegraph @

current/barcode/NovaDemux.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.LinkedHashMap;
9 import java.util.LinkedHashSet;
10 import java.util.Map.Entry;
11 import java.util.Set;
12 import java.util.regex.Pattern;
13
14 import aligner.MicroAligner2;
15 import barcode.stub.PCRMatrixProb;
16 import fileIO.ByteFile;
17 import fileIO.ByteStreamWriter;
18 import fileIO.FileFormat;
19 import fileIO.ReadWrite;
20 import hiseq.IlluminaHeaderParser2;
21 import shared.KillSwitch;
22 import shared.LineParserS2;
23 import shared.Parse;
24 import shared.Parser;
25 import shared.PreParser;
26 import shared.Shared;
27 import shared.Timer;
28 import shared.Tools;
29 import stream.BufferedMultiCros;
30 import stream.ConcurrentReadInputStream;
31 import stream.ConcurrentReadOutputStream;
32 import stream.FASTQ;
33 import stream.FastaReadInputStream;
34 import stream.Read;
35 import stream.SamLine;
36 import structures.ByteBuilder;
37 import structures.ListNum;
38 import tracker.ReadStats;
39
40
41 /**
42 * This class is designed to demultiplex barcoded reads using PCRMatrix.
43 *
44 * @author Brian Bushnell
45 * @date April 2, 2024
46 *
47 */
48 public class NovaDemux {
49
50 /** Code entrance from the command line */
51 public static void main(String[] args){
52
53 //Capture values of static variables that might be modified in case this is called by another class.
54 final int oldCap=Shared.numBuffers(), oldZipThreads=ReadWrite.MAX_ZIP_THREADS(), oldZl=ReadWrite.ZIPLEVEL;
55
56 //External compressor selection
57 final boolean oldPigz=ReadWrite.USE_PIGZ, oldUnpigz=ReadWrite.USE_UNPIGZ;
58 final boolean oldBgzip=ReadWrite.USE_BGZIP, oldPreferBgzip=ReadWrite.PREFER_BGZIP;
59
60 //Preserve quality scores even for reads with with incorrect quality scores
61 final boolean oldCQ=Read.CHANGE_QUALITY;
62
63 //Create and start a timer, for statistics
64 Timer t=new Timer();
65
66 //Create the demultiplexer object
67 NovaDemux demultiplexer=new NovaDemux(args);
68
69 //Process all data
70 try {
71 demultiplexer.process(t);
72 } catch (OutOfMemoryError e) {
73 KillSwitch.memKill(e);
74 }
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 NovaDemux(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 SamLine.SET_FROM_OK=true;
111
112 //Reduce default compression level to increase speed
113 //This automatically gets bumped up to 4 if pigz/bgzip is detected
114 ReadWrite.ZIPLEVEL=2;
115 Read.CHANGE_QUALITY=false;
116
117
118 {//Argument-parsing block
119
120 //Parse arguments
121 final Parser parser=parse(args);
122
123 //Process parser fields
124 //This is in the constructor rather than a function to allow final fields
125 Parser.processQuality();
126
127 maxReads=parser.maxReads;
128
129 overwrite=ReadStats.overwrite=parser.overwrite;
130 append=ReadStats.append=parser.append;
131 setInterleaved=parser.setInterleaved;
132 trackCardinality=parser.loglog;
133
134 in1=parser.in1;
135 in2=parser.in2;
136 // qfin1=parser.qfin1;
137 // qfin2=parser.qfin2;
138
139 out1=parser.out1;
140 out2=parser.out2;
141 // qfout1=parser.qfout1;
142 // qfout2=parser.qfout2;
143
144 extin=parser.extin;
145 extout=parser.extout;
146 }
147 PCRMatrix.postParseStatic();
148
149 if(!ReadWrite.SET_ZIP_THREADS) {
150 ReadWrite.setZipThreads(Shared.threads());
151 if(ReadWrite.MAX_ZIP_THREADS()>=8) {
152 float numerator=(ReadWrite.ZIPLEVEL>7 ? 32f : 8f);
153 ReadWrite.setZipThreadMult(numerator/ReadWrite.MAX_ZIP_THREADS());
154 }
155 }
156
157 //Ensure the input and output files are specified correctly
158 validate();
159
160 //Create FileFormat objects for input files
161 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
162 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
163
164 barcodeDelimiter=ffin1.barcodeDelimiter();
165 barcodeLength1=ffin1.barcodeLength(1);
166 barcodeLength2=ffin1.barcodeLength(2);
167
168 //If the input and output are in sam/bam format, print the sam header
169 if(ffin1!=null && out1!=null && ffin1.samOrBam()){
170 useSharedHeader=FileFormat.isSamOrBamFile(out1);
171 }
172
173 //Set up data structures
174 processHeaderDelimiter();
175
176 if(expectedSet==null && sampleMapFile!=null) {
177 expectedSet=new LinkedHashSet<String>();
178 expectedSet.add(sampleMapFile);//This should work due to stripping of tabs.
179 }
180 assert(expectedSet!=null && expectedSet.size()>0) : "Expected barcodes are a required parameter.";
181 BarcodeStats.loadBarcodeSet(expectedSet, (byte)barcodeDelimiter, rcIndex1, rcIndex2);
182 BarcodeStats.loadBarcodeSet(outSubset, (byte)barcodeDelimiter, rcIndex1, rcIndex2);
183
184 // //TODO: Activate this if stat dumps are needed
185 // readstats=ReadStats.collectingStats() ? new ReadStats() : null;
186
187 legacyWriter=(legacyPath==null ? null : new LegacyFileWriter());
188 }
189
190 /**
191 * Parse command-line arguments
192 * @param args Command-line arguments
193 * @return A Parser object with fields filled from the parameters
194 */
195 private Parser parse(final String[] args){
196
197 //Handles parsing of common flags
198 Parser parser=new Parser();
199 parser.overwrite=overwrite;
200
201 //Handles parsing of flags specific to this program
202 for(int i=0; i<args.length; i++){//Parsing loop
203 String arg=args[i];
204 String[] split=arg.split("=");
205 String a=split[0].toLowerCase();
206 String b=split.length>1 ? split[1] : null;
207
208 if(a.equals("verbose")){
209 verbose=Parse.parseBoolean(b);
210 BufferedMultiCros.verbose=verbose;
211 }else if(a.equals("verboseclient")){
212 verboseClient=Parse.parseBoolean(b);
213 }else if(a.equals("verbosemcros")){
214 BufferedMultiCros.verbose=Parse.parseBoolean(b);
215 }else if(a.equals("names") || a.equals("expected") || a.equals("barcodes")){
216 expectedSet=new LinkedHashSet<String>();
217 for(String s : b.split(",")){
218 expectedSet.add(s);
219 }
220 }else if(a.equals("subset") || a.equals("outset") || a.equals("outsubset")){
221 outSubset=new LinkedHashSet<String>();
222 for(String s : b.split(",")){
223 outSubset.add(s);
224 }
225 }else if(a.equals("barcode") || a.equals("barcodemode") || a.equals("index")){
226 if(Parse.parseBoolean(b)){mode=BARCODE_MODE;}
227 }else if(a.equals("perheader") || a.equals("persequence") || a.equals("header") || a.equals("headermode")){
228 if(Parse.parseBoolean(b)){mode=HEADER_MODE;}
229 }else if(a.equals("suffixmode") || a.equals("suffix") || a.equals("sm")){
230 if(Parse.parseBoolean(b)){mode=SUFFIX_MODE;}
231 }else if(a.equals("prefixmode") || a.equals("prefix") || a.equals("pm")){
232 if(Parse.parseBoolean(b)){mode=PREFIX_MODE;}
233 }else if(a.equals("delimiter")){
234 assert(false) : "Please specify headerdelimiter or barcodedelimiter instead of 'delimiter'";
235 }else if(a.equals("hdelimiter") || a.equals("headerdelimiter")){
236 headerDelimiter=Parse.parseSymbol(b);
237 }else if(a.equals("bdelimiter") || a.equals("barcodedelimiter")){
238 String s=Parse.parseSymbol(b);
239 assert(s!=null && s.length()==1) : "Invalid barcode delimiter: "+b;
240 barcodeDelimiter=s.charAt(0);
241 }else if(a.equals("rc1") || a.equals("rcindex1")){
242 rcIndex1=Parse.parseBoolean(b);
243 }else if(a.equals("rc2") || a.equals("rcindex2")){
244 rcIndex2=Parse.parseBoolean(b);
245 }else if(a.equals("column")){
246 column=Integer.parseInt(b);
247 assert(column>0 || column==-1) : "Column is 1-based; must be 1+ or else -1 to disable.";
248 column--;
249 }else if(a.equalsIgnoreCase("length") || a.equalsIgnoreCase("len") ||
250 a.equalsIgnoreCase("affixlength") || a.equalsIgnoreCase("affixlen")){
251 fixedLength=Integer.parseInt(b);
252 }else if(a.equalsIgnoreCase("stats") || a.equalsIgnoreCase("report") || a.equalsIgnoreCase("results")){
253 stats=b;
254 }else if(a.equalsIgnoreCase("minreadstodump") || a.equalsIgnoreCase("minreads")){
255 minReadsToDump=Parse.parseKMG(b);
256 }else if(a.equalsIgnoreCase("printRetireTime")){
257 printRetireTime=Parse.parseBoolean(b);
258 }else if(a.equals("outu") || a.equals("outu1")){
259 outu1=b;
260 }else if(a.equals("outu2")){
261 outu2=b;
262 }else if(a.equals("pattern")){
263 parser.out1=b;
264 }else if(a.equals("legacy") || a.equals("outlegacy") || a.equals("legacyout") || a.equals("legacypath")){
265 legacyPath=b;
266 }else if(a.equals("samplemapfile") || a.equals("samplemap")){
267 sampleMapFile=b;
268 }else if(a.equals("lane")){
269 lane=Integer.parseInt(b);
270 }else if(a.equals("statsonly")){
271 statsOnly=Parse.parseBoolean(b);
272 }else if(a.equals("remap") || a.equals("replace")){
273 symbolRemap=Parse.parseRemap(b);
274 }else if(a.equalsIgnoreCase("writeEmptyFiles") || a.equalsIgnoreCase("writeEmpty")) {
275 writeEmptyFiles=Parse.parseBoolean(b);
276 }else if(a.equals("countsin")){
277 countsIn=b;
278 }else if(a.equals("countsout")){
279 countsOut=b;
280 }else if(a.equals("barcodesout")){
281 barcodesOut=b;
282 }else if(a.equals("mincount0")){
283 minCount0=Long.parseLong(b);
284 }else if(a.equals("mincounta")){
285 minCountA=Long.parseLong(b);
286 }else if(a.equals("mincountr")){
287 minCountR=Long.parseLong(b);
288 }else if(a.equals("mapin")){
289 mapIn=b;
290 }else if(a.equals("mapout")){
291 mapOut=b;
292 }else if(a.equals("client") || a.equals("server") || a.equals("useserver")){
293 if("auto".equalsIgnoreCase(b)) {
294 useServer=false;
295 setUseServer=false;
296 }else{
297 useServer=Parse.parseBoolean(b);
298 setUseServer=true;
299 }
300 }
301
302 else if(a.equals("rename")){
303 rename=Parse.parseBoolean(b);
304 }else if(a.equals("nosplit")){
305 nosplit=Parse.parseBoolean(b);
306 }
307
308
309 else if(a.equals("refpath") || a.equals("spikepath") || a.equals("phixpath")){
310 refPath=b;
311 }else if(a.equals("spikelabel") || a.equals("phixlabel")
312 || a.equals("spikeindex") || a.equals("phixindex")){
313 spikeLabel=b;
314 }else if(a.equals("kspike") || a.equals("kphix")){
315 kSpike=Integer.parseInt(b);
316 }else if(a.equals("skipmask")){
317 skipMask=Integer.parseInt(b);
318 }else if(a.equals("minid") || a.equals("minspikeid") || a.equals("phixid")){
319 minSpikeIdentity=Float.parseFloat(b);
320 if(minSpikeIdentity>1) {minSpikeIdentity/=100;}
321 }else if(a.equalsIgnoreCase("mapUnexpected")){
322 mapUnexpectedToSpike=Parse.parseBoolean(b);
323 }else if(a.equalsIgnoreCase("mapUnknown")){
324 mapUnexpectedToSpike=!Parse.parseBoolean(b);
325 }else if(a.equalsIgnoreCase("mapAll")){
326 mapAllToSpike=Parse.parseBoolean(b);
327 }
328
329 else if(PCRMatrix.parseStatic(arg, a, b)){
330 //Flag was captured by PCRMatrix; do nothing
331 }else if(BufferedMultiCros.parseStatic(arg, a, b)){
332 //Flag was captured by BufferedMultiCros; do nothing
333 }else if(parser.parse(arg, a, b)){
334 //Flag was captured by the parser; do nothing
335 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
336 parser.in1=arg;
337 }else{
338 outstream.println("Unknown parameter "+args[i]);
339 assert(false) : "Unknown parameter "+args[i];
340 }
341 }
342
343 return parser;
344 }
345
346 /**
347 * Ensure input and output files are specified correctly,
348 * and that interleaved mode is consistent with the number of input files.
349 */
350 private void validate(){
351
352 //Validate patterns
353 assert(out1==null || out1.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
354 assert(out2==null || out2.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
355
356 //Perform # replacement for twin files
357 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
358 in2=in1.replace("#", "2");
359 in1=in1.replace("#", "1");
360 }
361 if(out1!=null && out2==null && out1.indexOf('#')>-1){
362 out2=out1.replace("#", "2");
363 out1=out1.replace("#", "1");
364 }
365 if(outu1!=null && outu2==null && outu1.indexOf('#')>-1){
366 outu2=outu1.replace("#", "2");
367 outu1=outu1.replace("#", "1");
368 }
369
370 //Disable interleaving if in2 is specified
371 if(in2!=null){
372 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
373 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
374 }
375
376 {//Perform various file validation
377 assert(FastaReadInputStream.settingsOK());
378 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
379 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
380
381 //ByteFile2 is multithreaded; only use it if there are plenty of threads
382 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
383 ByteFile.FORCE_MODE_BF2=true;
384 }
385
386 //Do some interleaving-detection logic if unspecified
387 if(!setInterleaved){
388 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
389 if(in2!=null){ //If there are 2 input streams.
390 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
391 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
392 }else{ //There is one input stream.
393 if(out2!=null){
394 FASTQ.FORCE_INTERLEAVED=true;
395 FASTQ.TEST_INTERLEAVED=false;
396 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
397 }
398 }
399 }
400
401 //If the user explicitly used the word "null", change it to null.
402 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
403 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
404
405 //Ensure output files have no duplicates and can be written
406 //Unfortunately, this does not prevent patterns expanding into a matching string
407 if(!Tools.testOutputFiles(overwrite, append, false, outu1, outu2, stats)){
408 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2+", "+outu1+", "+outu2+", "+stats);
409 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+", "+outu1+", "+outu2+", "+stats+"\n");
410 }
411
412 //This does not prevent expansion into a matching string
413 assert(out1==null || (!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1))) : "Input file and output file have same name.";
414 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
415 }
416 }
417
418 private void processHeaderDelimiter() {
419 //For length-1 delimiters, use a char instead of a String
420 assert(column<0 || headerDelimiter!=null) : "Column may not be set if there is no delimiter.";
421 if(headerDelimiter!=null){
422 if(headerDelimiter.length()==1){
423 delimiterChar=headerDelimiter.charAt(0);
424 }else if(headerDelimiter.length()==2 && headerDelimiter.charAt(0)=='\\'){
425 delimiterChar=headerDelimiter.charAt(1);
426 }else{
427 delimiterChar=0;
428 }
429 delimiterPattern=Pattern.compile(headerDelimiter);
430 lp=new LineParserS2(delimiterChar);
431 }
432 }
433
434 /*--------------------------------------------------------------*/
435 /*---------------- Inner Methods ----------------*/
436 /*--------------------------------------------------------------*/
437
438 private HashMap<String, String> makeAssignmentMap() {
439 if(mapIn!=null) {return BarcodeCounter.loadAssignmentMap(mapIn);}
440
441 Timer t=new Timer();
442 final Collection<Barcode> counts;
443
444 System.err.print("Counting Barcodes:\t");
445 if(countsIn!=null) {counts=BarcodeCounter.loadCounts(countsIn, minCount0);}
446 else {
447 HashMap<String, Barcode> codeMap=BarcodeCounter.countBarcodes(ffin1, maxReads, PCRMatrix.byTile);
448 counts=codeMap.values();
449 if(countsOut!=null) {BarcodeCounter.writeCounts(counts, minCount0, countsOut, true, overwrite, append);}
450 }
451 if(legacyWriter!=null) {legacyWriter.counts=counts;}
452 t.stop("");
453 t.start();
454 final HashMap<String, String> map;
455
456 if(PCRMatrix.matrixType0==PCRMatrix.PROB_TYPE && PCRMatrixProb.clientside() &&
457 !setUseServer && !useServer) {
458 useServer=true;
459 }
460 if(useServer) {
461 System.err.println("Using client-server mode for barcode analysis.");
462 DemuxData dd=new DemuxData(barcodeLength1, barcodeLength2, barcodeDelimiter);
463 dd.codeCounts=counts;
464 dd.expectedList=expectedSet;
465 DemuxClient client=new DemuxClient();
466 map=client.getMap(dd, verboseClient);
467 if(mapOut!=null) {
468 PCRMatrix.printAssignmentMapStatic(map, mapOut, counts, overwrite, append);
469 }
470 }else {
471 PCRMatrix pcrMatrix=PCRMatrix.create(barcodeLength1, barcodeLength2, barcodeDelimiter);
472 assert(expectedSet!=null && !expectedSet.isEmpty());
473 pcrMatrix.populateExpected(expectedSet);
474 pcrMatrix.populateSplitCodes();
475 pcrMatrix.initializeData();
476 pcrMatrix.refine(counts, minCountR);
477 map=pcrMatrix.makeAssignmentMap(counts, minCountA);
478 if(mapOut!=null) {
479 pcrMatrix.printAssignmentMap(map, mapOut, counts, overwrite, append);
480 }
481 pcrMatrix=null;
482 }
483
484 if(barcodesOut!=null) {
485 ByteStreamWriter bsw=new ByteStreamWriter(barcodesOut, overwrite, append, true);
486 bsw.start();
487 ArrayList<Barcode> list=Barcode.summateAssignments(map, expectedSet, counts);
488 for(Barcode b : list) {
489 bsw.print(b.name).tab().print(b.frequency, 5).tab().print(b.count()).nl();
490 }
491 bsw.poisonAndWait();
492 }
493
494 t.stop("Assignment Time:\t\t");
495 // if(mapOut!=null) {BarcodeCounter.writeAssignmentMap(map, mapOut, overwrite, append);}
496
497 // map=filterAssignmentMap(map, outSubset);//Sends known things to unknown
498
499 return map;
500 }
501
502 private HashMap<String, String> filterAssignmentMap(HashMap<String, String> map, Set<String> set) {
503 if(map==null || set==null || map.isEmpty() || set.isEmpty()) {return map;}
504 HashMap<String, String> filtered=new HashMap<String, String>();
505 for(Entry<String, String> e : map.entrySet()) {
506 if(set.contains(e.getValue())) {
507 filtered.put(e.getKey(), e.getValue());
508 }
509 }
510 return filtered;
511 }
512
513 /**
514 * Primary method.
515 * Starts and stops I/O streams, processes the data, and prints results.
516 * @param t A timer that was already started.
517 */
518 void process(Timer t){
519
520 assignmentMap=makeAssignmentMap();
521
522 Timer t2=new Timer();
523
524 //Create stream for input reads
525 final ConcurrentReadInputStream cris=makeInputStream();
526
527 //Create streams for output reads other than unmatched
528 final BufferedMultiCros mcros=(nosplit ? null : makeMatchedOutputStream(cris.paired()));
529
530 //Create stream for unmatched output reads
531 //TODO: Consider adding this to mcros
532 final ConcurrentReadOutputStream rosu=makeUnmatchedOutputStream();
533
534 spikeMapper=(refPath==null || spikeLabel==null ? null :
535 new MicroAligner2(kSpike, minSpikeIdentity, refPath));
536 if(spikeMapper!=null) {spikeMapper.skipmask=skipMask;}//Only lookup some kmers for speed
537
538 //Streams are set up, so process the reads
539 processInner(cris, mcros, rosu);
540 //At this point processing has finished.
541
542 //Close streams
543 cleanup(cris, mcros, rosu);
544
545 t2.stop("Writing Time:\t\t\t");
546 t2.start();
547
548 //Report statistics to file
549 if(stats!=null){printReport(mcros);}
550
551 if(legacyPath!=null) {
552 LinkedHashMap<String, String> sampleMap=legacyWriter.loadSampleMap(sampleMapFile,
553 (byte)barcodeDelimiter, rcIndex1, rcIndex2);
554 if(legacyPath.equals(".")) {legacyPath="";}
555 if(legacyPath.length()>0 && !legacyPath.endsWith("/")) {
556 legacyPath+="/";
557 }
558
559 if(sampleMap==null || sampleMap.isEmpty()) {
560 System.err.println("Warning: sample map is empty; "
561 + "sample names will be absent in legacy files.");
562 }
563 legacyWriter.writeTopUnknownBarcodes(expectedSet, assignmentMap,
564 (byte)barcodeDelimiter,
565 legacyPath+"Top_Unknown_Barcodes.csv", lane, 1000, overwrite);
566 legacyWriter.writeQualityMetrics(expectedSet, sampleMap,
567 (byte)barcodeDelimiter, legacyPath+"Quality_Metrics.csv", lane, overwrite);
568 legacyWriter.writeDemultiplexStats(legacyPath+"Demultiplex_Stats.csv", assignmentMap,
569 expectedSet, sampleMap, lane, overwrite);
570 legacyWriter.writeIndexHoppingCounts(expectedSet, sampleMap, (byte)barcodeDelimiter,
571 legacyPath+"Index_Hopping_Counts.csv", lane, overwrite);
572 legacyWriter.writeDemultiplexTileStats(legacyPath+"Demultiplex_Tile_Stats.csv",
573 sampleMap, (sampleMap==null ? expectedSet : null), lane, (byte)barcodeDelimiter, overwrite);
574 }
575 if(stats!=null || legacyPath!=null) {
576 t2.stop("Stats Writing Time:\t\t");
577 }
578
579 if(spikeMapper!=null) {
580 System.err.println("Mapping Attempts:\t"+spikeMapper.mapCount);
581 System.err.println("Quick Aligns: \t"+spikeMapper.quickAligns);
582 System.err.println("Slow Aligns: \t"+spikeMapper.slowAligns);
583 System.err.println("Align Success: \t"+spikeMapper.metCutoff);
584 double avgId=spikeMapper.idSum/(Tools.max(spikeMapper.metCutoff,1));
585 System.err.println("Avg Identity: \t"+String.format("%.6f", avgId));
586 }
587
588 if(printRetireTime && mcros!=null) {
589 outstream.println("\n"+mcros.printRetireTime()+mcros.printCreateTime()+"\n");
590 }
591
592 //Stop the timer
593 t.stop();
594
595 //Print results
596 printResultsToScreen(t);
597
598 if(errorState){//Exit with a message and error code
599 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
600 }
601 }
602
603 /** Create and start the input stream (cris). */
604 private ConcurrentReadInputStream makeInputStream(){
605 //Stream for input reads
606 final ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, useSharedHeader, ffin1, ffin2);
607 if(verbose){outstream.println("Started cris");}
608 cris.start();
609
610 //Report whether the input is being processed as paired.
611 final boolean paired=cris.paired();
612 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
613 return cris;
614 }
615
616 /** Create and start the normal output streams (mcros). */
617 private BufferedMultiCros makeMatchedOutputStream(boolean pairedInput){
618 //Streams for output reads other than unmatched
619 final BufferedMultiCros mcros;
620 if(out1!=null){
621 mcros=BufferedMultiCros.make(out1, out2, overwrite, append,
622 true, useSharedHeader, FileFormat.FASTQ);
623
624 //Set mcros fields not available in constructor
625 mcros.minReadsToDump=minReadsToDump;
626 mcros.trackCardinality=trackCardinality;
627
628 //Report output format
629 if(pairedInput && out2==null && (in1==null || !ffin1.samOrBam())){
630 outstream.println("Writing interleaved.");
631 }
632
633 //Start the mcros thread if necessary
634 if(mcros.threaded){mcros.start();}
635 }else{
636 mcros=null;
637 }
638 return mcros;
639 }
640
641 /** Create and start the unmatched output stream (rosu). */
642 private ConcurrentReadOutputStream makeUnmatchedOutputStream(){
643 //Stream for unmatched output reads
644 final ConcurrentReadOutputStream rosu;
645 if(outu1!=null){
646 //Number of output buffers; does not need to be high since access is single-threaded
647 final int buff=4;
648
649 FileFormat ffout1=FileFormat.testOutput(outu1, FileFormat.FASTQ, extout, true, overwrite, append, false);
650 FileFormat ffout2=(outu2==null ? null : FileFormat.testOutput(outu2, FileFormat.FASTQ, extout, true, overwrite, append, false));
651 rosu=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, true);
652 rosu.start();
653 }else{
654 rosu=null;
655 }
656
657 return rosu;
658 }
659
660 /**
661 * Process all reads.
662 * @param cris Input stream (required).
663 * @param mcros Matched read output stream (optional).
664 * @param rosu Unmatched read output stream (optional).
665 */
666 private void processInner(final ConcurrentReadInputStream cris, final BufferedMultiCros mcros, final ConcurrentReadOutputStream rosu) {
667
668 //Fetch the first list
669 ListNum<Read> ln=cris.nextList();
670 ArrayList<Read> reads=(ln!=null ? ln.list : null);
671
672 //Ensure pairing seems correct
673 if(reads!=null && !reads.isEmpty()){
674 Read r=reads.get(0);
675 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
676 }
677
678 //While there are more reads to process...
679 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
680
681 //List to accumulate unmatched reads
682 ArrayList<Read> unmatched=new ArrayList<Read>();
683
684 //For each read...
685 for(Read r : reads){
686
687 //Get the target file identifier
688 String name=getValue(r);
689 final int pairCount=r.pairCount(), pairLen=r.pairLength();
690 if(legacyWriter!=null) {
691 r.obj=name;
692 legacyWriter.add(r, name);
693 legacyWriter.add(r.mate, name);
694 }
695 if(name!=null){
696 //Set the name so that the mcros will send it to the right place
697 if(outSubset==null || outSubset.contains(name)) {
698 r.obj=(symbolRemap==null ? name : Tools.remap(symbolRemap, name));
699 readsOut+=pairCount;
700 basesOut+=pairLen;
701 }
702 }else{
703 //Send it to unmatched
704 unmatched.add(r);
705 readsUnmatched+=pairCount;
706 basesUnmatched+=pairLen;
707 }
708 if(rename) {rename(r, name);}
709
710 readsProcessed+=pairCount;
711 basesProcessed+=pairLen;
712 }
713 if(rosu!=null){rosu.add(nosplit ? reads : unmatched, ln.id);}//Send unmatched reads to rosu
714 if(mcros!=null){mcros.add(reads);}//Send matched reads to mcros
715
716 //Notify the input stream that the list has been processed
717 cris.returnList(ln);
718
719 //Fetch a new list
720 ln=cris.nextList();
721 reads=(ln!=null ? ln.list : null);
722 }
723
724 //Notify the input stream that this thread is done processing
725 if(ln!=null){
726 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
727 }
728 }
729
730 private void rename(Read r, String name) {
731 if(name==null) {name="UNKNOWN";}
732 r.id=r.id+"\t"+name;
733 if(r.mate!=null) {r.mate.id=r.mate.id+"\t"+name;}
734 }
735
736 /**
737 * Finish writing and close streams.
738 * @param cris Input stream (required).
739 * @param mcros Matched read output stream (optional).
740 * @param rosu Unmatched read output stream (optional).
741 */
742 private void cleanup(final ConcurrentReadInputStream cris, final BufferedMultiCros mcros,
743 final ConcurrentReadOutputStream rosu){
744
745 //Shut down mcros
746 if(mcros!=null){
747 mcros.close();
748 errorState|=mcros.errorState();
749 }
750
751 if(minReadsToDump>0 && mcros!=null){
752 //Dump the residual reads into the unmatched file
753 mcros.dumpResidual(rosu);
754
755 //Adjust statistics to reflect that residuals did not get demultiplexed
756 readsOut-=mcros.residualReads;
757 basesOut-=mcros.residualBases;
758 }
759
760 if(mcros!=null && writeEmptyFiles) {
761 Set<String> observed=mcros.getKeys();
762 for(String expected : expectedSet) {
763 String key=(symbolRemap==null ? expected : Tools.remap(symbolRemap, expected));
764 if(!observed.contains(key)) {
765
766 String s1=out1.replaceFirst("%", key);
767 String s2=out2==null ? null : out2.replaceFirst("%", key);
768 ReadWrite.writeString("", s1, overwrite, false);
769 if(s2!=null) {ReadWrite.writeString("", s2, overwrite, false);}
770 }
771 }
772 }
773
774 //errorState|=ReadStats.writeAll(); //Currently unused; allows tracking statistics.
775
776 //Shut down normal streams
777 errorState|=ReadWrite.closeStreams(cris, rosu);
778 }
779
780 /**
781 * @param t A Timer that has already been stopped
782 */
783 private void printResultsToScreen(Timer t) {
784 //Report statistics to screen
785 double rpnano=readsProcessed/(double)(t.elapsed);
786 double bpnano=basesProcessed/(double)(t.elapsed);
787
788 outstream.println("Time: "+t);
789 outstream.println("Reads Processed: "+readsProcessed+" \t"+Tools.format("%.2fk reads/sec", rpnano*1000000));
790 outstream.println("Bases Processed: "+basesProcessed+" \t"+Tools.format("%.2fm bases/sec", bpnano*1000));
791 outstream.println("Reads Out: "+readsOut);
792 outstream.println("Bases Out: "+basesOut);
793 outstream.println("Yield: "+String.format("%.5f", readsOut*1.0/readsProcessed));
794 }
795
796 /*--------------------------------------------------------------*/
797 /*---------------- Helper Methods ----------------*/
798 /*--------------------------------------------------------------*/
799
800 /** Returns the value this read maps to; meaning, the variable part of the output filename */
801 private String getValue(Read r){
802 String key=getKey(r);
803 // assert(key==null) : key;
804 // if(verbose){System.err.println("Got key "+key);}
805 String value=(key==null ? null : assignmentMap.get(key));
806 //Note - generally... unexpected are not in the assignment map anyway.
807 if(spikeMapper!=null && (mapAllToSpike || value==null ||
808 (mapUnexpectedToSpike && !expectedSet.contains(value)))) {
809 float id=spikeMapper.map(r);
810 if(id>=minSpikeIdentity) {value=spikeLabel;}
811 }
812 return value;
813 }
814
815 /** Generates a key from the read header */
816 private String getKey(Read r){
817 final String id=r.id;
818 final int idlen=id.length();
819 final String key;
820
821 //Simplest case; every header is its own key
822 if(mode==HEADER_MODE){return id;}
823
824 //Parse the barcode
825 if(mode==BARCODE_MODE){
826 ihp.parse(id);
827 String bc=ihp.barcode();
828 return PCRMatrix.byTile ? bc+ihp.tile() : bc;
829 }
830
831 //Return a prefix or suffix
832 if(mode==PREFIX_MODE || mode==SUFFIX_MODE){
833 assert(fixedLength>0);
834 key=(id.length()<=fixedLength ? id : mode==PREFIX_MODE ?
835 id.substring(0, fixedLength) : id.substring(idlen-fixedLength));
836 return key;
837 }
838
839 //Return a delimited substring
840 if(mode==DELIMITER_MODE){
841
842 if(delimiterChar>0){//Use LineParser
843 lp.set(id);
844 // int col=Tools.min(column, lp.terms()-1); //TODO: Make LineParserS
845 key=lp.parseString(column);
846 }else{//Use a split operation, which is slow
847 String[] split=delimiterPattern.split(id);//Faster; uses a precompiled pattern
848 assert(split.length>1) : "Delimiter '"+headerDelimiter+"' was not found in name '"+id+"'";
849
850 int col=Tools.min(column, split.length-1);
851 key=split[col];
852 if(col!=column && !warned){
853 outstream.println("*** WARNING! ***\n"
854 + "Only "+(col+1)+" columns for record "+id+"\n"
855 + "Further warnings will be suppressed.\n");
856 warned=true;
857 assert(errorState=true); //Change error state to true if assertions are enabled.
858 }
859 }
860 return key;
861 }
862
863 throw new RuntimeException("No mode is being used: "+mode); //Should be unreachable
864 }
865
866 /**
867 * Print statistics about demultiplexing to a file.
868 * @param mcros Output stream, after processing is completely finished.
869 */
870 void printReport(BufferedMultiCros mcros){
871 if(stats==null){return;}
872
873 //Make a writer for the stats file
874 ByteStreamWriter bsw=new ByteStreamWriter(stats, overwrite, append, true);
875 bsw.start();
876
877 {
878 ByteBuilder bb=new ByteBuilder();
879
880 //Print the header
881 bb.append("#ReadsIn\t").append(readsProcessed).nl();
882 bb.append("#BasesIn\t").append(basesProcessed).nl();
883 bb.append("#ReadsOut\t").append(readsOut).nl();
884 bb.append("#BasesOut\t").append(basesOut).nl();
885 bb.append("#Name\tReads\tBases"+(trackCardinality ? "\tCardinality" : "")+"\n");
886
887 //Print results of unmatched reads, which is not captured by the mcros
888 if(assignmentMap!=null && !assignmentMap.isEmpty()){
889 bb.append("Unmatched\t").append(readsUnmatched).tab().append(basesUnmatched).nl();
890 }
891 bsw.print(bb);
892 }
893
894 if(mcros!=null){//Print results from the mcros
895 ByteBuilder bb=mcros.report();
896 bsw.print(bb);
897 }
898
899 //Finish writing
900 bsw.poisonAndWait();
901 }
902
903 /*--------------------------------------------------------------*/
904 /*---------------- Fields ----------------*/
905 /*--------------------------------------------------------------*/
906
907 /** Primary input file */
908 private String in1=null;
909 /** Optional input file for read 2 of paired reads in twin files */
910 private String in2=null;
911
912 /** Output file pattern 1 */
913 private String out1=null;
914 /** Output file pattern 2 */
915 private String out2=null;
916
917 /** Unmatched read output file 1 */
918 private String outu1=null;
919 /** Unmatched read output file 2 */
920 private String outu2=null;
921
922 /** File extension override for input files */
923 private String extin=null;
924 /** File extension override for output files */
925 private String extout=null;
926
927 /** Pre-counted barcodes */
928 private String countsIn=null;
929 /** Output for barcode counts */
930 private String countsOut=null;
931
932 /** Output for barcode assignment counts */
933 private String barcodesOut=null;
934
935 private boolean rename=false;
936 private boolean nosplit=false;
937
938 /**
939 * Ignore barcodes occuring fewer times than this.
940 * Saves memory and speeds processing. */
941 private long minCount0=0;
942
943 /** Use stricter cutoffs during refinement for barcodes with lower count. */
944 private long minCountR=4;
945
946 /** Use stricter cutoffs during assignment for barcodes with lower count. */
947 private long minCountA=4;
948
949 /** Premade assignment map */
950 private String mapIn=null;
951 /** Assignment map output */
952 private String mapOut=null;
953
954 private boolean useServer=false;
955 private boolean setUseServer=false;
956
957 //This is for a spike-in like PhiX
958 private String spikeLabel=null;
959 private String refPath="phix";
960 private MicroAligner2 spikeMapper;
961 private int kSpike=27;
962 private int skipMask=3;
963 float minSpikeIdentity=0.7f;
964 boolean mapUnexpectedToSpike=false;
965 boolean mapAllToSpike=false;
966
967 /*--------------------------------------------------------------*/
968
969 /** Primary input file */
970 private final FileFormat ffin1;
971
972 /** Read 2 input file */
973 private final FileFormat ffin2;
974
975 /*--------------------------------------------------------------*/
976
977 /** Input reads */
978 long readsProcessed=0;
979 long basesProcessed=0;
980
981 /** Demultiplexed output reads */
982 long readsOut=0;
983 long basesOut=0;
984
985 /** Output reads that did not get demultiplexed */
986 long readsUnmatched=0;
987 long basesUnmatched=0;
988
989 /** Stop after this many input reads */
990 private long maxReads=-1;
991
992 /** File to print number of reads sent to each output file */
993 private String stats=null;
994
995 /** For splitting headers on a symbol */
996 private String headerDelimiter=null;
997
998 /** For splitting headers faster if the delimiter is just one character */
999 private char delimiterChar=0;
1000
1001 private LineParserS2 lp=null;
1002
1003 /** Precompiled pattern matching the delimiter */
1004 private Pattern delimiterPattern=null;
1005
1006 /** For replacing symbols in the filename */
1007 private byte[] symbolRemap=null;
1008
1009 /** If there is a delimiter, use this column after splitting.
1010 * Column is 1-based for parsing parameters but 0-based internally. */
1011 private int column=-1;
1012
1013 /** How to select a read's key; see static modes array */
1014 private int mode=BARCODE_MODE;
1015
1016 /** Track per-output-file cardinality; may be slow */
1017 private boolean trackCardinality=false;
1018
1019 /** Prevents issuing warnings multiple times */
1020 private boolean warned=false;
1021
1022 private boolean printRetireTime=false;
1023
1024 /**
1025 * Do not create files with under this many reads.
1026 * Increases memory usage since reads must be retained until processing is finished.
1027 * Upon running out of memory the program may go very slowly.
1028 */
1029 private long minReadsToDump=0;
1030
1031 /** Affix length if fixed */
1032 private int fixedLength=-1;
1033
1034 /**
1035 * A set of recognized names and the output names they map to.
1036 * The keys and values will be identical unless a Hamming distance is used.
1037 * This is only filled if explicit names are provided.
1038 */
1039 private HashMap<String, String> assignmentMap=null;//new HashMap<String, String>();
1040
1041 private LinkedHashSet<String> expectedSet=null;
1042 private LinkedHashSet<String> outSubset=null;
1043
1044 /** Whether input file interleaving was explicitly set */
1045 private boolean setInterleaved=false;
1046
1047 private IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
1048
1049 //Legacy file stuff
1050 // final ReadStats readstats;
1051 private int lane=0;
1052 private String legacyPath;
1053 private String sampleMapFile;
1054 private final LegacyFileWriter legacyWriter;
1055
1056 /*--------------------------------------------------------------*/
1057
1058 private int barcodeDelimiter=0;
1059 private int barcodeLength1=0;
1060 private int barcodeLength2=0;
1061 private boolean rcIndex1=false;
1062 private boolean rcIndex2=false;
1063
1064 /*--------------------------------------------------------------*/
1065
1066 /** Print messages here */
1067 private PrintStream outstream=System.err;
1068
1069 /** True if errors were encountered */
1070 public boolean errorState=false;
1071
1072 /** Create empty files for barcodes that are expected but absent. */
1073 private boolean writeEmptyFiles=true;
1074
1075 /** Permission to overwrite existing files. */
1076 private boolean overwrite=true;
1077
1078 /**
1079 * Append to existing files rather than overwriting.
1080 * It is not advisable to set this flag for this class.
1081 * */
1082 private boolean append=false;
1083
1084 /** Retain header of sam/bam files. */
1085 private boolean useSharedHeader=false;
1086
1087 /*--------------------------------------------------------------*/
1088 /*---------------- Static Fields ----------------*/
1089 /*--------------------------------------------------------------*/
1090
1091 /** Operation mode for selection of key */
1092 public static final int BARCODE_MODE=1, PREFIX_MODE=2, SUFFIX_MODE=3, DELIMITER_MODE=4, HEADER_MODE=5;
1093
1094 private static final String empty="";
1095
1096 /** Verbose messages for debugging */
1097 public static boolean verbose=false;
1098 public static boolean verboseClient=true;
1099
1100 public static boolean statsOnly=false;
1101
1102 }