Debian Codegraph @

current/template/A_Sample_Generator.java

raw symbols SCIP
1 package template;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.concurrent.atomic.AtomicLong;
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.ConcurrentReadOutputStream;
18 import stream.FASTQ;
19 import stream.FastaReadInputStream;
20 import stream.Read;
21 import structures.ListNum;
22 import tracker.ReadStats;
23
24 /**
25 * This class does nothing.
26 * It serves as a template for generating reads,
27 * potentially based on some input sequence.
28 *
29 * @author Brian Bushnell
30 * @date June 8, 2019
31 *
32 */
33 public class A_Sample_Generator {
34
35 /*--------------------------------------------------------------*/
36 /*---------------- Initialization ----------------*/
37 /*--------------------------------------------------------------*/
38
39 /**
40 * Code entrance from the command line.
41 * @param args Command line arguments
42 */
43 public static void main(String[] args){
44 //Start a timer immediately upon code entrance.
45 Timer t=new Timer();
46
47 //Create an instance of this class
48 A_Sample_Generator x=new A_Sample_Generator(args);
49
50 //Run the object
51 x.process(t);
52
53 //Close the print stream if it was redirected
54 Shared.closeStream(x.outstream);
55 }
56
57 /**
58 * Constructor.
59 * @param args Command line arguments
60 */
61 public A_Sample_Generator(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 //Set shared static variables prior to parsing
70 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
71 ReadWrite.setZipThreads(Shared.threads());
72 FASTQ.TEST_INTERLEAVED=FASTQ.FORCE_INTERLEAVED=false;
73
74 {//Parse the arguments
75 final Parser parser=parse(args);
76 Parser.processQuality();
77
78 maxReads=parser.maxReads;
79 overwrite=ReadStats.overwrite=parser.overwrite;
80 append=ReadStats.append=parser.append;
81
82 in1=parser.in1;
83 extin=parser.extin;
84
85 out1=parser.out1;
86 out2=parser.out2;
87 qfout1=parser.qfout1;
88 qfout2=parser.qfout2;
89 extout=parser.extout;
90 }
91
92 validateParams();
93 doPoundReplacement(); //Replace # with 1 and 2
94 fixExtensions(); //Add or remove .gz or .bz2 as needed
95 checkFileExistence(); //Ensure files can be read and written
96 checkStatics(); //Adjust file-related static fields as needed for this program
97
98 //Create output FileFormat objects
99 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
100 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
101
102 //Create input FileFormat objects
103 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
104 }
105
106 /*--------------------------------------------------------------*/
107 /*---------------- Initialization Helpers ----------------*/
108 /*--------------------------------------------------------------*/
109
110 /** Parse arguments from the command line */
111 private Parser parse(String[] args){
112
113 //Create a parser object
114 Parser parser=new Parser();
115
116 //Set any necessary Parser defaults here
117 //parser.foo=bar;
118
119 //Parse each argument
120 for(int i=0; i<args.length; i++){
121 String arg=args[i];
122
123 //Break arguments into their constituent parts, in the form of "a=b"
124 String[] split=arg.split("=");
125 String a=split[0].toLowerCase();
126 String b=split.length>1 ? split[1] : null;
127 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
128
129 if(a.equals("verbose")){
130 verbose=Parse.parseBoolean(b);
131 }else if(a.equals("parse_flag_goes_here")){
132 long fake_variable=Parse.parseKMG(b);
133 //Set a variable here
134 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
135 //do nothing
136 }else{
137 outstream.println("Unknown parameter "+args[i]);
138 assert(false) : "Unknown parameter "+args[i];
139 }
140 }
141
142 return parser;
143 }
144
145 /** Replace # with 1 and 2 in headers */
146 private void doPoundReplacement(){
147
148 //Do output file # replacement
149 if(out1!=null && out2==null && out1.indexOf('#')>-1){
150 out2=out1.replace("#", "2");
151 out1=out1.replace("#", "1");
152 }
153
154 //Ensure there is an input file
155 assert(false) : "May or may not be required...";
156 // if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
157
158 //Ensure out2 is not set without out1
159 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
160 }
161
162 /** Add or remove .gz or .bz2 as needed */
163 private void fixExtensions(){
164 in1=Tools.fixExtension(in1);
165 }
166
167 /** Ensure files can be read and written */
168 private void checkFileExistence(){
169 //Ensure output files can be written
170 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
171 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
172 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
173 }
174
175 //Ensure input files can be read
176 if(!Tools.testInputFiles(false, true, in1)){
177 throw new RuntimeException("\nCan't read some input files.\n");
178 }
179
180 //Ensure that no file was specified multiple times
181 if(!Tools.testForDuplicateFiles(true, in1, out1, out2)){
182 throw new RuntimeException("\nSome file names were specified multiple times.\n");
183 }
184 }
185
186 /** Adjust file-related static fields as needed for this program */
187 private static void checkStatics(){
188 //Adjust the number of threads for input file reading
189 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
190 ByteFile.FORCE_MODE_BF2=true;
191 }
192
193 assert(FastaReadInputStream.settingsOK());
194 }
195
196 /** Ensure parameter ranges are within bounds and required parameters are set */
197 private boolean validateParams(){
198 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
199 assert(false) : "TODO";
200 return true;
201 }
202
203 /*--------------------------------------------------------------*/
204 /*---------------- Outer Methods ----------------*/
205 /*--------------------------------------------------------------*/
206
207 /** Create read streams and process all data */
208 void process(Timer t){
209
210 //Turn off read validation in the input threads to increase speed
211 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
212 Read.VALIDATE_IN_CONSTRUCTOR=true;
213
214 //Create a read input stream
215 final ConcurrentReadInputStream cris=makeCris();
216
217 //Optionally create a read output stream
218 assert(false) : "TODO: Determine whether output should be paired.";
219 final ConcurrentReadOutputStream ros=makeCros(false);
220
221 //Reset counters
222 readsProcessed=readsOut=0;
223 basesProcessed=basesOut=0;
224
225 data=loadData(cris);
226
227 //Process the reads in separate threads
228 spawnThreads(cris, ros);
229
230 if(verbose){outstream.println("Finished; closing streams.");}
231
232 //Write anything that was accumulated by ReadStats
233 errorState|=ReadStats.writeAll();
234 //Close the read streams
235 errorState|=ReadWrite.closeStreams(cris, ros);
236
237 //Reset read validation
238 Read.VALIDATE_IN_CONSTRUCTOR=vic;
239
240 //Report timing and results
241 t.stop();
242 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
243 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
244
245 //Throw an exception of there was an error in a thread
246 if(errorState){
247 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
248 }
249 }
250
251 /** Create a Read Input Stream */
252 private ConcurrentReadInputStream makeCris(){
253 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
254 cris.start(); //Start the stream
255 if(verbose){outstream.println("Started cris");}
256 return cris;
257 }
258
259 /** Create a Read Output Stream */
260 private ConcurrentReadOutputStream makeCros(boolean pairedInput){
261 if(ffout1==null){return null;}
262
263 //Set output buffer size
264 final int buff=4;
265
266 //Notify user of output mode
267 if(pairedInput && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
268 outstream.println("Writing interleaved.");
269 }
270
271 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(
272 ffout1, ffout2, qfout1, qfout2, buff, null, false);
273 ros.start(); //Start the stream
274 return ros;
275 }
276
277 /** Spawn process threads */
278 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
279
280 //Do anything necessary prior to processing
281
282 //Determine how many threads may be used
283 final int threads=Shared.threads();
284
285 //Fill a list with ProcessThreads
286 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
287 for(int i=0; i<threads; i++){
288 alpt.add(new ProcessThread(ros, i, maxReads, nextReadID));
289 }
290
291 //Start the threads
292 for(ProcessThread pt : alpt){
293 pt.start();
294 }
295
296 //Wait for threads to finish
297 waitForThreads(alpt);
298
299 //Do anything necessary after processing
300
301 }
302
303 /** Wait until all worker threads are finished, then return */
304 private void waitForThreads(ArrayList<ProcessThread> alpt){
305
306 //Wait for completion of all threads
307 boolean success=true;
308 for(ProcessThread pt : alpt){
309
310 //Wait until this thread has terminated
311 while(pt.getState()!=Thread.State.TERMINATED){
312 try {
313 //Attempt a join operation
314 pt.join();
315 } catch (InterruptedException e) {
316 //Potentially handle this, if it is expected to occur
317 e.printStackTrace();
318 }
319 }
320
321 //Accumulate per-thread statistics
322 readsOut+=pt.readsOutT;
323 basesOut+=pt.basesOutT;
324 success&=pt.success;
325 }
326
327 //Track whether any threads failed
328 if(!success){errorState=true;}
329 }
330
331 /*--------------------------------------------------------------*/
332 /*---------------- Inner Methods ----------------*/
333 /*--------------------------------------------------------------*/
334
335 private ArrayList<Read> loadData(ConcurrentReadInputStream cris){
336
337 ArrayList<Read> input=new ArrayList<Read>();
338
339 //Grab the first ListNum of reads
340 ListNum<Read> ln=cris.nextList();
341
342 //As long as there is a nonempty read list...
343 while(ln!=null && ln.size()>0){
344 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
345
346 for(Read r : ln){
347
348 //Optional filter criteria
349 if(true){
350 input.add(r);
351 }
352
353 //Increment counters
354 readsProcessed+=r.pairCount();
355 basesProcessed+=r.pairLength();
356 }
357
358 //Notify the input stream that the list was used
359 cris.returnList(ln);
360 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
361
362 //Fetch a new list
363 ln=cris.nextList();
364 }
365
366 //Notify the input stream that the final list was used
367 if(ln!=null){
368 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
369 }
370
371 return input;
372 }
373
374 /*--------------------------------------------------------------*/
375 /*---------------- Inner Classes ----------------*/
376 /*--------------------------------------------------------------*/
377
378 /** This class is static to prevent accidental writing to shared variables.
379 * It is safe to remove the static modifier. */
380 private static class ProcessThread extends Thread {
381
382 //Constructor
383 ProcessThread(final ConcurrentReadOutputStream ros_, final int tid_,
384 final long maxReads_, final AtomicLong nextReadID_){
385 ros=ros_;
386 tid=tid_;
387 maxReads=maxReads_;
388 atomicReadID=nextReadID_;
389 }
390
391 //Called by start()
392 @Override
393 public void run(){
394 //Do anything necessary prior to processing
395
396 //Process the reads
397 processInner();
398
399 //Do anything necessary after processing
400
401 //Indicate successful exit status
402 success=true;
403 }
404
405 /** Iterate through the reads */
406 void processInner(){
407
408 //As long as there is a nonempty read list...
409 for(long generated=atomicReadID.getAndAdd(readsPerList); generated<maxReads;
410 generated=atomicReadID.getAndAdd(readsPerList)){
411 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
412
413 long toGenerate=Tools.min(readsPerList, maxReads-generated);
414
415 ArrayList<Read> reads=generateList((int)toGenerate, generated);
416
417 //Output reads to the output stream
418 if(ros!=null){ros.add(reads, 0);}
419 }
420 }
421
422 /** Generate the next list of reads */
423 private ArrayList<Read> generateList(int toGenerate, long nextID){
424
425 //Grab the actual read list from the ListNum
426 final ArrayList<Read> reads=new ArrayList<Read>(toGenerate);
427
428 //Loop through each read in the list
429 for(int i=0; i<toGenerate; i++, nextID++){
430 Read r=generateRead(nextID);
431 readsOutT+=r.pairCount();
432 basesOutT+=r.length();
433 reads.add(r);
434 }
435
436 return reads;
437 }
438
439 /**
440 * Generate a single read.
441 */
442 private Read generateRead(final long nextID){
443 // Read r=new Read(null, null, nextID);
444 throw new RuntimeException("TODO: Implement this method."); //TODO
445 }
446
447 /** Number of reads retained by this thread */
448 protected long readsOutT=0;
449 /** Number of bases retained by this thread */
450 protected long basesOutT=0;
451
452 /** True only if this thread has completed successfully */
453 boolean success=false;
454
455 private final AtomicLong atomicReadID;
456 private final long maxReads;
457 private final int readsPerList=Shared.bufferLen();
458
459 /** Shared output stream */
460 private final ConcurrentReadOutputStream ros;
461 /** Thread ID */
462 final int tid;
463 }
464
465 /*--------------------------------------------------------------*/
466 /*---------------- Fields ----------------*/
467 /*--------------------------------------------------------------*/
468
469 /** Primary input file path */
470 private String in1=null;
471
472 /** Primary output file path */
473 private String out1=null;
474 /** Secondary output file path */
475 private String out2=null;
476
477 private String qfout1=null;
478 private String qfout2=null;
479
480 /** Override input file extension */
481 private String extin=null;
482 /** Override output file extension */
483 private String extout=null;
484
485 /*--------------------------------------------------------------*/
486
487 /** Number of reads processed */
488 protected long readsProcessed=0;
489 /** Number of bases processed */
490 protected long basesProcessed=0;
491
492 /** Number of reads retained */
493 protected long readsOut=0;
494 /** Number of bases retained */
495 protected long basesOut=0;
496
497 /** Quit after generating this many OUTPUT reads */
498 private long maxReads=-1;
499
500 /** Input read storage, if needed */
501 private ArrayList<Read> data=new ArrayList<Read>();
502
503 private AtomicLong nextReadID=new AtomicLong(0);
504
505 /*--------------------------------------------------------------*/
506 /*---------------- Final Fields ----------------*/
507 /*--------------------------------------------------------------*/
508
509 /** Primary input file */
510 private final FileFormat ffin1;
511
512 /** Primary output file */
513 private final FileFormat ffout1;
514 /** Secondary output file */
515 private final FileFormat ffout2;
516
517 /*--------------------------------------------------------------*/
518 /*---------------- Common Fields ----------------*/
519 /*--------------------------------------------------------------*/
520
521 /** Print status messages to this output stream */
522 private PrintStream outstream=System.err;
523 /** Print verbose messages */
524 public static boolean verbose=false;
525 /** True if an error was encountered */
526 public boolean errorState=false;
527 /** Overwrite existing output files */
528 private boolean overwrite=true;
529 /** Append to existing output files */
530 private boolean append=false;
531
532 }