scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
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
//! Dual number implementation for automatic differentiation
//!
//! Dual numbers are the foundation of forward-mode automatic differentiation.
//! A dual number has the form a + b*ε where ε² = 0.

use crate::common::IntegrateFloat;
use scirs2_core::ndarray::{Array1, ArrayView1};
use std::fmt;
use std::ops::{Add, Div, Mul, Neg, Sub};

/// Dual number for forward-mode automatic differentiation
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Dual<F: IntegrateFloat> {
    /// The value part
    pub val: F,
    /// The derivative part
    pub der: F,
}

impl<F: IntegrateFloat> Dual<F> {
    /// Create a new dual number
    pub fn new(val: F, der: F) -> Self {
        Dual { val, der }
    }

    /// Create a constant dual number (zero derivative)
    pub fn constant(val: F) -> Self {
        Dual {
            val,
            der: F::zero(),
        }
    }

    /// Create a variable dual number (unit derivative)
    pub fn variable(val: F) -> Self {
        Dual { val, der: F::one() }
    }

    /// Extract the value
    pub fn value(&self) -> F {
        self.val
    }

    /// Extract the derivative
    pub fn derivative(&self) -> F {
        self.der
    }

    /// Compute sin(x)
    pub fn sin(&self) -> Self {
        Dual {
            val: self.val.sin(),
            der: self.der * self.val.cos(),
        }
    }

    /// Compute cos(x)
    pub fn cos(&self) -> Self {
        Dual {
            val: self.val.cos(),
            der: -self.der * self.val.sin(),
        }
    }

    /// Compute exp(x)
    pub fn exp(&self) -> Self {
        let exp_val = self.val.exp();
        Dual {
            val: exp_val,
            der: self.der * exp_val,
        }
    }

    /// Compute ln(x)
    pub fn ln(&self) -> Self {
        Dual {
            val: self.val.ln(),
            der: self.der / self.val,
        }
    }

    /// Compute sqrt(x)
    pub fn sqrt(&self) -> Self {
        let sqrt_val = self.val.sqrt();
        Dual {
            val: sqrt_val,
            der: self.der / (F::from(2.0).expect("Failed to convert constant to float") * sqrt_val),
        }
    }

    /// Compute x^y for constant y
    pub fn powf(&self, n: F) -> Self {
        Dual {
            val: self.val.powf(n),
            der: self.der * n * self.val.powf(n - F::one()),
        }
    }

    /// Compute abs(x)
    pub fn abs(&self) -> Self {
        if self.val >= F::zero() {
            *self
        } else {
            -*self
        }
    }

    /// Compute tan(x)
    pub fn tan(&self) -> Self {
        let cos_val = self.val.cos();
        Dual {
            val: self.val.tan(),
            der: self.der / (cos_val * cos_val),
        }
    }

    /// Compute tanh(x)
    pub fn tanh(&self) -> Self {
        let tanh_val = self.val.tanh();
        Dual {
            val: tanh_val,
            der: self.der * (F::one() - tanh_val * tanh_val),
        }
    }

    /// Compute sinh(x)
    pub fn sinh(&self) -> Self {
        Dual {
            val: self.val.sinh(),
            der: self.der * self.val.cosh(),
        }
    }

    /// Compute cosh(x)
    pub fn cosh(&self) -> Self {
        Dual {
            val: self.val.cosh(),
            der: self.der * self.val.sinh(),
        }
    }

    /// Compute atan(x)
    pub fn atan(&self) -> Self {
        Dual {
            val: self.val.atan(),
            der: self.der / (F::one() + self.val * self.val),
        }
    }

    /// Compute asin(x)
    pub fn asin(&self) -> Self {
        Dual {
            val: self.val.asin(),
            der: self.der / (F::one() - self.val * self.val).sqrt(),
        }
    }

    /// Compute acos(x)
    pub fn acos(&self) -> Self {
        Dual {
            val: self.val.acos(),
            der: -self.der / (F::one() - self.val * self.val).sqrt(),
        }
    }

    /// Compute atan2(y, x)
    pub fn atan2(&self, x: Self) -> Self {
        let r2 = self.val * self.val + x.val * x.val;
        Dual {
            val: self.val.atan2(x.val),
            der: (self.der * x.val - self.val * x.der) / r2,
        }
    }

    /// Compute max(self, other)
    pub fn max(&self, other: Self) -> Self {
        if self.val > other.val {
            *self
        } else if self.val < other.val {
            other
        } else {
            // When values are equal, average the derivatives
            Dual {
                val: self.val,
                der: (self.der + other.der)
                    / F::from(2.0).expect("Failed to convert constant to float"),
            }
        }
    }

    /// Compute min(self, other)
    pub fn min(&self, other: Self) -> Self {
        if self.val < other.val {
            *self
        } else if self.val > other.val {
            other
        } else {
            // When values are equal, average the derivatives
            Dual {
                val: self.val,
                der: (self.der + other.der)
                    / F::from(2.0).expect("Failed to convert constant to float"),
            }
        }
    }

