File size: 9,697 Bytes
84d2a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use std::cell::Cell;
use std::collections::BTreeSet;
use std::collections::Bound::{Excluded, Included, Unbounded};

use itertools::Itertools;
use rand::prelude::StdRng;
use rand::{Rng, SeedableRng};
use rand_distr::StandardNormal;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::index::field_index::histogram::{Histogram, Numericable, Point};
use crate::index::field_index::tests::histogram_test_utils::print_results;

pub fn count_range<T: PartialOrd>(points_index: &BTreeSet<Point<T>>, a: T, b: T) -> usize {
    points_index
        .iter()
        .filter(|x| a <= x.val && x.val <= b)
        .count()
}

#[test]
fn test_build_histogram_small() {
    let max_bucket_size = 10;
    let precision = 0.01;
    let num_samples = 1000;
    let mut rnd = StdRng::seed_from_u64(42);

    // let points = (0..100000).map(|i| Point { val: rnd.gen_range(-10.0..10.0), idx: i }).collect_vec();
    let points = (0..num_samples)
        .map(|i| Point {
            val: f64::round(rnd.sample::<f64, _>(StandardNormal) * 10.0),
            idx: i % num_samples / 2,
        })
        .collect_vec();

    let mut points_index: BTreeSet<Point<_>> = Default::default();

    let mut histogram = Histogram::new(max_bucket_size, precision);

    for point in &points {
        points_index.insert(point.clone());
        // print_results(&points_index, &histogram, Some(point.clone()));
        histogram.insert(
            point.clone(),
            |x| {
                points_index
                    .range((Unbounded, Excluded(x)))
                    .next_back()
                    .cloned()
            },
            |x| points_index.range((Excluded(x), Unbounded)).next().cloned(),
        );
    }

    for point in &points {
        print_results(&points_index, &histogram, Some(point.clone()));
        points_index.remove(point);
        histogram.remove(
            point,
            |x| {
                points_index
                    .range((Unbounded, Excluded(x)))
                    .next_back()
                    .cloned()
            },
            |x| points_index.range((Excluded(x), Unbounded)).next().cloned(),
        );
    }
}

pub fn test_range_by_cardinality(histogram: &Histogram<f64>) {
    let from = Unbounded;
    let range_size = 100;
    let to = histogram.get_range_by_size(from, range_size);
    let estimation = histogram.estimate(from, to);
    eprintln!("({from:?} - {to:?}) -> {estimation:?} / {range_size}");
    assert!(
        (estimation.1 as i64 - range_size as i64).abs()
            < 2 * histogram.current_bucket_size() as i64
    );

    let from = Unbounded;
    let range_size = 1000;
    let to = histogram.get_range_by_size(from, range_size);
    let estimation = histogram.estimate(from, to);
    eprintln!("({from:?} - {to:?}) -> {estimation:?} / {range_size}");
    assert!(
        (estimation.1 as i64 - range_size as i64).abs()
            < 2 * histogram.current_bucket_size() as i64
    );

    let from = Excluded(0.1);
    let range_size = 100;
    let to = histogram.get_range_by_size(from, range_size);
    let estimation = histogram.estimate(from, to);
    eprintln!("({from:?} - {to:?}) -> {estimation:?} / {range_size}");
    assert!(
        (estimation.1 as i64 - range_size as i64).abs()
            < 2 * histogram.current_bucket_size() as i64
    );

    let from = Excluded(0.1);
    let range_size = 1000;
    let to = histogram.get_range_by_size(from, range_size);
    let estimation = histogram.estimate(from, to);
    eprintln!("({from:?} - {to:?}) -> {estimation:?} / {range_size}");
    assert!(
        (estimation.1 as i64 - range_size as i64).abs()
            < 2 * histogram.current_bucket_size() as i64
    );

    let from = Excluded(0.1);
    let range_size = 100_000;
    let to = histogram.get_range_by_size(from, range_size);
    let estimation = histogram.estimate(from, to);
    eprintln!("({from:?} - {to:?}) -> {estimation:?} / {range_size}");
    assert!(matches!(to, Unbounded));
}

