Debian Codegraph @

current/bin/QuickBin.java

raw symbols SCIP
1 package bin;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.concurrent.locks.ReadWriteLock;
6 import java.util.concurrent.locks.ReentrantReadWriteLock;
7
8 import fileIO.ByteStreamWriter;
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 sketch.DisplayParams;
17 import sketch.Sketch;
18 import stream.ConcurrentReadInputStream;
19 import stream.ConcurrentReadOutputStream;
20 import stream.Read;
21 import structures.ByteBuilder;
22 import structures.IntHashMap;
23 import structures.IntLongHashMap;
24 import structures.ListNum;
25 import tax.TaxTree;
26 import template.Accumulator;
27 import template.ThreadWaiter;
28 import tracker.ReadStats;
29
30 /**
31 * Prototype for metagenome contig binning.
32 *
33 * @author Brian Bushnell
34 * @date December 6, 2024
35 *
36 */
37 public class QuickBin extends BinObject implements Accumulator<QuickBin.ProcessThread> {
38
39 /*--------------------------------------------------------------*/
40 /*---------------- Initialization ----------------*/
41 /*--------------------------------------------------------------*/
42
43 /**
44 * Code entrance from the command line.
45 * @param args Command line arguments
46 */
47 public static void main(String[] args){
48 //Start a timer immediately upon code entrance.
49 Timer t=new Timer();
50
51 //Create an instance of this class
52 QuickBin x=new QuickBin(args);
53
54 //Run the object
55 x.process(t);
56
57 //Close the print stream if it was redirected
58 Shared.closeStream(BinObject.outstream);
59 }
60
61 /**
62 * Constructor.
63 * @param args Command line arguments
64 */
65 public QuickBin(String[] args){
66
67 {//Preparse block for help, config files, and outstream
68 PreParser pp=new PreParser(args, getClass(), false);
69 args=pp.args;
70 outstream=pp.outstream;
71 }
72
73 //Set shared static variables prior to parsing
74 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
75 ReadWrite.setZipThreads(Shared.threads());
76
77 {//Parse the arguments
78 loader=new DataLoader(outstream);
79 binner=new Binner(outstream);
80 final Parser parser=parse(args);
81 Parser.processQuality();
82
83 overwrite=ReadStats.overwrite=parser.overwrite;
84 append=ReadStats.append=parser.append;
85
86 outPattern=parser.out1;
87 extout=parser.extout;
88 }
89
90 validateParams();
91 checkFileExistence(); //Ensure files can be read and written
92 loader.checkInput();
93
94 BinObject.tree=(sketchContigs || sketchClusters) ? loader.loadTree() : null;
95 sketcher=(sketchContigs || sketchClusters || sketchOutput) ? new BinSketcher(16, 2000) : null;
96 binner.sketcher=loader.sketcher=sketcher;
97 Sketch.defaultParams.format=DisplayParams.FORMAT_JSON;
98 KmerProb.load();
99 }
100
101 /*--------------------------------------------------------------*/
102 /*---------------- Initialization Helpers ----------------*/
103 /*--------------------------------------------------------------*/
104
105 /** Parse arguments from the command line */
106 private Parser parse(String[] args){
107 originalArgs=args.clone();
108
109 //Create a parser object
110 Parser parser=new Parser();
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("loud")){
128 loud=Parse.parseBoolean(b);
129 }
130
131 else if(a.equals("vectorout")){
132 vectorOut=b;
133 }else if(a.equalsIgnoreCase("emitTP")){
134 Oracle.emitTP=Parse.parseBoolean(b);
135 }else if(a.equalsIgnoreCase("emitTN")){
136 Oracle.emitTN=Parse.parseBoolean(b);
137 }else if(a.equalsIgnoreCase("emitFP")){
138 Oracle.emitFP=Parse.parseBoolean(b);
139 }else if(a.equalsIgnoreCase("emitFN")){
140 Oracle.emitFN=Parse.parseBoolean(b);
141 }else if(a.equalsIgnoreCase("minEmitSize")){
142 Oracle.minEmitSize=Parse.parseIntKMG(b);
143 }else if(a.equalsIgnoreCase("maxEmitSize")){
144 Oracle.maxEmitSize=Parse.parseIntKMG(b);
145 }else if(a.equalsIgnoreCase("negativeEmitProb")){
146 Oracle.negativeEmitProb=Double.parseDouble(b);
147 }
148
149 else if(a.equals("sizehist")){
150 sizeHist=b;
151 }else if(a.equals("report")){
152 report=b;
153 }else if(a.equalsIgnoreCase("writeChaff") || a.equalsIgnoreCase("chaff")){
154 writeChaff=Parse.parseBoolean(b);
155 }
156
157 else if(a.equals("clusterbytax") || a.equals("clusterbytaxid")){
158 clusterByTaxid=Parse.parseBoolean(b);
159 }else if(a.equals("clusterbytet") || a.equals("clusterbytetramer")){
160 clusterByTetramer=Parse.parseBoolean(b);
161 }else if(a.equals("refine") || a.equals("refineclusters")){
162 refineClusters=Parse.parseBoolean(b);
163 }else if(a.equals("residue") || a.equals("processresidue")){
164 processResidue=Parse.parseBoolean(b);
165 }else if(a.equals("purify") || a.equalsIgnoreCase("purifyClusters")){
166 purifyClusters=Parse.parseBoolean(b);
167 }else if(a.equals("fuse") || a.equalsIgnoreCase("fuseclusters")){
168 fuseClusters=Parse.parseBoolean(b);
169 }else if(a.equals("entropy") || a.equals("calcentropy")){
170 SpectraCounter.calcEntropy=Parse.parseBoolean(b);
171 }else if(a.equals("counttrimers") || a.equals("trimers")){
172 SpectraCounter.countTrimers=Parse.parseBoolean(b);
173 }else if(a.equals("strandedness") || a.equals("calcstrandedness")){
174 SpectraCounter.calcStrandedness=Parse.parseBoolean(b);
175 }else if(a.equals("entropyk")){
176 SpectraCounter.entropyK=Integer.parseInt(b);
177 }else if(a.equals("entropywindow")){
178 SpectraCounter.entropyWindow=Integer.parseInt(b);
179 }
180
181 else if(a.equalsIgnoreCase("sketchcontigs")){
182 sketchContigs=Parse.parseBoolean(b);
183 }else if(a.equalsIgnoreCase("sketchclusters") || a.equalsIgnoreCase("sketchbins")){
184 sketchClusters=Parse.parseBoolean(b);
185 }else if(a.equalsIgnoreCase("sketchoutput")){
186 sketchOutput=Parse.parseBoolean(b);
187 }else if(a.equalsIgnoreCase("sketch")){
188 sketchClusters=sketchContigs=sketchOutput=Parse.parseBoolean(b);
189 }else if(a.equalsIgnoreCase("density")){
190 float f=Float.parseFloat(b);
191 if(f<1) {sketchDensity=f;}
192 else {sketchDensity=1/f;}
193
194 }else if(a.equals("sketchbulk") || a.equalsIgnoreCase("sketchinbulk") || a.equals("bulk")){
195 sketchInBulk=Parse.parseBoolean(b);
196 }else if(a.equals("sketchsectionsize")){
197 BinSketcher.sectionSize=Tools.mid(1, Integer.parseInt(b), 10000);
198 }else if(a.equals("quant") || a.equals("quantize") || a.equals("quantizer")){
199 BinObject.setQuant(Tools.max(1, Integer.parseInt(b)));
200 }
201
202 else if(a.equals("mincluster") || a.equals("minclustersize") || a.equals("mcs")){
203 minClusterSize=Parse.parseIntKMG(b);
204 }else if(a.equals("mincontigs")){
205 minContigsPerCluster=Parse.parseIntKMG(b);
206 }else if(a.equals("validate") || a.equals("validation")){
207 validation=Parse.parseBoolean(b);
208 }else if(a.equalsIgnoreCase("followEdges1") || a.equals("e1")){
209 followEdge1Passes=(Tools.startsWithDigit(b) ? Integer.parseInt(b) :
210 Parse.parseBoolean(b) ? 4 : 0);
211 }else if(a.equalsIgnoreCase("followEdges2") || a.equals("e2") || a.equals("followEdges")){
212 followEdge2Passes=(Tools.startsWithDigit(b) ? Integer.parseInt(b) :
213 Parse.parseBoolean(b) ? 4 : 0);
214 }else if(a.equalsIgnoreCase("edgestringency1")){
215 edgeStringency1=Float.parseFloat(b);
216 }else if(a.equalsIgnoreCase("edgestringency2") || a.equalsIgnoreCase("edgestringency")){
217 edgeStringency2=Float.parseFloat(b);
218 }
219
220 else if(a.equalsIgnoreCase("xstrict") || a.equalsIgnoreCase("xs")){
221 strictnessMult=(Parse.parseBoolean(b) ? 0.6f : 1);
222 }else if(a.equalsIgnoreCase("ustrict") || a.equalsIgnoreCase("us")){
223 strictnessMult=(Parse.parseBoolean(b) ? 0.7f : 1);
224 }else if(a.equalsIgnoreCase("vstrict") || a.equalsIgnoreCase("vs")){
225 strictnessMult=(Parse.parseBoolean(b) ? 0.8f : 1);
226 }else if(a.equalsIgnoreCase("strict") || a.equalsIgnoreCase("s")){
227 strictnessMult=(Parse.parseBoolean(b) ? 0.9f : 1);
228 }else if(a.equalsIgnoreCase("normal") || a.equalsIgnoreCase("n")){
229 strictnessMult=(Parse.parseBoolean(b) ? 1 : 1);
230 }else if(a.equalsIgnoreCase("loose") || a.equalsIgnoreCase("l")){
231 strictnessMult=(Parse.parseBoolean(b) ? 1.125f : 1);
232 }else if(a.equalsIgnoreCase("vloose") || a.equalsIgnoreCase("vl")){
233 strictnessMult=(Parse.parseBoolean(b) ? 1.25f : 1);
234 }else if(a.equalsIgnoreCase("uloose") || a.equalsIgnoreCase("ul")){
235 strictnessMult=(Parse.parseBoolean(b) ? 1.375f : 1);
236 }else if(a.equalsIgnoreCase("xloose") || a.equalsIgnoreCase("xl")){
237 strictnessMult=(Parse.parseBoolean(b) ? 1.5f : 1);
238 }else if(a.equalsIgnoreCase("strictness")){
239 strictnessMult=Float.parseFloat(b);
240 }
241
242 else if(a.equals("covout") || a.equals("outcov")) {
243 covOut=b;
244 }
245
246 else if(a.equals("parse_flag_goes_here")){
247 long fake_variable=Parse.parseKMG(b);
248 //Set a variable here
249 }else if(binner.parse(arg, a, b)){
250 //do nothing
251 }else if(Key.parse(arg, a, b)){
252 //do nothing
253 }else if(SimilarityMeasures.parse(arg, a, b)){
254 //do nothing
255 }else if(loader.parse(arg, a, b)){
256 //do nothing
257 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
258 //do nothing
259 }else{
260 outstream.println("Unknown parameter "+args[i]);
261 assert(false) : "Unknown parameter "+args[i];
262 }
263 }
264
265 return parser;
266 }
267
268 private void reprocessArgs() {
269 for(int i=0; i<originalArgs.length; i++){
270 String arg=originalArgs[i];
271
272 //Break arguments into their constituent parts, in the form of "a=b"
273 String[] split=arg.split("=");
274 String a=split[0].toLowerCase();
275 String b=split.length>1 ? split[1] : null;
276 if(b!=null){
277 binner.parse(arg, a, b);
278 loader.parse(arg, a, b);
279 }
280 }
281 if(net0small!=null) {net0small.cutoff=Binner.netCutoff_small;}
282 if(net0small!=null) {net0mid.cutoff=Binner.netCutoff_mid;}
283 if(net0small!=null) {net0large.cutoff=Binner.netCutoff_large;}
284 binner.printThresholds();
285 }
286
287 /** Ensure parameter ranges are within bounds and required parameters are set */
288 private boolean validateParams(){
289 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
290 // assert(false) : "TODO";
291 return true;
292 }
293
294 /** Ensure files can be read and written */
295 private void checkFileExistence(){
296 //Ensure output files can be written
297 String o=(outPattern!=null && outPattern.indexOf('%')<0) ? outPattern : null;
298 if(!Tools.testOutputFiles(overwrite, append, false, o)){
299 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+o+"\n");
300 }
301 }
302
303 /*--------------------------------------------------------------*/
304 /*---------------- Outer Methods ----------------*/
305 /*--------------------------------------------------------------*/
306
307 /** Create read streams and process all data */
308 void process(Timer t){
309
310 Timer t2=new Timer();
311
312 contigList=loader.loadData();
313 assert(isValid(contigList, false));
314 if(covOut!=null) {DataLoader.writeCov(covOut, contigList, loader.numDepths, outstream);}
315 loader.trimEdges(contigList, Binner.maxEdges, Binner.minEdgeWeight, Binner.reciprocalEdges);
316 // System.err.println("Thresholds:");
317 // binner.printThresholds();
318 binner.setSamples(loader.numDepths, strictnessMult);
319 // System.err.println("Thresholds:");
320 // binner.printThresholds();
321 reprocessArgs();
322 // System.err.println("Thresholds:");
323 // binner.printThresholds();
324 // assert(false);
325
326 IntLongHashMap sizeMap=loader.sizeMap;
327 // @SuppressWarnings("unchecked")
328 // ArrayList<? extends Bin> bins=(ArrayList<Contig>) contigList.clone();
329 // if(clusterByTaxid) {
330 // bins=binner.clusterByTaxid(bins);
331 // }
332
333 if(vectorOut!=null) {
334 Oracle.bsw=ByteStreamWriter.makeBSW(vectorOut, overwrite, append, true);
335 // Oracle.bsw.println(Oracle.header());
336 }
337
338 Timer ct=new Timer(outstream);
339 ArrayList<Bin> binList=null;
340 if(followEdge1Passes>0 && loader.makePairGraph) {
341 t2.start();
342 outstream.println("Following Edges:");
343 assert(isValid(contigList, false));
344 int sum=0;
345 Oracle oracle=new Oracle(edgeStringency1, 2);
346 long merges=binner.followEdges(contigList, contigList, oracle);
347 sum+=merges;
348 for(int i=1; i<followEdge1Passes && merges>0; i++) {
349 binList=Binner.toBinList(contigList, 0);
350 merges=binner.followEdges(contigList, binList, oracle);
351 sum+=merges;
352 }
353 assert(binList==null ? isValid(contigList, true) : isValid(binList, false));
354 if(merges>0) {
355 binList=Binner.toBinList(contigList, 0);
356 }
357 t2.stop("Merged "+sum+" bins: ");
358 fastComparisonsEdge+=oracle.fastComparisons;
359 slowComparisonsEdge+=oracle.slowComparisons;
360 netComparisonsEdge+=oracle.netComparisons;
361 }
362
363 long fastComp=0, slowComp=0;
364 BinMap binMap=binner.makeBinMap(contigList, binList);
365 assert(binMap.isValid());
366 binList=null;
367 fastComparisonsCreate+=(binner.fastComparisons.get()-fastComp);
368 slowComparisonsCreate+=(binner.slowComparisons.get()-slowComp);
369
370 if(refineClusters) {
371 fastComp=binner.fastComparisons.get();
372 slowComp=binner.slowComparisons.get();
373 binner.refineBinMap(binMap);
374 assert(binMap.isValid());
375 fastComparisonsRefine+=(binner.fastComparisons.get()-fastComp);
376 slowComparisonsRefine+=(binner.slowComparisons.get()-slowComp);
377 }
378
379 if(followEdge2Passes>0 && loader.makePairGraph) {
380 fastComp=(binner.fastComparisons.get());
381 slowComp=(binner.slowComparisons.get());
382 t2.start();
383 outstream.println("Following Edges:");
384 long merges=100, sum=0;
385 assert(isValid(contigList, true));
386 Oracle oracle=new Oracle(edgeStringency2, 2);
387 for(int i=0; i<followEdge2Passes && merges>1; i++) {
388 // assert(isValid(contigList, true));
389 binList=Binner.toBinList(contigList, 0);
390 // assert(isValid(binList, false));
391 merges=binner.followEdges(contigList, binList, oracle);
392 sum+=merges;
393 }
394 t2.stop("Merged "+sum+" bins: ");
395 if(sum>0) {
396 binMap.clear(true);
397 binList=Binner.toBinList(contigList, 0);
398 assert(isValid(binList, false));
399 binMap.addAll(binList, Binner.minSizeToMerge);
400 }
401 fastComparisonsEdge+=(binner.fastComparisons.get()-fastComp);
402 slowComparisonsEdge+=(binner.slowComparisons.get()-slowComp);
403 }
404
405 if(processResidue) {
406 fastComp=(binner.fastComparisons.get());
407 slowComp=(binner.slowComparisons.get());
408 int removedResidue=binner.processResidue(binMap, Binner.residueStringency,
409 TaxTree.SPECIES, true, true, binner.residueRange);
410 fastComparisonsResidue+=(binner.fastComparisons.get()-fastComp);
411 slowComparisonsResidue+=(binner.slowComparisons.get()-slowComp);
412 if(removedResidue>1) {
413 fastComp=binner.fastComparisons.get();
414 slowComp=binner.slowComparisons.get();
415 //it would be best to have a bigger compare size limit for residue prior to this
416 //Possibly do this in 2 passes, with range +0 and +2
417 if(binner.runPassF) {
418 int removedThisPhase=binner.refinePhase(binMap,
419 "f", 0.9f, -1, true, true, binner.baseRange, Binner.minSizeToMerge, binner.basePasses+0);
420 }
421 if(binner.runPassG) {
422 int removedThisPhase=binner.refinePhase(binMap,
423 "g", 1.0f, -1, true, true, binner.baseRange+2, Binner.minSizeToMerge, binner.basePasses+1);
424 }
425 }
426 fastComparisonsRefine+=(binner.fastComparisons.get()-fastComp);
427 slowComparisonsRefine+=(binner.slowComparisons.get()-slowComp);
428 }
429
430 if(fuseClusters) {
431 long fused=99999, total=0;
432 for(int i=0; i<4 && fused>1; i++) {
433 ArrayList<Bin> bins=Binner.toBinList(contigList, Binner.fuseLowerLimit);
434 Collections.sort(bins);
435 fused=binner.fuse(contigList, bins, Binner.fuseStringency);
436 total+=fused;
437 }
438 if(total>0) {
439 binMap.clear(true);
440 binList=Binner.toBinList(contigList, 0);
441 assert(isValid(binList, false));
442 binMap.addAll(binList, Binner.minSizeToMerge);
443 }
444 System.err.println("Fused "+total+" clusters.");
445 }
446
447 if(Oracle.bsw!=null) {
448 Oracle.bsw.poisonAndWait();
449 Oracle.bsw=null;
450 }
451
452 if(purifyClusters) {
453 t2.start();
454 outstream.println("Purifying clusters:");
455 fastComp=(binner.fastComparisons.get());
456 slowComp=(binner.slowComparisons.get());
457 int purified=binner.purify(binMap,
458 Binner.purifyStringency, binner.baseRange+4, minClusterSize, Tools.min(minClusterSize/2, 20000));
459 fastComparisonsPurify+=(binner.fastComparisons.get()-fastComp);
460 slowComparisonsPurify+=(binner.slowComparisons.get()-slowComp);
461 t2.stop("Removed "+purified+" contigs: ");
462 }
463 ct.stop();
464
465 t2.stop();
466 ArrayList<Cluster> bins=binMap.toList(true);
467 Collections.sort(bins);
468 // assert(isValid(bins, false));
469
470 if(sketchOutput) {
471 System.err.println("Sketching output.");
472 sketcher.sketch(bins, true);
473 }
474
475 long cleanBins=0, cleanSize=0, partialCleanSize=0;
476 long contamBins=0, contamSize=0, partialContamSize=0;
477 double contamScore=0;
478 double compltScore=0;
479 long sizeOverLimit=0, binsOverLimit=0;
480 long contigsOverLimit=0, badContigsOverLimit=0;
481 IntHashMap tidBins=new IntHashMap();
482
483 // t2.start();
484 // System.err.print("Calculating statistics.");
485 for(Bin b : bins) {
486 if(b.size()<minClusterSize) {continue;}
487 if(validation) {b.calcContam(sizeMap);}
488 long contam=(int)(b.size()*b.contam);
489 compltScore+=((b.size()-contam)*b.completeness);
490 contamScore+=(b.size()*b.contam);
491 if(contam>0) {
492 contamBins++;
493 contamSize+=b.size();
494 partialContamSize+=contam;
495 partialCleanSize+=(b.size()-contam);
496 }else {
497 cleanBins++;
498 cleanSize+=b.size();
499 }
500 if(b.size()>=minClusterSize) {
501 sizeOverLimit+=b.size();
502 binsOverLimit++;
503 contigsOverLimit+=b.numContigs();
504 if(b.labelTaxid>0) {tidBins.increment(b.labelTaxid);}
505 badContigsOverLimit+=b.badContigs;
506 }
507 }
508 // t2.stopAndPrint();
509
510 // System.err.println("\nFinal clusters:");
511 // for(int i=0; i<bins.size(); i++) {
512 // Bin a=bins.get(i);
513 // if(a.size()>=4000 || a.numContigs()>1){
514 // System.out.println(a.toBytes());
515 // }
516 // if(a.size()<1000 || i>=4) {break;}
517 // }
518
519 if(report!=null) {GradeBins.printClusterReport(bins, minClusterSize, report);}
520 outputClusters(outPattern, bins, minClusterSize, minContigsPerCluster);
521
522 if(verbose){outstream.println("Finished; closing streams.");}
523
524 //Report timing and results
525 outstream.println();
526 t.stopAndPrint();
527
528 long totalComp=binner.slowComparisons.get()+slowComparisonsEdge;
529 fastComp=binner.fastComparisons.get()+fastComparisonsEdge;
530 long netComp=binner.netComparisons.get()+netComparisonsEdge;
531 float scps=(totalComp/(float)ct.elapsed)*1000000000;
532 float fcps=(fastComp/(float)ct.elapsed)*1000000000;
533 float ncps=(netComp/(float)ct.elapsed)*1000000000;
534 if(loud) {
535 outstream.println("Initial Fast Comparisons: \t"+fastComparisonsCreate);
536 outstream.println("Initial Slow Comparisons: \t"+slowComparisonsCreate);
537 outstream.println("Grid Fast Comparisons: \t"+fastComparisonsRefine);
538 outstream.println("Grid Slow Comparisons: \t"+slowComparisonsRefine);
539 outstream.println("Edge Fast Comparisons: \t"+fastComparisonsEdge);
540 outstream.println("Edge Slow Comparisons: \t"+slowComparisonsEdge);
541 outstream.println("Residue Fast Comparisons: \t"+fastComparisonsResidue);
542 outstream.println("Residue Slow Comparisons: \t"+slowComparisonsResidue);
543 outstream.println("Purify Fast Comparisons: \t"+fastComparisonsPurify);
544 outstream.println("Purify Slow Comparisons: \t"+slowComparisonsPurify);
545 }
546 outstream.println("Total Fast Comparisons: \t"+fastComp+" \t"+Tools.padKMB((long)fcps, 0)+" cps");
547 outstream.println("Total Slow Comparisons: \t"+totalComp+" \t"+Tools.padKMB((long)scps, 0)+" cps");
548 outstream.println("Total Net Comparisons: \t"+netComp+" \t"+Tools.padKMB((long)ncps, 0)+" cps");
549 outstream.println();
550
551 if(validation && loud) {
552 outstream.println(formatString("Good Merges Follow", 29, binner.goodMergesFollow, binner.badMergesFollow));
553 outstream.println(formatString("Bad Merges Follow", 29, binner.badMergesFollow, binner.goodMergesFollow));
554 outstream.println(formatString("Bad Merge Size Follow", 29, binner.badMergeSizeFollow, binner.goodMergeSizeFollow));
555 outstream.println(formatString("Good Merges Create", 29, binner.goodMergesCreate, binner.badMergesCreate));
556 outstream.println(formatString("Bad Merges Create", 29, binner.badMergesCreate, binner.goodMergesCreate));
557 outstream.println(formatString("Bad Merge Size Create", 29, binner.badMergeSizeCreate, binner.goodMergeSizeCreate));
558 outstream.println(formatString("Good Merges Refine", 29, binner.goodMergesRefine, binner.badMergesRefine));
559 outstream.println(formatString("Bad Merges Refine", 29, binner.badMergesRefine, binner.goodMergesRefine));
560 outstream.println(formatString("Bad Merge Size Refine", 29, binner.badMergeSizeRefine, binner.goodMergeSizeRefine));
561 outstream.println(formatString("Good Merges Residue", 29, binner.goodMergesResidue, binner.badMergesResidue));
562 outstream.println(formatString("Bad Merges Residue", 29, binner.badMergesResidue, binner.goodMergesResidue));
563 outstream.println(formatString("Bad Merge Size Residue", 29, binner.badMergeSizeResidue, binner.goodMergeSizeResidue));
564 outstream.println();
565 outstream.println(formatString("Clean Bins", 29, cleanBins, contamBins));
566 outstream.println(formatString("Dirty Bins", 29, contamBins, cleanBins));
567 outstream.println(formatString("Clean Bin Bases", 29, cleanSize, contamSize));
568 outstream.println(formatString("Dirty Bin Bases", 29, contamSize, cleanSize));
569 outstream.println(formatString("Tainted Bases", 29, partialCleanSize, cleanSize+contamSize-partialCleanSize));
570 outstream.println(formatString("Contam Bases", 29, partialContamSize, cleanSize+contamSize-partialContamSize));
571 outstream.println();
572 }
573
574 // outstream.println("Sequence Recovery: \t"+
575 // String.format("%.3f", sizeOverLimit*100.0/loader.basesLoaded));
576 // outstream.println("Contig Recovery: \t"+
577 // String.format("%.3f", contigsOverLimit*100.0/loader.contigsLoaded));
578 //
579 // if(validation) {
580 // outstream.println("Bad Contigs: \t"+
581 // String.format("%.3f", badContigsOverLimit*100.0/contigsOverLimit));
582 // outstream.println("Genomes Represented: \t"+
583 // String.format("%.3f", (tidBins.size())*100.0/sizeMap.size()));
584 // outstream.println("Completeness Score: \t"+
585 // String.format("%.3f", 100*compltScore/loader.basesLoaded));
586 // outstream.println("Contamination Score: \t"+
587 // String.format("%.4f", 100*contamScore/loader.basesLoaded));
588 // }
589 // outstream.println();
590 //
591
592 ArrayList<BinStats> stats=GradeBins.toStats(bins, minClusterSize);
593
594 if(loud && validation) {
595 outstream.println();
596 GradeBins.printCleanDirty(stats);
597 }
598
599 GradeBins.printL90(stats, loader.basesLoaded);
600
601 outstream.println();
602 GradeBins.printScore(stats, loader.basesLoaded, loader.contigsLoaded, sizeMap.size(), validation);
603
604 if(validation) {
605 outstream.println();
606 GradeBins.printBinQuality(stats, minClusterSize, outstream);
607 }
608
609 //Throw an exception of there was an error in a thread
610 if(errorState){
611 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
612 }
613 }
614
615 static String formatString(String term, int len, long a, long b) {
616 float pct=a*100f/(a+b);
617 while(term.length()<len) {term=term+" ";}
618 String apad=Long.toString(a);
619 while(apad.length()<12) {apad+=" ";}
620 return(term+"\t"+apad+"\t"+String.format("%.3f%%", pct));
621 }
622
623 private void outputClusters(String pattern, ArrayList<? extends Bin> clusters, long minBases, int minContigs) {
624 // if(pattern==null) {return;}
625 if(pattern!=null) {
626 if(!pattern.contains(".") && !pattern.contains("%")) {
627 if(!pattern.endsWith("/")) {pattern=pattern+"/";}
628 pattern=pattern+"bin_%.fa";
629 }
630 outstream.println("Writing clusters to "+pattern);
631 }
632 long sizeOverLimit=0;
633 if(pattern!=null && pattern.indexOf('%')>=0) {
634
635 ByteStreamWriter chaff=null;
636 if(writeChaff) {
637 chaff=ByteStreamWriter.makeBSW(pattern.replace("%", "chaff"), overwrite, append, true);
638 }
639
640 final ByteBuilder bb=new ByteBuilder(8192);
641 for(int i=0; i<clusters.size(); i++) {
642 Bin a=clusters.get(i);
643 if(a.size()>=minBases && a.numContigs()>=minContigs) {
644 String fname=pattern.replace("%", Integer.toString(i));
645 final ByteStreamWriter bsw=ByteStreamWriter.makeBSW(fname, overwrite, append, true);
646 printBin(a, bsw, bb, -1);
647 bsw.poison();
648 clustersWritten++;
649 contigsWritten+=a.numContigs();
650 basesWritten+=a.size();
651 }else {
652 printBin(a, chaff, bb, i+1);
653 }
654 }
655 if(chaff!=null) {chaff.poisonAndWait();}
656 }else {
657 final ByteBuilder bb=new ByteBuilder(8192);
658 final ByteStreamWriter bsw=ByteStreamWriter.makeBSW(pattern, overwrite, append, true);
659 for(int i=0; i<clusters.size(); i++) {
660 Bin a=clusters.get(i);
661 printBin(a, bsw, bb, i+1);
662 clustersWritten++;
663 contigsWritten+=a.numContigs();
664 basesWritten+=a.size();
665 }
666 if(bsw!=null) {bsw.poisonAndWait();}
667 }
668 float cpct=contigsWritten*100f/loader.contigsLoaded;
669 float bpct=basesWritten*100f/loader.basesLoaded;
670 if(loud) {
671 outstream.println("\nMetric \t In\t Out\tPercent");
672 outstream.println("Clusters \t"+Tools.padLeft(0, 10)+"\t"+Tools.padLeft(clustersWritten, 10));
673 outstream.println("Contigs \t"+Tools.padLeft(loader.contigsLoaded, 10)+"\t"+
674 Tools.padLeft(contigsWritten, 10)+"\t"+Tools.format("%.2f%%", cpct));
675 outstream.println("Bases \t"+Tools.padLeft(loader.basesLoaded, 10)+"\t"+
676 Tools.padLeft(basesWritten, 10)+"\t"+Tools.format("%.2f%%", bpct));
677 }
678 if(sizeHist!=null) {
679 final ByteStreamWriter bsw=ByteStreamWriter.makeBSW(sizeHist, overwrite, append, true);
680 bsw.print("#Size\tGood\tBad\n");
681 for(int i=0; i<binner.goodMergeSize.length; i++) {
682 long size=1L<<i;
683 bsw.print(size).tab().print(binner.goodMergeSize[i]).tab().print(binner.badMergeSize[i]).nl();
684 }
685 bsw.poisonAndWait();
686 }
687 }
688
689 private void printBin(Bin a, ByteStreamWriter bsw, ByteBuilder bb, int id) {
690 if(a.isCluster()) {printCluster((Cluster)a, bsw, bb, id);}
691 else {printContig((Contig)a, bsw, bb, id);}
692 }
693
694 private void printCluster(Cluster a, ByteStreamWriter bsw, ByteBuilder bb, int id) {
695 ArrayList<Contig> contigs=a.contigs;
696 Collections.sort(contigs);
697 for(Contig c : contigs) {
698 c.appendTo(bb, id);
699 if(bb.length>4096) {
700 if(bsw!=null) {bsw.print(bb);}
701 bb.clear();
702 }
703 }
704 if(bsw!=null && !bb.isEmpty()) {bsw.print(bb);}
705 bb.clear();
706 }
707
708 private void printContig(Contig c, ByteStreamWriter bsw, ByteBuilder bb, int id) {
709 c.appendTo(bb, id);
710 if(bsw!=null && !bb.isEmpty()) {bsw.print(bb);}
711 bb.clear();
712 }
713
714 // private ConcurrentReadInputStream makeCris(FileFormat ff1, FileFormat ff2){
715 // ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2);
716 // cris.start(); //Start the stream
717 // if(verbose){outstream.println("Started cris");}
718 // boolean paired=cris.paired();
719 //// if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
720 // return cris;
721 // }
722 //
723 // private ConcurrentReadOutputStream makeCros(String fname){
724 // if(fname==null) {return null;}
725 // FileFormat ff=FileFormat.testOutput(fname, FileFormat.FASTA, null, true, overwrite, append, false);
726 //
727 // //Select output buffer size based on whether it needs to be ordered
728 // final int buff=8;
729 //
730 // final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ff, null, buff, null, false);
731 // ros.start(); //Start the stream
732 // return ros;
733 // }
734
735 /*--------------------------------------------------------------*/
736 /*---------------- Inner Methods ----------------*/
737 /*--------------------------------------------------------------*/
738
739
740
741 /*--------------------------------------------------------------*/
742 /*---------------- Thread Management ----------------*/
743 /*--------------------------------------------------------------*/
744
745 /** Spawn process threads */
746 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
747
748 //Do anything necessary prior to processing
749
750 //Determine how many threads may be used
751 final int threads=Shared.threads();
752
753 //Fill a list with ProcessThreads
754 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
755 for(int i=0; i<threads; i++){
756 alpt.add(new ProcessThread(cris, ros, i));
757 }
758
759 //Start the threads and wait for them to finish
760 boolean success=ThreadWaiter.startAndWait(alpt, this);
761 errorState&=!success;
762
763 //Do anything necessary after processing
764
765 }
766
767 @Override
768 public final void accumulate(ProcessThread pt){
769 synchronized(pt) {
770 // readsProcessed+=pt.readsProcessedT;
771 // basesProcessed+=pt.basesProcessedT;
772 // readsOut+=pt.readsOutT;
773 // basesOut+=pt.basesOutT;
774 errorState|=(!pt.success);
775 }
776 }
777
778 @Override
779 public final boolean success(){return !errorState;}
780
781 /*--------------------------------------------------------------*/
782 /*---------------- Inner Classes ----------------*/
783 /*--------------------------------------------------------------*/
784
785 /** This class is static to prevent accidental writing to shared variables.
786 * It is safe to remove the static modifier. */
787 static class ProcessThread extends Thread {
788
789 //Constructor
790 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_){
791 cris=cris_;
792 ros=ros_;
793 tid=tid_;
794 }
795
796 //Called by start()
797 @Override
798 public void run(){
799 //Do anything necessary prior to processing
800
801 //Process the reads
802 processInner();
803
804 //Do anything necessary after processing
805
806 //Indicate successful exit status
807 success=true;
808 }
809
810 /** Iterate through the reads */
811 void processInner(){
812
813 //Grab the first ListNum of reads
814 ListNum<Read> ln=cris.nextList();
815
816 //Check to ensure pairing is as expected
817 if(ln!=null && !ln.isEmpty()){
818 Read r=ln.get(0);
819 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
820 }
821
822 //As long as there is a nonempty read list...
823 while(ln!=null && ln.size()>0){
824 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
825
826 processList(ln);
827
828 //Notify the input stream that the list was used
829 cris.returnList(ln);
830 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
831
832 //Fetch a new list
833 ln=cris.nextList();
834 }
835
836 //Notify the input stream that the final list was used
837 if(ln!=null){
838 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
839 }
840 }
841
842 void processList(ListNum<Read> ln){
843
844 //Grab the actual read list from the ListNum
845 final ArrayList<Read> reads=ln.list;
846
847 //Loop through each read in the list
848 for(int idx=0; idx<reads.size(); idx++){
849 final Read r1=reads.get(idx);
850 final Read r2=r1.mate;
851
852 //Validate reads in worker threads
853 if(!r1.validated()){r1.validate(true);}
854 if(r2!=null && !r2.validated()){r2.validate(true);}
855
856 //Track the initial length for statistics
857 final int initialLength1=r1.length();
858 final int initialLength2=r1.mateLength();
859
860 //Increment counters
861 readsProcessedT+=r1.pairCount();
862 basesProcessedT+=initialLength1+initialLength2;
863
864 {
865 //Reads are processed in this block.
866 boolean keep=processReadPair(r1, r2);
867
868 if(!keep){reads.set(idx, null);}
869 else{
870 readsOutT+=r1.pairCount();
871 basesOutT+=r1.pairLength();
872 }
873 }
874 }
875
876 //Output reads to the output stream
877 if(ros!=null){ros.add(reads, ln.id);}
878 }
879
880 /**
881 * Process a read or a read pair.
882 * @param r1 Read 1
883 * @param r2 Read 2 (may be null)
884 * @return True if the reads should be kept, false if they should be discarded.
885 */
886 boolean processReadPair(final Read r1, final Read r2){
887 throw new RuntimeException("TODO: Implement this method."); //TODO
888 // return true;
889 }
890
891 /** Number of reads processed by this thread */
892 protected long readsProcessedT=0;
893 /** Number of bases processed by this thread */
894 protected long basesProcessedT=0;
895
896 /** Number of reads retained by this thread */
897 protected long readsOutT=0;
898 /** Number of bases retained by this thread */
899 protected long basesOutT=0;
900
901 /** True only if this thread has completed successfully */
902 boolean success=false;
903
904 /** Shared input stream */
905 private final ConcurrentReadInputStream cris;
906 /** Shared output stream */
907 private final ConcurrentReadOutputStream ros;
908 /** Thread ID */
909 final int tid;
910 }
911
912 /*--------------------------------------------------------------*/
913 /*---------------- Fields ----------------*/
914 /*--------------------------------------------------------------*/
915
916 /** Primary output file path; should contain % symbol for bins */
917 private String outPattern=null;
918 private boolean writeChaff=false;
919
920 /** Override output file extension */
921 private String extout=null;
922
923 private String covOut=null;
924 private String vectorOut=null;
925 private String sizeHist=null;
926 private String report=null;
927
928 private ArrayList<Contig> contigList;
929
930 boolean clusterByTaxid=false;
931 boolean clusterByTetramer=true;
932 boolean refineClusters=true;
933 boolean processResidue=true;
934 boolean purifyClusters=true;
935 boolean fuseClusters=true;
936 int followEdge1Passes=0;
937 int followEdge2Passes=5;
938 float edgeStringency1=0.25f;
939 float edgeStringency2=1.1f;
940
941 float strictnessMult=1f;
942
943 /*--------------------------------------------------------------*/
944
945 // /** Number of reads processed */
946 // protected long readsProcessed=0;
947 // /** Number of bases processed */
948 // protected long basesProcessed=0;
949 //
950 // /** Number of reads retained */
951 // protected long readsOut=0;
952 // /** Number of bases retained */
953 // protected long basesOut=0;
954
955 private long clustersWritten=0;
956 private long contigsWritten=0;
957 private long basesWritten=0;
958
959 private DataLoader loader;
960 private Binner binner;
961
962
963 private long fastComparisonsCreate=0, slowComparisonsCreate=0;
964 private long fastComparisonsRefine=0, slowComparisonsRefine=0, netComparisonsRefine=0;
965 private long fastComparisonsEdge=0, slowComparisonsEdge=0, netComparisonsEdge=0;
966 private long fastComparisonsResidue=0, slowComparisonsResidue=0;
967 private long fastComparisonsPurify=0, slowComparisonsPurify=0;
968
969
970 /*--------------------------------------------------------------*/
971 /*---------------- Final Fields ----------------*/
972 /*--------------------------------------------------------------*/
973
974 // private final Timer phaseTimer=new Timer();
975
976 private final BinSketcher sketcher;
977
978 @Override
979 public final ReadWriteLock rwlock() {return rwlock;}
980 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
981 private String[] originalArgs;
982
983 /*--------------------------------------------------------------*/
984 /*---------------- Common Fields ----------------*/
985 /*--------------------------------------------------------------*/
986
987 /** Print verbose messages */
988 public static boolean verbose=false;
989 /** True if an error was encountered */
990 public boolean errorState=false;
991 /** Overwrite existing output files */
992 private boolean overwrite=true;
993 /** Append to existing output files */
994 private boolean append=false;
995
996 }