polydat 0.2.0

Polydat — a variates construction engine
Documentation
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Round-number selector nodes.
//!
//! General-purpose "snap this magnitude to a nice round number" math on
//! f64 values. Four scale families — powers of ten (`base10`), multiples
//! of the base-ten magnitude (`decade`), Fibonacci numbers (`fibonacci`),
//! and powers of two (`binomial`) — each in `floor_` / `ceiling_` /
//! `closest_` variants, plus a general arbitrary-`interval` rounder.
//!
//! These are pure numeric utilities (no adapter, no prefix), used to pick
//! human-friendly axis ticks, bucket boundaries, and magnitude labels.
//!
//! Edge handling: every family selector returns `0.0` for `x <= 0` and for
//! non-finite `x` — no panics, no NaN/inf leaking. Fractional `x` in `(0,1)`
//! yields fractional powers for `base10`/`binomial` (e.g. `floor_base10(0.5)
//! = 0.1`), which is correct and preserved. The interval rounders return
//! `x` unchanged when `interval` is non-positive or non-finite (identity —
//! never divide by zero).

// ---------------------------------------------------------------------------
// Private helpers (not nodes — plain module fns callable from node bodies).
// ---------------------------------------------------------------------------

/// True only for a strictly-positive, finite `x`. All family selectors gate
/// on this and return `0.0` otherwise, so `x <= 0`, `NaN`, and `±inf` all
/// fold to the zero magnitude without special-casing each node.
#[inline]
pub(crate) fn positive_finite(x: f64) -> bool {
    x.is_finite() && x > 0.0
}

/// Largest power of ten `10^n <= x`. Assumes `positive_finite(x)`.
///
/// The exponent is taken from `log10(x).floor()` but reconstructed with
/// `powi` (exact for `|result| < 2^53`) and corrected by at most one step,
/// so a one-ulp `log10` error at an exact power-of-ten boundary can't leak.
///
/// `pub` so non-node callers can reuse the exact `floor_base10` formula
/// without re-deriving it (DRY). `floor_base10` the node is just this
/// function behind the `positive_finite` guard, so a caller that already
/// guarantees a strictly-positive, finite `x` (e.g. the CQL batch-stride
/// planner, which floors `budget / row_size`) can call this directly.
#[inline]
pub fn floor_pow10(x: f64) -> f64 {
    let mut e = x.log10().floor() as i32;
    let mut p = 10f64.powi(e);
    if p > x {
        e -= 1;
        p = 10f64.powi(e);
    } else if p * 10.0 <= x {
        e += 1;
        p = 10f64.powi(e);
    }
    p
}

/// Largest power of two `2^n <= x`. Assumes `positive_finite(x)`.
///
/// Same `powi` + one-step-correction scheme as [`floor_pow10`].
#[inline]
pub(crate) fn floor_pow2(x: f64) -> f64 {
    let mut e = x.log2().floor() as i32;
    let mut p = 2f64.powi(e);
    if p > x {
        e -= 1;
        p = 2f64.powi(e);
    } else if p * 2.0 <= x {
        e += 1;
        p = 2f64.powi(e);
    }
    p
}

/// Pick whichever of `lo` / `hi` is nearer to `x` by absolute distance.
/// Ties resolve to `lo` (the floor), per the `closest_*` contract.
#[inline]
pub(crate) fn pick_closest(x: f64, lo: f64, hi: f64) -> f64 {
    if (hi - x).abs() < (x - lo).abs() {
        hi
    } else {
        lo
    }
}

/// Largest Fibonacci number (`1, 2, 3, 5, 8, …`) that is `<= x`, or `0.0`
/// when `x < 1` (nothing in the sequence is that small). Assumes finite `x`.
pub(crate) fn floor_fibonacci_val(x: f64) -> f64 {
    if x < 1.0 {
        return 0.0;
    }
    let (mut a, mut b) = (1.0f64, 2.0f64);
    while b <= x {
        let next = a + b;
        a = b;
        b = next;
        if !b.is_finite() {
            return a;
        }
    }
    a
}

/// Smallest Fibonacci number (`1, 2, 3, 5, 8, …`) that is `>= x`; `1.0` for
/// `x <= 1`. Assumes `positive_finite(x)`.
pub(crate) fn ceiling_fibonacci_val(x: f64) -> f64 {
    let (mut a, mut b) = (1.0f64, 2.0f64);
    if x <= a {
        return a;
    }
    loop {
        if b >= x {
            return b;
        }
        let next = a + b;
        a = b;
        b = next;
        if !b.is_finite() {
            return b;
        }
    }
}

// ---------------------------------------------------------------------------
// base10 — powers of ten (10^n).
// ---------------------------------------------------------------------------

/// Largest power of ten `<= x`: `10^floor(log10(x))`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn floor_base10(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    floor_pow10(x)
}

/// Smallest power of ten `>= x`: `10^ceil(log10(x))`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn ceiling_base10(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let lo = floor_pow10(x);
    if lo == x { lo } else { lo * 10.0 }
}