pub fn request_histogram(histogram: &Histogram<f64>, points_index: &BTreeSet<Point<f64>>) {
    let (est_min, estimation, est_max) = histogram.estimate(Included(0.0), Included(0.0));
    let real = count_range(points_index, 0., 0.);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(0.0), Included(0.0001));
    let real = count_range(points_index, 0., 0.0001);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(0.0), Included(0.01));
    let real = count_range(points_index, 0., 0.01);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(0.), Included(1.));
    let real = count_range(points_index, 0., 1.);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(0.), Included(100.));
    let real = count_range(points_index, 0., 100.);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(-100.), Included(100.));
    let real = count_range(points_index, -100., 100.);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());

    let (est_min, estimation, est_max) = histogram.estimate(Included(20.), Included(100.));
    let real = count_range(points_index, 20., 100.);

    eprintln!(
        "{real} / ({est_min}, {estimation}, {est_max}) = {}",
        estimation as f64 / real as f64,
    );
    assert!(real.abs_diff(estimation) < 2 * histogram.current_bucket_size());
}

pub fn build_histogram<T: Numericable + Serialize + DeserializeOwned + std::fmt::Debug>(
    max_bucket_size: usize,
    precision: f64,
    points: Vec<Point<T>>,
) -> (Histogram<T>, BTreeSet<Point<T>>) {
    let mut points_index: BTreeSet<Point<T>> = Default::default();
    let mut histogram = Histogram::new(max_bucket_size, precision);

    let read_counter = Cell::new(0);
    for point in points {
        points_index.insert(point.clone());
        // print_results(&points_index, &histogram, Some(point.clone()));
        histogram.insert(
            point,
            |x| {
                read_counter.set(read_counter.get() + 1);
                points_index
                    .range((Unbounded, Excluded(x)))
                    .next_back()
                    .cloned()
            },
            |x| {
                read_counter.set(read_counter.get() + 1);
                points_index.range((Excluded(x), Unbounded)).next().cloned()
            },
        );
    }
    eprintln!("read_counter.get() = {:#?}", read_counter.get());
    eprintln!("histogram.borders.len() = {:#?}", histogram.borders().len());
    for border in histogram.borders().iter().take(5) {
        eprintln!("border = {border:?}");
    }
    (histogram, points_index)
}

#[test]
fn test_build_histogram_round() {
    let max_bucket_size = 100;
    let precision = 0.01;
    let num_samples = 100_000;
    let mut rnd = StdRng::seed_from_u64(42);

    // let points = (0..100000).map(|i| Point { val: rnd.gen_range(-10.0..10.0), idx: i }).collect_vec();
    let points = (0..num_samples).map(|i| Point {
        val: f64::round(rnd.sample::<f64, _>(StandardNormal) * 100.0),
        idx: i,
    });
    let (histogram, points_index) = build_histogram(max_bucket_size, precision, points.collect());

    request_histogram(&histogram, &points_index);
}

#[test]
fn test_build_histogram() {
    let max_bucket_size = 1000;
    let precision = 0.01;
    let num_samples = 100_000;
    let mut rnd = StdRng::seed_from_u64(42);

    // let points = (0..100000).map(|i| Point { val: rnd.gen_range(-10.0..10.0), idx: i }).collect_vec();
    let points = (0..num_samples)
        .map(|i| Point {
            val: rnd.sample(StandardNormal),
            idx: i,
        })
        .collect_vec();

    let (histogram, points_index) = build_histogram(max_bucket_size, precision, points);
    request_histogram(&histogram, &points_index);
    test_range_by_cardinality(&histogram);
}

#[test]
fn test_save_load_histogram() {
    let max_bucket_size = 1000;
    let precision = 0.01;
    let num_samples = 100_000;
    let mut rnd = StdRng::seed_from_u64(42);

    let points = (0..num_samples)
        .map(|i| Point {
            val: rnd.gen_range(-10.0..10.0),
            idx: i,
        })
        .collect_vec();
    let (histogram, _) = build_histogram(max_bucket_size, precision, points);

    let dir = tempfile::Builder::new()
        .prefix("histogram_dir")
        .tempdir()
        .unwrap();
    histogram.save(dir.path()).unwrap();

    let loaded_histogram = Histogram::<f64>::load(dir.path()).unwrap();
    assert_eq!(histogram, loaded_histogram);
}