Debian Codegraph @

current/bin/Binner.java

raw symbols SCIP
1 package bin;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Collections;
7 import java.util.HashMap;
8 import java.util.concurrent.atomic.AtomicLong;
9 import java.util.concurrent.locks.ReadWriteLock;
10
11 import bin.SpectraCounter.LoadThread;
12 import shared.Parse;
13 import shared.Shared;
14 import shared.Timer;
15 import shared.Tools;
16 import structures.IntHashMap;
17 import structures.IntHashSet;
18 import structures.IntLongHashMap;
19 import tax.TaxTree;
20 import template.Accumulator;
21 import template.ThreadWaiter;
22
23 public class Binner extends BinObject implements Accumulator<Binner.CompareThread> {
24
25 /*--------------------------------------------------------------*/
26 /*---------------- Initialization ----------------*/
27 /*--------------------------------------------------------------*/
28
29 Binner(PrintStream outstream_){outstream=outstream_;}
30
31 boolean parse(String arg, String a, String b) {
32
33 if(a.equalsIgnoreCase("productMult")){
34 productMult=Float.parseFloat(b);
35 }
36
37 else if(a.equalsIgnoreCase("perfectoracle")){
38 PERFECT_ORACLE=Parse.parseBoolean(b);
39 }else if(a.equalsIgnoreCase("banbadmerges")){
40 BAN_BAD_MERGES=Parse.parseBoolean(b);
41 }
42
43 else if(a.equalsIgnoreCase("basePasses")){
44 basePasses=Integer.parseInt(b);
45 }else if(a.equalsIgnoreCase("baseRange")){
46 baseRange=Integer.parseInt(b);
47 }else if(a.equalsIgnoreCase("residueRange")){
48 residueRange=Integer.parseInt(b);
49 }
50
51 else if(a.equalsIgnoreCase("prepass") || a.equalsIgnoreCase("passAA")){
52 runPassAA=Parse.parseBoolean(b);
53 }else if(a.equalsIgnoreCase("runPassA") || a.equalsIgnoreCase("passA")){
54 runPassA=Parse.parseBoolean(b);
55 }else if(a.equalsIgnoreCase("runPassB") || a.equalsIgnoreCase("passB")){
56 runPassB=Parse.parseBoolean(b);
57 }else if(a.equalsIgnoreCase("runPassC") || a.equalsIgnoreCase("passC")){
58 runPassC=Parse.parseBoolean(b);
59 }else if(a.equalsIgnoreCase("runPassD") || a.equalsIgnoreCase("passD")){
60 runPassD=Parse.parseBoolean(b);
61 }else if(a.equalsIgnoreCase("runPassE") || a.equalsIgnoreCase("passE")){
62 runPassE=Parse.parseBoolean(b);
63 }else if(a.equalsIgnoreCase("runPassF") || a.equalsIgnoreCase("passF")){
64 runPassF=Parse.parseBoolean(b);
65 }else if(a.equalsIgnoreCase("runPassG") || a.equalsIgnoreCase("passG")){
66 runPassG=Parse.parseBoolean(b);
67 }
68
69 else if(a.equalsIgnoreCase("maxTrimerDif1") || a.equalsIgnoreCase("max3merDif1")){
70 maxTrimerDif1=Float.parseFloat(b);
71 }else if(a.equalsIgnoreCase("maxDif1") || a.equalsIgnoreCase("maxKmerDif1")){
72 maxKmerDif1=Float.parseFloat(b);
73 }else if(a.equalsIgnoreCase("maxPentamerDif1") || a.equalsIgnoreCase("max5merDif1")){
74 max5merDif1=Float.parseFloat(b);
75 }else if(a.equalsIgnoreCase("maxRatio1") || a.equalsIgnoreCase("maxDepthRatio1")){
76 maxDepthRatio1=Float.parseFloat(b);
77 }else if(a.equalsIgnoreCase("maxGCDif1")){
78 maxGCDif1=Float.parseFloat(b);
79 }else if(a.equalsIgnoreCase("maxCovariance1")){
80 maxCovariance1=Float.parseFloat(b);
81 }
82
83 else if(a.equalsIgnoreCase("maxTrimerDif2") || a.equalsIgnoreCase("maxTrimerDif") ||
84 a.equalsIgnoreCase("max3merDif")){
85 maxTrimerDif2=Float.parseFloat(b);
86 }else if(a.equalsIgnoreCase("maxKmerDif2") || a.equalsIgnoreCase("maxKmerDif") ||
87 a.equalsIgnoreCase("max4merDif")){
88 maxKmerDif2=Float.parseFloat(b);
89 }else if(a.equalsIgnoreCase("maxPentamerDif2") || a.equalsIgnoreCase("maxPentamerDif") ||
90 a.equalsIgnoreCase("max5merDif")){
91 max5merDif2=Float.parseFloat(b);
92 }else if(a.equalsIgnoreCase("maxDepthRatio2") || a.equalsIgnoreCase("maxDepthRatio")){
93 maxDepthRatio2=Float.parseFloat(b);
94 }else if(a.equalsIgnoreCase("maxGCDif2") || a.equalsIgnoreCase("maxGCDif")){
95 maxGCDif2=Float.parseFloat(b);
96 }else if(a.equalsIgnoreCase("maxCovariance2") || a.equalsIgnoreCase("maxCovariance")){
97 maxCovariance2=Float.parseFloat(b);
98 }else if(a.equalsIgnoreCase("minkmerprob") || a.equalsIgnoreCase("minkmerprob2")){
99 minKmerProb2=Float.parseFloat(b);
100 }
101
102 else if(a.equalsIgnoreCase("minSimilarity")){
103 minSimilarity=Float.parseFloat(b);
104 }
105
106 else if(a.equalsIgnoreCase("depthBoost")){
107 depthBoost=Float.parseFloat(b);
108 }
109
110 // else if(a.equalsIgnoreCase("minSizeToCluster")){
111 // minSizeToCluster=Parse.parseIntKMG(b);
112 // }else if(a.equalsIgnoreCase("minSizeToRefine")){
113 // minSizeToRefine=Parse.parseIntKMG(b);
114 // }
115 else if(a.equalsIgnoreCase("minseedsize") || a.equals("minsizeseed") || a.equals("minseed")){
116 minSizeToCompare=minSizeToMerge=Parse.parseIntKMG(b);
117 }else if(a.equalsIgnoreCase("minSizeToCompare")){
118 minSizeToCompare=Parse.parseIntKMG(b);
119 }else if(a.equalsIgnoreCase("minSizeToMerge")){
120 minSizeToMerge=Parse.parseIntKMG(b);
121 // }else if(a.equalsIgnoreCase("minSizeToAdd")){
122 // minSizeToAdd=Parse.parseIntKMG(b);
123 }else if(a.equalsIgnoreCase("minSizeResidue") || a.equalsIgnoreCase("minResidue")){
124 minSizeResidue=Parse.parseIntKMG(b);
125 }else if(a.equalsIgnoreCase("minNetSize")){
126 minNetSize=Parse.parseIntKMG(b);
127 }else if(a.equalsIgnoreCase("midNetSize")){
128 midNetSize=Parse.parseIntKMG(b);
129 }else if(a.equalsIgnoreCase("largeNetSize")){
130 largeNetSize=Parse.parseIntKMG(b);
131 }
132
133 else if(a.equalsIgnoreCase("residueStringency")){
134 residueStringency=Float.parseFloat(b);
135 }else if(a.equalsIgnoreCase("purifyStringency")){
136 purifyStringency=Float.parseFloat(b);
137 }else if(a.equalsIgnoreCase("smallthresh")){
138 smallThresh=Parse.parseIntKMG(b);
139 }else if(a.equalsIgnoreCase("smallmult")){
140 smallMult=Float.parseFloat(b);
141 }else if(a.equalsIgnoreCase("bigthresh")){
142 bigThresh=Parse.parseIntKMG(b);
143 }else if(a.equalsIgnoreCase("bigmult")){
144 bigMult=Float.parseFloat(b);
145 }else if(a.equalsIgnoreCase("hugethresh")){
146 hugeThresh=Parse.parseIntKMG(b);
147 }else if(a.equalsIgnoreCase("hugemult")){
148 hugeMult=Float.parseFloat(b);
149 }else if(a.equalsIgnoreCase("tinythresh")){
150 tinyThresh=Parse.parseIntKMG(b);
151 }else if(a.equalsIgnoreCase("tinyMult") || a.equalsIgnoreCase("smallPenalty")){
152 tinyMult=Float.parseFloat(b);
153 }
154
155 else if(a.equalsIgnoreCase("maxEdges")){
156 maxEdges=Integer.parseInt(b);
157 }else if(a.equalsIgnoreCase("minEdgeWeight")){
158 minEdgeWeight=Integer.parseInt(b);
159 }else if(a.equalsIgnoreCase("minEdgeRatio")){
160 minEdgeRatio=Float.parseFloat(b);
161 }else if(a.equalsIgnoreCase("reciprocalEdges")){
162 reciprocalEdges=Boolean.parseBoolean(b);
163 }
164
165 else if(a.equalsIgnoreCase("fuseLowerLimit")){
166 fuseLowerLimit=Parse.parseIntKMG(b);
167 }else if(a.equalsIgnoreCase("fuseUpperLimit")){
168 fuseUpperLimit=Parse.parseIntKMG(b);
169 }else if(a.equalsIgnoreCase("fuseStringency")){
170 fuseStringency=Float.parseFloat(b);
171 }
172
173 else if(a.equalsIgnoreCase("lowDepthEdgeRatio")){
174 lowDepthEdgeRatio=Float.parseFloat(b);
175 }else if(a.equalsIgnoreCase("highDepthEdgeRatio")){
176 highDepthEdgeRatio=Float.parseFloat(b);
177 }else if(a.equalsIgnoreCase("goodEdgeMult")){
178 goodEdgeMult=Float.parseFloat(b);
179 }else if(a.equalsIgnoreCase("transEdgeMult") || a.equalsIgnoreCase("goodTransEdgeMult") ||
180 a.equalsIgnoreCase("goodTransitiveEdgeMult")){
181 goodTransEdgeMult=Float.parseFloat(b);
182 }
183
184 else if(a.equals("netcutoff") || a.equals("cutoff")) {
185 netCutoff_small=netCutoff_mid=netCutoff_large=Float.parseFloat(b);
186 }else if(a.equals("cutoffsmall") || a.equals("smallcutoff")) {
187 netCutoff_small=Float.parseFloat(b);
188 }else if(a.equals("cutoffmid") || a.equals("midcutoff")) {
189 netCutoff_mid=Float.parseFloat(b);
190 }else if(a.equals("cutofflarge") || a.equals("largecutoff")) {
191 netCutoff_large=Float.parseFloat(b);
192 }else if(a.equals("netcutoffupper") || a.equals("cutoffupper") || a.equals("cutoff2")) {
193 netCutoffUpper=Float.parseFloat(b);
194 }else if(a.equals("netcutofflower") || a.equals("cutofflower")) {
195 netCutoffLower=Float.parseFloat(b);
196 }else if(a.equalsIgnoreCase("netMultUpper")) {
197 netMultUpper=Float.parseFloat(b);
198 }else if(a.equalsIgnoreCase("netMultLower")) {
199 netMultLower=Float.parseFloat(b);
200 }else if(a.equalsIgnoreCase("cutoffMultA")){
201 cutoffMultA=Float.parseFloat(b);
202 }else if(a.equalsIgnoreCase("cutoffMultB")){
203 cutoffMultB=Float.parseFloat(b);
204 }else if(a.equalsIgnoreCase("cutoffMultC")){
205 cutoffMultC=Float.parseFloat(b);
206 }else if(a.equalsIgnoreCase("cutoffMultD")){
207 cutoffMultD=Float.parseFloat(b);
208 }
209
210 // else if(a.equalsIgnoreCase("mtcompare") || a.equalsIgnoreCase("comparemt")){
211 // multiThreadedCompare=Parse.parseBoolean(b);
212 // }
213
214 else {return false;}
215
216 return true;
217 }
218
219 /*--------------------------------------------------------------*/
220 /*---------------- Graph ----------------*/
221 /*--------------------------------------------------------------*/
222
223 public long followEdges(ArrayList<Contig> contigs, ArrayList<? extends Bin> input, Oracle oracle){
224 // outstream.print("Following Edges: \t");
225 phaseTimer.start();
226 long merges=0;
227 merges=launchThreads(input, null, contigs, FOLLOW_MODE, 0, 0, oracle.clone());
228 // phaseTimer.stopAndPrint();
229 // phaseTimer.start();
230
231 //This phase can be much slower than edge-following, presumably when clusters get big.
232 if(merges>0) {merges=mergeWithDest(contigs, input);}
233
234 if(merges>0 && loud) {phaseTimer.stop("Merged "+merges+"/"+input.size()+" bins: \t");}
235 return merges;
236 }
237
238 private int mergeWithDest(ArrayList<Contig> contigs, ArrayList<? extends Bin> input){
239 int x=0, y=0, z=0;
240
241 for(Bin a : input) {
242 if(!a.isCluster() && a.cluster()!=null) {a.dest=-1;continue;}
243 if(a.isCluster() && a.numContigs()==0) {a.dest=-1;continue;}
244 assert(a.isValid());
245 if(a.dest<0) {
246 //ignore
247 x++;
248 }else {
249 y++;
250 Bin b=contigs.get(a.dest);
251 if(b.cluster()!=null) {b=b.cluster();}
252 if(!b.isEmpty() && !a.sameCluster(b)) {
253 if(a.labelTaxid>=0 && b.labelTaxid>=0) {
254 long minSize=Tools.min(a.size(), b.size());
255 addMerge(minSize, a.labelTaxid==b.labelTaxid);
256 if(a.labelTaxid==b.labelTaxid) {
257 goodMergesFollow++;
258 goodMergeSizeFollow+=minSize;
259 }else {
260 badMergesFollow++;
261 badMergeSizeFollow+=minSize;
262 }
263 }
264 assert(b.isValid());
265 if(a.isCluster()) {
266 try {
267 ((Cluster)a).add(b);
268 } catch (Throwable e) {
269 System.err.println(a.numContigs()+", "+((Cluster)a).contigs);
270 // TODO Auto-generated catch block
271 e.printStackTrace();
272 throw new RuntimeException(e);
273 }
274 }else if(b.isCluster()) {
275 ((Cluster)b).add(a);
276 }else if(a.cluster()!=null){
277 assert(false);
278 a.cluster().add(b);
279 }else {
280 Cluster c=a.toCluster();
281 c.add(b);
282 }
283 z++;
284 }
285 }
286 a.dest=-1;
287 }
288 return z;
289 }
290
291 private static final int countClustered(ArrayList<? extends Bin> list) {
292 int clustered=0;
293 for(Bin b : list) {
294 clustered+=(b.cluster()!=null ? b.numContigs() : 0);
295 }
296 return clustered;
297 }
298
299 public static final ArrayList<Bin> toBinList(ArrayList<? extends Bin> list, int minSize){
300 ArrayList<Bin> bins=new ArrayList<Bin>();
301 IntHashSet clusterSet=new IntHashSet(255);
302 for(Bin a : list) {
303 Cluster c=a.cluster();
304 long size=(c==null ? a.size() : c.size());
305 if(size<minSize) {continue;}
306
307 if(c==null) {//Contig
308 bins.add(a);
309 }else if(!clusterSet.contains(c.id())){
310 bins.add(c);
311 clusterSet.add(c.id());
312 }
313 // Bin b=bins.get(bins.size()-1);
314 // assert(b.size()>=minSize);//123
315 }
316 return bins;
317 }
318
319 private int followEdges(Bin a, ArrayList<Contig> contigs, Oracle oracle) {
320 oracle.clear();
321 ArrayList<KeyValue> edges=KeyValue.toList(a.pairMap);//TODO: Slow
322 float bestScore=0;
323 Bin target=null;
324 assert(a.isCluster() || a.cluster()==null);
325
326 int max=(a.isCluster() ? maxEdges : maxEdges+Tools.min(2, maxEdges)*Tools.min(8, a.numContigs()-1));
327 max=Tools.min(max, edges.size());
328 int minWeight=(int)Math.ceil(minEdgeRatio*edges.get(0).value);
329 minWeight=Tools.max(minWeight, minEdgeWeight);
330 for(int i=0; i<max; i++) {
331 KeyValue kv=edges.get(i);
332 if(kv.value<minWeight) {break;}
333 Contig c=contigs.get(kv.key);
334 Bin b=(c.cluster()!=null ? c.cluster() : c);
335 if(a==b || target==b) {continue;}
336 int min=Tools.min((int)c.countEdgesTo(a), kv.value);
337 // if(min>minWeight) {min=c.countReciprocalEdges(a);}//Slow
338
339 // verbose=(a.id()==71 && b.id()==14499);
340 if(verbose) {
341 System.err.println("a="+a.id()+", b="+b.id()+", c="+c.id()+", v="+kv.value);
342 System.err.println("ca="+c.countEdgesTo(a)+", cb="+c.countEdgesTo(b)+
343 ", ac="+a.countEdgesTo(c)+", bc="+b.countEdgesTo(c));
344 System.err.println(b.numContigs()+", "+b.cluster().contigSet+
345 "\naMap="+a.pairMap+"\nbMap="+b.pairMap+"\ncMap="+c.pairMap);
346 }
347 if(min>=minWeight) {
348 // float f=a.similarityTo(b, oracle.stringency0);
349 float f=oracle.similarity(a, b, 1f);
350 // assert(f==f2) : f+", "+f2+", "+a.id()+", "+b.id()+", "+min+", "+minWeight;
351 if(f>bestScore) {
352 target=b;
353 bestScore=f;
354 }
355 }
356 assert(!verbose);
357 }
358 return target==null ? -1 : target.id();
359 }
360
361 public Cluster findLinkedCluster(Bin a, ArrayList<Contig> contigs) {
362 if(a.pairMap==null) {return null;}
363 assert(a.isCluster() || a.cluster()==null);
364 int bestValue=0;
365 Cluster bestCluster=null;
366 int[] keys=a.pairMap.keys(), values=a.pairMap.values();
367 // final int max=Tools.max(values);
368 for(int i=0; i<keys.length; i++) {
369 int key=keys[i];
370 if(key!=a.pairMap.invalid()) {
371 int v=values[i];
372 Contig a2=contigs.get(key);
373 assert(key==a2.id());
374 Cluster c=contigs.get(key).cluster();
375 if(c!=null && v>bestValue && c!=a) {
376 assert(c.contigSet.contains(key));
377 if(!a.isCluster() || a.id()<=c.id) {
378 if(c.countEdgesTo(a)>0) {
379 bestValue=v;
380 bestCluster=c;
381 }
382 }
383 }
384 }
385 }
386 return bestCluster;
387 }
388
389 /*--------------------------------------------------------------*/
390 /*---------------- Binning ----------------*/
391 /*--------------------------------------------------------------*/
392
393 public BinMap makeBinMap(ArrayList<Contig> contigList, ArrayList<? extends Bin> input) {
394 outstream.print("Making BinMap: \t");
395 phaseTimer.start();
396
397 if(input==null) {
398 input=contigList;
399 }else {
400 Collections.sort(input);
401 }
402 BinMap map=new BinMap(contigList);
403 Key key=new Key();
404 float stringency=1;
405 long contigsAdded=0;
406 long clustersCreated=0;
407
408 for(int i=1; i<input.size(); i++) {
409 assert(input.get(i).size()<=input.get(i-1).size());
410 }
411
412 float[] ret=new float[1];
413 float maxProduct=maxKmerDif1*maxDepthRatio1*Binner.productMult;
414 Oracle oracle=new Oracle(maxGCDif1, maxDepthRatio1, maxTrimerDif1, maxKmerDif1, max5merDif1, maxProduct,
415 maxCovariance1, minKmerProb2, 0);
416 for(Bin a : input) {
417 int initialContigs=a.numContigs();
418 // Cluster c=map.addOrMerge(a, minSizeToCompare*8, minSizeToMerge*4, minSizeToCompare,
419 // maxKmerDif1, maxDepthRatio1, maxGCDif1, maxCovariance1, stringency,
420 // TaxTree.SPECIES, true, true, key, ret, 0);
421 Cluster c=map.addOrMerge(a, minSizeToCompare*8, minSizeToMerge*4, minSizeToCompare,
422 oracle, key, 0);
423 if(c==null) {
424 //residual.add(b);//Automatic
425 }else {
426 contigsAdded+=initialContigs;
427 if(c.numContigs()==1) {
428 clustersCreated++;
429 }else if(c.labelTaxid>0 && a.labelTaxid>0) {
430 long minSize=Tools.min(a.size(), c.size());
431 addMerge(minSize, a.labelTaxid==c.labelTaxid);
432 goodMergesCreate+=(c.labelTaxid==a.labelTaxid) ? 1 : 0;
433 badMergesCreate+=(c.labelTaxid==a.labelTaxid) ? 0 : 1;
434 if(a.labelTaxid!=c.labelTaxid) {
435 badMergeSizeCreate+=minSize;
436 }else {
437 goodMergeSizeCreate+=minSize;
438 }
439 }
440 }
441 }
442 fastComparisons.addAndGet(oracle.fastComparisons);
443 slowComparisons.addAndGet(oracle.slowComparisons);
444 netComparisons.addAndGet(oracle.netComparisons);
445 phaseTimer.stopAndPrint();
446 outstream.println("Made "+map.map.size()+" lists containing "+clustersCreated+
447 " clusters and "+contigsAdded+" contigs from "+contigList.size()+" elements.");
448 return map;
449 }
450
451 public int refineBinMapPass(BinMap map, float stringency,
452 int taxlevel, boolean allowNoTaxID, boolean allowHalfTaxID, int range, int minSize) {
453 // System.err.println("Merging clusters pass.");
454
455 float maxTrimerDif=maxTrimerDif2*stringency;
456 float maxKmerDif=maxKmerDif2*stringency;
457 float max5merDif=max5merDif2*stringency;
458 float maxDepthRatio=1+((maxDepthRatio2-1)*stringency);
459 float maxGCDif=maxGCDif2*stringency;
460 float maxProduct=maxKmerDif*maxDepthRatio*Binner.productMult;
461 float maxCovariance=maxCovariance2*stringency;
462
463 ArrayList<Cluster> clusters=map.toList(false);
464 Collections.sort(clusters);
465 Key key=new Key();
466
467 for(int i=1; i<clusters.size(); i++) {
468 assert(clusters.get(i).size()<=clusters.get(i-1).size());
469 }
470
471 // System.err.println("maxKmerDif="+maxKmerDif+", maxDepthRatio="+maxDepthRatio+", maxGCDif="+maxGCDif
472 // +", maxProduct="+maxProduct+", allowNoTaxID="+allowNoTaxID+", allowHalfTaxID="+allowHalfTaxID
473 // +", range="+range);
474
475 int merged=0;
476
477 Oracle oracle=new Oracle(maxGCDif, maxDepthRatio, maxTrimerDif, maxKmerDif, max5merDif,
478 maxProduct, maxCovariance, minKmerProb2, 0);
479 launchThreads(clusters, map, null, REFINE_MODE, range, minSize, oracle.clone());
480 for(Cluster c : clusters) {
481 synchronized(c) {
482 if(c.dest>=0) {
483 merged++;
484 }
485 }
486 }
487 // assert(false);
488 // assert(map.isValid());
489 if(merged<1) {return 0;}
490
491 for(int i=clusters.size()-1; i>=0; i--) {
492 Cluster a=clusters.get(i);
493 synchronized(a) {
494 final int dest=a.dest;
495 if(dest>=0 && dest!=a.id()) {
496 Cluster b=map.contigList.get(dest).cluster;
497 synchronized(b) {
498 if(b!=a) {
499 assert(!b.contigSet.contains(a.id));
500 assert(!a.contigSet.contains(b.id));
501 assert(a.id()!=dest && a.id()!=b.id()) : a.id+", "+dest+", "+b.id+", "+(a.id()==dest)+", "+(b.id()==dest)+", "+(a.id()!=b.id());
502
503 if(a.labelTaxid>0 && b.labelTaxid>0) {
504 long smaller=Tools.min(a.size(), b.size());
505 addMerge(smaller, a.labelTaxid==b.labelTaxid);
506 goodMergesRefine+=(a.labelTaxid==b.labelTaxid) ? 1 : 0;
507 badMergesRefine+=(a.labelTaxid==b.labelTaxid) ? 0 : 1;
508 if(a.labelTaxid!=b.labelTaxid) {
509 badMergeSizeRefine+=smaller;
510 }else {
511 goodMergeSizeRefine+=smaller;
512 }
513 }
514 b.add(a);
515 clusters.set(i, null);
516 }
517 }
518 }
519 }
520 }
521
522 map.clear(false);
523 // assert(map.isValid());
524 Tools.condense(clusters);
525 Collections.sort(clusters);
526 for(Cluster c : clusters) {
527 map.add(c, key);
528 }
529 assert(map.isValid());
530 return merged;
531 }
532
533 public int purify(BinMap map, float stringency, int range, int minSizePurify, int minSizeCompare) {
534 // System.err.println("Merging clusters pass.");
535
536 float maxTrimerDif=maxTrimerDif2*stringency;
537 float maxKmerDif=maxKmerDif2*stringency;
538 float max5merDif=max5merDif2*stringency;
539 float maxDepthRatio=1+((maxDepthRatio2-1)*stringency);
540 float maxGCDif=maxGCDif2*stringency;
541 float maxProduct=maxKmerDif*maxDepthRatio*Binner.productMult;
542 float maxCovariance=maxCovariance2*stringency;
543
544 for(Contig c : map.contigList) {
545 synchronized(c) {c.dest=-1;}
546 }
547
548 ArrayList<Cluster> clusters=new ArrayList<Cluster>();
549 {
550 ArrayList<Cluster> clusters0=map.toList(false);
551 Collections.sort(clusters0);
552 for(Cluster c : clusters0) {
553 if(c.size<minSizePurify) {break;}
554 if(c.numContigs()>1) {
555 clusters.add(c);
556 }
557 }
558 }
559 // System.err.println("Launching purify on "+clusters.size()+" clusters!");
560 if(clusters.isEmpty()) {return 0;}
561
562 int removed=0;
563
564 Oracle oracle=new Oracle(maxGCDif, maxDepthRatio, maxTrimerDif, maxKmerDif, max5merDif,
565 maxProduct, maxCovariance, minKmerProb2*0.8f, 0);
566 oracle.useEdges=false;
567 launchThreads(clusters, map, null, PURIFY_MODE, range, minSizeCompare, oracle.clone());
568 for(Cluster clust : clusters) {
569 synchronized(clust) {
570 removed+=purifyCluster(clust);
571 }
572 }
573 if(removed>0) {
574 map.clear(true);
575 ArrayList<Bin> bins=toBinList(map.contigList, 0);
576 Collections.sort(bins);
577 Key key=new Key();
578 for(Bin b : bins) {
579 map.add(b, key);
580 }
581 }
582 return removed;
583 }
584
585 int purifyCluster(Cluster clust) {
586 ArrayList<Contig> contigs=clust.contigs;
587 int removed=0;
588 for(int i=0; i<contigs.size(); i++) {
589 Contig c=contigs.get(i);
590 if(c.dest>=0 && c.dest!=clust.id) {
591 c.cluster=null;
592 removed++;
593 contigs.set(i, null);
594 }
595 }
596 if(removed>0) {
597 @SuppressWarnings("unchecked")
598 ArrayList<Contig> list=(ArrayList<Contig>) contigs.clone();
599 clust.clear();
600 for(Contig c : list) {
601 if(c!=null) {
602 c.cluster=null;
603 clust.add(c);
604 }
605 }
606 assert(clust.contigSet.contains(clust.id));
607 if(clust.numDepths()>1) {clust.fillNormDepth();}
608 }
609 return removed;
610 }
611
612 public int processResidue(BinMap map, float stringency,
613 int taxlevel, boolean allowNoTaxID, boolean allowHalfTaxID, int range) {
614 // assert(map.isValid());
615 System.err.println("Processing "+map.residual.size()+" residual contigs.");
616 Timer t=new Timer(outstream, true);
617 if(map.residual.isEmpty()) {return 0;}
618
619 float maxTrimerDif=maxTrimerDif2*stringency;
620 float maxKmerDif=maxKmerDif2*stringency;
621 float max5merDif=max5merDif2*stringency;
622 float maxDepthRatio=1+((maxDepthRatio2-1)*stringency);
623 float maxGCDif=maxGCDif2*stringency;
624 float maxProduct=maxKmerDif*maxDepthRatio*Binner.productMult;
625 float maxCovariance=maxCovariance2*stringency;
626
627 // System.err.println("maxKmerDif="+maxKmerDif+", maxDepthRatio="+maxDepthRatio+", maxGCDif="+maxGCDif
628 // +", maxProduct="+maxProduct+", allowNoTaxID="+allowNoTaxID+", allowHalfTaxID="+allowHalfTaxID
629 // +", range="+range);
630 int merged=0;
631 map.residual=toBinList(map.residual, 0);
632 // assert(map.isValid());
633
634 int minSize=Tools.max(minSizeToMerge, minClusterSize/5);
635 Oracle oracle=new Oracle(maxGCDif, maxDepthRatio, maxTrimerDif, maxKmerDif, max5merDif,
636 maxProduct, maxCovariance, minKmerProb2, 0);
637 launchThreads(map.residual, map, null, RESIDUE_MODE, range, minSize, oracle);
638 for(Bin c : map.residual) {
639 synchronized(c) {
640 if(c.dest>=0) {merged++;}
641 }
642 }
643 t.stopAndStart("Found "+merged+" merge targets.");
644
645 if(merged<1) {return 0;}
646 for(int i=0; i<map.residual.size(); i++) {
647 Bin a=map.residual.get(i);
648 if(a.dest>0) {
649 Cluster b=map.contigList.get(a.dest).cluster;
650 assert(a!=b) : "\n"+a.id()+"\n"+b.id()+"\n"+a.dest+"\n"+
651 a.getClass()+"\n"+b.getClass()+"\n"+b.contigSet.contains(a.id());
652 if(a.labelTaxid>0 && b.labelTaxid>0) {
653 long smaller=Tools.min(a.size(), b.size());
654 addMerge(smaller, a.labelTaxid==b.labelTaxid);
655 goodMergesResidue+=(a.labelTaxid==b.labelTaxid) ? 1 : 0;
656 badMergesResidue+=(a.labelTaxid==b.labelTaxid) ? 0 : 1;
657 if(a.labelTaxid!=b.labelTaxid) {
658 badMergeSizeResidue+=smaller;
659 }else {
660 goodMergeSizeResidue+=smaller;
661 }
662 }
663 b.add(a);//Note at this point b could be a residue that becomes bigger than residue size
664 map.residual.set(i, null);
665 }
666 }
667
668 Tools.condenseStrict(map.residual);
669 for(ArrayList<Cluster> list : map.map.values()) {
670 Collections.sort(list);
671 }
672 assert(map.isValid());
673
674 t.stop("Merged "+merged+" contigs into clusters.");
675 return merged;
676 }
677
678 public Cluster findBestResidualCluster(Bin a, BinMap map, Key key, Oracle oracle,
679 int range, int minSize) {
680 if(a==null || a.size()<minSizeResidue) {return null;}
681 int minSize2=(int)Tools.max(minSizeToCompare, a.size(), minSize);
682 Cluster b=map.findBestCluster(a, minSize2, key, range, oracle);
683 return b;
684 }
685
686 public int refineBinMap(BinMap map) {
687 System.err.println("Merging clusters.");
688 if(sketchClusters) {sketcher.sketch(map.toList(false), false);}
689 else {
690 for(Cluster c : map) {
691 if(c.sketchedSize()>=2*c.size()) {c.clearTax();}
692 }
693 }
694 phaseTimer.start();
695
696 int removedThisPhase=0;
697 int removedTotal=0;
698 // net0small.cutoff+=0.02;
699 // net0mid.cutoff+=0.02;
700 // net0large.cutoff+=0.02;
701 if(sketchContigs || sketchClusters) {
702 removedThisPhase=refinePhase(map, "aa", 2.5f, TaxTree.SPECIES, false, false, baseRange, minSizeToMerge, 8);
703 removedTotal+=removedThisPhase;
704
705 removedThisPhase=refinePhase(map, "bb", 1.5f, TaxTree.SPECIES, true, false, baseRange, minSizeToMerge, 8);
706 removedTotal+=removedThisPhase;
707
708 removedThisPhase=refinePhase(map, "cc", 1.0f, TaxTree.GENUS, true, true, baseRange, minSizeToMerge, 8);
709 removedTotal+=removedThisPhase;
710 }else {
711 if(runPassAA) {
712 removedThisPhase=refinePhase(map, "aa", 0.8f, -1, true, true, baseRange+1, Tools.max(4*minSizeToMerge, 20000), basePasses+1);
713 removedTotal+=removedThisPhase;
714 }
715 if(runPassA) {
716 removedThisPhase=refinePhase(map, "a", 0.8f, -1, true, true, baseRange, minSizeToMerge, basePasses+1);
717 removedTotal+=removedThisPhase;
718 }
719 if(runPassB) {
720 removedThisPhase=refinePhase(map, "b", 0.85f, -1, true, true, baseRange+2, minSizeToMerge, basePasses+2);
721 removedTotal+=removedThisPhase;
722 }
723 }
724 // net0small.cutoff-=0.02;
725 // net0mid.cutoff-=0.02;
726 // net0large.cutoff-=0.02;
727 if(runPassD) {
728 removedThisPhase=refinePhase(map, "d", 0.9f, -1, true, true, baseRange, minSizeToMerge, basePasses+0);
729 removedTotal+=removedThisPhase;
730 }
731 if(runPassE) {
732 removedThisPhase=refinePhase(map, "e", 1.0f, -1, true, true, baseRange+2, minSizeToMerge, basePasses+3);
733 removedTotal+=removedThisPhase;
734 }
735
736 phaseTimer.stop("Refinement merged "+removedTotal+" clusters. ");
737 return removedTotal;
738 }
739
740 int refinePhase(BinMap map, String phase,
741 float stringency, int taxLevel, boolean noTax, boolean halfTax, int range, int initialMinSize, int passes) {
742 Timer t=new Timer(outstream, true);
743 int removedThisPhase=0;
744 for(int pass=1; pass<=passes; pass++) {
745 int initial=map.countClusters();
746 int removed=refineBinMapPass(map, stringency, taxLevel, noTax, halfTax, range, initialMinSize*pass);
747 removedThisPhase+=removed;
748 if(loud) {
749 System.err.print("Refinement Pass "+pass+phase+": Merged "+removed+"/"+initial+" clusters. ");
750 t.stopAndStart("\t");
751 }
752 if(removed<2) {break;}
753 }
754 if(sketchClusters && removedThisPhase>0) {sketcher.sketch(map.toList(false), false);}
755 return removedThisPhase;
756 }
757
758 public ArrayList<Bin> clusterByTaxid(ArrayList<? extends Bin> bins){
759 outstream.print("Clustering by Taxid: \t");
760 phaseTimer.start();
761 Collections.sort(bins);
762 HashMap<Integer, Bin> map=new HashMap<Integer, Bin>();
763 int clustersMade=0;
764 int contigsClustered=0;
765
766 ArrayList<Bin> out=new ArrayList<Bin>();
767 for(int i=0; i<bins.size(); i++) {
768 Bin b=bins.get(i);
769 if(b.taxid()>0) {
770 Integer key=Integer.valueOf(b.taxid());
771 Bin old=map.get(key);
772 if(old==null) {
773 map.put(key, b);
774 b=null;
775 }else if(old.getClass()==Cluster.class) {
776 //Todo: Write "similar" function.
777 ((Cluster)old).add(b);
778 contigsClustered++;
779 b=null;
780 }else {
781 Cluster a=new Cluster(clustersMade);
782 a.add(old);
783 a.add(b);
784 map.put(key, a);
785 clustersMade++;
786 contigsClustered++;
787 b=null;
788 }
789 }
790 if(b!=null) {out.add(b);}
791 }
792
793 out.addAll(map.values());
794 Collections.sort(out);
795
796 phaseTimer.stopAndPrint();
797 outstream.println("Made "+clustersMade+" clusters containing "+contigsClustered+"/"+bins.size()+" elements.");
798 return out;
799 }
800
801 public long fuse(ArrayList<Contig> contigs, ArrayList<? extends Bin> input, float stringency){
802 if(loud) {outstream.print("Initiating Fusion: \t");}
803 phaseTimer.start();
804
805 // for(int i=1; i<input.size(); i++) {
806 // assert(input.get(i).size()<=input.get(i-1).size());
807 // assert(input.get(i).size()>=fuseLowerLimit);
808 // }
809 // assert(false) : fuseLowerLimit;
810
811 float maxTrimerDif=maxTrimerDif2*stringency;
812 float maxKmerDif=maxKmerDif2*stringency;
813 float max5merDif=max5merDif2*stringency;
814 float maxDepthRatio=1+((maxDepthRatio2-1)*stringency);
815 float maxGCDif=maxGCDif2*stringency;
816 float maxProduct=maxKmerDif*maxDepthRatio*Binner.productMult;
817 float maxCovariance=maxCovariance2*stringency;
818 Oracle oracle=new Oracle(maxGCDif, maxDepthRatio, maxTrimerDif, maxKmerDif, max5merDif,
819 maxProduct, maxCovariance, minKmerProb2, 0);
820
821 // System.err.println("maxKmerDif="+maxKmerDif+", maxDepthRatio="+maxDepthRatio+
822 // ", maxGCDif="+maxGCDif+", maxProduct="+maxProduct+
823 // ", maxCovariance="+maxCovariance+", minKmerProb2="+minKmerProb2);
824 // System.err.println("List size: "+input.size());
825
826 long merges=0;
827 merges=launchThreads(input, null, contigs, FUSE_MODE, 0, 0, oracle.clone());
828 // phaseTimer.stopAndPrint();
829 // phaseTimer.start();
830
831 //This phase can be slow.
832 if(merges>0) {merges=mergeWithDest(contigs, input);}
833
834 if(merges>0 && loud) {phaseTimer.stop("Merged "+merges+"/"+input.size()+" bins: \t");}
835 return merges;
836 }
837
838 /*--------------------------------------------------------------*/
839
840 void setSamples(int samples, float mult) {
841
842 if(samples<2) {//Single mode //maxkmerdif=0.0060 maxgcdif=0.045
843 maxKmerDif2=0.0048f;
844 // maxKmerDif2=0.008f;
845 maxDepthRatio2=1.38f;
846 maxGCDif2=0.032f;
847 minKmerProb2=0.82f;
848 max5merDif2=0.007f;
849
850 fuseStringency=1.6f;
851 }else if(samples<3){//Two mode
852 maxKmerDif2=0.0065f;
853 maxDepthRatio2=1.32f;
854 maxGCDif2=0.032f;
855 maxCovariance2=0.0035f;
856 minKmerProb2=0.80f;
857 max5merDif2=0.008f;
858
859 netCutoffUpper=0.85f;
860 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
861 fuseStringency=1.6f;
862 }else if(samples<4){//Three mode
863 // maxKmerDif2=0.0115f;
864 maxKmerDif2=0.0075f;
865 maxDepthRatio2=1.40f;
866 maxGCDif2=0.04f;
867 maxCovariance2=0.0045f;
868 minKmerProb2=0.75f;
869 max5merDif2=0.009f;
870
871 netCutoffUpper=0.85f;
872 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
873 fuseStringency=1.6f;
874 }else if(samples<5){//Four mode
875 // maxKmerDif2=0.02f;
876 maxKmerDif2=0.0085f;
877 maxDepthRatio2=1.4f;
878 maxGCDif2=0.05f;
879 maxCovariance2=0.0045f;
880 minKmerProb2=0.7f;
881 max5merDif2=0.010f;
882
883 netCutoffUpper=0.85f;
884 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
885 fuseStringency=1.6f;
886 purifyStringency=3.0f;
887 }else if(samples<6){//5
888 // maxKmerDif2=0.020f;
889 maxKmerDif2=0.0095f;
890 maxDepthRatio2=1.45f;
891 maxGCDif2=0.05f;
892 maxCovariance2=0.0035f;
893 minKmerProb2=0.7f;
894 max5merDif2=0.0011f;
895
896 netCutoffUpper=0.85f;
897 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
898 fuseStringency=1.6f;
899 purifyStringency=2.5f;
900 }else if(samples<7){//6
901 maxKmerDif2=0.0105f;
902 maxDepthRatio2=1.45f;
903 maxGCDif2=0.05f;
904 maxCovariance2=0.0035f;
905 minKmerProb2=0.7f;
906 max5merDif2=0.012f;
907
908 netCutoffUpper=0.85f;
909 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
910 fuseStringency=1.6f;
911 purifyStringency=2.5f;
912 }else{//7+
913 maxKmerDif2=0.0115f;
914 maxDepthRatio2=1.45f;
915 maxGCDif2=0.05f;
916 maxCovariance2=0.0035f;
917 minKmerProb2=0.7f;
918 max5merDif2=0.015f;
919
920 netCutoffUpper=0.85f;
921 netCutoff_small=netCutoff_mid=netCutoff_large=0.8f;
922 fuseStringency=1.6f;
923 purifyStringency=2.5f;
924 }
925
926 if(mult!=1) {
927 float lowMult=((mult-1)*0.5f)+1;
928 float highMult=((mult-1)*2f)+1;
929 maxKmerDif2*=lowMult;
930 maxDepthRatio2=1+(maxDepthRatio2-1)*mult;
931 maxGCDif2*=mult;
932 maxCovariance2*=(mult);
933 purifyStringency*=mult;
934 fuseStringency=1+(fuseStringency-1)*mult;
935 smallMult=1+(smallMult-1)*mult;
936
937 // float netAdjust=-((16*mult)-16)/400f;
938 // netCutoff_small+=netAdjust;
939 // netCutoff_mid+=netAdjust;
940 // netCutoff_large+=netAdjust;
941 // float netAdjust2=(1-mult)*0.08f;
942 // netCutoffUpper+=netAdjust2;
943
944 if(mult>1) {
945 minKmerProb2=1-mult*mult*mult*mult*(1-minKmerProb2);
946 }else {
947 minKmerProb2=1-mult*(1-minKmerProb2);
948 }
949 if(mult>1) {
950 hugeMult=1/(1+(1/hugeMult-1)/highMult);
951 }else {
952 hugeMult=1/(1+(1/hugeMult-1)/lowMult);
953 }
954 if(samples==1) {
955 // if(mult==1.4f) {
956 // maxKmerDif2=0.0078f;
957 // minKmerProb2=0.99f;
958 // }else if(mult==1.3f) {
959 // maxKmerDif2=0.0068f;
960 // minKmerProb2=0.99f;
961 // }else if(mult==1.2f) {
962 // maxKmerDif2=0.0062f;
963 // minKmerProb2=0.99f;
964 // }else if(mult==1.1f) {
965 // maxKmerDif2=0.0055f;
966 // minKmerProb2=0.99f;
967 // }
968 if(mult==1.5f) {
969 minKmerProb2=0.7f;
970 }else if(mult==1.375f) {
971 minKmerProb2=0.75f;
972 }else if(mult==1.25f) {
973 minKmerProb2=0.80f;
974 }else if(mult==1.125f) {
975 minKmerProb2=0.81f;
976 }
977 }
978 }
979 }
980
981 void printThresholds(){
982 // netCutoffUpper=0.7f;
983 System.err.println("maxKmerDif: "+maxKmerDif2);
984 System.err.println("minKmerProb: "+minKmerProb2);
985 System.err.println("maxDepthRatio: "+maxDepthRatio2);
986 System.err.println("maxGCDif: "+maxGCDif2);
987 System.err.println("maxCovariance: "+maxCovariance2);
988 System.err.println("netCutoff: "+netCutoff_large);
989 System.err.println("netCutoffUpper: "+netCutoffUpper);
990 System.err.println("fuseStringency: "+fuseStringency);
991 System.err.println("purifyStringency: "+purifyStringency);
992 System.err.println("smallThresh: "+smallThresh);
993 System.err.println("smallMult: "+smallMult);
994 System.err.println("bigThresh: "+bigThresh);
995 System.err.println("bigMult: "+bigMult);
996 }
997
998 /*--------------------------------------------------------------*/
999 /*---------------- Classes and Threading ----------------*/
1000 /*--------------------------------------------------------------*/
1001
1002 private synchronized long launchThreads(ArrayList<? extends Bin> list, BinMap map,
1003 ArrayList<Contig> contigs, int mode, int range, int minSize, Oracle oracle) {
1004
1005 //Do anything necessary prior to processing
1006
1007 //Determine how many threads may be used
1008 int threads=Tools.mid(1, list.size()/64, Shared.threads());
1009 // if(mode==FUSE_MODE) {threads=1;}//123
1010 threadMerges=0;
1011
1012 //Fill a list with LoadThreads
1013 ArrayList<CompareThread> alpt=new ArrayList<CompareThread>(threads);
1014 for(int i=0; i<threads; i++){
1015 CompareThread lt=new CompareThread(list, map, contigs, i,
1016 threads, mode, range, minSize, oracle.clone());
1017 alpt.add(lt);
1018 }
1019
1020 //Start the threads and wait for them to finish
1021 boolean success=ThreadWaiter.startAndWait(alpt, this);
1022 assert(success);
1023 //Do anything necessary after processing
1024
1025 return threadMerges;
1026 }
1027
1028 @Override
1029 public synchronized void accumulate(CompareThread t) {
1030 synchronized(t){
1031 fastComparisons.addAndGet(t.oracle.fastComparisons);
1032 slowComparisons.addAndGet(t.oracle.slowComparisons);
1033 netComparisons.addAndGet(t.oracle.netComparisons);
1034 threadMerges+=t.mergesT;
1035 errorState|=(!t.success);
1036 }
1037 }
1038
1039 @Override
1040 public ReadWriteLock rwlock() {return null;}
1041
1042 @Override
1043 public boolean success() {return !errorState;}
1044
1045 class CompareThread extends Thread {
1046
1047 public CompareThread(ArrayList<? extends Bin> list, BinMap map_, ArrayList<Contig> contigs_,
1048 int tid_, int threads_, int mode_, int range_, int minSize_, Oracle oracle_) {
1049 input=list;
1050 map=map_;
1051 contigs=(contigs_!=null ? contigs_ : map.contigList);
1052 tid=tid_;
1053 threads=threads_;
1054 mode=mode_;
1055 range=range_;
1056 minSize=minSize_;
1057 oracle=oracle_;
1058 }
1059
1060
1061 public void run() {
1062 synchronized(this) {
1063 if(mode==REFINE_MODE) {
1064 refine();
1065 }else if(mode==RESIDUE_MODE) {
1066 residue();
1067 }else if(mode==PURIFY_MODE) {
1068 purify();
1069 }else if(mode==FOLLOW_MODE) {
1070 follow();
1071 }else if(mode==FUSE_MODE) {
1072 fuse();
1073 }else {
1074 throw new RuntimeException("Bad mode: "+mode);
1075 }
1076 }
1077 success=true;
1078 }
1079
1080 private int follow() {
1081 for(int i=tid; i<input.size(); i+=threads) {
1082 Bin a=input.get(i);
1083 assert(a.dest<0);
1084 if(a.pairMap!=null) {
1085 int dest=followEdges(a, contigs, oracle);
1086 if(dest>=0) {
1087 mergesT++;
1088 synchronized(a) {a.dest=dest;}
1089 }
1090 }
1091 }
1092 return mergesT;
1093 }
1094
1095 private int fuse() {
1096 for(int i=tid; i<input.size(); i+=threads) {
1097 Bin a=input.get(i);
1098 if(a.size()<fuseLowerLimit) {
1099 assert(false);
1100 break;
1101 }
1102 if(a.size()>fuseUpperLimit) {continue;}
1103 fuseSeeks++;
1104 Bin b=findBestFuseTarget(a);
1105 mergesT+=(b==null ? 0 : 1);
1106 fuseTargets+=(b==null ? 0 : 1);
1107 }
1108 // System.err.println("fuseSeeks="+fuseSeeks);
1109 // System.err.println("fuseCompares="+fuseCompares);
1110 // System.err.println("fuseTargets="+fuseTargets);
1111 return mergesT;
1112 }
1113
1114 private Bin findBestFuseTarget(Bin a) {
1115 oracle.best=null;
1116 oracle.topScore=-1;
1117 for(Bin b : input) {
1118 if(b.size()<fuseLowerLimit) {
1119 assert(false) : a.size()+", "+b.size();
1120 break;
1121 }
1122 if(b.size()<a.size()) {break;}
1123 if(b==a) {continue;}
1124 fuseCompares++;
1125 float f=oracle.similarity(a, b, 1);
1126 // if(f<=0) {
1127 // verbose=true;
1128 // oracle.similarity(a, b, 1);
1129 // assert(false);
1130 // }
1131 if(f>oracle.topScore) {
1132 assert(f>0) : f;//Actually, could be -1; or clear should set to -1
1133 oracle.best=b;
1134 oracle.topScore=f;
1135 }
1136 }
1137 // System.err.print('.');
1138 if(oracle.best!=null) {a.dest=oracle.best.id();}
1139 return oracle.best;
1140 }
1141
1142 private int purify() {
1143 for(int i=tid; i<input.size(); i+=threads) {
1144 Bin a=input.get(i);
1145 assert(a.isCluster() && a.numContigs()>1);
1146 synchronized(a) {
1147 mergesT+=purifyCluster((Cluster)a);
1148 }
1149 }
1150 return mergesT;
1151 }
1152
1153 private int purifyCluster(Cluster clust) {
1154 int changes=0;
1155 clust.dest=-1;
1156 @SuppressWarnings("unchecked")
1157 ArrayList<Contig> contigs=(ArrayList<Contig>) clust.contigs.clone();
1158 for(Contig a : contigs) {
1159 synchronized(a) {
1160 a.dest=-1;
1161 a.score=oracle.similarity(clust, a, 1);
1162 if(a.score<0) {
1163 a.dest=a.id();
1164 changes++;
1165 // synchronized(Binner.class) {
1166 // oracle.verbose2=true;
1167 // oracle.similarity(clust, a, 1);
1168 // assert(false);
1169 // }
1170 }
1171 }
1172 }
1173 Collections.sort(contigs, ScoreComparator.comparator);
1174 for(Contig a : contigs) {
1175 if(a.id()!=clust.id()) {
1176 Cluster b=map.findBestCluster(a, minSize, key, range, oracle);
1177 if(b!=null && b!=clust && oracle.score>=1.125f*a.score) {
1178 synchronized(a) {
1179 if(a.dest<0) {changes++;}
1180 a.dest=b.id();
1181 }
1182 // System.err.print(".");
1183 }else {
1184 break;
1185 }
1186 }
1187 }
1188 return changes;
1189 }
1190
1191 private void residue() {
1192 for(int i=tid; i<input.size(); i+=threads) {
1193 Bin a=input.get(i);
1194 synchronized(a) {
1195 a.dest=-1;
1196 Cluster b=findBestResidualCluster(a, map, key, oracle, range, minSize);
1197
1198 assert(a!=b);
1199 if(b==null) {
1200 b=findLinkedCluster(a, map.contigList);
1201 assert(a!=b);
1202 }
1203
1204 if(b!=null) {
1205 a.dest=b.id;
1206 assert(a!=b);
1207 assert(a.cluster()!=b);
1208 assert(map.contigList.get(b.id).cluster==b);
1209 }
1210 }
1211 }
1212 }
1213
1214 private void refine() {
1215 for(int i=tid; i<input.size(); i+=threads) {
1216 Bin a=input.get(i);
1217 synchronized(a) {
1218 a.dest=-1;
1219 if(a.size()>=minSizeToMerge) {
1220 refineBin(a);
1221 }
1222 }
1223 }
1224 }
1225
1226 private void refineBin(Bin a) {
1227 a.dest=-1;
1228 int minSize2=(int)Tools.mid(minSize, a.size(), Integer.MAX_VALUE);
1229 Cluster b=map.findBestCluster(a, minSize2, key, range, oracle);
1230
1231 if(b==null) {
1232 //do nothing
1233 }else {
1234 // assert(a.size()<=b.size());
1235 assert(a!=b);
1236 assert(a.id()!=b.id);
1237 assert(!b.contigSet.contains(a.id()));
1238 assert(a.cluster()==null || !a.cluster().contigSet.contains(b.id));
1239 a.dest=b.id;
1240 }
1241 }
1242
1243 final ArrayList<? extends Bin> input;
1244 final BinMap map;
1245 final ArrayList<Contig> contigs;
1246 final int tid;
1247 final int threads;
1248 final int mode;
1249
1250
1251 long fuseCompares=0;
1252 long fuseSeeks=0;
1253 long fuseTargets=0;
1254
1255 // final float maxKmerDif;
1256 // final float maxDepthRatio;
1257 // final float maxGCDif;
1258 // final float maxProduct;
1259 // final float maxCovariance;
1260 // final int taxLevel;
1261 // final boolean allowNoTaxID;
1262 // final boolean allowHalfTaxID;
1263 final int range;
1264 final int minSize;
1265 final Key key=new Key();
1266 final float[] ret=new float[1];
1267 final Oracle oracle;
1268 boolean success=false;
1269 int mergesT=0;
1270 }
1271
1272 static float sizeAdjustMult(long size) {
1273 float f=sizeAdjustMult2(size);
1274 if(size<tinyThresh){// && size>minSizeToCompare) {
1275 f*=tinyMult;//This is to correct the exemption from residueStringency
1276 }
1277 return f;
1278 }
1279
1280 static float sizeAdjustMult2(long size) {
1281 if(size<smallThresh) {return 1f+smallMult*(smallThresh-size)/(float)smallThresh;}
1282 if(size>2*hugeThresh) {return hugeMult;}
1283 if(size>hugeThresh) {
1284 float range=1f-hugeMult;
1285 return Tools.min(bigThresh, 1f-(size-hugeThresh)*range/hugeThresh);
1286 }
1287 if(size>2*bigThresh) {return bigMult;}
1288 if(size>bigThresh) {
1289 float range=1f-bigMult;
1290 return 1f-(size-bigThresh)*range/bigThresh;
1291 }
1292 return 1f;
1293 }
1294
1295 void addMerge(long size, boolean good) {
1296 int idx=(int)(Tools.log2(size));
1297 if(good) {goodMergeSize[idx]++;}
1298 else {badMergeSize[idx]++;}
1299 }
1300
1301 /*--------------------------------------------------------------*/
1302 /*---------------- Fields ----------------*/
1303 /*--------------------------------------------------------------*/
1304
1305 boolean multiThreadedCompare=true;
1306
1307 // long refinementComparisons=0;
1308 // long refinementComparisonsSlow=0;
1309 BinSketcher sketcher;
1310 int baseRange=1;
1311 int basePasses=1;
1312 int residueRange=3;
1313 boolean errorState=false;
1314 boolean runPassAA=false;
1315 boolean runPassA=true;
1316 boolean runPassB=false;
1317 boolean runPassC=true;
1318 boolean runPassD=true;
1319 boolean runPassE=true;
1320 boolean runPassF=false;
1321 boolean runPassG=true;
1322
1323 long goodMergesFollow=0;
1324 long badMergesFollow=0;
1325 long goodMergeSizeFollow=0;
1326 long badMergeSizeFollow=0;
1327 long goodMergesCreate=0;
1328 long badMergesCreate=0;
1329 long goodMergeSizeCreate=0;
1330 long badMergeSizeCreate=0;
1331 long goodMergesRefine=0;
1332 long badMergesRefine=0;
1333 long goodMergeSizeRefine=0;
1334 long badMergeSizeRefine=0;
1335 long goodMergesResidue=0;
1336 long badMergesResidue=0;
1337 long goodMergeSizeResidue=0;
1338 long badMergeSizeResidue=0;
1339
1340 long[] goodMergeSize=new long[40];
1341 long[] badMergeSize=new long[40];
1342
1343 BinMap binMap;
1344
1345 /*--------------------------------------------------------------*/
1346 /*---------------- Final Fields ----------------*/
1347 /*--------------------------------------------------------------*/
1348
1349 final Timer phaseTimer=new Timer();
1350 final PrintStream outstream;
1351
1352 /*--------------------------------------------------------------*/
1353 /*---------------- Static Fields ----------------*/
1354 /*--------------------------------------------------------------*/
1355
1356 static boolean PERFECT_ORACLE=false;
1357 static boolean BAN_BAD_MERGES=false;
1358
1359 static final int REFINE_MODE=0;
1360 static final int RESIDUE_MODE=1;
1361 static final int PURIFY_MODE=2;
1362 static final int FOLLOW_MODE=3;
1363 static final int FUSE_MODE=4;
1364
1365 static int fuseLowerLimit=5000;
1366 static int fuseUpperLimit=1000000;
1367 static float fuseStringency=1.56f;
1368 static float purifyStringency=3f;
1369
1370 static float residueStringency=0.6f;
1371 static float productMult=0.68f;
1372 static float minSimilarity=0.0f;
1373
1374 static int maxEdges=3;
1375 static int minEdgeWeight=2;
1376 static boolean reciprocalEdges=true;
1377 static float minEdgeRatio=0.4f;
1378
1379 static float lowDepthEdgeRatio=0.2f;
1380 static float highDepthEdgeRatio=2f;
1381 static float goodEdgeMult=1.4f;
1382 static float goodTransEdgeMult=1.3f;
1383
1384 static int hugeThresh=1200000;
1385 static float hugeMult=0.4f;
1386 static int bigThresh=100000;
1387 static float bigMult=0.75f;
1388 static int smallThresh=8000;
1389 static float smallMult=2.44f;
1390 static int tinyThresh=1000;
1391 static float tinyMult=0.72f;
1392
1393 // static int minSizeToCluster=0;
1394 // static int minSizeToRefine=500;
1395 /** Size of the bigger one */
1396 static int minSizeToCompare=3000;//2000
1397 /** Size of the smaller one being compared */
1398 static int minSizeToMerge=3000;//1500
1399 // static int minSizeToAdd=4000;//Should always be the same as minSizeToCompare...
1400 static int minSizeResidue=200;
1401 static int minNetSize=200;
1402 static int midNetSize=3000;
1403 static int largeNetSize=15000;
1404 static float netCutoffUpper=0.65f;
1405 static float netCutoffLower=0.547f;
1406 static float netCutoff_small=0.56f;
1407 static float netCutoff_mid=0.56f;
1408 static float netCutoff_large=0.56f;
1409 static float netMultUpper=1.4f;
1410 static float netMultLower=0.5f;
1411 static float cutoffMultA=2.7f;
1412 static float cutoffMultB=1.7f;
1413 static float cutoffMultC=1.6f;
1414 static float cutoffMultD=1.2f;
1415
1416 //Optimal selection when forming clusters
1417 static float maxTrimerDif1=0.1f;
1418 static float maxKmerDif1=0.002f;
1419 static float max5merDif1=0.1f;
1420 static float maxDepthRatio1=1.05f;
1421 static float maxGCDif1=0.01f;
1422 static float maxCovariance1=0.00005f;
1423
1424 //When merging clusters
1425 static float maxTrimerDif2=0.1f;
1426 static float maxKmerDif2=0.005f; //.005 for k=4; .012 for k=5; .008 for Euclid
1427 static float max5merDif2=0.007f;
1428 static float maxDepthRatio2=1.36f;
1429 static float maxGCDif2=0.03f; //0.02f for 1 depth, 0.05 for 4 depths
1430 static float maxCovariance2=0.002f;
1431 static float minKmerProb2=0.9f;
1432
1433 private int threadMerges=0;
1434 public AtomicLong fastComparisons=new AtomicLong(0);
1435 public AtomicLong slowComparisons=new AtomicLong(0);
1436 public AtomicLong netComparisons=new AtomicLong(0);
1437
1438 }