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
//! Solver traits and configuration.
use crate::geometry::{Boundary, Geometry};
use crate::result::SolveResult;
use crate::Result;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Optimization strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Strategy {
/// Bottom-Left Fill (fast, lower quality).
#[default]
BottomLeftFill,
/// NFP-guided placement (balanced).
NfpGuided,
/// Genetic Algorithm (slower, higher quality).
GeneticAlgorithm,
/// Biased Random-Key Genetic Algorithm (balanced, robust).
Brkga,
/// Simulated Annealing.
SimulatedAnnealing,
/// Extreme Point heuristic (3D only).
ExtremePoint,
/// Goal-Driven Ruin and Recreate (GDRR).
Gdrr,
/// Adaptive Large Neighborhood Search (ALNS).
Alns,
/// MILP-based exact solver (small instances, optimal solution).
MilpExact,
/// Hybrid: Try exact first, fallback to heuristic on timeout.
HybridExact,
}
impl Strategy {
/// The short name of each strategy -- what a refusal of an unknown name
/// lists as expected. [`Strategy::parse`] reads these and the longer
/// forms in [`Strategy::SPELLINGS`].
/// Whether this strategy reads `setting` -- one of the settings only some
/// strategies use. A request that names one its strategy does not read is
/// refused rather than run without it (see `ConfigRequest::to_config`).
/// Settings every strategy reads are not listed and always read.
///
/// - `crossover_rate`, `mutation_rate`: the genetic algorithm.
/// - `population_size`, `max_generations`: the two population searches.
/// - `seed`: the stochastic searches (and the hybrid's ALNS fallback).
/// - `target_utilization`: the searches that stop on a target (GA, BRKGA,
/// SA).
pub fn reads_setting(self, setting: &str) -> bool {
use Strategy::*;
match setting {
"crossover_rate" | "mutation_rate" => matches!(self, GeneticAlgorithm),
"population_size" | "max_generations" => matches!(self, GeneticAlgorithm | Brkga),
"seed" => matches!(
self,
GeneticAlgorithm | Brkga | SimulatedAnnealing | Gdrr | Alns | HybridExact
),
"target_utilization" => matches!(self, GeneticAlgorithm | Brkga | SimulatedAnnealing),
_ => true,
}
}
/// The names of the strategies that read `setting` (see
/// [`Self::reads_setting`]).
pub fn readers_of(setting: &str) -> Vec<&'static str> {
Self::NAMES
.iter()
.copied()
.filter(|n| Self::parse(n).is_some_and(|s| s.reads_setting(setting)))
.collect()
}
pub const NAMES: [&'static str; 10] = [
"blf",
"nfp",
"ga",
"brkga",
"sa",
"ep",
"gdrr",
"alns",
"milpexact",
"hybridexact",
];
/// Every spelling [`Strategy::parse`] reads, with the strategy it names:
/// the [`Strategy::NAMES`] and their longer forms.
pub const SPELLINGS: [(&'static str, Self); 18] = [
("blf", Self::BottomLeftFill),
("bottomleftfill", Self::BottomLeftFill),
("nfp", Self::NfpGuided),
("nfpguided", Self::NfpGuided),
("ga", Self::GeneticAlgorithm),
("genetic", Self::GeneticAlgorithm),
("geneticalgorithm", Self::GeneticAlgorithm),
("brkga", Self::Brkga),
("sa", Self::SimulatedAnnealing),
("simulatedannealing", Self::SimulatedAnnealing),
("ep", Self::ExtremePoint),
("extremepoint", Self::ExtremePoint),
("gdrr", Self::Gdrr),
("alns", Self::Alns),
("milpexact", Self::MilpExact),
("exact", Self::MilpExact),
("hybridexact", Self::HybridExact),
("hybrid", Self::HybridExact),
];
/// Parses a strategy name (case-insensitive, whitespace-trimmed).
///
/// Returns `None` for unrecognized names so callers surface an explicit
/// error instead of silently falling back to a default strategy (which
/// hides typos from consumers). This is the single source of truth for
/// strategy-name parsing across all bindings (C FFI, Python, WASM).
pub fn parse(name: &str) -> Option<Self> {
let name = name.trim().to_lowercase();
Self::SPELLINGS
.iter()
.find(|(spelling, _)| *spelling == name)
.map(|&(_, strategy)| strategy)
}
}
/// Common configuration for solvers.
///
/// It holds no thread count: a build with the `parallel` feature runs its
/// parallel work on the rayon pool the solve is called from, so
/// `rayon::ThreadPool::install` around the solve (or `RAYON_NUM_THREADS`)
/// bounds it; without the feature a solve runs on the calling thread.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Config {
/// Optimization strategy.
pub strategy: Strategy,
/// Minimum distance between any two placed geometries. It does not apply
/// between a geometry and the boundary — that is `margin`.
pub spacing: f64,
/// Minimum distance between any placed geometry and the boundary edge.
pub margin: f64,
/// Maximum computation time in milliseconds (0 = unlimited).
///
/// The search strategies check it between individual placements, so a solve
/// returns within the limit plus the time of the greedy bottom-left pass it is
/// compared against. The layout returned is the best one found in that time.
pub time_limit_ms: u64,
/// Target utilization (0.0 - 1.0). Solver stops if reached.
pub target_utilization: Option<f64>,
// GA-specific parameters
/// Population size for the population-based strategies (GA, BRKGA).
///
/// `None` runs each strategy with the size it is tuned for -- 2D GA and
/// BRKGA 30, 3D GA 100, 3D BRKGA 50; `Some(n)` runs it with `n`, at least
/// 2. The other strategies have no population and do not read it.
pub population_size: Option<usize>,
/// Generation budget for the population-based strategies (GA, BRKGA).
///
/// `None` runs each strategy with the budget it is tuned for -- 2D GA and
/// BRKGA 50, 3D GA 500, 3D BRKGA 100; `Some(n)` allows `n` generations (0
/// evaluates the first population only). A run also ends on the time
/// limit, on cancellation and when the best layout stops improving.
pub max_generations: Option<u32>,
/// Crossover rate for GA (0.0 - 1.0).
pub crossover_rate: f64,
/// Mutation rate for GA (0.0 - 1.0).
pub mutation_rate: f64,
/// Elite count for GA.
pub elite_count: usize,
/// Optional RNG seed for reproducible runs of the stochastic strategies
/// (GA, BRKGA, SA, GDRR, ALNS -- 2D and 3D). `None` seeds from system
/// entropy (non-deterministic).
///
/// A seeded run draws every random choice from the seed, so the same
/// request with the same seed returns the same layout **when the run ends
/// on its own budget** -- the generation or iteration count, convergence,
/// or the target utilization. A run cut short by the clock is not
/// reproduced: how far a search gets before `time_limit_ms` (or a
/// cancellation) stops it depends on the machine and its load. In 2D a
/// search keeps a time budget of its own even when `time_limit_ms` is 0
/// (15 s for GA and BRKGA, 10 s for SA, GDRR and ALNS), so a large 2D
/// request can reach it.
pub seed: Option<u64>,
}
impl Default for Config {
fn default() -> Self {
Self {
strategy: Strategy::default(),
spacing: 0.0,
margin: 0.0,
time_limit_ms: 30000,
target_utilization: None,
population_size: None,
max_generations: None,
crossover_rate: 0.85,
mutation_rate: 0.05,
elite_count: 5,
seed: None,
}
}
}
impl Config {
/// Creates a new configuration with default values.
pub fn new() -> Self {
Self::default()
}
/// Checks the fields a caller sets against their ranges -- the builders
/// store what they are given, and every solver calls this before it runs.
///
/// # Errors
/// `ConfigError` naming the first field out of range: `spacing` or
/// `margin` negative or not finite, `crossover_rate`/`mutation_rate` or
/// `target_utilization` outside `[0, 1]`, a `population_size` set below 2.
pub fn validate(&self) -> Result<()> {
use crate::error::{check_at_least, check_range};
check_at_least("spacing", self.spacing, 0.0)?;
check_at_least("margin", self.margin, 0.0)?;
if let Some(size) = self.population_size {
Self::check_population_size(size as i128)?;
}
check_range("crossover_rate", self.crossover_rate, 0.0, 1.0)?;
check_range("mutation_rate", self.mutation_rate, 0.0, 1.0)?;
if let Some(util) = self.target_utilization {
check_range("target_utilization", util, 0.0, 1.0)?;
}
Ok(())
}
/// A population size: at least 2, the fewest a generation can cross. A
/// request's value and a configuration's own are judged here alike.
pub(crate) fn check_population_size(value: i128) -> Result<usize> {
crate::error::whole_at_least("population_size", value, 2)
}
/// Sets the optimization strategy.
pub fn with_strategy(mut self, strategy: Strategy) -> Self {
self.strategy = strategy;
self
}
/// Sets the spacing between geometries.
pub fn with_spacing(mut self, spacing: f64) -> Self {
self.spacing = spacing;
self
}
/// Sets the margin from boundary edges.
pub fn with_margin(mut self, margin: f64) -> Self {
self.margin = margin;
self
}
/// Sets the time limit in milliseconds.
pub fn with_time_limit(mut self, ms: u64) -> Self {
self.time_limit_ms = ms;
self
}
/// Sets the target utilization.
pub fn with_target_utilization(mut self, util: f64) -> Self {
self.target_utilization = Some(util);
self
}
/// Sets the RNG seed for reproducible stochastic runs (see [`Config::seed`]).
pub fn with_seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
self
}
/// Sets the population size of the population-based strategies, in place
/// of each strategy's own (see [`Config::population_size`]).
pub fn with_population_size(mut self, size: usize) -> Self {
self.population_size = Some(size);
self
}
/// Sets the generation budget of the population-based strategies, in
/// place of each strategy's own (see [`Config::max_generations`]).
pub fn with_max_generations(mut self, generations: u32) -> Self {
self.max_generations = Some(generations);
self
}
}
/// Progress callback for long-running operations.
pub type ProgressCallback = Box<dyn Fn(ProgressInfo) + Send + Sync>;
/// Progress information during solving.
#[derive(Debug, Clone, Default)]
pub struct ProgressInfo {
/// Current iteration/generation number.
pub iteration: u32,
/// Total expected iterations (0 if unknown).
pub total_iterations: u32,
/// Current best utilization (0.0 to 1.0).
pub utilization: f64,
/// Current best fitness value.
pub best_fitness: f64,
/// Number of items placed.
pub items_placed: usize,
/// Total number of items.
pub total_items: usize,
/// Elapsed time in milliseconds.
pub elapsed_ms: u64,
/// Current phase/stage description.
pub phase: String,
/// Whether the solver is still running.
pub running: bool,
}
impl ProgressInfo {
/// Creates a new progress info with default values.
pub fn new() -> Self {
Self {
running: true,
..Default::default()
}
}
/// Sets the iteration info.
pub fn with_iteration(mut self, current: u32, total: u32) -> Self {
self.iteration = current;
self.total_iterations = total;
self
}
/// Sets the utilization.
pub fn with_utilization(mut self, utilization: f64) -> Self {
self.utilization = utilization;
self
}
/// Sets the best fitness.
pub fn with_fitness(mut self, fitness: f64) -> Self {
self.best_fitness = fitness;
self
}
/// Sets the items placed info.
pub fn with_items(mut self, placed: usize, total: usize) -> Self {
self.items_placed = placed;
self.total_items = total;
self
}
/// Sets the elapsed time.
pub fn with_elapsed(mut self, elapsed_ms: u64) -> Self {
self.elapsed_ms = elapsed_ms;
self
}
/// Sets the phase description.
pub fn with_phase(mut self, phase: impl Into<String>) -> Self {
self.phase = phase.into();
self
}
/// Marks the solver as finished.
pub fn finished(mut self) -> Self {
self.running = false;
self
}
/// Calculates the progress percentage (0.0 to 1.0).
pub fn progress_percent(&self) -> f64 {
if self.total_iterations > 0 {
self.iteration as f64 / self.total_iterations as f64
} else {
0.0
}
}
}
/// Trait for nesting/packing solvers.
pub trait Solver {
/// The geometry type this solver handles.
type Geometry: Geometry;
/// The boundary type this solver handles.
type Boundary: Boundary;
/// The scalar type for coordinates.
type Scalar;
/// Solves the nesting/packing problem.
fn solve(
&self,
geometries: &[Self::Geometry],
boundary: &Self::Boundary,
) -> Result<SolveResult<Self::Scalar>>;
/// Solves with a progress callback.
fn solve_with_progress(
&self,
geometries: &[Self::Geometry],
boundary: &Self::Boundary,
callback: ProgressCallback,
) -> Result<SolveResult<Self::Scalar>>;
/// Cancels an ongoing solve operation.
fn cancel(&self);
}
#[cfg(test)]
mod config_tests {
use super::Config;
#[test]
fn a_target_utilization_above_one_is_refused_not_clamped() {
let config = Config::default().with_target_utilization(1.5);
assert_eq!(config.target_utilization, Some(1.5), "stored as given");
let err = config.validate().expect_err("1.5 is not a utilization");
assert!(err.to_string().contains("target_utilization"), "{err}");
assert!(Config::default()
.with_target_utilization(0.9)
.validate()
.is_ok());
let nan_rate = Config {
mutation_rate: f64::NAN,
..Config::default()
};
assert!(nan_rate.validate().is_err());
}
/// A budget left unset is the strategy's to choose; one that is set is
/// stored as given and judged by `validate`.
#[test]
fn a_population_is_stored_as_given_and_judged_by_validate() {
let unset = Config::default();
assert_eq!(unset.population_size, None);
assert_eq!(unset.max_generations, None);
assert!(unset.validate().is_ok());
let set = Config::default()
.with_population_size(100)
.with_max_generations(0);
assert_eq!(set.population_size, Some(100));
assert_eq!(set.max_generations, Some(0), "0 generations is a budget");
assert!(set.validate().is_ok());
let one = Config::default().with_population_size(1);
assert_eq!(one.population_size, Some(1), "stored as given");
let err = one.validate().expect_err("a population of 1 cannot cross");
assert_eq!(err.code(), "parameter_out_of_range");
assert_eq!(
err.to_string(),
"population_size must be a whole number >= 2, got 1"
);
}
}