num_dual/lib.rs
1//! Generalized, recursive, scalar and vector (hyper) dual numbers for the automatic and exact calculation of (partial) derivatives.
2//!
3//! # Example
4//! This example defines a generic scalar and a generic vector function that can be called using any (hyper-) dual number and automatically calculates derivatives.
5//! ```
6//! use num_dual::*;
7//! use nalgebra::SVector;
8//!
9//! fn foo<D: DualNum<f64>>(x: D) -> D {
10//! x.powi(3)
11//! }
12//!
13//! fn bar<D: DualNum<f64>, const N: usize>(x: SVector<D, N>) -> D {
14//! x.dot(&x).sqrt()
15//! }
16//!
17//! fn main() {
18//! // Calculate a simple derivative
19//! let (f, df) = first_derivative(foo, 5.0);
20//! assert_eq!(f, 125.0);
21//! assert_eq!(df, 75.0);
22//!
23//! // Manually construct the dual number
24//! let x = Dual64::new(5.0, 1.0);
25//! println!("{}", foo(x)); // 125 + 75ε
26//!
27//! // Calculate a gradient
28//! let (f, g) = gradient(bar, &SVector::from([4.0, 3.0]));
29//! assert_eq!(f, 5.0);
30//! assert_eq!(g[0], 0.8);
31//!
32//! // Calculate a Hessian
33//! let (f, g, h) = hessian(bar, &SVector::from([4.0, 3.0]));
34//! println!("{h}"); // [[0.072, -0.096], [-0.096, 0.128]]
35//!
36//! // for x=cos(t) calculate the third derivative of foo w.r.t. t
37//! let (f0, f1, f2, f3) = third_derivative(|t| foo(t.cos()), 1.0);
38//! println!("{f3}"); // 1.5836632930100278
39//! }
40//! ```
41//!
42//! # Usage
43//! There are two ways to use the data structures and functions provided in this crate:
44//! 1. (recommended) Using the provided functions for explicit ([`first_derivative`], [`gradient`], ...) and
45//! implicit ([`implicit_derivative`], [`implicit_derivative_binary`], [`implicit_derivative_vec`]) functions.
46//! 2. (for experienced users) Using the different dual number types ([`Dual`], [`HyperDual`], [`DualVec`], ...) directly.
47//!
48//! The following examples and explanations focus on the first way.
49//!
50//! # Derivatives of explicit functions
51//! To be able to calculate the derivative of a function, it needs to be generic over the type of dual number used.
52//! Most commonly this would look like this:
53//! ```compile_fail
54//! fn foo<D: DualNum<f64> + Copy>(x: X) -> O {...}
55//! ```
56//! Of course, the function could also use single precision ([`f32`]) or be generic over the precision (`F:` [`DualNumFloat`]).
57//! For now, [`Copy`] is not a supertrait of [`DualNum`] to enable the calculation of derivatives with respect
58//! to a dynamic number of variables. However, in practice, using the [`Copy`] trait bound leads to an
59//! implementation that is more similar to one not using AD and there could be severe performance ramifications
60//! when using dynamically allocated dual numbers.
61//!
62//! The type `X` above is `D` for univariate functions, [`&OVector`](nalgebra::OVector) for multivariate
63//! functions, and `(D, D)` or `(&OVector, &OVector)` for partial derivatives. In the simplest case, the output
64//! `O` is a scalar `D`. However, it is generalized using the [`Mappable`] trait to also include types like
65//! [`Option<D>`] or [`Result<D, E>`], collections like [`Vec<D>`] or [`HashMap<K, D>`], or custom structs that
66//! implement the [`Mappable`] trait. Therefore, it is, e.g., possible to calculate the derivative of a fallible
67//! function:
68//!
69//! ```no_run
70//! # use num_dual::{DualNum, first_derivative};
71//! # type E = ();
72//! fn foo<D: DualNum<f64> + Copy>(x: D) -> Result<D, E> { todo!() }
73//!
74//! fn main() -> Result<(), E> {
75//! let (val, deriv) = first_derivative(foo, 2.0)?;
76//! // ...
77//! Ok(())
78//! }
79//! ```
80//! All dual number types can contain other dual numbers as inner types. Therefore, it is also possible to
81//! use the different derivative functions inside of each other.
82//!
83//! ## Extra arguments
84//! The [`partial`] and [`partial2`] functions are used to pass additional arguments to the function, e.g.:
85//! ```no_run
86//! # use num_dual::{DualNum, first_derivative, partial};
87//! fn foo<D: DualNum<f64> + Copy>(x: D, args: &(D, D)) -> D { todo!() }
88//!
89//! fn main() {
90//! let (val, deriv) = first_derivative(partial(foo, &(3.0, 4.0)), 5.0);
91//! }
92//! ```
93//! All types that implement the [`DualStruct`] trait can be used as additional function arguments. The
94//! only difference between using the [`partial`] and [`partial2`] functions compared to passing the extra
95//! arguments via a closure, is that the type of the extra arguments is automatically adjusted to the correct
96//! dual number type used for the automatic differentiation. Note that the following code would not compile:
97//! ```compile_fail
98//! # use num_dual::{DualNum, first_derivative};
99//! # fn foo<D: DualNum<f64> + Copy>(x: D, args: &(D, D)) -> D { todo!() }
100//! fn main() {
101//! let (val, deriv) = first_derivative(|x| foo(x, &(3.0, 4.0)), 5.0);
102//! }
103//! ```
104//! The code created by [`partial`] essentially translates to:
105//! ```no_run
106//! # use num_dual::{DualNum, first_derivative, Dual, DualStruct};
107//! # fn foo<D: DualNum<f64> + Copy>(x: D, args: &(D, D)) -> D { todo!() }
108//! fn main() {
109//! let (val, deriv) = first_derivative(|x| foo(x, &(Dual::from_inner(&3.0), Dual::from_inner(&4.0))), 5.0);
110//! }
111//! ```
112//!
113//! ## The [`Gradients`] trait
114//! The functions [`gradient`], [`hessian`], [`partial_hessian`] and [`jacobian`] are generic over the dimensionality
115//! of the variable vector. However, to use the functions in a generic context requires not using the [`Copy`] trait
116//! bound on the dual number type, because the dynamically sized dual numbers can by construction not implement
117//! [`Copy`]. Also, due to frequent heap allocations, the performance of the automatic differentiation could
118//! suffer significantly for dynamically sized dual numbers compared to statically sized dual numbers. The
119//! [`Gradients`] trait is introduced to overcome these limitations.
120//! ```
121//! # use num_dual::{DualNum, Gradients};
122//! # use nalgebra::{OVector, DefaultAllocator, allocator::Allocator, vector, dvector};
123//! # use approx::assert_relative_eq;
124//! fn foo<D: DualNum<f64> + Copy, N: Gradients>(x: OVector<D, N>, n: &D) -> D where DefaultAllocator: Allocator<N> {
125//! x.dot(&x).sqrt() - n
126//! }
127//!
128//! fn main() {
129//! let x = vector![1.0, 5.0, 5.0, 7.0];
130//! let (f, grad) = Gradients::gradient(foo, &x, &10.0);
131//! assert_eq!(f, 0.0);
132//! assert_relative_eq!(grad, vector![0.1, 0.5, 0.5, 0.7]);
133//!
134//! let x = dvector![1.0, 5.0, 5.0, 7.0];
135//! let (f, grad) = Gradients::gradient(foo, &x, &10.0);
136//! assert_eq!(f, 0.0);
137//! assert_relative_eq!(grad, dvector![0.1, 0.5, 0.5, 0.7]);
138//! }
139//! ```
140//! For dynamically sized input arrays, the [`Gradients`] trait evaluates gradients or higher-order derivatives
141//! by iteratively evaluating scalar derivatives. For functions that do not rely on the [`Copy`] trait bound,
142//! only benchmarking can reveal Whether the increased performance through the avoidance of heap allocations
143//! can overcome the overhead of repeated function evaluations, i.e., if [`Gradients`] outperforms directly
144//! calling [`gradient`], [`hessian`], [`partial_hessian`] or [`jacobian`].
145//!
146//! # Derivatives of implicit functions
147//! Implicit differentiation is used to determine the derivative `dy/dx` where the output `y` is only related
148//! implicitly to the input `x` via the equation `f(x,y)=0`. Automatic implicit differentiation generalizes the
149//! idea to determining the output `y` with full derivative information. Note that the first step in calculating
150//! an implicit derivative is always determining the "real" part (i.e., neglecting all derivatives) of the equation
151//! `f(x,y)=0`. The `num-dual` library is focused on automatic differentiation and not nonlinear equation
152//! solving. Therefore, this first step needs to be done with your own custom solutions, or Rust crates for
153//! nonlinear equation solving and optimization like, e.g., [argmin](https://argmin-rs.org/).
154//!
155//! The following example implements a square root for generic dual numbers using implicit differentiation. Of
156//! course, the derivatives of the square root can also be determined explicitly using the chain rule, so the
157//! example serves mostly as illustration. `x.re()` provides the "real" part of the dual number which is a [`f64`]
158//! and therefore, we can use all the functionalities from the std library (including the square root).
159//! ```
160//! # use num_dual::{DualNum, implicit_derivative, first_derivative};
161//! fn implicit_sqrt<D: DualNum<f64> + Copy>(x: D) -> D {
162//! implicit_derivative(|s, x| s * s - x, x.re().sqrt(), &x)
163//! }
164//!
165//! fn main() {
166//! // sanity check, not actually calculating any derivative
167//! assert_eq!(implicit_sqrt(25.0), 5.0);
168//!
169//! let (sq, deriv) = first_derivative(implicit_sqrt, 25.0);
170//! assert_eq!(sq, 5.0);
171//! // The derivative of sqrt(x) is 1/(2*sqrt(x)) which should evaluate to 0.1
172//! assert_eq!(deriv, 0.1);
173//! }
174//! ```
175//! The `implicit_sqrt` or any likewise defined function is generic over the dual type `D`
176//! and can, therefore, be used anywhere as a part of an arbitrary complex computation. The functions
177//! [`implicit_derivative_binary`] and [`implicit_derivative_vec`] can be used for implicit functions
178//! with more than one variable.
179//!
180//! For implicit functions that contain complex models and a large number of parameters, the [`ImplicitDerivative`]
181//! interface might come in handy. The idea is to define the implicit function using the [`ImplicitFunction`] trait
182//! and feeding it into the [`ImplicitDerivative`] struct, which internally stores the parameters as dual numbers
183//! and their real parts. The [`ImplicitDerivative`] then provides methods for the evaluation of the real part
184//! of the residual (which can be passed to a nonlinear solver) and the implicit derivative which can be called
185//! after solving for the real part of the solution to reconstruct all the derivatives.
186//! ```
187//! # use num_dual::{ImplicitFunction, DualNum, Dual, ImplicitDerivative};
188//! struct ImplicitSqrt;
189//! impl ImplicitFunction<f64> for ImplicitSqrt {
190//! type Parameters<D> = D;
191//! type Variable<D> = D;
192//! fn residual<D: DualNum<f64> + Copy>(x: D, square: &D) -> D {
193//! *square - x * x
194//! }
195//! }
196//!
197//! fn main() {
198//! let x = Dual::from_re(25.0).derivative();
199//! let func = ImplicitDerivative::new(ImplicitSqrt, x);
200//! assert_eq!(func.residual(5.0), 0.0);
201//! assert_eq!(x.sqrt(), func.implicit_derivative(5.0));
202//! }
203//! ```
204//!
205//! ## Combination with nonlinear solver libraries
206//! As mentioned previously, this crate does not contain any algorithms for nonlinear optimization or root finding.
207//! However, combining the capabilities of automatic differentiation with nonlinear solving can be very fruitful.
208//! Most importantly, the calculation of Jacobians or Hessians can be completely automated, if the model can be
209//! expressed within the functionalities of the [`DualNum`] trait. On top of that implicit derivatives can be of
210//! interest, if derivatives of the result of the optimization itself are relevant (e.g., in a bilevel
211//! optimization). The synergy is exploited in the [`ipopt-ad`](https://github.com/prehner/ipopt-ad) crate that
212//! turns the NLP solver [IPOPT](https://github.com/coin-or/Ipopt) into a black-box optimization algorithm (i.e.,
213//! it only requires a function that returns the values of the optimization variable and constraints), without
214//! any repercussions regarding the robustness or speed of convergence of the solver.
215//!
216//! If you are developing nonlinear optimization algorithms in Rust, feel free to reach out to us. We are happy to
217//! discuss how to enhance your algorithms with the automatic differentiation capabilities of this crate.
218
219#![warn(clippy::all)]
220#![warn(clippy::allow_attributes)]
221
222use nalgebra::allocator::Allocator;
223use nalgebra::{DefaultAllocator, Dim, OMatrix, Scalar};
224#[cfg(feature = "ndarray")]
225use ndarray::ScalarOperand;
226use num_traits::{Float, FloatConst, FromPrimitive, Inv, NumAssignOps, NumOps, Signed};
227use std::collections::HashMap;
228use std::fmt;
229use std::hash::Hash;
230use std::iter::{Product, Sum};
231
232#[macro_use]
233mod macros;
234#[macro_use]
235mod impl_derivatives;
236
237mod bessel;
238mod datatypes;
239mod explicit;
240mod implicit;
241pub use bessel::BesselDual;
242pub use datatypes::derivative::Derivative;
243pub use datatypes::dual::{Dual, Dual32, Dual64};
244pub use datatypes::dual_vec::{
245 DualDVec32, DualDVec64, DualSVec, DualSVec32, DualSVec64, DualVec, DualVec32, DualVec64,
246};
247pub use datatypes::dual2::{Dual2, Dual2_32, Dual2_64};
248pub use datatypes::dual2_vec::{
249 Dual2DVec, Dual2DVec32, Dual2DVec64, Dual2SVec, Dual2SVec32, Dual2SVec64, Dual2Vec, Dual2Vec32,
250 Dual2Vec64,
251};
252pub use datatypes::dual3::{Dual3, Dual3_32, Dual3_64};
253pub use datatypes::hyperdual::{HyperDual, HyperDual32, HyperDual64};
254pub use datatypes::hyperdual_vec::{
255 HyperDualDVec32, HyperDualDVec64, HyperDualSVec32, HyperDualSVec64, HyperDualVec,
256 HyperDualVec32, HyperDualVec64,
257};
258pub use datatypes::hyperhyperdual::{HyperHyperDual, HyperHyperDual32, HyperHyperDual64};
259pub use datatypes::real::Real;
260pub use explicit::{
261 Gradients, first_derivative, gradient, hessian, jacobian, partial, partial_hessian, partial2,
262 second_derivative, second_partial_derivative, third_derivative, third_partial_derivative,
263 third_partial_derivative_vec, zeroth_derivative,
264};
265pub use implicit::{
266 ImplicitDerivative, ImplicitFunction, implicit_derivative, implicit_derivative_binary,
267 implicit_derivative_sp, implicit_derivative_vec,
268};
269
270pub mod linalg;
271
272#[cfg(feature = "python")]
273pub mod python;
274
275#[cfg(feature = "python_macro")]
276mod python_macro;
277
278/// A generalized (hyper) dual number.
279#[cfg(feature = "ndarray")]
280pub trait DualNum<F>:
281 NumOps
282 + for<'r> NumOps<&'r Self>
283 + Signed
284 + NumOps<F>
285 + NumAssignOps
286 + NumAssignOps<F>
287 + Clone
288 + Inv<Output = Self>
289 + Sum
290 + Product
291 + FromPrimitive
292 + From<F>
293 + DualStruct<Self, F, Real = F>
294 + Mappable<Self>
295 + fmt::Display
296 + PartialEq
297 + fmt::Debug
298 + ScalarOperand
299 + 'static
300{
301 /// Highest derivative that can be calculated with this struct
302 const NDERIV: usize;
303
304 /// Reciprocal (inverse) of a number `1/x`
305 fn recip(&self) -> Self;
306
307 /// Power with integer exponent `x^n`
308 fn powi(&self, n: i32) -> Self;
309
310 /// Power with real exponent `x^n`
311 fn powf(&self, n: F) -> Self;
312
313 /// Square root
314 fn sqrt(&self) -> Self;
315
316 /// Cubic root
317 fn cbrt(&self) -> Self;
318
319 /// Exponential `e^x`
320 fn exp(&self) -> Self;
321
322 /// Exponential with base 2 `2^x`
323 fn exp2(&self) -> Self;
324
325 /// Exponential minus 1 `e^x-1`
326 fn exp_m1(&self) -> Self;
327
328 /// Natural logarithm
329 fn ln(&self) -> Self;
330
331 /// Logarithm with arbitrary base
332 fn log(&self, base: F) -> Self;
333
334 /// Logarithm with base 2
335 fn log2(&self) -> Self;
336
337 /// Logarithm with base 10
338 fn log10(&self) -> Self;
339
340 /// Logarithm on x plus one `ln(1+x)`
341 fn ln_1p(&self) -> Self;
342
343 /// Sine
344 fn sin(&self) -> Self;
345
346 /// Cosine
347 fn cos(&self) -> Self;
348
349 /// Tangent
350 fn tan(&self) -> Self;
351
352 /// Calculate sine and cosine simultaneously
353 fn sin_cos(&self) -> (Self, Self);
354
355 /// Arcsine
356 fn asin(&self) -> Self;
357
358 /// Arccosine
359 fn acos(&self) -> Self;
360
361 /// Arctangent
362 fn atan(&self) -> Self;
363
364 /// Arctangent
365 fn atan2(&self, other: Self) -> Self;
366
367 /// Hyperbolic sine
368 fn sinh(&self) -> Self;
369
370 /// Hyperbolic cosine
371 fn cosh(&self) -> Self;
372
373 /// Hyperbolic tangent
374 fn tanh(&self) -> Self;
375
376 /// Area hyperbolic sine
377 fn asinh(&self) -> Self;
378
379 /// Area hyperbolic cosine
380 fn acosh(&self) -> Self;
381
382 /// Area hyperbolic tangent
383 fn atanh(&self) -> Self;
384
385 /// 0th order spherical Bessel function of the first kind
386 fn sph_j0(&self) -> Self;
387
388 /// 1st order spherical Bessel function of the first kind
389 fn sph_j1(&self) -> Self;
390
391 /// 2nd order spherical Bessel function of the first kind
392 fn sph_j2(&self) -> Self;
393
394 /// Fused multiply-add
395 #[inline]
396 fn mul_add(&self, a: Self, b: Self) -> Self {
397 self.clone() * a + b
398 }
399
400 /// Power with dual exponent `x^n`
401 #[inline]
402 fn powd(&self, exp: Self) -> Self {
403 (self.ln() * exp).exp()
404 }
405}
406
407/// A generalized (hyper) dual number.
408#[cfg(not(feature = "ndarray"))]
409pub trait DualNum<F>:
410 NumOps
411 + for<'r> NumOps<&'r Self>
412 + Signed
413 + NumOps<F>
414 + NumAssignOps
415 + NumAssignOps<F>
416 + Clone
417 + Inv<Output = Self>
418 + Sum
419 + Product
420 + FromPrimitive
421 + From<F>
422 + DualStruct<Self, F, Real = F>
423 + Mappable<Self>
424 + fmt::Display
425 + PartialEq
426 + fmt::Debug
427 + 'static
428{
429 /// Highest derivative that can be calculated with this struct
430 const NDERIV: usize;
431
432 /// Reciprocal (inverse) of a number `1/x`
433 fn recip(&self) -> Self;
434
435 /// Power with integer exponent `x^n`
436 fn powi(&self, n: i32) -> Self;
437
438 /// Power with real exponent `x^n`
439 fn powf(&self, n: F) -> Self;
440
441 /// Square root
442 fn sqrt(&self) -> Self;
443
444 /// Cubic root
445 fn cbrt(&self) -> Self;
446
447 /// Exponential `e^x`
448 fn exp(&self) -> Self;
449
450 /// Exponential with base 2 `2^x`
451 fn exp2(&self) -> Self;
452
453 /// Exponential minus 1 `e^x-1`
454 fn exp_m1(&self) -> Self;
455
456 /// Natural logarithm
457 fn ln(&self) -> Self;
458
459 /// Logarithm with arbitrary base
460 fn log(&self, base: F) -> Self;
461
462 /// Logarithm with base 2
463 fn log2(&self) -> Self;
464
465 /// Logarithm with base 10
466 fn log10(&self) -> Self;
467
468 /// Logarithm on x plus one `ln(1+x)`
469 fn ln_1p(&self) -> Self;
470
471 /// Sine
472 fn sin(&self) -> Self;
473
474 /// Cosine
475 fn cos(&self) -> Self;
476
477 /// Tangent
478 fn tan(&self) -> Self;
479
480 /// Calculate sine and cosine simultaneously
481 fn sin_cos(&self) -> (Self, Self);
482
483 /// Arcsine
484 fn asin(&self) -> Self;
485
486 /// Arccosine
487 fn acos(&self) -> Self;
488
489 /// Arctangent
490 fn atan(&self) -> Self;
491
492 /// Arctangent
493 fn atan2(&self, other: Self) -> Self;
494
495 /// Hyperbolic sine
496 fn sinh(&self) -> Self;
497
498 /// Hyperbolic cosine
499 fn cosh(&self) -> Self;
500
501 /// Hyperbolic tangent
502 fn tanh(&self) -> Self;
503
504 /// Area hyperbolic sine
505 fn asinh(&self) -> Self;
506
507 /// Area hyperbolic cosine
508 fn acosh(&self) -> Self;
509
510 /// Area hyperbolic tangent
511 fn atanh(&self) -> Self;
512
513 /// 0th order spherical Bessel function of the first kind
514 fn sph_j0(&self) -> Self;
515
516 /// 1st order spherical Bessel function of the first kind
517 fn sph_j1(&self) -> Self;
518
519 /// 2nd order spherical Bessel function of the first kind
520 fn sph_j2(&self) -> Self;
521
522 /// Fused multiply-add
523 #[inline]
524 fn mul_add(&self, a: Self, b: Self) -> Self {
525 self.clone() * a + b
526 }
527
528 /// Power with dual exponent `x^n`
529 #[inline]
530 fn powd(&self, exp: Self) -> Self {
531 (self.ln() * exp).exp()
532 }
533}
534
535/// The underlying data type of individual derivatives. Usually f32 or f64.
536pub trait DualNumFloat:
537 Float + FloatConst + FromPrimitive + Signed + fmt::Display + fmt::Debug + Sync + Send + 'static
538{
539}
540impl<T> DualNumFloat for T where
541 T: Float
542 + FloatConst
543 + FromPrimitive
544 + Signed
545 + fmt::Display
546 + fmt::Debug
547 + Sync
548 + Send
549 + 'static
550{
551}
552
553macro_rules! impl_dual_num_float {
554 ($float:ty) => {
555 impl DualNum<$float> for $float {
556 const NDERIV: usize = 0;
557
558 fn mul_add(&self, a: Self, b: Self) -> Self {
559 <$float>::mul_add(*self, a, b)
560 }
561 fn recip(&self) -> Self {
562 <$float>::recip(*self)
563 }
564 fn powi(&self, n: i32) -> Self {
565 <$float>::powi(*self, n)
566 }
567 fn powf(&self, n: Self) -> Self {
568 <$float>::powf(*self, n)
569 }
570 fn powd(&self, n: Self) -> Self {
571 <$float>::powf(*self, n)
572 }
573 fn sqrt(&self) -> Self {
574 <$float>::sqrt(*self)
575 }
576 fn exp(&self) -> Self {
577 <$float>::exp(*self)
578 }
579 fn exp2(&self) -> Self {
580 <$float>::exp2(*self)
581 }
582 fn ln(&self) -> Self {
583 <$float>::ln(*self)
584 }
585 fn log(&self, base: Self) -> Self {
586 <$float>::log(*self, base)
587 }
588 fn log2(&self) -> Self {
589 <$float>::log2(*self)
590 }
591 fn log10(&self) -> Self {
592 <$float>::log10(*self)
593 }
594 fn cbrt(&self) -> Self {
595 <$float>::cbrt(*self)
596 }
597 fn sin(&self) -> Self {
598 <$float>::sin(*self)
599 }
600 fn cos(&self) -> Self {
601 <$float>::cos(*self)
602 }
603 fn tan(&self) -> Self {
604 <$float>::tan(*self)
605 }
606 fn asin(&self) -> Self {
607 <$float>::asin(*self)
608 }
609 fn acos(&self) -> Self {
610 <$float>::acos(*self)
611 }
612 fn atan(&self) -> Self {
613 <$float>::atan(*self)
614 }
615 fn atan2(&self, other: $float) -> Self {
616 <$float>::atan2(*self, other)
617 }
618 fn sin_cos(&self) -> (Self, Self) {
619 <$float>::sin_cos(*self)
620 }
621 fn exp_m1(&self) -> Self {
622 <$float>::exp_m1(*self)
623 }
624 fn ln_1p(&self) -> Self {
625 <$float>::ln_1p(*self)
626 }
627 fn sinh(&self) -> Self {
628 <$float>::sinh(*self)
629 }
630 fn cosh(&self) -> Self {
631 <$float>::cosh(*self)
632 }
633 fn tanh(&self) -> Self {
634 <$float>::tanh(*self)
635 }
636 fn asinh(&self) -> Self {
637 <$float>::asinh(*self)
638 }
639 fn acosh(&self) -> Self {
640 <$float>::acosh(*self)
641 }
642 fn atanh(&self) -> Self {
643 <$float>::atanh(*self)
644 }
645 fn sph_j0(&self) -> Self {
646 if self.abs() < <$float>::EPSILON {
647 1.0 - self * self / 6.0
648 } else {
649 self.sin() / self
650 }
651 }
652 fn sph_j1(&self) -> Self {
653 if self.abs() < <$float>::EPSILON {
654 self / 3.0
655 } else {
656 let sc = self.sin_cos();
657 let rec = self.recip();
658 (sc.0 * rec - sc.1) * rec
659 }
660 }
661 fn sph_j2(&self) -> Self {
662 if self.abs() < <$float>::EPSILON {
663 self * self / 15.0
664 } else {
665 let sc = self.sin_cos();
666 let s2 = self * self;
667 ((3.0 - s2) * sc.0 - 3.0 * self * sc.1) / (self * s2)
668 }
669 }
670 }
671 };
672}
673
674impl_dual_num_float!(f32);
675impl_dual_num_float!(f64);
676
677/// A struct that contains dual numbers. Needed for arbitrary arguments in [ImplicitFunction].
678///
679/// The trait is implemented for all dual types themselves, and common data types (tuple, vec,
680/// array, ...) and can be implemented for custom data types to achieve full flexibility.
681pub trait DualStruct<D, F> {
682 type Real;
683 type Inner;
684 fn re(&self) -> Self::Real;
685 fn from_inner(inner: &Self::Inner) -> Self;
686}
687
688/// Trait for structs used as an output of functions for which derivatives are calculated.
689///
690/// The main intention is to generalize the calculation of derivatives to fallible functions, but
691/// other use cases might also appear in the future.
692pub trait Mappable<D> {
693 type Output<O>;
694 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O>;
695}
696
697impl<D, F> DualStruct<D, F> for () {
698 type Real = ();
699 type Inner = ();
700 fn re(&self) {}
701 fn from_inner(_: &Self::Inner) -> Self {}
702}
703
704impl<D> Mappable<D> for () {
705 type Output<O> = ();
706 fn map_dual<M: FnOnce(D) -> O, O>(self, _: M) {}
707}
708
709impl DualStruct<f32, f32> for f32 {
710 type Real = f32;
711 type Inner = f32;
712 fn re(&self) -> f32 {
713 *self
714 }
715 fn from_inner(inner: &Self::Inner) -> Self {
716 *inner
717 }
718}
719
720impl Mappable<f32> for f32 {
721 type Output<O> = O;
722 fn map_dual<M: FnOnce(f32) -> O, O>(self, f: M) -> Self::Output<O> {
723 f(self)
724 }
725}
726
727impl DualStruct<f64, f64> for f64 {
728 type Real = f64;
729 type Inner = f64;
730 fn re(&self) -> f64 {
731 *self
732 }
733 fn from_inner(inner: &Self::Inner) -> Self {
734 *inner
735 }
736}
737
738impl Mappable<f64> for f64 {
739 type Output<O> = O;
740 fn map_dual<M: FnOnce(f64) -> O, O>(self, f: M) -> Self::Output<O> {
741 f(self)
742 }
743}
744
745impl<D, F, T1: DualStruct<D, F>, T2: DualStruct<D, F>> DualStruct<D, F> for (T1, T2) {
746 type Real = (T1::Real, T2::Real);
747 type Inner = (T1::Inner, T2::Inner);
748 fn re(&self) -> Self::Real {
749 let (s1, s2) = self;
750 (s1.re(), s2.re())
751 }
752 fn from_inner(re: &Self::Inner) -> Self {
753 let (r1, r2) = re;
754 (T1::from_inner(r1), T2::from_inner(r2))
755 }
756}
757
758impl<D, T1: Mappable<D>, T2: Mappable<D>> Mappable<D> for (T1, T2) {
759 type Output<O> = (T1::Output<O>, T2::Output<O>);
760 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
761 let (s1, s2) = self;
762 (s1.map_dual(&f), s2.map_dual(&f))
763 }
764}
765
766impl<D, F, T1: DualStruct<D, F>, T2: DualStruct<D, F>, T3: DualStruct<D, F>> DualStruct<D, F>
767 for (T1, T2, T3)
768{
769 type Real = (T1::Real, T2::Real, T3::Real);
770 type Inner = (T1::Inner, T2::Inner, T3::Inner);
771 fn re(&self) -> Self::Real {
772 let (s1, s2, s3) = self;
773 (s1.re(), s2.re(), s3.re())
774 }
775 fn from_inner(inner: &Self::Inner) -> Self {
776 let (r1, r2, r3) = inner;
777 (T1::from_inner(r1), T2::from_inner(r2), T3::from_inner(r3))
778 }
779}
780
781impl<D, T1: Mappable<D>, T2: Mappable<D>, T3: Mappable<D>> Mappable<D> for (T1, T2, T3) {
782 type Output<O> = (T1::Output<O>, T2::Output<O>, T3::Output<O>);
783 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
784 let (s1, s2, s3) = self;
785 (s1.map_dual(&f), s2.map_dual(&f), s3.map_dual(&f))
786 }
787}
788
789impl<D, F, T1: DualStruct<D, F>, T2: DualStruct<D, F>, T3: DualStruct<D, F>, T4: DualStruct<D, F>>
790 DualStruct<D, F> for (T1, T2, T3, T4)
791{
792 type Real = (T1::Real, T2::Real, T3::Real, T4::Real);
793 type Inner = (T1::Inner, T2::Inner, T3::Inner, T4::Inner);
794 fn re(&self) -> Self::Real {
795 let (s1, s2, s3, s4) = self;
796 (s1.re(), s2.re(), s3.re(), s4.re())
797 }
798 fn from_inner(inner: &Self::Inner) -> Self {
799 let (r1, r2, r3, r4) = inner;
800 (
801 T1::from_inner(r1),
802 T2::from_inner(r2),
803 T3::from_inner(r3),
804 T4::from_inner(r4),
805 )
806 }
807}
808
809impl<D, T1: Mappable<D>, T2: Mappable<D>, T3: Mappable<D>, T4: Mappable<D>> Mappable<D>
810 for (T1, T2, T3, T4)
811{
812 type Output<O> = (T1::Output<O>, T2::Output<O>, T3::Output<O>, T4::Output<O>);
813 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
814 let (s1, s2, s3, s4) = self;
815 (
816 s1.map_dual(&f),
817 s2.map_dual(&f),
818 s3.map_dual(&f),
819 s4.map_dual(&f),
820 )
821 }
822}
823
824impl<
825 D,
826 F,
827 T1: DualStruct<D, F>,
828 T2: DualStruct<D, F>,
829 T3: DualStruct<D, F>,
830 T4: DualStruct<D, F>,
831 T5: DualStruct<D, F>,
832> DualStruct<D, F> for (T1, T2, T3, T4, T5)
833{
834 type Real = (T1::Real, T2::Real, T3::Real, T4::Real, T5::Real);
835 type Inner = (T1::Inner, T2::Inner, T3::Inner, T4::Inner, T5::Inner);
836 fn re(&self) -> Self::Real {
837 let (s1, s2, s3, s4, s5) = self;
838 (s1.re(), s2.re(), s3.re(), s4.re(), s5.re())
839 }
840 fn from_inner(inner: &Self::Inner) -> Self {
841 let (r1, r2, r3, r4, r5) = inner;
842 (
843 T1::from_inner(r1),
844 T2::from_inner(r2),
845 T3::from_inner(r3),
846 T4::from_inner(r4),
847 T5::from_inner(r5),
848 )
849 }
850}
851
852impl<D, T1: Mappable<D>, T2: Mappable<D>, T3: Mappable<D>, T4: Mappable<D>, T5: Mappable<D>>
853 Mappable<D> for (T1, T2, T3, T4, T5)
854{
855 type Output<O> = (
856 T1::Output<O>,
857 T2::Output<O>,
858 T3::Output<O>,
859 T4::Output<O>,
860 T5::Output<O>,
861 );
862 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
863 let (s1, s2, s3, s4, s5) = self;
864 (
865 s1.map_dual(&f),
866 s2.map_dual(&f),
867 s3.map_dual(&f),
868 s4.map_dual(&f),
869 s5.map_dual(&f),
870 )
871 }
872}
873
874impl<D, F, T: DualStruct<D, F>, const N: usize> DualStruct<D, F> for [T; N] {
875 type Real = [T::Real; N];
876 type Inner = [T::Inner; N];
877 fn re(&self) -> Self::Real {
878 self.each_ref().map(|x| x.re())
879 }
880 fn from_inner(re: &Self::Inner) -> Self {
881 re.each_ref().map(T::from_inner)
882 }
883}
884
885impl<D, T: Mappable<D>, const N: usize> Mappable<D> for [T; N] {
886 type Output<O> = [T::Output<O>; N];
887 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
888 self.map(|x| x.map_dual(&f))
889 }
890}
891
892impl<D, F, T: DualStruct<D, F>> DualStruct<D, F> for Option<T> {
893 type Real = Option<T::Real>;
894 type Inner = Option<T::Inner>;
895 fn re(&self) -> Self::Real {
896 self.as_ref().map(|x| x.re())
897 }
898 fn from_inner(inner: &Self::Inner) -> Self {
899 inner.as_ref().map(|x| T::from_inner(x))
900 }
901}
902
903impl<D, T: Mappable<D>> Mappable<D> for Option<T> {
904 type Output<O> = Option<T::Output<O>>;
905 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
906 self.map(|x| x.map_dual(f))
907 }
908}
909
910impl<D, T: Mappable<D>, E> Mappable<D> for Result<T, E> {
911 type Output<O> = Result<T::Output<O>, E>;
912 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
913 self.map(|x| x.map_dual(f))
914 }
915}
916
917impl<D, F, T: DualStruct<D, F>> DualStruct<D, F> for Vec<T> {
918 type Real = Vec<T::Real>;
919 type Inner = Vec<T::Inner>;
920 fn re(&self) -> Self::Real {
921 self.iter().map(|x| x.re()).collect()
922 }
923 fn from_inner(inner: &Self::Inner) -> Self {
924 inner.iter().map(|x| T::from_inner(x)).collect()
925 }
926}
927
928impl<D, T: Mappable<D>> Mappable<D> for Vec<T> {
929 type Output<O> = Vec<T::Output<O>>;
930 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
931 self.into_iter().map(|x| x.map_dual(&f)).collect()
932 }
933}
934
935impl<D, F, T: DualStruct<D, F>, K: Clone + Eq + Hash> DualStruct<D, F> for HashMap<K, T> {
936 type Real = HashMap<K, T::Real>;
937 type Inner = HashMap<K, T::Inner>;
938 fn re(&self) -> Self::Real {
939 self.iter().map(|(k, x)| (k.clone(), x.re())).collect()
940 }
941 fn from_inner(inner: &Self::Inner) -> Self {
942 inner
943 .iter()
944 .map(|(k, x)| (k.clone(), T::from_inner(x)))
945 .collect()
946 }
947}
948
949impl<D, T: Mappable<D>, K: Eq + Hash> Mappable<D> for HashMap<K, T> {
950 type Output<O> = HashMap<K, T::Output<O>>;
951 fn map_dual<M: Fn(D) -> O, O>(self, f: M) -> Self::Output<O> {
952 self.into_iter().map(|(k, x)| (k, x.map_dual(&f))).collect()
953 }
954}
955
956impl<D: DualNum<F>, F: DualNumFloat, R: Dim, C: Dim> DualStruct<D, F> for OMatrix<D, R, C>
957where
958 DefaultAllocator: Allocator<R, C>,
959 D::Inner: DualNum<F>,
960{
961 type Real = OMatrix<F, R, C>;
962 type Inner = OMatrix<D::Inner, R, C>;
963 fn re(&self) -> Self::Real {
964 self.map(|x| x.re())
965 }
966 fn from_inner(inner: &Self::Inner) -> Self {
967 inner.map(|x| D::from_inner(&x))
968 }
969}
970
971impl<D: Scalar, R: Dim, C: Dim> Mappable<Self> for OMatrix<D, R, C>
972where
973 DefaultAllocator: Allocator<R, C>,
974{
975 type Output<O> = O;
976 fn map_dual<M: Fn(Self) -> O, O>(self, f: M) -> O {
977 f(self)
978 }
979}