solverforge_solver/heuristic/selector/ruin.rs
1/* Ruin move selector for Large Neighborhood Search.
2
3Generates `RuinMove` instances that unassign subsets of entities,
4enabling exploration of distant regions in the solution space.
5
6# Zero-Erasure Design
7
8Uses `fn` pointers for variable access and entity counting.
9No `Arc<dyn Fn>`, no trait objects in hot paths.
10
11# Example
12
13```
14use solverforge_solver::heuristic::selector::{MoveSelector, RuinMoveSelector};
15use solverforge_solver::heuristic::r#move::RuinMove;
16use solverforge_core::domain::PlanningSolution;
17use solverforge_core::score::SoftScore;
18use solverforge_scoring::{Director, ScoreDirector};
19use solverforge_core::domain::SolutionDescriptor;
20use std::any::TypeId;
21
22#[derive(Clone, Debug)]
23struct Task { assigned_to: Option<i32> }
24
25#[derive(Clone, Debug)]
26struct Schedule { tasks: Vec<Task>, score: Option<SoftScore> }
27
28impl PlanningSolution for Schedule {
29type Score = SoftScore;
30fn score(&self) -> Option<Self::Score> { self.score }
31fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
32}
33
34fn entity_count(s: &Schedule) -> usize { s.tasks.len() }
35fn get_task(s: &Schedule, idx: usize) -> Option<i32> {
36s.tasks.get(idx).and_then(|t| t.assigned_to)
37}
38fn set_task(s: &mut Schedule, idx: usize, v: Option<i32>) {
39if let Some(t) = s.tasks.get_mut(idx) { t.assigned_to = v; }
40}
41
42// Create selector that ruins 2-3 entities at a time
43let selector = RuinMoveSelector::<Schedule, i32>::new(
442, 3,
45entity_count,
46get_task, set_task,
47"assigned_to", 0,
48);
49
50// Use with a score director
51let solution = Schedule {
52tasks: vec![
53Task { assigned_to: Some(1) },
54Task { assigned_to: Some(2) },
55Task { assigned_to: Some(3) },
56],
57score: None,
58};
59let descriptor = SolutionDescriptor::new("Schedule", TypeId::of::<Schedule>());
60let director = ScoreDirector::simple(
61solution, descriptor, |s, _| s.tasks.len()
62);
63
64let moves: Vec<_> = selector.iter_moves(&director).collect();
65assert!(!moves.is_empty());
66```
67*/
68
69use std::fmt::Debug;
70use std::marker::PhantomData;
71
72use rand::rngs::StdRng;
73use rand::{RngExt, SeedableRng};
74use smallvec::SmallVec;
75use solverforge_core::domain::PlanningSolution;
76use solverforge_scoring::Director;
77
78use crate::heuristic::r#move::RuinMove;
79
80use super::MoveSelector;
81
82/// A move selector that generates `RuinMove` instances for Large Neighborhood Search.
83///
84/// Selects random subsets of entities to "ruin" (unassign), enabling a construction
85/// heuristic to reassign them in potentially better configurations.
86///
87/// # Type Parameters
88/// * `S` - The planning solution type
89/// * `V` - The variable value type
90///
91/// # Zero-Erasure
92///
93/// All variable access uses `fn` pointers:
94/// - `getter: fn(&S, usize) -> Option<V>` - gets current value
95/// - `setter: fn(&mut S, usize, Option<V>)` - sets value
96/// - `entity_count: fn(&S) -> usize` - counts entities
97pub struct RuinMoveSelector<S, V> {
98 // Minimum entities to include in each ruin move.
99 min_ruin_count: usize,
100 // Maximum entities to include in each ruin move.
101 max_ruin_count: usize,
102 // Random seed for reproducible subset selection.
103 seed: Option<u64>,
104 // Function to get entity count from solution.
105 entity_count: fn(&S) -> usize,
106 // Function to get current value.
107 getter: fn(&S, usize) -> Option<V>,
108 // Function to set value.
109 setter: fn(&mut S, usize, Option<V>),
110 // Variable name.
111 variable_name: &'static str,
112 // Entity descriptor index.
113 descriptor_index: usize,
114 // Number of ruin moves to generate per iteration.
115 moves_per_step: usize,
116 _phantom: PhantomData<fn() -> V>,
117}
118
119impl<S, V: Debug> Debug for RuinMoveSelector<S, V> {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.debug_struct("RuinMoveSelector")
122 .field("min_ruin_count", &self.min_ruin_count)
123 .field("max_ruin_count", &self.max_ruin_count)
124 .field("moves_per_step", &self.moves_per_step)
125 .field("variable_name", &self.variable_name)
126 .field("descriptor_index", &self.descriptor_index)
127 .finish()
128 }
129}
130
131impl<S, V> RuinMoveSelector<S, V> {
132 /// Creates a new ruin move selector with typed function pointers.
133 ///
134 /// # Arguments
135 /// * `min_ruin_count` - Minimum entities to ruin (at least 1)
136 /// * `max_ruin_count` - Maximum entities to ruin
137 /// * `entity_count` - Function to get total entity count
138 /// * `getter` - Function to get current value
139 /// * `setter` - Function to set value
140 /// * `variable_name` - Name of the planning variable
141 /// * `descriptor_index` - Entity descriptor index
142 ///
143 /// # Panics
144 /// Panics if `min_ruin_count` is 0 or `max_ruin_count < min_ruin_count`.
145 pub fn new(
146 min_ruin_count: usize,
147 max_ruin_count: usize,
148 entity_count: fn(&S) -> usize,
149 getter: fn(&S, usize) -> Option<V>,
150 setter: fn(&mut S, usize, Option<V>),
151 variable_name: &'static str,
152 descriptor_index: usize,
153 ) -> Self {
154 assert!(min_ruin_count >= 1, "min_ruin_count must be at least 1");
155 assert!(
156 max_ruin_count >= min_ruin_count,
157 "max_ruin_count must be >= min_ruin_count"
158 );
159
160 Self {
161 min_ruin_count,
162 max_ruin_count,
163 seed: None,
164 entity_count,
165 getter,
166 setter,
167 variable_name,
168 descriptor_index,
169 moves_per_step: 10, // Default: generate 10 ruin moves per step
170 _phantom: PhantomData,
171 }
172 }
173
174 /// Sets the number of ruin moves to generate per iteration.
175 ///
176 /// Default is 10.
177 pub fn with_moves_per_step(mut self, count: usize) -> Self {
178 self.moves_per_step = count;
179 self
180 }
181
182 pub fn with_seed(mut self, seed: u64) -> Self {
183 self.seed = Some(seed);
184 self
185 }
186
187 fn create_rng(&self) -> StdRng {
188 match self.seed {
189 Some(seed) => StdRng::seed_from_u64(seed),
190 None => StdRng::from_rng(&mut rand::rng()),
191 }
192 }
193}
194
195impl<S, V> MoveSelector<S, RuinMove<S, V>> for RuinMoveSelector<S, V>
196where
197 S: PlanningSolution,
198 V: Clone + Send + Sync + Debug + 'static,
199{
200 fn iter_moves<'a, D: Director<S>>(
201 &'a self,
202 score_director: &'a D,
203 ) -> impl Iterator<Item = RuinMove<S, V>> + 'a {
204 let total_entities = (self.entity_count)(score_director.working_solution());
205 let getter = self.getter;
206 let setter = self.setter;
207 let variable_name = self.variable_name;
208 let descriptor_index = self.descriptor_index;
209
210 let min = self.min_ruin_count.min(total_entities);
211 let max = self.max_ruin_count.min(total_entities);
212 let moves_count = self.moves_per_step;
213
214 // Pre-generate subsets using RNG
215 let mut rng = self.create_rng();
216 let subsets: Vec<SmallVec<[usize; 8]>> = (0..moves_count)
217 .map(|_| {
218 if total_entities == 0 {
219 return SmallVec::new();
220 }
221 let ruin_count = if min == max {
222 min
223 } else {
224 rng.random_range(min..=max)
225 };
226 let mut indices: SmallVec<[usize; 8]> = (0..total_entities).collect();
227 for i in 0..ruin_count {
228 let j = rng.random_range(i..total_entities);
229 indices.swap(i, j);
230 }
231 indices.truncate(ruin_count);
232 indices
233 })
234 .collect();
235
236 subsets.into_iter().map(move |indices| {
237 RuinMove::new(&indices, getter, setter, variable_name, descriptor_index)
238 })
239 }
240
241 fn size<D: Director<S>>(&self, score_director: &D) -> usize {
242 let total = (self.entity_count)(score_director.working_solution());
243 if total == 0 {
244 return 0;
245 }
246 // Return configured moves per step (not combinatorial count)
247 self.moves_per_step
248 }
249
250 fn is_never_ending(&self) -> bool {
251 // Random selection means we could generate moves indefinitely
252 false
253 }
254}