numr 0.5.2

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
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
564
565
566
//! Special mathematical functions trait for scientific computing.
//!
//! Defines the `SpecialFunctions` trait required by probability distributions,
//! statistics, and scientific applications. These are critical for
//! solvr::stats to implement distributions like normal, gamma, beta, etc.
//!
//! # Functions Provided
//!
//! ## Error Functions (for normal distribution)
//! - `erf` - Error function
//! - `erfc` - Complementary error function (1 - erf(x))
//! - `erfinv` - Inverse error function
//!
//! ## Gamma Functions (for gamma, chi2, t, F distributions)
//! - `gamma` - Gamma function Γ(x)
//! - `lgamma` - Log-gamma function ln(Γ(x)) (numerically stable)
//! - `digamma` - Digamma function ψ(x) = Γ'(x)/Γ(x)
//!
//! ## Beta Functions (for beta distribution)
//! - `beta` - Beta function B(a,b) = Γ(a)Γ(b)/Γ(a+b)
//! - `betainc` - Regularized incomplete beta function I_x(a,b)
//!
//! ## Incomplete Gamma (for gamma/chi2 CDF)
//! - `gammainc` - Lower regularized incomplete gamma P(a,x)
//! - `gammaincc` - Upper regularized incomplete gamma Q(a,x) = 1 - P(a,x)
//!
//! ## Bessel Functions
//! - `bessel_j0`, `bessel_j1` - First kind J₀, J₁
//! - `bessel_y0`, `bessel_y1` - Second kind Y₀, Y₁
//! - `bessel_i0`, `bessel_i1` - Modified first kind I₀, I₁
//! - `bessel_k0`, `bessel_k1` - Modified second kind K₀, K₁
//!
//! ## Elliptic Integrals
//! - `ellipk` - Complete elliptic integral of first kind K(m)
//! - `ellipe` - Complete elliptic integral of second kind E(m)
//!
//! ## Hypergeometric Functions
//! - `hyp2f1` - Gauss hypergeometric function ₂F₁(a, b; c; z)
//! - `hyp1f1` - Confluent hypergeometric function ₁F₁(a; b; z)
//!
//! ## Airy Functions
//! - `airy_ai` - Airy function of first kind Ai(x)
//! - `airy_bi` - Airy function of second kind Bi(x)
//!
//! ## Legendre Functions and Spherical Harmonics
//! - `legendre_p` - Legendre polynomial P_n(x)
//! - `legendre_p_assoc` - Associated Legendre function P_n^m(x)
//! - `sph_harm` - Real spherical harmonic Y_n^m(θ, φ)
//!
//! ## Fresnel Integrals
//! - `fresnel_s` - Fresnel sine integral S(x)
//! - `fresnel_c` - Fresnel cosine integral C(x)
//!
//! # Algorithm Sources
//!
//! Implementations follow well-established numerical algorithms:
//! - Cody's rational approximation for erf/erfc
//! - Lanczos approximation for gamma/lgamma
//! - Continued fraction expansion for incomplete gamma/beta
//! - Newton-Raphson iteration for inverse functions
//! - Numerical Recipes polynomial approximations for Bessel functions
//! - AGM method for elliptic integrals
//! - Power series with transformations for hypergeometric functions
//! - Power series and asymptotic expansions for Airy functions
//! - Three-term recurrence for Legendre polynomials

use crate::error::{Error, Result};
use crate::runtime::Runtime;
use crate::tensor::Tensor;

// ============================================================================
// Special Functions Trait
// ============================================================================

/// Special mathematical functions for scientific computing.
///
/// All backends must implement these functions to enable solvr probability
/// distributions and statistical functions.
///
/// # Implementation Notes
///
/// - Functions operate element-wise on tensors
/// - Input validation (domain checks) should return appropriate errors
/// - Numerical stability is critical - use established algorithms
/// - GPU implementations can use the same algorithms as CPU
pub trait SpecialFunctions<R: Runtime> {
    // ========================================================================
    // Error Functions
    // ========================================================================

