libitofin 0.7.0

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
//! Calibrated model base.
//!
//! Port of the [`CalibratedModel`] parts of `ql/models/model.{hpp,cpp}` needed
//! by the closed-form affine path: the [`Parameter`] storage, `params()` /
//! `set_params()`, and the [`PrivateConstraint`] over the arguments. A concrete
//! model embeds a `CalibratedModel` the way a curve embeds a
//! [`TermStructureBase`](crate::termstructures::TermStructureBase), delegates
//! its parameter machinery, and exposes the shared [`Observable`] through
//! [`AsObservable`].
//!
//! The observer-driven regeneration C++ runs in `update()` =
//! `generateArguments()` + `notifyObservers()` (`model.hpp:87`) is wired by
//! [`register_with_term_structure`]: it registers a concrete model as an
//! observer of its term-structure handle so a relink re-runs
//! [`generate_arguments`](CalibratedModelHolder::generate_arguments) and then
//! re-broadcasts. It is opt-in per model, matching C++, where Hull-White / G2
//! `registerWith(termStructure)` but ExtendedCoxIngersollRoss does not.
//!
//! ## Divergences from QuantLib
//!
//! - C++'s `PrivateConstraint::Impl` holds `const std::vector<Parameter>&`
//!   aliasing the model's own `arguments_` (`model.hpp:168,223`), a
//!   self-referential borrow Rust cannot hold. [`CalibratedModel::constraint`]
//!   instead builds the [`PrivateConstraint`] on demand from a clone of the
//!   current arguments. It is consumed only by the deferred `calibrate()`, so
//!   it is unexercised by the affine oracle.
//! - C++'s `setParams` always calls the virtual `generateArguments()`
//!   (`model.cpp:146`); a subclass override is dispatched through the base. An
//!   embedded [`CalibratedModel`] cannot dispatch up into the concrete type, so
//!   the regenerating `setParams` lives on the [`CalibratedModelHolder`] trait
//!   the concrete model implements, and [`CalibratedModel::set_params`] itself
//!   only writes and notifies (the base's `generateArguments()` is a no-op).
//!   Writing through the embedded model directly therefore bypasses
//!   regeneration - a fitted model must route parameter changes through its
//!   holder [`set_params`](CalibratedModelHolder::set_params). The
//!   [`CalibrationFunction`] wired by [`calibrate`] does exactly that, so a
//!   fitted model regenerates its curve-derived state on every parameter move.
//! - C++'s `CalibrationFunction::value`/`values` propagate a `calibrationError`
//!   throw (`model.cpp:50,60`); the [`CostFunction`] trait here is infallible,
//!   so a failed [`calibration_error`](CalibrationHelper::calibration_error) (or
//!   a rejected `set_params`) maps to a non-finite residual the optimizer's
//!   penalty path steers away from (the same guard the Levenberg-Marquardt
//!   adapter applies). [`calibration_value`] therefore returns `Ok(NAN)` where
//!   C++ would throw.
//! - The holder [`set_params`](CalibratedModelHolder::set_params) notifies while
//!   the model's `borrow_mut` is still live, so a model observer that reads the
//!   model back during the notification would panic. Calibration engines are
//!   `LazyObject`s that only defer on notification (they read the model later,
//!   inside `calibration_error`, after the borrow is dropped), so the affine
//!   path is safe; the per-instrument loop drops the `borrow_mut` before pricing
//!   for exactly that reason (D1).

use crate::errors::QlResult;
use crate::handle::Handle;
use crate::math::array::Array;
use crate::math::optimization::constraint::{CompositeConstraint, Constraint};
use crate::math::optimization::costfunction::CostFunction;
use crate::math::optimization::endcriteria::{EndCriteria, EndCriteriaType};
use crate::math::optimization::method::OptimizationMethod;
use crate::math::optimization::problem::Problem;
use crate::math::optimization::projectedconstraint::ProjectedConstraint;
use crate::math::optimization::projection::Projection;
use crate::models::calibrationhelper::CalibrationHelper;
use crate::models::parameter::Parameter;
use crate::patterns::observable::{AsObservable, Observable, Observer, ResetThenNotify};
use crate::require;
use crate::shared::{Shared, SharedMut, shared};
use crate::termstructures::yieldtermstructure::YieldTermStructure;
use crate::types::{Integer, Real, Size};

/// Calibrated model class (`model.hpp:86`).
///
/// Both [`Observable`] (pricing engines observe the model) and, through its
/// [`as_observer`](CalibratedModel::as_observer) handle, an observer half that
/// regenerates and re-broadcasts when observed market data changes (C++'s
/// `update()` = `generateArguments()` + `notifyObservers()`, `model.hpp:90`).
pub struct CalibratedModel {
    arguments: Vec<Parameter>,
    observable: Shared<Observable>,
    updater: SharedMut<ResetThenNotify>,
    end_criteria: EndCriteriaType,
    problem_values: Array,
    function_evaluation: Integer,
}

impl CalibratedModel {
    /// `CalibratedModel(Size nArguments)` (`model.cpp:32`): `n_arguments`
    /// placeholder parameters the concrete model overwrites in its constructor.
    pub fn new(n_arguments: Size) -> CalibratedModel {
        let observable = shared(Observable::new());
        let updater = ResetThenNotify::forwarding(Shared::clone(&observable));
        CalibratedModel {
            arguments: vec![Parameter::default(); n_arguments],
            observable,
            updater,
            end_criteria: EndCriteriaType::None,
            problem_values: Array::new(),
            function_evaluation: 0,
        }
    }

