Debian Codegraph @

current/stream/MultiCros3.java

raw symbols SCIP
1 package stream;
2
3 import java.util.ArrayDeque;
4 import java.util.ArrayList;
5 import java.util.LinkedHashMap;
6 import java.util.Map.Entry;
7 import java.util.Set;
8
9 import cardinality.CardinalityTracker;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import shared.KillSwitch;
13 import shared.Shared;
14 import shared.Tools;
15 import structures.ByteBuilder;
16 import structures.ListNum;
17
18 /**
19 * This implementation allows multiple concurrent open streams.
20 *
21 * @author Brian Bushnell
22 * @date May 14, 2019
23 *
24 */
25 public class MultiCros3 extends BufferedMultiCros {
26
27 /**
28 * For testing.<br>
29 * args should be:
30 * {input file, output pattern, names...}
31 */
32 public static void main(String[] args){
33
34 //Do some basic parsing
35 String in=args[0];
36 String pattern=args[1];
37 ArrayList<String> names=new ArrayList<String>();
38 for(int i=2; i<args.length; i++){names.add(args[i]);}
39
40 //Create an mcros for this pattern
41 MultiCros3 mcros=new MultiCros3(pattern, null, false, false, false, false, FileFormat.FASTQ, false, 4);
42
43 //Create the input stream
44 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(-1, true, false, in);
45 cris.start();
46
47 //Fetch the first list
48 ListNum<Read> ln=cris.nextList();
49 ArrayList<Read> reads=(ln!=null ? ln.list : null);
50
51 //Process all remaining lists
52 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
53
54 //Add the reads by barcode
55 for(Read r1 : reads){
56 mcros.add(r1, r1.barcode(true));
57 }
58
59 //Return the old list and get a new one
60 cris.returnList(ln);
61 ln=cris.nextList();
62 reads=(ln!=null ? ln.list : null);
63 }
64
65 //Close the streams
66 cris.returnList(ln);
67 ReadWrite.closeStreams(cris);
68 mcros.close();
69 }
70
71 /*--------------------------------------------------------------*/
72 /*---------------- Initialization ----------------*/
73 /*--------------------------------------------------------------*/
74
75 /** @See Details in superclass constructor */
76 public MultiCros3(String pattern1_, String pattern2_,
77 boolean overwrite_, boolean append_, boolean allowSubprocess_, boolean useSharedHeader_, int defaultFormat_, boolean threaded_, int maxStreams_){
78 super(pattern1_, pattern2_, overwrite_, append_, allowSubprocess_, useSharedHeader_, defaultFormat_, threaded_, maxStreams_);
79
80 bufferMap=new LinkedHashMap<String, Buffer>();
81 streamQueue=new ArrayDeque<String>(maxStreams);
82 }
83
84 /*--------------------------------------------------------------*/
85 /*---------------- Outer Methods ----------------*/
86 /*--------------------------------------------------------------*/
87
88 @Override
89 public boolean finishedSuccessfully(){
90 return !errorState;
91 }
92
93 @Override
94 public void add(Read r, String name){
95 Buffer b=bufferMap.get(name);
96 if(b==null){
97 b=new Buffer(name);
98 bufferMap.put(name, b);
99 //Note: I could adjust bytesPerBuffer threshold here in response to the number of buffers.
100 }
101 b.add(r);
102 }
103
104 @Override
105 public long dumpResidual(ConcurrentReadOutputStream rosu){
106 //For each Buffer, check if it contains residual reads
107 //If so, dump it into the stream
108 for(Entry<String, Buffer> e : bufferMap.entrySet()){
109 Buffer b=e.getValue();
110 assert((b.readsIn<minReadsToDump) == (b.list!=null && !b.list.isEmpty()));
111 if(b.readsIn>0 && b.readsIn<minReadsToDump){
112 assert(b.list!=null && !b.list.isEmpty());
113 residualReads+=b.readsIn;
114 residualBases+=b.basesIn;
115 if(rosu!=null){rosu.add(b.list, 0);}
116 }
117 b.list=null;
118 }
119 return residualReads;
120 }
121
122 @Override
123 public ByteBuilder report(){
124 ByteBuilder bb=new ByteBuilder(1024);
125
126 //Add a line for residual reads dumped
127 if(minReadsToDump>0){
128 bb.append("Residual").tab().append(residualReads).tab().append(residualBases).nl();
129 }
130
131 //Add a line for each Buffer
132 for(Entry<String, Buffer> e : bufferMap.entrySet()){
133 Buffer buffer=e.getValue();
134 if(buffer.numDumps>0){//Only add a line if this Buffer actually created a file
135 buffer.appendTo(bb);
136 }
137 }
138 return bb;
139 }
140
141 @Override
142 public Set<String> getKeys(){return bufferMap.keySet();}
143
144 /*--------------------------------------------------------------*/
145 /*---------------- Inner Methods ----------------*/
146 /*--------------------------------------------------------------*/
147
148 @Override
149 long closeInner() {
150 //First dump everything
151 final long x=dumpAll();
152 //Then, retire any active streams
153 while(!streamQueue.isEmpty()){retire(4);}
154 return x;
155 }
156
157 @Override
158 long dumpAll(){
159 if(verbose) {
160 System.err.println("before dumpAll: bytesInFlight="+bytesInFlight+
161 ", limit="+memLimitUpper+", readsInFlight="+readsInFlight);
162 }
163 long dumped=0;
164 for(Entry<String, Buffer> e : bufferMap.entrySet()){
165 dumped+=e.getValue().dump();
166 }
167 if(verbose) {
168 System.err.println("after dumpAll: bytesInFlight="+bytesInFlight+
169 ", limit="+memLimitUpper+", readsInFlight="+readsInFlight+", dumped="+dumped);
170 }
171 return dumped;
172 }
173
174 /** Close the least-recently-used stream */
175 private void retire_old(){
176 if(verbose){System.err.println("Enter retire(); streamQueue="+streamQueue);}
177
178 //Select the first name in the queue, which is the least-recently-used.
179 String name=streamQueue.removeFirst();
180 Buffer b=bufferMap.get(name);
181
182 if(verbose){System.err.println("retire("+name+"); ros="+(b.currentRos!=null)+", streamQueue="+streamQueue);}
183 assert(b!=null);
184 assert(b.currentRos!=null) : name+"\n"+streamQueue+"\n";
185
186 //Purge any remaining reads first
187 b.dump(b.currentRos);
188
189 //Then close the stream
190 if(closeFast){
191 b.currentRos.close();//Faster, but the error state is not caught
192 //Also the stream could be re-opened before writing is done, which is very bad, so this is unsafe as implemented.
193 }else{
194 //Unfortunately, this is very slow.
195 errorState=ReadWrite.closeStream(b.currentRos) | errorState;//Traditional synchronous close-and-wait
196 }
197
198 // ros.close();
199 // ros.join();
200 // errorState|=(ros.errorState() || !ros.finishedSuccessfully());
201
202 //Delete the pointer to output stream
203 b.currentRos=null;
204 if(verbose){System.err.println("Exit retire("+name+"); ros="+(b.currentRos!=null)+
205 ", streamQueue="+streamQueue);}
206 // assert(!streamQueue.contains(name)); //Slow
207 }
208
209 /** Close the least-recently-used streams */
210 private void retire(int count){
211 if(verbose){System.err.println("Enter retire("+count+"); streamQueue="+streamQueue);}
212 final long time0=System.nanoTime(), time1, time2, time3, time4;
213 count=Tools.min(streamQueue.size(), count);
214
215 ArrayList<Buffer> rlist=new ArrayList<Buffer>(count);
216 //Select the first name in the queue, which is the least-recently-used.
217 for(int i=0; i<count; i++) {
218 String name=streamQueue.removeFirst();
219 Buffer b=bufferMap.get(name);
220 rlist.add(b);
221 }
222 time1=System.nanoTime();
223 for(Buffer b : rlist) {
224 if(verbose){
225 System.err.println("retire("+b.name+"); ros="+
226 (b.currentRos!=null)+", streamQueue="+streamQueue);
227 }
228 assert(b!=null);
229 assert(b.currentRos!=null) : b.name+"\n"+streamQueue+"\n";
230 //Purge any remaining reads first
231 b.dump(b.currentRos);
232 }
233 time2=System.nanoTime();
234 for(Buffer b : rlist) {b.currentRos.close();}
235 time3=System.nanoTime();
236 for(Buffer b : rlist) {
237 ConcurrentReadOutputStream ros=b.currentRos;
238 ros.join();
239 errorState|=(ros.errorState() || !ros.finishedSuccessfully());
240 //Delete the pointer to output stream
241 b.currentRos=null;
242 if(verbose){System.err.println("Exit retire("+b.name+"); ros="+(b.currentRos!=null)+
243 ", streamQueue="+streamQueue);}
244 }
245 time4=System.nanoTime();
246 retireTime1+=(time1-time0);
247 retireTime2+=(time2-time1);
248 retireTime3+=(time3-time2);
249 retireTime4+=(time4-time3);
250 retireCount+=count;
251 retireCalls++;
252 }
253
254 public String printRetireTime() {
255 ByteBuilder bb=new ByteBuilder();
256 float mult=0.001f/retireCount;
257 bb.append("Max Streams:\t").append(maxStreams).nl();
258 bb.append("Retire Count:\t").append(retireCount).nl();
259 bb.append("Retires Per Call:\t").append(retireCount/(float)retireCalls, 2).nl();
260 bb.append("streamsToRetire:\t").append(streamsToRetire).nl();
261 bb.append("Retire Time 1:\t").append(retireTime1*mult, 2).append(" us").nl();
262 bb.append("Retire Time 2:\t").append(retireTime2*mult, 2).append(" us").nl();
263 bb.append("Retire Time 3:\t").append(retireTime3*mult, 2).append(" us").nl();
264 bb.append("Retire Time 4:\t").append(retireTime4*mult, 2).append(" us").nl();
265 bb.append("Total: \t").append((retireTime1+retireTime2+retireTime3+retireTime4)/1000000000.0, 3).append(" s").nl();
266 return bb.toString();
267 }
268
269 private long retireTime1=0;
270 private long retireTime2=0;
271 private long retireTime3=0;
272 private long retireTime4=0;
273 private long retireCount=0;
274 private long retireCalls=0;
275
276 public String printCreateTime() {
277 ByteBuilder bb=new ByteBuilder();
278 float mult=0.001f/retireCount;
279 bb.append("Create Time 1:\t").append(createTime1*mult, 2).append(" us").nl();
280 bb.append("Create Time 2:\t").append(createTime2*mult, 2).append(" us").nl();
281 bb.append("Create Time 3:\t").append(createTime3*mult, 2).append(" us").nl();
282 bb.append("Create Time 4:\t").append(createTime4*mult, 2).append(" us").nl();
283 bb.append("Create Time 5:\t").append(createTime5*mult, 2).append(" us").nl();
284 bb.append("Total: \t").append((createTime2+createTime3+createTime4+createTime5)/1000000000.0, 3).append(" s").nl();
285 return bb.toString();
286 }
287
288 private long createTime1=0;
289 private long createTime2=0;
290 private long createTime3=0;
291 private long createTime4=0;
292 private long createTime5=0;
293
294 /*--------------------------------------------------------------*/
295 /*---------------- Inner Classes ----------------*/
296 /*--------------------------------------------------------------*/
297
298 /**
299 * A Buffer holds reads destined for to a specific file.
300 * When sufficient reads are present, it opens a stream and writes them.
301 * If too many streams are open, it closes another stream first.
302 */
303 private class Buffer implements Comparable<Buffer>{
304
305 Buffer(String name_){
306 name=name_;
307 timestamp=(bufferTimer++);
308 String s1=pattern1.replaceFirst("%", name);
309 String s2=pattern2==null ? null : pattern2.replaceFirst("%", name);
310
311 //These are created with overwrite=false append=true because
312 //the files will be appended to if the stream gets prematurely retired.
313 //Therefore, files must be explicitly deleted first.
314 //Alternative would be to create a new FileFormat each time.
315 ff1=FileFormat.testOutput(s1, defaultFormat, null, allowSubprocess, false, true, false);
316 ff2=FileFormat.testOutput(s2, defaultFormat, null, allowSubprocess, false, true, false);
317
318 list=new ArrayList<Read>(readsPerBuffer);
319 if(trackCardinality){loglog=CardinalityTracker.makeTracker();}
320 if(verbose){System.err.println("Made buffer for "+name);}
321 }
322
323 /**
324 * Add a read to this buffer, and update all the tracking variables.
325 * This may trigger a dump.
326 */
327 void add(Read r){
328 //Add the read
329 list.add(r);
330
331 //Gather statistics
332 long size=r.countPairBytes();
333 int count=r.pairCount();
334 currentBytes+=size;
335 bytesInFlight+=size;
336 basesIn+=size;//should be pairlen...
337 readsInFlight+=count;
338 readsIn+=count;
339 if(trackCardinality){loglog.hash(r);}
340
341 //Decide whether to dump
342 handleLoad();
343 }
344
345 /**
346 * Determine whether to dump this buffer based on its current size.
347 * Then, determine whether to dump all buffers based on their combined size.
348 */
349 private void handleLoad(){
350 //3rd term allows preemptive dumping
351 //More generally, this triggers a dump if the reads in this buffer exceed
352 //the maximum allowed reads or bytes
353 final int size=list.size();
354 if(size>=readsPerBuffer || currentBytes>=bytesPerBuffer ||
355 (currentRos!=null && (size>=200 || currentBytes>400000))){
356 if(verbose){
357 System.err.println("list.size="+list.size()+"/"+readsPerBuffer+
358 ", bytes="+currentBytes+"/"+bytesPerBuffer+", bytesInFlight="+bytesInFlight+"/"+memLimitUpper);
359 }
360 dump();
361 }
362
363 //Too much buffered data in ALL buffers; dump everything.
364 if(bytesInFlight>=memLimitUpper){
365 long dumped=dumpAll();
366 if(dumped<1 && Shared.EA()){//Dump failed; exit
367 KillSwitch.kill("\nThis program ran out of memory."
368 + "\nTry increasing the -Xmx flag or get rid of the minreads flag,"
369 + "\nor disable assertions to skip this message and try anyway.");
370 }
371 }
372 }
373
374 /** Dump buffered reads, creating a stream if needed */
375 long dump(){
376 if(list.isEmpty() || readsIn<minReadsToDump){return 0;}
377 ConcurrentReadOutputStream ros=getStream();
378 return dump(ros);
379 }
380
381 /**
382 * Dump buffered reads to the stream.
383 * If the buffer is empty, nothing happens. */
384 long dump(final ConcurrentReadOutputStream ros){
385 if(verbose){System.err.println("Dumping "+name);}
386 if(list.isEmpty()){return 0;}
387 final long size0=list.size();
388
389 //Send the list to the output stream
390 //This part is async
391 ros.add(list, numDumps);
392
393 //Create a new list, since the old one is busy
394 list=new ArrayList<Read>(400);
395
396 //Manage statistics
397 bytesInFlight-=currentBytes;
398 readsInFlight-=size0;
399 readsWritten+=size0;
400 currentBytes=0;
401 numDumps++;
402 timestamp=(bufferTimer++);
403 return size0;
404 }
405
406 /** Fetch the stream for this buffer, creating a new one if needed */
407 private ConcurrentReadOutputStream getStream(){
408 if(verbose){System.err.println("Enter getStream("+name+"); ros="+(currentRos!=null)+", +streamQueue="+streamQueue);}
409
410 if(currentRos!=null){//The stream already exists
411 // assert(streamQueue.contains(name));//slow
412 if(streamQueue.peekLast()!=name){
413 //Move to end to prevent early retirement
414 boolean b=streamQueue.remove(name);
415 assert(b) : "streamQueue did not contain "+name+", but the ros was open.";
416 streamQueue.addLast(name);
417 }
418 }else{//The stream does not exist, so create it
419 createStream();
420 }
421
422 assert(currentRos!=null) : "The stream for "+name+" was not created.";
423 assert(streamQueue.peekLast()==name) : "The stream for "+name+" was not placed in the queue.";
424 if(verbose){System.err.println("Exit getStream("+name+"); ros="+(currentRos!=null)+", +streamQueue="+streamQueue);}
425 return currentRos;
426 }
427
428 /** Create a stream for this buffer, and stick it in the queue */
429 private ConcurrentReadOutputStream createStream(){
430 assert(currentRos==null) : "This should never be called if there is an existing stream.";
431 if(numDumps==0 && overwrite){
432 //First time, an existing file must be deleted first, because the ff is set to append mode
433 if(verbose){System.err.println("Deleting "+name+" ; exists? "+ff1.exists());}
434 delete(ff1);
435 delete(ff2);
436 }
437 final long time0=System.nanoTime(), time1, time2, time3, time4, time5;
438
439 // assert(!streamQueue.contains(name));//slow
440
441 //Active streams should never exceed maxStreams
442 assert(streamQueue.size()<=maxStreams) : "Too many streams: "+streamQueue+", "+maxStreams;
443 if(streamQueue.size()>=maxStreams){
444 //Too many open streams; retire one.
445 retire(streamsToRetire);
446 }
447 //After retirement, open streams must be less than maxStreams
448 assert(streamQueue.size()<maxStreams) : "Too many streams: "+streamQueue+", "+maxStreams;
449 time1=System.nanoTime();
450 time2=time1;
451
452 //Create a stream
453 currentRos=ConcurrentReadOutputStream.getStream(ff1, ff2, rswBuffers, null, useSharedHeader && numDumps==0);
454 time3=System.nanoTime();
455 currentRos.start();
456 if(verbose){System.err.println("Created ros "+name+"; ow="+ff1.overwrite()+", append="+ff1.append());}
457 time4=System.nanoTime();
458
459 //Add it to the queue
460 streamQueue.addLast(name);
461 time5=System.nanoTime();
462
463 createTime1+=(time1-time0);
464 createTime2+=(time2-time1);
465 createTime3+=(time3-time2);
466 createTime4+=(time4-time3);
467 createTime5+=(time5-time4);
468 return currentRos;
469 }
470
471 /** Delete this file if it exists */
472 private void delete(FileFormat ff){
473 if(ff==null){return;}
474 assert(overwrite || !ff.exists()) : "Trying to delete file "+ff.name()+", but overwrite=f. Please add the flag overwrite=t.";
475 ff.deleteIfPresent();
476 }
477
478 /**
479 * Format this buffer's summary as a line of text.
480 * @param bb ByteBuilder to append the text
481 * @return The modified ByteBuilder
482 */
483 ByteBuilder appendTo(ByteBuilder bb) {
484 bb.append(name).tab().append(readsIn).tab().append(basesIn);
485 if(trackCardinality){bb.tab().append(loglog.cardinality());}
486 return bb.nl();
487 }
488
489 @Override
490 public String toString(){
491 return appendTo(new ByteBuilder()).toString();
492 }
493
494 @Override
495 public int compareTo(Buffer b) {
496 assert(timestamp!=b.timestamp);
497 return timestamp<b.timestamp ? -1 : 1;
498 }
499
500 /** Stream name, which is the variable part of the file pattern */
501 private final String name;
502 /** Output file 1 */
503 private final FileFormat ff1;
504 /** Output file 2 */
505 private final FileFormat ff2;
506
507 /** Once created, the stream sticks around to be re-used unless it is retired. */
508 private ConcurrentReadOutputStream currentRos;
509
510 /** Current list of buffered reads */
511 private ArrayList<Read> list;
512
513 /** Number of reads entering the buffer */
514 private long readsIn=0;
515 /** Number of bases entering the buffer */
516 private long basesIn=0;
517 /** Number of reads written to disk */
518 @SuppressWarnings("unused")
519 private long readsWritten=0;//This does not count read2!
520 /** Number of bytes currently in this buffer (estimated) */
521 private long currentBytes=0;
522 /** Number of dumps executed */
523 private long numDumps=0;
524 /** Time of last dump */
525 private long timestamp=-1;
526 /** Optional, for tracking cardinality */
527 private CardinalityTracker loglog;
528
529 }
530
531 /*--------------------------------------------------------------*/
532 /*---------------- Fields ----------------*/
533 /*--------------------------------------------------------------*/
534
535 private long bufferTimer=0;
536
537 /** Open stream names */
538 private final ArrayDeque<String> streamQueue;
539
540 /** Map of names to buffers */
541 public final LinkedHashMap<String, Buffer> bufferMap;
542
543 /*--------------------------------------------------------------*/
544 /*---------------- Static Fields ----------------*/
545 /*--------------------------------------------------------------*/
546
547 /**
548 * Trigger stream close, but don't wait for it to finish.
549 * Prevents error state from being captured.
550 *
551 * THIS IS UNSAFE AND CAUSES ERRORS,
552 * because the stream might get reopened again before writing is finished.
553 */
554 private static final boolean closeFast=false;
555
556 }