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
//! N-dimensional array operations for WASM

use crate::error::WasmError;
use crate::utils::{js_array_to_vec_f64, parse_shape, typed_array_to_vec_f64};
use scirs2_core::ndarray::{Array1, ArrayD};
use wasm_bindgen::prelude::*;

/// A wrapper around ndarray for JavaScript interop
#[wasm_bindgen]
pub struct WasmArray {
    data: ArrayD<f64>,
}

// Internal implementation for accessing data
impl WasmArray {
    pub(crate) fn from_array(data: ArrayD<f64>) -> Self {
        Self { data }
    }

    pub(crate) fn data(&self) -> &ArrayD<f64> {
        &self.data
    }
}

#[wasm_bindgen]
impl WasmArray {
    /// Create a 1D array from a JavaScript array or typed array
    #[wasm_bindgen(constructor)]
    pub fn new(data: &JsValue) -> Result<WasmArray, JsValue> {
        let vec = if data.is_array() {
            let array = js_sys::Array::from(data);
            js_array_to_vec_f64(&array)?
        } else {
            typed_array_to_vec_f64(data)?
        };

        let array = Array1::from_vec(vec).into_dyn();
        Ok(WasmArray { data: array })
    }

    /// Create an array with a specific shape from flat data
    #[wasm_bindgen]
    pub fn from_shape(shape: &JsValue, data: &JsValue) -> Result<WasmArray, JsValue> {
        let shape_vec = parse_shape(shape)?;
        let data_vec = if data.is_array() {
            let array = js_sys::Array::from(data);
            js_array_to_vec_f64(&array)?
        } else {
            typed_array_to_vec_f64(data)?
        };

        let total_size: usize = shape_vec.iter().product();
        if data_vec.len() != total_size {
            return Err(WasmError::ShapeMismatch {
                expected: vec![total_size],
                actual: vec![data_vec.len()],
            }
            .into());
        }

        let array = ArrayD::from_shape_vec(shape_vec, data_vec)
            .map_err(|e: ndarray::ShapeError| WasmError::InvalidDimensions(e.to_string()))?;

        Ok(WasmArray { data: array })
    }

    /// Create an array of zeros with the given shape
    #[wasm_bindgen]
    pub fn zeros(shape: &JsValue) -> Result<WasmArray, JsValue> {
        let shape_vec = parse_shape(shape)?;
        let array = ArrayD::zeros(shape_vec);
        Ok(WasmArray { data: array })
    }

    /// Create an array of ones with the given shape
    #[wasm_bindgen]
    pub fn ones(shape: &JsValue) -> Result<WasmArray, JsValue> {
        let shape_vec = parse_shape(shape)?;
        let array = ArrayD::ones(shape_vec);
        Ok(WasmArray { data: array })
    }

    /// Create an array filled with a constant value
    #[wasm_bindgen]
    pub fn full(shape: &JsValue, value: f64) -> Result<WasmArray, JsValue> {
        let shape_vec = parse_shape(shape)?;
        let array = ArrayD::from_elem(shape_vec, value);
        Ok(WasmArray { data: array })
    }

    /// Create an evenly spaced array (like numpy.linspace)
    #[wasm_bindgen]
    pub fn linspace(start: f64, end: f64, num: usize) -> Result<WasmArray, JsValue> {
        if num == 0 {
            return Err(WasmError::InvalidParameter("num must be > 0".to_string()).into());
        }

        let step = if num > 1 {
            (end - start) / (num - 1) as f64
        } else {
            0.0
        };

        let vec: Vec<f64> = (0..num).map(|i| start + i as f64 * step).collect();

        let array = Array1::from_vec(vec).into_dyn();
        Ok(WasmArray { data: array })
    }

    /// Create an array with evenly spaced values (like numpy.arange)
    #[wasm_bindgen]
    pub fn arange(start: f64, end: f64, step: f64) -> Result<WasmArray, JsValue> {
        if step == 0.0 {
            return Err(WasmError::InvalidParameter("step cannot be zero".to_string()).into());
        }

        if (end - start).signum() != step.signum() {
            return Err(WasmError::InvalidParameter(
                "step direction does not match range".to_string(),
            )
            .into());
        }

        let num = ((end - start) / step).abs().ceil() as usize;
        let vec: Vec<f64> = (0..num).map(|i| start + i as f64 * step).collect();

        let array = Array1::from_vec(vec).into_dyn();
        Ok(WasmArray { data: array })
    }

