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
//! Problem traits the user implements about their objective. Solvers
//! bind on whichever subset they need (e.g. gradient descent requires
//! [`CostFunction`] *and* [`Gradient`]; Nelder-Mead only needs
//! [`CostFunction`]).
//!
//! # Soft reject vs hard abort
//!
//! Every problem trait method returns `Result<_, Self::Error>`. The two
//! ways to signal "something went wrong" are *deliberately* distinct:
//!
//! - **Soft reject (`Ok(f64::INFINITY)`)** — return `+∞` from
//! [`CostFunction::cost`] to reject a single point. Line searches treat
//! it as worse and retreat; population solvers treat it as worst
//! fitness. This is the right channel for "this `x` is outside my
//! domain, but the solve should continue."
//! - **Hard abort (`Err(_)`)** — return `Err` to terminate the entire
//! solve. The error bubbles all the way out of
//! [`Executor::run`](crate::Executor::run) typed as
//! `Result<_, P::Error>`. Use this when the failure is *not* about a
//! particular `x` — a downstream service vanished, the user pressed
//! cancel, an early-stopping criterion in the problem's own state fired.
//!
//! Problems that never fail in this way pick
//! `type Error = std::convert::Infallible;` (or
//! [`!`](https://doc.rust-lang.org/std/primitive.never.html) on nightly).
//! Niche optimization collapses `Result<f64, Infallible>` to `f64` layout,
//! so the happy path stays zero-cost.
/// Scalar-valued objective `f(x): Param → Output`. The smallest
/// problem trait — every solver binds at least on this.
///
/// # Contract
///
/// - **Implementor must:** be a *pure* function of `param` —
/// evaluating at the same `param` twice must return the same
/// `Output` (or the same `Err`). Solvers cache costs across iterations,
/// line searches reuse evaluations, and termination criteria assume the
/// cost they read from the state matches what a fresh `cost(param)`
/// would return.
/// - **Implementor must not:** assume any particular call order or
/// frequency. Solvers may evaluate at exploratory points outside the
/// accepted iterate sequence (line-search probes, Nelder-Mead
/// reflections / contractions / shrinks, finite-difference probes).
///
/// # Soft reject vs hard abort
///
/// See the [module docs](self#soft-reject-vs-hard-abort). Return
/// `Ok(f64::INFINITY)` to *reject one point*; return `Err(_)` to abort
/// the entire solve.
///
/// # Examples
///
/// A never-fails problem uses [`Infallible`](std::convert::Infallible) as
/// its error:
///
/// ```
/// use basin::CostFunction;
///
/// struct Sphere;
/// impl CostFunction for Sphere {
/// type Param = Vec<f64>;
/// type Output = f64;
/// type Error = std::convert::Infallible;
/// fn cost(&self, x: &Vec<f64>) -> Result<f64, std::convert::Infallible> {
/// Ok(x.iter().map(|xi| xi * xi).sum())
/// }
/// }
///
/// assert_eq!(Sphere.cost(&vec![3.0, 4.0]).unwrap(), 25.0);
/// ```
/// Analytic gradient `∇f(x): Param → Gradient`. Required by
/// first-order solvers (gradient descent, BFGS, …).
///
/// `Gradient` is a *subtrait* of [`CostFunction`]: a gradient is the
/// gradient *of* a cost, so the parameter and error types are inherited
/// and the two cannot disagree.
///
/// # Contract
///
/// - **Implementor must:** be a *pure* function of `param`, with the
/// same call-order independence as [`CostFunction::cost`].
/// - **Implementor must:** return a `Gradient` whose shape matches
/// `param` so solver math (`x ← x − α·∇f(x)`) lines up. Most
/// problems have `Gradient = Param`, which is what the shipped
/// solvers' bounds expect (e.g. `Gradient<Gradient = V>` paired with
/// `CostFunction<Param = V>`).
/// - The gradient must agree with [`CostFunction::cost`]: it is the
/// actual derivative, not a finite-difference approximation unless
/// the implementor is happy taking the loss in solver
/// convergence behavior.
///
/// # Fused evaluation
///
/// When a solver needs *both* `f(x)` and `∇f(x)` at the same point —
/// which it almost always does at the start of every iteration —
/// it calls [`cost_and_gradient`](Self::cost_and_gradient). The default
/// body simply calls [`CostFunction::cost`] and [`Gradient::gradient`]
/// in turn, which is the right answer for most problems and what
/// users get for free.
///
/// **Override `cost_and_gradient` when the two share substantial
/// intermediate work** — autodiff tapes, forward-mode adjoints,
/// neural-net activations, expensive simulation state. The default
/// then becomes a no-op and the solver picks up the fusion savings
/// without any further change.
///
/// Cost-only callers (line searches probing trial steps, cost-only
/// termination criteria, derivative-free solvers) keep calling
/// [`CostFunction::cost`] directly — no waste from the fused method.
///
/// # Examples
///
/// ```
/// use basin::{CostFunction, Gradient};
///
/// struct Sphere;
/// impl CostFunction for Sphere {
/// type Param = Vec<f64>;
/// type Output = f64;
/// type Error = std::convert::Infallible;
/// fn cost(&self, x: &Vec<f64>) -> Result<f64, std::convert::Infallible> {
/// Ok(x.iter().map(|xi| xi * xi).sum())
/// }
/// }
/// impl Gradient for Sphere {
/// type Gradient = Vec<f64>;
/// fn gradient(&self, x: &Vec<f64>) -> Result<Vec<f64>, std::convert::Infallible> {
/// Ok(x.iter().map(|xi| 2.0 * xi).collect())
/// }
/// }
///
/// assert_eq!(Sphere.gradient(&vec![1.0, 2.0]).unwrap(), vec![2.0, 4.0]);
/// ```
///
/// Fusion override (cost and gradient share `x * x`):
///
/// ```
/// use basin::{CostFunction, Gradient};
///
/// struct Sphere;
/// impl CostFunction for Sphere {
/// type Param = Vec<f64>;
/// type Output = f64;
/// type Error = std::convert::Infallible;
/// fn cost(&self, x: &Vec<f64>) -> Result<f64, std::convert::Infallible> {
/// Ok(x.iter().map(|xi| xi * xi).sum())
/// }
/// }
/// impl Gradient for Sphere {
/// type Gradient = Vec<f64>;
/// fn gradient(&self, x: &Vec<f64>) -> Result<Vec<f64>, std::convert::Infallible> {
/// Ok(x.iter().map(|xi| 2.0 * xi).collect())
/// }
/// fn cost_and_gradient(
/// &self,
/// x: &Vec<f64>,
/// ) -> Result<(f64, Vec<f64>), std::convert::Infallible> {
/// // Single pass over x; the per-element work is shared.
/// let mut cost = 0.0;
/// let grad = x
/// .iter()
/// .map(|xi| {
/// cost += xi * xi;
/// 2.0 * xi
/// })
/// .collect();
/// Ok((cost, grad))
/// }
/// }
/// ```
/// Vector-valued residual `r(x): Param → Output` for least-squares
/// problems. Required by Gauss-Newton, Levenberg-Marquardt, and any
/// solver that minimizes `½‖r(x)‖²`.
///
/// # Contract
///
/// - **Implementor must:** be a *pure* function of `param`, with the
/// same call-order independence as [`CostFunction::cost`].
/// - **Implementor must:** return an `Output` whose length `m` is fixed
/// for a given problem — `m` does not depend on the iterate. Solvers
/// may allocate workspace once based on the first call. `m` is
/// independent of `param.len() = n`.
/// - When [`CostFunction`] is also implemented, the cost must agree
/// with the residual under the convention `cost(x) = ½ Σ rᵢ(x)²`,
/// unless the problem documents an unscaled `Σ rᵢ²` form (see e.g.
/// the existing Rosenbrock cost, which is the published unscaled
/// form).
///
/// # Soft reject vs hard abort
///
/// `Residual` carries its *own* [`Error`](Residual::Error) (independent
/// of [`CostFunction::Error`]); the soft/hard split from the
/// [module docs](self#soft-reject-vs-hard-abort) applies identically.
/// NLLS solvers `?`-propagate residual errors and treat any `Err` as a
/// hard abort.
///
/// # Examples
///
/// ```
/// use basin::Residual;
///
/// // r(x) = (x₀ − 1, x₁ − 2); the least-squares optimum is (1, 2).
/// struct Affine;
/// impl Residual for Affine {
/// type Param = Vec<f64>;
/// type Output = Vec<f64>;
/// type Error = std::convert::Infallible;
/// fn residual(&self, x: &Vec<f64>) -> Result<Vec<f64>, std::convert::Infallible> {
/// Ok(vec![x[0] - 1.0, x[1] - 2.0])
/// }
/// }
///
/// assert_eq!(
/// Affine.residual(&vec![0.0, 0.0]).unwrap(),
/// vec![-1.0, -2.0]
/// );
/// ```
/// Analytic Jacobian `J(x) = ∂r/∂x: Param → Jacobian` for least-squares
/// solvers (Gauss-Newton, LM, TRF). The associated `Jacobian` matrix
/// type is what lets solvers bound on the linear-algebra ops they need
/// ([`MatVec`](crate::core::math::MatVec),
/// [`LinearSolveSpd`](crate::core::math::LinearSolveSpd), …) without
/// baking in a specific backend or assuming density.
///
/// `Jacobian` is a *subtrait* of [`Residual`]: a Jacobian is the
/// Jacobian *of* a residual, so the parameter and error types are
/// inherited.
///
/// # Contract
///
/// - **Implementor must:** be a *pure* function of `param`, with the
/// same call-order independence as [`CostFunction::cost`].
/// - **Implementor must:** return a matrix of shape `m × n` where
/// `m = residual(param).len()` and `n = param.len()`. The `(i, j)`
/// entry is `∂rᵢ / ∂xⱼ`. Shape is fixed across iterates.
/// - The Jacobian must agree with [`Residual::residual`]: it is the
/// actual derivative, not a finite-difference approximation, unless
/// the implementor accepts the loss in solver convergence behavior.
///
/// # Fused evaluation
///
/// NLLS solvers (Gauss-Newton, LM, TRF) evaluate `r(x)` and `J(x)`
/// together at every accepted iterate — and `r(x)` is usually the
/// dominant cost, with `J(x)` reusing intermediate state (forward-mode
/// AD on the residual graph, FE assembly, simulation adjoints).
/// [`residual_and_jacobian`](Self::residual_and_jacobian) provides the
/// fused entry point. The default body calls [`Residual::residual`] and
/// [`Jacobian::jacobian`] in turn; override when work can be shared.
///
/// # Backends
///
/// Wired up for the LA-heavy backends only:
///
/// - `Param = nalgebra::DVector<f64>` → `Jacobian = nalgebra::DMatrix<f64>`
/// (dense) or `nalgebra_sparse::CscMatrix<f64>` (sparse). Both ride
/// on the `nalgebra` feature.
/// - `Param = faer::Col<f64>` → `Jacobian = faer::Mat<f64>` (dense) or
/// `faer::sparse::SparseColMat<usize, f64>` (sparse). Both ride on
/// the `faer` feature.
///
/// `Vec<f64>` deliberately does not implement `Jacobian` — there is no
/// honest matrix type to pair with it. `ndarray::Array1<f64>` likewise
/// has no `Jacobian` impl: `ndarray-linalg` requires system BLAS/LAPACK
/// and breaks the wasm-default tenet, so there's no honest
/// [`LinearSolveSpd`](crate::core::math::LinearSolveSpd) to back it.
/// Per tenet 5 in `AGENTS.md`, missing backend coverage is a
/// compile-time error rather than a runtime surprise.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nalgebra")] {
/// use basin::{Jacobian, Residual};
/// use nalgebra::{DMatrix, DVector};
///
/// struct Affine;
/// impl Residual for Affine {
/// type Param = DVector<f64>;
/// type Output = DVector<f64>;
/// type Error = std::convert::Infallible;
/// fn residual(
/// &self,
/// x: &DVector<f64>,
/// ) -> Result<DVector<f64>, std::convert::Infallible> {
/// Ok(DVector::from_vec(vec![x[0] - 1.0, x[1] - 2.0]))
/// }
/// }
/// impl Jacobian for Affine {
/// type Jacobian = DMatrix<f64>;
/// fn jacobian(
/// &self,
/// _x: &DVector<f64>,
/// ) -> Result<DMatrix<f64>, std::convert::Infallible> {
/// Ok(DMatrix::identity(2, 2))
/// }
/// }
///
/// let j = Affine.jacobian(&DVector::from_vec(vec![0.0, 0.0])).unwrap();
/// assert_eq!(j[(0, 0)], 1.0);
/// # }
/// ```
/// Analytic Hessian `H(x) = ∇²f(x): Param → Hessian` for second-order
/// solvers (Newton, trust-region-Newton). The associated `Hessian`
/// matrix type lets solvers bound on the linear-algebra ops they need
/// ([`LinearSolveSpd`](crate::core::math::LinearSolveSpd),
/// [`SymmetricEigen`](crate::core::math::SymmetricEigen), …) without
/// baking in a backend.
///
/// `Hessian` is a *subtrait* of [`Gradient`] (which is a subtrait of
/// [`CostFunction`]): a Hessian is the second derivative of a cost.
/// The error type is therefore [`CostFunction::Error`].
///
/// # Contract
///
/// - **Implementor must:** be a *pure* function of `param`, with the
/// same call-order independence as [`CostFunction::cost`].
/// - **Implementor must:** return a **symmetric** `n × n` matrix where
/// `n = param.len()`. The `(i, j)` entry is `∂²f / ∂xᵢ∂xⱼ`. Shape is
/// fixed across iterates.
/// - The Hessian must agree with [`CostFunction::cost`] and
/// [`Gradient::gradient`]: it is the actual second derivative, not a
/// finite-difference approximation, unless the implementor accepts
/// the loss in solver convergence behavior.
///
/// # Fused evaluation
///
/// Second-order solvers evaluate `f`, `∇f`, and `∇²f` together at
/// every accepted iterate. The
/// [`cost_and_gradient_and_hessian`](Self::cost_and_gradient_and_hessian)
/// method provides the fused entry point. The default body composes
/// [`Gradient::cost_and_gradient`] with [`Hessian::hessian`]; override
/// when all three share intermediate state.
///
/// # Backends
///
/// Wired up for the LA-heavy backends only, mirroring [`Jacobian`]:
///
/// - `Param = nalgebra::DVector<f64>` → `Hessian = nalgebra::DMatrix<f64>`
/// (rides on the `nalgebra` feature).
/// - `Param = faer::Col<f64>` → `Hessian = faer::Mat<f64>` (rides on
/// the `faer` feature).
///
/// `Vec<f64>` and `ndarray::Array1<f64>` deliberately have no `Hessian`
/// impl — there's no honest dense matrix type to pair with them. Per
/// tenet 5 in `AGENTS.md`, missing backend coverage is a compile-time
/// error rather than a runtime surprise.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nalgebra")] {
/// use basin::{CostFunction, Gradient, Hessian};
/// use nalgebra::{DMatrix, DVector};
///
/// // f(x) = x₀² + x₁² has constant Hessian 2·I.
/// struct Sphere;
/// impl CostFunction for Sphere {
/// type Param = DVector<f64>;
/// type Output = f64;
/// type Error = std::convert::Infallible;
/// fn cost(&self, x: &DVector<f64>) -> Result<f64, std::convert::Infallible> {
/// Ok(x.dot(x))
/// }
/// }
/// impl Gradient for Sphere {
/// type Gradient = DVector<f64>;
/// fn gradient(
/// &self,
/// x: &DVector<f64>,
/// ) -> Result<DVector<f64>, std::convert::Infallible> {
/// Ok(2.0 * x)
/// }
/// }
/// impl Hessian for Sphere {
/// type Hessian = DMatrix<f64>;
/// fn hessian(
/// &self,
/// x: &DVector<f64>,
/// ) -> Result<DMatrix<f64>, std::convert::Infallible> {
/// Ok(2.0 * DMatrix::identity(x.len(), x.len()))
/// }
/// }
///
/// let h = Sphere.hessian(&DVector::from_vec(vec![1.0, 1.0])).unwrap();
/// assert_eq!(h[(0, 0)], 2.0);
/// # }
/// ```
/// Per-kind evaluation counters carried by [`Problem`].
///
/// One field per problem-trait method family. The
/// [`Executor`](crate::core::executor::Executor) mirrors these onto the
/// solver `State` after every successful
/// [`Solver::next_iter`](crate::core::solver::Solver::next_iter) /
/// [`Solver::init`](crate::core::solver::Solver::init), with the per-state
/// rule defined by the state's [`CountsMirror`](crate::core::state::CountsMirror)
/// impl. The wrapper itself is authoritative; the state mirror is the
/// "available-everywhere" view that termination criteria and
/// [`OptimizationResult`](crate::core::executor::OptimizationResult) read.
/// Counting wrapper that solvers receive instead of `&P` directly.
///
/// Every problem-trait method on [`Problem`] bumps the relevant
/// [`EvalCounts`] field before delegating to the inner problem, so
/// solvers can't accidentally lose a count: forgetting to count becomes
/// a compile error (the inner is private; the only way to evaluate the
/// problem is through the wrapper). The
/// [`Executor`](crate::core::executor::Executor) wraps the user's
/// problem once in [`Executor::new`](crate::core::executor::Executor::new)
/// and mirrors [`counts`](Self::counts) onto the solver `State` after
/// every successful
/// [`Solver::init`](crate::core::solver::Solver::init) /
/// [`Solver::next_iter`](crate::core::solver::Solver::next_iter).
///
/// # Composition
///
/// Outer solvers that drive an inner solver receive their own
/// `&mut Problem<P>` in `next_iter`. Two shapes are supported:
///
/// - **Same-problem inner** (e.g.
/// [`CmaInject`](crate::solver::CmaInject)): the outer passes its own
/// `&mut Problem<P>` straight through to the inner via
/// [`run_loop`](crate::core::executor::run_loop). Inner counts flow
/// into the outer's wrapper transparently; no explicit roll-up. Inner
/// `state` counts reflect per-run work (snapshot-relative, computed by
/// [`run_loop`](crate::core::executor::run_loop)).
/// - **Adapter-problem inner** (e.g.
/// [`BarrierMethod`](crate::solver::BarrierMethod) /
/// [`AugmentedLagrangianMethod`](crate::solver::AugmentedLagrangianMethod)):
/// the outer constructs a fresh `Problem::new(adapter)` around its
/// adapter type, runs the inner against it, then folds the inner's
/// counts back into the outer's wrapper via
/// [`EvalCounts::add`].
///
/// # Error path
///
/// Counters bump **before** the delegated inner call. A mid-call `Err`
/// therefore still leaves the wrapper count incremented — the wrapper is
/// authoritative even on the hard-abort path, where the state mirror may
/// be stale. Observers can read the true count via
/// [`counts`](Self::counts) regardless.