Debian Codegraph @

current/sketch/CompareSSU.java

raw symbols SCIP
1 package sketch;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Map.Entry;
8 import java.util.concurrent.atomic.AtomicInteger;
9 import java.util.concurrent.locks.ReadWriteLock;
10 import java.util.concurrent.locks.ReentrantReadWriteLock;
11
12 import fileIO.ByteFile;
13 import fileIO.ByteStreamWriter;
14 import fileIO.FileFormat;
15 import fileIO.ReadWrite;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.FASTQ;
23 import stream.FastaReadInputStream;
24 import stream.Read;
25 import structures.ByteBuilder;
26 import structures.FloatList;
27 import tax.TaxNode;
28 import tax.TaxTree;
29 import template.Accumulator;
30 import template.ThreadWaiter;
31 import tracker.ReadStats;
32
33 /**
34 * Compares SSUs, all-to-all or fractional matrix.
35 *
36 * @author Brian Bushnell
37 * @date December 2, 2019
38 *
39 */
40 public class CompareSSU implements Accumulator<CompareSSU.ProcessThread> {
41
42 /*--------------------------------------------------------------*/
43 /*---------------- Initialization ----------------*/
44 /*--------------------------------------------------------------*/
45
46 /**
47 * Code entrance from the command line.
48 * @param args Command line arguments
49 */
50 public static void main(String[] args){
51 //Start a timer immediately upon code entrance.
52 Timer t=new Timer();
53
54 //Create an instance of this class
55 CompareSSU x=new CompareSSU(args);
56
57 //Run the object
58 x.process(t);
59
60 //Close the print stream if it was redirected
61 Shared.closeStream(x.outstream);
62 }
63
64 /**
65 * Constructor.
66 * @param args Command line arguments
67 */
68 public CompareSSU(String[] args){
69
70 {//Preparse block for help, config files, and outstream
71 PreParser pp=new PreParser(args, getClass(), false);
72 args=pp.args;
73 outstream=pp.outstream;
74 }
75
76 //Set shared static variables prior to parsing
77 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
78 ReadWrite.setZipThreads(Shared.threads());
79
80 {//Parse the arguments
81 final Parser parser=parse(args);
82 Parser.processQuality();
83
84 maxReads=parser.maxReads;
85 overwrite=ReadStats.overwrite=parser.overwrite;
86 append=ReadStats.append=parser.append;
87
88 in1=parser.in1;
89
90 out1=parser.out1;
91 }
92
93 validateParams();
94 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
95 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
96 checkFileExistence(); //Ensure files can be read and written
97 checkStatics(); //Adjust file-related static fields as needed for this program
98
99 //Create output FileFormat objects
100 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, ordered);
101
102 tree=(treeFile==null) ? null : TaxTree.loadTaxTree(treeFile, outstream, true, false);
103
104 SSUMap.r16SFile=in1;
105 if(SSUMap.r16SFile!=null){
106 SSUMap.load(outstream);
107 HashMap<Integer, byte[]> ssuMap=SSUMap.r16SMap;
108 ssuList=new ArrayList<Read>(ssuMap.size());
109 for(Entry<Integer, byte[]> e : ssuMap.entrySet()){
110 int id=e.getKey();
111 byte[] value=e.getValue();
112 if(value.length>=minlen && value.length<=maxlen){
113 Read r=new Read(value, null, id);//Sets numeric ID to TaxID.
114 if(maxns<0 || r.countNocalls()<=maxns){
115 ssuList.add(r);
116 }
117 }
118 }
119 Collections.shuffle(ssuList);
120 }
121 for(int i=0; i<idLists.length; i++){
122 idLists[i]=new FloatList();
123 }
124 }
125
126 /*--------------------------------------------------------------*/
127 /*---------------- Initialization Helpers ----------------*/
128 /*--------------------------------------------------------------*/
129
130 /** Parse arguments from the command line */
131 private Parser parse(String[] args){
132
133 //Create a parser object
134 Parser parser=new Parser();
135
136 //Set any necessary Parser defaults here
137 //parser.foo=bar;
138
139 //Parse each argument
140 for(int i=0; i<args.length; i++){
141 String arg=args[i];
142
143 //Break arguments into their constituent parts, in the form of "a=b"
144 String[] split=arg.split("=");
145 String a=split[0].toLowerCase();
146 String b=split.length>1 ? split[1] : null;
147 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
148
149 if(a.equals("verbose")){
150 verbose=Parse.parseBoolean(b);
151 }else if(a.equals("tree")){
152 treeFile=b;
153 }else if(a.equals("ordered")){
154 ordered=Parse.parseBoolean(b);
155 }else if(a.equals("ata") || a.equals("alltoall")){
156 allToAll=Parse.parseBoolean(b);
157 }else if(a.equals("store") || a.equals("storeresults")){
158 storeResults=Parse.parseBoolean(b);
159 }else if(a.equals("minlen") || a.equals("maxlength")){
160 minlen=Parse.parseIntKMG(b);
161 }else if(a.equals("maxlen") || a.equals("maxlength")){
162 maxlen=Parse.parseIntKMG(b);
163 }else if(a.equalsIgnoreCase("maxns")){
164 maxns=Parse.parseIntKMG(b);
165 }else if(a.equals("parse_flag_goes_here")){
166 long fake_variable=Parse.parseKMG(b);
167 //Set a variable here
168 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
169 //do nothing
170 }else{
171 outstream.println("Unknown parameter "+args[i]);
172 assert(false) : "Unknown parameter "+args[i];
173 }
174 }
175
176 return parser;
177 }
178
179 /** Ensure files can be read and written */
180 private void checkFileExistence(){
181 //Ensure output files can be written
182 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
183 outstream.println((out1==null)+", "+out1);
184 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out1+"\n");
185 }
186
187 //Ensure input files can be read
188 if(!Tools.testInputFiles(false, true, in1)){
189 throw new RuntimeException("\nCan't read some input files.\n");
190 }
191
192 //Ensure that no file was specified multiple times
193 if(!Tools.testForDuplicateFiles(true, in1, out1)){
194 throw new RuntimeException("\nSome file names were specified multiple times.\n");
195 }
196 }
197
198 /** Adjust file-related static fields as needed for this program */
199 private static void checkStatics(){
200 //Adjust the number of threads for input file reading
201 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
202 ByteFile.FORCE_MODE_BF2=true;
203 }
204
205 assert(FastaReadInputStream.settingsOK());
206 }
207
208 /** Ensure parameter ranges are within bounds and required parameters are set */
209 private boolean validateParams(){
210 return true;
211 }
212
213 /*--------------------------------------------------------------*/
214 /*---------------- Outer Methods ----------------*/
215 /*--------------------------------------------------------------*/
216
217 /** Create read streams and process all data */
218 void process(Timer t){
219
220 ByteStreamWriter bsw=makeBSW(ffout1);
221 if(bsw!=null){
222 bsw.forcePrint("#Level\tIdentity\tQueryID\tRefID\n");
223 }
224
225 //Reset counters
226 queriesProcessed=0;
227 comparisons=0;
228
229 //Process the reads in separate threads
230 spawnThreads(bsw);
231
232 if(verbose){outstream.println("Finished; closing streams.");}
233
234 //Close the read streams
235 if(bsw!=null){errorState|=bsw.poisonAndWait();}
236
237 {
238 ByteBuilder bb=new ByteBuilder();
239 bb.append("\nLevel \tCount\tMean"+(storeResults ? "\tMedian\t90%ile\t10%ile\tSTDev" : "")+"\n");
240 outstream.print(bb);
241 final int minlen="superkingdom".length();
242 for(int level=0; level<taxLevels; level++){
243 if(counts[level]>0){
244 bb.clear();
245 bb.append(TaxTree.levelToStringExtended(level));
246 while(bb.length()<minlen){bb.space();}
247 bb.tab().append(counts[level]).tab();
248 bb.append(sums[level]/counts[level]*100, 3);
249 if(storeResults){
250 FloatList list=idLists[level];
251 list.sort();
252 double stdev=list.stdev();
253 double median=list.median();
254 // double mode=list.mode();
255 double percent90=list.percentile(0.9f);
256 double percent10=list.percentile(0.1f);
257 bb.tab().append(median*100, 3).tab().append(percent90*100, 3).tab().append(percent10*100, 3).tab().append(stdev*100, 3);
258 }
259 bb.nl();
260 outstream.print(bb);
261 }
262 }
263 }
264
265 //Report timing and results
266 t.stop();
267 outstream.println();
268 outstream.println(Tools.timeQueriesComparisonsProcessed(t, queriesProcessed, comparisons, 8));
269
270 //Throw an exception of there was an error in a thread
271 if(errorState){
272 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
273 }
274 }
275
276 /*--------------------------------------------------------------*/
277 /*---------------- Thread Management ----------------*/
278 /*--------------------------------------------------------------*/
279
280 /** Spawn process threads */
281 private void spawnThreads(ByteStreamWriter bsw){
282
283 //Do anything necessary prior to processing
284
285 //Determine how many threads may be used
286 final int threads=Shared.threads();
287
288 //Fill a list with ProcessThreads
289 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
290 for(int i=0; i<threads; i++){
291 alpt.add(new ProcessThread(bsw, i, threads));
292 }
293
294 //Start the threads and wait for them to finish
295 boolean success=ThreadWaiter.startAndWait(alpt, this);
296 errorState&=!success;
297
298 //Do anything necessary after processing
299
300 }
301
302 @Override
303 public final void accumulate(ProcessThread pt){
304 queriesProcessed+=pt.querysProcessedT;
305 comparisons+=pt.comparisonsT;
306 errorState|=(!pt.success);
307
308 for(int i=0; i<taxLevels; i++){
309 idLists[i].addAll(pt.idListsT[i]);
310 counts[i]+=pt.countsT[i];
311 sums[i]+=pt.sumsT[i];
312 }
313 }
314
315 @Override
316 public final boolean success(){return !errorState;}
317
318 /*--------------------------------------------------------------*/
319 /*---------------- Inner Methods ----------------*/
320 /*--------------------------------------------------------------*/
321
322 private static ByteStreamWriter makeBSW(FileFormat ff){
323 if(ff==null){return null;}
324 ByteStreamWriter bsw=new ByteStreamWriter(ff);
325 bsw.start();
326 return bsw;
327 }
328
329 /*--------------------------------------------------------------*/
330 /*---------------- Inner Classes ----------------*/
331 /*--------------------------------------------------------------*/
332
333 /** This class is static to prevent accidental writing to shared variables.
334 * It is safe to remove the static modifier. */
335 class ProcessThread extends Thread {
336
337 //Constructor
338 ProcessThread(ByteStreamWriter bsw_, final int tid_, final int threads_){
339 bsw=bsw_;
340 threadID=tid_;
341 threads=threads_;
342 listCopy=new ArrayList<Read>(ssuList.size());
343 listCopy.addAll(ssuList);
344 for(int i=0; i<idListsT.length; i++){
345 idListsT[i]=new FloatList();
346 }
347 }
348
349 //Called by start()
350 @Override
351 public void run(){
352 //Do anything necessary prior to processing
353
354 //Process the reads
355 processInner();
356
357 //Do anything necessary after processing
358
359 //Indicate successful exit status
360 success=true;
361 }
362
363 /** Iterate through the reads */
364 void processInner(){
365 final long limit=Tools.min(ssuList.size(), (maxReads>0 ? maxReads : Integer.MAX_VALUE));
366
367 for(int num=next.getAndIncrement(); num<limit; num=next.getAndIncrement()){
368 Read r=ssuList.get(num);
369 processRead(r);
370 }
371 }
372
373 void processRead(Read query){
374 if(query.numericID<1){return;}//invalid TID
375 final int qid=(int)query.numericID;
376 if(tree.getNode(qid)==null) {return;}
377 if(querysProcessedT%5==0) {
378 Collections.shuffle(listCopy);
379 }
380 querysProcessedT++;
381
382 ByteBuilder bb=new ByteBuilder();
383
384 long seen=0;
385 for(Read ref :listCopy){
386 int rid=(int)ref.numericID;
387 if(rid!=qid && rid>0 && tree.getNode(rid)!=null){
388 int aid=tree.commonAncestor(qid, rid);
389 if(aid>0){
390 TaxNode tn=tree.getNode(aid);
391 if(tn.isRanked()){
392 int level=tn.levelExtended;
393 long mask=1L<<level;
394 if(allToAll || ((mask&printLevels)!=0 && (mask&seen)==0)){
395 seen|=mask;
396 float identity=compare(query, ref, level);
397 bb.append(TaxTree.levelToStringExtended(level)).tab().append(identity, 6);
398 bb.tab().append(qid).tab().append(rid).nl();
399 }
400 }
401 }
402 }
403 }
404 if(bsw!=null){
405 bsw.addJob(bb);
406 }
407 }
408
409 float compare(Read query, Read ref, int level){
410 comparisonsT++;
411 float identity=SketchObject.align(query.bases, ref.bases);
412 if(storeResults){idListsT[level].add(identity);}
413 countsT[level]++;
414 sumsT[level]+=identity;
415 return identity;
416 }
417
418 /** Number of reads processed by this thread */
419 protected long querysProcessedT=0;
420 /** Number of bases processed by this thread */
421 protected long comparisonsT=0;
422
423 /** True only if this thread has completed successfully */
424 boolean success=false;
425
426 /** Shared output stream */
427 private final ByteStreamWriter bsw;
428 /** Thread ID */
429 final int threadID;
430
431 final int threads;
432
433 ArrayList<Read> listCopy;
434
435 final FloatList[] idListsT=new FloatList[taxLevels];
436 long[] countsT=new long[taxLevels];
437 double[] sumsT=new double[taxLevels];
438 }
439
440 /*--------------------------------------------------------------*/
441 /*---------------- Fields ----------------*/
442 /*--------------------------------------------------------------*/
443
444 /** Primary input file path */
445 private String in1=null;
446
447 private String treeFile="auto";
448
449 /** Primary output file path */
450 private String out1=null;
451
452 public static ArrayList<Read> ssuList=null;
453
454 final static int taxLevels=TaxTree.numTaxLevelNamesExtended;
455 static final String[] printLevelsArray=new String[] {"strain", "species", "genus", "family", "order", "class", "phylum", "superkingdom", "life"};
456 static final long printLevels=makePrintLevels(printLevelsArray);
457
458 private final TaxTree tree;
459
460 private static final long makePrintLevels(String[] names){
461 long mask=0;
462 for(String s : names){
463 int level=TaxTree.stringToLevelExtended(s);
464 mask|=(1L<<level);
465 }
466 return mask;
467 }
468
469 private FloatList[] idLists=new FloatList[taxLevels];
470 private long[] counts=new long[taxLevels];
471 private double[] sums=new double[taxLevels];
472
473 private int minlen=0;
474 private int maxlen=Integer.MAX_VALUE;
475 private int maxns=-1;
476
477 /*--------------------------------------------------------------*/
478
479 /** Number of reads processed */
480 protected long queriesProcessed=0;
481 /** Number of bases processed */
482 protected long comparisons=0;
483
484 /** Quit after processing this many input reads; -1 means no limit */
485 private long maxReads=-1;
486
487 private AtomicInteger next=new AtomicInteger(0);
488
489 private boolean allToAll=false;
490 private boolean storeResults=false;
491
492 /*--------------------------------------------------------------*/
493 /*---------------- Final Fields ----------------*/
494 /*--------------------------------------------------------------*/
495
496 /** Primary output file */
497 private final FileFormat ffout1;
498
499 @Override
500 public final ReadWriteLock rwlock() {return rwlock;}
501 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
502
503 /*--------------------------------------------------------------*/
504 /*---------------- Common Fields ----------------*/
505 /*--------------------------------------------------------------*/
506
507 /** Print status messages to this output stream */
508 private PrintStream outstream=System.err;
509 /** Print verbose messages */
510 public static boolean verbose=false;
511 /** True if an error was encountered */
512 public boolean errorState=false;
513 /** Overwrite existing output files */
514 private boolean overwrite=true;
515 /** Append to existing output files */
516 private boolean append=false;
517 /** Reads are output in input order */
518 private boolean ordered=false;
519
520 }