summaryrefslogtreecommitdiffstats
path: root/statistics/src/main/java/com/yahoo/statistics/Histogram.java
blob: 194fd51c13acae0b4dc902454023624d60291f25 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.statistics;


import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;


/**
 * A set of sums or other histograms.
 *
 * @author  <a href="mailto:steinar@yahoo-inc.com">Steinar Knutsen</a>
 */
public class Histogram implements Bucket {
    // The upper and lower limit for the bucket in another histogram
    // this histogram represents. The "outermost" histogram in a
    // multidimensional histogram will effectively ignore this, but set
    // them to -Inf and Inf for consistency.
    private final double lower;
    private final double upper;

    // The names of all the axes, only used in "outermost" histogram in
    // multi dimensional histogram.
    private String axes = null;

    private List<Bucket> buckets = new ArrayList<>();

    /**
     * Build a new histogram using bucket limits from the given Limits
     * object.
     */
    public Histogram(Limits limits) {
        // lower and upper will never be used here,
        // but it's nicer with defined values
        this(limits, 0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);

        // generate axis names, but only if there is more than one
        int guard = limits.getDimensions();
        if (guard == 1) {
            return;
        }
        StringBuffer names = new StringBuffer();
        int i = 0;
        while (i < guard) {
            names.append(limits.getAxis(i).getName());
            i++;
            if (i < guard) {
                names.append(",");
            }
        }
        axes = names.toString();
    }

    private Histogram(Limits limits, int dim, double lower, double upper) {
        this.lower = lower;
        this.upper = upper;
        // last axis, create sum objects instead of histograms
        boolean lastAxis = dim == (limits.getDimensions() - 1);
        Axis next = limits.getAxis(dim);
        double[] delimiters = next.getLimits();
        int i = 0;
        double previousBucket = Double.NEGATIVE_INFINITY;
        dim++;
        while (i < delimiters.length) {
            if (lastAxis) {
                buckets.add(new Sum(previousBucket, delimiters[i]));
            } else {
                buckets.add(new Histogram(limits, dim,
                                          previousBucket, delimiters[i]));
            }
            previousBucket = delimiters[i];
            i++;
        }
        if (lastAxis) {
            buckets.add(new Sum(previousBucket, Double.POSITIVE_INFINITY));
        } else {
            buckets.add(new Histogram(limits, dim,
                                      previousBucket,
                                      Double.POSITIVE_INFINITY));
        }

    }

    /**
     * Increment the corresponding bucket for this data point by 1.
     */
    public synchronized void put(double[] value) {
        put(value, 0);
    }

    /**
     * Increment the corresponding bucket for this data point by 1.
     *
     * @param dim the index of the first value to consider in value array
     */
    @Override
    public void put(double[] value, int dim) {
        Bucket bucket = findBucket(0, buckets.size(), value[dim]);
        bucket.put(value, ++dim);
    }

    private Bucket findBucket(int offset, int limit, double value) {
        int index = offset + (limit - offset) / 2;
        Bucket bucket = buckets.get(index);
        if (bucket.lowerLimit() <= value && value < bucket.upperLimit()) {
            return bucket;
        } else if (bucket.upperLimit() <= value) {
            return findBucket(index + 1, limit, value);
        } else { // value < bucket.lowerLimit()
            return findBucket(offset, index, value);
        }
    }

    @Override
    public String toString() {
        StringBuffer s;
        int i, t;

        s = new StringBuffer();
        if (axes != null) {
            s.append(axes).append(" ");
        }
        s.append("(");
        s.append(buckets.get(0).toString());
        s.append(")");

        t = buckets.size();
        i = 1;
        while (i < t) {
            Bucket b = buckets.get(i);
            s.append(" < ");
            s.append(b.lowerLimit());
            s.append(" (");
            s.append(b.toString());
            s.append(")");
            i += 1;
        }

        return s.toString();
    }

    /**
     * Reset all contained buckets.
     */
    @Override
    public void reset() {
        for (Iterator<Bucket> i = buckets.iterator(); i.hasNext(); ) {
            i.next().reset();
        }
    }

    /**
     * The lower limit for the bucket this histogram represents.
     *
     * @return the lower limit for the bucket this histogram represents
     */
    @Override
    public double lowerLimit() {
        return lower;
    }

    /**
     * The upper limit for the bucket this histogram represents.
     *
     * @return the upper limit for the bucket this histogram represents
     */
    @Override
    public double upperLimit() {
        return upper;
    }

    @Override
    public List<Bucket> getBuckets() {
        return buckets;
    }

    private List<Bucket> getLeaves() {
        final class Bookmark {
            final int i;
            final List<Bucket> buckets;
            Bookmark(int i, List<Bucket> buckets) {
                this.i = i;
                this.buckets = buckets;
            }
        }
        List<Bucket> sums = new ArrayList<>();
        Deque<Bookmark> stack = new ArrayDeque<>();
        List<Bucket> current;
        int i = 0;
        stack.addFirst(new Bookmark(i, buckets));
        while (stack.size() > 0) {
            Bookmark currentMark = stack.removeFirst();
            i = currentMark.i;
            current = currentMark.buckets;
            while (i < current.size()) {
                Bucket b = current.get(i++);
                if (b.isLeaf()) {
                    sums.add(b);
                } else {
                    Bookmark marker = new Bookmark(i, current);
                    stack.addFirst(marker);
                    i = 0;
                    current = b.getBuckets();
                }
            }
        }
        return sums;
    }

    void merge(Histogram source) {
        List<Bucket> src = source.getLeaves();
        List<Bucket> dst = getLeaves();
        if (dst.size() != src.size()) {
            throw new IllegalStateException(
                    "Number of buckets in destination and source not equal. (Source "
                            + src.size() + ", destination " + dst.size() + ".");
        }
        for (int i = 0; i < dst.size(); ++i) {
            dst.get(i).add(src.get(i).getSum());
        }
    }

    @Override
    public long getSum() {
        throw new RuntimeException("Not implemented.");
    }

    @Override
    public boolean isLeaf() {
        return false;
    }

    @Override
    public void add(long n) {
        throw new IllegalStateException("Can not add directly to a Histogram instance.");
    }
}