scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
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
567
568
569
570
571
572
573
//! Dual numbers for forward-mode automatic differentiation
//!
//! This module implements dual numbers, which are used for forward-mode automatic
//! differentiation. Dual numbers extend real numbers with an infinitesimal part
//! that tracks derivatives.

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

/// Dual number for forward-mode automatic differentiation
///
/// A dual number is of the form a + b*ε where ε² = 0.
/// This allows us to compute both function values and derivatives simultaneously.
#[derive(Debug, Clone, Copy)]
pub struct Dual {
    /// Real part (function value)
    value: f64,
    /// Dual part (derivative)
    derivative: f64,
}

impl Dual {
    /// Create a new dual number
    pub fn new(value: f64, derivative: f64) -> Self {
        Self { value, derivative }
    }

    /// Create a dual number representing a constant (derivative = 0)
    pub fn constant(value: f64) -> Self {
        Self {
            value,
            derivative: 0.0,
        }
    }

    /// Create a dual number representing a variable (derivative = 1)
    pub fn variable(value: f64) -> Self {
        Self {
            value,
            derivative: 1.0,
        }
    }

    /// Get the real part (function value)
    pub fn value(self) -> f64 {
        self.value
    }

    /// Get the dual part (derivative)
    pub fn derivative(self) -> f64 {
        self.derivative
    }

    /// Compute sine of dual number
    pub fn sin(self) -> Self {
        Self {
            value: self.value.sin(),
            derivative: self.derivative * self.value.cos(),
        }
    }

    /// Compute cosine of dual number
    pub fn cos(self) -> Self {
        Self {
            value: self.value.cos(),
            derivative: -self.derivative * self.value.sin(),
        }
    }

    /// Compute tangent of dual number
    pub fn tan(self) -> Self {
        let cos_val = self.value.cos();
        Self {
            value: self.value.tan(),
            derivative: self.derivative / (cos_val * cos_val),
        }
    }

    /// Compute exponential of dual number
    pub fn exp(self) -> Self {
        let exp_val = self.value.exp();
        Self {
            value: exp_val,
            derivative: self.derivative * exp_val,
        }
    }

    /// Compute natural logarithm of dual number
    pub fn ln(self) -> Self {
        Self {
            value: self.value.ln(),
            derivative: self.derivative / self.value,
        }
    }

    /// Compute power of dual number (self^n)
    pub fn powi(self, n: i32) -> Self {
        let n_f64 = n as f64;
        Self {
            value: self.value.powi(n),
            derivative: self.derivative * n_f64 * self.value.powi(n - 1),
        }
    }

    /// Compute power of dual number (self^p) where p is real
    pub fn powf(self, p: f64) -> Self {
        Self {
            value: self.value.powf(p),
            derivative: self.derivative * p * self.value.powf(p - 1.0),
        }
    }

    /// Compute square root of dual number
    pub fn sqrt(self) -> Self {
        let sqrt_val = self.value.sqrt();
        Self {
            value: sqrt_val,
            derivative: self.derivative / (2.0 * sqrt_val),
        }
    }

    /// Compute absolute value of dual number
    pub fn abs(self) -> Self {
        Self {
            value: self.value.abs(),
            derivative: if self.value >= 0.0 {
                self.derivative
            } else {
                -self.derivative
            },
        }
    }

    /// Compute maximum of two dual numbers
    pub fn max(self, other: Self) -> Self {
        if self.value >= other.value {
            self
        } else {
            other
        }
    }

    /// Compute minimum of two dual numbers
    pub fn min(self, other: Self) -> Self {
        if self.value <= other.value {
            self
        } else {
            other
        }
    }
}

// Arithmetic operations for dual numbers

impl Add for Dual {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            value: self.value + other.value,
            derivative: self.derivative + other.derivative,
        }
    }
}

impl Add<f64> for Dual {
    type Output = Self;

    fn add(self, scalar: f64) -> Self {
        Self {
            value: self.value + scalar,
            derivative: self.derivative,
        }
    }
}

impl Add<Dual> for f64 {
    type Output = Dual;

    fn add(self, dual: Dual) -> Dual {
        dual + self
    }
}

impl Sub for Dual {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self {
            value: self.value - other.value,
            derivative: self.derivative - other.derivative,
        }
    }
}

impl Sub<f64> for Dual {
    type Output = Self;

    fn sub(self, scalar: f64) -> Self {
        Self {
            value: self.value - scalar,
            derivative: self.derivative,
        }
    }
}