    /// The model's arguments, for a concrete model's inspectors
    /// (C++'s protected `arguments_`).
    pub fn arguments(&self) -> &[Parameter] {
        &self.arguments
    }

    /// The model's arguments for a concrete model's constructor to populate.
    /// The count is fixed at [`new`](CalibratedModel::new), so this is a slice:
    /// a subclass sets each argument but cannot resize the vector out from
    /// under `params()` or the constraint. Public because Rust has no
    /// "protected": this is the model-building surface C++ exposes to subclasses.
    pub fn arguments_mut(&mut self) -> &mut [Parameter] {
        &mut self.arguments
    }

    /// `params()` (`model.cpp:126`): the arguments' values flattened in order.
    pub fn params(&self) -> Array {
        let size = self.arguments.iter().map(Parameter::size).sum();
        let mut params = Array::with_size(size);
        let mut k = 0;
        for argument in &self.arguments {
            for j in 0..argument.size() {
                params[k] = argument.params()[j];
                k += 1;
            }
        }
        params
    }

    /// Re-slices `params` back into the arguments in order, without notifying:
    /// the `setParams` re-slice loop (`model.cpp:139-146`) split out so a
    /// [`CalibratedModelHolder`] can regenerate derived state before it notifies
    /// (D1: no observer runs until every mutation is done).
    ///
    /// # Errors
    ///
    /// Fails if `params` has too few values for the arguments
    /// (`"parameter array too small"`) or too many
    /// (`"parameter array too big!"`).
    pub fn write_params(&mut self, params: &Array) -> QlResult<()> {
        let mut p = 0;
        for argument in &mut self.arguments {
            for j in 0..argument.size() {
                require!(p < params.size(), "parameter array too small");
                argument.set_param(j, params[p]);
                p += 1;
            }
        }
        require!(p == params.size(), "parameter array too big!");
        Ok(())
    }

    /// `setParams(const Array&)` (`model.cpp:138`): re-slices `params` back into
    /// the arguments in order, then notifies. The C++ base also calls the
    /// virtual `generateArguments()` (a no-op for the base and for Vasicek); a
    /// model whose `generateArguments()` is not a no-op must instead route
    /// through [`CalibratedModelHolder::set_params`], which regenerates before
    /// notifying.
    ///
    /// # Errors
    ///
    /// Fails if `params` has too few or too many values for the arguments.
    pub fn set_params(&mut self, params: &Array) -> QlResult<()> {
        self.write_params(params)?;
        self.observable.notify_observers();
        Ok(())
    }

    /// `constraint()` (`model.hpp:159`): the [`PrivateConstraint`] over the
    /// current arguments, rebuilt from a snapshot on each call.
    pub fn constraint(&self) -> PrivateConstraint {
        PrivateConstraint {
            arguments: self.arguments.clone(),
        }
    }

    /// `endCriteria()` (`model.hpp:112`): the criterion the last
    /// [`calibrate`] run ended on, or [`EndCriteriaType::None`] if never run.
    pub fn end_criteria(&self) -> EndCriteriaType {
        self.end_criteria
    }

    /// `problemValues()` (`model.hpp:115`): the per-instrument residuals at the
    /// calibrated point, empty until [`calibrate`] runs.
    pub fn problem_values(&self) -> &Array {
        &self.problem_values
    }

    /// `functionEvaluation()` (`model.hpp:121`): the cost-function evaluation
    /// count of the last [`calibrate`] run.
    pub fn function_evaluation(&self) -> Integer {
        self.function_evaluation
    }

    /// This model's observer half, wired to its observable (C++'s
    /// `CalibratedModel` publicly *is* an `Observer`). Register it with an
    /// observed observable so a change re-broadcasts.
    ///
    /// This is the pure-forwarding half: it re-broadcasts but does not re-run a
    /// concrete model's `generate_arguments()`. A term-structure-consistent
    /// model that must regenerate curve-derived state on a relink registers
    /// through [`register_with_term_structure`] instead.
    pub fn as_observer(&self) -> SharedMut<dyn Observer> {
        self.updater.clone() as SharedMut<dyn Observer>
    }

    /// The embedded observable as a shared handle, so the relink observer can
    /// notify after releasing its `borrow_mut` on the model (D1: no borrow is
    /// held across the notification). Mirrors the way [`Link::link_to`] hands
    /// its observable back for a notify outside the link borrow.
    ///
    /// [`Link::link_to`]: crate::handle::Handle
    fn shared_observable(&self) -> Shared<Observable> {
        self.observable.clone()
    }
}

impl AsObservable for CalibratedModel {
    fn observable(&self) -> &Observable {
        &self.observable
    }
}

