Debian Codegraph @

current/jgi/DemuxByName.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.HashMap;
9 import java.util.HashSet;
10
11 import fileIO.ByteFile;
12 import fileIO.ByteFile1;
13 import fileIO.ByteFile2;
14 import fileIO.FileFormat;
15 import fileIO.ReadWrite;
16 import fileIO.TextFile;
17 import shared.Parse;
18 import shared.Parser;
19 import shared.PreParser;
20 import shared.Shared;
21 import shared.Timer;
22 import shared.Tools;
23 import stream.ArrayListSet;
24 import stream.ConcurrentGenericReadInputStream;
25 import stream.ConcurrentReadInputStream;
26 import stream.ConcurrentReadOutputStream;
27 import stream.FASTQ;
28 import stream.FastaReadInputStream;
29 import stream.MultiCros;
30 import stream.Read;
31 import structures.ListNum;
32 import tracker.ReadStats;
33
34
35 /**
36 * @author Brian Bushnell
37 * @date Oct 9, 2014
38 *
39 */
40 public class DemuxByName {
41
42 public static void main(String[] args){
43
44 final int oldCap=Shared.numBuffers(), oldZipThreads=ReadWrite.MAX_ZIP_THREADS(), oldZl=ReadWrite.ZIPLEVEL;
45 final boolean oldPigz=ReadWrite.USE_PIGZ, oldUnpigz=ReadWrite.USE_UNPIGZ;
46
47 Timer t=new Timer();
48 DemuxByName x=new DemuxByName(args);
49 x.process(t);
50
51 Shared.setBuffers(oldCap);
52 ReadWrite.ZIPLEVEL=oldZl;
53 ReadWrite.USE_PIGZ=oldPigz;
54 ReadWrite.USE_UNPIGZ=oldUnpigz;
55 ReadWrite.setZipThreads(oldZipThreads);
56
57 //Close the print stream if it was redirected
58 Shared.closeStream(x.outstream);
59 }
60
61 public DemuxByName(String[] args){
62
63 {//Preparse block for help, config files, and outstream
64 PreParser pp=new PreParser(args, getClass(), false);
65 args=pp.args;
66 outstream=pp.outstream;
67 }
68
69 boolean setInterleaved=false; //Whether it was explicitly set.
70
71 Shared.capBuffers(4);
72 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
73 ReadWrite.setZipThreads(Shared.threads());
74 ReadWrite.ZIPLEVEL=1;
75
76
77 Parser parser=new Parser();
78 for(int i=0; i<args.length; i++){
79 String arg=args[i];
80 String[] split=arg.split("=");
81 String a=split[0].toLowerCase();
82 String b=split.length>1 ? split[1] : null;
83
84 if(parser.parse(arg, a, b)){
85 //do nothing
86 }else if(a.equals("verbose")){
87 verbose=Parse.parseBoolean(b);
88 ByteFile1.verbose=verbose;
89 ByteFile2.verbose=verbose;
90 stream.FastaReadInputStream.verbose=verbose;
91 ConcurrentGenericReadInputStream.verbose=verbose;
92 stream.FastqReadInputStream.verbose=verbose;
93 ReadWrite.verbose=verbose;
94 }else if(a.equals("names") || a.equals("name") || a.equals("affixes")){
95 if(b!=null){
96 String[] x=b.split(",");
97 for(String s : x){
98 names.add(s);
99 }
100 }
101 }else if(a.equalsIgnoreCase("length") || a.equalsIgnoreCase("len") || a.equalsIgnoreCase("affixlength") || a.equalsIgnoreCase("affixlen")){
102 fixedAffixLength=Integer.parseInt(b);
103 }else if(a.equals("prefixmode") || a.equals("prefix") || a.equals("pm")){
104 prefixMode=Parse.parseBoolean(b);
105 }else if(a.equals("suffixmode") || a.equals("suffix") || a.equals("sm")){
106 prefixMode=!Parse.parseBoolean(b);
107 }else if(a.equals("column")){
108 column=Integer.parseInt(b);
109 assert(column>0 || column==-1) : "Column is 1-based; must be 1+ or else -1 to disable.";
110 column--;
111 }else if(a.equals("substringmode") || a.equals("substring")){
112 substringMode=Parse.parseBoolean(b);
113 }else if(a.equals("outu") || a.equals("outu1")){
114 outu1=b;
115 }else if(a.equals("outu2")){
116 outu2=b;
117 }else if(a.equals("perheader") || a.equals("persequence") || a.equals("pername")){
118 perheader=Parse.parseBoolean(b);
119 }else if(a.equals("delimiter")){
120 delimiter=Parse.parseSymbol(b);
121 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
122 parser.in1=arg;
123 }else{
124 outstream.println("Unknown parameter "+args[i]);
125 assert(false) : "Unknown parameter "+args[i];
126 // throw new RuntimeException("Unknown parameter "+args[i]);
127 }
128 }
129
130 if(perheader){
131 ReadWrite.USE_PIGZ=false;
132 }else{
133 String[] x=names.toArray(new String[names.size()]);
134 names.clear();
135 for(String s : x){
136 File f=new File(s);
137 if(f.exists() && f.isFile()){
138 TextFile tf=new TextFile(s);
139 String[] lines=tf.toStringLines();
140 for(String s2 : lines){
141 names.add(s2);
142 }
143 }else{
144 names.add(s);
145 }
146 }
147
148 // for(String s : names){
149 // assert(affixLen<0 || affixLen==s.length()) : "All names must have the same length.";
150 // affixLen=s.length();
151 // }
152 // assert(affixLen>0) : "Must include at least one non-zero-length affix (name).";
153
154 {
155 BitSet bs=new BitSet();
156 if(fixedAffixLength>0){
157 bs.set(fixedAffixLength);
158 }
159 for(String s : names){
160 bs.set(s.length());
161 }
162 affixLengths=new int[bs.cardinality()];
163 for(int i=0, bit=-1; i<affixLengths.length; i++){
164 bit=bs.nextSetBit(bit+1);
165 affixLengths[i]=bit;
166 }
167 Arrays.sort(affixLengths);
168 Tools.reverseInPlace(affixLengths);
169 }
170
171 assert((affixLengths.length>0 && affixLengths[0]>0) || delimiter!=null || perheader) :
172 "Must include at least one non-zero-length affix (name), or a delimiter.";
173 ReadWrite.setZipThreads(Tools.max(1, Tools.min(ReadWrite.MAX_ZIP_THREADS(), (Shared.threads()*2-1)/Tools.max(1, names.size()))));
174 if(names.size()>8){ReadWrite.USE_PIGZ=false;}
175 }
176
177 {//Process parser fields
178 Parser.processQuality();
179
180 maxReads=parser.maxReads;
181
182 overwrite=ReadStats.overwrite=parser.overwrite;
183 append=ReadStats.append=parser.append;
184
185 setInterleaved=parser.setInterleaved;
186
187 in1=parser.in1;
188 in2=parser.in2;
189 qfin1=parser.qfin1;
190 qfin2=parser.qfin2;
191
192 out1=parser.out1;
193 out2=parser.out2;
194 qfout1=parser.qfout1;
195 qfout2=parser.qfout2;
196
197 extin=parser.extin;
198 extout=parser.extout;
199 }
200
201 assert(out1==null || out1.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
202 assert(out2==null || out2.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
203 assert(qfout1==null || qfout1.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
204 assert(qfout2==null || qfout2.contains("%")) : "Output filename must contain '%' symbol, which will be replaced by affix.";
205
206 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
207 in2=in1.replace("#", "2");
208 in1=in1.replace("#", "1");
209 }
210 if(out1!=null && out2==null && out1.indexOf('#')>-1){
211 out2=out1.replace("#", "2");
212 out1=out1.replace("#", "1");
213 }
214 if(outu1!=null && outu2==null && outu1.indexOf('#')>-1){
215 outu2=outu1.replace("#", "2");
216 outu1=outu1.replace("#", "1");
217 }
218 if(in2!=null){
219 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
220 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
221 }
222
223 assert(FastaReadInputStream.settingsOK());
224
225 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
226 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
227 ByteFile.FORCE_MODE_BF2=true;
228 }
229
230 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
231
232 if(!setInterleaved){
233 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
234 if(in2!=null){ //If there are 2 input streams.
235 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
236 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
237 }else{ //There is one input stream.
238 if(out2!=null){
239 FASTQ.FORCE_INTERLEAVED=true;
240 FASTQ.TEST_INTERLEAVED=false;
241 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
242 }
243 }
244 }
245
246 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
247 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
248
249 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, outu1, outu2)){
250 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2+", "+outu1+", "+outu2);
251 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+", "+outu1+", "+outu2+"\n");
252 }
253
254 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
255 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
256
257 if(ffin1!=null && out1!=null && ffin1.samOrBam()){
258 useSharedHeader=FileFormat.isSamOrBamFile(out1);
259 }
260
261 if(perheader){
262 fixedAffixLength=-1;
263 substringMode=false;
264 affixLengths=null;
265 delimiter=null;
266 }
267 }
268
269 void process(Timer t){
270
271
272 final ConcurrentReadInputStream cris;
273 {
274 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, useSharedHeader, ffin1, ffin2, qfin1, qfin2);
275 if(verbose){outstream.println("Started cris");}
276 cris.start(); //4567
277 }
278 boolean paired=cris.paired();
279 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
280
281 final MultiCros mcros;
282 if(out1!=null){
283 final int buff=4;
284
285 mcros=(fixedAffixLength>0 || delimiter!=null || perheader ?
286 new MultiCros(out1, out2, false, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, buff) : null);
287
288 if(paired && out2==null && (in1==null || !in1.contains(".sam"))){
289 outstream.println("Writing interleaved.");
290 }
291
292 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
293 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
294
295 for(String s : names){
296
297 String qf1=null, qf2=null;
298 if(qfout1!=null){qf1=qfout1.replace("%", s);}
299 if(qfout2!=null){qf2=qfout2.replace("%", s);}
300
301 FileFormat ffout1=FileFormat.testOutput(out1.replace("%", s), FileFormat.FASTQ, extout, true, overwrite, append, false);
302 FileFormat ffout2=(out2==null ? null : FileFormat.testOutput(out2.replace("%", s), FileFormat.FASTQ, extout, true, overwrite, append, false));
303 ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qf1, qf2, buff, null, true);
304 ros.start();
305 nameToStream.put(s, ros);
306 }
307 }else{
308 mcros=null;
309 }
310
311 final ConcurrentReadOutputStream rosu;
312 if(outu1!=null){
313 final int buff=4;
314
315 FileFormat ffout1=FileFormat.testOutput(outu1, FileFormat.FASTQ, extout, true, overwrite, append, false);
316 FileFormat ffout2=(outu2==null ? null : FileFormat.testOutput(outu2, FileFormat.FASTQ, extout, true, overwrite, append, false));
317 rosu=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, true);
318 rosu.start();
319 }else{
320 rosu=null;
321 }
322
323 long readsProcessed=0;
324 long basesProcessed=0;
325
326 long readsOut=0;
327 long basesOut=0;
328
329 {
330
331 ListNum<Read> ln=cris.nextList();
332 ArrayList<Read> reads=(ln!=null ? ln.list : null);
333
334 // outstream.println("Fetched "+reads);
335
336 if(reads!=null && !reads.isEmpty()){
337 Read r=reads.get(0);
338 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
339 }
340
341 for(String s : names){
342 nameToArray.put(s, new ArrayList<Read>());
343 }
344 final ArrayListSet als=(fixedAffixLength<1 && delimiter==null && !perheader ? null : new ArrayListSet(false));
345
346 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
347
348 ArrayList<Read> unmatched=new ArrayList<Read>();
349 for(int idx=0; idx<reads.size(); idx++){
350 final Read r1=reads.get(idx);
351 final Read r2=r1.mate;
352
353 final int initialLength1=r1.length();
354 final int initialLength2=(r1.mateLength());
355
356 final String id=r1.id;
357 final int idlen=id.length();
358
359 ArrayList<Read> al2=null;
360 if(names.size()>0){
361 if(substringMode){
362 for(String s : names){
363 if(id.contains(s)){
364 al2=nameToArray.get(s);
365 break;
366 }
367 }
368 }else{
369 for(int affixLen : affixLengths){
370 final String sub=idlen>=affixLen ? prefixMode ? id.substring(0, affixLen) : id.substring(idlen-affixLen) : id;
371 al2=nameToArray.get(sub);
372 if(al2!=null){break;}
373 }
374 }
375 }
376
377 if(al2!=null || als!=null){
378 readsOut++;
379 basesOut+=initialLength1;
380 if(r2!=null){
381 readsOut++;
382 basesOut+=initialLength2;
383 }
384
385 if(al2!=null){
386 al2.add(r1);
387 {
388 readsOut++;
389 basesOut+=initialLength1;
390 }
391 if(r2!=null){
392 readsOut++;
393 basesOut+=initialLength2;
394 }
395 }else if(als!=null){
396 String sub=r1.id;
397 if(fixedAffixLength>0){
398 sub=(sub.length()<=fixedAffixLength ? sub : prefixMode ? id.substring(0, fixedAffixLength) : id.substring(idlen-fixedAffixLength));
399 }else if(delimiter!=null) {
400 String[] split=sub.split(delimiter);
401 assert(split.length>1) : "Delimiter '"+delimiter+"' was not found in name '"+sub+"'";
402 if(column>-1){
403 int col=Tools.min(column, split.length-1);
404 sub=split[col];
405 if(col!=column && !warned){
406 System.err.println("*** WARNING! ***\n"
407 + "Only "+(col+1)+" columns for record "+r1.id+"\n"
408 + "Further warnings will be suppressed.\n");
409 warned=true;
410 assert(errorState=true); //Change error state to true if assertions are enabled.
411 }
412 }else{
413 sub=split[prefixMode ? 0 : split.length-1];
414 }
415 }else{
416 assert(perheader);
417 //Use the full ID
418 }
419 als.add(r1, sub);
420 }
421
422 }else{
423 unmatched.add(r1);
424 }
425 {
426 readsProcessed++;
427 basesProcessed+=initialLength1;
428 }
429 if(r2!=null){
430 readsProcessed++;
431 basesProcessed+=initialLength2;
432 }
433 }
434
435 for(String s : names){
436 ArrayList<Read> listOut=nameToArray.put(s, new ArrayList<Read>());
437 ConcurrentReadOutputStream ros=nameToStream.get(s);
438 if(ros!=null){ros.add(listOut, ln.id);}
439 }
440 if(mcros!=null && als!=null){
441 if(als.size()+names.size()>8){ReadWrite.USE_PIGZ=false;}
442 mcros.add(als, ln.id);
443 }
444 if(rosu!=null){rosu.add(unmatched, ln.id);}
445
446 cris.returnList(ln);
447 ln=cris.nextList();
448 reads=(ln!=null ? ln.list : null);
449 }
450 if(ln!=null){
451 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
452 }
453 }
454
455 errorState|=ReadStats.writeAll();
456
457 errorState|=ReadWrite.closeStream(cris);
458
459 for(String s : names){
460 ConcurrentReadOutputStream ros=nameToStream.get(s);
461 errorState|=ReadWrite.closeStream(ros);
462 }
463
464 if(mcros!=null){
465 errorState|=ReadWrite.closeStreams(mcros);
466 }
467
468 t.stop();
469
470 double rpnano=readsProcessed/(double)(t.elapsed);
471 double bpnano=basesProcessed/(double)(t.elapsed);
472
473 outstream.println("Time: "+t);
474 outstream.println("Reads Processed: "+readsProcessed+" \t"+Tools.format("%.2fk reads/sec", rpnano*1000000));
475 outstream.println("Bases Processed: "+basesProcessed+" \t"+Tools.format("%.2fm bases/sec", bpnano*1000));
476 outstream.println("Reads Out: "+readsOut);
477 outstream.println("Bases Out: "+basesOut);
478
479 if(errorState){
480 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
481 }
482 }
483
484 /*--------------------------------------------------------------*/
485
486 /*--------------------------------------------------------------*/
487
488 private String in1=null;
489 private String in2=null;
490
491 private String qfin1=null;
492 private String qfin2=null;
493
494 private String out1=null;
495 private String out2=null;
496
497 private String outu1=null;
498 private String outu2=null;
499
500 private String qfout1=null;
501 private String qfout2=null;
502
503 private String extin=null;
504 private String extout=null;
505
506 /*--------------------------------------------------------------*/
507
508 private long maxReads=-1;
509 // private boolean exclude=true;
510
511 private String delimiter=null;
512 private boolean prefixMode=true;
513 private boolean substringMode=false;
514 private boolean perheader=false;
515 private int column=-1;
516 private boolean warned=false;
517 // private int affixLen=-1;
518
519 private int fixedAffixLength=-1;
520
521 private int[] affixLengths;
522
523 private HashSet<String> names=new HashSet<String>();
524 private HashMap<String, ArrayList<Read>> nameToArray=new HashMap<String, ArrayList<Read>>();
525 private HashMap<String, ConcurrentReadOutputStream> nameToStream=new HashMap<String, ConcurrentReadOutputStream>();
526
527 /*--------------------------------------------------------------*/
528
529 private final FileFormat ffin1;
530 private final FileFormat ffin2;
531
532
533 /*--------------------------------------------------------------*/
534
535 private PrintStream outstream=System.err;
536 public static boolean verbose=false;
537 public boolean errorState=false;
538 private boolean overwrite=true;
539 private boolean append=false;
540 private boolean useSharedHeader=false;
541
542 }