Debian Codegraph @

current/stream/BufferedMultiCros.java

raw symbols SCIP
1 package stream;
2
3 import java.util.ArrayList;
4 import java.util.Set;
5 import java.util.concurrent.ArrayBlockingQueue;
6
7 import fileIO.FileFormat;
8 import shared.KillSwitch;
9 import shared.Parse;
10 import shared.Shared;
11 import shared.Tools;
12 import structures.ByteBuilder;
13
14 /**
15 * Allows output of reads to multiple different output streams.
16 * Each output stream is controlled by a buffer,
17 * which stores reads until there is a sufficient quantity to dump.
18 *
19 * @author Brian Bushnell
20 * @date May 14, 2019
21 *
22 */
23 public abstract class BufferedMultiCros extends Thread {
24
25 /*--------------------------------------------------------------*/
26 /*---------------- Constructors ----------------*/
27 /*--------------------------------------------------------------*/
28
29 public static BufferedMultiCros make(String out1, String out2, boolean overwrite, boolean append,
30 boolean allowSubprocess, boolean useSharedHeader, int defaultFormat) {
31 return make(out1, out2, overwrite, append, allowSubprocess, useSharedHeader,
32 defaultFormat, defaultThreaded, defaultMcrosType, defaultMaxStreams);
33 }
34
35 public static BufferedMultiCros make(String out1, String out2, boolean overwrite, boolean append,
36 boolean allowSubprocess, boolean useSharedHeader, int defaultFormat, boolean threaded,
37 int mcrosType, int maxStreams) {
38
39 BufferedMultiCros mcros=null;
40 if(mcrosType==2){//Slow, synchronous mcros type
41 mcros=new MultiCros2(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, threaded);
42 }else if(mcrosType==3){//Faster, asynchronous type
43 mcros=new MultiCros3(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, threaded, maxStreams);
44 }else if(mcrosType==4){//Threaded file closing
45 mcros=new MultiCros4(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, threaded, maxStreams);
46 }else if(mcrosType==5){//New retirement ordering by timer
47 mcros=new MultiCros5(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, threaded, maxStreams);
48 }else if(mcrosType==6){//New retirement ordering by timer
49 mcros=new MultiCros6(out1, out2, overwrite, append, true, useSharedHeader, FileFormat.FASTQ, threaded, maxStreams);
50 }else{
51 throw new RuntimeException("Bad mcrosType: "+mcrosType);
52 }
53 return mcros;
54 }
55
56 /**
57 * Primary constructor.
58 * @param pattern1_ Name pattern for file 1; must contain % (required)
59 * @param pattern2_ Name pattern for file 2; must contain % (optional)
60 * @param overwrite_ Permission to overwrite
61 * @param append_ Permission to append to existing files (this should generally be false)
62 * @param allowSubprocess_ Allow subprocesses such as pigz, bgzip, or samtools
63 * @param useSharedHeader_ Print the stored header (from an input sam file) in all output sam files
64 * @param defaultFormat_ Assume files are in this format if they don't have a valid extension
65 * @param threaded_ Run this mcros in its own thread
66 * @param maxStreams_ Max allowed number of concurrent open streams
67 */
68 public BufferedMultiCros(String pattern1_, String pattern2_,
69 boolean overwrite_, boolean append_, boolean allowSubprocess_, boolean useSharedHeader_,
70 int defaultFormat_, boolean threaded_, int maxStreams_){
71 assert(pattern1_!=null && pattern1_.indexOf('%')>=0);
72 assert(pattern2_==null || pattern1_.indexOf('%')>=0);
73
74 //Perform # expansion for twin files
75 if(pattern2_==null && pattern1_.indexOf('#')>=0){
76 pattern1=pattern1_.replaceFirst("#", "1");
77 pattern2=pattern1_.replaceFirst("#", "2");
78 }else{
79 pattern1=pattern1_;
80 pattern2=pattern2_;
81 }
82
83 overwrite=overwrite_;
84 append=append_;
85 allowSubprocess=allowSubprocess_;
86 useSharedHeader=useSharedHeader_;
87
88 defaultFormat=defaultFormat_;
89
90 threaded=threaded_;
91 transferQueue=threaded ? new ArrayBlockingQueue<ArrayList<Read>>(8) : null;
92 maxStreams=maxStreams_;
93
94 //Significantly impacts performance.
95 //Higher numbers give more retires but less time per retire.
96 //Optimal seems to be around 4-6, at least for 16 streams.
97 streamsToRetire=Tools.mid(2, (maxStreams+1)/3, 16);
98
99 final long bytes=Shared.memAvailable();
100 memLimitLower=Tools.max(50000000, (long)(memLimitLowerMult*bytes));
101 memLimitMid=Tools.max(70000000, (long)(memLimitMidMult*bytes));
102 memLimitUpper=Tools.max(90000000, (long)(memLimitUpperMult*bytes));
103 }
104
105 /*--------------------------------------------------------------*/
106 /*---------------- Parsing ----------------*/
107 /*--------------------------------------------------------------*/
108
109 public static boolean parseStatic(String arg, String a, String b){
110 if(a.equals("mcrostype")){
111 defaultMcrosType=Integer.parseInt(b);
112 }else if(a.equals("threaded")){
113 defaultThreaded=Parse.parseBoolean(b);
114 }else if(a.equals("streams")){
115 defaultMaxStreams=Integer.parseInt(b);
116 }else if(a.equalsIgnoreCase("readsPerBuffer")){
117 defaultReadsPerBuffer=Integer.parseInt(b);
118 }else if(a.equalsIgnoreCase("bytesPerBuffer")){
119 defaultBytesPerBuffer=Integer.parseInt(b);
120 }else if(a.equalsIgnoreCase("memLimitLowerMult") || a.equals("mllmult") || a.equals("mllm")){
121 memLimitLowerMult=Float.parseFloat(b);
122 assert(memLimitLowerMult>=0 && memLimitLowerMult<1);
123 }else if(a.equalsIgnoreCase("memLimitMidMult") || a.equals("mlmmult") || a.equals("mlmm")){
124 memLimitMidMult=Float.parseFloat(b);
125 assert(memLimitMidMult>=0 && memLimitMidMult<1);
126 }else if(a.equalsIgnoreCase("memLimitUpperMult") || a.equals("mlumult") || a.equals("mlum")){
127 memLimitUpperMult=Float.parseFloat(b);
128 assert(memLimitUpperMult>=0 && memLimitUpperMult<1);
129 }else{
130 return false;
131 }
132
133 return true;
134 }
135
136 /*--------------------------------------------------------------*/
137 /*---------------- Abstract Methods ----------------*/
138 /*--------------------------------------------------------------*/
139
140 /** True if no errors were encountered */
141 public abstract boolean finishedSuccessfully();
142
143 /**
144 * Add a single read. Should not be used in threaded mode.
145 * Should only be used by this class.
146 * @param r Read to add.
147 * @param name Name of destination buffer.
148 */
149 abstract void add(Read r, String name);
150
151 /**
152 * Dump all buffered reads to disk, except when minReadsToDump forbids it.
153 * @return Number of reads dumped.
154 */
155 abstract long dumpAll();
156
157 /**
158 * Dump all residual reads to this stream.
159 * @param rosu Destination stream.
160 * @return Number of residual reads dumped.
161 */
162 public abstract long dumpResidual(ConcurrentReadOutputStream rosu);
163
164 /** Dump everything and close any open streams. */
165 abstract long closeInner();
166
167 /** Generate a report on how many reads went to each file */
168 public abstract ByteBuilder report();
169
170 /** Time for shutting down output threads */
171 public String printRetireTime() {
172 throw new RuntimeException("printRetireTime not available for "+getClass().getName());
173 }
174
175 /** Time for shutting down output threads */
176 public String printCreateTime() {
177 throw new RuntimeException("printRetireTime not available for "+getClass().getName());
178 }
179
180 public abstract Set<String> getKeys();
181
182 /*--------------------------------------------------------------*/
183 /*---------------- Final Methods ----------------*/
184 /*--------------------------------------------------------------*/
185
186 /** Shut this down and perform any cleanup needed. */
187 public final void close(){
188 if(threaded){poisonAndWait();}
189 else{closeInner();}
190 }
191
192 /** Primary file pattern */
193 public final String fname(){return pattern1;}
194
195 /** Return true if this stream has detected an error */
196 public final boolean errorState(){
197 return errorState;
198 }
199
200 /**
201 * Send a list of reads to an output buffer.
202 * The reads must have a name attached to the object field in order to be written.
203 */
204 public final void add(ArrayList<Read> list) {
205 if(threaded){//Send to the transfer queue
206 addToQueue(list);
207 }else{//Add the reads from this thread
208 addToBuffers(list);
209 }
210 }
211
212 /** Send individual reads to their designated buffer */
213 private final void addToBuffers(ArrayList<Read> list) {
214 for(Read r : list){
215 if(r.obj!=null){
216 String name=(String)r.obj;
217 readsInTotal++;
218 add(r, name);//Reads without a name in the obj field get ignored here.
219 }
220 }
221 handleLoad0();
222 }
223
224 /** Called to handle load after adding a list */
225 void handleLoad0() {
226 //Do nothing
227 }
228
229 /*--------------------------------------------------------------*/
230 /*---------------- Threaded Methods ----------------*/
231 /*--------------------------------------------------------------*/
232
233 @Override
234 /** For threaded mode */
235 public final void run(){
236 assert(threaded) : "This should only be called in threaded mode.";
237 try {
238 for(ArrayList<Read> list=transferQueue.take(); list!=poisonToken; list=transferQueue.take()){
239 if(verbose){System.err.println("Got list; size=\"+transferQueue.size())");}
240 addToBuffers(list);
241 if(verbose){System.err.println("Added list; size="+transferQueue.size());}
242 }
243 } catch (InterruptedException e) {
244 //Terminate JVM if something goes wrong
245 KillSwitch.exceptionKill(e);
246 }
247 closeInner();
248 }
249
250 /** Indicate that no more reads will be sent, for threaded mode */
251 public final void poison(){
252 assert(threaded) : "This should only be called in threaded mode.";
253 addToQueue(poisonToken);
254 }
255
256 boolean addToQueue(ArrayList<Read> list) {
257 boolean success=false;
258 for(int i=0; i<10 && !success; i++) {
259 try {
260 transferQueue.put(list);
261 success=true;
262 } catch (InterruptedException e) {
263 // TODO Auto-generated catch block
264 e.printStackTrace();
265 }
266 }
267 if(!success) {
268 KillSwitch.kill("Something went wrong when adding to "+getClass().getName());
269 }
270 return success;
271 }
272
273 /** Indicate that no more reads will be sent, for threaded mode */
274 public final void poisonAndWait(){
275 assert(threaded) : "This should only be called in threaded mode.";
276 poison();
277 waitForFinish();
278 }
279
280 /** Wait for this object's thread to terminate */
281 public final void waitForFinish(){
282 assert(threaded);
283 if(verbose){System.err.println("Waiting for finish.");}
284 while(this.getState()!=Thread.State.TERMINATED){
285 if(verbose){System.err.println("Attempting join.");}
286 try {
287 this.join(1000);
288 } catch (InterruptedException e) {
289 e.printStackTrace();
290 }
291 }
292 }
293
294 /*--------------------------------------------------------------*/
295 /*---------------- Fields ----------------*/
296 /*--------------------------------------------------------------*/
297
298 /** Output file patterns containing a % symbol */
299 public final String pattern1, pattern2;
300
301 /** True if an error was encountered */
302 boolean errorState=false;
303
304 /** File overwrite permission */
305 final boolean overwrite;
306
307 /** File append permission */
308 final boolean append;
309
310 /** Subprocess spawning permission (e.g., for pigz) */
311 final boolean allowSubprocess;
312
313 /** Output file format, if unclear from file extension */
314 final int defaultFormat;
315
316 /** Buffers for each ReadStreamWriter */
317 int rswBuffers=1;
318
319 /** Print the shared header (for sam files) */
320 final boolean useSharedHeader;
321
322 /** Don't retire below this limit */
323 final long memLimitLower;
324
325 /** Possibly take some action */
326 final long memLimitMid;
327
328 /** Dump everything if this limit is reached from buffered reads */
329 final long memLimitUpper;
330
331 /** Allow this many active streams, for MCros3+ */
332 public final int maxStreams;
333
334 /** Retire this many streams at a time */
335 public final int streamsToRetire;
336
337 /** Dump a buffer once it holds this many reads */
338 public int readsPerBuffer=defaultReadsPerBuffer;
339
340 /** Dump a buffer once it holds this many bytes (estimated) */
341 public int bytesPerBuffer=defaultBytesPerBuffer;
342
343 /** Never write files with fewer than this many reads */
344 public long minReadsToDump=0;
345
346 /** Number of reads encountered that were not written */
347 public long residualReads=0, residualBases=0;
348
349 long readsInTotal=0;
350
351 /** Current number of buffered reads */
352 long readsInFlight=0;
353
354 /** Current number of buffered bytes (estimated) */
355 long bytesInFlight=0;
356
357 /** Used when MultiCros is run in threaded mode */
358 private final ArrayBlockingQueue<ArrayList<Read>> transferQueue;
359
360 /** Signal to terminate when in threaded mode */
361 private final ArrayList<Read> poisonToken=new ArrayList<Read>(0);
362
363 /** True if this object is intended to run in a separate thread */
364 public final boolean threaded;
365
366 /** Use a LogLog to track cardinality for each output file */
367 public boolean trackCardinality=false;
368
369 /*--------------------------------------------------------------*/
370 /*---------------- Static Fields ----------------*/
371 /*--------------------------------------------------------------*/
372
373 private static float memLimitLowerMult=0.20f;
374 private static float memLimitMidMult=0.40f;
375 private static float memLimitUpperMult=0.60f;
376 public static boolean defaultThreaded=true;
377 public static int defaultMaxStreams=12;
378 public static int defaultMcrosType=6;
379 public static int defaultReadsPerBuffer=32000;
380 public static int defaultBytesPerBuffer=16000000;
381
382 public static boolean verbose=false;
383
384 }