scirs2-wasm 0.4.3

WebAssembly (WASM) bindings for SciRS2 - JavaScript/TypeScript interop for scientific computing
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
//! Interpolation functions for WASM
//!
//! Provides wasm_bindgen bindings for 1D interpolation methods including
//! linear, nearest, quadratic (cubic), cubic spline, Lagrange polynomial,
//! PCHIP (Piecewise Cubic Hermite Interpolating Polynomial), and Akima
//! interpolation.

use crate::error::WasmError;
use scirs2_interpolate::advanced::akima::AkimaSpline;
use scirs2_interpolate::advanced::barycentric::BarycentricInterpolator;
use scirs2_interpolate::interp1d::{Interp1d, InterpolationMethod};
use scirs2_interpolate::spline::CubicSpline;
use wasm_bindgen::prelude::*;

/// Validate that input arrays are non-empty and have matching lengths.
///
/// Returns an error if any of the arrays are empty or if x and y have
/// different lengths.
fn validate_xy(x: &[f64], y: &[f64]) -> Result<(), WasmError> {
    if x.is_empty() || y.is_empty() {
        return Err(WasmError::InvalidParameter(
            "Input arrays must not be empty".to_string(),
        ));
    }
    if x.len() != y.len() {
        return Err(WasmError::ShapeMismatch {
            expected: vec![x.len()],
            actual: vec![y.len()],
        });
    }
    Ok(())
}

/// Validate that x_new is non-empty.
fn validate_x_new(x_new: &[f64]) -> Result<(), WasmError> {
    if x_new.is_empty() {
        return Err(WasmError::InvalidParameter(
            "Evaluation points array must not be empty".to_string(),
        ));
    }
    Ok(())
}

/// Convert slices to ndarray Array1 views for use with scirs2-interpolate.
fn to_array_view(data: &[f64]) -> scirs2_core::ndarray::ArrayView1<'_, f64> {
    scirs2_core::ndarray::ArrayView1::from(data)
}

/// Perform 1D interpolation with a specified method.
///
/// Interpolates between the given (x, y) data points and evaluates the
/// interpolation at the new x coordinates.
///
/// # Arguments
///
/// * `x` - Known x-coordinates (must be sorted in ascending order)
/// * `y` - Known y-coordinates (same length as x)
/// * `x_new` - x-coordinates at which to evaluate the interpolation
/// * `kind` - Interpolation method: "linear", "nearest", or "quadratic" (uses cubic/Catmull-Rom)
///
/// # Returns
///
/// A `Vec<f64>` containing the interpolated values at each point in `x_new`.
///
/// # Errors
///
/// Returns an error if:
/// - Input arrays are empty or have mismatched lengths
/// - x values are not sorted in ascending order
/// - An unknown interpolation kind is specified
/// - Insufficient points for the requested method
#[wasm_bindgen]
pub fn interp1d(x: &[f64], y: &[f64], x_new: &[f64], kind: &str) -> Result<Vec<f64>, JsValue> {
    validate_xy(x, y)?;
    validate_x_new(x_new)?;

    let method = match kind {
        "linear" => InterpolationMethod::Linear,
        "nearest" => InterpolationMethod::Nearest,
        "quadratic" | "cubic" => InterpolationMethod::Cubic,
        other => {
            return Err(WasmError::InvalidParameter(format!(
                "Unknown interpolation kind '{}'. Use 'linear', 'nearest', or 'quadratic'",
                other
            ))
            .into());
        }
    };

    let x_view = to_array_view(x);
    let y_view = to_array_view(y);
    let x_new_view = to_array_view(x_new);

    let interp = Interp1d::new(
        &x_view,
        &y_view,
        method,
        scirs2_interpolate::interp1d::ExtrapolateMode::Nearest,
    )
    .map_err(|e| WasmError::ComputationError(format!("Failed to create interpolator: {}", e)))?;

    let result = interp.evaluate_array(&x_new_view).map_err(|e| {
        WasmError::ComputationError(format!("Interpolation evaluation failed: {}", e))
    })?;

    Ok(result.to_vec())
}

