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
use crateBoxProblem;
use crate;
use crate;
use crate;
use crateSolver;
use cratePopulationProgress;
// Joint ascending-by-cost sort shared with the population solvers.
use cratesort_population_ascending;
/// Elitist (1+λ) random search over a feasible box.
///
/// Samples independent candidates and retains the best member between
/// generations. Publishes [`PopulationProgress`] while owning its RNG.
///
/// # Algorithm
///
/// At [`init`](Solver::init) an empty state receives `λ` candidates drawn
/// uniformly from the problem's box `[lower, upper]`; explicit members are
/// projected into that box. The solver evaluates each and sorts by cost.
///
/// Each [`next_iter`](Solver::next_iter):
///
/// ```text
/// elite ← (candidates[0], costs[0]) # current best
/// resample λ candidates uniformly in [lower, upper]
/// evaluate each, append along with the elite (now λ + 1 entries)
/// sort ascending by cost
/// truncate back to λ # drops the worst
/// ```
///
/// Elite carry-over keeps the current best cost non-increasing for finite
/// objectives. Optional cost-change and step tests compare generation
/// representatives, including generations that retain the same elite.
///
/// # Reproducibility
///
/// The solver carries a [`ChaCha8Rng`] seeded from the `seed: u64`
/// passed to [`new`](Self::new). Same seed → same trajectory, on every
/// platform basin builds for (including `wasm32-unknown-unknown`). To
/// vary runs, vary the seed; to share runs, share the seed.
///
/// # Contract
///
/// - **Caller must:** declare a box-only set using [`BoxBounds`](crate::BoxBounds) on the problem with
/// `lower[i] ≤ upper[i]` for every component. Equal bounds are
/// allowed (the corresponding component is pinned).
/// - Supply [`PopulationProgress::empty`] to sample `lambda` members, or
/// [`PopulationProgress::from_population`] with exactly `lambda` finite
/// vectors whose dimension matches the bounds. Bounds must be non-empty,
/// finite, equal in length, and ordered. Invalid shapes panic at initialization.
/// - Fresh initialization resets progress and the configured RNG, projects
/// explicit members into the box, reevaluates every member, and sorts by cost.
/// Reusing a final population is a population warm start. Supply an empty
/// state to reproduce the original seeded run.
/// - Solver-aware exact checkpoints retain the population, RNG, and raw
/// evaluation counts and skip initialization. With `serde`, both the solver
/// and progress serialize. A progress-only snapshot cannot continue exactly.
///
/// # Termination
///
/// No solver-internal optimality test; random search has no canonical
/// fixed-point criterion. Use the framework's
/// [`max_iter`](crate::Executor::max_iter),
/// [`max_cost_evals`](crate::Executor::max_cost_evals),
/// [`max_time`](crate::Executor::max_time),
/// [`with_absolute_cost_change_tolerance`](Self::with_absolute_cost_change_tolerance), or
/// [`with_absolute_step_tolerance`](Self::with_absolute_step_tolerance). The
/// elite-carryover makes cost monotonicity honest, so cost-based budgets
/// behave as expected.
///
/// # Backends
///
/// `Vec<F>`, nalgebra `DVector<F>`, ndarray `Array1<F>`, and faer `Col<F>`,
/// for all supported releases with `F = f32` or `f64`. Requires
/// [`SampleUniformBox`], [`VectorLen`], `Index<usize, Output = F>`,
/// `IndexMut<usize, Output = F>`, and `Clone`. No matrix operations are needed.
/// The problem must declare a box-only set using [`BoxBounds`](crate::BoxBounds).
///
/// # Examples
///
/// Elitist random search over a feasible box. The problem implements
/// [`CostFunction`] and [`BoxBounds`](crate::BoxBounds); the
/// initial population is generated from an empty state via
/// [`PopulationProgress::empty`](crate::PopulationProgress::empty):
///
/// ```
/// use basin::{PopulationProgress, CostFunction, Executor, RandomSearch};
///
/// struct BoundedSphere {
/// lower: Vec<f64>,
/// upper: Vec<f64>,
/// }
/// impl basin::Constraints for BoundedSphere {
/// type Set = basin::ConstraintSet<basin::BoxBounds<Vec<f64>>>;
/// fn constraints(&self) -> <Self::Set as basin::ConstraintDescription>::Borrowed<'_> { basin::ConstraintSet::new().with_bounds(basin::BoxBounds::new(Some(&self.lower), Some(&self.upper))) }
/// }
/// impl CostFunction for BoundedSphere {
/// type Param = Vec<f64>;
/// type Output = f64;
/// type Error = std::convert::Infallible;
/// fn cost(&self, x: &Vec<f64>) -> Result<f64, Self::Error> {
/// Ok(x.iter().map(|xi| xi * xi).sum())
/// }
/// }
///
///
/// let problem = BoundedSphere { lower: vec![-5.0, -5.0], upper: vec![5.0, 5.0] };
/// let result = Executor::new(
/// problem,
/// RandomSearch::new(16, 42),
/// PopulationProgress::<Vec<f64>>::empty(),
/// )
/// .max_iter(500)
/// .run()
/// .unwrap();
/// assert!(result.cost() < 1.0);
/// ```