    /// Compute x^y where both x and y are dual numbers
    pub fn pow(&self, other: Self) -> Self {
        let val = self.val.powf(other.val);
        let der = if self.val > F::zero() {
            val * (other.der * self.val.ln() + other.val * self.der / self.val)
        } else {
            F::zero() // Handle edge case
        };
        Dual { val, der }
    }
}

// Arithmetic operations for dual numbers
impl<F: IntegrateFloat> Add for Dual<F> {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Dual {
            val: self.val + other.val,
            der: self.der + other.der,
        }
    }
}

impl<F: IntegrateFloat> Sub for Dual<F> {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Dual {
            val: self.val - other.val,
            der: self.der - other.der,
        }
    }
}

impl<F: IntegrateFloat> Mul for Dual<F> {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Dual {
            val: self.val * other.val,
            der: self.der * other.val + self.val * other.der,
        }
    }
}

impl<F: IntegrateFloat> Div for Dual<F> {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        let inv_val = F::one() / other.val;
        Dual {
            val: self.val * inv_val,
            der: (self.der * other.val - self.val * other.der) * inv_val * inv_val,
        }
    }
}

impl<F: IntegrateFloat> Neg for Dual<F> {
    type Output = Self;

    fn neg(self) -> Self {
        Dual {
            val: -self.val,
            der: -self.der,
        }
    }
}

// Operations with scalars
impl<F: IntegrateFloat> Add<F> for Dual<F> {
    type Output = Self;

    fn add(self, scalar: F) -> Self {
        Dual {
            val: self.val + scalar,
            der: self.der,
        }
    }
}

impl<F: IntegrateFloat> Sub<F> for Dual<F> {
    type Output = Self;

    fn sub(self, scalar: F) -> Self {
        Dual {
            val: self.val - scalar,
            der: self.der,
        }
    }
}

impl<F: IntegrateFloat> Mul<F> for Dual<F> {
    type Output = Self;

    fn mul(self, scalar: F) -> Self {
        Dual {
            val: self.val * scalar,
            der: self.der * scalar,
        }
    }
}

impl<F: IntegrateFloat> Div<F> for Dual<F> {
    type Output = Self;

    fn div(self, scalar: F) -> Self {
        Dual {
            val: self.val / scalar,
            der: self.der / scalar,
        }
    }
}

impl<F: IntegrateFloat> fmt::Display for Dual<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} + {}ε", self.val, self.der)
    }
}

/// Vector of dual numbers for multi-dimensional forward AD
pub struct DualVector<F: IntegrateFloat> {
    /// Values
    pub values: Array1<F>,
    /// Jacobian matrix (derivatives)
    pub jacobian: Array1<Array1<F>>,
}

impl<F: IntegrateFloat> DualVector<F> {
    /// Create a new dual vector
    pub fn new(values: Array1<F>, jacobian: Array1<Array1<F>>) -> Self {
        DualVector { values, jacobian }
    }

    /// Create from a regular vector with specified active variable
    pub fn from_vector(_values: ArrayView1<F>, activevar: usize) -> Self {
        let n = _values.len();
        let mut jacobian = Array1::from_elem(n, Array1::zeros(n));

        // Set the derivative of the active variable to 1
        jacobian[activevar][activevar] = F::one();

        DualVector {
            values: _values.to_owned(),
            jacobian,
        }
    }

    /// Create a constant dual vector (zero derivatives)
    pub fn constant(values: Array1<F>) -> Self {
        let n = values.len();
        let jacobian = Array1::from_elem(n, Array1::zeros(n));
        DualVector { values, jacobian }
    }

    /// Get the dimension
    pub fn dim(&self) -> usize {
        self.values.len()
    }

    /// Extract values
    pub fn values(&self) -> &Array1<F> {
        &self.values
    }

    /// Extract Jacobian
    pub fn jacobian(&self) -> &Array1<Array1<F>> {
        &self.jacobian
    }
}

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

    #[test]
    fn test_dual_arithmetic() {
        let x = Dual::new(2.0, 1.0);
        let y = Dual::new(3.0, 0.0);

        // Test addition
        let sum = x + y;
        assert_eq!(sum.val, 5.0);
        assert_eq!(sum.der, 1.0);

        // Test multiplication
        let prod = x * y;
        assert_eq!(prod.val, 6.0);
        assert_eq!(prod.der, 3.0); // d/dx(x*3) = 3

        // Test chain rule: d/dx(x^2) = 2x
        let square = x * x;
        assert_eq!(square.val, 4.0);
        assert_eq!(square.der, 4.0);
    }

    #[test]
    fn test_dual_functions() {
        let x = Dual::variable(0.0);

        // Test sin/cos derivatives
        let sin_x = x.sin();
        assert!((sin_x.val - 0.0_f64).abs() < 1e-10_f64);
        assert!((sin_x.der - 1.0_f64).abs() < 1e-10_f64); // cos(0) = 1

        let cos_x = x.cos();
        assert!((cos_x.val - 1.0).abs() < 1e-10);
        assert!((cos_x.der - 0.0).abs() < 1e-10); // -sin(0) = 0

        // Test exp derivative
        let exp_x = x.exp();
        assert!((exp_x.val - 1.0).abs() < 1e-10);
        assert!((exp_x.der - 1.0).abs() < 1e-10); // exp(0) = 1
    }
}