Debian Codegraph @

current/aligner/AllToAll.java

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