heuropt 0.11.0

A practical Rust toolkit for heuristic single-, multi-, and many-objective optimization.
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
//! `TabuSearch` — Glover 1986 tabu search with a user-supplied neighbor
//! generator and decision-level FIFO tabu list.

use std::collections::{HashSet, VecDeque};
use std::hash::Hash;

use crate::core::candidate::Candidate;
use crate::core::objective::Direction;
use crate::core::population::Population;
use crate::core::problem::Problem;
use crate::core::result::OptimizationResult;
use crate::core::rng::{Rng, rng_from_seed};
use crate::traits::{Initializer, Optimizer};

/// Configuration for [`TabuSearch`].
#[derive(Debug, Clone)]
pub struct TabuSearchConfig {
    /// Number of iterations.
    pub iterations: usize,
    /// Maximum size of the FIFO tabu list (older entries are evicted).
    pub tabu_tenure: usize,
    /// Seed for the deterministic RNG used by the neighbor generator.
    pub seed: u64,
}

impl Default for TabuSearchConfig {
    fn default() -> Self {
        Self {
            iterations: 500,
            tabu_tenure: 16,
            seed: 42,
        }
    }
}

/// Single-objective tabu search.
///
/// Each iteration the user-supplied `neighbors` closure produces a finite
/// list of candidate moves from the current incumbent. The best non-tabu
/// neighbor (or any tabu neighbor that improves the best-seen-ever
/// incumbent — the standard "aspiration" override) is accepted as the new
/// incumbent and its decision is appended to a FIFO tabu list of size
/// `tabu_tenure`. Tabu matches the full decision; users wanting move-based
/// tabu can wrap moves into a custom decision type.
pub struct TabuSearch<D, I, N>
where
    D: Clone + Hash + Eq,
    I: Initializer<D>,
    N: FnMut(&D, &mut Rng) -> Vec<D>,
{
    /// Algorithm configuration.
    pub config: TabuSearchConfig,
    /// Initial-decision sampler.
    pub initializer: I,
    /// Neighbor generator: produces a finite list of candidate moves from
    /// the current incumbent.
    pub neighbors: N,
    _marker: std::marker::PhantomData<D>,
}

