u-numflow 0.8.0

Foundational mathematical primitives: statistics, probability distributions, random sampling, and collections.
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! WASM bindings for u-numflow.
//!
//! Exposes a subset of the library's public API to JavaScript via `wasm-bindgen`.
//! Only enabled when the `wasm` feature is active.
//!
//! # Exported functions
//! - `mean(data)` → `f64` (throws `empty_input` when `data` is empty)
//! - `std_dev(data)` → `f64` (throws `insufficient_data` below 2 elements)
//! - `variance(data)` → `f64` (throws `insufficient_data` below 2 elements)
//! - `normal_cdf(x)` → `f64` — standard normal CDF Φ(x), i.e. N(0,1)
//! - `normal_sf(x)` → `f64` — standard normal upper tail P(Z > x), tail-precise
//! - `box_cox(data, lambda)` → `Result<Vec<f64>, JsValue>`
//! - `estimate_lambda(data, lambda_min, lambda_max)` → `{ lambda, at_bound }` (or throws)
//! - `rfft(data)` → `Vec<f64>` — DFT of a real sequence, interleaved `[re0, im0, re1, im1, …]`
//! - `inverse_normal_cdf(p)` → `f64` — standard normal quantile (throws outside `(0, 1)`)
//! - `t_distribution_cdf(t, df)` / `t_distribution_quantile(p, df)` → `f64` (throw on an invalid argument)
//! - `f_distribution_cdf(x, df1, df2)` / `f_distribution_quantile(p, df1, df2)` → `f64` (same)
//! - `chi_squared_cdf(x, k)` / `chi_squared_quantile(p, k)` → `f64` (same)
//!
//! Every `data` argument is a `number[]` or a `Float64Array`, read as sent: an
//! element that is not a number (`null`, a string) is refused as
//! `malformed_input` and a NaN or ±Infinity as `value_not_finite`, each with
//! the element's `index`. (A `&[f64]` parameter would let wasm-bindgen copy the
//! array into a typed array first, turning `null` into 0 and a string into NaN.)
//!
//! Every refusal throws an `Error` whose `message` is readable text and which
//! carries `code` -- a stable reason -- and the values behind it (`parameter`,
//! `min`, `max`, `got`). See the README's *Errors*.

#![cfg(feature = "wasm")]

use wasm_bindgen::prelude::*;

use crate::transforms::TransformError;

// ── Refusals ──────────────────────────────────────────────────────────────