impl Sub<Dual> for f64 {
    type Output = Dual;

    fn sub(self, dual: Dual) -> Dual {
        Dual {
            value: self - dual.value,
            derivative: -dual.derivative,
        }
    }
}

impl Mul for Dual {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Self {
            value: self.value * other.value,
            derivative: self.derivative * other.value + self.value * other.derivative,
        }
    }
}

impl Mul<f64> for Dual {
    type Output = Self;

    fn mul(self, scalar: f64) -> Self {
        Self {
            value: self.value * scalar,
            derivative: self.derivative * scalar,
        }
    }
}

impl Mul<Dual> for f64 {
    type Output = Dual;

    fn mul(self, dual: Dual) -> Dual {
        dual * self
    }
}

impl Div for Dual {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        let denom = other.value * other.value;

        // Protect against division by zero
        let value = if other.value == 0.0 {
            if self.value == 0.0 {
                f64::NAN
            }
            // 0/0 is undefined
            else if self.value > 0.0 {
                f64::INFINITY
            } else {
                f64::NEG_INFINITY
            }
        } else {
            self.value / other.value
        };

        let derivative = if denom == 0.0 {
            // Handle derivative at division by zero
            if other.value == 0.0 && self.derivative == 0.0 && other.derivative == 0.0 {
                f64::NAN
            } else {
                f64::INFINITY
            }
        } else {
            (self.derivative * other.value - self.value * other.derivative) / denom
        };

        Self { value, derivative }
    }
}

impl Div<f64> for Dual {
    type Output = Self;

    fn div(self, scalar: f64) -> Self {
        if scalar == 0.0 {
            // Division by zero
            Self {
                value: if self.value == 0.0 {
                    f64::NAN
                } else if self.value > 0.0 {
                    f64::INFINITY
                } else {
                    f64::NEG_INFINITY
                },
                derivative: if self.derivative == 0.0 {
                    f64::NAN
                } else {
                    f64::INFINITY
                },
            }
        } else {
            Self {
                value: self.value / scalar,
                derivative: self.derivative / scalar,
            }
        }
    }
}

impl Div<Dual> for f64 {
    type Output = Dual;

    fn div(self, dual: Dual) -> Dual {
        Dual::constant(self) / dual
    }
}

impl Neg for Dual {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            value: -self.value,
            derivative: -self.derivative,
        }
    }
}

// Conversion traits
impl From<f64> for Dual {
    fn from(value: f64) -> Self {
        Self::constant(value)
    }
}

impl From<Dual> for f64 {
    fn from(dual: Dual) -> Self {
        dual.value
    }
}

// Partial ordering for optimization algorithms
impl PartialEq for Dual {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl PartialOrd for Dual {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.value.partial_cmp(&other.value)
    }
}

/// Trait for dual number operations
pub trait DualNumber: Clone + Copy {
    /// Get the value part
    fn value(self) -> f64;

    /// Get the derivative part
    fn derivative(self) -> f64;

    /// Create from value and derivative
    fn new(value: f64, derivative: f64) -> Self;

    /// Create constant (derivative = 0)
    fn constant(value: f64) -> Self;

    /// Create variable (derivative = 1)
    fn variable(value: f64) -> Self;
}

impl DualNumber for Dual {
    fn value(self) -> f64 {
        self.value
    }

    fn derivative(self) -> f64 {
        self.derivative
    }

    fn new(value: f64, derivative: f64) -> Self {
        Self::new(value, derivative)
    }

    fn constant(value: f64) -> Self {
        Self::constant(value)
    }

    fn variable(value: f64) -> Self {
        Self::variable(value)
    }
}

/// Multi-dimensional dual number for computing gradients
#[derive(Debug, Clone)]
pub struct MultiDual {
    /// Function value
    value: f64,
    /// Partial derivatives (gradient components)
    derivatives: Array1<f64>,
}

impl MultiDual {
    /// Create a new multi-dimensional dual number
    pub fn new(value: f64, derivatives: Array1<f64>) -> Self {
        Self { value, derivatives }
    }

    /// Create a constant multi-dual (all derivatives = 0)
    pub fn constant(value: f64, nvars: usize) -> Self {
        Self {
            value,
            derivatives: Array1::zeros(nvars),
        }
    }

    /// Create a variable multi-dual (one derivative = 1, others = 0)
    pub fn variable(value: f64, var_index: usize, nvars: usize) -> Self {
        let mut derivatives = Array1::zeros(nvars);
        derivatives[var_index] = 1.0;
        Self { value, derivatives }
    }

