Debian Codegraph @

current/stream/MultiCros6.java

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