    /// Get the shape of the array
    #[wasm_bindgen]
    pub fn shape(&self) -> js_sys::Array {
        let shape = self.data.shape();
        let array = js_sys::Array::new_with_length(shape.len() as u32);

        for (i, &dim) in shape.iter().enumerate() {
            array.set(i as u32, JsValue::from_f64(dim as f64));
        }

        array
    }

    /// Get the number of dimensions
    #[wasm_bindgen]
    pub fn ndim(&self) -> usize {
        self.data.ndim()
    }

    /// Get the total number of elements
    #[wasm_bindgen]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Check if the array is empty
    #[wasm_bindgen]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Convert to a flat JavaScript Float64Array
    #[wasm_bindgen]
    pub fn to_array(&self) -> js_sys::Float64Array {
        let vec: Vec<f64> = self.data.iter().copied().collect();
        let array = js_sys::Float64Array::new_with_length(vec.len() as u32);
        array.copy_from(&vec);
        array
    }

    /// Convert to a JavaScript array (nested for multi-dimensional arrays)
    #[wasm_bindgen]
    pub fn to_nested_array(&self) -> JsValue {
        // For simplicity, return flat array with shape info
        // In production, implement proper nested array conversion
        let vec: Vec<f64> = self.data.iter().copied().collect();
        serde_wasm_bindgen::to_value(&vec).unwrap_or(JsValue::NULL)
    }

    /// Get a value at the specified index (flat indexing)
    #[wasm_bindgen]
    pub fn get(&self, index: usize) -> Result<f64, JsValue> {
        self.data
            .as_slice()
            .and_then(|s| s.get(index).copied())
            .ok_or_else(|| {
                WasmError::IndexOutOfBounds(format!(
                    "Index {} out of bounds for array of length {}",
                    index,
                    self.len()
                ))
                .into()
            })
    }

    /// Set a value at the specified index (flat indexing)
    #[wasm_bindgen]
    pub fn set(&mut self, index: usize, value: f64) -> Result<(), JsValue> {
        self.data
            .as_slice_mut()
            .and_then(|s| s.get_mut(index))
            .map(|v| *v = value)
            .ok_or_else(|| {
                WasmError::IndexOutOfBounds(format!(
                    "Index {} out of bounds for array of length {}",
                    index,
                    self.len()
                ))
                .into()
            })
    }

    /// Reshape the array
    #[wasm_bindgen]
    pub fn reshape(&self, new_shape: &JsValue) -> Result<WasmArray, JsValue> {
        let shape_vec = parse_shape(new_shape)?;
        let total_size: usize = shape_vec.iter().product();

        if total_size != self.len() {
            return Err(WasmError::ShapeMismatch {
                expected: vec![self.len()],
                actual: vec![total_size],
            }
            .into());
        }

        let vec: Vec<f64> = self.data.iter().copied().collect();
        let array = ArrayD::from_shape_vec(shape_vec, vec)
            .map_err(|e: ndarray::ShapeError| WasmError::InvalidDimensions(e.to_string()))?;

        Ok(WasmArray { data: array })
    }

    /// Transpose the array (2D only for now)
    #[wasm_bindgen]
    pub fn transpose(&self) -> Result<WasmArray, JsValue> {
        if self.ndim() != 2 {
            return Err(WasmError::InvalidDimensions(
                "Transpose is only supported for 2D arrays".to_string(),
            )
            .into());
        }

        let transposed = self
            .data
            .clone()
            .into_dimensionality::<ndarray::Ix2>()
            .map_err(|e: ndarray::ShapeError| WasmError::ComputationError(e.to_string()))?
            .t()
            .to_owned()
            .into_dyn();

        Ok(WasmArray { data: transposed })
    }

    /// Clone the array
    #[allow(clippy::should_implement_trait)]
    #[wasm_bindgen]
    pub fn clone(&self) -> WasmArray {
        WasmArray {
            data: self.data.clone(),
        }
    }
}

/// Add two arrays element-wise
#[wasm_bindgen]
pub fn add(a: &WasmArray, b: &WasmArray) -> Result<WasmArray, JsValue> {
    if a.data().shape() != b.data().shape() {
        return Err(WasmError::ShapeMismatch {
            expected: a.data().shape().to_vec(),
            actual: b.data().shape().to_vec(),
        }
        .into());
    }

    Ok(WasmArray {
        data: a.data() + b.data(),
    })
}