/// Perform natural cubic spline interpolation.
///
/// Constructs a natural cubic spline (zero second derivative at boundaries)
/// through the given data points and evaluates it at the specified x coordinates.
/// Provides C2 continuity (continuous second derivatives).
///
/// # Arguments
///
/// * `x` - Known x-coordinates (must be sorted in ascending order, at least 3 points)
/// * `y` - Known y-coordinates (same length as x)
/// * `x_new` - x-coordinates at which to evaluate the spline
///
/// # Returns
///
/// A `Vec<f64>` containing the interpolated values at each point in `x_new`.
///
/// # Errors
///
/// Returns an error if:
/// - Input arrays are empty or have mismatched lengths
/// - Fewer than 3 data points are provided
/// - x values are not sorted in ascending order
/// - Evaluation points are outside the data range
#[wasm_bindgen]
pub fn cubic_spline(x: &[f64], y: &[f64], x_new: &[f64]) -> Result<Vec<f64>, JsValue> {
    validate_xy(x, y)?;
    validate_x_new(x_new)?;

    if x.len() < 3 {
        return Err(WasmError::InvalidParameter(
            "Cubic spline requires at least 3 data points".to_string(),
        )
        .into());
    }

    let x_view = to_array_view(x);
    let y_view = to_array_view(y);
    let x_new_view = to_array_view(x_new);

    let spline = CubicSpline::new(&x_view, &y_view).map_err(|e| {
        WasmError::ComputationError(format!("Failed to create cubic spline: {}", e))
    })?;

    let result = spline.evaluate_array(&x_new_view).map_err(|e| {
        WasmError::ComputationError(format!("Cubic spline evaluation failed: {}", e))
    })?;

    Ok(result.to_vec())
}

/// Perform Lagrange polynomial interpolation.
///
/// Uses barycentric Lagrange interpolation, which is numerically more stable
/// than the naive Lagrange formula. The order of the polynomial equals
/// the number of data points minus one.
///
/// # Arguments
///
/// * `x` - Known x-coordinates (must have distinct values)
/// * `y` - Known y-coordinates (same length as x)
/// * `x_new` - x-coordinates at which to evaluate the polynomial
///
/// # Returns
///
/// A `Vec<f64>` containing the interpolated values at each point in `x_new`.
///
/// # Errors
///
/// Returns an error if:
/// - Input arrays are empty or have mismatched lengths
/// - Fewer than 2 data points are provided
/// - x values contain duplicates
#[wasm_bindgen]
pub fn lagrange(x: &[f64], y: &[f64], x_new: &[f64]) -> Result<Vec<f64>, JsValue> {
    validate_xy(x, y)?;
    validate_x_new(x_new)?;

    if x.len() < 2 {
        return Err(WasmError::InvalidParameter(
            "Lagrange interpolation requires at least 2 data points".to_string(),
        )
        .into());
    }

    let x_view = to_array_view(x);
    let y_view = to_array_view(y);
    let x_new_view = to_array_view(x_new);

    // Use barycentric interpolation with order = n-1 (full polynomial degree)
    let order = x.len() - 1;
    let interp = BarycentricInterpolator::new(&x_view, &y_view, order).map_err(|e| {
        WasmError::ComputationError(format!(
            "Failed to create Lagrange (barycentric) interpolator: {}",
            e
        ))
    })?;

    let result = interp.evaluate_array(&x_new_view).map_err(|e| {
        WasmError::ComputationError(format!("Lagrange interpolation evaluation failed: {}", e))
    })?;

    Ok(result.to_vec())
}

