Debian Codegraph @

current/tracker/EntropyTracker.java

raw symbols SCIP
1 package tracker;
2
3 import java.util.Arrays;
4
5 import dna.AminoAcid;
6 import shared.Parse;
7 import shared.Tools;
8
9 /**
10 * Tracks entropy over a sliding window.
11 * @author Brian Bushnell
12 * @date Oct 6, 2017
13 *
14 */
15 public class EntropyTracker {
16
17 public static void main(String[] args){
18 final int k=args.length>0 ? Integer.parseInt(args[0]) : 2;
19 final int window=args.length>1 ? Integer.parseInt(args[1]) : 3;
20 final float cutoff=args.length>2 ? Float.parseFloat(args[2]) : 0.7f;
21 final boolean highPass=args.length>3 ? Parse.parseBoolean(args[3]) : true;
22
23 EntropyTracker et=new EntropyTracker(k, window, false, cutoff, highPass);
24 System.err.println(et);
25 }
26
27 /*--------------------------------------------------------------*/
28 /*---------------- Initialization ----------------*/
29 /*--------------------------------------------------------------*/
30
31 /**
32 * Normal constructor.
33 * @param k_ Kmer length.
34 * @param window_ Window size in bases.
35 */
36 public EntropyTracker(int k_, int window_, boolean amino_){
37 this(k_, window_, amino_, -1, true);
38 }
39
40 /**
41 * Allows the use of passes() based on entropy.
42 * @param k_ Kmer length.
43 * @param window_ Window size in bases.
44 * @param cutoff_ Entropy cutoff, 0 (no entropy) to 1 (max entropy).
45 * @param highPass_ True passes entropy of at least cutoff; false fails.
46 */
47 public EntropyTracker(boolean amino_, float cutoff_, boolean highPass_){
48 this((setDefaultK ? defaultK : amino_ ? 2 : defaultK),
49 (setDefaultWindow ? defaultWindowBases : amino_ ? 25 : 50),
50 amino_, cutoff_, highPass_);
51 }
52
53 /**
54 * Allows the use of passes() based on entropy.
55 * @param k_ Kmer length.
56 * @param window_ Window size in bases.
57 * @param cutoff_ Entropy cutoff, 0 (no entropy) to 1 (max entropy).
58 * @param highPass_ True passes entropy of at least cutoff; false fails.
59 */
60 public EntropyTracker(int k_, int window_, boolean amino_, float cutoff_, boolean highPass_){
61
62 k=k_;
63 windowBases=window_;
64 windowKmers=windowBases-k+1;
65 amino=amino_;
66 entropyCutoff=cutoff_;
67 highPass=highPass_;
68
69
70 assert(k>0 && k<=15 && k<windowBases) : k+", "+windowBases;
71 assert(windowKmers>0 && (entropyCutoff>=0 || entropyCutoff==-1) && entropyCutoff<=1) : k+", "+windowBases+", "+windowKmers+", "+entropyCutoff;
72
73 bitsPerBase=(amino ? 5 : 2);
74 mask=(k>15 ? -1 : ~((-1)<<(bitsPerBase*k)));
75 kmerSpace=(1<<(bitsPerBase*k));//Note: This should be different for amino, but decoding would be a pain
76 symbolToNumber=AminoAcid.symbolToNumber(amino);
77 symbolToNumber0=AminoAcid.symbolToNumber0(amino);
78
79 entropy=makeEntropyArray(windowKmers);
80 entropyMult=-1/Math.log(windowKmers);
81 baseCountMult=1f/windowBases;
82 baseCounts=new short[4];
83 counts=new short[kmerSpace];
84 countCounts=new short[windowKmers+2];
85 countCounts[0]=(short)windowKmers;
86 baseRingBuffer=new byte[windowBases];
87
88 // assert(false) : "\namino="+amino+", windowBases="+windowBases+", windowKmers="+windowKmers+", cutoff="+entropyCutoff+", bpb="+bitsPerBase+", mask="+
89 // Integer.toBinaryString(mask)+", space="+kmerSpace+", mult="+entropyMult+"\n"+"entropy="+Arrays.toString(entropy);
90
91 // entropyDeltaPlus=makeEntropyDeltaPlus(entropy, entropyMult);
92 // entropyDeltaMinus=makeEntropyDeltaMinus(entropy, entropyMult);
93 }
94
95 /**
96 * @param maxCount Highest possible count; equal to window size in kmers.
97 * @return Entropy array
98 */
99 private static final double[] makeEntropyArray(int maxCount){
100 final double[] array=new double[maxCount+2]; //+2 to handle temporary condition of an extra kmer
101 final double mult=1d/maxCount;
102 for(int i=1; i<array.length; i++){//First element (kmer count of 0) contains zero entropy, and yields NaN, so is skipped.
103 double pk=i*mult;
104 array[i]=pk*Math.log(pk);
105 }
106 return array;
107 }
108
109 /**
110 * @param entropy Entropy array
111 * @param entropyMult Multiplier applied to each array element
112 * @return entropyDeltaPlus array
113 */
114 @SuppressWarnings("unused")
115 private static final double[] makeEntropyDeltaPlus(double[] entropy, double entropyMult){
116 final double[] array=new double[entropy.length];
117 for(int i=0; i<entropy.length-1; i++){//Last element is never used.
118 array[i]=(entropy[i+1]-entropy[i])*entropyMult;
119 }
120 return array;
121 }
122
123 /**
124 * @param entropy Entropy array
125 * @param entropyMult Multiplier applied to each array element
126 * @return entropyDeltaMinus array
127 */
128 @SuppressWarnings("unused")
129 private static final double[] makeEntropyDeltaMinus(double[] entropy, double entropyMult){
130 final double[] array=new double[entropy.length];
131 for(int i=1; i<entropy.length; i++){//First element is never used.
132 array[i]=(entropy[i-1]-entropy[i])*entropyMult;
133 }
134 return array;
135 }
136
137 /*--------------------------------------------------------------*/
138 /*---------------- Getters ----------------*/
139 /*--------------------------------------------------------------*/
140
141 /** @return Number of unique kmers in current window. */
142 public int unique(){return unique;}
143
144 /** @return Number of undefined bases in current window. */
145 public int ns(){return ns;}
146
147 /** @return Sequence position of rightmost base in window. */
148 public int rightPos(){return len-1;}
149
150 /** @return Sequence position of leftmost base in window. */
151 public int leftPos(){return len-windowBases;}
152
153 /** @return Window size in bases. */
154 public int windowBases() {return windowBases;}
155
156 public int k() {return k;}
157
158 /** @return Entropy cutoff. */
159 public float cutoff() {return entropyCutoff;}
160
161 /*--------------------------------------------------------------*/
162 /*---------------- Entropy Calculation ----------------*/
163 /*--------------------------------------------------------------*/
164
165 public float calcMaxMonomerFraction(){
166 //int total=sum(baseCounts); should be window length
167 int max=Tools.max(baseCounts);
168 return baseCountMult*max;
169 }
170
171 /**
172 * Calculate entropy in current window.
173 * @return Entropy in current window.
174 */
175 public float calcEntropy(){
176 if(speed==FAST){return calcEntropyFast();}
177 else if(speed==MEDIUM){return calcEntropyMedium();}
178 else if(speed==SLOW){return calcEntropySlow();}
179 else{return calcEntropySuperSlow();}
180 }
181
182 /** Sub-method of calcEntropy() */
183 private float calcEntropyFast(){
184 final float f=(float)(currentEsum*entropyMult);
185 // final float f=(float)currentEsum; //For delta arrays
186
187 //Avoid potential negative numbers due to underflow
188 return f>0 ? f : 0;
189 }
190
191 /** Sub-method of calcEntropy()
192 * Calculates entropy from countCounts using precalculated entropy array and early exit. */
193 private float calcEntropyMedium(){
194 //Sum of entropy contributions from each kmer
195 double eSum=0;
196
197 //Sum of kmer counts, used for loop early exit
198 int cSum=countCounts[0];
199
200 //Simpler loop with no early exit. Slower for complex sequences, but faster for homopolymonomers.
201 // for(int i=1; i<countCounts.length; i++){
202
203 //Loop over all nonzero kmer counts
204 for(int i=1; cSum<windowKmers; i++){
205 //Number of unique kmers with count i
206 final int cc=countCounts[i];
207 cSum+=cc;
208
209 //Entropy contribution for each unique kmer with count i
210 double pklogpk=entropy[i];
211
212 //Add the entropy contribution for all unique kmers with count i
213 eSum+=(cc*pklogpk);
214 }
215 //eSum now holds negative entropy in bits.
216
217 //Adjust entropy to 0-1 scale based on window size
218 float e=(float)(eSum*entropyMult);
219 assert(e>=0 && e<=1) : e+", "+eSum+", "+entropyMult+"\n"+Arrays.toString(entropy)+"\n"+this;
220
221 //Get rid of negative zero
222 if(e<=0){e=0;}
223
224 if(verbose){
225 System.err.println(Tools.format("%.3f", eSum)+"\t"+Tools.format("%.3f", entropyMult)+"\t"
226 +Tools.format("%.3f", e)+"\t"+len+"\t"+unique+"\t"+basesToString());
227 }
228
229 return e;
230 }
231
232 /** Sub-method of calcEntropy()
233 * Calculates entropy from counts using precalculated entropy array. */
234 private float calcEntropySlow(){
235 //Sum of entropy contributions from each kmer
236 double eSum=0;
237
238 //Loop over all nonzero kmer counts
239 for(int count : counts){
240
241 //Entropy contribution for this kmer's count
242 double pklogpk=entropy[count];
243 eSum+=pklogpk;
244 }
245 //eSum now holds negative entropy in bits.
246
247 //Adjust entropy to 0-1 scale based on window size
248 float e=(float)(eSum*entropyMult);
249 assert(e>=0 && e<=1) : e+", "+eSum+", "+entropyMult+"\n"+Arrays.toString(entropy)+"\n"+this;
250
251 //Get rid of negative zero
252 if(e<=0){e=0;}
253
254 if(verbose){
255 System.err.println(Tools.format("%.3f", eSum)+"\t"+Tools.format("%.3f", entropyMult)+"\t"
256 +Tools.format("%.3f", e)+"\t"+len+"\t"+unique+"\t"+basesToString());
257 }
258
259 return e;
260 }
261
262 /**
263 * Sub-method of calcEntropy()
264 * Demonstrates explicit entropy calculation.
265 *
266 * Definition:
267 * Entropy, or information content, can be calculated using kmer counts of a sequence.
268 *
269 * Probability of an event (unique kmer), pk, is that kmer's count divided by the number of kmers.
270 * Entropy contribution from that kmer is -pk*log(pk).
271 * Total entropy is sum of (-pk*log(pk)) for all kmer counts.
272 * entropyMult is simply a multiplier to convert the entropy measure (in bits) to a convenient 0-1 scale,
273 * corresponding to the inverse of the maximum possible entropy.
274 */
275 private float calcEntropySuperSlow(){
276 //Sum of entropy contributions from each kmer
277 double eSum=0;
278
279 //Loop over all nonzero kmer counts
280 for(int count : counts){
281 //Prevent NaN and INF
282 // System.err.println("count="+count);
283 if(count>0){
284 //Fraction of total represented by this kmer
285 double pk=count/(double)windowKmers;
286 // System.err.println("pk="+pk);
287
288 //Entropy contribution for this kmer's count
289 double npklogpk=-pk*Math.log(pk);
290 // System.err.println("npklogpk="+npklogpk);
291 eSum+=npklogpk;
292 // System.err.println("eSum="+eSum);
293 }
294 }
295 //eSum now holds entropy in bits.
296
297 //Multiplier to convert entropy to 0-1 scale.
298 double multiplier=1/Math.log(windowKmers);
299
300 //Adjust entropy to 0-1 scale based on window size
301 float e=(float)(eSum*multiplier);
302 // System.err.println("e="+e);
303 assert(e>=0 && e<=1) : e+", "+eSum+", "+entropyMult+"\n"+Arrays.toString(entropy)+"\n"+this;
304
305 //Get rid of negative zero
306 if(e<=0){e=0;}
307
308 if(verbose){
309 System.err.println(Tools.format("%.3f", eSum)+"\t"+Tools.format("%.3f", entropyMult)+"\t"
310 +Tools.format("%.3f", e)+"\t"+len+"\t"+unique+"\t"+basesToString());
311 }
312
313 return e;
314 }
315
316 /*--------------------------------------------------------------*/
317
318 public static float strandedness(byte[] bases, int[] counts, int k) {
319 if(counts==null) {counts=new int[1<<(2*k)];}
320 countKmers(bases, counts, k);
321 return strandedness(counts, k);
322 }
323
324 public static float strandedness(int[] counts, int k) {
325 final int mask=~((-1)<<(2*k));
326 assert(mask==counts.length-1);
327 long lower=0, upper=0;
328 for(int kmer=0, limit=counts.length/2; kmer<limit; kmer++) {
329 int a=counts[kmer];
330 int b=counts[mask&(~kmer)];
331 lower+=Math.min(a, b);
332 upper+=Math.max(a, b);
333 }
334 return lower/(float)(Long.max(1, upper));
335 }
336
337 public static float strandednessK2(int[] counts) {
338 final int mask=15;
339 assert(counts.length==16);
340 long lower=0, upper=0;
341 for(int kmer=0; kmer<8; kmer++) {
342 int a=counts[kmer];
343 int b=counts[mask&(~kmer)];
344 lower+=Math.min(a, b);
345 upper+=a+b;
346 }
347 return lower/(float)(Long.max(1, upper-lower));
348 }
349
350 public static float strandednessWindowed(byte[] bases, int[] counts, int k, int window) {
351 if(k==2) {return strandednessWindowedK2(bases, counts, window);}
352 assert(k>2);
353 if(counts==null) {counts=new int[1<<(2*k)];}
354
355 final int shift=2*k;
356 final int mask=~((-1)<<shift);
357 assert(mask==counts.length-1);
358
359 int valid=0;
360 double sum=0;
361 int sums=0;
362 for(int i=0, j=-window, ikmer=0, jkmer=0, ilen=0, jlen=0; i<bases.length; i++, j++){
363 {
364 byte b=bases[i];
365 int x=AminoAcid.baseToNumber[b];
366 ikmer=((ikmer<<2)|x)&mask;
367 if(x>=0){
368 ilen++;
369 if(ilen>=k) {
370 valid++;
371 counts[ikmer]++;
372 }
373 }else{ilen=ikmer=0;}
374 }
375
376 if(j>=0){
377 byte b=bases[i];
378 int y=AminoAcid.baseToNumber[b];
379 jkmer=((jkmer<<2)|y)&mask;
380 if(y>=0){
381 jlen++;
382 if(jlen>=k) {
383 valid--;
384 counts[jkmer]--;
385 }
386 }else{jlen=jkmer=0;}
387 }
388
389 if(i>=window-1) {
390 sums++;
391 sum+=strandedness(counts, k);
392 }
393 }
394 if(sums<1) {
395 return strandedness(counts, k);
396 }
397 return (float)(sum/sums);
398 }
399
400 public static float strandednessWindowedK2(byte[] bases, int[] counts, int window) {
401 if(counts==null) {counts=new int[16];}
402
403 final int mask=15;
404 assert(mask==counts.length-1);
405
406 int valid=0;
407 double sum=0;
408 int sums=0;
409 for(int i=0, j=-window, ikmer=0, jkmer=0, ilen=0, jlen=0; i<bases.length; i++, j++){
410 {
411 byte b=bases[i];
412 int x=AminoAcid.baseToNumber[b];
413 ikmer=((ikmer<<2)|x)&mask;
414 if(x>=0){
415 ilen++;
416 if(ilen>=2) {
417 valid++;
418 counts[ikmer]++;
419 }
420 }else{ilen=ikmer=0;}
421 }
422
423 if(j>=0){
424 byte b=bases[i];
425 int y=AminoAcid.baseToNumber[b];
426 jkmer=((jkmer<<2)|y)&mask;
427 if(y>=0){
428 jlen++;
429 if(jlen>=2) {
430 valid--;
431 counts[jkmer]--;
432 }
433 }else{jlen=jkmer=0;}
434 }
435
436 if(i>=window-1) {
437 sums++;
438 sum+=strandednessK2(counts);
439 }
440 }
441 if(sums<1) {
442 return strandednessK2(counts);
443 }
444 return (float)(sum/sums);
445 }
446
447 /*--------------------------------------------------------------*/
448
449 public static float calcEntropy(byte[] bases, int[] counts, int k){
450 assert(k<=10) : k;//This is for small kmers
451 if(counts==null) {counts=new int[1<<(2*k)];}
452 countKmers(bases, counts, k);
453 return calcEntropyFromCounts(counts);
454 }
455
456 /**
457 * Static, non-windowed version.
458 * Demonstrates explicit entropy calculation.
459 *
460 * Definition:
461 * Entropy, or information content, can be calculated using kmer counts of a sequence.
462 *
463 * Probability of an event (unique kmer), pk, is that kmer's count divided by the number of kmers.
464 * Entropy contribution from that kmer is -pk*log(pk).
465 * Total entropy is sum of (-pk*log(pk)) for all kmer counts.
466 * entropyMult is simply a multiplier to convert the entropy measure (in bits) to a convenient 0-1 scale,
467 * corresponding to the inverse of the maximum possible entropy.
468 */
469 public static float calcEntropyFromCounts(int[] counts){
470 //Sum of entropy contributions from each kmer
471 double eSum=0;
472
473 long windowKmers=Tools.sum(counts);
474 double invKmers=1.0/windowKmers;
475 //Loop over all nonzero kmer counts
476 for(int count : counts){
477 //Prevent NaN and INF
478 // System.err.println("count="+count);
479 if(count>0){
480 //Fraction of total represented by this kmer
481 double pk=count*invKmers;
482 // System.err.println("pk="+pk);
483
484 //Entropy contribution for this kmer's count
485 double npklogpk=-pk*Math.log(pk);
486 // System.err.println("npklogpk="+npklogpk);
487 eSum+=npklogpk;
488 // System.err.println("eSum="+eSum);
489 }
490 }
491 //eSum now holds entropy in bits.
492
493 //Multiplier to convert entropy to 0-1 scale.
494 double multiplier=1/Math.log(windowKmers);
495
496 //Adjust entropy to 0-1 scale based on window size
497 float e=(float)(eSum*multiplier);
498
499 //Get rid of negative zero
500 if(e<=0){e=0;}
501
502 return e;
503 }
504
505 public static int countKmers(final byte[] bases, final int[] counts, int k){
506 Arrays.fill(counts, 0);
507 if(bases==null || bases.length<k){return 0;}
508
509 final int shift=2*k;
510 final int mask=~((-1)<<shift);
511
512 int kmer=0;
513 int len=0;
514 int valid=0;
515
516 for(int i=0; i<bases.length; i++){
517 byte b=bases[i];
518 int x=AminoAcid.baseToNumber[b];
519 kmer=((kmer<<2)|x)&mask;
520 if(x>=0){
521 len++;
522 if(len>=k) {
523 valid++;
524 counts[kmer]++;
525 }
526 }else{len=kmer=0;}
527 }
528 return valid;
529 }
530
531 /*--------------------------------------------------------------*/
532
533 /**
534 * Calculate the average entropy of a sequence.
535 * @param bases Sequence as bytes
536 * @param allowNs True if windows containing undefined bases should be included
537 * @return Average entropy
538 */
539 public float averageEntropy(byte[] bases, boolean allowNs){
540 return averageEntropy(bases, allowNs, 0, bases.length-1);
541 }
542
543 /**
544 * Calculate the average entropy of a sequence.
545 * @param bases Sequence as bytes
546 * @param allowNs True if windows containing undefined bases should be included
547 * @return Average entropy
548 */
549 public float averageEntropy(final byte[] bases, final boolean allowNs, final int from, final int to){
550 assert(from>=0 && to<bases.length && from<=to) : from+", "+to+", "+bases.length;
551 final int len=to-from+1;
552
553 //Reset the initial state
554 clear();
555
556 //Position in sequence
557 int i=from;
558
559 //Accumulated entropy
560 double sum=0;
561
562 //Number of entropy measurements
563 int divisor=0;
564
565 // System.err.println("\n"+new String(bases, from, len));
566 // System.err.println("from="+from+", to="+to+", lim=min("+(bases.length)+","+windowBases+","+(to+1)+")");
567
568 //Prefill the first window
569 for(final int lim=Tools.min(bases.length, windowBases+from, to+1); i<lim; i++){
570 add(bases[i]);
571 }
572
573 //Calculate entropy for the first window.
574 //This allows entropy to pass if it is high enough even though the sequence is shorter than window length.
575 if(allowNs || ns==0){
576 sum+=calcEntropy();
577 divisor++;
578 }
579
580 //Calculate entropy for remaining windows
581 for(; i<=to; i++){
582 add(bases[i]);
583 if(allowNs || ns==0){
584 sum+=calcEntropy();
585 divisor++;
586 }
587 }
588
589 if(divisor<0){return -1;}//No valid windows.
590
591 //Calculate the average
592 double avg=(sum/(Tools.max(1, divisor)));
593 return (float)avg;
594 }
595
596 /**
597 * Reports the longest block of consecutive bases in which all windows
598 * are below the entropy cutoff and at least the (optional) monomer fraction.
599 * @param bases
600 * @param allowNs
601 * @param maxMonomer
602 * @return
603 */
604 public int longestLowEntropyBlock(byte[] bases, boolean allowNs, float maxMonomerFraction){
605 //Reset the initial state
606 clear();
607
608 //Position in sequence
609 int i=0;
610
611 //Number of entropy measurements
612 int totalWindows=0;
613
614 double sum=0;
615 int totalLowWindows=0;
616 int currentLowWindows=0;
617 int maxLowWindows=0;
618
619 //Prefill the first window
620 for(final int lim=Tools.min(bases.length, windowBases); i<lim; i++){add(bases[i]);}
621
622 //Calculate entropy for the first window.
623 //This allows entropy to pass if it is high enough even though the sequence is shorter than window length.
624 if(allowNs || ns==0){
625 totalWindows++;
626 double e=calcEntropy();
627 float mmf=calcMaxMonomerFraction();
628 sum+=e;
629 if(e<entropyCutoff && mmf>=maxMonomerFraction){
630 totalLowWindows++;
631 currentLowWindows++;
632 maxLowWindows=Tools.max(maxLowWindows, currentLowWindows);
633 }else{
634 currentLowWindows=0;
635 }
636 }
637
638 //Calculate entropy for remaining windows
639 for(; i<bases.length; i++){
640 add(bases[i]);
641 if(allowNs || ns==0){
642 totalWindows++;
643 double e=calcEntropy();
644 float mmf=calcMaxMonomerFraction();
645 sum+=e;
646 if(e<entropyCutoff && mmf>maxMonomerFraction){
647 totalLowWindows++;
648 currentLowWindows++;
649 maxLowWindows=Tools.max(maxLowWindows, currentLowWindows);
650 }else{
651 currentLowWindows=0;
652 }
653 }
654 }
655
656 //Calculate the average; not needed
657 double avg=(sum/(Tools.max(1, totalWindows)));
658
659 int maxLowBlock=maxLowWindows<1 ? 0 : Tools.min(bases.length, maxLowWindows+windowBases-1);
660 return maxLowBlock;
661 }
662
663 /**
664 * Calculate entropy in the window and compare to the cutoff.
665 * If Ns are important they should be handled externally with ns().
666 * @return True if the entropy passes the cutoff.
667 */
668 public boolean passes(){
669 //This function should only be used if entropyCutoff is set.
670 assert(entropyCutoff>=0);
671 float e=calcEntropy();
672
673 //XOR: highPass inverts truth of comparison.
674 return highPass ^ (e<entropyCutoff);
675 }
676
677 /**
678 * Calculate average entropy of the sequence and compare to the cutoff.
679 * @param sequence Sequence to measure.
680 * @param allowNs True if entropy should be calculated in windows containing Ns.
681 * @return True if the average entropy passes the cutoff.
682 */
683 public boolean passes(byte[] sequence, boolean allowNs){
684 //This function should only be used if entropyCutoff is set.
685 assert(entropyCutoff>=0);
686 float e=averageEntropy(sequence, allowNs);
687
688 //XOR: highPass inverts truth of comparison.
689 return highPass ^ (e<entropyCutoff);
690 }
691
692 /*--------------------------------------------------------------*/
693 /*---------------- Mutating Methods ----------------*/
694 /*--------------------------------------------------------------*/
695
696 /**
697 * Slide the window by adding a new base.
698 * @param b Base to add.
699 */
700 public void add(final byte b){
701
702 //Test initial state
703 assert(!verify || verify()) : this;
704
705 final byte oldBase=baseRingBuffer[pos]; //Leftmost base, about to be overwritten
706
707 if(verbose){System.err.println("\nAdding "+Character.toString((char)b)+
708 "; evicting "+Character.toString((char)oldBase)+"; counts="+Arrays.toString(counts)+"; countcounts="+Arrays.toString(countCounts)+", pos="+pos+", pos2="+pos2);}
709
710 //Increment length
711 len++;
712
713 {//Add a new rightmost base
714 baseRingBuffer[pos]=b;
715 final int n=symbolToNumber0[b];
716 baseCounts[n]++;
717 kmer=((kmer<<bitsPerBase)|n)&mask; //Generate new rightmost kmer using the new base
718
719 //Update number of Ns in current window
720 if(!isFullyDefined(b)){
721 ns++;
722 assert(ns<=windowBases+1) : "There are more Ns than bases in the window:\n"+this;
723 }
724
725 if(len>=k){//Add a kmer
726 //System.err.println("Adding "+kmer);
727
728 final short oldCount=counts[kmer];
729
730 /* Update unique kmer count */
731 if(oldCount<1){
732 assert(oldCount==0) : "An incoming array has negative counts: \n"+this;
733 unique++;
734 }
735
736 /* Decrement the old countCount */
737 countCounts[oldCount]--;
738
739 /* countCounts[0] could be temporarily -1 at this point; for all others, min is 0. */
740 assert(countCounts[oldCount]>=-1) : this;
741
742 /* Increment the kmer count */
743 final short newCount=counts[kmer]=(short)(oldCount+1);
744
745 /* The count could at most be 1 more than the total window kmers here temporarily */
746 assert(newCount<=windowKmers+1) : this;
747
748 /* Increment the new countCount */
749 countCounts[newCount]++;
750
751 /* Update entropy */
752 currentEsum=currentEsum+entropy[newCount]-entropy[oldCount];
753 // currentEsum+=entropyDeltaPlus[oldCount];
754
755 assert(!verify || unique==Tools.cardinality(counts)) : this;
756 assert(!verify || (shared.Vector.sum(countCounts)>0 && (shared.Vector.sum(countCounts)<=windowKmers+1))) : this;
757 }
758 }
759 if(verbose){System.err.println("B: counts="+Arrays.toString(counts)+"; countcounts="+Arrays.toString(countCounts));}
760
761 //At this point the state is inconsistent as it may have one too many kmers.
762
763 if(pos2>=0){//Remove the leftmost base
764 final byte b2=(k>1 ? baseRingBuffer[pos2] : oldBase);//This is not the leftmost base, but the base to the right of the leftmost kmer
765 final int n2=symbolToNumber0[b2];
766 //Generate old leftmost kmer using an internal base near the left end
767 kmer2=((kmer2<<bitsPerBase)|n2)&mask;
768
769 if(verbose){System.err.println("B2: pos="+pos+", pos2="+pos2+"; b2="+Character.toString((char)b2)+"; kmer2="+kmer2);}
770
771 if(len>windowBases){//Remove a kmer, only if a base is leaving the window
772 baseCounts[n2]--;
773 //System.err.println("Removing "+kmer2);
774
775 //Update number of Ns in current window
776 if(!isFullyDefined(oldBase)){
777 ns--;
778 assert(ns>=0) : "There are fewer than 0 Ns in the window:\n"+this;
779 }
780
781 assert(kmer2>=0) : "A negative kmer was observed: "+kmer2+"\n"+this;
782
783 final short oldCount=counts[kmer2];
784 assert(oldCount>0) : "Attempting to decrement a nonpositive count: \n"+oldCount+"\n"+this;
785
786 //Decrement the old countCount
787 countCounts[oldCount]--;
788
789 assert(countCounts[oldCount]>=0) : "A countCount became negative: \n"+countCounts[oldCount]+"\n"+this;
790
791 //Decrement the kmer count
792 final short newCount=counts[kmer2]=(short)(oldCount-1);
793
794 /* Increment the new countCount */
795 countCounts[newCount]++;
796
797 /* Update unique kmer count */
798 if(newCount<1){
799 assert(newCount==0): "An outgoing array has negative counts: \n"+this;
800 unique--;
801 }
802
803 /* Update entropy */
804 currentEsum=currentEsum+entropy[newCount]-entropy[oldCount];
805 // currentEsum+=entropyDeltaMinus[oldCount];
806
807 assert(!verify || unique==Tools.cardinality(counts)) : this;
808 assert(!verify || (shared.Vector.sum(countCounts)>=0 && (shared.Vector.sum(countCounts)<=windowKmers))) : this;
809 }
810 }
811 if(verbose){System.err.println("C: counts="+Arrays.toString(counts)+"; countcounts="+Arrays.toString(countCounts));}
812
813 //Update position pointers
814 //Can use modulo, but this is faster because the branch is normally skipped.
815 //Ternary conditionals are also slower.
816 pos++;
817 pos2++;
818 if(pos>=windowBases){pos=0;}
819 if(pos2>=windowBases){pos2=0;}
820 assert(k==1 || pos!=pos2) : "pos="+pos+", pos2="+pos2;
821
822 //Test final state.
823 assert(!verify || verify()) : this;
824 }
825
826 /**
827 * Reset fields to prepare for a new sequence.
828 */
829 public void clear(){
830 //Reset scalars
831 kmer=kmer2=len=pos=unique=ns=0;
832 pos=0;
833 pos2=0-windowBases+k-1;
834 currentEsum=0;
835
836 //Clear mutable arrays. Bases does not need to be cleared.
837 Arrays.fill(baseCounts, (short)0); //4 operations
838 Arrays.fill(counts, (short)0); //Time proportional to kmer space
839
840 //Note - countCounts are only needed for medium speed mode.
841 Arrays.fill(countCounts, (short)0); //Time proportional to window size
842
843 //Sets the number of kmers with a count of zero to maximum.
844 countCounts[0]=(short)windowKmers;
845
846 //Verify the state was cleared
847 assert(!verify || verifyClear()) : this;
848 }
849
850 /*--------------------------------------------------------------*/
851 /*---------------- Validation ----------------*/
852 /*--------------------------------------------------------------*/
853
854 /**
855 * Verify that mutable fields were properly cleared.
856 * Throws an assertion error upon failure.
857 * @return True.
858 */
859 public boolean verifyClear(){
860 for(int c : baseCounts){assert(c==0) : this;}
861 for(int c : counts){assert(c==0) : this;}
862 for(int i=1; i<countCounts.length; i++){assert(countCounts[i]==0) : this;}
863 assert(kmer==0 && kmer2==0) : this;
864 assert(pos==0) : this;
865 assert(len==pos) : this;
866 assert(ns==0) : this;
867 assert(unique==0) : this;
868 assert(pos2<0) : this;
869 assert(currentEsum==0) : this;
870 return true;
871 }
872
873 /**
874 * Verify that internal state is consistent.
875 * Throws an assertion error upon failure.
876 * @return True.
877 */
878 public boolean verify(){
879
880 //Number of unique kmers in the window
881 int existSum=0;
882
883 //Total number of kmers in the window
884 int countSum=0;
885
886 //Number of undefined symbols in the window
887 int nSum=0;
888
889 //Check the kmer counts
890 for(int c : counts){
891 assert(c>=0 && c<=windowKmers) : "A kmer count exceeds the possible bounds.\n"+this;
892 if(c>0){
893 existSum++;
894 countSum+=c;
895 }
896 }
897
898 //Check the countCounts
899 for(int cc : countCounts){
900 assert(cc>=0 && cc<=windowKmers) : "A countCount exceeds the possible bounds.\n"+this;
901 }
902
903 //Count undefined symbols
904 for(byte b : baseRingBuffer){
905 if(!isFullyDefined(b)){nSum++;}
906 }
907
908 //Number of kmers with count 0
909 final int cc0=countCounts[0];
910
911 //Sum of countCounts
912 final int ccSum=(int)shared.Vector.sum(countCounts);
913
914 //Sum of nonzero countCounts; should equal the number of unique kmers
915 final int ccSum1=ccSum-cc0;
916
917 //Do assertions
918 assert(len<windowBases || ns==nSum) : this;
919 assert(existSum==unique) : this;
920 assert(existSum==ccSum1) : this;
921 assert(existSum>=0 && existSum<=windowKmers) : this;
922 assert(len<windowBases || countSum==windowKmers) : this;
923 assert(ccSum==windowKmers);
924 assert(pos==len%windowBases) : this;
925
926 //Ensure different entropy calculation methods are consistent
927 if(len>=windowKmers){
928 float a=calcEntropyFast();
929 float b=calcEntropyMedium();
930 float c=calcEntropySlow();
931 float d=calcEntropySuperSlow(); //"d" should be identical to "c".
932 assert(Tools.absdif(a, b)<0.0001) : "Fast and Medium entropy differ:\n"+a+"\n"+b+"\n"+c+"\n"+this;
933 assert(Tools.absdif(b, c)<0.000001) : "Medium and Slow entropy differ:\n"+a+"\n"+b+"\n"+c+"\n"+this;
934 assert(c==d) : "Slow and SuperSlow entropy differ:\n"+a+"\n"+b+"\n"+c+"\n"+d+"\n"+this;
935 }
936 return true;
937 }
938
939 @Override
940 public String toString(){
941 StringBuilder sb=new StringBuilder();
942 sb.append('\n');
943 sb.append("kmer\t"+kmer).append('\n');
944 sb.append("kmer2\t"+kmer2).append('\n');
945 sb.append("pos\t"+pos).append('\n');
946 sb.append("pos2\t"+pos2).append('\n');
947 sb.append("len\t"+len).append('\n');
948 sb.append("unique\t"+unique).append('\n');
949 sb.append("ns\t"+ns).append('\n');
950 sb.append('\n');
951 sb.append("k\t"+k).append('\n');
952 sb.append("windowBases\t"+windowBases).append('\n');
953 sb.append("windowKmers\t"+windowKmers).append('\n');
954 sb.append("mask\t"+mask).append('\n');
955 sb.append('\n');
956 sb.append("cardinality\t"+Tools.cardinality(counts)).append('\n');
957 sb.append("counts\t"+Arrays.toString(counts)).append('\n');
958 sb.append("ccounts\t"+Arrays.toString(countCounts)).append('\n');
959 sb.append("bases\t"+basesToString()).append('\n');
960 sb.append("entropy\t"+Arrays.toString(entropy)).append('\n');
961 sb.append("entropyMult\t"+entropyMult).append('\n');
962 sb.append("entropySum\t"+currentEsum).append('\n');
963 return sb.toString();
964 }
965
966 /** Returns the ring buffer as a String in its correct order. */
967 public String basesToString(){
968 StringBuilder sb=new StringBuilder(baseRingBuffer.length);
969 for(int i=0; i<baseRingBuffer.length; i++){
970 byte b=(baseRingBuffer[(i+pos)%baseRingBuffer.length]);
971 if(b==0){b='N';}
972 sb.append((char)b);
973 }
974 return sb.toString();
975 }
976
977 /*--------------------------------------------------------------*/
978 /*---------------- Mutable Fields ----------------*/
979 /*--------------------------------------------------------------*/
980
981 /** Current leading kmer; rightmost k bases of window */
982 int kmer=0;
983 /** Current trailing kmer; leftmost k-1 bases of window plus the removed base */
984 int kmer2=0;
985 /** Position in ring buffer to place incoming bases */
986 int pos=0;
987 /** Position in ring buffer to read next base for kmer2 */
988 int pos2=0;
989 /** Current number of processed bases. Equal to pos without being reset at buffer wrap. */
990 int len=0;
991 /** Number of unique kmers in the current window */
992 int unique=0;
993 /** Number of undefined bases in the current window */
994 int ns;
995
996 /** Current sum of entropy from kmers in the current window */
997 double currentEsum=0;
998
999 /*--------------------------------------------------------------*/
1000 /*---------------- Mutable Arrays ----------------*/
1001 /*--------------------------------------------------------------*/
1002
1003 /** Number of times each base occurs in current window.
1004 * Equivalent to counts if k=1. */
1005 private final short[] baseCounts;
1006
1007 /** Number of times each kmer occurs in current window.
1008 * Indexed by the kmer's numeric value.
1009 * counts[0] stores the count of the kmer AAA, if k=3. */
1010 private final short[] counts;
1011
1012 /** Number of instances of each number in counts.
1013 * countCounts[0] stores the number of kmers with count 0.
1014 * This is only needed in medium speed mode (or verify mode). */
1015 private final short[] countCounts;
1016
1017 /** Ring buffer of bases in current window.
1018 * Not strictly necessary, but convenient. */
1019 private final byte[] baseRingBuffer;
1020
1021 /*--------------------------------------------------------------*/
1022 /*---------------- Final Fields ----------------*/
1023 /*--------------------------------------------------------------*/
1024
1025 /** Kmer length for entropy calculation */
1026 private final int k;
1027 /** Window length for entropy calculation */
1028 private final int windowBases;
1029 /** Number of kmers in the window */
1030 private final int windowKmers;
1031 /** Amino acid mode */
1032 private final boolean amino;
1033
1034 /** Bits per symbol */
1035 private final int bitsPerBase;
1036 /** Mask for sliding kmers */
1037 private final int mask;
1038
1039 /** Minimum entropy to be considered "complex", on a scale of 0-1; optional */
1040 private final float entropyCutoff;
1041 /** Pass entropy values above the cutoff */
1042 private final boolean highPass;
1043
1044 /** Number of possible unique kmers */
1045 private final int kmerSpace;
1046 /** A precalculated constant */
1047 private final double entropyMult;
1048 /** Array of precalculated constants */
1049 private final double[] entropy;
1050
1051 /** Precalculated constant equal to 1f/windowBases */
1052 private final float baseCountMult;
1053
1054 /** Translation table yielding 0 if undefined */
1055 private final byte[] symbolToNumber0;
1056 /** Translation table yielding -1 if undefined */
1057 private final byte[] symbolToNumber;
1058
1059 final boolean isFullyDefined(byte symbol){
1060 return symbol>=0 && symbolToNumber[symbol]>=0;
1061 }
1062
1063 //Note: These incur fewer operations, but in testing, were not faster.
1064 // /** For calculating entropy running average quickly when adding a kmer.
1065 // * entropyDeltaPlus[i] = (entropy[i+1]-entropy[i])*entropyMult */
1066 // private final double[] entropyDeltaPlus;
1067 // /** For calculating entropy running average quickly when removing a kmer.
1068 // * entropyDeltaMinus[i] = (entropy[i-1]-entropy[i])*entropyMult */
1069 // private final double[] entropyDeltaMinus;
1070
1071 /*--------------------------------------------------------------*/
1072 /*---------------- Constants ----------------*/
1073 /*--------------------------------------------------------------*/
1074
1075 /** Entropy calculation speed constants.
1076 * FAST is less precise for long sequences.
1077 * MEDIUM is probably most precise. */
1078 public static final int FAST=0, MEDIUM=1, SLOW=2, SUPERSLOW=3;
1079
1080 /*--------------------------------------------------------------*/
1081 /*---------------- Static Fields ----------------*/
1082 /*--------------------------------------------------------------*/
1083
1084 /** Kmer length for entropy calculation */
1085 public static int defaultK=5;
1086 public static boolean setDefaultK=false;
1087 /** Window length for entropy calculation */
1088 public static int defaultWindowBases=50;
1089 public static boolean setDefaultWindow=false;
1090 // /** Minimum entropy to be considered "complex", on a scale of 0-1 */
1091 // public static float defaultCutoff=-1;
1092
1093 /** Entropy calculation mode */
1094 public static int speed=FAST;
1095
1096 /** Verify consistency of related data structures (slow) */
1097 public static boolean verify=false;
1098 /** Verbose output */
1099 public static final boolean verbose=false;
1100
1101 }