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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use ;
use crateBasisFunction;
use crateModelBasisFunctionBuilder;
use cratecheck_parameter_names;
use crateModelBasisFunction;
use crateSeparableModel;
use ModelBuildError;
/// contains the error for the model builder
/// A builder that allows us to construct a valid [SeparableModel],
/// which is an implementor of the [SeparableNonlinearModel](crate::model::SeparableNonlinearModel)
/// trait.
///
/// # Introduction
///
/// In the main crate we defined a separable model as a vector valued function
/// `$\vec{f}(\vec{\alpha},\vec{c})$`, but we are going to deviate from this
/// definition slightly here. We want to provide an *independent variable* `$\vec{x}$`
/// that the function depends on, to make a model usable on different supports.
///
/// To make the dependence on the independent variable explitict,
/// we now writethe separable model as
/// ```math
/// \vec{f}(\vec{x},\vec{\alpha},\vec{c}) = \sum_{j=1}^{N_{basis}} c_j \vec{f}_j(\vec{x},S_j(\alpha))
/// ```
///
/// The basis functions `$\vec{f}_j(\vec{x},S_j(\alpha))$` depend on the independent variable `$\vec{x}$`
/// and *a subset* `$S_j(\alpha)$` of the *nonlinear* model parameters `$\vec{\alpha}$`
/// just as in the other notation.
///
/// # Usage
/// The SeparableModelBuilder is concerned with building a model from basis functions and their derivatives.
/// This is done as a step by step process.
///
/// ## Constructing an Empty Builder
/// The first step is to create an empty builder by specifying the complete set of *nonlinear* parameters that
/// the model will be depending on. This is done by calling [SeparableModelBuilder::new](SeparableModelBuilder::new)
/// and specifying the list of parameters of the model by name.
///
/// ## Adding Basis Functions to The Model
///
/// Basis functions come in two flavors. Those that depend on a subset of the nonlinear parameters
/// `$\vec{\alpha}$` and those that do not. Both function types have to obey certain rules to
/// be considered valid:
///
/// **Function Arguments and Output**
///
/// * The first argument of the function must be a reference to a `&DVector` type
/// that accepts the independent variable (the `$\vec{x}$` values) and the other
/// parameters must be scalars that are the nonlinear parameters that the basis
/// function depends on.
///
/// So if we want to model a basis function `$\vec{f_1}(\vec{x},\vec{\alpha})$`
/// where `$\vec{\alpha}=(\alpha_1,\alpha_2)$` we would write the function in Rust as
///
/// ```rust
/// # use nalgebra::DVector;
/// fn f1(x: &DVector<f32>, alpha1: f32, alpha2: f32) -> DVector<f32> {
/// // e.g. for sinusoidal function with frequency alpha1 and phase alpha2
/// // apply the function elementwise to the vector x
/// x.map(|x| f32::sin(alpha1*x+alpha2))
/// }
/// ```
/// using single precision (`f32`) floats.
///
/// **Linear Independence**
///
/// The basis functions must be linearly independent. That means adding `$\vec{f_1}(\vec{x})=\vec{x}$`
/// and `$\vec{f_1}(\vec{x})=2\,\vec{x}$` is forbidden. Adding functions that
/// are lineary dependent will possibly destabilize the fitting process.
/// the calculations. Adding linearly dependent functions is also a bad idea
/// because it adds no value due to the linear superposition of the basis functions.
///
/// For some models, e.g. sums of exponential decays it might happen that the basis functions become
/// linearly dependent *for some combinations* of nonlinear model parameters. This isn't great but it is
/// okay, since the VarPro algorithm in this crate exhibits a degree of robustness against basis functions
/// becoming collinear. The linear solver backends automatically handle numerical stability by using
/// appropriate tolerance values for rank determination.
///
/// ### Invariant Basis Functions
///
/// Basis functions that do not depend on model parameters are treated specially. The library refers
/// to them as *invariant functions* and they are added to a builder by calling
/// [SeparableModelBuilder::invariant_function](SeparableModelBuilder::invariant_function). Since
/// the basis function depends only on `$\vec{x}$` it can be written as `$\vec{f}_j(\vec{x})$`. In Rust
/// this translates to a signature `Fn(&DVector<ScalarType>) -> DVector<ScalarType> + 'static` for the callable.
///
/// **Example**: Calling [SeparableModelBuilder::invariant_function](SeparableModelBuilder::invariant_function)
/// adds the function to the model. These calls can be chained to add more functions.
///
/// ```rust
/// use nalgebra::DVector;
/// use varpro::prelude::SeparableModelBuilder;
/// fn squared(x: &DVector<f64>) -> DVector<f64> {
/// x.map(|x|x.powi(2))
/// }
///
/// let builder = SeparableModelBuilder::<f64>::new(&["alpha","beta"])
/// // we can add an invariant function using a function pointer
/// .invariant_function(squared)
/// // or we can add it using a lambda
/// .invariant_function(|x|x.map(|x|(x+1.).sin()));
///```
/// Caveat: we cannot successfully build a model containing only invariant functions. It would
/// make no sense to use the varpro library to fit such a model because that is purely a linear
/// least squares problem. See the next section for adding parameter dependent functions.
///
/// ### Nonlinear Basis Functions
///
/// The core functionality of the builder is to add basis functions to the model
/// that depend nonlinearly on some (or all) of the model parameters `$\vec{\alpha}$`.
/// We add a basis function to a builder by calling `builder.function`. Each call must
/// be immediately followed by calls to `partial_deriv` for each of the parameters that the basis
/// function depends on.
///
/// #### Rules for Model Functions
///
/// There are several rules for adding model basis functions. One of them is enforced by the compiler,
/// some of them are enforced at runtime (when trying to build the model) and others simply cannot
/// be enforced by the library.
///
/// ** Rules You Must Abide By **
///
/// * Basis functions must be **nonlinear** in the parameters they take. If they aren't, you can always
/// rewrite the problem so that the linear parameters go in the coefficient vector `$\vec{c}$`. This
/// means that each partial derivative also depend on all the parameters that the basis function depends
/// on.
///
/// * Derivatives must take the same parameter arguments *and in the same order* as the original
/// basis function. This means if basis function `$\vec{f}_j$` is given as `$\vec{f}_j(\vec{x},a,b)$`,
/// then the derivatives must also be given with the parameters `$a,b$` in the same order, i.e.
/// `$\partial/\partial a \vec{f}_j(\vec{x},a,b)$`, `$\partial/\partial b \vec{f}_j(\vec{x},a,b)$`.
///
/// **Rules Enforced at Compile Time**
///
/// * Partial derivatives cannot be added to invariant functions.
///
/// **Rules Enforced at Runtime**
///
/// * A partial derivative must be given for each parameter that the basis function depends on.
/// * Basis functions may only depend on the parameters that the model depends on.
///
///
/// The builder allows us to provide basis functions for a separable model as a step by step process.
///
/// ## Example
///
/// Let's build a model that is the sum of an exponential decay `$\exp(-t/\tau)$`
/// and a sine function `$\sin(\omega t + \phi)$`. The model depends on the parameters `$\tau$`,
/// `$\omega$` and `$\phi$`. The exponential decay depends only on `$\tau$` and the sine function
/// depends on `$\omega$` and `$\phi$`. The model is given by
///
/// ```math
/// f(t,\tau,\omega,\phi) = \exp(-t/\tau) + \sin(\omega t + \phi)
/// ```
/// which is a reasonable nontrivial model to demonstrate the usage of the library.
///
/// ```rust
/// // exponential decay f(t,tau) = exp(-t/tau)
/// use nalgebra::{Scalar, DVector};
/// use num_traits::Float;
/// use varpro::prelude::SeparableModelBuilder;
/// pub fn exp_decay<ScalarType: Float + Scalar>(
/// tvec: &DVector<ScalarType>,
/// tau: ScalarType,
/// ) -> DVector<ScalarType> {
/// tvec.map(|t| (-t / tau).exp())
/// }
///
/// // derivative of exp decay with respect to tau
/// pub fn exp_decay_dtau<ScalarType: Scalar + Float>(
/// tvec: &DVector<ScalarType>,
/// tau: ScalarType,
/// ) -> DVector<ScalarType> {
/// tvec.map(|t| (-t / tau).exp() * t / (tau * tau))
/// }
///
/// // function sin (omega*t+phi)
/// pub fn sin_ometa_t_plus_phi<ScalarType: Scalar + Float>(
/// tvec: &DVector<ScalarType>,
/// omega: ScalarType,
/// phi: ScalarType,
/// ) -> DVector<ScalarType> {
/// tvec.map(|t| (omega * t + phi).sin())
/// }
///
/// // derivative d/d(omega) sin (omega*t+phi)
/// pub fn sin_ometa_t_plus_phi_domega<ScalarType: Scalar + Float>(
/// tvec: &DVector<ScalarType>,
/// omega: ScalarType,
/// phi: ScalarType,
/// ) -> DVector<ScalarType> {
/// tvec.map(|t| t * (omega * t + phi).cos())
/// }
///
/// // derivative d/d(phi) sin (omega*t+phi)
/// pub fn sin_ometa_t_plus_phi_dphi<ScalarType: Scalar + Float>(
/// tvec: &DVector<ScalarType>,
/// omega: ScalarType,
/// phi: ScalarType,
/// ) -> DVector<ScalarType> {
/// tvec.map(|t| (omega * t + phi).cos())
/// }
///
/// let x_coords = DVector::from_vec(vec![0.,1.,2.,3.,4.,5.]);
/// let initial_guess = vec![1.,1.,1.];
///
/// let model = SeparableModelBuilder::<f64>::new(&["tau","omega","phi"])
/// // the x coordintates that this model
/// // is evaluated on
/// .independent_variable(x_coords)
/// // add the exp decay and all derivatives
/// .function(&["tau"],exp_decay)
/// .partial_deriv("tau",exp_decay_dtau)
/// // a new call to function finalizes adding the previous function
/// .function(&["omega","phi"],sin_ometa_t_plus_phi)
/// .partial_deriv("phi", sin_ometa_t_plus_phi_dphi)
/// .partial_deriv("omega",sin_ometa_t_plus_phi_domega)
/// // we can also add invariant functions. Same as above, the
/// // call tells the model builder that the previous function has all
/// // the partial derivatives finished
/// .invariant_function(|x|x.clone())
/// // the initial nonlinear parameters
/// // of the model
/// .initial_parameters(initial_guess)
/// // we build the model calling build. This returns either a valid model
/// // or an error variant which is pretty helpful in understanding what went wrong
/// .build().unwrap();
/// ```
///
/// There is some [special macro magic](https://geo-ant.github.io/blog/2021/rust-traits-and-variadic-functions/)
/// that allows us to pass a function `$f(\vec{x},a_1,..,a_n)$`
/// as any item that implements the Rust trait `Fn(&DVector<ScalarType>, ScalarType,... ,ScalarType)->DVector<ScalarType> + 'static`.
/// This allows us to write the functions in an intuitive fashion in Rust code. All nonlinear parameters `$\alpha$`
/// are simply scalar arguments in the parameter list of the function. This works for functions
/// taking up to 10 nonlinear arguments, but can be extended easily by modifying this crates source.
///
///
/// ## Building a Model
///
/// The model is finalized and built using the [SeparableModelBuilder::build](SeparableModelBuilder::build)
/// method. This method returns a valid model or an error variant doing a pretty good job of
/// explaning why the model is invalid.
/// a helper structure that represents an unfinished separable model
/// create a SeparableModelBuilder which contains an error variant
/// create a SeparableModelBuilder with the given result variant
/// try to convert an unfinished model into a valid model
/// # Returns
/// If the model is valid, then the model is returned as an ok variant, otherwise an error variant
/// A model is valid, when
/// * the model has at least one modelfunction, and
/// * for each model parameter we have at least one function that depends on this
/// parameter.
/// try and extend a model with the given function in the builder
/// if building the function in the builder fails, an error is returned,
/// otherwise the extended model is returned