1use crate::linalg::LU;
2use crate::{
3 Dual, DualNum, DualNumFloat, DualSVec, DualStruct, DualVec, Gradients, first_derivative,
4 jacobian, partial,
5};
6use nalgebra::allocator::Allocator;
7use nalgebra::{DefaultAllocator, Dim, OVector, SVector, U1, U2};
8use std::marker::PhantomData;
9
10pub fn implicit_derivative<G, D: DualNum<F>, F: DualNumFloat, A: DualStruct<Dual<D, F>, F>>(
22 g: G,
23 x: F,
24 args: &A::Inner,
25) -> D
26where
27 G: Fn(Dual<D, F>, &A) -> Dual<D, F>,
28{
29 let mut x = D::from(x);
30 for _ in 0..D::NDERIV {
31 let (f, df) = first_derivative(partial(&g, args), x.clone());
32 x -= f / df;
33 }
34 x
35}
36
37pub fn implicit_derivative_binary<
51 G,
52 D: DualNum<F>,
53 F: DualNumFloat,
54 A: DualStruct<DualVec<D, F, U2>, F>,
55>(
56 g: G,
57 x: F,
58 y: F,
59 args: &A::Inner,
60) -> [D; 2]
61where
62 G: Fn(DualVec<D, F, U2>, DualVec<D, F, U2>, &A) -> [DualVec<D, F, U2>; 2],
63{
64 let mut x = D::from(x);
65 let mut y = D::from(y);
66 let args = A::from_inner(args);
67 for _ in 0..D::NDERIV {
68 let (f, jac) = jacobian(
69 |x| {
70 let [[x, y]] = x.data.0;
71 SVector::from(g(x, y, &args))
72 },
73 &SVector::from([x.clone(), y.clone()]),
74 );
75 let [[f0, f1]] = f.data.0;
76 let [[j00, j10], [j01, j11]] = jac.data.0;
77 let det = (j00.clone() * &j11 - j01.clone() * &j10).recip();
78 x -= (j11 * &f0 - j01 * &f1) * &det;
79 y -= (j00 * &f1 - j10 * &f0) * &det;
80 }
81 [x, y]
82}
83
84pub fn implicit_derivative_vec<
102 G,
103 D: DualNum<F> + Copy,
104 F: DualNumFloat,
105 A: DualStruct<DualVec<D, F, N>, F>,
106 N: Dim,
107>(
108 g: G,
109 x: OVector<F, N>,
110 args: &A::Inner,
111) -> OVector<D, N>
112where
113 DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>,
114 G: Fn(OVector<DualVec<D, F, N>, N>, &A) -> OVector<DualVec<D, F, N>, N>,
115{
116 let mut x = x.map(D::from);
117 let args = A::from_inner(args);
118 for _ in 0..D::NDERIV {
119 let (f, jac) = jacobian(|x| g(x, &args), &x);
120 x -= LU::new(jac).unwrap().solve(&f);
121 }
122 x
123}
124
125pub fn implicit_derivative_sp<
153 G,
154 D: DualNum<F> + Copy,
155 F: DualNumFloat,
156 A: DualStruct<N::Dual2<D, F>, F>,
157 N: Gradients,
158>(
159 g: G,
160 x: OVector<F, N>,
161 args: &A::Inner,
162) -> OVector<D, N>
163where
164 DefaultAllocator: Allocator<N> + Allocator<N, N> + Allocator<U1, N>,
165 G: Fn(OVector<N::Dual2<D, F>, N>, &A) -> N::Dual2<D, F>,
166{
167 let mut x = x.map(D::from);
168 for _ in 0..D::NDERIV {
169 let (_, grad, hess) = N::hessian(|x, args| g(x, args), &x, args);
170 x -= LU::new(hess).unwrap().solve(&grad);
171 }
172 x
173}
174
175pub trait ImplicitFunction<F> {
178 type Parameters<D>;
180
181 type Variable<D>;
183
184 fn residual<D: DualNum<F> + Copy>(
186 x: Self::Variable<D>,
187 parameters: &Self::Parameters<D>,
188 ) -> Self::Variable<D>;
189}
190
191pub struct ImplicitDerivative<G: ImplicitFunction<F>, D: DualNum<F> + Copy, F: DualNumFloat, V> {
195 base: G::Parameters<D::Real>,
196 derivative: G::Parameters<D>,
197 phantom: PhantomData<V>,
198}
199
200impl<G: ImplicitFunction<F>, D: DualNum<F> + Copy, F: DualNum<F> + DualNumFloat>
201 ImplicitDerivative<G, D, F, G::Variable<f64>>
202where
203 G::Parameters<D>: DualStruct<D, F, Real = G::Parameters<F>>,
204{
205 pub fn new(_: G, parameters: G::Parameters<D>) -> Self {
206 Self {
207 base: parameters.re(),
208 derivative: parameters,
209 phantom: PhantomData,
210 }
211 }
212
213 pub fn residual(&self, x: G::Variable<F>) -> G::Variable<F> {
215 G::residual(x, &self.base)
216 }
217}
218
219impl<G: ImplicitFunction<F>, D: DualNum<F> + Copy, F: DualNum<F> + DualNumFloat>
220 ImplicitDerivative<G, D, F, F>
221where
222 G::Parameters<D>: DualStruct<D, F, Real = G::Parameters<F>>,
223{
224 pub fn implicit_derivative<A: DualStruct<Dual<D, F>, F, Inner = G::Parameters<D>>>(
226 &self,
227 x: F,
228 ) -> D
229 where
230 G: ImplicitFunction<F, Variable<Dual<D, F>> = Dual<D, F>, Parameters<Dual<D, F>> = A>,
231 {
232 implicit_derivative(G::residual::<Dual<D, F>>, x, &self.derivative)
233 }
234}
235
236impl<G: ImplicitFunction<F>, D: DualNum<F> + Copy, F: DualNum<F> + DualNumFloat>
237 ImplicitDerivative<G, D, F, [F; 2]>
238where
239 G::Parameters<D>: DualStruct<D, F, Real = G::Parameters<F>>,
240{
241 pub fn implicit_derivative<A: DualStruct<DualVec<D, F, U2>, F, Inner = G::Parameters<D>>>(
243 &self,
244 x: F,
245 y: F,
246 ) -> [D; 2]
247 where
248 G: ImplicitFunction<
249 F,
250 Variable<DualVec<D, F, U2>> = [DualVec<D, F, U2>; 2],
251 Parameters<DualVec<D, F, U2>> = A,
252 >,
253 {
254 implicit_derivative_binary(
255 |x, y, args: &A| G::residual::<DualVec<D, F, U2>>([x, y], args),
256 x,
257 y,
258 &self.derivative,
259 )
260 }
261}
262
263impl<G: ImplicitFunction<F>, D: DualNum<F> + Copy, F: DualNum<F> + DualNumFloat, const N: usize>
264 ImplicitDerivative<G, D, F, SVector<F, N>>
265where
266 G::Parameters<D>: DualStruct<D, F, Real = G::Parameters<F>>,
267{
268 pub fn implicit_derivative<A: DualStruct<DualSVec<D, F, N>, F, Inner = G::Parameters<D>>>(
270 &self,
271 x: SVector<F, N>,
272 ) -> SVector<D, N>
273 where
274 G: ImplicitFunction<
275 F,
276 Variable<DualSVec<D, F, N>> = SVector<DualSVec<D, F, N>, N>,
277 Parameters<DualSVec<D, F, N>> = A,
278 >,
279 {
280 implicit_derivative_vec(G::residual::<DualSVec<D, F, N>>, x, &self.derivative)
281 }
282}
283
284#[cfg(test)]
285mod test {
286 use super::*;
287 use nalgebra::SVector;
288
289 struct TestFunction;
290 impl ImplicitFunction<f64> for TestFunction {
291 type Parameters<D> = D;
292 type Variable<D> = D;
293
294 fn residual<D: DualNum<f64> + Copy>(x: D, square: &D) -> D {
295 *square - x * x
296 }
297 }
298
299 struct TestFunction2;
300 impl ImplicitFunction<f64> for TestFunction2 {
301 type Parameters<D> = (D, D);
302 type Variable<D> = [D; 2];
303
304 fn residual<D: DualNum<f64> + Copy>([x, y]: [D; 2], (square_sum, sum): &(D, D)) -> [D; 2] {
305 [*square_sum - x * x - y * y, *sum - x - y]
306 }
307 }
308
309 struct TestFunction3<const N: usize>;
310 impl<const N: usize> ImplicitFunction<f64> for TestFunction3<N> {
311 type Parameters<D> = D;
312 type Variable<D> = SVector<D, N>;
313
314 fn residual<D: DualNum<f64> + Copy>(x: SVector<D, N>, &square_sum: &D) -> SVector<D, N> {
315 let mut res = x;
316 for i in 1..N {
317 res[i] = x[i] - x[i - 1] - D::from(1.0);
318 }
319 res[0] = square_sum - x.dot(&x);
320 res
321 }
322 }
323
324 #[test]
325 fn test() {
326 let f: crate::Dual64 = Dual::from(25.0).derivative();
327 let func = ImplicitDerivative::new(TestFunction, f);
328 println!("{}", func.residual(5.0));
329 println!("{}", func.implicit_derivative(5.0));
330 println!("{}", f.sqrt());
331 assert_eq!(f.sqrt(), func.implicit_derivative(5.0));
332
333 let a: crate::Dual64 = Dual::from(25.0).derivative();
334 let b: crate::Dual64 = Dual::from(7.0);
335 let func = ImplicitDerivative::new(TestFunction2, (a, b));
336 println!("\n{:?}", func.residual([4.0, 3.0]));
337 let [x, y] = func.implicit_derivative(4.0, 3.0);
338 let xa = (b + (a * 2.0 - b * b).sqrt()) * 0.5;
339 let ya = (b - (a * 2.0 - b * b).sqrt()) * 0.5;
340 println!("{x}, {y}");
341 println!("{xa}, {ya}");
342 assert_eq!(x, xa);
343 assert_eq!(y, ya);
344
345 let s: crate::Dual64 = Dual::from(30.0).derivative();
346 let func = ImplicitDerivative::new(TestFunction3, s);
347 println!("\n{:?}", func.residual(SVector::from([1.0, 2.0, 3.0, 4.0])));
348 let x = func.implicit_derivative(SVector::from([1.0, 2.0, 3.0, 4.0]));
349 let x0 = ((s - 5.0).sqrt() - 5.0) * 0.5;
350 println!("{}, {}, {}, {}", x[0], x[1], x[2], x[3]);
351 println!("{}, {}, {}, {}", x0 + 1.0, x0 + 2.0, x0 + 3.0, x0 + 4.0);
352 assert_eq!(x0 + 1.0, x[0]);
353 assert_eq!(x0 + 2.0, x[1]);
354 assert_eq!(x0 + 3.0, x[2]);
355 assert_eq!(x0 + 4.0, x[3]);
356 }
357}