Debian Codegraph @

current/assemble/KmerCompressor.java

raw symbols SCIP
1 package assemble;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.BitSet;
7 import java.util.concurrent.atomic.AtomicInteger;
8 import java.util.concurrent.atomic.AtomicLong;
9
10 import dna.AminoAcid;
11 import fileIO.ByteFile;
12 import fileIO.ByteStreamWriter;
13 import fileIO.FileFormat;
14 import fileIO.ReadWrite;
15 import kmer.AbstractKmerTable;
16 import kmer.AbstractKmerTableSet;
17 import kmer.HashArray1D;
18 import kmer.HashForest;
19 import kmer.KmerNode;
20 import kmer.KmerTableSet;
21 import shared.Parse;
22 import shared.Parser;
23 import shared.PreParser;
24 import shared.Shared;
25 import shared.Timer;
26 import shared.Tools;
27 import sort.ContigLengthComparator;
28 import sort.ReadLengthComparator;
29 import stream.FastaReadInputStream;
30 import structures.ByteBuilder;
31 import structures.IntList;
32 import structures.LongList;
33 import tracker.ReadStats;
34 import ukmer.Kmer;
35 import ukmer.KmerTableSetU;
36
37
38 /**
39 * Assembles kmers into a concise representation.
40 * @author Brian Bushnell
41 * @date May 15, 2015
42 *
43 */
44 public class KmerCompressor {
45
46 /**
47 * Code entrance from the command line.
48 * @param args Command line arguments
49 */
50 public static void main(String[] args){
51 Timer t=new Timer(), t2=new Timer();
52 t.start();
53 t2.start();
54
55 final KmerCompressor x=new KmerCompressor(args, true);
56 t2.stop();
57 outstream.println("Initialization Time: \t"+t2);
58
59 ///And run it
60 x.process(t);
61
62 //Close the print stream if it was redirected
63 Shared.closeStream(outstream);
64 }
65
66 public static final int preparseK(String[] args){
67 int k=31;
68 for(int i=0; i<args.length; i++){
69 final String arg=args[i];
70 String[] split=arg.split("=");
71 String a=split[0].toLowerCase();
72 String b=split.length>1 ? split[1] : null;
73
74 if(a.equals("k")){
75 k=Integer.parseInt(b);
76 }
77 }
78 return Kmer.getMult(k)*Kmer.getK(k);
79 }
80
81 /**
82 * Constructor.
83 * @param args Command line arguments
84 */
85 public KmerCompressor(String[] args, boolean setDefaults){
86
87 {//Preparse block for help, config files, and outstream
88 PreParser pp=new PreParser(args, getClass(), false);
89 args=pp.args;
90 outstream=pp.outstream;
91 }
92
93 k=preparseK(args);
94
95 if(setDefaults){
96 /* Set global defaults */
97 ReadWrite.ZIPLEVEL=8;
98 ReadWrite.USE_UNPIGZ=true;
99 ReadWrite.USE_PIGZ=true;
100 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
101 ByteFile.FORCE_MODE_BF2=true;
102 }
103 AbstractKmerTableSet.defaultMinprob=0.5;
104 }
105
106 /* Initialize local variables with defaults */
107 Parser parser=new Parser();
108 ArrayList<String> in1=new ArrayList<String>();
109 ArrayList<String> in2=new ArrayList<String>();
110 int fuse_=0;
111
112 /* Parse arguments */
113 for(int i=0; i<args.length; i++){
114
115 final String arg=args[i];
116 String[] split=arg.split("=");
117 String a=split[0].toLowerCase();
118 String b=split.length>1 ? split[1] : null;
119
120 if(Parser.parseCommonStatic(arg, a, b)){
121 //do nothing
122 }else if(Parser.parseZip(arg, a, b)){
123 //do nothing
124 }else if(Parser.parseQuality(arg, a, b)){
125 //do nothing
126 }else if(Parser.parseFasta(arg, a, b)){
127 //do nothing
128 }else if(parser.parseInterleaved(arg, a, b)){
129 //do nothing
130 }else if(parser.parseTrim(arg, a, b)){
131 //do nothing
132 }else if(a.equals("in") || a.equals("in1")){
133 in1.clear();
134 if(b!=null){
135 String[] s=b.split(",");
136 for(String ss : s){
137 in1.add(ss);
138 }
139 }
140 }else if(a.equals("in2")){
141 in2.clear();
142 if(b!=null){
143 String[] s=b.split(",");
144 for(String ss : s){
145 in2.add(ss);
146 }
147 }
148 }else if(a.equals("out") || a.equals("contigs")){
149 outContigs=b;
150 }else if(a.equals("append") || a.equals("app")){
151 append=ReadStats.append=Parse.parseBoolean(b);
152 }else if(a.equals("overwrite") || a.equals("ow")){
153 overwrite=Parse.parseBoolean(b);
154 }else if(a.equals("fuse")){
155 if(b==null || Character.isLetter(b.charAt(0))){
156 fuse_=Parse.parseBoolean(b) ? 100000 : 0;
157 }else{
158 fuse_=Integer.parseInt(b);
159 }
160 }else if(a.equals("showstats") || a.equals("stats")){
161 showStats=Parse.parseBoolean(b);
162 }else if(a.equals("mincount") || a.equals("mincov") || a.equals("mindepth") || a.equals("min")){
163 minCount=Parse.parseIntKMG(b);
164 }else if(a.equals("maxcount") || a.equals("maxcov") || a.equals("maxdepth") || a.equals("max")){
165 maxCount=Parse.parseIntKMG(b);
166 }else if(a.equals("requiresamecount") || a.equals("rsc") || a.equals("rsd")){
167 REQUIRE_SAME_COUNT=Parse.parseBoolean(b);
168 }else if(a.equals("threads") || a.equals("t")){
169 Shared.setThreads(b);
170 }else if(a.equals("buildthreads") || a.equals("bthreads") || a.equals("bt")){
171 assert(b!=null) : "Bad parameter: "+arg;
172 if(b.equalsIgnoreCase("auto")){
173 BUILD_THREADS=Shared.threads();
174 }else{
175 BUILD_THREADS=Integer.parseInt(b);
176 }
177 }else if(a.equals("showspeed") || a.equals("ss")){
178 showSpeed=Parse.parseBoolean(b);
179 }else if(a.equals("verbose")){
180 // assert(false) : "Verbose flag is currently static final; must be recompiled to change.";
181 verbose=Parse.parseBoolean(b);
182 }else if(a.equals("verbose2")){
183 // assert(false) : "Verbose flag is currently static final; must be recompiled to change.";
184 verbose2=Parse.parseBoolean(b);
185 }else if(a.equals("ilb") || a.equals("ignoreleftbranches") || a.equals("ignoreleftjunctions") || a.equals("ibb") || a.equals("ignorebackbranches")){
186 extendThroughLeftJunctions=Parse.parseBoolean(b);
187 }else if(a.equals("rcomp")){
188 doRcomp=Parse.parseBoolean(b);
189 }
190
191 else if(KmerTableSetU.isValidArgument(a)){
192 //Do nothing
193 }else{
194 throw new RuntimeException("Unknown parameter "+args[i]);
195 }
196 }
197
198 fuse=fuse_;
199 LOAD_THREADS=Shared.threads();
200
201 {//Process parser fields
202 Parser.processQuality();
203 }
204
205 /* Adjust I/O settings and filenames */
206
207 assert(FastaReadInputStream.settingsOK());
208
209 nextTable=new AtomicInteger[1];
210 nextVictims=new AtomicInteger[1];
211 for(int i=0; i<1; i++){
212 nextTable[i]=new AtomicInteger(0);
213 nextVictims[i]=new AtomicInteger(0);
214 }
215
216 if(!Tools.testOutputFiles(overwrite, append, false, outContigs)){
217 throw new RuntimeException("\nCan't write to some output files; overwrite="+overwrite+"\n");
218 }
219 assert(LOAD_THREADS>0);
220 outstream.println("Using "+LOAD_THREADS+" threads.");
221
222
223 final int bytesPerKmer;
224 {
225 int mult=12+k; //worst case for no assembly;
226 if(true){mult+=4;}
227 bytesPerKmer=mult;
228 }
229
230 tables=new KmerTableSet(args, bytesPerKmer);
231 k2=tables.k2;
232 }
233
234
235 /*--------------------------------------------------------------*/
236 /*---------------- Outer Methods ----------------*/
237 /*--------------------------------------------------------------*/
238
239
240 public final void process(Timer t){
241
242 /* Count kmers */
243 process2();
244
245 /* Stop timer and calculate speed statistics */
246 t.stop();
247
248
249 if(showSpeed){
250 outstream.println("\nTotal Time: \t"+t);
251 }
252
253 if(showStats && outContigs!=null && FileFormat.isFastaExt(ReadWrite.rawExtension(outContigs)) && !FileFormat.isStdio(outContigs)){
254 outstream.println();
255 jgi.AssemblyStats2.main(new String[] {"in="+outContigs});
256 }
257
258 /* Throw an exception if errors were detected */
259 if(errorState){
260 throw new RuntimeException(getClass().getSimpleName()+" terminated in an error state; the output may be corrupt.");
261 }
262 }
263
264 public long loadKmers(Timer t){
265 tables.process(t);
266 return tables.kmersLoaded;
267 }
268
269 public final void process2(){
270
271 /* Start phase timer */
272 Timer t=new Timer();
273
274 /* Fill tables with kmers */
275 outstream.println("\nLoading kmers.\n");
276 loadKmers(t);
277
278 t.stop();
279 // outstream.println("Input: \t"+tables.readsIn+" reads \t\t"+tables.basesIn+" bases.");
280 // outstream.println("Unique Kmers: \t"+tables.kmersLoaded);
281 // outstream.println("Load Time: \t"+t);
282
283
284 t.start();
285
286 {
287 /* Build contigs */
288 outstream.println("\nBuilding contigs.\n");
289 buildContigs();
290
291 if(DISPLAY_PROGRESS){
292 outstream.println("\nAfter building contigs:");
293 Shared.printMemory();
294 outstream.println();
295 }
296
297 t.stop();
298
299 if(readsIn>0){outstream.println("Input: \t"+readsIn+" reads \t\t"+basesIn+" bases.");}
300 outstream.println("Bases generated: \t"+basesBuilt);
301 outstream.println("Contigs generated: \t"+contigsBuilt);
302 outstream.println("Longest contig: \t"+longestContig);
303 outstream.println("Contig-building time: \t"+t);
304 }
305 }
306
307
308 /*--------------------------------------------------------------*/
309 /*---------------- Inner Methods ----------------*/
310 /*--------------------------------------------------------------*/
311
312 /**
313 * Build contigs.
314 */
315 private final void buildContigs(){
316
317 allContigs=new ArrayList<Contig>();
318
319 tables.initializeOwnership();
320
321 /* Create ProcessThreads */
322 ArrayList<AbstractBuildThread> alpt=new ArrayList<AbstractBuildThread>(BUILD_THREADS);
323 for(int i=0; i<BUILD_THREADS; i++){alpt.add(makeBuildThread(i));}
324 for(AbstractBuildThread pt : alpt){pt.start();}
325
326 /* Wait for threads to die, and gather statistics */
327 for(AbstractBuildThread pt : alpt){
328 while(pt.getState()!=Thread.State.TERMINATED){
329 try {
330 pt.join();
331 } catch (InterruptedException e) {
332 // TODO Auto-generated catch block
333 e.printStackTrace();
334 }
335 }
336 for(Contig contig : pt.contigs){
337 allContigs.add(contig);
338 contigsBuilt++;
339 basesBuilt+=contig.length();
340 longestContig=Tools.max(longestContig, contig.length());
341 }
342
343 readsIn+=pt.readsInT;
344 basesIn+=pt.basesInT;
345 lowqReads+=pt.lowqReadsT;
346 lowqBases+=pt.lowqBasesT;
347 }
348
349 if(outContigs!=null){
350 FileFormat ff=FileFormat.testOutput(outContigs, FileFormat.FA, 0, 0, true, overwrite, append, false);
351 // ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ff, null, null, null, 4, null, false);
352 // ros.start();
353 ByteStreamWriter bsw=new ByteStreamWriter(ff);
354 bsw.start();
355 if(allContigs!=null){
356 // Shared.sort(allContigs, ReadComparatorID.comparator);
357 ReadLengthComparator.comparator.setAscending(false);
358 Shared.sort(allContigs, ContigLengthComparator.comparator);
359 fuse(allContigs, fuse);
360 for(int i=0; i<allContigs.size(); i++){
361 Contig r=allContigs.get(i);
362 bsw.println(r);
363 }
364 }
365 errorState|=bsw.poisonAndWait();
366 }
367 }
368
369 private static void fuse(ArrayList<Contig> contigs, int fuse){
370 if(fuse<2){return;}
371 ArrayList<Contig> temp=new ArrayList<Contig>();
372 ByteBuilder bb=new ByteBuilder();
373 int num=0;
374 for(int i=0; i<contigs.size(); i++){
375 Contig r=contigs.set(i, null);
376 if(bb.length()>0){bb.append('N');}
377 bb.append(r.bases);
378 if(bb.length()>=fuse){
379 Contig fused=new Contig(bb.toBytes(), num);
380 num++;
381 temp.add(fused);
382 bb.clear();
383 }
384 }
385 if(bb.length()>0){
386 Contig fused=new Contig(bb.toBytes(), num);
387 num++;
388 temp.add(fused);
389 bb.clear();
390 }
391 contigs.clear();
392 contigs.addAll(temp);
393 temp=null;
394 }
395
396 /*--------------------------------------------------------------*/
397 /*---------------- Inner Classes ----------------*/
398 /*--------------------------------------------------------------*/
399
400 /*--------------------------------------------------------------*/
401 /*---------------- BuildThread ----------------*/
402 /*--------------------------------------------------------------*/
403
404 BuildThread makeBuildThread(int id){
405 return new BuildThread(id);
406 }
407
408 /**
409 * Builds contigs.
410 */
411 private class BuildThread extends AbstractBuildThread{
412
413 public BuildThread(int id_){
414 super(id_, Tadpole.contigMode, null);
415 }
416
417 @Override
418 public void run(){
419 //Build from kmers
420
421 //Final pass
422 while(processNextTable(nextTable[0])){}
423 while(processNextVictims(nextVictims[0])){}
424 }
425
426 private boolean processNextTable(AtomicInteger aint){
427 final int tnum=aint.getAndAdd(1);
428 if(tnum>=tables.ways){return false;}
429 final HashArray1D table=tables.getTable(tnum);
430 if(verbose && id==0){System.err.println("Processing table "+tnum+", size "+table.size());}
431 final int max=table.arrayLength();
432 for(int cell=0; cell<max; cell++){
433 int x=processCell(table, cell);
434 }
435 return true;
436 }
437
438 private boolean processNextVictims(AtomicInteger aint){
439 final int tnum=aint.getAndAdd(1);
440 if(tnum>=tables.ways){return false;}
441 final HashArray1D table=tables.getTable(tnum);
442 final HashForest forest=table.victims();
443 if(verbose && id==0){System.err.println("Processing forest "+tnum+", size "+forest.size());}
444 final int max=forest.arrayLength();
445 for(int cell=0; cell<max; cell++){
446 KmerNode kn=forest.getNode(cell);
447 int x=traverseKmerNode(kn);
448 }
449 return true;
450 }
451
452 private int processCell(HashArray1D table, int cell){
453 int count=table.readCellValue(cell);
454 if(count<minCount || count>maxCount){return 0;}
455
456 long key=table.getKmer(cell);
457
458 if(verbose){outstream.println("id="+id+" processing cell "+cell+"; \tkmer="+key+"\t"+toText(key));}
459 int owner=table.getCellOwner(cell);
460 if(verbose){outstream.println("Owner is initially "+owner);}
461 if(owner>-1){return 0;}
462 owner=table.setOwner(key, id, cell);
463 if(verbose){outstream.println("Owner is now "+owner);}
464 if(owner!=id){return 0;}
465 return processKmer(key);
466 }
467
468 private int traverseKmerNode(KmerNode kn){
469 int sum=0;
470 if(kn!=null){
471 sum+=processKmerNode(kn);
472 if(kn.left()!=null){
473 sum+=traverseKmerNode(kn.left());
474 }
475 if(kn.right()!=null){
476 sum+=traverseKmerNode(kn.right());
477 }
478 }
479 return sum;
480 }
481
482 private int processKmerNode(KmerNode kn){
483 final long key=kn.pivot();
484 final int count=kn.getValue(key);
485 if(count<minCount || count>maxCount){return 0;}
486
487 if(verbose){outstream.println("id="+id+" processing KmerNode; \tkmer="+key+"\t"+toText(key));}
488 int owner=kn.getOwner(key);
489 if(verbose){outstream.println("Owner is initially "+owner);}
490 if(owner>-1){return 0;}
491 owner=kn.setOwner(key, id);
492 if(verbose){outstream.println("Owner is now "+owner);}
493 if(owner!=id){return 0;}
494 return processKmer(key);
495 }
496
497 /** Returns length of new contig */
498 private int processKmer(long key){
499 byte[] bases=makeContig(key, builderT, true);
500 if(bases!=null){
501 final long num=contigNum.incrementAndGet();
502 final String id;
503 if(REQUIRE_SAME_COUNT){
504 id="n"+num+",c="+tables.getCount(key);
505 }else{
506 id=Long.toString(num);
507 }
508
509 Contig r=new Contig(bases, id, (int)num);
510 contigs.add(r);
511 if(verbose){System.err.println("Added "+bases.length);}
512 return bases.length;
513 }else{
514 if(verbose){System.err.println("Created null contig.");}
515 }
516 return 0;
517 }
518
519 /** From kmers */
520 private byte[] makeContig(final long key, final ByteBuilder bb, boolean alreadyClaimed){
521 builderT.setLength(0);
522 builderT.appendKmer(key, k);
523 if(verbose){outstream.println("Filled builder: "+builderT);}
524
525 final int initialLength=bb.length();
526 assert(initialLength==k);
527 if(initialLength<k){return null;}
528 // System.err.print("A");
529
530 {
531 boolean success=(alreadyClaimed || claim(key, id));
532 if(verbose){System.err.println("Thread "+id+" checking owner after setting: "+findOwner(bb, id));}
533 if(!success){
534 assert(bb.length()==k);
535 // release(bb, id); //no need to release
536 return null;
537 }
538 }
539 // System.err.print("B");
540 if(verbose /*|| true*/){System.err.println("Thread "+id+" building contig; initial length "+bb.length());}
541 if(verbose){System.err.println("Extending to right.");}
542 {
543 final int status=extendToRight(bb, rightCounts, id);
544
545 if(status==DEAD_END){
546 //do nothing
547 }else if(status==TOO_LONG){
548 //do nothing
549 }else if(status==BAD_SEED){
550 if(bb.length()<=k){
551 release(key, id);
552 return null;
553 }
554 }else{
555 throw new RuntimeException("Bad return value: "+status);
556 }
557 }
558 // System.err.print("C");
559
560 bb.reverseComplementInPlace();
561 if(verbose /*|| true*/){System.err.println("Extending rcomp to right; current length "+bb.length());}
562 {
563 final int status;
564 if(doRcomp){
565 status=extendToRight(bb, rightCounts, id);
566 }else{
567 status=extendToRight_RcompOnly(bb, rightCounts, id);
568 }
569
570 if(status==DEAD_END){
571 //do nothing
572 }else if(status==TOO_LONG){
573 //do nothing
574 }else if(status==BAD_SEED){
575 if(bb.length()<=k){
576 release(key, id);
577 return null;
578 }
579 }else{
580 throw new RuntimeException("Bad return value: "+status);
581 }
582 }
583 // System.err.print("D");
584
585 if(verbose /*|| true*/){System.err.println("A: Final length for thread "+id+": "+bb.length());}
586
587 //TODO: Success only if this thread actually owns some kmer in the contig. And trim unowned terminal kmers.
588
589 if(bb.length()>=k){
590 bb.reverseComplementInPlace();
591 return bb.toBytes();
592 }
593 if(verbose /*|| true*/){System.err.println("A: Contig was too short for "+id+": "+bb.length());}
594 // assert(false) : bb.length()+", "+initialLength+", "+minExtension+", "+minContigLen;
595 // System.err.print("F");
596 return null;
597 }
598
599 }
600
601 /*--------------------------------------------------------------*/
602 /*---------------- Extension Methods ----------------*/
603 /*--------------------------------------------------------------*/
604
605
606 /**
607 * Extend these bases into a contig.
608 * Stops at both left and right junctions.
609 * Claims ownership.
610 */
611 public int extendToRight(final ByteBuilder bb, final int[] rightCounts, final int id){
612 if(bb.length()<k){return BAD_SEED;}
613 final int shift=2*k;
614 final int shift2=shift-2;
615 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
616 long kmer=0;
617 long rkmer=0;
618 int len=0;
619
620 /* Loop through the bases, maintaining a forward and reverse kmer via bitshifts, to get the rightmost kmer */
621 {
622 final int bblen=bb.length();
623 final byte[] bases=bb.array;
624 for(int i=bblen-k; i<bblen; i++){
625 final byte b=bases[i];
626 final long x=AminoAcid.baseToNumber[b];
627 final long x2=AminoAcid.baseToComplementNumber[b];
628 kmer=((kmer<<2)|x)&mask;
629 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
630 if(x<0){
631 len=0;
632 kmer=rkmer=0;
633 }else{len++;}
634 if(verbose){outstream.println("A: Scanning i="+i+", len="+len+", kmer="+kmer+", rkmer="+rkmer+"\t"+new String(bases, Tools.max(0, i-k2), Tools.min(i+1, k)));}
635 }
636 }
637
638 if(len<k){
639 if(verbose){outstream.println("Returning BAD_SEED 1");}
640 return BAD_SEED;
641 }
642 else{assert(len==k);}
643
644 /* Now the trailing kmer has been initialized. */
645
646 long key=toValue(kmer, rkmer);
647 HashArray1D table=tables.getTableForKey(key);
648 int count=table.getValue(key);
649 if(count<minCount || count>maxCount){
650 if(verbose){
651 outstream.println("Returning because count was too low: "+count);
652 outstream.println("Returning BAD_SEED 2");
653 }
654 return BAD_SEED;
655 }
656
657 int owner=table.getOwner(key);
658 if(verbose){outstream.println("Owner: "+owner);}
659 if(owner>-1 && owner!=id){
660 if(verbose){outstream.println("Returning BAD_SEED 3");}
661 return BAD_SEED;
662 }
663
664 owner=table.setOwner(key, id);
665 if(verbose){outstream.println("A. Owner is now "+id+" for key "+key);}
666 if(owner!=id){
667 if(verbose){
668 outstream.println("Returning early because owner was "+owner+" for thread "+id+".");
669 outstream.println("Returning BAD_SEED 4");
670 }
671 return BAD_SEED;
672 }
673
674 final int maxLen=Tools.max(100000, bb.length()+90000);
675
676 while(bb.length()<maxLen){
677
678 fillRightCounts(kmer, rkmer, rightCounts, mask, shift2);
679 int selected=-1;
680 for(int i=0; i<4; i++){
681 final int count2=rightCounts[i];
682 if(count2>=minCount && count2<=maxCount && (!REQUIRE_SAME_COUNT || count2==count)){
683 final long y=i;
684 final long y2=AminoAcid.numberToComplement[i];
685 final long kmer2=((kmer<<2)|(long)y)&mask;
686 final long rkmer2=(rkmer>>>2)|(y2<<shift2);
687 final long key2=toValue(kmer2, rkmer2);
688 HashArray1D table2=tables.getTableForKey(key2);
689 if(table2.getOwner(key2)<0){
690 if(table2.setOwner(key2, id)==id){
691 selected=i;
692 kmer=kmer2;
693 rkmer=rkmer2;
694 key=key2;
695 count=count2;
696 final byte b=AminoAcid.numberToBase[selected];
697 bb.append(b);
698 break;
699 }
700 }
701 }
702 }
703
704 if(verbose){
705 outstream.println("kmer: "+toText(kmer)+", "+toText(rkmer));
706 outstream.println("Counts: "+count+", "+Arrays.toString(rightCounts));
707 }
708
709 if(selected<0){
710 if(verbose){outstream.println("Returning DEAD_END");}
711 return DEAD_END;
712 }//TODO: Explore on failure
713 }
714 if(verbose){
715 outstream.println("Current contig length: "+bb.length()+"\nReturning TOO_LONG");
716 }
717 // assert(owner!=id) : owner+"!="+id+"; maxLen="+maxLen+"; len="+bb.length();
718 return TOO_LONG;
719 }
720
721
722 /**
723 * Extend these bases into a contig.
724 * Stops at both left and right junctions.
725 * Claims ownership.
726 */
727 public int extendToRight_RcompOnly(final ByteBuilder bb, final int[] rightCounts, final int id){
728 if(bb.length()<k){return BAD_SEED;}
729 final int shift=2*k;
730 final int shift2=shift-2;
731 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
732 long kmer=0;
733 long rkmer=0;
734 int len=0;
735
736 /* Loop through the bases, maintaining a forward and reverse kmer via bitshifts, to get the rightmost kmer */
737 {
738 final int bblen=bb.length();
739 final byte[] bases=bb.array;
740 for(int i=bblen-k; i<bblen; i++){
741 final byte b=bases[i];
742 final long x=AminoAcid.baseToNumber[b];
743 final long x2=AminoAcid.baseToComplementNumber[b];
744 kmer=((kmer<<2)|x)&mask;
745 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
746 if(x<0){
747 len=0;
748 kmer=rkmer=0;
749 }else{len++;}
750 if(verbose){outstream.println("A: Scanning i="+i+", len="+len+", kmer="+kmer+", rkmer="+rkmer+"\t"+new String(bases, Tools.max(0, i-k2), Tools.min(i+1, k)));}
751 }
752 }
753
754 if(len<k){
755 if(verbose){outstream.println("Returning BAD_SEED 1");}
756 return BAD_SEED;
757 }
758 else{assert(len==k);}
759
760 /* Now the trailing kmer has been initialized. */
761
762 long key=rkmer;
763 HashArray1D table=tables.getTableForKey(key);
764 int count=table.getValue(key);
765 if(count<minCount || count>maxCount){
766 if(verbose){
767 outstream.println("Returning because count was too low: "+count);
768 outstream.println("Returning BAD_SEED 2");
769 }
770 return BAD_SEED;
771 }
772
773 int owner=table.getOwner(key);
774 if(verbose){outstream.println("Owner: "+owner);}
775 if(owner>-1 && owner!=id){
776 if(verbose){outstream.println("Returning BAD_SEED 3");}
777 return BAD_SEED;
778 }
779
780 owner=table.setOwner(key, id);
781 if(verbose){outstream.println("A. Owner is now "+id+" for key "+key);}
782 if(owner!=id){
783 if(verbose){
784 outstream.println("Returning early because owner was "+owner+" for thread "+id+".");
785 outstream.println("Returning BAD_SEED 4");
786 }
787 return BAD_SEED;
788 }
789
790 final int maxLen=Tools.max(100000, bb.length()+90000);
791
792 while(bb.length()<maxLen){
793
794 fillRightCountsRcompOnly(kmer, rkmer, rightCounts, mask, shift2);
795 int selected=-1;
796 for(int i=0; i<4; i++){
797 final int count2=rightCounts[i];
798 if(count2>=minCount && count2<=maxCount && (!REQUIRE_SAME_COUNT || count2==count)){
799 final long y=i;
800 final long y2=AminoAcid.numberToComplement[i];
801 final long kmer2=((kmer<<2)|(long)y)&mask;
802 final long rkmer2=(rkmer>>>2)|(y2<<shift2);
803 final long key2=rkmer2;
804 HashArray1D table2=tables.getTableForKey(key2);
805 if(table2.getOwner(key2)<0){
806 if(table2.setOwner(key2, id)==id){
807 selected=i;
808 kmer=kmer2;
809 rkmer=rkmer2;
810 key=key2;
811 count=count2;
812 final byte b=AminoAcid.numberToBase[selected];
813 bb.append(b);
814 break;
815 }
816 }
817 }
818 }
819
820 if(verbose){
821 outstream.println("kmer: "+toText(kmer)+", "+toText(rkmer));
822 outstream.println("Counts: "+count+", "+Arrays.toString(rightCounts));
823 }
824
825 if(selected<0){
826 if(verbose){outstream.println("Returning DEAD_END");}
827 return DEAD_END;
828 }//TODO: Explore on failure
829 }
830 if(verbose){
831 outstream.println("Current contig length: "+bb.length()+"\nReturning TOO_LONG");
832 }
833 // assert(owner!=id) : owner+"!="+id+"; maxLen="+maxLen+"; len="+bb.length();
834 return TOO_LONG;
835 }
836
837
838 /*--------------------------------------------------------------*/
839 /*---------------- Helper Methods ----------------*/
840 /*--------------------------------------------------------------*/
841
842 /** Currently unused */
843 protected final static Kmer getKmer(byte[] bases, int loc, Kmer kmer){
844 kmer.clear();
845 for(int i=loc, lim=loc+kmer.k; i<lim; i++){
846 byte b=bases[i];
847 int x=AminoAcid.baseToNumber[b];
848 if(x<0){return null;}
849 kmer.addRightNumeric(x);
850 }
851 assert(kmer.len==kmer.k);
852 return kmer;
853 }
854
855 /*--------------------------------------------------------------*/
856 /*---------------- Recall Methods ----------------*/
857 /*--------------------------------------------------------------*/
858
859 private final long rcomp(long kmer){return AminoAcid.reverseComplementBinaryFast(kmer, k);}
860 private final long toValue(long kmer, long rkmer){return tables.toValue(kmer, rkmer);}
861 public final int getCount(long kmer, long rkmer){return tables.getCount(kmer, rkmer);}
862 final boolean claim(long kmer, int id){return claim(kmer, rcomp(kmer), id);}
863 private final boolean claim(long kmer, long rkmer, int id){return tables.claim(kmer, rkmer, id);}
864 final int findOwner(ByteBuilder bb, int id){return tables.findOwner(bb, id);}
865 final void release(long key, int id){tables.release(key, id);}
866 private final int fillRightCounts(long kmer, long rkmer, int[] counts, long mask, int shift2){return tables.fillRightCounts(kmer, rkmer, counts, mask, shift2);}
867 private final int fillRightCountsRcompOnly(long kmer, long rkmer, int[] counts, long mask, int shift2){return tables.fillRightCountsRcompOnly(kmer, rkmer, counts, mask, shift2);}
868 final StringBuilder toText(long kmer){return AbstractKmerTable.toText(kmer, k);}
869
870 /*--------------------------------------------------------------*/
871 /*---------------- Fields ----------------*/
872 /*--------------------------------------------------------------*/
873
874 public final KmerTableSet tables;
875
876 /** Normal kmer length */
877 final int k;
878 /** k-1; used in some expressions */
879 private final int k2;
880
881 private ArrayList<Contig> allContigs;
882 private long contigsBuilt=0;
883 private long basesBuilt=0;
884 private long longestContig=0;
885
886 protected boolean extendThroughLeftJunctions=true;
887
888 int minCount=1;
889 int maxCount=Integer.MAX_VALUE;
890
891 /** Only extend to kmers with the same count as this kmer */
892 boolean REQUIRE_SAME_COUNT=false;
893
894 public boolean showStats=true;
895
896 /** Has this class encountered errors while processing? */
897 public boolean errorState=false;
898
899 /** Contig output file */
900 private String outContigs=null;
901
902 long readsIn=0;
903 long basesIn=0;
904 long readsOut=0;
905 long basesOut=0;
906 long lowqReads=0;
907 long lowqBases=0;
908
909 /*--------------------------------------------------------------*/
910 /*---------------- ThreadLocal Temps ----------------*/
911 /*--------------------------------------------------------------*/
912
913 protected final void initializeThreadLocals(){
914 if(localRightCounts.get()!=null){return;}
915 localRightCounts.set(new int[4]);
916 localLongList.set(new LongList());
917 localIntList.set(new IntList());
918 localByteBuilder.set(new ByteBuilder());
919 localBitSet.set(new BitSet(300));
920 localKmer.set(new Kmer(k));
921 }
922
923 protected ThreadLocal<int[]> localRightCounts=new ThreadLocal<int[]>();
924 protected ThreadLocal<LongList> localLongList=new ThreadLocal<LongList>();
925 protected ThreadLocal<IntList> localIntList=new ThreadLocal<IntList>();
926 protected ThreadLocal<ByteBuilder> localByteBuilder=new ThreadLocal<ByteBuilder>();
927 protected ThreadLocal<BitSet> localBitSet=new ThreadLocal<BitSet>();
928 protected ThreadLocal<Kmer> localKmer=new ThreadLocal<Kmer>();
929
930 /*--------------------------------------------------------------*/
931 /*---------------- Final Primitives ----------------*/
932 /*--------------------------------------------------------------*/
933
934 /** For numbering contigs */
935 final AtomicLong contigNum=new AtomicLong(0);
936
937 /** For controlling access to tables for contig-building */
938 final AtomicInteger nextTable[];
939
940 /** For controlling access to victim buffers for contig-building */
941 final AtomicInteger nextVictims[];
942
943 final int fuse;
944
945 /*--------------------------------------------------------------*/
946 /*---------------- Static Fields ----------------*/
947 /*--------------------------------------------------------------*/
948
949 /** Print messages to this stream */
950 protected static PrintStream outstream=System.err;
951 /** Permission to overwrite existing files */
952 public static boolean overwrite=true;
953 /** Permission to append to existing files */
954 public static boolean append=false;
955 /** Print speed statistics upon completion */
956 public static boolean showSpeed=true;
957 /** Display progress messages such as memory usage */
958 public static boolean DISPLAY_PROGRESS=true;
959 /** Verbose messages */
960 public static boolean verbose=false;
961 /** Debugging verbose messages */
962 public static boolean verbose2=false;
963 /** Reverse-complement */
964 public static boolean doRcomp=true;
965 /** Number of load threads */
966 public static int LOAD_THREADS=Shared.threads();
967 /** Number of build threads */
968 public static int BUILD_THREADS=1;
969
970 /** Explore codes */
971 public static final int KEEP_GOING=0, DEAD_END=1, TOO_SHORT=2, TOO_LONG=3, TOO_DEEP=4;
972
973 /** Extend codes */
974 public static final int BAD_SEED=12;
975
976 public static final int STATUS_UNEXPLORED=0, STATUS_EXPLORED=1, STATUS_REMOVE=2, STATUS_KEEP=3;
977
978 }