Debian Codegraph @

current/bin/DataLoader.java

raw symbols SCIP
1 package bin;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Collection;
8 import java.util.Collections;
9 import java.util.HashMap;
10 import java.util.Map.Entry;
11 import bloom.BloomFilter;
12 import bloom.KmerCountAbstract;
13 import dna.Data;
14 import fileIO.ByteFile;
15 import fileIO.ByteStreamWriter;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import ml.CellNet;
19 import ml.CellNetParser;
20 import shared.LineParser1;
21 import shared.LineParser2;
22 import shared.LineParserS1;
23 import shared.LineParserS4;
24 import shared.Parse;
25 import shared.Shared;
26 import shared.Timer;
27 import shared.Tools;
28 import stream.ConcurrentReadInputStream;
29 import stream.FastaReadInputStream;
30 import stream.Read;
31 import stream.SamLine;
32 import stream.SamLineStreamer;
33 import structures.ByteBuilder;
34 import structures.IntHashMap;
35 import structures.IntLongHashMap;
36 import structures.ListNum;
37 import tax.TaxTree;
38 import ukmer.Kmer;
39
40 public class DataLoader extends BinObject {
41
42 /*--------------------------------------------------------------*/
43 /*---------------- Initialization ----------------*/
44 /*--------------------------------------------------------------*/
45
46 DataLoader(PrintStream outstream_){outstream=outstream_;}
47
48 boolean parse(String arg, String a, String b) {
49
50 if(a.equals("tree")){
51 if(b==null || b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {
52 treePath="auto";
53 }else if(b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {
54 treePath=null;
55 }else {
56 treePath=b;
57 }
58 }else if(a.equals("maxdepths") || a.equals("maxdepthcount") || a.equals("samples")){
59 MAX_DEPTH_COUNT=Parse.parseIntKMG(b);
60 }else if(a.equals("maxedgestoprint")){
61 MAX_EDGES_TO_PRINT=Parse.parseIntKMG(b);
62 }else if(a.equals("maxreads")){
63 maxReads=Parse.parseKMG(b);
64 }else if(a.equals("mincontig") || a.equals("minsizetoload")){
65 minContigToLoad=Parse.parseIntKMG(b);
66 }else if(a.equals("mapq") || a.equals("minmapq")){
67 minMapq=Integer.parseInt(b);
68 }else if(a.equals("maxsubs")){
69 maxSubs=Integer.parseInt(b);
70 }else if(a.equalsIgnoreCase("tipLimit")){
71 tipLimit=Integer.parseInt(b);
72 }else if(a.equals("minid")){
73 minID=Float.parseFloat(b);
74 if(minID>1) {minID/=100;}
75 assert(minID>=0 && minID<=1) : minID;
76 }else if(a.equals("minmateid")){
77 minMateID=Float.parseFloat(b);
78 if(minMateID>1) {minMateID/=100;}
79 assert(minMateID>=0 && minMateID<=1) : minMateID;
80 }else if(a.equals("minentropy")){
81 minEntropy=Float.parseFloat(b);
82 assert(minEntropy>=0 && minEntropy<=1);
83 }else if(a.equals("minalignedbases")){
84 minAlignedBases=Integer.parseInt(b);
85 }
86
87 else if(a.equals("bloomk") || a.equals("kbloom")){
88 bloomkbig=Integer.parseInt(b);
89 bloomkbig=Kmer.getKbig(bloomkbig);
90 }else if(a.equals("bits") || a.equals("cbits")){
91 cbits=Integer.parseInt(b);
92 }else if(a.equals("ignoremissingcontigs")){
93 ignoreMissingContigs=Parse.parseBoolean(b);
94 }else if(a.equals("hashes")){
95 hashes=Integer.parseInt(b);
96 }
97
98 else if(a.equals("makegraph") || a.equals("makepairgraph")
99 || a.equals("pairmap") || a.equals("makepairmap")){
100 makePairGraph=Parse.parseBoolean(b);
101 }
102
103 else if(a.equalsIgnoreCase("streamContigs")){
104 streamContigs=Parse.parseBoolean(b);
105 }
106
107 else if(a.equals("network") || a.equals("netfile") || a.equals("net") || a.equals("nn")){
108 if(b==null || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {b=null;}
109 else if(b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {b="auto";}
110 netFileSmall=netFileMid=netFileLarge=b;
111 }else if(a.equals("netsmall") || a.equals("smallnet") || a.equals("nnsmall") || a.equals("smallnn")){
112 if(b==null || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {b=null;}
113 else if(b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {b="auto";}
114 netFileSmall=b;
115 }else if(a.equals("netmid") || a.equals("midnet") || a.equals("nnmid") || a.equals("midnn")){
116 if(b==null || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {b=null;}
117 else if(b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {b="auto";}
118 netFileMid=b;
119 }else if(a.equals("netlarge") || a.equals("largenet") || a.equals("nnlarge") || a.equals("largenn")){
120 if(b==null || b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {b=null;}
121 else if(b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {b="auto";}
122 netFileLarge=b;
123 }
124
125 else if(a.equals("samserial") || a.equals("loadsamserial")){
126 loadSamSerial=Parse.parseBoolean(b);
127 }else if(a.equals("samparallel") || a.equals("loadsamparallel")){
128 loadSamSerial=!Parse.parseBoolean(b);
129 }else if(a.equals("pentamers")){
130 countPentamers=Parse.parseBoolean(b);
131 }else if(a.equals("minpentamersize")){
132 minPentamerSizeCount=minPentamerSizeCompare=Parse.parseIntKMG(b);
133 }else if(a.equals("minpentamersizecount")){
134 minPentamerSizeCount=Parse.parseIntKMG(b);
135 }else if(a.equals("minpentamersizecompare")){
136 minPentamerSizeCompare=Parse.parseIntKMG(b);
137 }
138
139 else if(a.equals("ref") || a.equals("contigs") || a.equals("scaffolds") || a.equals("in")){
140 ref=b;
141 }else if(a.equals("readsin") || a.equals("reads1") || a.equals("read1") || a.equals("reads") || a.equals("sam") || a.equals("bam")){
142 readFiles.clear();
143 Tools.getFileOrFiles(b, readFiles, false, true, true, false);
144 }else if(a.equals("covstats")){
145 covstats.clear();
146 Tools.getFileOrFiles(b, covstats, true, true, true, true);
147 }else if(a.equals("cov") || a.equals("covin")){
148 covIn=b;
149 }else if(new File(arg).isFile()) {
150 if(looksLikeCovFile(arg)) {
151 System.err.println("Adding cov file "+ReadWrite.stripPath(arg));
152 covIn=arg;
153 }else {
154 FileFormat ff=FileFormat.testInput(arg, FileFormat.SAM, null, false, false);
155 if(ff.samOrBam() || ff.fastq()) {
156 System.err.println("Adding reads file "+ff.simpleName());
157 readFiles.add(arg);
158 }else if(ff.fasta()) {
159 System.err.println("Adding ref file "+ff.simpleName());
160 ref=arg;
161 }else if(ff.bbnet()){
162 System.err.println("Adding network file "+ff.simpleName());
163 netFileSmall=netFileMid=netFileLarge=arg;
164 }else if(b.contains("stats") && ff.text()){
165 System.err.println("Adding covstats file "+ff.simpleName());
166 covstats.add(arg);
167 }else {
168 return false;
169 }
170 }
171 }
172
173 else {return false;}
174
175 return true;
176 }
177
178 static boolean looksLikeCovFile(String s) {
179 if(s==null) {return false;}
180 String ext=ReadWrite.rawExtension(s);
181 if("txt".equals(ext) || "tsv".equals(ext) || "cov".equals(ext)) {
182 return s.contains("cov");
183 }
184 return false;
185 }
186
187 /*--------------------------------------------------------------*/
188 /*---------------- Validation ----------------*/
189 /*--------------------------------------------------------------*/
190
191 /** Adjust file-related static fields as needed for this program */
192 private static void checkStatics(){
193 //Adjust the number of threads for input file reading
194 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
195 ByteFile.FORCE_MODE_BF2=true;
196 }
197
198 assert(FastaReadInputStream.settingsOK());
199 }
200
201 void checkInput() {
202 //TODO; validate input files
203 }
204
205 /*--------------------------------------------------------------*/
206 /*---------------- Wrapper ----------------*/
207 /*--------------------------------------------------------------*/
208
209 ArrayList<Contig> loadData() {
210 ArrayList<Contig> contigs=loadContigs(ref);
211
212 // sizeMap=sc.sizeMap;
213 // phaseTimer.stopAndPrint();
214
215 if(validation && makePairGraph) {
216 validateEdges(contigs);
217 }
218
219 if(sketchContigs) {
220 System.err.println("Sketching contigs. ");
221 sketcher.sketch(contigs, true);
222 }
223
224 //Reset read validation
225 Read.VALIDATE_IN_CONSTRUCTOR=true;//should be adjusted for many threads
226 numDepths=(contigs.isEmpty()) ? 0 : contigs.get(0).numDepths();
227 assert(numDepths>0) : "At least one depth is required.";
228
229 net0small=loadNetwork(netFileSmall, "all", Binner.netCutoff_small, numDepths);
230 net0mid=loadNetwork(netFileMid, "all", Binner.netCutoff_mid, numDepths);
231 net0large=loadNetwork(netFileLarge, "all", Binner.netCutoff_large, numDepths);
232
233 if(net0small==null && net0mid==null && net0large==null) {
234 Binner.cutoffMultA=Binner.cutoffMultB=Binner.cutoffMultC=Binner.cutoffMultD=1;
235 }
236
237 allContigs=contigs;
238 return contigs;
239 }
240
241 int fixEdges(final Contig c, final int numContigs) {
242 if(c.pairMap==null) {return 0;}
243 int removed=0, seen=0;
244 for(KeyValue kv : KeyValue.toList(c.pairMap)) {
245 seen++;
246 if(kv.key>=numContigs) {
247 c.pairMap.remove(kv.key);
248 removed++;
249 }
250 }
251 if(removed>=seen) {c.pairMap=null;}
252 return removed;
253 }
254
255 public ArrayList<Contig> loadContigs(String fname){
256
257 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
258 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
259
260 final boolean parseCov=(covIn==null && readFiles.isEmpty() && covstats.isEmpty());
261 final ArrayList<Contig> contigs=loadAndProcessContigs(fname, parseCov);
262
263 if(parseCov) {
264 depthCalculated=true;
265 }else {
266 calculateDepth(contigs);
267 }
268 if(streamContigs && contigs.get(0).numDepths()>1) {//Normally handled by SpectraCounter
269 for(Contig c : contigs) {
270 synchronized(c) {
271 float[] f=c.normDepth();
272 assert(f!=null);
273 assert(f.length==c.numDepths()) : f.length+", "+c.numDepths();
274 }
275 }
276 }
277 assert(depthCalculated);
278 assert(isValid(contigs, false)) : parseCov;
279
280 long removedEdges=0;
281 phaseTimer.start();
282 for(Contig c : contigs) {
283 removedEdges+=fixEdges(c, contigs.size());
284 }
285 if(removedEdges>0) {
286 phaseTimer.stop("Removed "+removedEdges+" edges: \t");
287 }
288
289 Read.VALIDATE_IN_CONSTRUCTOR=vic;
290
291 return contigs;//not necessarily optimal
292 }
293
294 public ArrayList<Contig> loadAndProcessContigs(String fname, boolean parseCov) {
295 return streamContigs ? loadAndProcessContigsMT(fname, parseCov) :
296 loadAndProcessContigsST(fname, parseCov);
297 }
298
299 public ArrayList<Contig> loadAndProcessContigsMT(String fname, boolean parseCov) {
300 final ArrayList<Contig> contigs=new ArrayList<Contig>();
301 boolean parseTID=validation;
302 sizeMap=new IntLongHashMap(1023);
303
304 FileFormat ff=FileFormat.testInput(fname, FileFormat.FASTA, null, true, true);
305 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff, null);
306 cris.start(); //Start the stream
307 if(verbose){outstream.println("Started cris");}
308 outstream.print("Loading contigs:\t");
309 phaseTimer.start();
310 SpectraCounter sc=new SpectraCounter(outstream, parseCov, parseTID, sizeMap);
311 sc.makeSpectra(contigs, cris, minContigToLoad);
312 errorState|=sc.errorState;
313 contigsLoaded+=sc.contigsLoaded;
314 basesLoaded+=sc.basesLoaded;
315 contigsRetained+=sc.contigsRetained;
316 basesRetained+=sc.basesRetained;
317 phaseTimer.stopAndPrint();
318 Collections.sort(contigs);
319 for(int i=0; i<contigs.size(); i++) {contigs.get(i).setID(i);}
320 errorState|=ReadWrite.closeStream(cris);
321
322 return contigs;
323 }
324
325 public ArrayList<Contig> loadAndProcessContigsST(String fname, boolean parseCov) {
326 final ArrayList<Contig> contigs=loadContigsST(ref, minContigToLoad);
327 boolean parseTID=false;
328 outstream.print("Calculating kmer frequency spectra: \t");
329 SpectraCounter sc=new SpectraCounter(outstream, parseCov, parseTID, sizeMap);
330 sc.makeSpectra(contigs, null, minContigToLoad);
331 phaseTimer.stopAndPrint();
332 return contigs;
333 }
334
335 /*--------------------------------------------------------------*/
336 /*---------------- Data Loading ----------------*/
337 /*--------------------------------------------------------------*/
338
339 CellNet loadNetwork(String fname, String size, float cutoff, int samples) {
340 if(fname==null) {return null;}
341 String d=(samples<2 ? "1" : "N");
342 if(fname.equals("auto")) {
343 //E.G. "?quickbin1D_small.bbnet" or "?quickbinND_small.bbnet"
344 fname=Data.findPath("?quickbin"+d+"D_"+size+".bbnet", false);
345 }
346 CellNet net0=CellNetParser.load(fname);
347 if(cutoff!=-9999) {net0.cutoff=cutoff;}
348 return net0;
349 }
350
351 void calculateDepth(ArrayList<Contig> contigs) {
352 final boolean sam=(!readFiles.isEmpty() && FileFormat.isSamOrBamFile(readFiles.get(0)));
353
354 if(covIn!=null) {
355 loadCovFile(covIn, contigs, MAX_DEPTH_COUNT);
356 }else if(covstats.size()>0) {
357 HashMap<String, Contig> contigMap=toMap(contigs);
358 for(int i=0; i<readFiles.size(); i++) {
359 calcDepthFromCovStats(covstats.get(i), i, contigMap, minContigToLoad);
360 }
361 }else if(sam) {
362 Timer t=new Timer(outstream);
363 HashMap<String, Contig> contigMap=toMap(contigs);
364 long readsUsed=0;
365 if(loadSamSerial) {
366 for(int i=0; i<readFiles.size(); i++) {
367 FileFormat ff=FileFormat.testInput(readFiles.get(i), FileFormat.SAM, null, true, false);
368 calcDepthFromSam(ff, i, contigMap);
369 }
370 }else {
371 if(makePairGraph) {graph=new IntHashMap[contigMap.size()];}
372
373 SamLine.PARSE_0=false;
374 SamLine.PARSE_7=false;
375 SamLine.PARSE_8=false;
376 SamLine.PARSE_10=false;
377 SamLine.PARSE_OPTIONAL_MATEQ_ONLY=true;
378 // public static boolean PARSE_OPTIONAL=true;
379 // public static boolean PARSE_OPTIONAL_MD_ONLY=false;
380
381 SamLoader samLoader=new SamLoader(outstream);
382 samLoader.minMapq=minMapq;
383 samLoader.minMateq=minMapq;
384
385 samLoader.minID=minID;
386 samLoader.minMateID=minMateID;
387 samLoader.maxSubs=maxSubs;
388 samLoader.tipLimit=tipLimit;
389 samLoader.minEntropy=minEntropy;
390 samLoader.minAlignedBases=minAlignedBases;
391
392 samLoader.load(readFiles, contigMap, contigs, graph);
393 readsUsed=samLoader.readsUsed;
394 if(makePairGraph) {
395 synchronized(graph) {
396 for(int i=0; i<contigs.size(); i++) {
397 Contig c=contigs.get(i);
398 IntHashMap pairMap=graph[i];
399 if(pairMap!=null) {
400 synchronized(c) {
401 synchronized(pairMap) {c.pairMap=pairMap;}
402 }
403 }
404 }
405 }
406 }
407 depthCalculated=true;
408 }
409 t.stop("Loaded "+Tools.plural("file", readFiles.size())+" and "+readsUsed+" reads: ");
410 }
411
412 if(readFiles.isEmpty() && !depthCalculated) {
413 calcDepthFromHeader(contigs);
414 }else if(!readFiles.isEmpty() && !sam) {
415 for(int i=0; i<readFiles.size(); i++) {
416 BloomFilter bloomFilter=makeBloomFilter(readFiles.get(i), null);
417 calcDepthFromBloomFilter(contigs, bloomFilter, 0);
418 }
419 }
420 }
421
422 void validateEdges(ArrayList<Contig> contigs) {
423 //TODO: add cov file only flag to quickbin
424 //TODO: have BBMap suppress ambig or low-Q alignments
425 //TODO: track good/bad rates of first, second, 3rd, and nth edges
426 //TODO: suppress edges not near contig ends
427 //TODO: Track good/bad rate as a function of relative weight to top edge.
428 //TODO: Track good/bad rate as a function of edge weight.
429 outstream.println("Validating edges: ");
430 phaseTimer.start();
431 long goodEdges=0, badEdges=0, otherEdges=0;
432 long goodWeight=0, badWeight=0, otherWeight=0;
433 long reciprocalGood=0, reciprocalBad=0, reciprocalOther=0;
434 long sizeSumGood=0;
435 long sizeSumBad=0;
436 final int max=4;
437 long[] edgeCount=new long[max+1];
438 long[] weightCount=new long[max+1];
439 for(Contig c : contigs) {
440 IntHashMap pairMap=c.pairMap;
441 if(pairMap==null) {
442 edgeCount[0]++;
443 }else {
444 final int[] keys=pairMap.keys(), values=pairMap.values();
445 final int invalid=pairMap.invalid();
446 edgeCount[Tools.min(max, pairMap.size())]++;
447 for(int kpos=0; kpos<keys.length; kpos++) {
448 int dest=keys[kpos], weight=values[kpos];
449 if(dest!=invalid) {
450 weightCount[Tools.min(max, weight)]++;
451 Contig c2=contigs.get(dest);
452 boolean reciprocal=(c2.pairMap!=null && c2.pairMap.contains(c.id()));
453 if(c.labelTaxid<1 || c2.labelTaxid<1) {
454 otherEdges++;
455 otherWeight+=weight;
456 if(reciprocal) {reciprocalOther++;}
457 // assert(false) : "\n"+c+"\n"+c2+"\n";
458 }else if(c.labelTaxid==c2.labelTaxid) {
459 goodEdges++;
460 goodWeight+=weight;
461 if(reciprocal) {reciprocalGood++;}
462 sizeSumGood+=Tools.min(c.size(), c2.size());
463 }else {
464 badEdges++;
465 badWeight+=weight;
466 if(reciprocal) {reciprocalBad++;}
467 sizeSumBad+=Tools.min(c.size(), c2.size());
468 }
469 }
470 }
471 }
472 }
473 phaseTimer.stopAndPrint();
474 if(!loud) {return;}
475 outstream.println("Type: \tGood\tBad\tOther");
476 outstream.println("Edges: \t"+goodEdges+"\t"+badEdges+"\t"+otherEdges);
477 outstream.println("Reciprocal: \t"+reciprocalGood+"\t"+reciprocalBad+"\t"+reciprocalOther);
478 float w1=goodWeight*1f/goodEdges;
479 float w2=badWeight*1f/badEdges;
480 float w3=otherWeight*1f/otherEdges;
481 outstream.println(String.format("Weights: \t%.2f\t%.2f\t%.2f", w1, w2, w3));
482 float s1=sizeSumGood*1f/goodEdges;
483 float s2=sizeSumBad*1f/badEdges;
484 outstream.println(String.format("Sizes: \t%.2f\t%.2f", s1, s2));
485 outstream.println("Counts: \t0\t1\t2\t3\t4+");
486 outstream.println("Edges: \t"+Arrays.toString(edgeCount));
487 outstream.println("Weights: \t"+Arrays.toString(weightCount));
488 }
489
490 TaxTree loadTree() {
491 if("auto".equals(treePath)){treePath=TaxTree.defaultTreeFile();}
492 if(treePath!=null) {
493 tree=TaxTree.loadTaxTree(treePath, outstream, false, false);
494 }
495 return tree;
496 }
497
498 HashMap<String, Contig> toMap(Collection<Contig> list){
499 HashMap<String, Contig> map=new HashMap<String, Contig>(list.size());
500 for(Contig c : list) {map.put(c.shortName, c);}
501 return map;
502 }
503
504 ArrayList<Contig> loadContigsST(String fname, int minlen){
505 //Turn off read validation in the input threads to increase speed
506 assert(fname!=null) : "No contigs specified.";
507 outstream.print("Loading contigs:\t");
508 phaseTimer.start();
509 sizeMap=new IntLongHashMap(1023);
510 FileFormat ff=FileFormat.testInput(fname, FileFormat.FASTA, null, true, true);
511 ArrayList<Contig> list=new ArrayList<Contig>();
512
513 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff, null);
514 cris.start(); //Start the stream
515 if(verbose){outstream.println("Started cris");}
516
517 //Grab the first ListNum of reads
518 ListNum<Read> ln=cris.nextList();
519
520 //Check to ensure pairing is as expected
521 if(ln!=null && !ln.isEmpty()){
522 Read r=ln.get(0);
523 assert(r.mate==null);
524 }
525
526 //As long as there is a nonempty read list...
527 while(ln!=null && ln.size()>0){
528
529 for(Read r : ln) {
530 Contig c=loadContig(r, minlen);
531 if(c!=null) {list.add(c);}
532 }
533
534 //Notify the input stream that the list was used
535 cris.returnList(ln);
536 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
537
538 //Fetch a new list
539 ln=cris.nextList();
540 }
541
542 //Notify the input stream that the final list was used
543 if(ln!=null){
544 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
545 }
546 errorState|=ReadWrite.closeStream(cris);
547 phaseTimer.stopAndPrint();
548 Collections.sort(list);
549 for(int i=0; i<list.size(); i++) {list.get(i).setID(i);}
550 return list;
551 }
552
553 Contig loadContig(Read r, int minlen) {
554 contigsLoaded++;
555 basesLoaded+=r.length();
556 int tid=-1;
557 if(validation) {
558 tid=parseTaxID(r.name());
559 if(tid>0) {sizeMap.increment(tid, r.length());}
560 }
561 if(r.length()<minlen) {return null;}
562 contigsRetained++;
563 basesRetained+=r.length();
564 Contig c=new Contig(r.name(), r.bases, (int)contigsRetained);
565 c.labelTaxid=tid;
566 // if(tid>0) {
567 // c.labelTaxid=tid;
568 // if(!validation) {c.taxid=tid;}
569 // }
570 return c;
571 }
572
573 public static int parseTaxID(String line) {
574 if(!parseTaxid) {return -1;}
575 final String term="tid_";
576 int pos=line.indexOf(term);
577 if(pos<0) {return -1;}
578 long id=0;
579 for(int i=pos+4; i<line.length(); i++) {
580 char c=line.charAt(i);
581 if(c<'0' || c>'9') {break;}
582 id=id*10+(c-'0');
583 }
584 assert(id>0 && id<Integer.MAX_VALUE) : id+"\n"+line+"\n";
585 return (int)id;
586 }
587
588 BloomFilter makeBloomFilter(String in1, String in2) {
589 // if(ffin1.samOrBam()) {return null;}
590 outstream.print("Making Bloom filter: \t");
591 KmerCountAbstract.CANONICAL=true;
592 bloomkbig=Kmer.getKbig(bloomkbig);
593 int bloomk=Kmer.getK(bloomkbig);
594 BloomFilter filter=new BloomFilter(in1, in2, null, bloomk, bloomkbig, cbits, hashes, 1,
595 true, false, false, 0.5f);
596 phaseTimer.stopAndPrint();
597 outstream.println(filter.filter.toShortString());
598 return filter;
599 }
600
601 void calcDepthFromCovStats(String fname, int sample, HashMap<String, Contig> contigMap, int minlen) {
602 ByteFile bf=ByteFile.makeByteFile(fname, true);
603 outstream.print("Loading covstats file ("+fname+"): \t");
604 byte[] line=null;
605 LineParser2 lp=new LineParser2('\t');
606 int found=0;
607 for(line=bf.nextLine(); line!=null; line=bf.nextLine()){
608 if(Tools.startsWith(line, '#')) {
609 //header
610 assert(Tools.startsWith(line, "#ID\tAvg_fold")) : new String(line);
611 }else {
612 lp.set(line);
613 String name=lp.parseString();
614 String shortName=ContigRenamer.toShortName(name);
615 float depth=lp.parseFloat();
616 Contig c=contigMap.get(shortName);
617 assert(c!=null || minlen>0 || ignoreMissingContigs) :
618 "Can't find contig that is specified in covstats: "+shortName;
619 if(c!=null) {
620 if(c!=null) {
621 c.setDepth(depth, sample);
622 found++;
623 }
624 }
625 }
626 }
627 assert(found<=contigMap.size()) : "Duplicate entries found in covstats file.";
628 assert(found==contigMap.size() || minlen>0) : "Some contigs were not found in covstats file.";
629 assert(found>0) : "No matching entries found in covstats file.";
630 depthCalculated=true;
631 phaseTimer.stopAndPrint();
632 }
633
634 @Deprecated
635 void calcDepthFromSam(FileFormat ff, final int sample, HashMap<String, Contig> contigMap) {
636 SamLineStreamer ss=null;
637 outstream.print("Loading sam file: \t");
638 phaseTimer.start();
639 final int streamerThreads=Tools.min(4, Shared.threads());
640 ss=new SamLineStreamer(ff, streamerThreads, false, maxReads);
641 ss.start();
642 processSam(ss, sample, contigMap);
643 for(Entry<String, Contig> e : contigMap.entrySet()) {
644 Contig c=e.getValue();
645 c.setDepth(c.depthSum/(Tools.max(1f, c.bases.length)), sample);
646 c.depthSum=0;
647 }
648 depthCalculated=true;
649 phaseTimer.stopAndPrint();
650 }
651
652 @Deprecated
653 private void processSam(SamLineStreamer ss, final int sample, HashMap<String, Contig> contigMap) {
654 ListNum<SamLine> ln=ss.nextLines();
655 ArrayList<SamLine> reads=(ln==null ? null : ln.list);
656
657 while(ln!=null && reads!=null && reads.size()>0){
658
659 for(int idx=0; idx<reads.size(); idx++){
660 SamLine sl=reads.get(idx);
661 if(sl.mapped()) {
662 String rname=ContigRenamer.toShortName(sl.rname());
663 Contig c=contigMap.get(rname);
664 assert(c!=null || minContigToLoad>0 || ignoreMissingContigs) :
665 "Can't find contig for rname "+rname+"\nsize="+contigMap.size()
666 +"\n[0]="+contigMap.keySet().toArray(new String[0])[0];
667 if(c!=null) {
668 c.depthSum+=sl.length();
669 }
670 }
671 }
672 ln=ss.nextLines();
673 reads=(ln==null ? null : ln.list);
674 }
675 }
676
677 public void calcDepthFromHeader(Collection<Contig> list) {
678 outstream.print("Parsing depth from contig headers: \t");
679 phaseTimer.start();
680 LineParserS1 lps=new LineParserS1('_');
681 LineParserS4 lpt=new LineParserS4(",,=,");
682 for(Contig c : list) {
683 boolean b=parseAndSetDepth(c, lps, lpt);
684 assert(b) : "Could not parse depth from "+c.name;
685 // c.depthepth=parseDepth(c.name, lps, lpt);
686 }
687 depthCalculated=true;
688 phaseTimer.stopAndPrint();
689 }
690
691 public static boolean parseAndSetDepth(Contig c, LineParserS1 lps, LineParserS4 lpt) {
692 String name=c.name;
693 c.clearDepth();
694 if(name.contains(" cov_")) {//Multiple coverage
695 String[] array=Tools.whitespacePlus.split(name);
696 for(String s : array) {
697 lps.set(s);
698 if(lps.terms()==2 && lps.termEquals("cov", 0)) {
699 float depth=lps.parseFloat(1);
700 c.appendDepth(depth);
701 if(c.numDepths()>=MAX_DEPTH_COUNT) {break;}
702 }
703 }
704 }else if(name.startsWith("NODE_") && name.contains("_cov_")) {//Spades
705 lps.set(name);
706 float depth=lps.parseFloat(5);
707 c.setDepth(depth, 0);
708 }else if(name.startsWith("contig_") && name.contains(",cov=")) {//Tadpole
709 lpt.set(name);
710 float depth=lpt.parseFloat(3);
711 c.setDepth(depth, 0);
712 }else if(name.contains("_cov_")) {//Generic
713 lps.set(name);
714 for(int i=0; i<lps.terms()-1; i++) {
715 if(lps.termEquals("cov", i)) {
716 i++;
717 c.appendDepth(lps.parseFloat(i));
718 }
719 }
720 }else {
721 return false;
722 }
723 return true;
724 }
725
726 public void calcDepthFromBloomFilter(Collection<Contig> list, BloomFilter bf, int sample) {
727 outstream.print("Calculating depth from Bloom filter: \t");
728 for(Contig c : list) {c.setDepth(bf.averageCount(c.bases), sample);}
729 depthCalculated=true;
730 phaseTimer.stopAndPrint();
731 }
732
733 public void loadCovFile(String fname, ArrayList<Contig> contigs, final int maxSamples) {
734 outstream.print("Loading coverage from "+fname+": \t");
735 phaseTimer.start();
736 LineParser1 lp=new LineParser1('\t');
737 ByteFile bf=ByteFile.makeByteFile(fname, true);
738
739 byte[] line=bf.nextLine();
740 int numDepths=0;
741 for(; Tools.startsWith(line, '#'); line=bf.nextLine()) {
742 if(Tools.startsWith(line, "#Depths")) {
743 numDepths=lp.set(line).parseInt(1);
744 }
745 }
746 assert(numDepths>0) : numDepths;
747 final int edgeStart=3+numDepths;
748 final int samples=Tools.min(numDepths, maxSamples);
749 int loaded=0;
750 for(; line!=null; line=bf.nextLine()) {
751 lp.set(line);
752 int id=lp.parseInt(1);
753 if(id>=contigs.size()) {continue;}//Presumably small contigs that were not loaded
754 int size=lp.parseInt(2);
755 int edges=(lp.terms()-edgeStart)/2;
756 Contig c=contigs.get(id);
757 assert(c.id()==id);
758 assert(c.size()==size) : c.name()+", "+c.size()+", "+size+"\n"+new String(line);
759 assert(lp.termEquals(c.shortName, 0));
760 assert(c.numDepths()==0);
761 for(int i=0; i<samples; i++) {
762 float f=lp.parseFloat(i+3);
763 c.setDepth(f, i);
764 }
765 if(lp.terms()>edgeStart && makePairGraph) {
766 c.pairMap=new IntHashMap((1+(edges*4)/3)|1);
767 for(int term=edgeStart; term<lp.terms(); term+=2) {
768 int dest=lp.parseInt(term);
769 int weight=lp.parseInt(term+1);
770 c.pairMap.put(dest, weight);
771 }
772 }
773 loaded++;
774 }
775 assert(loaded==contigs.size()) : loaded+", "+contigs.size();
776 depthCalculated=true;
777 phaseTimer.stopAndPrint();
778 }
779
780 public long trimEdges(ArrayList<Contig> contigs, int maxEdges, int minWeight, boolean reciprocal) {
781 phaseTimer.start();
782 long trimmed=trimEdgesPass(contigs, maxEdges+99, minWeight, reciprocal);
783 trimmed+=trimEdgesPass(contigs, maxEdges, minWeight, reciprocal);
784 phaseTimer.stop("Trimmed "+trimmed+" edges: ");
785 return trimmed;
786 }
787
788 public long trimEdgesPass(ArrayList<Contig> contigs, int maxEdges, int minWeight, boolean reciprocal) {
789 // Timer t=new Timer(outstream);
790 long trimmed=0;
791 for(int i=0; i<contigs.size(); i++) {
792 Contig c=contigs.get(i);
793 assert(c.id()==i);
794 if(c.pairMap!=null) {
795 trimmed+=c.pairMap.size();
796 ArrayList<KeyValue> list=KeyValue.toList(c.pairMap);
797 c.pairMap.clear();
798 for(KeyValue kv : list) {
799 if(c.pairMap.size()>=Binner.maxEdges) {break;}
800 if(kv.value>=minWeight && kv.key<contigs.size()) {
801 if(!reciprocal || contigs.get(kv.key).countEdgesTo(c)>minWeight) {
802 c.pairMap.put(kv.key, kv.value);
803 }
804 }
805 }
806 trimmed-=c.pairMap.size();
807 if(c.pairMap.isEmpty()) {c.pairMap=null;}
808 }
809 }
810 return trimmed;
811 }
812
813 public static void writeCov(String fname, Collection<Contig> contigs, int numDepths, PrintStream outstream) {
814 outstream.print("Writing coverage to "+fname+": ");
815 Timer t=new Timer(outstream);
816 ByteStreamWriter bsw=new ByteStreamWriter(fname, true, false, true);
817 bsw.start();
818 ByteBuilder bb=new ByteBuilder();
819 bb.append("#Contigs\t").append(contigs.size()).nl();
820 bb.append("#Depths\t").append(numDepths).nl();
821 bb.append("#ShortName\tID\tSize");
822 for(int i=0; i<numDepths; i++) {bb.tab().append("Cov_"+i);}
823 bb.tab().append("Edge\tWeight");
824 bsw.println(bb);
825 for(Contig c : contigs) {
826 c.toCov(bb.clear());
827 bsw.print(bb.nl());
828 }
829 bsw.poisonAndWait();
830 t.stopAndPrint();
831 }
832
833 /*--------------------------------------------------------------*/
834 /*---------------- Fields ----------------*/
835 /*--------------------------------------------------------------*/
836
837 /** Assembly path */
838 String ref=null;
839 String covIn=null;
840
841 String netFileSmall="auto";
842 String netFileMid="auto";
843 String netFileLarge="auto";
844
845 private final ArrayList<String> covstats=new ArrayList<String>();
846
847 /** Primary read input file path */
848 private final ArrayList<String> readFiles=new ArrayList<String>();
849
850 // /** Primary read input file */
851 // FileFormat ffin1;
852
853 boolean depthCalculated=false;
854 boolean ignoreMissingContigs=false;
855
856 long contigsLoaded=0;
857 long basesLoaded=0;
858
859 long contigsRetained=0;
860 long basesRetained=0;
861
862 private int bloomkbig=31;
863 private int cbits=16;
864 private int hashes=3;
865
866 BinSketcher sketcher;
867
868 int minContigToLoad=100;
869 int minMapq=20;
870 float minID=0.96f;//Optimal results so far are from 0.98 but that is pretty high
871 float minMateID=0.97f;
872 int maxSubs=999;
873 float minEntropy=0;
874 int tipLimit=100;
875 int minAlignedBases=1;
876 int gap=0;
877
878 /** Quit after processing this many input reads; -1 means no limit */
879 private long maxReads=-1;
880
881 String treePath="auto";
882 TaxTree tree;
883
884 IntLongHashMap sizeMap;
885 IntHashMap[] graph;
886
887 static int MAX_DEPTH_COUNT=999;
888 static int MAX_EDGES_TO_PRINT=8;
889 static boolean loadSamSerial=false;
890 boolean makePairGraph=true;
891 int numDepths=0;
892 static boolean streamContigs=true;
893 boolean errorState=false;
894
895 static ArrayList<Contig> allContigs;
896
897 /*--------------------------------------------------------------*/
898 /*---------------- Final Fields ----------------*/
899 /*--------------------------------------------------------------*/
900
901 final Timer phaseTimer=new Timer();
902 final PrintStream outstream;
903 // static final Pattern covPattern=Pattern.compile(" cov_");
904
905 }