/// Perform PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) interpolation.
///
/// PCHIP produces a monotonicity-preserving interpolant: if the input data is
/// monotonically increasing (or decreasing) in an interval, the interpolation
/// will be too. The first derivatives are continuous, but the second derivatives
/// may have jumps at the knot points.
///
/// # Arguments
///
/// * `x` - Known x-coordinates (must be sorted in ascending order, at least 2 points)
/// * `y` - Known y-coordinates (same length as x)
/// * `x_new` - x-coordinates at which to evaluate the interpolation
///
/// # Returns
///
/// A `Vec<f64>` containing the interpolated values at each point in `x_new`.
///
/// # Errors
///
/// Returns an error if:
/// - Input arrays are empty or have mismatched lengths
/// - Fewer than 2 data points are provided
/// - x values are not sorted in ascending order
#[wasm_bindgen]
pub fn pchip(x: &[f64], y: &[f64], x_new: &[f64]) -> Result<Vec<f64>, JsValue> {
    validate_xy(x, y)?;
    validate_x_new(x_new)?;

    if x.len() < 2 {
        return Err(WasmError::InvalidParameter(
            "PCHIP interpolation requires at least 2 data points".to_string(),
        )
        .into());
    }

    let x_view = to_array_view(x);
    let y_view = to_array_view(y);
    let x_new_view = to_array_view(x_new);

    let result =
        scirs2_interpolate::interp1d::pchip_interpolate(&x_view, &y_view, &x_new_view, false)
            .map_err(|e| {
                WasmError::ComputationError(format!("PCHIP interpolation failed: {}", e))
            })?;

    Ok(result.to_vec())
}

