Debian Codegraph @

current/driver/LoadReads.java

raw symbols SCIP
1 package driver;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6
7 import fileIO.ByteFile;
8 import fileIO.FileFormat;
9 import fileIO.ReadWrite;
10 import shared.Parse;
11 import shared.Parser;
12 import shared.PreParser;
13 import shared.Shared;
14 import shared.Timer;
15 import shared.Tools;
16 import stream.ConcurrentReadInputStream;
17 import stream.FASTQ;
18 import stream.FastaReadInputStream;
19 import stream.Read;
20 import structures.ListNum;
21 import tracker.ReadStats;
22
23 /**
24 * This class loads data to see how much memory is used.
25 *
26 * @author Brian Bushnell
27 * @date October 28, 2016
28 *
29 */
30 public class LoadReads {
31
32 /*--------------------------------------------------------------*/
33 /*---------------- Initialization ----------------*/
34 /*--------------------------------------------------------------*/
35
36 /**
37 * Code entrance from the command line.
38 * @param args Command line arguments
39 */
40 public static void main(String[] args){
41 Timer t=new Timer();
42 LoadReads x=new LoadReads(args);
43 x.process(t);
44
45 //Close the print stream if it was redirected
46 Shared.closeStream(x.outstream);
47 }
48
49 /**
50 * Constructor.
51 * @param args Command line arguments
52 */
53 public LoadReads(String[] args){
54
55 {//Preparse block for help, config files, and outstream
56 PreParser pp=new PreParser(args, getClass(), false);
57 args=pp.args;
58 outstream=pp.outstream;
59 }
60
61 //Set shared static variables
62 Shared.capBufferLen(100);
63 Shared.capBuffers(1);
64 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
65 ReadWrite.setZipThreads(Shared.threads());
66
67 //Create a parser object
68 Parser parser=new Parser();
69 boolean setInterleaved=false; //Whether interleaved was explicitly set.
70
71 //Parse each argument
72 for(int i=0; i<args.length; i++){
73 String arg=args[i];
74
75 //Break arguments into their constituent parts, in the form of "a=b"
76 String[] split=arg.split("=");
77 String a=split[0].toLowerCase();
78 String b=split.length>1 ? split[1] : null;
79
80 if(parser.parse(arg, a, b)){//Parse standard flags in the parser
81 //do nothing
82 }else if(a.equals("verbose")){
83 verbose=Parse.parseBoolean(b);
84 }else if(a.equals("earlyexit")){
85 earlyExit=Parse.parseBoolean(b);
86 }else if(a.equals("lowcomplexity")){
87 lowComplexity=Parse.parseBoolean(b);
88 }else if(a.equals("gc")){
89 gc=Parse.parseBoolean(b);
90 }else if(a.equals("overhead")){
91 overhead=Integer.parseInt(b);
92 }else if(a.equals("parse_flag_goes_here")){
93 //Set a variable here
94 }else{
95 outstream.println("Unknown parameter "+args[i]);
96 assert(false) : "Unknown parameter "+args[i];
97 // throw new RuntimeException("Unknown parameter "+args[i]);
98 }
99 }
100
101 {//Process parser fields
102 Parser.processQuality();
103
104 maxReads=parser.maxReads;
105
106 overwrite=ReadStats.overwrite=parser.overwrite;
107 append=ReadStats.append=parser.append;
108 setInterleaved=parser.setInterleaved;
109
110 in1=parser.in1;
111 in2=parser.in2;
112 qfin1=parser.qfin1;
113 qfin2=parser.qfin2;
114
115 extin=parser.extin;
116 }
117
118 //Do input file # replacement
119 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
120 in2=in1.replace("#", "2");
121 in1=in1.replace("#", "1");
122 }
123
124 //Adjust interleaved detection based on the number of input files
125 if(in2!=null){
126 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
127 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
128 }
129
130 assert(FastaReadInputStream.settingsOK());
131
132 //Ensure there is an input file
133 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
134
135 //Adjust the number of threads for input file reading
136 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
137 ByteFile.FORCE_MODE_BF2=true;
138 }
139
140 //Adjust interleaved settings based on number of output files
141 if(!setInterleaved){
142 assert(in1!=null) : "\nin1="+in1+"\nin2="+in2+"\n";
143 if(in2!=null){ //If there are 2 input streams.
144 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
145 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
146 }
147 }
148
149 //Ensure input files can be read
150 if(!Tools.testInputFiles(false, true, in1, in2)){
151 throw new RuntimeException("\nCan't read some input files.\n");
152 }
153
154 //Ensure that no file was specified multiple times
155 if(!Tools.testForDuplicateFiles(true, in1, in2)){
156 throw new RuntimeException("\nSome file names were specified multiple times.\n");
157 }
158
159 //Create input FileFormat objects
160 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
161 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
162 }
163
164 /*--------------------------------------------------------------*/
165 /*---------------- Outer Methods ----------------*/
166 /*--------------------------------------------------------------*/
167
168 /** Create read streams and process all data */
169 void process(Timer t){
170
171 calcMem();
172
173 //Create a read input stream
174 final ConcurrentReadInputStream cris;
175 {
176 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
177 cris.start(); //Start the stream
178 if(verbose){outstream.println("Started cris");}
179 }
180 boolean paired=cris.paired();
181 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
182
183
184 //Reset counters
185 readsProcessed=0;
186 basesProcessed=0;
187
188 //Process the read stream
189 processInner(cris);
190
191 if(verbose){outstream.println("Finished; closing streams.");}
192
193 //Write anything that was accumulated by ReadStats
194 errorState|=ReadStats.writeAll();
195 //Close the read streams
196 errorState|=ReadWrite.closeStreams(cris);
197
198 calcMem();
199
200 double[] estimates=Tools.estimateFileMemory(in1, 200, overhead, earlyExit, lowComplexity);
201 long memEst0=(long)estimates[0];
202 long diskEst0=(long)estimates[1];
203 double memRatio0=estimates[2];
204 double diskRatio0=estimates[3];
205 double readEst0=estimates[4];
206
207 long size=new File(in1).length();
208 long usedMem=maxMem-minMem;
209 double memRatio1=memBytesProcessed/(double)size;
210 double memRatio=usedMem/(double)size;
211 double diskRatio=diskBytesProcessed/(double)size;
212 double readRatio=readsProcessed/(double)size;
213
214 long overhead=usedMem-diskBytesProcessed;
215
216 double mult=1.0/readsProcessed;
217 double memPerRead=usedMem*mult;
218 // double mem0PerRead=usedMem*mult;
219 double mem1PerRead=memBytesProcessed*mult;
220 double basesPerRead=basesProcessed*mult;
221 double qualsPerRead=qualitiesProcessed*mult;
222 double headerPerRead=headersProcessed*mult;
223 double overheadPerRead=overhead*mult;
224
225
226 final long afterGC;
227 if(gc){
228 outstream.println("Final GC.");
229
230 System.gc();
231 afterGC=Shared.memUsed();
232 }else{
233 afterGC=0;
234 }
235
236 outstream.println("Initial Memory: \t"+(initialMem/1000000)+" m");
237 outstream.println("Final Memory: \t"+(finalMem/1000000)+" m");
238 if(gc){outstream.println("After GC: \t"+(afterGC/1000000)+" m");}
239 outstream.println("Min Memory: \t"+(minMem/1000000)+" m");
240 outstream.println("Max Memory: \t"+(maxMem/1000000)+" m");
241 outstream.println();
242 outstream.println("Memory Estimate 0: \t"+(memEst0/1000000)+" m");
243 outstream.println("Memory Estimate 1: \t"+(memBytesProcessed/1000000)+" m");
244 outstream.println("Memory: \t"+(usedMem/1000000)+" m");
245 outstream.println();
246 outstream.println("Disk Estimate 0: \t"+(diskEst0/1000000+" m"));
247 outstream.println("Disk Bytes: \t"+((diskBytesProcessed)/1000000)+" m");
248 outstream.println();
249 outstream.println("Memory Ratio Est 0: \t"+(Tools.format("%.2f", memRatio0)));
250 outstream.println("Memory Ratio Est 1: \t"+(Tools.format("%.2f", memRatio1)));
251 outstream.println("Memory Ratio: \t"+(Tools.format("%.2f", memRatio)));
252 outstream.println();
253 outstream.println("Disk Ratio Est 0: \t"+(Tools.format("%.2f", diskRatio0)));
254 outstream.println("Disk Ratio: \t"+(Tools.format("%.2f", diskRatio)));
255 outstream.println();
256 outstream.println("Read Estimate 0: \t"+(Tools.format("%d", (long)Math.ceil(readEst0))));
257 outstream.println("Read Ratio 1: \t"+(Tools.format("%.2f", readRatio)));
258 outstream.println("Reads: \t"+(Tools.format("%d", readsProcessed)));
259 outstream.println();
260 // outstream.println("Average Memory 0: \t"+(Tools.format("%.2f", mem0PerRead)));
261 outstream.println("Average Memory 1: \t"+(Tools.format("%.2f", mem1PerRead)));
262 outstream.println("Average Memory: \t"+(Tools.format("%.2f", memPerRead)));
263 outstream.println("Average Bases: \t"+(Tools.format("%.2f", basesPerRead)));
264 outstream.println("Average Q-Scores: \t"+(Tools.format("%.2f", qualsPerRead)));
265 outstream.println("Average Header Len: \t"+(Tools.format("%.2f", headerPerRead)));
266 outstream.println("Average Overhead: \t"+(Tools.format("%.2f", overheadPerRead)));
267 outstream.println();
268
269
270 //Report timing and results
271 {
272 t.stop();
273
274 //Calculate units per nanosecond
275 double dpnano=diskBytesProcessed/(double)(t.elapsed);
276 double mpnano=memBytesProcessed/(double)(t.elapsed);
277
278 //Add "k" and "m" for large numbers
279 String dpstring=(diskBytesProcessed<100000 ? ""+diskBytesProcessed : diskBytesProcessed<100000000 ? (diskBytesProcessed/1000)+"k" : (diskBytesProcessed/1000000)+"m");
280 String mpstring=(memBytesProcessed<100000 ? ""+memBytesProcessed : memBytesProcessed<100000000 ? (memBytesProcessed/1000)+"k" : (memBytesProcessed/1000000)+"m");
281
282 //Format the strings so they have they are right-justified
283 while(dpstring.length()<8){dpstring=" "+dpstring;}
284 while(mpstring.length()<8){mpstring=" "+mpstring;}
285
286 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
287 outstream.println("Disk Bytes Processed: "+dpstring+" \t"+Tools.format("%.2fm bytes/sec", dpnano*1000));
288 outstream.println("Mem Bytes Processed: "+mpstring+" \t"+Tools.format("%.2fm bytes/sec", mpnano*1000));
289 }
290
291 //Throw an exception of there was an error in a thread
292 if(errorState){
293 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
294 }
295 }
296
297 /** Iterate through the reads */
298 void processInner(final ConcurrentReadInputStream cris){
299
300 //Do anything necessary prior to processing
301
302 {
303 //Grab the first ListNum of reads
304 ListNum<Read> ln=cris.nextList();
305 //Grab the actual read list from the ListNum
306 ArrayList<Read> reads=(ln!=null ? ln.list : null);
307
308 //Check to ensure pairing is as expected
309 if(reads!=null && !reads.isEmpty()){
310 Read r=reads.get(0);
311 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
312 }
313
314 //As long as there is a nonempty read list...
315 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
316 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
317 storage.add(reads);
318 calcMem();
319
320 //Loop through each read in the list
321 for(int idx=0; idx<reads.size(); idx++){
322 final Read r1=reads.get(idx);
323 final Read r2=r1.mate;
324
325 //Track the initial length for statistics
326 final int initialLength1=r1.length();
327 final int initialLength2=(r1.mateLength());
328
329 //Increment counters
330 readsProcessed+=r1.pairCount();
331 basesProcessed+=initialLength1+initialLength2;
332
333 qualitiesProcessed+=(r1.qlength()+(r2==null ? 0 : r2.qlength()));
334 headersProcessed+=(r1.id.length()+(r2==null ? 0 : r2.id.length()));
335
336 diskBytesProcessed+=r1.countFastqBytes();
337 if(r2!=null){diskBytesProcessed+=r2.countFastqBytes();}
338
339 memBytesProcessed+=r1.countBytes();
340 if(r2!=null){memBytesProcessed+=r2.countBytes();}
341 }
342
343 //Notify the input stream that the list was used
344 cris.returnList(ln);
345 if(verbose){outstream.println("Returned a list.");}
346
347 //Fetch a new list
348 ln=cris.nextList();
349 reads=(ln!=null ? ln.list : null);
350 }
351
352 //Notify the input stream that the final list was used
353 if(ln!=null){
354 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
355 }
356 }
357
358 //Do anything necessary after processing
359
360 }
361
362 /*--------------------------------------------------------------*/
363 /*---------------- Inner Methods ----------------*/
364 /*--------------------------------------------------------------*/
365
366 private void calcMem(){
367 final long used=Shared.memUsed();
368 minMem=Tools.min(used, minMem);
369 maxMem=Tools.max(used, maxMem);
370 finalMem=used;
371 if(initialMem<0){
372 // System.err.println(minMem+", "+maxMem+", "+initialMem+", "+finalMem);
373 initialMem=used;
374 }
375 // System.err.println(minMem+", "+maxMem+", "+initialMem+", "+finalMem);
376 }
377
378 /*--------------------------------------------------------------*/
379 /*---------------- Fields ----------------*/
380 /*--------------------------------------------------------------*/
381
382 /** Primary input file path */
383 private String in1=null;
384 /** Secondary input file path */
385 private String in2=null;
386
387 private String qfin1=null;
388 private String qfin2=null;
389
390 /** Override input file extension */
391 private String extin=null;
392
393 private ArrayList<ArrayList<Read>> storage=new ArrayList<ArrayList<Read>>();
394
395 /*--------------------------------------------------------------*/
396
397 /** Number of reads processed */
398 protected long readsProcessed=0;
399 /** Number of bases processed */
400 protected long basesProcessed=0;
401 /** Number of quality scores processed */
402 protected long qualitiesProcessed=0;
403 /** Number of header characters processed */
404 protected long headersProcessed=0;
405
406 /** Approximate number of fastq disk bytes processed */
407 protected long diskBytesProcessed=0;
408 /** Approximate number of read memory bytes processed */
409 protected long memBytesProcessed=0;
410
411 /** Minimal observed memory usage */
412 protected long minMem=Long.MAX_VALUE;
413 /** Maximal observed memory usage */
414 protected long maxMem=0;
415
416 protected long initialMem=-1;
417 protected long finalMem=-1;
418
419 /** Quit after processing this many input reads; -1 means no limit */
420 private long maxReads=-1;
421
422 private int overhead=0;
423 private boolean earlyExit=false;
424 private boolean gc=false;
425 private boolean lowComplexity=false;
426
427 /*--------------------------------------------------------------*/
428 /*---------------- Final Fields ----------------*/
429 /*--------------------------------------------------------------*/
430
431 /** Primary input file */
432 private final FileFormat ffin1;
433 /** Secondary input file */
434 private final FileFormat ffin2;
435
436 /*--------------------------------------------------------------*/
437 /*---------------- Common Fields ----------------*/
438 /*--------------------------------------------------------------*/
439
440 /** Print status messages to this output stream */
441 private PrintStream outstream=System.err;
442 /** Print verbose messages */
443 public static boolean verbose=false;
444 /** True if an error was encountered */
445 public boolean errorState=false;
446 /** Overwrite existing output files */
447 private boolean overwrite=true;
448 /** Append to existing output files */
449 private boolean append=false;
450 /** This flag has no effect on singlethreaded programs */
451 private final boolean ordered=false;
452
453 }