1 package org.djutils.stats.summarizers.quantileaccumulator;
2
3 import org.djutils.exceptions.Throw;
4 import org.djutils.stats.summarizers.Tally;
5
6 import com.tdunning.math.stats.TDigest;
7
8
9
10
11
12
13
14
15
16
17
18 public class TDigestAccumulator implements QuantileAccumulator
19 {
20
21 private TDigest tDigest;
22
23
24 private final int compression;
25
26
27 public static final int DEFAULT_COMPRESSION = 100;
28
29
30
31
32
33 public TDigestAccumulator(final int compression)
34 {
35 this.compression = compression;
36 initialize();
37 }
38
39
40
41
42 public TDigestAccumulator()
43 {
44 this(DEFAULT_COMPRESSION);
45 }
46
47
48 @Override
49 public double register(final double value)
50 {
51 Throw.when(Double.isNaN(value), IllegalArgumentException.class, "accumulator can not accumlate NaN value");
52 this.tDigest.add(value);
53 return value;
54 }
55
56
57 @Override
58 public double getQuantile(final Tally tally, final double probability)
59 {
60 Throw.whenNull(tally, "tally cannot be null");
61 Throw.when(probability < 0 || probability > 1, IllegalArgumentException.class,
62 "probability should be between 0 and 1 (inclusive)");
63 return this.tDigest.quantile(probability);
64 }
65
66
67 @Override
68 public double getCumulativeProbability(final Tally tally, final double quantile)
69 {
70 return this.tDigest.cdf(quantile);
71 }
72
73
74 @Override
75 public void initialize()
76 {
77 this.tDigest = TDigest.createDigest(this.compression);
78 }
79
80
81 @Override
82 public final String toString()
83 {
84 return "TDigestAccumulator [tDigest=" + this.tDigest + ", compression=" + this.compression + "]";
85 }
86
87 }