nacfahi 0.3.7

Simpler, but less error-prone API for `levenberg-marquardt` optimization crate
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
use core::{
    iter::Sum,
    ops::{Div, Mul},
};

use generic_array::{
    functional::FunctionalSequence,
    sequence::{Flatten, Unflatten},
    ArrayLength, GenericArray,
};
use generic_array_storage::Conv;
use typenum::{Prod, ToUInt};

/// Basic building blocks for the models.
pub mod basic;

/// Utility models for composing more complex models.
pub mod utility;

#[doc = include_str!("../../doc/derive_sum.md")]
pub use nacfahi_derive::FitModelSum;

#[doc(hidden)]
type TNum<const N: usize> = <typenum::Const<N> as ToUInt>::Output;

/// Defines object that can fit to a set of data points.
///
/// Generally, you have no reason to implement this trait, as there are model primitives and derive macro for that. Manual implementation is always an option though - I've left some hints, in case you're unfamiliar with the types.
pub trait FitModel {
    /// Type of `x`, `y`, model parameters and all the derivatives. Different types are not supported (yet)
    type Scalar;

    /// Type representing number of parameters.
    ///
    /// **Hint**: [`typenum`]`::{U1, U2, ..}` types would most likely work for you.
    ///
    /// [`typenum`]: https://docs.rs/typenum/latest/typenum/
    type ParamCount: generic_array_storage::Conv;

    /// Computes model value for supplied `x` value and current parameters.
    fn evaluate(&self, x: &Self::Scalar) -> Self::Scalar;

    /// Computes jacobian (array of derivatives) for supplied `x` value and current parameters.
    ///
    /// **Hint**: return type allows you to return core Rust array, as long as it's size is correct.
    fn jacobian(
        &self,
        x: &Self::Scalar,
    ) -> impl Into<GenericArray<Self::Scalar, <Self::ParamCount as generic_array_storage::Conv>::TNum>>;

    /// Sets model parameters to ones contained in a generic array
    ///
    /// **Hint**: `GenericArray::into_array` is a thing. So if your model has two params, you can extract them as
    /// ```rust
    /// # use generic_array::GenericArray;
    /// let new_params: GenericArray<_, typenum::U2> = /* ... */
    /// # GenericArray::from_array([(), ()]);
    /// let [p1, p2] = new_params.into_array();
    /// ```
    fn set_params(
        &mut self,
        new_params: GenericArray<
            Self::Scalar,
            <Self::ParamCount as generic_array_storage::Conv>::TNum,
        >,
    );

    /// Returns current values of model params.
    ///
    /// **Hint**: return type allows you to return core Rust array, as long as it's size is correct.
    fn get_params(
        &self,
    ) -> impl Into<GenericArray<Self::Scalar, <Self::ParamCount as generic_array_storage::Conv>::TNum>>;
}

/// Defines model having derivative over the `x` variable.
///
/// This trait is meant to extend [`FitModel`] to allow usage of [`Composition`](utility::Composition) model, as it requires derivative over `x` for outer model.
pub trait FitModelXDeriv: FitModel {
    /// Returns derivative over `x` at supplied `x` value.
    fn deriv_x(&self, x: &Self::Scalar) -> Self::Scalar;
}

/// Defines models having a corresponding error-defining type.
///
/// This trait is meant to extend [`FitModel`] to allow usage of [`macro@crate::fit_stat!`].
pub trait FitModelErrors: FitModel {
    /// Type of the error model
    ///
    /// Most of the time, this can be just `Self`.
    type OwnedModel: 'static;

    /// Creates new model representing errors from the error array
    fn with_errors(
        errors: GenericArray<Self::Scalar, <Self::ParamCount as generic_array_storage::Conv>::TNum>,
    ) -> Self::OwnedModel;
}