/// The regeneration seam C++ puts on [`CalibratedModel`]: the virtual
/// `generateArguments()` and the `setParams` path that invokes it
/// (`model.hpp:88`, `model.cpp:138`).
///
/// A concrete model embeds a [`CalibratedModel`], which - unlike the C++ base -
/// cannot virtual-dispatch up into the concrete type. The overridable
/// `generateArguments()` hook therefore lives here, on a trait the concrete
/// model implements over its embedded model. A model whose C++
/// `generateArguments()` is the base no-op (Vasicek) can leave the defaults; a
/// term-structure-fitted model overrides
/// [`generate_arguments`](Self::generate_arguments) to rebuild the parameters
/// derived from its arguments, and both its constructor and any parameter change
/// go through this seam.
pub trait CalibratedModelHolder {
    /// The embedded [`CalibratedModel`].
    fn calibrated_model(&self) -> &CalibratedModel;

    /// The embedded [`CalibratedModel`], mutably.
    fn calibrated_model_mut(&mut self) -> &mut CalibratedModel;

    /// `generateArguments()` (`model.hpp:154`): rebuild the parameters derived
    /// from the model's arguments. The base is a no-op.
    fn generate_arguments(&mut self) {}

    /// `setParams(const Array&)` (`model.cpp:138`): re-slice `params` into the
    /// arguments, regenerate derived state, then notify - in that order, so no
    /// observer runs until every mutation is done (D1).
    ///
    /// # Errors
    ///
    /// Fails if `params` has too few or too many values for the arguments.
    fn set_params(&mut self, params: &Array) -> QlResult<()> {
        self.calibrated_model_mut().write_params(params)?;
        self.generate_arguments();
        self.calibrated_model().observable().notify_observers();
        Ok(())
    }
}

/// Term-structure consistent model base (`model.hpp:73`): holds the
/// [`YieldTermStructure`] handle a fitted model reprices exactly, and exposes it.
///
/// C++'s class is `public virtual Observable`; here it is a plain holder. A
/// concrete fitted model embeds both this and a [`CalibratedModel`] (C++
/// multiply-inherits them). Whether the model *observes* the handle is a
/// per-model choice made in the concrete constructor: Hull-White / G2 / GSR
/// `registerWith(termStructure)`, but ExtendedCoxIngersollRoss (the affine
/// fitting oracle) deliberately does not, because its fitting law reads the
/// handle live on every evaluation.
pub struct TermStructureConsistentModel {
    term_structure: Handle<dyn YieldTermStructure>,
}

impl TermStructureConsistentModel {
    /// `TermStructureConsistentModel(Handle<YieldTermStructure>)`
    /// (`model.hpp:75`).
    pub fn new(term_structure: Handle<dyn YieldTermStructure>) -> TermStructureConsistentModel {
        TermStructureConsistentModel { term_structure }
    }

    /// `termStructure()` (`model.hpp:77`): the fitted curve handle.
    pub fn term_structure(&self) -> &Handle<dyn YieldTermStructure> {
        &self.term_structure
    }
}

/// Registers `model` as an observer of its term-structure `handle`, so a relink
/// or a change inside the linked curve re-runs the concrete model's
/// [`generate_arguments`](CalibratedModelHolder::generate_arguments) and then
/// re-broadcasts - the observation half C++ wires with
/// `registerWith(termStructure)` (`hullwhite.cpp:41`), whose inherited
/// `CalibratedModel::update()` is `generateArguments()` + `notifyObservers()`
/// (`model.hpp:87`). `handle` must be the same handle the model reads in
/// `generate_arguments` (handle clones share one link), or the model would
/// regenerate off a stale curve.
///
/// Opt-in per model, matching C++: a term-structure-consistent model that reads
/// its curve live on every evaluation (`ExtendedCoxIngersollRoss`, which does
/// not `registerWith` the curve) never calls this, so a relink does not
/// regenerate; a model caching curve-derived scalars (Hull-White's `r0`/`phi`)
/// does.
///
/// Returns the observer, which the model must keep alive: the handle holds only
/// a weak back-reference to it, and it holds only a weak reference to the model,
/// so a dropped model or a dropped observer prunes cleanly and no reference
/// cycle forms. On notification the regeneration takes the model's `borrow_mut`
/// and releases it before notifying, so an observer that reads the model back
/// during the notification (a pricing engine calling `discount_bond`, a cached
/// scalar) sees the regenerated state (D1: no borrow held across the notify).
pub fn register_with_term_structure<M: CalibratedModelHolder + 'static>(
    model: &SharedMut<M>,
    handle: &Handle<dyn YieldTermStructure>,
) -> SharedMut<dyn Observer> {
    let observable = model.borrow().calibrated_model().shared_observable();
    let weak = SharedMut::downgrade(model);
    let observer = ResetThenNotify::broadcasting(observable, move || {
        if let Some(model) = weak.upgrade() {
            model.borrow_mut().generate_arguments();
        }
    }) as SharedMut<dyn Observer>;
    handle.register_observer(&observer);
    observer
}

/// The calibration cost function (`model.cpp:35`): on each evaluation it writes
/// the projected parameters back into the model and returns the (weighted)
/// per-instrument [`calibration_error`](CalibrationHelper::calibration_error)s.
///
/// C++ holds a non-owning `CalibratedModel*` (`model.cpp:41`, `null_deleter`)
/// and mutates the model on every cost call while `Problem`/`minimize` also
/// borrow the function; here it holds a [`SharedMut`] clone of the same model
/// handle (no second ownership path) and interior-mutates through it, so a
/// `&dyn CostFunction` can drive the model. It routes through the holder
/// [`set_params`](CalibratedModelHolder::set_params) so a fitted model
/// regenerates its derived state on every parameter move.
struct CalibrationFunction<M: CalibratedModelHolder> {
    model: SharedMut<M>,
    instruments: Vec<SharedMut<dyn CalibrationHelper>>,
    weights: Vec<Real>,
    projection: Projection,
}

