rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
//! WASM bindings for advanced mathematical operations - Refactored
//! 高度数学操作のWASMバインディング - リファクタリング版

use crate::wasm::common::{
    JsArrayBuilder, MemoryManager, WasmAnalyzer, WasmError, WasmMathOperation, WasmOperation,
    WasmParamValidator, WasmResult, WasmStatistical, WasmStats, WasmValidation, WasmVersion,
};
use crate::wasm::tensor::WasmTensor;
use js_sys::Array;
use wasm_bindgen::prelude::*;

/// WASM wrapper for advanced mathematical operations
#[wasm_bindgen]
pub struct WasmAdvancedMath;

#[wasm_bindgen]
impl WasmAdvancedMath {
    /// Create new advanced math instance
    #[wasm_bindgen(constructor)]
    pub fn new() -> WasmAdvancedMath {
        WasmAdvancedMath
    }

    /// Hyperbolic sine
    pub fn sinh(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.sinh()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Hyperbolic cosine
    pub fn cosh(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.cosh()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Hyperbolic tangent
    pub fn tanh(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.tanh()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Inverse sine (arcsine)
    pub fn asin(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.asin()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Inverse cosine (arccosine)
    pub fn acos(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.acos()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Inverse tangent (arctangent)
    pub fn atan(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.atan()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Two-argument arctangent
    pub fn atan2(&self, y: &WasmTensor, x: &WasmTensor) -> WasmResult<WasmTensor> {
        y.validate_non_empty()?;
        x.validate_shape_match(y)?;

        let mut result_buffer = MemoryManager::get_buffer(y.data().len());
        result_buffer.extend(
            y.data()
                .iter()
                .zip(x.data().iter())
                .map(|(&y_val, &x_val)| y_val.atan2(x_val)),
        );

        Ok(WasmTensor::new(result_buffer, y.shape()))
    }

    /// Error function (approximate)
    pub fn erf(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());

        result_buffer.extend(tensor.data().iter().map(|&x| {
            let a1 = 0.254829592;
            let a2 = -0.284496736;
            let a3 = 1.421413741;
            let a4 = -1.453152027;
            let a5 = 1.061405429;
            let p = 0.3275911;

            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            let x = x.abs();

            let t = 1.0 / (1.0 + p * x);
            let y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * (-x * x).exp();

            sign * y
        }));

        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Complementary error function
    pub fn erfc(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        let erf_result = self.erf(tensor)?;
        let mut result_buffer = MemoryManager::get_buffer(erf_result.data().len());
        result_buffer.extend(erf_result.data().iter().map(|&x| 1.0 - x));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Gamma function (approximate)
    pub fn gamma(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());

        result_buffer.extend(tensor.data().iter().map(|&x| {
            if x <= 0.0 {
                f32::NAN
            } else if x < 1.0 {
                self.gamma_approx(x + 1.0) / x
            } else {
                self.gamma_approx(x)
            }
        }));

        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Log gamma function
    pub fn lgamma(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        let gamma_result = self.gamma(tensor)?;
        let mut result_buffer = MemoryManager::get_buffer(gamma_result.data().len());
        result_buffer.extend(gamma_result.data().iter().map(|&x| x.ln()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Clamp values between min and max
    pub fn clamp(&self, tensor: &WasmTensor, min_val: f32, max_val: f32) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        if min_val > max_val {
            return Err(WasmError::invalid_param(
                "range",
                format!("{}..{}", min_val, max_val),
                "min must be <= max",
            ));
        }

        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.clamp(min_val, max_val)));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Sign function
    pub fn sign(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| {
            if x > 0.0 {
                1.0
            } else if x < 0.0 {
                -1.0
            } else {
                0.0
            }
        }));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Linear interpolation between two tensors
    pub fn lerp(
        &self,
        start: &WasmTensor,
        end: &WasmTensor,
        weight: f32,
    ) -> WasmResult<WasmTensor> {
        start.validate_non_empty()?;
        start.validate_shape_match(end)?;

        let mut result_buffer = MemoryManager::get_buffer(start.data().len());
        result_buffer.extend(
            start
                .data()
                .iter()
                .zip(end.data().iter())
                .map(|(&s, &e)| s + weight * (e - s)),
        );

        Ok(WasmTensor::new(result_buffer, start.shape()))
    }

    /// Power function with scalar exponent
    pub fn pow(&self, base: &WasmTensor, exponent: f32) -> WasmResult<WasmTensor> {
        base.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(base.data().len());
        result_buffer.extend(base.data().iter().map(|&x| x.powf(exponent)));
        Ok(WasmTensor::new(result_buffer, base.shape()))
    }

    /// Element-wise power
    pub fn pow_tensor(&self, base: &WasmTensor, exponent: &WasmTensor) -> WasmResult<WasmTensor> {
        base.validate_non_empty()?;
        base.validate_shape_match(exponent)?;

        let mut result_buffer = MemoryManager::get_buffer(base.data().len());
        result_buffer.extend(
            base.data()
                .iter()
                .zip(exponent.data().iter())
                .map(|(&b, &e)| b.powf(e)),
        );

        Ok(WasmTensor::new(result_buffer, base.shape()))
    }

    /// Round to nearest integer
    pub fn round(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.round()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Floor function
    pub fn floor(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.floor()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Ceiling function
    pub fn ceil(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.ceil()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Truncate to integer
    pub fn trunc(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(tensor.data().iter().map(|&x| x.trunc()));
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Check if values are finite
    pub fn is_finite(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(
            tensor
                .data()
                .iter()
                .map(|&x| if x.is_finite() { 1.0 } else { 0.0 }),
        );
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Check if values are infinite
    pub fn is_infinite(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(
            tensor
                .data()
                .iter()
                .map(|&x| if x.is_infinite() { 1.0 } else { 0.0 }),
        );
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Check if values are NaN
    pub fn is_nan(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        tensor.validate_non_empty()?;
        let mut result_buffer = MemoryManager::get_buffer(tensor.data().len());
        result_buffer.extend(
            tensor
                .data()
                .iter()
                .map(|&x| if x.is_nan() { 1.0 } else { 0.0 }),
        );
        Ok(WasmTensor::new(result_buffer, tensor.shape()))
    }

    /// Stirling's approximation for gamma function
    fn gamma_approx(&self, x: f32) -> f32 {
        if x < 1.0 {
            return f32::NAN;
        }

        let two_pi = 2.0 * std::f32::consts::PI;
        let e = std::f32::consts::E;

        (two_pi / x).sqrt() * (x / e).powf(x)
    }
}

/// Advanced statistical functions for web applications
#[wasm_bindgen]
pub struct WasmStatisticalFunctions;

#[wasm_bindgen]
impl WasmStatisticalFunctions {
    /// Create new statistical functions instance
    #[wasm_bindgen(constructor)]
    pub fn new() -> WasmStatisticalFunctions {
        WasmStatisticalFunctions
    }

    /// Calculate correlation coefficient between two tensors
    pub fn correlation(&self, x: &WasmTensor, y: &WasmTensor) -> WasmResult<f32> {
        x.validate_non_empty()?;
        x.validate_shape_match(y)?;

        let x_data = x.data();
        let y_data = y.data();

        let x_mean = WasmStats::mean(&x_data);
        let y_mean = WasmStats::mean(&y_data);

        let numerator: f32 = x_data
            .iter()
            .zip(y_data.iter())
            .map(|(&xi, &yi)| (xi - x_mean) * (yi - y_mean))
            .sum();

        let x_var: f32 = x_data.iter().map(|&xi| (xi - x_mean).powi(2)).sum();
        let y_var: f32 = y_data.iter().map(|&yi| (yi - y_mean).powi(2)).sum();

        let denominator = (x_var * y_var).sqrt();

        if denominator == 0.0 {
            Ok(0.0)
        } else {
            Ok(numerator / denominator)
        }
    }

    /// Calculate covariance between two tensors
    pub fn covariance(&self, x: &WasmTensor, y: &WasmTensor) -> WasmResult<f32> {
        x.validate_non_empty()?;
        x.validate_shape_match(y)?;

        let x_data = x.data();
        let y_data = y.data();

        let n = x_data.len() as f32;
        let x_mean = WasmStats::mean(&x_data);
        let y_mean = WasmStats::mean(&y_data);

        let covariance: f32 = x_data
            .iter()
            .zip(y_data.iter())
            .map(|(&xi, &yi)| (xi - x_mean) * (yi - y_mean))
            .sum::<f32>()
            / (n - 1.0);

        Ok(covariance)
    }

    /// Calculate percentile
    pub fn percentile(&self, tensor: &WasmTensor, percentile: f32) -> WasmResult<f32> {
        tensor.validate_non_empty()?;
        WasmParamValidator::validate_percentage_range(percentile, "percentile")?;

        let mut data = tensor.data().clone();
        data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let index = ((percentile / 100.0) * (data.len() - 1) as f32).round() as usize;
        Ok(data[index.min(data.len() - 1)])
    }

    /// Calculate quantiles
    pub fn quantiles(&self, tensor: &WasmTensor, q: &[f32]) -> WasmResult<Array> {
        tensor.validate_non_empty()?;
        if q.is_empty() {
            return Err(WasmError::empty_tensor());
        }

        let mut data = tensor.data().clone();
        data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let mut builder = JsArrayBuilder::with_capacity(q.len());
        for &quantile in q {
            WasmParamValidator::validate_percentage_range(quantile, "quantile")?;
            let index = ((quantile / 100.0) * (data.len() - 1) as f32).round() as usize;
            let value = data[index.min(data.len() - 1)];
            builder = builder.push_f32(value);
        }

        Ok(builder.build())
    }
}

/// Version information
#[wasm_bindgen]
pub fn wasm_advanced_math_version() -> String {
    WasmVersion::module_version("Advanced Math")
}

// Trait implementations for WasmAdvancedMath
impl WasmOperation for WasmAdvancedMath {
    fn name(&self) -> String {
        "AdvancedMath".to_string()
    }
}

impl WasmMathOperation for WasmAdvancedMath {
    fn apply_unary(&self, tensor: &WasmTensor) -> WasmResult<WasmTensor> {
        // Default to sinh operation for unary application
        self.sinh(tensor)
    }
    fn supports_operation(&self, operation: &str) -> bool {
        matches!(
            operation,
            "sinh"
                | "cosh"
                | "tanh"
                | "asin"
                | "acos"
                | "atan"
                | "atan2"
                | "erf"
                | "erfc"
                | "gamma"
                | "lgamma"
                | "clamp"
                | "sign"
                | "lerp"
                | "pow"
                | "pow_tensor"
                | "round"
                | "floor"
                | "ceil"
                | "trunc"
                | "is_finite"
                | "is_infinite"
                | "is_nan"
        )
    }

    fn operation_complexity(&self, operation: &str) -> u32 {
        match operation {
            "sign" | "round" | "floor" | "ceil" | "trunc" | "is_finite" | "is_infinite"
            | "is_nan" => 1,
            "sinh" | "cosh" | "tanh" | "asin" | "acos" | "atan" | "clamp" | "lerp" | "pow" => 2,
            "atan2" | "pow_tensor" => 3,
            "erf" | "erfc" | "gamma" | "lgamma" => 4,
            _ => 1,
        }
    }
}

// Trait implementations for WasmStatisticalFunctions
impl WasmOperation for WasmStatisticalFunctions {
    fn name(&self) -> String {
        "StatisticalFunctions".to_string()
    }
}

impl WasmAnalyzer for WasmStatisticalFunctions {
    fn analyze(&self, tensor: &WasmTensor) -> WasmResult<String> {
        tensor.validate_non_empty()?;
        let data = tensor.data();

        let mean = WasmStats::mean(&data);
        let std_dev = WasmStats::std_dev(&data, Some(mean));
        let min = WasmStats::min(&data);
        let max = WasmStats::max(&data);

        Ok(format!(
            "{{\"type\":\"statistical_summary\",\"mean\":{:.6},\"std\":{:.6},\"min\":{:.6},\"max\":{:.6},\"count\":{}}}",
            mean, std_dev, min, max, data.len()
        ))
    }

    fn analysis_type(&self) -> &'static str {
        "statistical_functions"
    }
}

impl WasmStatistical for WasmStatisticalFunctions {
    fn calculate_stats(&self, tensor: &WasmTensor) -> WasmResult<String> {
        self.analyze(tensor)
    }
    fn statistical_summary(&self, tensor: &WasmTensor) -> WasmResult<String> {
        self.analyze(tensor)
    }

    fn supports_statistical_operation(&self, operation: &str) -> bool {
        matches!(
            operation,
            "correlation" | "covariance" | "percentile" | "quantiles"
        )
    }
}