/// Power of ten nearest to `x` by absolute distance (ties → floor).
/// `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn closest_base10(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let lo = floor_pow10(x);
    let hi = if lo == x { lo } else { lo * 10.0 };
    pick_closest(x, lo, hi)
}

// ---------------------------------------------------------------------------
// decade — multiples of the base-ten magnitude `base = 10^floor(log10(x))`.
// ---------------------------------------------------------------------------

/// Round `x` down to a multiple of its base-ten magnitude:
/// `floor(x/base)*base`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn floor_decade(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let base = floor_pow10(x);
    (x / base).floor() * base
}

/// Round `x` up to a multiple of its base-ten magnitude:
/// `ceil(x/base)*base`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn ceiling_decade(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let base = floor_pow10(x);
    (x / base).ceil() * base
}

/// Round `x` to the nearest multiple of its base-ten magnitude:
/// `round(x/base)*base`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn closest_decade(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let base = floor_pow10(x);
    (x / base).round() * base
}

// ---------------------------------------------------------------------------
// fibonacci — Fibonacci numbers 1, 2, 3, 5, 8, 13, … (start 1, 2).
// ---------------------------------------------------------------------------

/// Largest Fibonacci number `<= x`. `x < 1` (incl. `x <= 0`) → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn floor_fibonacci(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    floor_fibonacci_val(x)
}

/// Smallest Fibonacci number `>= x`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn ceiling_fibonacci(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    ceiling_fibonacci_val(x)
}

/// Fibonacci number nearest to `x` by absolute distance (ties → floor).
/// `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn closest_fibonacci(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    pick_closest(x, floor_fibonacci_val(x), ceiling_fibonacci_val(x))
}

// ---------------------------------------------------------------------------
// binomial — powers of two (2^n).
// ---------------------------------------------------------------------------

/// Largest power of two `<= x`: `2^floor(log2(x))`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn floor_binomial(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    floor_pow2(x)
}

/// Smallest power of two `>= x`: `2^ceil(log2(x))`. `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn ceiling_binomial(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let lo = floor_pow2(x);
    if lo == x { lo } else { lo * 2.0 }
}

/// Power of two nearest to `x` by absolute distance (ties → floor).
/// `x <= 0` → `0.0`.
#[crate::polydat_node(category = Math)]
pub(crate) fn closest_binomial(x: f64) -> f64 {
    if !positive_finite(x) {
        return 0.0;
    }
    let lo = floor_pow2(x);
    let hi = if lo == x { lo } else { lo * 2.0 };
    pick_closest(x, lo, hi)
}

// ---------------------------------------------------------------------------
// General arbitrary-interval rounders.
// ---------------------------------------------------------------------------

/// Round `x` down to a multiple of `interval`: `floor(x/interval)*interval`.
/// `interval <= 0` or non-finite → returns `x` unchanged (identity).
#[crate::polydat_node(category = Math)]
pub(crate) fn round_floor(x: f64, interval: f64) -> f64 {
    if !(interval.is_finite() && interval > 0.0) {
        return x;
    }
    (x / interval).floor() * interval
}

/// Round `x` up to a multiple of `interval`: `ceil(x/interval)*interval`.
/// `interval <= 0` or non-finite → returns `x` unchanged (identity).
#[crate::polydat_node(category = Math)]
pub(crate) fn round_ceiling(x: f64, interval: f64) -> f64 {
    if !(interval.is_finite() && interval > 0.0) {
        return x;
    }
    (x / interval).ceil() * interval
}

