Skip to main content

solverforge_solver/heuristic/move/
ruin.rs

1/* RuinMove - unassigns a subset of entities for Large Neighborhood Search.
2
3This move "ruins" (unassigns) selected entities, allowing a construction
4heuristic to reassign them. This is the fundamental building block for
5Large Neighborhood Search (LNS) algorithms.
6
7# Zero-Erasure Design
8
9Uses concrete function pointers for variable access. No `dyn Any`, no downcasting.
10*/
11
12use std::fmt::Debug;
13
14use smallvec::SmallVec;
15use solverforge_core::domain::PlanningSolution;
16use solverforge_scoring::Director;
17
18use super::metadata::{
19    encode_option_debug, encode_usize, hash_str, MoveTabuScope, ScopedEntityTabuToken,
20};
21use super::{Move, MoveTabuSignature};
22
23/// A move that unassigns multiple entities for Large Neighborhood Search.
24///
25/// This move sets the planning variable to `None` for a set of entities,
26/// creating "gaps" that a construction heuristic can fill. Combined with
27/// construction, this enables exploring distant regions of the search space.
28///
29/// # Type Parameters
30/// * `S` - The planning solution type
31/// * `V` - The variable value type
32///
33/// # Example
34///
35/// ```
36/// use solverforge_solver::heuristic::r#move::RuinMove;
37/// use solverforge_core::domain::PlanningSolution;
38/// use solverforge_core::score::SoftScore;
39///
40/// #[derive(Clone, Debug)]
41/// struct Task { assigned_to: Option<i32>, score: Option<SoftScore> }
42/// #[derive(Clone, Debug)]
43/// struct Schedule { tasks: Vec<Task>, score: Option<SoftScore> }
44///
45/// impl PlanningSolution for Schedule {
46///     type Score = SoftScore;
47///     fn score(&self) -> Option<Self::Score> { self.score }
48///     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
49/// }
50///
51/// fn get_task(s: &Schedule, idx: usize, _var: usize) -> Option<i32> {
52///     s.tasks.get(idx).and_then(|t| t.assigned_to)
53/// }
54/// fn set_task(s: &mut Schedule, idx: usize, _var: usize, v: Option<i32>) {
55///     if let Some(t) = s.tasks.get_mut(idx) { t.assigned_to = v; }
56/// }
57///
58/// // Ruin entities 0, 2, and 4
59/// let m = RuinMove::<Schedule, i32>::new(
60///     &[0, 2, 4],
61///     get_task, set_task,
62///     0, "assigned_to", 0,
63/// );
64/// ```
65pub struct RuinMove<S, V> {
66    // Indices of entities to unassign
67    entity_indices: SmallVec<[usize; 8]>,
68    getter: fn(&S, usize, usize) -> Option<V>,
69    // Set value for an entity
70    setter: fn(&mut S, usize, usize, Option<V>),
71    variable_index: usize,
72    variable_name: &'static str,
73    descriptor_index: usize,
74}
75
76impl<S, V: Debug> Debug for RuinMove<S, V> {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("RuinMove")
79            .field("entities", &self.entity_indices.as_slice())
80            .field("variable_index", &self.variable_index)
81            .field("variable_name", &self.variable_name)
82            .finish()
83    }
84}
85
86impl<S, V> RuinMove<S, V> {
87    /// Creates a new ruin move with concrete function pointers.
88    ///
89    /// # Arguments
90    /// * `entity_indices` - Indices of entities to unassign
91    /// * `getter` - Function to get current value
92    /// * `setter` - Function to set value
93    /// * `variable_name` - Name of the planning variable
94    /// * `descriptor_index` - Entity descriptor index
95    pub fn new(
96        entity_indices: &[usize],
97        getter: fn(&S, usize, usize) -> Option<V>,
98        setter: fn(&mut S, usize, usize, Option<V>),
99        variable_index: usize,
100        variable_name: &'static str,
101        descriptor_index: usize,
102    ) -> Self {
103        Self::from_indices(
104            SmallVec::from_slice(entity_indices),
105            getter,
106            setter,
107            variable_index,
108            variable_name,
109            descriptor_index,
110        )
111    }
112
113    pub(crate) fn from_indices(
114        entity_indices: SmallVec<[usize; 8]>,
115        getter: fn(&S, usize, usize) -> Option<V>,
116        setter: fn(&mut S, usize, usize, Option<V>),
117        variable_index: usize,
118        variable_name: &'static str,
119        descriptor_index: usize,
120    ) -> Self {
121        Self {
122            entity_indices,
123            getter,
124            setter,
125            variable_index,
126            variable_name,
127            descriptor_index,
128        }
129    }
130
131    pub fn entity_indices_slice(&self) -> &[usize] {
132        &self.entity_indices
133    }
134
135    pub fn ruin_count(&self) -> usize {
136        self.entity_indices.len()
137    }
138}
139
140impl<S, V> Move<S> for RuinMove<S, V>
141where
142    S: PlanningSolution,
143    V: Clone + Send + Sync + Debug + 'static,
144{
145    type Undo = SmallVec<[(usize, Option<V>); 8]>;
146
147    fn is_doable<D: Director<S>>(&self, score_director: &D) -> bool {
148        // At least one entity must be currently assigned
149        let solution = score_director.working_solution();
150        self.entity_indices
151            .iter()
152            .any(|&idx| (self.getter)(solution, idx, self.variable_index).is_some())
153    }
154
155    fn do_move<D: Director<S>>(&self, score_director: &mut D) -> Self::Undo {
156        let getter = self.getter;
157        let setter = self.setter;
158        let descriptor = self.descriptor_index;
159        let variable_index = self.variable_index;
160
161        // Collect old values for undo
162        let old_values: SmallVec<[(usize, Option<V>); 8]> = self
163            .entity_indices
164            .iter()
165            .map(|&idx| {
166                let old = getter(score_director.working_solution(), idx, variable_index);
167                (idx, old)
168            })
169            .collect();
170
171        // Unassign all entities
172        for &idx in &self.entity_indices {
173            score_director.before_variable_changed(descriptor, idx);
174            setter(
175                score_director.working_solution_mut(),
176                idx,
177                variable_index,
178                None,
179            );
180            score_director.after_variable_changed(descriptor, idx);
181        }
182
183        old_values
184    }
185
186    fn undo_move<D: Director<S>>(&self, score_director: &mut D, undo: Self::Undo) {
187        for (idx, _) in &undo {
188            score_director.before_variable_changed(self.descriptor_index, *idx);
189        }
190        for (idx, old_value) in undo {
191            (self.setter)(
192                score_director.working_solution_mut(),
193                idx,
194                self.variable_index,
195                old_value,
196            );
197        }
198        for &idx in &self.entity_indices {
199            score_director.after_variable_changed(self.descriptor_index, idx);
200        }
201    }
202
203    fn descriptor_index(&self) -> usize {
204        self.descriptor_index
205    }
206
207    fn entity_indices(&self) -> &[usize] {
208        &self.entity_indices
209    }
210
211    fn variable_name(&self) -> &str {
212        self.variable_name
213    }
214
215    fn tabu_signature<D: Director<S>>(&self, score_director: &D) -> MoveTabuSignature {
216        let scope = MoveTabuScope::new(self.descriptor_index, self.variable_name);
217        let entity_ids: SmallVec<[u64; 2]> = self
218            .entity_indices
219            .iter()
220            .map(|&idx| encode_usize(idx))
221            .collect();
222        let entity_tokens: SmallVec<[ScopedEntityTabuToken; 2]> = entity_ids
223            .iter()
224            .copied()
225            .map(|entity_id| scope.entity_token(entity_id))
226            .collect();
227        let mut value_ids: SmallVec<[u64; 2]> = SmallVec::new();
228        for &idx in &self.entity_indices {
229            let value = (self.getter)(score_director.working_solution(), idx, self.variable_index);
230            value_ids.push(encode_option_debug(value.as_ref()));
231        }
232        let variable_id = hash_str(self.variable_name);
233        let mut move_id = SmallVec::<[u64; 8]>::from_slice(&[
234            encode_usize(self.descriptor_index),
235            variable_id,
236            encode_usize(self.entity_indices.len()),
237        ]);
238        move_id.extend(entity_ids.iter().copied());
239        move_id.extend(value_ids.iter().copied());
240
241        MoveTabuSignature::new_self_undoing(scope, move_id).with_entity_tokens(entity_tokens)
242    }
243}