impl<M: CalibratedModelHolder> CalibrationFunction<M> {
    /// Writes `full` into the model through the holder seam, dropping the
    /// `borrow_mut` before returning so the caller's per-instrument loop can
    /// price without a live model borrow. Returns whether the write succeeded.
    fn set_params(&self, full: &Array) -> bool {
        self.model.borrow_mut().set_params(full).is_ok()
    }
}

impl<M: CalibratedModelHolder> CostFunction for CalibrationFunction<M> {
    /// `values` (`model.cpp:56`): each entry is
    /// `calibration_error() * sqrt(weight)`. A failed write or
    /// [`calibration_error`](CalibrationHelper::calibration_error) becomes a
    /// non-finite residual the optimizer's penalty path rejects (the trait is
    /// infallible; see the module divergence note).
    fn values(&self, params: &Array) -> Array {
        let full = self.projection.include(params);
        let n = self.instruments.len();
        if !self.set_params(&full) {
            return Array::filled(n, Real::NAN);
        }
        let mut values = Array::with_size(n);
        for (i, instrument) in self.instruments.iter().enumerate() {
            values[i] = match instrument.borrow_mut().calibration_error() {
                Ok(error) => error * self.weights[i].sqrt(),
                Err(_) => Real::NAN,
            };
        }
        values
    }

    /// `value` (`model.cpp:46`): `sqrt(sum_i diff_i^2 * w_i)`. Overrides the
    /// default root-*mean*-square (which divides by the residual count) to match
    /// C++'s plain root-sum-of-squares.
    fn value(&self, params: &Array) -> Real {
        let full = self.projection.include(params);
        if !self.set_params(&full) {
            return Real::NAN;
        }
        let mut value = 0.0;
        for (i, instrument) in self.instruments.iter().enumerate() {
            let diff = match instrument.borrow_mut().calibration_error() {
                Ok(error) => error,
                Err(_) => return Real::NAN,
            };
            value += diff * diff * self.weights[i];
        }
        value.sqrt()
    }

    /// `finiteDifferenceEpsilon` (`model.cpp:66`). Consulted only when the
    /// method uses the cost function's own Jacobian; the Levenberg-Marquardt
    /// default uses its own forward-difference step.
    fn finite_difference_epsilon(&self) -> Real {
        1e-6
    }
}

/// `CalibratedModel::calibrate` (`model.cpp:75`): fits `model`'s free arguments
/// to `instruments` with `method`, then writes the fitted parameters, the end
/// criterion, the residuals and the evaluation count back onto the model and
/// notifies its observers.
///
/// Shaped as a free function over a [`SharedMut`] model, mirroring
/// [`register_with_term_structure`]: the [`CalibrationFunction`] must interior-
/// mutate the model while [`Problem`] borrows it as a `&dyn CostFunction`, which
/// a `&mut self` method on the holder could not express.
///
/// `additional_constraint` is `None` for C++'s default empty `Constraint()`, or
/// `Some(c)` to intersect `c` with the model's own private constraint.
///
/// # Errors
///
/// Fails on empty `instruments`, a `weights` or `fix_parameters` length that
/// does not match, an all-fixed projection, or a failure of `method.minimize`.
pub fn calibrate<M: CalibratedModelHolder>(
    model: &SharedMut<M>,
    instruments: &[SharedMut<dyn CalibrationHelper>],
    method: &mut dyn OptimizationMethod,
    end_criteria: &EndCriteria,
    additional_constraint: Option<Box<dyn Constraint>>,
    weights: Vec<Real>,
    fix_parameters: Vec<bool>,
) -> QlResult<()> {
    require!(!instruments.is_empty(), "no instruments provided");

    let private = model.borrow().calibrated_model().constraint();
    let constraint: Box<dyn Constraint> = match additional_constraint {
        None => Box::new(private),
        Some(additional) => Box::new(CompositeConstraint::new(private, additional)),
    };

    require!(
        weights.is_empty() || weights.len() == instruments.len(),
        "mismatch between number of instruments ({}) and weights ({})",
        instruments.len(),
        weights.len()
    );
    let weights = if weights.is_empty() {
        vec![1.0; instruments.len()]
    } else {
        weights
    };

    let prms = model.borrow().calibrated_model().params();
    require!(
        fix_parameters.is_empty() || fix_parameters.len() == prms.size(),
        "mismatch between number of parameters ({}) and fixed-parameter specs ({})",
        prms.size(),
        fix_parameters.len()
    );
    let projection = Projection::new(&prms, fix_parameters)?;
    let projected_constraint = ProjectedConstraint::new(constraint, projection.clone());
    let function = CalibrationFunction {
        model: SharedMut::clone(model),
        instruments: instruments.to_vec(),
        weights,
        projection: projection.clone(),
    };
    let mut problem = Problem::new(&function, &projected_constraint, projection.project(&prms));
    let end_criteria_result = method.minimize(&mut problem, end_criteria)?;
    let result = problem.current_value().clone();
    model
        .borrow_mut()
        .set_params(&projection.include(&result))?;
    let problem_values = problem.values(&result);
    let function_evaluation = problem.function_evaluation();

    {
        let mut borrowed = model.borrow_mut();
        let calibrated = borrowed.calibrated_model_mut();
        calibrated.end_criteria = end_criteria_result;
        calibrated.problem_values = problem_values;
        calibrated.function_evaluation = function_evaluation;
    }
    model
        .borrow()
        .calibrated_model()
        .observable()
        .notify_observers();
    Ok(())
}