/// Round `x` to the nearest multiple of `interval`: `round(x/interval)*interval`.
/// `interval <= 0` or non-finite → returns `x` unchanged (identity).
#[crate::polydat_node(category = Math)]
pub(crate) fn round_nearest(x: f64, interval: f64) -> f64 {
    if !(interval.is_finite() && interval > 0.0) {
        return x;
    }
    (x / interval).round() * interval
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{PolydatNode, Value};

    fn run1(node: &dyn PolydatNode, x: f64) -> f64 {
        let mut out = [Value::None];
        node.eval(&[Value::F64(x)], &mut out);
        out[0].as_f64()
    }

    fn run2(node: &dyn PolydatNode, x: f64, interval: f64) -> f64 {
        let mut out = [Value::None];
        node.eval(&[Value::F64(x), Value::F64(interval)], &mut out);
        out[0].as_f64()
    }

    // ── base10 ────────────────────────────────────────────
    #[test]
    fn base10_vectors() {
        assert_eq!(run1(&FloorBase10::new(), 1732.234), 1000.0);
        assert_eq!(run1(&CeilingBase10::new(), 1732.0), 10000.0);
        assert_eq!(run1(&ClosestBase10::new(), 1732.0), 1000.0);
        assert_eq!(run1(&ClosestBase10::new(), 6000.0), 10000.0);
    }

    #[test]
    fn base10_exact_power_is_stable() {
        // On an exact power of ten, floor == ceiling == x.
        assert_eq!(run1(&FloorBase10::new(), 1000.0), 1000.0);
        assert_eq!(run1(&CeilingBase10::new(), 1000.0), 1000.0);
    }

    #[test]
    fn base10_fractional_below_one() {
        // (0,1): powers of ten stay fractional — keep it.
        assert!((run1(&FloorBase10::new(), 0.5) - 0.1).abs() < 1e-12);
    }

    // ── decade ────────────────────────────────────────────
    #[test]
    fn decade_vectors() {
        assert_eq!(run1(&FloorDecade::new(), 2734.0), 2000.0);
        assert_eq!(run1(&CeilingDecade::new(), 2734.0), 3000.0);
        assert_eq!(run1(&ClosestDecade::new(), 2734.0), 3000.0);
        assert_eq!(run1(&FloorDecade::new(), 1732.0), 1000.0);
        assert_eq!(run1(&ClosestDecade::new(), 1732.0), 2000.0);
        assert_eq!(run1(&CeilingDecade::new(), 1732.0), 2000.0);
    }

    // ── fibonacci ─────────────────────────────────────────
    #[test]
    fn fibonacci_vectors() {
        assert_eq!(run1(&FloorFibonacci::new(), 1732.0), 1597.0);
        assert_eq!(run1(&CeilingFibonacci::new(), 1732.0), 2584.0);
        assert_eq!(run1(&ClosestFibonacci::new(), 1732.0), 1597.0);
    }

    #[test]
    fn fibonacci_floor_below_one_is_zero() {
        assert_eq!(run1(&FloorFibonacci::new(), 0.5), 0.0);
    }

    #[test]
    fn fibonacci_exact_member_is_stable() {
        assert_eq!(run1(&FloorFibonacci::new(), 1597.0), 1597.0);
        assert_eq!(run1(&CeilingFibonacci::new(), 1597.0), 1597.0);
    }

    // ── binomial ──────────────────────────────────────────
    #[test]
    fn binomial_vectors() {
        assert_eq!(run1(&FloorBinomial::new(), 1732.0), 1024.0);
        assert_eq!(run1(&CeilingBinomial::new(), 1732.0), 2048.0);
        assert_eq!(run1(&ClosestBinomial::new(), 1732.0), 2048.0);
    }

    #[test]
    fn binomial_exact_power_is_stable() {
        assert_eq!(run1(&FloorBinomial::new(), 1024.0), 1024.0);
        assert_eq!(run1(&CeilingBinomial::new(), 1024.0), 1024.0);
    }

    // ── non-positive / non-finite edges ───────────────────
    #[test]
    fn non_positive_inputs_are_zero() {
        assert_eq!(run1(&FloorBase10::new(), 0.0), 0.0);
        assert_eq!(run1(&FloorBase10::new(), -5.0), 0.0);
        assert_eq!(run1(&CeilingBinomial::new(), -1.0), 0.0);
        assert_eq!(run1(&ClosestFibonacci::new(), 0.0), 0.0);
        assert_eq!(run1(&ClosestDecade::new(), -1000.0), 0.0);
        assert_eq!(run1(&FloorBase10::new(), f64::INFINITY), 0.0);
        assert_eq!(run1(&FloorBinomial::new(), f64::NAN), 0.0);
    }

    // ── general interval rounders ─────────────────────────
    #[test]
    fn round_interval_vectors() {
        assert_eq!(run2(&RoundFloor::new(), 1732.0, 500.0), 1500.0);
        assert_eq!(run2(&RoundCeiling::new(), 1732.0, 500.0), 2000.0);
        // (1732/500).round() = 3, so nearest multiple of 500 is 1500.
        assert_eq!(run2(&RoundNearest::new(), 1732.0, 500.0), 1500.0);
        assert_eq!(run2(&RoundNearest::new(), 1700.0, 500.0), 1500.0);
        // interval <= 0 → identity.
        assert_eq!(run2(&RoundFloor::new(), 1732.0, 0.0), 1732.0);
    }

    #[test]
    fn round_interval_identity_on_bad_interval() {
        assert_eq!(run2(&RoundNearest::new(), 1732.0, -5.0), 1732.0);
        assert_eq!(run2(&RoundCeiling::new(), 1732.0, f64::INFINITY), 1732.0);
        assert_eq!(run2(&RoundFloor::new(), 1732.0, f64::NAN), 1732.0);
    }

    // ── registry discovery ────────────────────────────────
    #[test]
    fn all_fifteen_registered_under_math() {
        for name in [
            "floor_base10", "ceiling_base10", "closest_base10",
            "floor_decade", "ceiling_decade", "closest_decade",
            "floor_fibonacci", "ceiling_fibonacci", "closest_fibonacci",
            "floor_binomial", "ceiling_binomial", "closest_binomial",
            "round_floor", "round_ceiling", "round_nearest",
        ] {
            let sig = crate::dsl::registry::lookup(name)
                .unwrap_or_else(|| panic!("node '{name}' not registered"));
            assert_eq!(
                sig.category,
                crate::dsl::registry::FuncCategory::Math,
                "node '{name}' registered under wrong category",
            );
        }
    }
}