/// A value carried on a refusal.
#[derive(Debug, Clone, PartialEq)]
enum Field {
    Num(f64),
    Str(&'static str),
    Null,
}

/// A refusal on its way to JavaScript: the text for `Error.message`, a stable
/// `code`, and the values behind it.
#[derive(Debug, Clone, PartialEq)]
struct Refusal {
    code: &'static str,
    message: String,
    fields: Vec<(&'static str, Field)>,
}

impl Refusal {
    /// An argument outside the range the function accepts; `max` is `None`
    /// when the range is open above.
    fn out_of_range(
        parameter: &'static str,
        min: f64,
        max: Option<f64>,
        got: f64,
        message: String,
    ) -> Self {
        Refusal {
            code: "parameter_out_of_range",
            message,
            fields: vec![
                ("parameter", Field::Str(parameter)),
                ("min", Field::Num(min)),
                ("max", max.map_or(Field::Null, Field::Num)),
                ("got", Field::Num(got)),
            ],
        }
    }
}

/// One element of a JS number array, as found.
#[derive(Debug, Clone, PartialEq)]
enum Element {
    Number(f64),
    /// Anything else, by its JS type name (`"null"`, `"string"`, …).
    Other(String),
}

/// The values of a number array, refusing the first element that is not a
/// finite number and naming where it sits.
///
/// Kept apart from the `JsValue` walk so it runs off `wasm32` in tests.
fn numbers_from(
    parameter: &'static str,
    elements: impl IntoIterator<Item = Element>,
) -> Result<Vec<f64>, Refusal> {
    let mut out = Vec::new();
    for (i, element) in elements.into_iter().enumerate() {
        match element {
            Element::Number(x) if x.is_finite() => out.push(x),
            Element::Number(x) => {
                return Err(Refusal {
                    code: "value_not_finite",
                    message: format!("{parameter}[{i}]: expected a finite number, got {x}"),
                    fields: vec![
                        ("parameter", Field::Str(parameter)),
                        ("index", Field::Num(i as f64)),
                    ],
                })
            }
            Element::Other(kind) => {
                return Err(Refusal {
                    code: "malformed_input",
                    message: format!("{parameter}[{i}]: expected a number, got {kind}"),
                    fields: vec![
                        ("parameter", Field::Str(parameter)),
                        ("index", Field::Num(i as f64)),
                    ],
                })
            }
        }
    }
    Ok(out)
}

/// Reads a `number[]` or `Float64Array` argument without converting it.
fn read_numbers(value: &JsValue, parameter: &'static str) -> Result<Vec<f64>, Refusal> {
    use wasm_bindgen::JsCast;
    if let Some(typed) = value.dyn_ref::<js_sys::Float64Array>() {
        return numbers_from(parameter, typed.to_vec().into_iter().map(Element::Number));
    }
    if !js_sys::Array::is_array(value) {
        return Err(Refusal {
            code: "malformed_input",
            message: format!("{parameter}: expected an array of numbers or a Float64Array"),
            fields: vec![("parameter", Field::Str(parameter))],
        });
    }
    let array: &js_sys::Array = value.unchecked_ref();
    numbers_from(
        parameter,
        array.iter().map(|item| match item.as_f64() {
            Some(x) => Element::Number(x),
            None if item.is_null() => Element::Other("null".to_string()),
            None => Element::Other(item.js_typeof().as_string().unwrap_or_default()),
        }),
    )
}

/// `data` with at least `min` values, or `insufficient_data` saying so.
fn at_least(data: Vec<f64>, min: usize) -> Result<Vec<f64>, Refusal> {
    if data.len() >= min {
        Ok(data)
    } else {
        Err(Refusal {
            code: "insufficient_data",
            message: format!("data: at least {min} values are needed, got {}", data.len()),
            fields: vec![
                ("parameter", Field::Str("data")),
                ("min", Field::Num(min as f64)),
                ("got", Field::Num(data.len() as f64)),
            ],
        })
    }
}

impl From<TransformError> for Refusal {
    fn from(e: TransformError) -> Self {
        let code = match e {
            TransformError::NonPositiveData => "non_positive_data",
            TransformError::NonFiniteData => "value_not_finite",
            TransformError::InsufficientData => "insufficient_data",
            TransformError::InvalidTransform => "invalid_transform",
            TransformError::InvalidInverse => "invalid_inverse",
            TransformError::InvalidLambdaRange => "invalid_lambda_range",
        };
        Refusal {
            code,
            message: e.to_string(),
            fields: Vec::new(),
        }
    }
}

/// Every refusal crosses into JavaScript as an `Error` whose `message` is the
/// readable text, with `code` and the fields set on it as properties.
impl From<Refusal> for JsValue {
    fn from(refusal: Refusal) -> JsValue {
        let err = js_sys::Error::new(&refusal.message);
        // `Reflect::set` on a freshly created ordinary object cannot fail.
        let _ = js_sys::Reflect::set(&err, &"code".into(), &refusal.code.into());
        for (key, value) in refusal.fields {
            let value = match value {
                Field::Num(n) => JsValue::from_f64(n),
                Field::Str(s) => s.into(),
                Field::Null => JsValue::NULL,
            };
            let _ = js_sys::Reflect::set(&err, &key.into(), &value);
        }
        err.into()
    }
}

/// Arithmetic mean of `data` using Kahan compensated summation.
///
/// # Errors
/// Throws `empty_input` when `data` is empty, and as every `data` argument
/// does for an element that is not a finite number.
#[wasm_bindgen]
pub fn mean(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
) -> Result<f64, JsValue> {
    let data = read_numbers(&data, "data")?;
    if data.is_empty() {
        return Err(Refusal {
            code: "empty_input",
            message: "data: the mean of no values is undefined".to_string(),
            fields: vec![("parameter", Field::Str("data"))],
        }
        .into());
    }
    Ok(crate::stats::mean(&data).expect("non-empty finite data has a mean"))
}

/// Sample standard deviation of `data` (Bessel-corrected, denominator n−1).
///
/// # Errors
/// Throws `insufficient_data` below 2 values.
#[wasm_bindgen]
pub fn std_dev(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
) -> Result<f64, JsValue> {
    let data = at_least(read_numbers(&data, "data")?, 2)?;
    Ok(crate::stats::std_dev(&data).expect("two or more finite values have a std_dev"))
}

/// Sample variance of `data` (Bessel-corrected, denominator n−1).
///
/// # Errors
/// Throws `insufficient_data` below 2 values.
#[wasm_bindgen]
pub fn variance(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
) -> Result<f64, JsValue> {
    let data = at_least(read_numbers(&data, "data")?, 2)?;
    Ok(crate::stats::variance(&data).expect("two or more finite values have a variance"))
}

/// Standard normal CDF Φ(x) = P(Z ≤ x) for Z ~ N(0, 1).
///
/// To evaluate a general normal N(μ, σ), pass `(x - μ) / σ`.
///
/// Computed as `erfc(−x/√2)/2` with a direct `erfc`, so the lower tail keeps
/// relative precision. For the upper tail use [`normal_sf`].
#[wasm_bindgen]
pub fn normal_cdf(x: f64) -> f64 {
    crate::special::standard_normal_cdf(x)
}

/// Standard normal survival function P(Z > x) = 1 − Φ(x) for Z ~ N(0, 1).
///
/// Computed directly (not as `1 − normal_cdf(x)`), so upper-tail
/// probabilities such as PPM defect rates keep their significant digits:
/// `normal_sf(6)` is `9.865876450376948e-10` to about 15 digits.
#[wasm_bindgen]
pub fn normal_sf(x: f64) -> f64 {
    crate::special::standard_normal_sf(x)
}

/// Apply the Box-Cox power transformation to positive data.
///
/// All values in `data` must be strictly positive.
///
/// # Errors
/// Throws `non_positive_data`, `value_not_finite` or `insufficient_data` when
/// data contains a value ≤ 0, a NaN or infinity, or fewer than 2 elements, and
/// `invalid_transform` when a result is not finite.
#[wasm_bindgen]
pub fn box_cox(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
    lambda: f64,
) -> Result<Vec<f64>, JsValue> {
    let data = read_numbers(&data, "data")?;
    crate::transforms::box_cox(&data, lambda).map_err(|e| Refusal::from(e).into())
}

/// Output of [`estimate_lambda`]: `{ lambda, at_bound }`.
#[derive(serde::Serialize, tsify::Tsify)]
struct LambdaEstimateDto {
    lambda: f64,
    at_bound: bool,
}

/// Estimate the optimal Box-Cox lambda via profile maximum likelihood.
///
/// Searches in the range `[lambda_min, lambda_max]` using golden-section search
/// and returns `{ lambda: number, at_bound: boolean }`. `at_bound` is `true`
/// when the maximum lies on an end of the range — the likelihood was still
/// rising there, so `lambda` is that range limit (reported exactly), not an
/// interior estimate; widen the range to find the unconstrained optimum.
///
/// # Errors
/// Throws as [`box_cox`] does for the data, and `invalid_lambda_range` when the
/// range is not finite with `lambda_min < lambda_max`.
#[wasm_bindgen(unchecked_return_type = "LambdaEstimateDto")]
pub fn estimate_lambda(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
    lambda_min: f64,
    lambda_max: f64,
) -> Result<JsValue, JsValue> {
    let data = read_numbers(&data, "data")?;
    let est =
        crate::transforms::estimate_lambda(&data, lambda_min, lambda_max).map_err(Refusal::from)?;
    serde_wasm_bindgen::to_value(&LambdaEstimateDto {
        lambda: est.lambda,
        at_bound: est.at_bound,
    })
    .map_err(|e| {
        Refusal {
            code: "malformed_input",
            message: e.to_string(),
            fields: vec![("parameter", Field::Str("result"))],
        }
        .into()
    })
}

/// Forward DFT of a real sequence of any length.
///
/// Returns the `n` complex bins interleaved as `[re0, im0, re1, im1, …]`
/// (length `2n`). Bins `k` and `n − k` are conjugates, so the spectrum of a
/// real signal is fully described by bins `0..=n/2`.
///
/// # Errors
/// Throws as every `data` argument does for an element that is not a finite
/// number.
#[wasm_bindgen]
pub fn rfft(
    #[wasm_bindgen(unchecked_param_type = "number[] | Float64Array")] data: JsValue,
) -> Result<Vec<f64>, JsValue> {
    let data = read_numbers(&data, "data")?;
    Ok(crate::fourier::rfft(&data)
        .into_iter()
        .flat_map(|z| [z.re, z.im])
        .collect())
}

// ── Distribution CDFs and quantiles (critical values) ─────────────────────
//
// The crate functions return NaN for an argument outside their domain. Across
// the JS boundary a NaN critical value draws nothing and raises nothing, so
// these wrappers refuse such arguments instead and name the one that failed.

/// `p` strictly inside `(0, 1)`: `parameter_out_of_range` with `min` 0 and
/// `max` 1 -- both excluded, as the message says.
fn check_probability(p: f64) -> Result<(), Refusal> {
    if p.is_finite() && p > 0.0 && p < 1.0 {
        Ok(())
    } else {
        Err(Refusal::out_of_range(
            "p",
            0.0,
            Some(1.0),
            p,
            format!("p must be strictly between 0 and 1, got {p}"),
        ))
    }
}

/// Degrees of freedom: a finite number above 0 (`min` 0, excluded).
fn check_df(name: &'static str, df: f64) -> Result<(), Refusal> {
    if df.is_finite() && df > 0.0 {
        Ok(())
    } else {
        Err(Refusal::out_of_range(
            name,
            0.0,
            None,
            df,
            format!("{name} must be a finite number > 0, got {df}"),
        ))
    }
}

fn check_finite(name: &'static str, x: f64) -> Result<(), Refusal> {
    if x.is_nan() {
        Err(Refusal {
            code: "value_not_finite",
            message: format!("{name} must be a number, got NaN"),
            fields: vec![("parameter", Field::Str(name))],
        })
    } else {
        Ok(())
    }
}

/// Standard normal quantile Φ⁻¹(p): the `z` with `P(Z ≤ z) = p`.
///
/// # Errors
/// Throws if `p` is not strictly between 0 and 1.
#[wasm_bindgen]
pub fn inverse_normal_cdf(p: f64) -> Result<f64, JsValue> {
    check_probability(p)?;
    Ok(crate::special::inverse_normal_cdf(p))
}

/// Student's t CDF: `P(T ≤ t)` for `T ~ t(df)`. `df` may be fractional.
///
/// # Errors
/// Throws if `t` is NaN or `df` is not a finite number > 0.
#[wasm_bindgen]
pub fn t_distribution_cdf(t: f64, df: f64) -> Result<f64, JsValue> {
    check_finite("t", t)?;
    check_df("df", df)?;
    Ok(crate::special::t_distribution_cdf(t, df))
}

/// Student's t quantile: the `t` with `P(T ≤ t) = p`. A two-sided critical
/// value at level α is `t_distribution_quantile(1 − α/2, df)`.
///
/// # Errors
/// Throws if `p` is not strictly between 0 and 1, or `df` is not a finite
/// number > 0.
#[wasm_bindgen]
pub fn t_distribution_quantile(p: f64, df: f64) -> Result<f64, JsValue> {
    check_probability(p)?;
    check_df("df", df)?;
    Ok(crate::special::t_distribution_quantile(p, df))
}

/// F CDF: `P(X ≤ x)` for `X ~ F(df1, df2)` (`0` for `x ≤ 0`).
///
/// # Errors
/// Throws if `x` is NaN, or `df1`/`df2` is not a finite number > 0.
#[wasm_bindgen]
pub fn f_distribution_cdf(x: f64, df1: f64, df2: f64) -> Result<f64, JsValue> {
    check_finite("x", x)?;
    check_df("df1", df1)?;
    check_df("df2", df2)?;
    Ok(crate::special::f_distribution_cdf(x, df1, df2))
}

/// F quantile: the `x` with `P(X ≤ x) = p` for `X ~ F(df1, df2)`.
///
/// # Errors
/// Throws if `p` is not strictly between 0 and 1, or `df1`/`df2` is not a
/// finite number > 0.
#[wasm_bindgen]
pub fn f_distribution_quantile(p: f64, df1: f64, df2: f64) -> Result<f64, JsValue> {
    check_probability(p)?;
    check_df("df1", df1)?;
    check_df("df2", df2)?;
    Ok(crate::special::f_distribution_quantile(p, df1, df2))
}

/// Chi-squared CDF: `P(X ≤ x)` for `X ~ χ²(k)` (`0` for `x ≤ 0`).
///
/// # Errors
/// Throws if `x` is NaN or `k` is not a finite number > 0.
#[wasm_bindgen]
pub fn chi_squared_cdf(x: f64, k: f64) -> Result<f64, JsValue> {
    check_finite("x", x)?;
    check_df("k", k)?;
    Ok(crate::special::chi_squared_cdf(x, k))
}

/// Chi-squared quantile: the `x` with `P(X ≤ x) = p` for `X ~ χ²(k)`.
///
/// # Errors
/// Throws if `p` is not strictly between 0 and 1, or `k` is not a finite
/// number > 0.
#[wasm_bindgen]
pub fn chi_squared_quantile(p: f64, k: f64) -> Result<f64, JsValue> {
    check_probability(p)?;
    check_df("k", k)?;
    Ok(crate::special::chi_squared_quantile(p, k))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_probability_outside_0_1_names_the_range() {
        let r = check_probability(1.5).expect_err("outside");
        assert_eq!(r.code, "parameter_out_of_range");
        assert_eq!(
            r.fields,
            vec![
                ("parameter", Field::Str("p")),
                ("min", Field::Num(0.0)),
                ("max", Field::Num(1.0)),
                ("got", Field::Num(1.5)),
            ]
        );
        assert!(check_probability(0.5).is_ok());
    }

    #[test]
    fn degrees_of_freedom_are_open_above() {
        let r = check_df("df2", 0.0).expect_err("zero");
        assert_eq!(r.fields[0], ("parameter", Field::Str("df2")));
        assert_eq!(r.fields[2], ("max", Field::Null));
    }

    #[test]
    fn nan_is_refused_as_not_finite() {
        assert_eq!(
            check_finite("x", f64::NAN).expect_err("NaN").code,
            "value_not_finite"
        );
        assert!(check_finite("x", f64::INFINITY).is_ok());
    }

    #[test]
    fn a_number_array_is_read_as_sent() {
        let ok = numbers_from("data", [1.0, -2.5].map(Element::Number)).expect("numbers");
        assert_eq!(ok, vec![1.0, -2.5]);
        assert!(numbers_from("data", []).expect("empty").is_empty());
    }

    #[test]
    fn null_is_refused_where_it_sits_not_read_as_zero() {
        let r = numbers_from(
            "data",
            [
                Element::Number(1.0),
                Element::Other("null".into()),
                Element::Number(3.0),
            ],
        )
        .expect_err("null");
        assert_eq!(r.code, "malformed_input");
        assert_eq!(
            r.fields,
            vec![
                ("parameter", Field::Str("data")),
                ("index", Field::Num(1.0))
            ]
        );
        assert!(r.message.contains("got null"), "{}", r.message);
    }

    #[test]
    fn a_non_finite_element_is_not_finite_with_its_index() {
        let r = numbers_from("data", [0.0, f64::INFINITY].map(Element::Number)).expect_err("inf");
        assert_eq!(r.code, "value_not_finite");
        assert_eq!(r.fields[1], ("index", Field::Num(1.0)));
    }

    #[test]
    fn too_few_values_say_how_many_are_needed() {
        let r = at_least(vec![1.0], 2).expect_err("one");
        assert_eq!(r.code, "insufficient_data");
        assert_eq!(r.fields[1], ("min", Field::Num(2.0)));
        assert_eq!(r.fields[2], ("got", Field::Num(1.0)));
        assert!(at_least(vec![1.0, 2.0], 2).is_ok());
    }

    #[test]
    fn transform_errors_keep_their_reason() {
        let r = Refusal::from(TransformError::NonPositiveData);
        assert_eq!(r.code, "non_positive_data");
        assert_eq!(r.message, TransformError::NonPositiveData.to_string());
    }
}