impl<Model> FitModel for &'_ mut Model
where
    Model: FitModel,
{
    type Scalar = Model::Scalar;
    type ParamCount = Model::ParamCount;

    #[inline]
    fn evaluate(&self, x: &Self::Scalar) -> Self::Scalar {
        let s: &Model = self;
        Model::evaluate(s, x)
    }

    #[inline]
    fn jacobian(
        &self,
        x: &Self::Scalar,
    ) -> impl Into<GenericArray<Self::Scalar, <Self::ParamCount as generic_array_storage::Conv>::TNum>>
    {
        let s: &Model = self;
        Model::jacobian(s, x)
    }

    #[inline]
    fn set_params(
        &mut self,
        new_params: GenericArray<
            Self::Scalar,
            <Self::ParamCount as generic_array_storage::Conv>::TNum,
        >,
    ) {
        let s: &mut Model = self;
        Model::set_params(s, new_params);
    }

    #[inline]
    fn get_params(
        &self,
    ) -> impl Into<GenericArray<Self::Scalar, <Self::ParamCount as generic_array_storage::Conv>::TNum>>
    {
        let s: &Model = self;
        Model::get_params(s)
    }
}

impl<Model: FitModelXDeriv> FitModelXDeriv for &'_ mut Model {
    #[inline]
    fn deriv_x(&self, x: &Model::Scalar) -> Model::Scalar {
        <Model as FitModelXDeriv>::deriv_x(self, x)
    }
}

impl<Model: FitModelErrors> FitModelErrors for &'_ mut Model {
    type OwnedModel = Model::OwnedModel;

    #[inline]
    fn with_errors(
        errors: GenericArray<
            Model::Scalar,
            <Self::ParamCount as generic_array_storage::Conv>::TNum,
        >,
    ) -> Self::OwnedModel {
        <Model as FitModelErrors>::with_errors(errors)
    }
}

#[cfg(test)]
static_assertions::assert_impl_all!([basic::Gaussian<f64>; 1]: FitModel);
#[cfg(test)]
static_assertions::assert_impl_all!([basic::Exponent<f64>; 5]: FitModel);

impl<const N: usize, Model> FitModel for [Model; N]
where
    Model: FitModel,
    Model::Scalar: Sum,
    typenum::Const<N>: ToUInt,
    TNum<N>: ArrayLength,
    <Model::ParamCount as generic_array_storage::Conv>::TNum: Mul<TNum<N>>,
    Prod<<Model::ParamCount as generic_array_storage::Conv>::TNum, TNum<N>>:
        generic_array_storage::Conv<
                TNum = Prod<<Model::ParamCount as generic_array_storage::Conv>::TNum, TNum<N>>,
            > + ArrayLength
            + Div<<Model::ParamCount as generic_array_storage::Conv>::TNum, Output = TNum<N>>,
{
    type Scalar = Model::Scalar;
    type ParamCount = Prod<<Model::ParamCount as generic_array_storage::Conv>::TNum, TNum<N>>;

    #[inline]
    fn evaluate(&self, x: &Model::Scalar) -> Model::Scalar {
        self.iter()
            .map(move |e| e.evaluate(x))
            .sum::<Model::Scalar>()
    }

    #[inline]
    fn jacobian(
        &self,
        x: &Model::Scalar,
    ) -> impl Into<GenericArray<Model::Scalar, <Self::ParamCount as Conv>::TNum>> {
        let jacobian_generic_arr: GenericArray<
            GenericArray<Model::Scalar, <Model::ParamCount as Conv>::TNum>,
            TNum<N>,
        > = GenericArray::from_array(self.each_ref().map(|entity| entity.jacobian(x).into()));
        jacobian_generic_arr.flatten()
    }

    #[inline]
    fn set_params(
        &mut self,
        new_params: GenericArray<Model::Scalar, <Self::ParamCount as Conv>::TNum>,
    ) {
        let unflat: GenericArray<
            GenericArray<_, <<Model as FitModel>::ParamCount as Conv>::TNum>,
            <typenum::Const<N> as ToUInt>::Output,
        > = new_params.unflatten();
        let inners: &mut GenericArray<Model, TNum<N>> =
            GenericArray::from_mut_slice(self.as_mut_slice());
        inners.zip(unflat, Model::set_params);
    }

    #[inline]
    fn get_params(
        &self,
    ) -> impl Into<GenericArray<Model::Scalar, <Self::ParamCount as Conv>::TNum>> {
        let jacobian_generic_arr: GenericArray<
            GenericArray<Model::Scalar, <Model::ParamCount as Conv>::TNum>,
            TNum<N>,
        > = GenericArray::from_array(self.each_ref().map(|entity| entity.get_params().into()));
        jacobian_generic_arr.flatten()
    }
}