/// Perform Akima interpolation.
///
/// Akima interpolation is a piecewise cubic method that is designed to be
/// robust against outliers. Unlike standard cubic splines, Akima interpolation
/// uses a local scheme for computing derivatives, making it less prone to
/// oscillations near outliers or abrupt changes in the data.
///
/// # Arguments
///
/// * `x` - Known x-coordinates (must be sorted in strictly ascending order, at least 5 points)
/// * `y` - Known y-coordinates (same length as x)
/// * `x_new` - x-coordinates at which to evaluate the interpolation
///
/// # Returns
///
/// A `Vec<f64>` containing the interpolated values at each point in `x_new`.
///
/// # Errors
///
/// Returns an error if:
/// - Input arrays are empty or have mismatched lengths
/// - Fewer than 5 data points are provided (Akima requires at least 5)
/// - x values are not sorted in strictly ascending order
/// - Evaluation points are outside the data range
#[wasm_bindgen]
pub fn akima(x: &[f64], y: &[f64], x_new: &[f64]) -> Result<Vec<f64>, JsValue> {
    validate_xy(x, y)?;
    validate_x_new(x_new)?;

    if x.len() < 5 {
        return Err(WasmError::InvalidParameter(
            "Akima interpolation requires at least 5 data points".to_string(),
        )
        .into());
    }

    let x_view = to_array_view(x);
    let y_view = to_array_view(y);
    let x_new_view = to_array_view(x_new);

    let spline = AkimaSpline::new(&x_view, &y_view).map_err(|e| {
        WasmError::ComputationError(format!("Failed to create Akima spline: {}", e))
    })?;

    let result = spline.evaluate_array(&x_new_view).map_err(|e| {
        WasmError::ComputationError(format!("Akima interpolation evaluation failed: {}", e))
    })?;

    Ok(result.to_vec())
}

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

    fn sample_x() -> Vec<f64> {
        vec![0.0, 1.0, 2.0, 3.0, 4.0]
    }

    fn sample_y() -> Vec<f64> {
        vec![0.0, 1.0, 4.0, 9.0, 16.0]
    }

    fn sample_x_new() -> Vec<f64> {
        vec![0.5, 1.5, 2.5, 3.5]
    }

    // -- interp1d tests --

    #[test]
    fn test_interp1d_linear() {
        let x = sample_x();
        let y = sample_y();
        let x_new = sample_x_new();

        let result = interp1d(&x, &y, &x_new, "linear").expect("linear interp1d should succeed");
        assert_eq!(result.len(), x_new.len());
        // Between (0,0) and (1,1): midpoint -> 0.5
        assert_relative_eq!(result[0], 0.5, epsilon = 1e-10);
        // Between (1,1) and (2,4): midpoint -> 2.5
        assert_relative_eq!(result[1], 2.5, epsilon = 1e-10);
    }

    #[test]
    fn test_interp1d_nearest() {
        let x = sample_x();
        let y = sample_y();
        let x_new = vec![0.3, 0.7, 2.6];

        let result = interp1d(&x, &y, &x_new, "nearest").expect("nearest interp1d should succeed");
        assert_eq!(result.len(), 3);
        // 0.3 is closer to 0.0 -> y=0.0
        assert_relative_eq!(result[0], 0.0, epsilon = 1e-10);
        // 0.7 is closer to 1.0 -> y=1.0
        assert_relative_eq!(result[1], 1.0, epsilon = 1e-10);
        // 2.6 is closer to 3.0 -> y=9.0
        assert_relative_eq!(result[2], 9.0, epsilon = 1e-10);
    }

    #[test]
    fn test_interp1d_quadratic() {
        let x = sample_x();
        let y = sample_y();
        let x_new = vec![1.0, 2.0, 3.0];

        let result =
            interp1d(&x, &y, &x_new, "quadratic").expect("quadratic interp1d should succeed");
        assert_eq!(result.len(), 3);
        // At known data points, result should be exact
        assert_relative_eq!(result[0], 1.0, epsilon = 1e-10);
        assert_relative_eq!(result[1], 4.0, epsilon = 1e-10);
        assert_relative_eq!(result[2], 9.0, epsilon = 1e-10);
    }

    #[test]
    fn test_interp1d_invalid_kind() {
        let x = sample_x();
        let y = sample_y();
        let x_new = sample_x_new();

        let result = interp1d(&x, &y, &x_new, "unknown");
        assert!(result.is_err());
    }

    #[test]
    fn test_interp1d_empty_input() {
        let result = interp1d(&[], &[], &[1.0], "linear");
        assert!(result.is_err());
    }

    #[test]
    fn test_interp1d_mismatched_lengths() {
        let result = interp1d(&[1.0, 2.0], &[1.0], &[1.5], "linear");
        assert!(result.is_err());
    }

    // -- cubic_spline tests --

    #[test]
    fn test_cubic_spline_at_data_points() {
        let x = sample_x();
        let y = sample_y();
        // Evaluate at the known data points
        let x_new = x.clone();

        let result = cubic_spline(&x, &y, &x_new).expect("cubic_spline should succeed");
        for (i, &val) in result.iter().enumerate() {
            assert_relative_eq!(val, y[i], epsilon = 1e-8);
        }
    }

    #[test]
    fn test_cubic_spline_between_points() {
        let x = sample_x();
        let y = sample_y();
        let x_new = sample_x_new();

        let result = cubic_spline(&x, &y, &x_new).expect("cubic_spline should succeed");
        assert_eq!(result.len(), x_new.len());
        // For y = x^2, cubic spline should approximate well
        for (i, &xv) in x_new.iter().enumerate() {
            let expected = xv * xv;
            assert_relative_eq!(result[i], expected, epsilon = 1.0);
        }
    }

    #[test]
    fn test_cubic_spline_too_few_points() {
        let result = cubic_spline(&[1.0, 2.0], &[1.0, 4.0], &[1.5]);
        assert!(result.is_err());
    }

    // -- lagrange tests --

    #[test]
    fn test_lagrange_at_data_points() {
        let x = vec![0.0, 1.0, 2.0, 3.0];
        let y = vec![0.0, 1.0, 8.0, 27.0]; // y = x^3
        let x_new = x.clone();

        let result = lagrange(&x, &y, &x_new).expect("lagrange should succeed");
        for (i, &val) in result.iter().enumerate() {
            assert_relative_eq!(val, y[i], epsilon = 1e-8);
        }
    }

    #[test]
    fn test_lagrange_polynomial() {
        // For 4 points, Lagrange gives exact cubic polynomial
        let x = vec![0.0, 1.0, 2.0, 3.0];
        let y = vec![0.0, 1.0, 8.0, 27.0]; // y = x^3

        let x_new = vec![0.5, 1.5, 2.5];
        let result = lagrange(&x, &y, &x_new).expect("lagrange should succeed");

        // x^3 at those points
        assert_relative_eq!(result[0], 0.125, epsilon = 1e-6);
        assert_relative_eq!(result[1], 3.375, epsilon = 1e-6);
        assert_relative_eq!(result[2], 15.625, epsilon = 1e-6);
    }

    #[test]
    fn test_lagrange_too_few_points() {
        let result = lagrange(&[1.0], &[1.0], &[1.5]);
        assert!(result.is_err());
    }

    // -- pchip tests --

    #[test]
    fn test_pchip_at_data_points() {
        let x = sample_x();
        let y = sample_y();

        // Evaluate near but not exactly at data points to avoid boundary issues
        let x_new = vec![0.01, 1.01, 2.01, 3.01, 3.99];

        let result = pchip(&x, &y, &x_new).expect("pchip should succeed");
        assert_eq!(result.len(), x_new.len());
        // Values should be close to f(x) = x^2 for these near-data-point evaluations
        for (i, &xv) in x_new.iter().enumerate() {
            let expected = xv * xv;
            assert_relative_eq!(result[i], expected, epsilon = 0.5);
        }
    }

    #[test]
    fn test_pchip_monotonicity() {
        // PCHIP preserves monotonicity of monotone data
        let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
        let y = vec![0.0, 1.0, 2.0, 3.0, 4.0]; // strictly increasing

        let x_new = vec![0.5, 1.5, 2.5, 3.5];
        let result = pchip(&x, &y, &x_new).expect("pchip should succeed");

        // Each result should be between the surrounding y-values
        for (i, &val) in result.iter().enumerate() {
            let lower = y[i];
            let upper = y[i + 1];
            assert!(
                val >= lower && val <= upper,
                "PCHIP violated monotonicity: {} not in [{}, {}]",
                val,
                lower,
                upper
            );
        }
    }

    #[test]
    fn test_pchip_too_few_points() {
        let result = pchip(&[1.0], &[1.0], &[1.5]);
        assert!(result.is_err());
    }

    // -- akima tests --

    #[test]
    fn test_akima_at_data_points() {
        let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
        let y = vec![0.0, 1.0, 4.0, 9.0, 16.0];
        let x_new = x.clone();

        let result = akima(&x, &y, &x_new).expect("akima should succeed");
        for (i, &val) in result.iter().enumerate() {
            assert_relative_eq!(val, y[i], epsilon = 1e-8);
        }
    }

    #[test]
    fn test_akima_between_points() {
        let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
        let y = vec![0.0, 1.0, 4.0, 9.0, 16.0];
        let x_new = vec![0.5, 1.5, 2.5, 3.5];

        let result = akima(&x, &y, &x_new).expect("akima should succeed");
        assert_eq!(result.len(), x_new.len());
        // For y = x^2, Akima should give reasonable approximations
        for (i, &xv) in x_new.iter().enumerate() {
            let expected = xv * xv;
            assert_relative_eq!(result[i], expected, epsilon = 1.0);
        }
    }

    #[test]
    fn test_akima_too_few_points() {
        let result = akima(&[1.0, 2.0, 3.0, 4.0], &[1.0, 4.0, 9.0, 16.0], &[2.5]);
        assert!(result.is_err());
    }

    #[test]
    fn test_akima_empty_x_new() {
        let result = akima(&[0.0, 1.0, 2.0, 3.0, 4.0], &[0.0, 1.0, 4.0, 9.0, 16.0], &[]);
        assert!(result.is_err());
    }
}