num-dual 0.13.6

Generalized (hyper) dual numbers for the calculation of exact (partial) derivatives
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
#[macro_export]
macro_rules! impl_dual_num {
    ($py_type_name:ty, $data_type:ty, $field_type:ty) => {
        impl From<$data_type> for $py_type_name {
            fn from(d: $data_type) -> Self {
                Self(d)
            }
        }

        impl From<$py_type_name> for $data_type {
            fn from(d: $py_type_name) -> Self {
                d.0
            }
        }

        #[pymethods]
        impl $py_type_name {
            #[staticmethod]
            /// (Hyper) dual number from real part, setting all other parts to zero.
            pub fn from_re(re: $field_type) -> Self {
                <$data_type>::from_re(re.into()).into()
            }

            #[getter]
            /// Real part.
            fn get_value(&self) -> $field_type {
                self.0.re.into()
            }

            #[inline]
            /// Reciprocal value of self.
            pub fn recip(&self) -> Self {
                self.0.recip().into()
            }

            #[inline]
            /// Power using 32-bit integer as exponent.
            pub fn powi(&self, n: i32) -> Self {
                self.0.powi(n).into()
            }

            #[inline]
            /// Power using 64-bin float as exponent.
            pub fn powf(&self, n: f64) -> Self {
                self.0.powf(n).into()
            }

            #[inline]
            /// Power using self (hyper) dual number as exponent.
            pub fn powd(&self, n: Self) -> Self {
                self.0.powd(n.0).into()
            }

            #[inline]
            /// Sqaure root.
            pub fn sqrt(&self) -> Self {
                self.0.sqrt().into()
            }

            #[inline]
            /// Cubic root.
            pub fn cbrt(&self) -> Self {
                self.0.cbrt().into()
            }

            #[inline]
            /// Calculate the exponential of (hyper) dual number.
            pub fn exp(&self) -> Self {
                self.0.exp().into()
            }

            #[inline]
            /// Calculate 2**x of (hyper) dual number x.
            pub fn exp2(&self) -> Self {
                self.0.exp2().into()
            }

            #[inline]
            /// Calculate exp(x) - 1.
            pub fn expm1(&self) -> Self {
                self.0.exp_m1().into()
            }

            #[inline]
            /// Calculate natural logarithm.
            pub fn log(&self) -> Self {
                self.0.ln().into()
            }

            #[inline]
            /// Calculate logarithm with given base.
            pub fn log_base(&self, base: f64) -> Self {
                self.0.log(base).into()
            }

            #[inline]
            /// Calculate logarithm with base 2.
            pub fn log2(&self) -> Self {
                self.0.log2().into()
            }

            #[inline]
            /// Calculate logarithm with base 10.
            pub fn log10(&self) -> Self {
                self.0.log10().into()
            }

            #[inline]
            /// Returns ln(1+n) (natural logarithm) more accurately than if the operations were performed separately.
            pub fn log1p(&self) -> Self {
                self.0.ln_1p().into()
            }

            #[inline]
            /// Hyperbolic sine function.
            pub fn sin(&self) -> Self {
                self.0.sin().into()
            }

            #[inline]
            /// Hyperbolic cosine function.
            pub fn cos(&self) -> Self {
                self.0.cos().into()
            }

            #[inline]
            /// Computes the tangent of a (hyper) dual number (in radians).
            pub fn tan(&self) -> Self {
                self.0.tan().into()
            }

            #[inline]
            /// Simultaneously computes the sine and cosine of the (hyper) dual number, x.
            pub fn sin_cos(&self) -> (Self, Self) {
                let (a, b) = self.0.sin_cos();
                (a.into(), b.into())
            }

            #[inline]
            /// Computes the arcsine of a (hyper) dual number.
            pub fn arcsin(&self) -> Self {
                self.0.asin().into()
            }

            #[inline]
            /// Computes the arccosine of a (hyper) dual number.
            pub fn arccos(&self) -> Self {
                self.0.acos().into()
            }

            #[inline]
            /// Computes the arctangent of a (hyper) dual number.
            pub fn arctan(&self) -> Self {
                self.0.atan().into()
            }

            #[inline]
            /// Computes the hyperbolic sine of a (hyper) dual number.
            pub fn sinh(&self) -> Self {
                self.0.sinh().into()
            }

            #[inline]
            /// Computes the hyperbolic cosine of a (hyper) dual number.
            pub fn cosh(&self) -> Self {
                self.0.cosh().into()
            }

            #[inline]
            /// Computes the hyperbolic tangent of a (hyper) dual number.
            pub fn tanh(&self) -> Self {
                self.0.tanh().into()
            }

            #[inline]
            /// Computes the inverse hyperbolic sine of a (hyper) dual number.
            pub fn arcsinh(&self) -> Self {
                self.0.asinh().into()
            }

            #[inline]
            /// Computes the inverse hyperbolic cosine of a (hyper) dual number.
            pub fn arccosh(&self) -> Self {
                self.0.acosh().into()
            }

            #[inline]
            /// Computes the inverse hyperbolic tangent of a (hyper) dual number.
            pub fn arctanh(&self) -> Self {
                self.0.atanh().into()
            }

            #[inline]
            /// Computes the first spherical bessel function.
            pub fn sph_j0(&self) -> Self {
                self.0.sph_j0().into()
            }
            #[inline]
            /// Computes the second spherical bessel function.
            pub fn sph_j1(&self) -> Self {
                self.0.sph_j1().into()
            }

            #[inline]
            /// Computes the third spherical bessel function.
            pub fn sph_j2(&self) -> Self {
                self.0.sph_j2().into()
            }

            #[inline]
            /// Fused multiply-add. Computes (self * a) + b with only one rounding error.
            fn mul_add(&self, a: Self, b: Self) -> Self {
                self.0.mul_add(a.0, b.0).into()
            }

            fn __add__<'py>(&self, rhs: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
                if let Ok(r) = rhs.extract::<f64>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() + r))?.into_any());
                };
                if let Ok(r) = rhs.extract::<Self>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() + r.0))?.into_any());
                };
                if let Ok(r) = rhs.extract::<PyReadonlyArrayDyn<f64>>() {
                    return Ok(PyArray::from_owned_object_array(
                        rhs.py(),
                        r.as_array()
                            .mapv(|ri| Py::new(rhs.py(), Self(self.0.clone() + ri)).unwrap()),
                    )
                    .into_any());
                }
                if let Ok(mut r) = rhs.extract::<PyReadwriteArrayDyn<Py<PyAny>>>() {
                    // check data type of first element
                    if r.as_array()
                        .get(0)
                        .unwrap()
                        .bind(rhs.py())
                        .is_instance_of::<Self>()
                    {
                        r.as_array_mut().map_inplace(|ri| {
                            *ri = Py::new(rhs.py(), Self(self.0.clone() + ri.extract::<Self>(rhs.py()).unwrap().0)).unwrap().into_any()
                        });
                        return Ok(r.as_any().clone());
                    } else {
                        return Err(PyErr::new::<PyTypeError, _>(format!(
                            "Operation with the provided object type is not implemented. Supported data types are 'float', 'int' and '{}'.",
                            stringify!($py_type_name)
                        )));
                    }
                }

                Err(PyErr::new::<PyTypeError, _>(format!(
                    "Addition of \nleft:  {}\nright: {:?}\nis not implemented!",
                    stringify!($py_type_name),
                    rhs.get_type()
                )))
            }

            fn __radd__(&self, lhs: f64) -> Self {
                (self.0.clone() + lhs).into()
            }

            fn __sub__<'py>(&self, rhs: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
                if let Ok(r) = rhs.extract::<f64>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() - r))?.into_any());
                };
                if let Ok(r) = rhs.extract::<Self>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() - r.0))?.into_any());
                };
                if let Ok(r) = rhs.extract::<PyReadonlyArrayDyn<f64>>() {
                    return Ok(PyArray::from_owned_object_array(
                        rhs.py(),
                        r.as_array()
                            .mapv(|ri| Py::new(rhs.py(), Self(self.0.clone() - ri)).unwrap()),
                    )
                    .into_any());
                }
                if let Ok(mut r) = rhs.extract::<PyReadwriteArrayDyn<Py<PyAny>>>() {
                    // check data type of first element
                    if r.as_array()
                        .get(0)
                        .unwrap()
                        .bind(rhs.py())
                        .is_instance_of::<Self>()
                    {
                        r.as_array_mut().map_inplace(|ri| {
                            *ri = Py::new(rhs.py(), Self(self.0.clone() - ri.extract::<Self>(rhs.py()).unwrap().0)).unwrap().into_any()
                        });
                        return Ok(r.as_any().clone());
                    } else {
                        return Err(PyErr::new::<PyTypeError, _>(format!(
                            "Operation with the provided object type is not implemented. Supported data types are 'float', 'int' and '{}'.",
                            stringify!($py_type_name)
                        )));
                    }
                }

                Err(PyErr::new::<PyTypeError, _>(format!(
                    "Subtraction of \nleft:  {}\nright: {:?}\nis not implemented!",
                    stringify!($py_type_name),
                    rhs.get_type()
                )))
            }

            fn __rsub__(&self, lhs: f64) -> Self {
                (-self.0.clone() + lhs).into()
            }

            fn __mul__<'py>(&self, rhs: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
                if let Ok(r) = rhs.extract::<f64>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() * r))?.into_any());
                };
                if let Ok(r) = rhs.extract::<Self>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() * r.0))?.into_any());
                };
                if let Ok(r) = rhs.extract::<PyReadonlyArrayDyn<f64>>() {
                    return Ok(PyArray::from_owned_object_array(
                        rhs.py(),
                        r.as_array()
                            .mapv(|ri| Py::new(rhs.py(), Self(self.0.clone() * ri)).unwrap()),
                    )
                    .into_any());
                }
                if let Ok(mut r) = rhs.extract::<PyReadwriteArrayDyn<Py<PyAny>>>() {
                    // check data type of first element
                    if r.as_array()
                        .get(0)
                        .unwrap()
                        .bind(rhs.py())
                        .is_instance_of::<Self>()
                    {
                        r.as_array_mut().map_inplace(|ri| {
                            *ri = Py::new(rhs.py(), Self(self.0.clone() * ri.extract::<Self>(rhs.py()).unwrap().0)).unwrap().into_any()
                        });
                        return Ok(r.as_any().clone());
                    } else {
                        return Err(PyErr::new::<PyTypeError, _>(format!(
                            "Operation with the provided object type is not implemented. Supported data types are 'float', 'int' and '{}'.",
                            stringify!($py_type_name)
                        )));
                    }
                }

                Err(PyErr::new::<PyTypeError, _>(format!(
                    "Multiplication of \nleft:  {}\nright: {:?}\nis not implemented!",
                    stringify!($py_type_name),
                    rhs.get_type()
                )))
            }

            fn __rmul__(&self, lhs: f64) -> Self {
                (self.0.clone() * lhs).into()
            }

            fn __truediv__<'py>(&self, rhs: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
                if let Ok(r) = rhs.extract::<f64>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() / r))?.into_any());
                };
                if let Ok(r) = rhs.extract::<Self>() {
                    return Ok(Bound::new(rhs.py(), Self(self.0.clone() / r.0))?.into_any());
                };
                if let Ok(r) = rhs.extract::<PyReadonlyArrayDyn<f64>>() {
                    return Ok(PyArray::from_owned_object_array(
                        rhs.py(),
                        r.as_array()
                            .mapv(|ri| Py::new(rhs.py(), Self(self.0.clone() / ri)).unwrap()),
                    )
                    .into_any());
                }
                if let Ok(mut r) = rhs.extract::<PyReadwriteArrayDyn<Py<PyAny>>>() {
                    // check data type of first element
                    if r.as_array()
                        .get(0)
                        .unwrap()
                        .bind(rhs.py())
                        .is_instance_of::<Self>()
                    {
                        r.as_array_mut().map_inplace(|ri| {
                            *ri = Py::new(rhs.py(), Self(self.0.clone() / ri.extract::<Self>(rhs.py()).unwrap().0)).unwrap().into_any()
                        });
                        return Ok(r.as_any().clone());
                    } else {
                        return Err(PyErr::new::<PyTypeError, _>(format!(
                            "Operation with the provided object type is not implemented. Supported data types are 'float', 'int' and '{}'.",
                            stringify!($py_type_name)
                        )));
                    }
                }

                Err(PyErr::new::<PyTypeError, _>(format!(
                    "Division of \nleft:  {}\nright: {:?}\nis not implemented!",
                    stringify!($py_type_name),
                    rhs.get_type()
                )))
            }

            fn __rtruediv__(&self, lhs: f64) -> Self {
                (self.0.recip() * lhs).into()
            }

            fn __pow__(&self, rhs: &Bound<'_, PyAny>, _mod: Option<u32>) -> PyResult<Self> {
                if let Ok(r) = rhs.extract::<i32>() {
                    return Ok(self.0.powi(r).into());
                };
                if let Ok(r) = rhs.extract::<f64>() {
                    return Ok(self.0.powf(r).into());
                };
                if let Ok(r) = rhs.extract::<Self>() {
                    return Ok(self.0.powd(r.0).into());
                };
                Err(PyErr::new::<PyTypeError, _>(format!("not implemented!")))
            }

            fn __richcmp__(
                &self,
                rhs: &Bound<'_, PyAny>,
                op: pyo3::class::basic::CompareOp,
            ) -> PyResult<bool> {
                use pyo3::class::basic::CompareOp;

                if let Ok(r) = rhs.extract::<f64>() {
                    match op {
                        CompareOp::Lt => Ok(self.0 < r),
                        CompareOp::Le => Ok(self.0 <= r),
                        CompareOp::Eq => Ok(self.0 == r),
                        CompareOp::Ne => Ok(self.0 != r),
                        CompareOp::Gt => Ok(self.0 > r),
                        CompareOp::Ge => Ok(self.0 >= r),
                    }
                } else if let Ok(r) = rhs.extract::<Self>() {
                    match op {
                        CompareOp::Lt => Ok(self.0 < r.0),
                        CompareOp::Le => Ok(self.0 <= r.0),
                        CompareOp::Eq => Ok(self.0 == r.0),
                        CompareOp::Ne => Ok(self.0 != r.0),
                        CompareOp::Gt => Ok(self.0 > r.0),
                        CompareOp::Ge => Ok(self.0 >= r.0),
                    }
                } else {
                    match op {
                        CompareOp::Eq => Ok(false),
                        CompareOp::Ne => Ok(true),
                        _ =>
                        Err(PyErr::new::<PyTypeError, _>(format!(
                            "unsupported operand types for comparison: '{}' and unsupported type '{:?}'. Supported data types are 'float' and '{}'.",
                            stringify!($py_type_name),
                            rhs.get_type(),
                            stringify!($py_type_name)
                        ))),
                    }
                }
            }

            fn __neg__(&self) -> PyResult<Self> {
                Ok((-self.0.clone()).into())
            }

            fn __repr__(&self) -> PyResult<String> {
                Ok(self.0.to_string())
            }
        }
    };
}