/// `CalibratedModel::value` (`model.cpp:117`): the calibration cost of `params`
/// against `instruments` under unit weights and an identity projection. Like
/// C++ it writes `params` into the model as a side effect.
///
/// # Errors
///
/// Fails if `params` is empty (no free parameters for the identity projection).
pub fn calibration_value<M: CalibratedModelHolder>(
    model: &SharedMut<M>,
    params: &Array,
    instruments: &[SharedMut<dyn CalibrationHelper>],
) -> QlResult<Real> {
    let weights = vec![1.0; instruments.len()];
    let projection = Projection::new(params, Vec::new())?;
    let function = CalibrationFunction {
        model: SharedMut::clone(model),
        instruments: instruments.to_vec(),
        weights,
        projection,
    };
    Ok(function.value(params))
}

/// Constraint imposed on a [`CalibratedModel`]'s arguments (`model.hpp:164`).
///
/// Owns a snapshot of the arguments (see the module divergence note) and, for
/// each, slices the flat parameter array into that argument's share, in order,
/// delegating to the argument's own constraint (`model.hpp:171-220`).
pub struct PrivateConstraint {
    arguments: Vec<Parameter>,
}

impl PrivateConstraint {
    fn bound(&self, params: &Array, f: impl Fn(&dyn Constraint, &Array) -> Array) -> Array {
        let total: Size = self.arguments.iter().map(Parameter::size).sum();
        let mut result = Array::with_size(total);
        let mut k = 0;
        let mut k2 = 0;
        for argument in &self.arguments {
            let size = argument.size();
            let mut partial = Array::with_size(size);
            for j in 0..size {
                partial[j] = params[k];
                k += 1;
            }
            let tmp = f(argument.constraint(), &partial);
            for j in 0..size {
                result[k2] = tmp[j];
                k2 += 1;
            }
        }
        result
    }
}

impl Constraint for PrivateConstraint {
    fn test(&self, params: &Array) -> bool {
        let mut k = 0;
        for argument in &self.arguments {
            let size = argument.size();
            let mut test_params = Array::with_size(size);
            for j in 0..size {
                test_params[j] = params[k];
                k += 1;
            }
            if !argument.test_params(&test_params) {
                return false;
            }
        }
        true
    }

    fn upper_bound(&self, params: &Array) -> Array {
        self.bound(params, |constraint, partial| {
            constraint.upper_bound(partial)
        })
    }