    /// Get the function value
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Get the gradient
    pub fn gradient(&self) -> &Array1<f64> {
        &self.derivatives
    }

    /// Get a specific partial derivative
    pub fn partial(&self, index: usize) -> f64 {
        self.derivatives[index]
    }
}

// Arithmetic operations for MultiDual
impl Add for MultiDual {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            value: self.value + other.value,
            derivatives: &self.derivatives + &other.derivatives,
        }
    }
}

impl Mul for MultiDual {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Self {
            value: self.value * other.value,
            derivatives: &self.derivatives * other.value + &other.derivatives * self.value,
        }
    }
}

impl Mul<f64> for MultiDual {
    type Output = Self;

    fn mul(self, scalar: f64) -> Self {
        Self {
            value: self.value * scalar,
            derivatives: &self.derivatives * scalar,
        }
    }
}

/// Create an array of dual numbers for gradient computation
#[allow(dead_code)]
pub fn create_dual_variables(x: &ArrayView1<f64>) -> Vec<Dual> {
    x.iter().map(|&xi| Dual::variable(xi)).collect()
}

/// Create multi-dual variables for a given point
#[allow(dead_code)]
pub fn create_multi_dual_variables(x: &ArrayView1<f64>) -> Vec<MultiDual> {
    let n = x.len();
    x.iter()
        .enumerate()
        .map(|(i, &xi)| MultiDual::variable(xi, i, n))
        .collect()
}

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

    #[test]
    fn test_dual_arithmetic() {
        let a = Dual::new(2.0, 1.0);
        let b = Dual::new(3.0, 0.5);

        // Test addition
        let sum = a + b;
        assert_abs_diff_eq!(sum.value(), 5.0, epsilon = 1e-10);
        assert_abs_diff_eq!(sum.derivative(), 1.5, epsilon = 1e-10);

        // Test multiplication
        let product = a * b;
        assert_abs_diff_eq!(product.value(), 6.0, epsilon = 1e-10);
        assert_abs_diff_eq!(product.derivative(), 4.0, epsilon = 1e-10); // 1*3 + 2*0.5

        // Test division
        let quotient = a / b;
        assert_abs_diff_eq!(quotient.value(), 2.0 / 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(
            quotient.derivative(),
            (1.0 * 3.0 - 2.0 * 0.5) / (3.0 * 3.0),
            epsilon = 1e-10
        );
    }

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

        // Test exp(x) at x=1
        let exp_x = x.exp();
        assert_abs_diff_eq!(exp_x.value(), std::f64::consts::E, epsilon = 1e-10);
        assert_abs_diff_eq!(exp_x.derivative(), std::f64::consts::E, epsilon = 1e-10);

        // Test sin(x) at x=0
        let x0 = Dual::variable(0.0);
        let sin_x = x0.sin();
        assert_abs_diff_eq!(sin_x.value(), 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(sin_x.derivative(), 1.0, epsilon = 1e-10); // cos(0) = 1

        // Test x² at x=3
        let x3 = Dual::variable(3.0);
        let x_squared = x3.powi(2);
        assert_abs_diff_eq!(x_squared.value(), 9.0, epsilon = 1e-10);
        assert_abs_diff_eq!(x_squared.derivative(), 6.0, epsilon = 1e-10); // 2*3
    }

    #[test]
    fn test_multi_dual() {
        let x = MultiDual::variable(2.0, 0, 2);
        let y = MultiDual::variable(3.0, 1, 2);

        // Test x * y
        let product = x * y;
        assert_abs_diff_eq!(product.value(), 6.0, epsilon = 1e-10);
        assert_abs_diff_eq!(product.partial(0), 3.0, epsilon = 1e-10); // ∂(xy)/∂x = y
        assert_abs_diff_eq!(product.partial(1), 2.0, epsilon = 1e-10); // ∂(xy)/∂y = x
    }

    #[test]
    fn test_create_dual_variables() {
        let x = Array1::from_vec(vec![1.0, 2.0, 3.0]);
        let duals = create_dual_variables(&x.view());

        assert_eq!(duals.len(), 3);
        assert_abs_diff_eq!(duals[0].value(), 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(duals[1].value(), 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(duals[2].value(), 3.0, epsilon = 1e-10);

        // All should have derivative = 1 (variables)
        for dual in &duals {
            assert_abs_diff_eq!(dual.derivative(), 1.0, epsilon = 1e-10);
        }
    }
}