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
use crate::numerical::Nonlinear_systems::error::SolveError;
use nalgebra::{DMatrix, DVector};
/// Box constraints for a nonlinear system.
#[derive(Debug, Clone, PartialEq)]
pub struct Bounds {
/// Lower and upper limits for each variable.
limits: Vec<(f64, f64)>,
}
impl Bounds {
/// Creates validated bounds from `(lower, upper)` pairs.
pub fn new(limits: Vec<(f64, f64)>) -> Result<Self, SolveError> {
if limits.is_empty() {
return Err(SolveError::InvalidConfig(
"bounds must not be empty".to_string(),
));
}
for (index, (lower, upper)) in limits.iter().copied().enumerate() {
if lower > upper {
return Err(SolveError::InvalidConfig(format!(
"invalid bounds at index {index}: lower bound {lower} exceeds upper bound {upper}"
)));
}
}
Ok(Self { limits })
}
/// Converts `Option<Vec<_>>` into validated optional bounds.
pub fn from_optional(limits: Option<Vec<(f64, f64)>>) -> Result<Option<Self>, SolveError> {
limits.map(Self::new).transpose()
}
/// Returns the problem dimension covered by the bounds.
pub fn len(&self) -> usize {
self.limits.len()
}
/// Returns `true` when the bounds collection is empty.
pub fn is_empty(&self) -> bool {
self.limits.is_empty()
}
/// Returns the internal slice of `(lower, upper)` pairs.
pub fn as_slice(&self) -> &[(f64, f64)] {
&self.limits
}
/// Checks that a point is inside the bounds.
pub fn validate(&self, x: &DVector<f64>) -> Result<(), SolveError> {
if x.len() != self.len() {
return Err(SolveError::DimensionMismatch {
expected: self.len(),
actual: x.len(),
context: "bounds validation",
});
}
for (index, value) in x.iter().copied().enumerate() {
let (lower, upper) = self.limits[index];
if value < lower || value > upper {
return Err(SolveError::InfeasibleInitialGuess {
index,
value,
lower,
upper,
});
}
}
Ok(())
}
/// Projects a point back to the box in place.
///
/// This is the allocation-free counterpart of [`Self::project`]. It is
/// useful on solver trial points, where the vector has already been
/// allocated by the method's step arithmetic.
pub fn project_in_place(&self, x: &mut DVector<f64>) {
let limit = x.len().min(self.limits.len());
for index in 0..limit {
let (lower, upper) = self.limits[index];
x[index] = x[index].clamp(lower, upper);
}
}
/// Projects a point back to the box.
pub fn project(&self, x: &DVector<f64>) -> DVector<f64> {
let mut projected = x.clone();
self.project_in_place(&mut projected);
projected
}
/// Returns the largest scalar `alpha` such that `x + alpha * step` stays inside the box.
pub fn max_step_scale(&self, x: &DVector<f64>, step: &DVector<f64>) -> f64 {
let mut scale: f64 = 1.0;
let limit = x.len().min(step.len()).min(self.limits.len());
for index in 0..limit {
let value = x[index];
let delta = step[index];
let (lower, upper) = self.limits[index];
if delta > 0.0 {
scale = scale.min((upper - value) / delta);
} else if delta < 0.0 {
scale = scale.min((lower - value) / delta);
}
}
if scale.is_finite() {
scale
} else {
1.0
}
}
}
/// Problem definition based on residual evaluation.
pub trait NonlinearProblem {
/// Returns the number of unknowns.
fn dimension(&self) -> usize;
/// Evaluates the residual vector at `x`.
fn residual(&self, x: &DVector<f64>) -> Result<DVector<f64>, SolveError>;
/// Returns whether [`Self::residual_into`] is an allocation-aware path.
///
/// This is opt-in so adding the compatibility method cannot make existing
/// providers slower. Implementors overriding `residual_into` should also
/// override this method and return `true`.
fn supports_residual_into(&self) -> bool {
false
}
/// Evaluates the residual into caller-owned storage.
///
/// The default keeps existing implementations source-compatible by
/// delegating to [`Self::residual`] and copying the returned vector. A
/// provider with reusable storage can override this method to write
/// directly into `out` and avoid a temporary allocation per evaluation.
fn residual_into(&self, x: &DVector<f64>, out: &mut DVector<f64>) -> Result<(), SolveError> {
let residual = self.residual(x)?;
if residual.len() != out.len() {
return Err(SolveError::DimensionMismatch {
expected: self.dimension(),
actual: residual.len(),
context: "residual evaluation",
});
}
out.copy_from(&residual);
Ok(())
}
}
/// Extension of [`NonlinearProblem`] with an analytic Jacobian.
pub trait JacobianProvider: NonlinearProblem {
/// Evaluates the Jacobian matrix at `x`.
fn jacobian(&self, x: &DVector<f64>) -> Result<DMatrix<f64>, SolveError>;
/// Returns whether [`Self::jacobian_into`] is an allocation-aware path.
///
/// This is opt-in for the same compatibility reason as
/// [`NonlinearProblem::supports_residual_into`].
fn supports_jacobian_into(&self) -> bool {
false
}
/// Evaluates the Jacobian into caller-owned storage.
///
/// The default preserves the owned-returning API. Providers that can
/// reuse matrix storage may override it to fill `out` in place.
fn jacobian_into(&self, x: &DVector<f64>, out: &mut DMatrix<f64>) -> Result<(), SolveError> {
let jacobian = self.jacobian(x)?;
if jacobian.nrows() != out.nrows() || jacobian.ncols() != out.ncols() {
return Err(SolveError::InvalidConfig(format!(
"Jacobian evaluation returned {}x{}, expected {}x{}",
jacobian.nrows(),
jacobian.ncols(),
out.nrows(),
out.ncols()
)));
}
out.copy_from(&jacobian);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_in_place_matches_owned_projection() {
let bounds = Bounds::new(vec![(0.0, 1.0), (-2.0, 2.0), (10.0, 20.0)]).expect("bounds");
let input = DVector::from_vec(vec![-3.0, 0.5, 25.0]);
let expected = bounds.project(&input);
let mut actual = input;
bounds.project_in_place(&mut actual);
assert_eq!(actual, expected);
assert_eq!(actual.as_slice(), &[0.0, 0.5, 20.0]);
}
#[test]
fn method_workspace_reuses_affine_trial_storage() {
let base = DVector::from_vec(vec![1.0, 2.0, 3.0]);
let direction = DVector::from_vec(vec![0.5, -1.0, 2.0]);
let mut workspace = crate::numerical::Nonlinear_systems::engine::MethodWorkspace::new(3);
let initial_pointer = workspace.trial_x().as_slice().as_ptr();
workspace
.set_affine_trial(&base, -2.0, &direction)
.expect("matching dimensions");
assert_eq!(workspace.trial_x().as_slice(), &[0.0, 4.0, -1.0]);
assert_eq!(workspace.trial_x().as_slice().as_ptr(), initial_pointer);
}
}