Debian Codegraph @

current/template/A_SampleByteFileMT.java

raw symbols SCIP
1 package template;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.concurrent.locks.ReadWriteLock;
6 import java.util.concurrent.locks.ReentrantReadWriteLock;
7
8 import fileIO.ByteFile;
9 import fileIO.ByteStreamWriter;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import shared.Parse;
13 import shared.Parser;
14 import shared.PreParser;
15 import shared.Shared;
16 import shared.Timer;
17 import shared.Tools;
18 import structures.ByteBuilder;
19
20 /**
21 * This class models loading a text file,
22 * then spawning threads that each read a second text file.
23 *
24 * @author Brian Bushnell
25 * @date February 6, 2023
26 *
27 */
28 public class A_SampleByteFileMT implements Accumulator<A_SampleByteFileMT.ProcessThread> {
29
30 /*--------------------------------------------------------------*/
31 /*---------------- Initialization ----------------*/
32 /*--------------------------------------------------------------*/
33
34 /**
35 * Code entrance from the command line.
36 * @param args Command line arguments
37 */
38 public static void main(String[] args){
39 //Start a timer immediately upon code entrance.
40 Timer t=new Timer();
41
42 //Create an instance of this class
43 A_SampleByteFileMT x=new A_SampleByteFileMT(args);
44
45 //Run the object
46 x.process(t);
47
48 //Close the print stream if it was redirected
49 Shared.closeStream(x.outstream);
50 }
51
52 /**
53 * Constructor.
54 * @param args Command line arguments
55 */
56 public A_SampleByteFileMT(String[] args){
57
58 {//Preparse block for help, config files, and outstream
59 PreParser pp=new PreParser(args, getClass(), false);
60 args=pp.args;
61 outstream=pp.outstream;
62 }
63
64 //Set shared static variables prior to parsing
65 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
66 ReadWrite.setZipThreads(Shared.threads());
67
68 {//Parse the arguments
69 final Parser parser=parse(args);
70 overwrite=parser.overwrite;
71 append=parser.append;
72
73 in1=parser.in1;
74 in2=parser.in2;
75
76 out1=parser.out1;
77 }
78
79 validateParams();
80 fixExtensions(); //Add or remove .gz or .bz2 as needed
81 checkFileExistence(); //Ensure files can be read and written
82 checkStatics(); //Adjust file-related static fields as needed for this program
83
84 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, false);
85 ffoutInvalid=FileFormat.testOutput(outInvalid, FileFormat.TXT, null, true, overwrite, append, false);
86 ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
87 ffin2=FileFormat.testInput(in2, FileFormat.TXT, null, true, true);
88 }
89
90 /*--------------------------------------------------------------*/
91 /*---------------- Initialization Helpers ----------------*/
92 /*--------------------------------------------------------------*/
93
94 /** Parse arguments from the command line */
95 private Parser parse(String[] args){
96
97 //Create a parser object
98 Parser parser=new Parser();
99 // parser.out1="stdout";
100
101 //Set any necessary Parser defaults here
102 //parser.foo=bar;
103
104 //Parse each argument
105 for(int i=0; i<args.length; i++){
106 String arg=args[i];
107
108 //Break arguments into their constituent parts, in the form of "a=b"
109 String[] split=arg.split("=");
110 String a=split[0].toLowerCase();
111 String b=split.length>1 ? split[1] : null;
112 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
113
114 if(a.equals("verbose")){
115 verbose=Parse.parseBoolean(b);
116 }else if(a.equals("lines")){
117 maxLines=Long.parseLong(b);
118 if(maxLines<0){maxLines=Long.MAX_VALUE;}
119 }else if(a.equals("parse_flag_goes_here")){
120 long fake_variable=Parse.parseKMG(b);
121 //Set a variable here
122 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
123 //do nothing
124 }else{
125 outstream.println("Unknown parameter "+args[i]);
126 assert(false) : "Unknown parameter "+args[i];
127 throw new RuntimeException("Unknown parameter "+args[i]);
128 }
129 }
130
131 return parser;
132 }
133
134 /** Add or remove .gz or .bz2 as needed */
135 private void fixExtensions(){
136 in1=Tools.fixExtension(in1);
137 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
138 }
139
140 /** Ensure files can be read and written */
141 private void checkFileExistence(){
142 //Ensure output files can be written
143 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
144 outstream.println((out1==null)+", "+out1);
145 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out1+"\n");
146 }
147
148 //Ensure input files can be read
149 if(!Tools.testInputFiles(false, true, in1)){
150 throw new RuntimeException("\nCan't read some input files.\n");
151 }
152
153 //Ensure that no file was specified multiple times
154 if(!Tools.testForDuplicateFiles(true, in1, out1)){
155 throw new RuntimeException("\nSome file names were specified multiple times.\n");
156 }
157 }
158
159 /** Adjust file-related static fields as needed for this program */
160 private static void checkStatics(){
161 //Adjust the number of threads for input file reading
162 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
163 ByteFile.FORCE_MODE_BF2=true;
164 }
165
166 // if(!ByteFile.FORCE_MODE_BF2){
167 // ByteFile.FORCE_MODE_BF2=false;
168 // ByteFile.FORCE_MODE_BF1=true;
169 // }
170 }
171
172 /** Ensure parameter ranges are within bounds and required parameters are set */
173 private boolean validateParams(){
174 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
175 assert(false) : "TODO";
176 return true;
177 }
178
179 /*--------------------------------------------------------------*/
180 /*---------------- Outer Methods ----------------*/
181 /*--------------------------------------------------------------*/
182
183 /** Create read streams and process all data */
184 void process(Timer t){
185
186 //Reset counters
187 linesProcessed=linesOut=0;
188 bytesProcessed=bytesOut=0;
189
190 processFF1(ffin1);
191
192 //Process the reads in separate threads
193 spawnThreads(ffin2);
194
195 if(verbose){outstream.println("Finished; closing streams.");}
196
197
198 //Report timing and results
199 t.stop();
200
201 outstream.println(Tools.timeLinesBytesProcessed(t, linesProcessed, bytesProcessed, 8));
202
203 outstream.println();
204 outstream.println("Valid Lines: \t"+linesOut);
205 outstream.println("Invalid Lines: \t"+(linesProcessed-linesOut));
206
207 //Throw an exception of there was an error in a thread
208 if(errorState){
209 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
210 }
211 }
212
213 /*--------------------------------------------------------------*/
214 /*---------------- Thread Management ----------------*/
215 /*--------------------------------------------------------------*/
216
217 /** Spawn process threads */
218 private void spawnThreads(FileFormat ffin){
219
220 //Do anything necessary prior to processing
221
222 //Determine how many threads may be used
223 final int threads=Shared.threads();
224
225 //Fill a list with ProcessThreads
226 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
227 for(int i=0; i<threads; i++){
228 alpt.add(new ProcessThread(ffin, i));
229 }
230
231 //Start the threads and wait for them to finish
232 boolean success=ThreadWaiter.startAndWait(alpt, this);
233 errorState&=!success;
234
235 //Do anything necessary after processing
236
237 }
238
239 @Override
240 public final void accumulate(ProcessThread pt){
241 linesProcessed+=pt.linesProcessedT;
242 bytesProcessed+=pt.bytesProcessedT;
243 linesOut+=pt.linesOutT;
244 bytesOut+=pt.bytesOutT;
245 errorState|=(!pt.success);
246 errorState|=(pt.errorStateT);
247 }
248
249 @Override
250 public final boolean success(){return !errorState;}
251
252 /*--------------------------------------------------------------*/
253 /*---------------- Inner Methods ----------------*/
254 /*--------------------------------------------------------------*/
255
256 private void processFF1(FileFormat ff){
257 ByteFile bf=ByteFile.makeByteFile(ff);
258 ByteStreamWriter bsw=makeBSW(ffout1);
259 ByteStreamWriter bswInvalid=makeBSW(ffoutInvalid);
260
261 byte[] line=bf.nextLine();
262 ByteBuilder bb=new ByteBuilder();
263
264 while(line!=null){
265 if(line.length>0){
266 if(maxLines>0 && linesProcessed>=maxLines){break;}
267 linesProcessed++;
268 bytesProcessed+=(line.length+1);
269
270 final boolean valid=(line[0]!='#');
271
272 if(valid){
273 linesOut++;
274 bytesOut+=(line.length+1);
275 for(int i=0; i<line.length && line[i]!='\t'; i++){
276 bb.append(line[i]);
277 }
278 bb.nl();
279 bsw.print(bb.toBytes());
280 bb.clear();
281 }else{
282 if(bswInvalid!=null){
283 bswInvalid.println(line);
284 }
285 }
286 }
287 line=bf.nextLine();
288 }
289
290 errorState|=bf.close();
291 if(bsw!=null){errorState|=bsw.poisonAndWait();}
292 if(bswInvalid!=null){errorState|=bswInvalid.poisonAndWait();}
293 }
294
295 /*--------------------------------------------------------------*/
296 /*---------------- Inner Classes ----------------*/
297 /*--------------------------------------------------------------*/
298
299 /** This class is static to prevent accidental writing to shared variables.
300 * It is safe to remove the static modifier. */
301 static class ProcessThread extends Thread {
302
303 //Constructor
304 ProcessThread(final FileFormat ffin_, final int tid_){
305 ffin=ffin_;
306 tid=tid_;
307 }
308
309 //Called by start()
310 @Override
311 public void run(){
312 //Do anything necessary prior to processing
313
314 //Process the reads
315 processInner();
316
317 //Do anything necessary after processing
318
319 //Indicate successful exit status
320 success=true;
321 }
322
323 /** Iterate through the lines */
324 void processInner(){
325 ByteFile bf=ByteFile.makeByteFile(ffin);
326 byte[] line=bf.nextLine();
327 ByteBuilder bb=new ByteBuilder();
328
329 while(line!=null){
330 if(line.length>0){
331 if(maxLines>0 && linesProcessedT>=maxLines){break;}
332 linesProcessedT++;
333 bytesProcessedT+=(line.length+1);
334
335 final boolean valid=(line[0]!='#');
336
337 if(valid){
338 processLine(line);
339 }else{
340 //Do something else
341 }
342 }
343 line=bf.nextLine();
344 }
345 errorStateT|=bf.close();
346 }
347
348 /**
349 * Process a read or a read pair.
350 * @param r1 Read 1
351 * @param r2 Read 2 (may be null)
352 * @return True if the reads should be kept, false if they should be discarded.
353 */
354 boolean processLine(final byte[] line){
355 // throw new RuntimeException("TODO: Implement this method."); //TODO
356 assert(false);
357 return true;
358 }
359
360 /** Number of reads processed by this thread */
361 protected long linesProcessedT=0;
362 /** Number of bases processed by this thread */
363 protected long bytesProcessedT=0;
364
365 /** Number of reads retained by this thread */
366 protected long linesOutT=0;
367 /** Number of bases retained by this thread */
368 protected long bytesOutT=0;
369
370 protected boolean errorStateT=false;
371
372 /** True only if this thread has completed successfully */
373 boolean success=false;
374
375 /** Shared input stream */
376 private final FileFormat ffin;
377 /** Thread ID */
378 final int tid;
379 }
380
381 private static ByteStreamWriter makeBSW(FileFormat ff){
382 if(ff==null){return null;}
383 ByteStreamWriter bsw=new ByteStreamWriter(ff);
384 bsw.start();
385 return bsw;
386 }
387
388 /*--------------------------------------------------------------*/
389 /*---------------- Fields ----------------*/
390 /*--------------------------------------------------------------*/
391
392 /** Primary input file path */
393 private String in1=null;
394
395 /** Secondary input file path */
396 private String in2=null;
397
398 /** Primary output file path */
399 private String out1=null;
400
401 /** Junk output file path */
402 private String outInvalid=null;
403
404 /*--------------------------------------------------------------*/
405
406 private long linesProcessed=0;
407 private long linesOut=0;
408 private long bytesProcessed=0;
409 private long bytesOut=0;
410
411 private static long maxLines=Long.MAX_VALUE;//TODO: Static to compile; make non-static if threads are non-static
412
413 /*--------------------------------------------------------------*/
414 /*---------------- Final Fields ----------------*/
415 /*--------------------------------------------------------------*/
416
417 /** Input File */
418 private final FileFormat ffin1;
419
420 /** Secondary Input File */
421 private final FileFormat ffin2;
422 /** Output File */
423 private final FileFormat ffout1;
424 /** Optional Output File for Junk */
425 private final FileFormat ffoutInvalid;
426
427 @Override
428 public final ReadWriteLock rwlock() {return rwlock;}
429 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
430
431 /*--------------------------------------------------------------*/
432 /*---------------- Common Fields ----------------*/
433 /*--------------------------------------------------------------*/
434
435 /** Print status messages to this output stream */
436 private PrintStream outstream=System.err;
437 /** Print verbose messages */
438 public static boolean verbose=false;
439 /** True if an error was encountered */
440 public boolean errorState=false;
441 /** Overwrite existing output files */
442 private boolean overwrite=true;
443 /** Append to existing output files */
444 private boolean append=false;
445
446 }