    fn lower_bound(&self, params: &Array) -> Array {
        self.bound(params, |constraint, partial| {
            constraint.lower_bound(partial)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handle::RelinkableHandle;
    use crate::interestrate::Compounding;
    use crate::math::optimization::constraint::{NoConstraint, PositiveConstraint};
    use crate::math::optimization::levenbergmarquardt::LevenbergMarquardt;
    use crate::models::calibrationhelper::CalibrationHelper;
    use crate::models::parameter::ConstantParameter;
    use crate::patterns::observable::Observer;
    use crate::shared::{Shared, SharedMut, WeakMut, shared, shared_mut};
    use crate::termstructures::yields::FlatForward;
    use crate::time::date::{Date, Month};
    use crate::time::daycounters::actual360::Actual360;
    use crate::time::frequency::Frequency;
    use crate::types::Real;
    use std::cell::Cell;
    use std::rc::Rc;

    struct UpdateCounter {
        count: usize,
    }

    impl Observer for UpdateCounter {
        fn update(&mut self) {
            self.count += 1;
        }
    }

    fn two_argument_model() -> CalibratedModel {
        let mut model = CalibratedModel::new(2);
        model.arguments_mut()[0] =
            ConstantParameter::new(0.1, Rc::new(PositiveConstraint)).unwrap();
        model.arguments_mut()[1] = ConstantParameter::new(0.2, Rc::new(NoConstraint)).unwrap();
        model
    }

    #[test]
    fn params_flattens_arguments_in_order() {
        let model = two_argument_model();
        assert_eq!(model.params(), Array::from([0.1, 0.2]));
    }

    #[test]
    fn set_params_round_trips_through_params() {
        let mut model = two_argument_model();
        model.set_params(&Array::from([0.3, 0.4])).unwrap();
        assert_eq!(model.params(), Array::from([0.3, 0.4]));
        assert_eq!(model.arguments()[0].value(0.0), 0.3);
        assert_eq!(model.arguments()[1].value(0.0), 0.4);
    }

    #[test]
    fn set_params_rejects_too_few_values() {
        let mut model = two_argument_model();
        let err = model.set_params(&Array::from([0.3])).unwrap_err();
        assert_eq!(err.message(), "parameter array too small");
    }

    #[test]
    fn set_params_rejects_too_many_values() {
        let mut model = two_argument_model();
        let err = model.set_params(&Array::from([0.3, 0.4, 0.5])).unwrap_err();
        assert_eq!(err.message(), "parameter array too big!");
    }

    #[test]
    fn private_constraint_tests_each_argument_on_its_own_slice() {
        let constraint = two_argument_model().constraint();
        // argument 0 is positive-constrained, argument 1 is unconstrained
        assert!(constraint.test(&Array::from([0.5, -9.0])));
        assert!(!constraint.test(&Array::from([-0.5, 0.0])));
    }

    #[test]
    fn private_constraint_slices_bounds_per_argument() {
        let constraint = two_argument_model().constraint();
        // PositiveConstraint lower bound is 0.0; NoConstraint lower bound is -MAX
        let lower = constraint.lower_bound(&Array::from([0.5, 0.5]));
        assert_eq!(lower[0], 0.0);
        assert_eq!(lower[1], -crate::types::Real::MAX);
    }

    #[test]
    fn set_params_notifies_registered_observers() {
        let mut model = two_argument_model();
        let counter = shared_mut(UpdateCounter { count: 0 });
        model
            .observable()
            .register_observer(&(counter.clone() as SharedMut<dyn Observer>));

        model.set_params(&Array::from([0.3, 0.4])).unwrap();
        assert_eq!(counter.borrow().count, 1);
    }

    #[test]
    fn as_observer_rebroadcasts_to_the_models_observers() {
        let model = CalibratedModel::new(0);
        let counter = shared_mut(UpdateCounter { count: 0 });
        model
            .observable()
            .register_observer(&(counter.clone() as SharedMut<dyn Observer>));

        // driving the pure-forwarding observer half (as an observed observable
        // would) re-broadcasts to the model's own observers; it does NOT re-run
        // a concrete model's generate_arguments (that is the opt-in
        // register_with_term_structure path, covered below)
        model.as_observer().borrow_mut().update();
        assert_eq!(counter.borrow().count, 1);
    }

    #[test]
    fn write_params_updates_the_arguments_without_notifying() {
        let mut model = two_argument_model();
        let counter = shared_mut(UpdateCounter { count: 0 });
        model
            .observable()
            .register_observer(&(counter.clone() as SharedMut<dyn Observer>));

        model.write_params(&Array::from([0.3, 0.4])).unwrap();

        assert_eq!(model.params(), Array::from([0.3, 0.4]));
        assert_eq!(counter.borrow().count, 0);
    }

    /// A minimal fitted model: it counts every regeneration so a test can pin
    /// that the holder's `set_params` fires `generate_arguments`.
    struct FittedModel {
        model: CalibratedModel,
        regenerations: usize,
    }

    impl CalibratedModelHolder for FittedModel {
        fn calibrated_model(&self) -> &CalibratedModel {
            &self.model
        }
        fn calibrated_model_mut(&mut self) -> &mut CalibratedModel {
            &mut self.model
        }
        fn generate_arguments(&mut self) {
            self.regenerations += 1;
        }
    }

    #[test]
    fn holder_set_params_writes_regenerates_then_notifies() {
        let mut fitted = FittedModel {
            model: two_argument_model(),
            regenerations: 0,
        };
        let counter = shared_mut(UpdateCounter { count: 0 });
        fitted
            .calibrated_model()
            .observable()
            .register_observer(&(counter.clone() as SharedMut<dyn Observer>));

        fitted.set_params(&Array::from([0.3, 0.4])).unwrap();

        assert_eq!(fitted.calibrated_model().params(), Array::from([0.3, 0.4]));
        assert_eq!(fitted.regenerations, 1);
        assert_eq!(counter.borrow().count, 1);
    }

    #[test]
    fn holder_set_params_propagates_the_size_error() {
        let mut fitted = FittedModel {
            model: two_argument_model(),
            regenerations: 0,
        };
        let err = fitted.set_params(&Array::from([0.3])).unwrap_err();
        assert_eq!(err.message(), "parameter array too small");
        assert_eq!(fitted.regenerations, 0);
    }

    #[test]
    fn term_structure_consistent_model_exposes_its_handle() {
        let curve = FlatForward::with_rate(
            Date::new(17, Month::May, 1998),
            0.05,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        );
        let handle: Handle<dyn YieldTermStructure> =
            Handle::new(shared(curve) as Shared<dyn YieldTermStructure>);
        let consistent = TermStructureConsistentModel::new(handle.clone());
        assert!(consistent.term_structure().points_to_same_link(&handle));
    }

    /// A flat continuously-compounded curve at `rate`, as a yield-curve handle
    /// pointee. Two different rates give two different `discount(1.0)`.
    fn flat_curve(rate: Real) -> Shared<dyn YieldTermStructure> {
        shared(FlatForward::with_rate(
            Date::new(17, Month::May, 1998),
            rate,
            Actual360::new(),
            Compounding::Continuous,
            Frequency::Annual,
        )) as Shared<dyn YieldTermStructure>
    }

    /// A minimal term-structure-consistent fitted model: it caches one
    /// curve-derived scalar (its discount to `t = 1`, standing in for
    /// Hull-White's `r0 = zeroRate(0)`) and recomputes it whenever
    /// `generate_arguments` runs. Zero calibrated arguments - the point is the
    /// cached scalar, not a `Parameter`.
    struct FittedScalarModel {
        model: CalibratedModel,
        term_structure: Handle<dyn YieldTermStructure>,
        discount_at_one: Real,
    }

    impl FittedScalarModel {
        /// Mirrors `HullWhite::HullWhite` calling `generateArguments()` in its
        /// constructor: the cached scalar starts at `f(curve)`, not a default.
        fn new(term_structure: Handle<dyn YieldTermStructure>) -> FittedScalarModel {
            let mut fitted = FittedScalarModel {
                model: CalibratedModel::new(0),
                term_structure,
                discount_at_one: 0.0,
            };
            fitted.generate_arguments();
            fitted
        }
    }

    impl CalibratedModelHolder for FittedScalarModel {
        fn calibrated_model(&self) -> &CalibratedModel {
            &self.model
        }
        fn calibrated_model_mut(&mut self) -> &mut CalibratedModel {
            &mut self.model
        }
        fn generate_arguments(&mut self) {
            self.discount_at_one = self
                .term_structure
                .current_link()
                .unwrap()
                .discount(1.0, true)
                .unwrap();
        }
    }

    #[test]
    fn registered_model_regenerates_on_relink() {
        let curve2 = flat_curve(0.10);
        let rh: RelinkableHandle<dyn YieldTermStructure> = RelinkableHandle::new(flat_curve(0.05));
        let model = shared_mut(FittedScalarModel::new(rh.handle()));
        let before = model.borrow().discount_at_one;

        let _observer = register_with_term_structure(&model, &rh.handle());
        rh.link_to(curve2.clone());

        let after = model.borrow().discount_at_one;
        assert_ne!(before, after, "relink must regenerate the cached scalar");
        assert_eq!(
            after,
            curve2.discount(1.0, true).unwrap(),
            "the regenerated scalar must reflect the newly linked curve"
        );
    }

    #[test]
    fn unregistered_model_does_not_regenerate_on_relink() {
        let rh: RelinkableHandle<dyn YieldTermStructure> = RelinkableHandle::new(flat_curve(0.05));
        let model = shared_mut(FittedScalarModel::new(rh.handle()));
        let before = model.borrow().discount_at_one;

        // opt-in default: no register_with_term_structure call
        rh.link_to(flat_curve(0.10));

        assert_eq!(
            model.borrow().discount_at_one,
            before,
            "an unregistered model must not regenerate on relink"
        );
    }

    /// Reads the model's cached scalar during its own `update`, with a plain
    /// `borrow()`: if a regeneration ever held the model's `borrow_mut` across
    /// the notify, this would panic instead of silently passing.
    struct ScalarReader {
        model: WeakMut<FittedScalarModel>,
        seen: Option<Real>,
    }

    impl Observer for ScalarReader {
        fn update(&mut self) {
            self.seen = self.model.upgrade().map(|m| m.borrow().discount_at_one);
        }
    }

    #[test]
    fn model_observers_see_the_regenerated_value_during_notification() {
        let curve2 = flat_curve(0.10);
        let rh: RelinkableHandle<dyn YieldTermStructure> = RelinkableHandle::new(flat_curve(0.05));
        let model = shared_mut(FittedScalarModel::new(rh.handle()));
        let _observer = register_with_term_structure(&model, &rh.handle());

        let reader = shared_mut(ScalarReader {
            model: SharedMut::downgrade(&model),
            seen: None,
        });
        model
            .borrow()
            .calibrated_model()
            .observable()
            .register_observer(&(reader.clone() as SharedMut<dyn Observer>));

        rh.link_to(curve2.clone());

        // the model observer ran after regeneration and read the model back
        // without hitting a live borrow: it sees curve2's discount, the proof
        // that the borrow_mut was released before the notify (D1)
        assert_eq!(
            reader.borrow().seen,
            Some(curve2.discount(1.0, true).unwrap())
        );
    }

    /// A one-parameter fitted model whose only derived state is
    /// `derived = 2 * param`, rebuilt ONLY in `generate_arguments` and shared
    /// with the helper through an `Rc<Cell>`. Writing parameters through the
    /// embedded `CalibratedModel::set_params` (bypassing `generate_arguments`)
    /// leaves the cell stale, so a helper reading the cell detects wrong
    /// routing (the de-degeneration the gate requires).
    struct DerivedModel {
        model: CalibratedModel,
        derived: Rc<Cell<Real>>,
    }

    impl DerivedModel {
        fn new(seed: Real, derived: Rc<Cell<Real>>) -> SharedMut<DerivedModel> {
            let mut model = CalibratedModel::new(1);
            model.arguments_mut()[0] = ConstantParameter::new(seed, Rc::new(NoConstraint)).unwrap();
            let mut fitted = DerivedModel { model, derived };
            fitted.generate_arguments();
            shared_mut(fitted)
        }
    }

    impl CalibratedModelHolder for DerivedModel {
        fn calibrated_model(&self) -> &CalibratedModel {
            &self.model
        }
        fn calibrated_model_mut(&mut self) -> &mut CalibratedModel {
            &mut self.model
        }
        fn generate_arguments(&mut self) {
            self.derived.set(2.0 * self.model.params()[0]);
        }
    }

    /// A helper reading the model's CACHED derived value: its calibration error
    /// is `derived - target`, so its minimum is at `2 * param == target`.
    struct DerivedHelper {
        derived: Rc<Cell<Real>>,
        target: Real,
    }

    impl CalibrationHelper for DerivedHelper {
        fn calibration_error(&mut self) -> QlResult<Real> {
            Ok(self.derived.get() - self.target)
        }
    }

    fn helper(derived: &Rc<Cell<Real>>, target: Real) -> SharedMut<dyn CalibrationHelper> {
        shared_mut(DerivedHelper {
            derived: Rc::clone(derived),
            target,
        }) as SharedMut<dyn CalibrationHelper>
    }

    fn criteria() -> EndCriteria {
        EndCriteria::new(1000, Some(100), 1e-10, 1e-10, None).unwrap()
    }

    #[test]
    fn calibrate_drives_the_free_parameter_to_the_analytic_minimum() {
        let derived = Rc::new(Cell::new(0.0));
        let model = DerivedModel::new(1.0, Rc::clone(&derived));
        let instruments = vec![helper(&derived, 6.0)];
        let mut method = LevenbergMarquardt::default();

        calibrate(
            &model,
            &instruments,
            &mut method,
            &criteria(),
            None,
            Vec::new(),
            Vec::new(),
        )
        .unwrap();

        assert!((model.borrow().calibrated_model().params()[0] - 3.0).abs() < 1e-4);
        // derived == 2 * 3 == 6 proves generate_arguments ran on the final
        // set_params too (had calibrate bypassed the holder seam it would be
        // stale at 2 * seed).
        assert!((derived.get() - 6.0).abs() < 1e-4);
        assert!(model.borrow().calibrated_model().end_criteria().succeeded());
    }

    #[test]
    fn calibrate_finds_the_least_squares_point_of_two_helpers() {
        let derived = Rc::new(Cell::new(0.0));
        let model = DerivedModel::new(1.0, Rc::clone(&derived));
        // minima at 2*param == 6 (param 3) and 2*param == 10 (param 5); the
        // least-squares compromise is param 4.
        let instruments = vec![helper(&derived, 6.0), helper(&derived, 10.0)];
        let mut method = LevenbergMarquardt::default();

        calibrate(
            &model,
            &instruments,
            &mut method,
            &criteria(),
            None,
            Vec::new(),
            Vec::new(),
        )
        .unwrap();

        assert!((model.borrow().calibrated_model().params()[0] - 4.0).abs() < 1e-4);
    }

    #[test]
    fn calibrate_rejects_an_all_fixed_projection() {
        let derived = Rc::new(Cell::new(0.0));
        let model = DerivedModel::new(1.0, Rc::clone(&derived));
        let instruments = vec![helper(&derived, 6.0)];
        let mut method = LevenbergMarquardt::default();

        let err = calibrate(
            &model,
            &instruments,
            &mut method,
            &criteria(),
            None,
            Vec::new(),
            vec![true],
        )
        .unwrap_err();
        assert_eq!(err.message(), "numberOfFreeParameters==0");
    }

    #[test]
    fn calibrate_guards_reject_bad_inputs() {
        let derived = Rc::new(Cell::new(0.0));
        let model = DerivedModel::new(1.0, Rc::clone(&derived));
        let mut method = LevenbergMarquardt::default();

        let err = calibrate(
            &model,
            &[],
            &mut method,
            &criteria(),
            None,
            Vec::new(),
            Vec::new(),
        )
        .unwrap_err();
        assert_eq!(err.message(), "no instruments provided");

        let instruments = vec![helper(&derived, 6.0)];
        let err = calibrate(
            &model,
            &instruments,
            &mut method,
            &criteria(),
            None,
            vec![1.0, 1.0],
            Vec::new(),
        )
        .unwrap_err();
        assert_eq!(
            err.message(),
            "mismatch between number of instruments (1) and weights (2)"
        );

        let err = calibrate(
            &model,
            &instruments,
            &mut method,
            &criteria(),
            None,
            Vec::new(),
            vec![false, false],
        )
        .unwrap_err();
        assert_eq!(
            err.message(),
            "mismatch between number of parameters (1) and fixed-parameter specs (2)"
        );
    }

    #[test]
    fn calibration_value_is_the_root_sum_of_squares_and_writes_params() {
        let derived = Rc::new(Cell::new(0.0));
        let model = DerivedModel::new(1.0, Rc::clone(&derived));
        let instruments = vec![helper(&derived, 6.0), helper(&derived, 10.0)];

        let value = calibration_value(&model, &Array::from([2.0]), &instruments).unwrap();
        // derived = 2 * 2 = 4; diffs -2 and -6; the C++ value is the plain
        // root-sum-of-squares sqrt(4 + 36) = sqrt(40), NOT the default
        // root-MEAN-square sqrt(40 / 2) = sqrt(20).
        assert!((value - 40.0_f64.sqrt()).abs() < 1e-12);
        // value() writes params into the model as a side effect (faithful to
        // C++'s setParams inside value()).
        assert_eq!(model.borrow().calibrated_model().params()[0], 2.0);
        assert!((derived.get() - 4.0).abs() < 1e-12);
    }
}