impl<const N: usize, Model> FitModelXDeriv for [Model; N]
where
    Self: FitModel,
    Self::Scalar: Sum,
    Model: FitModelXDeriv<Scalar = Self::Scalar>,
{
    #[inline]
    fn deriv_x(&self, x: &Self::Scalar) -> Self::Scalar {
        self.iter().map(|m| m.deriv_x(x)).sum()
    }
}

impl<const N: usize, Model> FitModelErrors for [Model; N]
where
    Self: FitModel,
    Self::Scalar: Sum,
    typenum::Const<N>: ToUInt,
    TNum<N>: ArrayLength,
    Model: FitModelErrors<Scalar = Self::Scalar>,
    <Self::ParamCount as Conv>::TNum: Div<<Model::ParamCount as Conv>::TNum, Output = TNum<N>>,
{
    type OwnedModel = [Model::OwnedModel; N];

    #[inline]
    fn with_errors(
        errors: GenericArray<Self::Scalar, <Self::ParamCount as Conv>::TNum>,
    ) -> Self::OwnedModel {
        let unflat: GenericArray<
            GenericArray<_, <<Model as FitModel>::ParamCount as Conv>::TNum>,
            <typenum::Const<N> as ToUInt>::Output,
        > = errors.unflatten();
        unflat.map(Model::with_errors).into_array()
    }
}

#[cfg(doc)]
#[macro_export]
#[doc = include_str!("../../doc/test_model_derivative.md")]
macro_rules! test_model_derivative {
    (
        $isolation_module:ident,
        $model_type:path,
        $model_construction:expr,
        [$(($x:expr, $y:expr)),*]
    ) => {
        /* ... */
    };
    (
        $model_type:path,
        $model_construction:expr,
        [$(($x:expr, $y:expr)),*]
    ) => {
        /* ... */
    };
}