impl<D, I, N> TabuSearch<D, I, N>
where
    D: Clone + Hash + Eq,
    I: Initializer<D>,
    N: FnMut(&D, &mut Rng) -> Vec<D>,
{
    /// Construct a `TabuSearch`.
    pub fn new(config: TabuSearchConfig, initializer: I, neighbors: N) -> Self {
        Self {
            config,
            initializer,
            neighbors,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<P, I, N> Optimizer<P> for TabuSearch<P::Decision, I, N>
where
    P: Problem + Sync,
    P::Decision: Clone + Hash + Eq + Send,
    I: Initializer<P::Decision>,
    N: FnMut(&P::Decision, &mut Rng) -> Vec<P::Decision>,
{
    fn run(&mut self, problem: &P) -> OptimizationResult<P::Decision> {
        let objectives = problem.objectives();
        assert!(
            objectives.is_single_objective(),
            "TabuSearch requires exactly one objective",
        );
        assert!(
            self.config.tabu_tenure >= 1,
            "TabuSearch tabu_tenure must be >= 1",
        );
        let direction = objectives.objectives[0].direction;
        let mut rng = rng_from_seed(self.config.seed);

        let mut initial = self.initializer.initialize(1, &mut rng);
        assert!(
            !initial.is_empty(),
            "TabuSearch initializer returned no decisions"
        );
        let mut current_decision = initial.remove(0);
        let mut current_eval = problem.evaluate(&current_decision);
        let mut best_decision = current_decision.clone();
        let mut best_eval = current_eval.clone();
        let mut evaluations = 1usize;

        let mut tabu_queue: VecDeque<P::Decision> =
            VecDeque::with_capacity(self.config.tabu_tenure);
        let mut tabu_set: HashSet<P::Decision> = HashSet::new();

        for _ in 0..self.config.iterations {
            let candidates = (self.neighbors)(&current_decision, &mut rng);
            if candidates.is_empty() {
                break;
            }

            // Best non-tabu candidate, OR best tabu candidate that beats the
            // best-seen-ever (aspiration).
            let mut best_idx: Option<usize> = None;
            let mut best_cand_eval: Option<crate::core::evaluation::Evaluation> = None;
            let evaluations_before = evaluations;
            let mut cand_evals: Vec<crate::core::evaluation::Evaluation> =
                Vec::with_capacity(candidates.len());
            for c in &candidates {
                cand_evals.push(problem.evaluate(c));
            }
            evaluations += candidates.len();
            let _ = evaluations_before;

            for (i, c) in candidates.iter().enumerate() {
                let is_tabu = tabu_set.contains(c);
                let aspires = is_tabu && better_than(&cand_evals[i], &best_eval, direction);
                if is_tabu && !aspires {
                    continue;
                }
                let eligible = match &best_cand_eval {
                    None => true,
                    Some(b) => better_than(&cand_evals[i], b, direction),
                };
                if eligible {
                    best_idx = Some(i);
                    best_cand_eval = Some(cand_evals[i].clone());
                }
            }

            // If everything is tabu and nothing aspires, fall back to the
            // best tabu candidate (avoid getting stuck).
            if best_idx.is_none() {
                for (i, _) in candidates.iter().enumerate() {
                    let eligible = match &best_cand_eval {
                        None => true,
                        Some(b) => better_than(&cand_evals[i], b, direction),
                    };
                    if eligible {
                        best_idx = Some(i);
                        best_cand_eval = Some(cand_evals[i].clone());
                    }
                }
            }

            let chosen_idx = best_idx.expect("non-empty candidate list");
            let chosen_decision = candidates[chosen_idx].clone();
            current_eval = cand_evals.remove(chosen_idx);
            current_decision = chosen_decision.clone();

            if better_than(&current_eval, &best_eval, direction) {
                best_decision = current_decision.clone();
                best_eval = current_eval.clone();
            }

            // Update FIFO tabu list.
            tabu_queue.push_back(chosen_decision.clone());
            tabu_set.insert(chosen_decision);
            if tabu_queue.len() > self.config.tabu_tenure {
                if let Some(old) = tabu_queue.pop_front() {
                    tabu_set.remove(&old);
                }
            }
        }

        let best = Candidate::new(best_decision, best_eval);
        let population = Population::new(vec![best.clone()]);
        let front = vec![best.clone()];
        OptimizationResult::new(
            population,
            front,
            Some(best),
            evaluations,
            self.config.iterations,
        )
    }
}

fn better_than(
    a: &crate::core::evaluation::Evaluation,
    b: &crate::core::evaluation::Evaluation,
    direction: Direction,
) -> bool {
    match (a.is_feasible(), b.is_feasible()) {
        (true, false) => true,
        (false, true) => false,
        (false, false) => a.constraint_violation < b.constraint_violation,
        (true, true) => match direction {
            Direction::Minimize => a.objectives[0] < b.objectives[0],
            Direction::Maximize => a.objectives[0] > b.objectives[0],
        },
    }
}

#[cfg(feature = "async")]
impl<D, I, N> TabuSearch<D, I, N>
where
    D: Clone + Hash + Eq,
    I: Initializer<D>,
    N: FnMut(&D, &mut Rng) -> Vec<D>,
{
    /// Async version of [`Optimizer::run`] — drives evaluations through
    /// the user-chosen async runtime. Available only with the `async`
    /// feature.
    ///
    /// Each iteration evaluates the K neighbors of the current
    /// incumbent concurrently (bounded by `concurrency`), then picks
    /// the best non-tabu (or aspiration-passing) move.
    pub async fn run_async<P>(&mut self, problem: &P, concurrency: usize) -> OptimizationResult<D>
    where
        P: crate::core::async_problem::AsyncProblem<Decision = D>,
        D: Send + Sync,
    {
        use crate::algorithms::parallel_eval_async::evaluate_batch_async;

        let objectives = problem.objectives();
        assert!(
            objectives.is_single_objective(),
            "TabuSearch requires exactly one objective",
        );
        assert!(
            self.config.tabu_tenure >= 1,
            "TabuSearch tabu_tenure must be >= 1",
        );
        let direction = objectives.objectives[0].direction;
        let mut rng = rng_from_seed(self.config.seed);

        let mut initial = self.initializer.initialize(1, &mut rng);
        assert!(
            !initial.is_empty(),
            "TabuSearch initializer returned no decisions"
        );
        let mut current_decision = initial.remove(0);
        let mut current_eval = problem.evaluate_async(&current_decision).await;
        let mut best_decision = current_decision.clone();
        let mut best_eval = current_eval.clone();
        let mut evaluations = 1usize;

        let mut tabu_queue: VecDeque<D> = VecDeque::with_capacity(self.config.tabu_tenure);
        let mut tabu_set: HashSet<D> = HashSet::new();

        for _ in 0..self.config.iterations {
            let candidates = (self.neighbors)(&current_decision, &mut rng);
            if candidates.is_empty() {
                break;
            }

            let cand_results = evaluate_batch_async(problem, candidates.clone(), concurrency).await;
            let mut cand_evals: Vec<crate::core::evaluation::Evaluation> =
                cand_results.into_iter().map(|c| c.evaluation).collect();
            evaluations += candidates.len();

            let mut best_idx: Option<usize> = None;
            let mut best_cand_eval: Option<crate::core::evaluation::Evaluation> = None;

            for (i, c) in candidates.iter().enumerate() {
                let is_tabu = tabu_set.contains(c);
                let aspires = is_tabu && better_than(&cand_evals[i], &best_eval, direction);
                if is_tabu && !aspires {
                    continue;
                }
                let eligible = match &best_cand_eval {
                    None => true,
                    Some(b) => better_than(&cand_evals[i], b, direction),
                };
                if eligible {
                    best_idx = Some(i);
                    best_cand_eval = Some(cand_evals[i].clone());
                }
            }

            if best_idx.is_none() {
                for (i, _) in candidates.iter().enumerate() {
                    let eligible = match &best_cand_eval {
                        None => true,
                        Some(b) => better_than(&cand_evals[i], b, direction),
                    };
                    if eligible {
                        best_idx = Some(i);
                        best_cand_eval = Some(cand_evals[i].clone());
                    }
                }
            }

            let chosen_idx = best_idx.expect("non-empty candidate list");
            let chosen_decision = candidates[chosen_idx].clone();
            current_eval = cand_evals.remove(chosen_idx);
            current_decision = chosen_decision.clone();

            if better_than(&current_eval, &best_eval, direction) {
                best_decision = current_decision.clone();
                best_eval = current_eval.clone();
            }

            tabu_queue.push_back(chosen_decision.clone());
            tabu_set.insert(chosen_decision);
            if tabu_queue.len() > self.config.tabu_tenure {
                if let Some(old) = tabu_queue.pop_front() {
                    tabu_set.remove(&old);
                }
            }
        }

        let best = Candidate::new(best_decision, best_eval);
        let population = Population::new(vec![best.clone()]);
        let front = vec![best.clone()];
        OptimizationResult::new(
            population,
            front,
            Some(best),
            evaluations,
            self.config.iterations,
        )
    }
}

impl<D, I, N> crate::traits::AlgorithmInfo for TabuSearch<D, I, N>
where
    D: Clone + Hash + Eq,
    I: Initializer<D>,
    N: FnMut(&D, &mut Rng) -> Vec<D>,
{
    fn name(&self) -> &'static str {
        "Tabu Search"
    }
    fn seed(&self) -> Option<u64> {
        Some(self.config.seed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::evaluation::Evaluation;
    use crate::core::objective::{Objective, ObjectiveSpace};
    use rand::Rng as _;

    /// Trivial integer-grid problem: minimize `(x - 7)^2`.
    struct GridProblem;
    impl Problem for GridProblem {
        type Decision = Vec<i32>;

        fn objectives(&self) -> ObjectiveSpace {
            ObjectiveSpace::new(vec![Objective::minimize("f")])
        }

        fn evaluate(&self, x: &Vec<i32>) -> Evaluation {
            let v = (x[0] - 7) as f64;
            Evaluation::new(vec![v * v])
        }
    }

    /// Initialize a single 1-D integer at 0.
    struct StartAtZero;
    impl Initializer<Vec<i32>> for StartAtZero {
        fn initialize(&mut self, size: usize, _rng: &mut Rng) -> Vec<Vec<i32>> {
            (0..size).map(|_| vec![0]).collect()
        }
    }

    fn make_optimizer<F>(seed: u64, neighbors: F) -> TabuSearch<Vec<i32>, StartAtZero, F>
    where
        F: FnMut(&Vec<i32>, &mut Rng) -> Vec<Vec<i32>>,
    {
        TabuSearch::new(
            TabuSearchConfig {
                iterations: 50,
                tabu_tenure: 4,
                seed,
            },
            StartAtZero,
            neighbors,
        )
    }

    #[test]
    fn finds_optimum_on_grid() {
        // Neighbors: ±1 of current value.
        let neighbors = |x: &Vec<i32>, _rng: &mut Rng| vec![vec![x[0] - 1], vec![x[0] + 1]];
        let mut opt = make_optimizer(1, neighbors);
        let r = opt.run(&GridProblem);
        let best = r.best.unwrap();
        assert_eq!(best.decision, vec![7]);
        assert_eq!(best.evaluation.objectives, vec![0.0]);
    }

    #[test]
    fn deterministic_with_same_seed() {
        let neighbors = |x: &Vec<i32>, rng: &mut Rng| {
            (0..5)
                .map(|_| vec![x[0] + rng.random_range(-3..=3)])
                .collect::<Vec<_>>()
        };
        let mut a = make_optimizer(99, neighbors);
        let mut b = make_optimizer(99, |x: &Vec<i32>, rng: &mut Rng| {
            (0..5)
                .map(|_| vec![x[0] + rng.random_range(-3..=3)])
                .collect::<Vec<_>>()
        });
        let ra = a.run(&GridProblem);
        let rb = b.run(&GridProblem);
        assert_eq!(
            ra.best.unwrap().evaluation.objectives,
            rb.best.unwrap().evaluation.objectives,
        );
    }

    // ---- Mutation-test pinned helpers --------------------------------------

    #[test]
    fn better_than_feasibility_first_and_direction() {
        use crate::core::objective::Direction;
        let feasible = Evaluation::new(vec![100.0]);
        let infeasible = Evaluation::constrained(vec![0.0], 1.0);
        assert!(better_than(&feasible, &infeasible, Direction::Minimize));
        assert!(!better_than(&infeasible, &feasible, Direction::Minimize));
        let lo = Evaluation::new(vec![1.0]);
        let hi = Evaluation::new(vec![2.0]);
        assert!(better_than(&lo, &hi, Direction::Minimize));
        assert!(better_than(&hi, &lo, Direction::Maximize));
        let eq = Evaluation::new(vec![1.0]);
        assert!(!better_than(&lo, &eq, Direction::Minimize));
        let v_lo = Evaluation::constrained(vec![0.0], 0.2);
        let v_hi = Evaluation::constrained(vec![0.0], 0.8);
        assert!(better_than(&v_lo, &v_hi, Direction::Minimize));
    }
}