/// Subtract two arrays element-wise
#[wasm_bindgen]
pub fn subtract(a: &WasmArray, b: &WasmArray) -> Result<WasmArray, JsValue> {
    if a.data().shape() != b.data().shape() {
        return Err(WasmError::ShapeMismatch {
            expected: a.data().shape().to_vec(),
            actual: b.data().shape().to_vec(),
        }
        .into());
    }

    Ok(WasmArray {
        data: a.data() - b.data(),
    })
}

/// Multiply two arrays element-wise
#[wasm_bindgen]
pub fn multiply(a: &WasmArray, b: &WasmArray) -> Result<WasmArray, JsValue> {
    if a.data().shape() != b.data().shape() {
        return Err(WasmError::ShapeMismatch {
            expected: a.data().shape().to_vec(),
            actual: b.data().shape().to_vec(),
        }
        .into());
    }

    Ok(WasmArray {
        data: a.data() * b.data(),
    })
}

/// Divide two arrays element-wise
#[wasm_bindgen]
pub fn divide(a: &WasmArray, b: &WasmArray) -> Result<WasmArray, JsValue> {
    if a.data().shape() != b.data().shape() {
        return Err(WasmError::ShapeMismatch {
            expected: a.data().shape().to_vec(),
            actual: b.data().shape().to_vec(),
        }
        .into());
    }

    Ok(WasmArray {
        data: a.data() / b.data(),
    })
}

/// Compute dot product (1D) or matrix multiplication (2D)
#[wasm_bindgen]
pub fn dot(a: &WasmArray, b: &WasmArray) -> Result<WasmArray, JsValue> {
    match (a.ndim(), b.ndim()) {
        (1, 1) => {
            // 1D dot product
            let a1 = a
                .data()
                .clone()
                .into_dimensionality::<ndarray::Ix1>()
                .map_err(|e: ndarray::ShapeError| WasmError::ComputationError(e.to_string()))?;
            let b1 = b
                .data()
                .clone()
                .into_dimensionality::<ndarray::Ix1>()
                .map_err(|e: ndarray::ShapeError| WasmError::ComputationError(e.to_string()))?;

            let result = a1.dot(&b1);
            let array = ArrayD::from_elem(vec![], result);
            Ok(WasmArray { data: array })
        }
        (2, 2) => {
            // Matrix multiplication
            let a2 = a
                .data()
                .clone()
                .into_dimensionality::<ndarray::Ix2>()
                .map_err(|e: ndarray::ShapeError| WasmError::ComputationError(e.to_string()))?;
            let b2 = b
                .data()
                .clone()
                .into_dimensionality::<ndarray::Ix2>()
                .map_err(|e: ndarray::ShapeError| WasmError::ComputationError(e.to_string()))?;

            if a2.ncols() != b2.nrows() {
                return Err(WasmError::ShapeMismatch {
                    expected: vec![a2.nrows(), b2.ncols()],
                    actual: vec![a2.nrows(), a2.ncols(), b2.nrows(), b2.ncols()],
                }
                .into());
            }

            let result = a2.dot(&b2).into_dyn();
            Ok(WasmArray { data: result })
        }
        _ => Err(WasmError::InvalidDimensions(
            "dot only supports 1D-1D or 2D-2D arrays".to_string(),
        )
        .into()),
    }
}

/// Sum all elements in the array
#[wasm_bindgen]
pub fn sum(arr: &WasmArray) -> f64 {
    arr.data().sum()
}

/// Compute the mean of all elements
#[wasm_bindgen]
pub fn mean(arr: &WasmArray) -> f64 {
    if arr.is_empty() {
        return f64::NAN;
    }
    arr.data().sum() / arr.len() as f64
}

/// Find the minimum value
#[wasm_bindgen]
pub fn min(arr: &WasmArray) -> f64 {
    arr.data().iter().copied().fold(f64::INFINITY, f64::min)
}

/// Find the maximum value
#[wasm_bindgen]
pub fn max(arr: &WasmArray) -> f64 {
    arr.data().iter().copied().fold(f64::NEG_INFINITY, f64::max)
}