#[cfg(not(doc))]
#[macro_export]
#[doc = include_str!("../../doc/test_model_derivative.md")]
macro_rules! test_model_derivative {
    ($isolation:ident, $name:path, $model:expr, [$(($x:expr, $y:expr)),*]) => {
        #[cfg(test)]
        #[doc(hidden)]
        mod $isolation {
            #[allow(unused_imports)]
            use super::*;
            $crate::test_model_derivative!($name, $model, [$(($x, $y)), *]);
        }
    };
    ($name:path, $model:expr, [$(($x:expr, $y:expr)),*]) => {
        #[cfg(test)]
        #[test]
        #[cfg_attr(miri, ignore = "Miri gets angry because of stacked borrows rules somewhere inside nalgebra's storage. The thing is, my own storage implementation IS USED NEARBY (generic_array_storage one), so I AM SCARED PWEASE DON'T HUWT MW")]
        #[allow(clippy::too_many_lines, unused_imports)]
        fn model_numeric_test() {
            use ::generic_array_storage::{Conv, GenericMatrixExt, GenericMatrixFromExt};
            use ::nalgebra::{Matrix, Vector};
            use $crate::{AsMatrixView, models::FitModel, models::basic::*, models::utility::*};

            type Opt<'l, F> = $crate::const_problem::ConstOptimizationProblem<
                'l,
                ::typenum::Const<M>,
                $name,
                F,
            >;

            const N: usize = <<<$name as FitModel>::ParamCount as Conv>::TNum as typenum::Unsigned>::USIZE;
            const M: usize = [$($x),*].len();

            struct T<'l, F>(Opt<'l, F>);

            impl<F: Fn(f64, f64) -> f64>
                ::levenberg_marquardt::LeastSquaresProblem<
                    f64,
                    ::nalgebra::Const<M>,
                    ::nalgebra::Const<N>,
                > for T<'_, F>
            where
                Vector<f64, ::nalgebra::Const<N>, ::nalgebra::base::ArrayStorage<f64, N, 1>>:
                    ::generic_array_storage::GenericMatrixFromExt<
                        ::typenum::Const<N>,
                        ::typenum::Const<1>,
                    >,
            {
                type ResidualStorage = ::nalgebra::base::ArrayStorage<f64, M, 1>;
                type JacobianStorage = ::nalgebra::base::ArrayStorage<f64, M, N>;
                type ParameterStorage = ::nalgebra::base::ArrayStorage<f64, N, 1>;

                fn set_params(
                    &mut self,
                    x: &Vector<f64, ::nalgebra::Const<N>, Self::ParameterStorage>,
                ) {
                    let x: Vector<f64, ::nalgebra::Const<N>, Self::ParameterStorage> = x.clone();
                    <Opt<'_, F> as ::levenberg_marquardt::LeastSquaresProblem<
                        f64,
                        ::nalgebra::Const<M>,
                        ::nalgebra::Const<N>,
                    >>::set_params(&mut self.0, &x.into_generic_matrix());
                }

                fn params(&self) -> Vector<f64, ::nalgebra::Const<N>, Self::ParameterStorage> {
                    <Opt<'_, F> as ::levenberg_marquardt::LeastSquaresProblem<
                        f64,
                        ::nalgebra::Const<M>,
                        ::nalgebra::Const<N>,
                    >>::params(&self.0)
                    .into_regular_matrix()
                }

                fn residuals(
                    &self,
                ) -> Option<Vector<f64, ::nalgebra::Const<M>, Self::ResidualStorage>> {
                    Some(
                        <Opt<'_, F> as ::levenberg_marquardt::LeastSquaresProblem<
                            f64,
                            ::nalgebra::Const<M>,
                            ::nalgebra::Const<N>,
                        >>::residuals(&self.0)?
                        .into_regular_matrix()
                    )
                }

                fn jacobian(
                    &self,
                ) -> Option<
                    Matrix<f64, ::nalgebra::Const<M>, ::nalgebra::Const<N>, Self::JacobianStorage>,
                > {
                    Some(
                        <Opt<'_, F> as ::levenberg_marquardt::LeastSquaresProblem<
                            f64,
                            ::nalgebra::Const<M>,
                            ::nalgebra::Const<N>,
                        >>::jacobian(&self.0)?
                        .into_regular_matrix()
                    )
                }
            }

            // arrange
            let model = $model;
            let x = [$($x),*].convert();
            let y = [$($y),*].convert();
            let mut combined = T($crate::const_problem::ConstOptimizationProblem {
                model,
                x,
                y,
                weights: |_, _| 1.0,
            });

            // act
            let analytic =
                <T<'_, _> as ::levenberg_marquardt::LeastSquaresProblem<_, _, _>>::jacobian(
                    &combined,
                )
                .expect("Should be able to compute jacobian analytically");
            let numerical = ::levenberg_marquardt::differentiate_numerically(&mut combined)
                .expect("Should be able to compute jacobian numerically");

            // assert
            if !::approx::ulps_eq!(analytic, numerical, epsilon = 1e-6) {
                panic!(
                    "Different jacobian values:\n\tanalytic={analytic}\n\tnumerical={numerical}"
                );
            }
        }
    };
}