#[cfg(feature = "nalgebra")]
use crate::linalg::LU;
use crate::{Dual, DualNum, DualNumFloat, DualStruct, first_derivative, partial};
#[cfg(feature = "nalgebra")]
use crate::{DualSVec, DualVec, Gradients, jacobian};
#[cfg(feature = "nalgebra")]
use nalgebra::{DefaultAllocator, Dim, OVector, SVector, U1, U2, allocator::Allocator};
use std::marker::PhantomData;
pub fn implicit_derivative<G, D: DualNum, A: DualStruct>(
g: G,
x: D::Primitive,
args: &A::Inner,
) -> D
where
G: Fn(Dual<D>, &A) -> Dual<D>,
{
let mut x = D::from(x);
for _ in 0..D::NDERIV {
let (f, df) = first_derivative(partial(&g, args), x.clone());
x -= f / df;
}
x
}
#[cfg(feature = "nalgebra")]
pub fn implicit_derivative_binary<G, D: DualNum, A: DualStruct>(
g: G,
x: D::Primitive,
y: D::Primitive,
args: &A::Inner,
) -> [D; 2]
where
G: Fn(DualVec<D, U2>, DualVec<D, U2>, &A) -> [DualVec<D, U2>; 2],
{
let mut x = D::from(x);
let mut y = D::from(y);
let args = A::from_inner(args);
for _ in 0..D::NDERIV {
let (f, jac) = jacobian(
|x| {
let [[x, y]] = x.data.0;
SVector::from(g(x, y, &args))
},
&SVector::from([x.clone(), y.clone()]),
);
let [[f0, f1]] = f.data.0;
let [[j00, j10], [j01, j11]] = jac.data.0;
let det = (j00.clone() * &j11 - j01.clone() * &j10).recip();
x -= (j11 * &f0 - j01 * &f1) * &det;
y -= (j00 * &f1 - j10 * &f0) * &det;
}
[x, y]
}
#[cfg(feature = "nalgebra")]
pub fn implicit_derivative_vec<G, D: DualNum + Copy, A: DualStruct, N: Dim>(
g: G,
x: OVector<D::Primitive, N>,
args: &A::Inner,
) -> OVector<D, N>
where
DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>,
G: Fn(OVector<DualVec<D, N>, N>, &A) -> OVector<DualVec<D, N>, N>,
{
let mut x = x.map(D::from);
let args = A::from_inner(args);
for _ in 0..D::NDERIV {
let (f, jac) = jacobian(|x| g(x, &args), &x);
x -= LU::new(jac).unwrap().solve(&f);
}
x
}
#[cfg(feature = "nalgebra")]
pub fn implicit_derivative_sp<G, D: DualNum + Copy, A: DualStruct, N: Gradients>(
g: G,
x: OVector<D::Primitive, N>,
args: &A::Inner,
) -> OVector<D, N>
where
DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>,
G: Fn(OVector<N::Dual2<D>, N>, &A) -> N::Dual2<D>,
{
let mut x = x.map(D::from);
for _ in 0..D::NDERIV {
let (_, grad, hess) = N::hessian(|x, args| g(x, args), &x, args);
x -= LU::new(hess).unwrap().solve(&grad);
}
x
}
pub trait ImplicitFunction {
type Parameters<D>;
type Variable<D>;
fn residual<D: DualNum + Copy>(
x: Self::Variable<D>,
parameters: &Self::Parameters<D>,
) -> Self::Variable<D>;
}
pub struct ImplicitDerivative<G: ImplicitFunction, D: DualNum + Copy, V> {
base: G::Parameters<D::Real>,
derivative: G::Parameters<D>,
phantom: PhantomData<V>,
}
impl<G: ImplicitFunction, D: DualNum + Copy> ImplicitDerivative<G, D, G::Variable<f64>>
where
G::Parameters<D>: DualStruct<Real = G::Parameters<D::Primitive>>,
{
pub fn new(_: G, parameters: G::Parameters<D>) -> Self {
Self {
base: parameters.re(),
derivative: parameters,
phantom: PhantomData,
}
}
pub fn residual(&self, x: G::Variable<D::Primitive>) -> G::Variable<D::Primitive> {
G::residual(x, &self.base)
}
}
impl<G: ImplicitFunction, D: DualNum<Primitive = F> + Copy, F: DualNumFloat>
ImplicitDerivative<G, D, F>
where
G::Parameters<D>: DualStruct<Real = G::Parameters<D::Primitive>>,
{
pub fn implicit_derivative<A: DualStruct<Inner = G::Parameters<D>>>(&self, x: F) -> D
where
G: ImplicitFunction<Variable<Dual<D>> = Dual<D>, Parameters<Dual<D>> = A>,
{
implicit_derivative(G::residual::<Dual<D>>, x, &self.derivative)
}
}
#[cfg(feature = "nalgebra")]
impl<G: ImplicitFunction, D: DualNum<Primitive = F> + Copy, F: DualNumFloat>
ImplicitDerivative<G, D, [F; 2]>
where
G::Parameters<D>: DualStruct<Real = G::Parameters<D::Primitive>>,
{
pub fn implicit_derivative<A: DualStruct<Inner = G::Parameters<D>>>(&self, x: F, y: F) -> [D; 2]
where
G: ImplicitFunction<
Variable<DualVec<D, U2>> = [DualVec<D, U2>; 2],
Parameters<DualVec<D, U2>> = A,
>,
{
implicit_derivative_binary(
|x, y, args: &A| G::residual::<DualVec<D, U2>>([x, y], args),
x,
y,
&self.derivative,
)
}
}
#[cfg(feature = "nalgebra")]
impl<G: ImplicitFunction, D: DualNum<Primitive = F> + Copy, F: DualNumFloat, const N: usize>
ImplicitDerivative<G, D, SVector<F, N>>
where
G::Parameters<D>: DualStruct<Real = G::Parameters<D::Primitive>>,
{
pub fn implicit_derivative<A: DualStruct<Inner = G::Parameters<D>>>(
&self,
x: SVector<F, N>,
) -> SVector<D, N>
where
G: ImplicitFunction<
Variable<DualSVec<D, N>> = SVector<DualSVec<D, N>, N>,
Parameters<DualSVec<D, N>> = A,
>,
{
implicit_derivative_vec(G::residual::<DualSVec<D, N>>, x, &self.derivative)
}
}
#[cfg(test)]
mod test {
use super::*;
struct TestFunction;
impl ImplicitFunction for TestFunction {
type Parameters<D> = D;
type Variable<D> = D;
fn residual<D: DualNum + Copy>(x: D, square: &D) -> D {
*square - x * x
}
}
#[test]
fn test() {
let f: crate::Dual64 = Dual::from(25.0).derivative();
let func = ImplicitDerivative::new(TestFunction, f);
println!("{}", func.residual(5.0));
println!("{}", func.implicit_derivative(5.0));
println!("{}", f.sqrt());
assert_eq!(f.sqrt(), func.implicit_derivative(5.0));
}
}
#[cfg(test)]
#[cfg(feature = "nalgebra")]
mod test_nalgebra {
use super::*;
use nalgebra::SVector;
struct TestFunction2;
impl ImplicitFunction for TestFunction2 {
type Parameters<D> = (D, D);
type Variable<D> = [D; 2];
fn residual<D: DualNum + Copy>([x, y]: [D; 2], (square_sum, sum): &(D, D)) -> [D; 2] {
[*square_sum - x * x - y * y, *sum - x - y]
}
}
struct TestFunction3<const N: usize>;
impl<const N: usize> ImplicitFunction for TestFunction3<N> {
type Parameters<D> = D;
type Variable<D> = SVector<D, N>;
fn residual<D: DualNum + Copy>(x: SVector<D, N>, &square_sum: &D) -> SVector<D, N> {
let mut res = x;
for i in 1..N {
res[i] = x[i] - x[i - 1] - D::one();
}
res[0] = square_sum - x.dot(&x);
res
}
}
#[test]
fn test_nalgebra() {
let a: crate::Dual64 = Dual::from(25.0).derivative();
let b: crate::Dual64 = Dual::from(7.0);
let func = ImplicitDerivative::new(TestFunction2, (a, b));
println!("\n{:?}", func.residual([4.0, 3.0]));
let [x, y] = func.implicit_derivative(4.0, 3.0);
let xa = (b + (a * 2.0 - b * b).sqrt()) * 0.5;
let ya = (b - (a * 2.0 - b * b).sqrt()) * 0.5;
println!("{x}, {y}");
println!("{xa}, {ya}");
assert_eq!(x, xa);
assert_eq!(y, ya);
let s: crate::Dual64 = Dual::from(30.0).derivative();
let func = ImplicitDerivative::new(TestFunction3, s);
println!("\n{:?}", func.residual(SVector::from([1.0, 2.0, 3.0, 4.0])));
let x = func.implicit_derivative(SVector::from([1.0, 2.0, 3.0, 4.0]));
let x0 = ((s - 5.0).sqrt() - 5.0) * 0.5;
println!("{}, {}, {}, {}", x[0], x[1], x[2], x[3]);
println!("{}, {}, {}, {}", x0 + 1.0, x0 + 2.0, x0 + 3.0, x0 + 4.0);
assert_eq!(x0 + 1.0, x[0]);
assert_eq!(x0 + 2.0, x[1]);
assert_eq!(x0 + 3.0, x[2]);
assert_eq!(x0 + 4.0, x[3]);
}
}