    /// Compute the error function element-wise.
    ///
    /// ```text
    /// erf(x) = (2/√π) ∫₀ˣ e^(-t²) dt
    /// ```
    ///
    /// # Properties
    /// - Domain: all real numbers
    /// - Range: (-1, 1)
    /// - erf(0) = 0
    /// - erf(∞) = 1, erf(-∞) = -1
    /// - erf(-x) = -erf(x) (odd function)
    fn erf(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::erf",
        })
    }

    /// Compute the complementary error function element-wise.
    ///
    /// ```text
    /// erfc(x) = 1 - erf(x) = (2/√π) ∫ₓ^∞ e^(-t²) dt
    /// ```
    ///
    /// For large x, erf(x) ≈ 1 and computing 1 - erf(x) loses precision.
    /// erfc(x) computes the small tail directly, maintaining accuracy.
    fn erfc(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::erfc",
        })
    }

    /// Compute the inverse error function element-wise.
    ///
    /// Returns y such that erf(y) = x.
    ///
    /// # Properties
    /// - Domain: (-1, 1)
    /// - Range: all real numbers
    /// - erfinv(0) = 0
    fn erfinv(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::erfinv",
        })
    }

    // ========================================================================
    // Gamma Functions
    // ========================================================================

    /// Compute the gamma function element-wise.
    ///
    /// ```text
    /// Γ(x) = ∫₀^∞ t^(x-1) e^(-t) dt
    /// ```
    ///
    /// # Properties
    /// - Γ(n) = (n-1)! for positive integers
    /// - Γ(1) = 1, Γ(1/2) = √π
    /// - Has poles at non-positive integers (returns NaN/Inf)
    fn gamma(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::gamma",
        })
    }

    /// Compute the log-gamma function element-wise.
    ///
    /// ```text
    /// lgamma(x) = ln(|Γ(x)|)
    /// ```
    ///
    /// Γ(x) grows extremely fast (Γ(171) overflows F64).
    /// lgamma computes the logarithm directly without overflow.
    fn lgamma(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::lgamma",
        })
    }

    /// Compute the digamma (psi) function element-wise.
    ///
    /// ```text
    /// ψ(x) = d/dx ln(Γ(x)) = Γ'(x)/Γ(x)
    /// ```
    fn digamma(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::digamma",
        })
    }

    // ========================================================================
    // Beta Functions
    // ========================================================================

    /// Compute the beta function element-wise.
    ///
    /// ```text
    /// B(a, b) = Γ(a)Γ(b)/Γ(a+b)
    /// ```
    fn beta(&self, a: &Tensor<R>, b: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, b);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::beta",
        })
    }

    /// Compute the regularized incomplete beta function element-wise.
    ///
    /// ```text
    /// I_x(a,b) = B(x;a,b)/B(a,b) = (1/B(a,b)) ∫₀ˣ t^(a-1)(1-t)^(b-1) dt
    /// ```
    fn betainc(&self, a: &Tensor<R>, b: &Tensor<R>, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, b, x);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::betainc",
        })
    }

    // ========================================================================
    // Incomplete Gamma Functions
    // ========================================================================

    /// Compute the lower regularized incomplete gamma function.
    ///
    /// ```text
    /// P(a, x) = γ(a,x)/Γ(a) = (1/Γ(a)) ∫₀ˣ t^(a-1) e^(-t) dt
    /// ```
    fn gammainc(&self, a: &Tensor<R>, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, x);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::gammainc",
        })
    }

    /// Compute the upper regularized incomplete gamma function.
    ///
    /// ```text
    /// Q(a, x) = 1 - P(a, x)
    /// ```
    fn gammaincc(&self, a: &Tensor<R>, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, x);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::gammaincc",
        })
    }

    /// Compute the inverse of the lower regularized incomplete gamma function.
    ///
    /// Returns x such that P(a, x) = p.
    ///
    /// # Properties
    /// - Domain: p in [0, 1], a > 0
    /// - Range: x >= 0
    /// - gammaincinv(a, 0) = 0
    /// - gammaincinv(a, 1) = ∞
    fn gammaincinv(&self, a: &Tensor<R>, p: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, p);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::gammaincinv",
        })
    }

    /// Compute the inverse of the regularized incomplete beta function.
    ///
    /// Returns x such that I_x(a, b) = p.
    ///
    /// # Properties
    /// - Domain: p in [0, 1], a > 0, b > 0
    /// - Range: x in [0, 1]
    /// - betaincinv(a, b, 0) = 0
    /// - betaincinv(a, b, 1) = 1
    fn betaincinv(&self, a: &Tensor<R>, b: &Tensor<R>, p: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, b, p);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::betaincinv",
        })
    }

    // ========================================================================
    // Bessel Functions
    // ========================================================================

    /// Compute Bessel function of the first kind, order 0.
    ///
    /// J₀(0) = 1, even function, oscillates with decreasing amplitude.
    fn bessel_j0(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_j0",
        })
    }

    /// Compute Bessel function of the first kind, order 1.
    ///
    /// J₁(0) = 0, odd function, oscillates with decreasing amplitude.
    fn bessel_j1(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_j1",
        })
    }

    /// Compute Bessel function of the second kind, order 0 (Neumann function).
    ///
    /// Y₀(x) → -∞ as x → 0⁺. Domain: x > 0.
    fn bessel_y0(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_y0",
        })
    }

    /// Compute Bessel function of the second kind, order 1 (Neumann function).
    ///
    /// Y₁(x) → -∞ as x → 0⁺. Domain: x > 0.
    fn bessel_y1(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_y1",
        })
    }

    /// Compute modified Bessel function of the first kind, order 0.
    ///
    /// I₀(0) = 1, even function, grows exponentially.
    fn bessel_i0(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_i0",
        })
    }

    /// Compute modified Bessel function of the first kind, order 1.
    ///
    /// I₁(0) = 0, odd function, grows exponentially.
    fn bessel_i1(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_i1",
        })
    }

    /// Compute modified Bessel function of the second kind, order 0.
    ///
    /// K₀(x) → ∞ as x → 0⁺. Domain: x > 0. Decays exponentially.
    fn bessel_k0(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_k0",
        })
    }

    /// Compute modified Bessel function of the second kind, order 1.
    ///
    /// K₁(x) → ∞ as x → 0⁺. Domain: x > 0. Decays exponentially.
    fn bessel_k1(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::bessel_k1",
        })
    }

    // ========================================================================
    // Elliptic Integrals
    // ========================================================================

    /// Compute the complete elliptic integral of the first kind K(m).
    ///
    /// ```text
    /// K(m) = ∫₀^(π/2) dθ / √(1 - m·sin²θ)
    /// ```
    ///
    /// # Properties
    /// - Domain: m ∈ [0, 1)
    /// - K(0) = π/2
    /// - K(m) → ∞ as m → 1
    /// - Uses parameter convention m = k², where k is the modulus
    fn ellipk(&self, m: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = m;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::ellipk",
        })
    }

    /// Compute the complete elliptic integral of the second kind E(m).
    ///
    /// ```text
    /// E(m) = ∫₀^(π/2) √(1 - m·sin²θ) dθ
    /// ```
    ///
    /// # Properties
    /// - Domain: m ∈ [0, 1]
    /// - E(0) = π/2
    /// - E(1) = 1
    fn ellipe(&self, m: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = m;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::ellipe",
        })
    }

    // ========================================================================
    // Hypergeometric Functions
    // ========================================================================

    /// Compute the Gauss hypergeometric function ₂F₁(a, b; c; z).
    ///
    /// ```text
    /// ₂F₁(a, b; c; z) = Σ_{n=0}^∞ (a)_n (b)_n / ((c)_n n!) z^n
    /// ```
    ///
    /// # Properties
    /// - Converges for |z| < 1
    /// - ₂F₁(a, b; c; 0) = 1
    ///
    /// # Arguments
    /// - a, b, c: Scalar parameters
    /// - z: Input tensor
    fn hyp2f1(&self, a: f64, b: f64, c: f64, z: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, b, c, z);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::hyp2f1",
        })
    }

    /// Compute the confluent hypergeometric function ₁F₁(a; b; z) (Kummer's M).
    ///
    /// ```text
    /// ₁F₁(a; b; z) = M(a, b, z) = Σ_{n=0}^∞ (a)_n / ((b)_n n!) z^n
    /// ```
    ///
    /// # Properties
    /// - ₁F₁(a; b; 0) = 1
    /// - ₁F₁(0; b; z) = 1
    /// - Entire function in z
    fn hyp1f1(&self, a: f64, b: f64, z: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (a, b, z);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::hyp1f1",
        })
    }

    // ========================================================================
    // Airy Functions
    // ========================================================================

    /// Compute the Airy function of the first kind Ai(x).
    ///
    /// ```text
    /// Ai(x) is the solution of y'' - xy = 0 that decays as x → +∞
    /// ```
    ///
    /// # Properties
    /// - Ai(x) → 0 as x → +∞ (exponentially)
    /// - Ai(x) oscillates for x < 0
    /// - Ai(0) ≈ 0.3550280538878172
    fn airy_ai(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::airy_ai",
        })
    }

    /// Compute the Airy function of the second kind Bi(x).
    ///
    /// ```text
    /// Bi(x) is the solution of y'' - xy = 0 that grows as x → +∞
    /// ```
    ///
    /// # Properties
    /// - Bi(x) → +∞ as x → +∞ (exponentially)
    /// - Bi(x) oscillates for x < 0
    /// - Bi(0) ≈ 0.6149266274460007
    fn airy_bi(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::airy_bi",
        })
    }

    // ========================================================================
    // Legendre Functions
    // ========================================================================

    /// Compute the Legendre polynomial P_n(x).
    ///
    /// # Properties
    /// - Domain: x ∈ [-1, 1]
    /// - P_n(1) = 1
    /// - P_n(-1) = (-1)^n
    /// - P_0(x) = 1, P_1(x) = x
    fn legendre_p(&self, n: i32, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (n, x);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::legendre_p",
        })
    }

    /// Compute the associated Legendre function P_n^m(x).
    ///
    /// Uses Condon-Shortley phase convention (factor of (-1)^m).
    ///
    /// # Properties
    /// - Domain: x ∈ [-1, 1], 0 ≤ m ≤ n
    /// - P_n^0(x) = P_n(x)
    fn legendre_p_assoc(&self, n: i32, m: i32, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (n, m, x);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::legendre_p_assoc",
        })
    }

    /// Compute the real spherical harmonic Y_n^m(θ, φ).
    ///
    /// Returns the real-valued spherical harmonic with Schmidt semi-normalization.
    /// - m > 0: Y_n^m ∝ P_n^m(cos θ) cos(mφ)
    /// - m = 0: Y_n^0 ∝ P_n(cos θ)
    /// - m < 0: Y_n^m ∝ P_n^|m|(cos θ) sin(|m|φ)
    ///
    /// # Arguments
    /// - n: degree (n ≥ 0)
    /// - m: order (-n ≤ m ≤ n)
    /// - theta: polar angle θ ∈ [0, π] (colatitude)
    /// - phi: azimuthal angle φ ∈ [0, 2π)
    fn sph_harm(&self, n: i32, m: i32, theta: &Tensor<R>, phi: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = (n, m, theta, phi);
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::sph_harm",
        })
    }

    // ========================================================================
    // Fresnel Integrals
    // ========================================================================

    /// Compute the Fresnel sine integral S(x).
    ///
    /// ```text
    /// S(x) = ∫₀ˣ sin(π t²/2) dt
    /// ```
    ///
    /// # Properties
    /// - S(0) = 0
    /// - S(∞) = 0.5
    /// - S(-x) = -S(x) (odd function)
    fn fresnel_s(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::fresnel_s",
        })
    }

    /// Compute the Fresnel cosine integral C(x).
    ///
    /// ```text
    /// C(x) = ∫₀ˣ cos(π t²/2) dt
    /// ```
    ///
    /// # Properties
    /// - C(0) = 0
    /// - C(∞) = 0.5
    /// - C(-x) = -C(x) (odd function)
    fn fresnel_c(&self, x: &Tensor<R>) -> Result<Tensor<R>> {
        let _ = x;
        Err(Error::NotImplemented {
            feature: "SpecialFunctions::fresnel_c",
        })
    }
}