Skip to main content

solverforge_solver/heuristic/move/
list_ruin.rs

1//! ListRuinMove - ruin-and-recreate move for Large Neighborhood Search on list variables.
2//!
3//! Removes selected elements from a list entity, then greedily reinserts each
4//! one into the best available position across all entities. This makes the move
5//! self-contained: it can be accepted by a local search acceptor without leaving
6//! the solution in a degenerate state.
7//!
8//! # Zero-Erasure Design
9//!
10//! Uses typed function pointers for list operations. No `dyn Any`, no downcasting.
11
12use std::fmt::Debug;
13use std::marker::PhantomData;
14
15use smallvec::SmallVec;
16use solverforge_core::domain::PlanningSolution;
17use solverforge_scoring::ScoreDirector;
18
19use super::Move;
20
21/// A ruin-and-recreate move for Large Neighborhood Search on list variables.
22///
23/// Removes selected elements from a source entity, then reinserts each one
24/// greedily into the best position across all entities (including the source).
25/// The move is self-contained: accepting it leaves the solution valid.
26///
27/// # Type Parameters
28/// * `S` - The planning solution type
29/// * `V` - The list element value type
30///
31/// # Example
32///
33/// ```
34/// use solverforge_solver::heuristic::r#move::ListRuinMove;
35/// use solverforge_core::domain::PlanningSolution;
36/// use solverforge_core::score::SimpleScore;
37///
38/// #[derive(Clone, Debug)]
39/// struct Route { stops: Vec<i32>, score: Option<SimpleScore> }
40///
41/// impl PlanningSolution for Route {
42///     type Score = SimpleScore;
43///     fn score(&self) -> Option<Self::Score> { self.score }
44///     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
45/// }
46///
47/// fn entity_count(s: &Route) -> usize { 1 }
48/// fn list_len(s: &Route, _: usize) -> usize { s.stops.len() }
49/// fn list_remove(s: &mut Route, _: usize, idx: usize) -> i32 { s.stops.remove(idx) }
50/// fn list_insert(s: &mut Route, _: usize, idx: usize, v: i32) { s.stops.insert(idx, v); }
51///
52/// // Ruin elements at indices 1 and 3, then recreate greedily
53/// let m = ListRuinMove::<Route, i32>::new(
54///     0,
55///     &[1, 3],
56///     entity_count,
57///     list_len, list_remove, list_insert,
58///     "stops", 0,
59/// );
60/// ```
61pub struct ListRuinMove<S, V> {
62    /// Entity index to ruin from
63    entity_index: usize,
64    /// Indices of elements to remove (sorted ascending)
65    element_indices: SmallVec<[usize; 8]>,
66    /// Number of entities in solution (for recreate phase)
67    entity_count: fn(&S) -> usize,
68    /// Get list length
69    list_len: fn(&S, usize) -> usize,
70    /// Remove element at index, returning it
71    list_remove: fn(&mut S, usize, usize) -> V,
72    /// Insert element at index
73    list_insert: fn(&mut S, usize, usize, V),
74    variable_name: &'static str,
75    descriptor_index: usize,
76    _phantom: PhantomData<fn() -> V>,
77}
78
79impl<S, V> Clone for ListRuinMove<S, V> {
80    fn clone(&self) -> Self {
81        Self {
82            entity_index: self.entity_index,
83            element_indices: self.element_indices.clone(),
84            entity_count: self.entity_count,
85            list_len: self.list_len,
86            list_remove: self.list_remove,
87            list_insert: self.list_insert,
88            variable_name: self.variable_name,
89            descriptor_index: self.descriptor_index,
90            _phantom: PhantomData,
91        }
92    }
93}
94
95impl<S, V: Debug> Debug for ListRuinMove<S, V> {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.debug_struct("ListRuinMove")
98            .field("entity", &self.entity_index)
99            .field("elements", &self.element_indices.as_slice())
100            .field("variable_name", &self.variable_name)
101            .finish()
102    }
103}
104
105impl<S, V> ListRuinMove<S, V> {
106    /// Creates a new list ruin-and-recreate move.
107    ///
108    /// # Arguments
109    /// * `entity_index` - Entity index to ruin from
110    /// * `element_indices` - Indices of elements to remove
111    /// * `entity_count` - Function returning total entity count
112    /// * `list_len` - Function to get list length for an entity
113    /// * `list_remove` - Function to remove element at index
114    /// * `list_insert` - Function to insert element at index
115    /// * `variable_name` - Name of the list variable
116    /// * `descriptor_index` - Entity descriptor index
117    #[allow(clippy::too_many_arguments)]
118    pub fn new(
119        entity_index: usize,
120        element_indices: &[usize],
121        entity_count: fn(&S) -> usize,
122        list_len: fn(&S, usize) -> usize,
123        list_remove: fn(&mut S, usize, usize) -> V,
124        list_insert: fn(&mut S, usize, usize, V),
125        variable_name: &'static str,
126        descriptor_index: usize,
127    ) -> Self {
128        let mut indices: SmallVec<[usize; 8]> = SmallVec::from_slice(element_indices);
129        indices.sort_unstable();
130        Self {
131            entity_index,
132            element_indices: indices,
133            entity_count,
134            list_len,
135            list_remove,
136            list_insert,
137            variable_name,
138            descriptor_index,
139            _phantom: PhantomData,
140        }
141    }
142
143    /// Returns the entity index.
144    pub fn entity_index(&self) -> usize {
145        self.entity_index
146    }
147
148    /// Returns the element indices being removed.
149    pub fn element_indices(&self) -> &[usize] {
150        &self.element_indices
151    }
152
153    /// Returns the number of elements being removed.
154    pub fn ruin_count(&self) -> usize {
155        self.element_indices.len()
156    }
157}
158
159impl<S, V> Move<S> for ListRuinMove<S, V>
160where
161    S: PlanningSolution,
162    V: Clone + Send + Sync + Debug + 'static,
163{
164    fn is_doable<D: ScoreDirector<S>>(&self, score_director: &D) -> bool {
165        if self.element_indices.is_empty() {
166            return false;
167        }
168        let solution = score_director.working_solution();
169        let len = (self.list_len)(solution, self.entity_index);
170        self.element_indices.iter().all(|&idx| idx < len)
171    }
172
173    fn do_move<D: ScoreDirector<S>>(&self, score_director: &mut D) {
174        let list_remove = self.list_remove;
175        let list_insert = self.list_insert;
176        let list_len = self.list_len;
177        let entity_count = self.entity_count;
178        let src = self.entity_index;
179        let descriptor = self.descriptor_index;
180
181        // --- Ruin phase: remove elements from source entity ---
182        score_director.before_variable_changed(descriptor, src);
183        let mut removed: SmallVec<[V; 8]> = SmallVec::new();
184        for &idx in self.element_indices.iter().rev() {
185            let value = list_remove(score_director.working_solution_mut(), src, idx);
186            removed.push(value);
187        }
188        // removed is in reverse removal order; reverse to get original order
189        removed.reverse();
190        score_director.after_variable_changed(descriptor, src);
191
192        // --- Recreate phase: greedily reinsert each element at best position ---
193        // Track where each element ends up for the undo closure.
194        let mut placements: SmallVec<[(usize, usize); 8]> = SmallVec::new();
195
196        let n_entities = entity_count(score_director.working_solution());
197
198        for elem in removed.iter() {
199            let mut best_score: Option<S::Score> = None;
200            let mut best_entity = src;
201            let mut best_pos = list_len(score_director.working_solution(), src);
202
203            for e in 0..n_entities {
204                let len = list_len(score_director.working_solution(), e);
205                for pos in 0..=len {
206                    score_director.before_variable_changed(descriptor, e);
207                    list_insert(score_director.working_solution_mut(), e, pos, elem.clone());
208                    score_director.after_variable_changed(descriptor, e);
209
210                    let candidate_score = score_director.calculate_score();
211                    if best_score.is_none_or(|b| candidate_score > b) {
212                        best_score = Some(candidate_score);
213                        best_entity = e;
214                        best_pos = pos;
215                    }
216
217                    score_director.before_variable_changed(descriptor, e);
218                    list_remove(score_director.working_solution_mut(), e, pos);
219                    score_director.after_variable_changed(descriptor, e);
220                }
221            }
222
223            // Apply the best insertion permanently
224            score_director.before_variable_changed(descriptor, best_entity);
225            list_insert(
226                score_director.working_solution_mut(),
227                best_entity,
228                best_pos,
229                elem.clone(),
230            );
231            score_director.after_variable_changed(descriptor, best_entity);
232
233            // Store the placement as recorded at insertion time (no adjustment needed;
234            // undo will compute actual current positions accounting for later insertions).
235            placements.push((best_entity, best_pos));
236        }
237
238        // --- Register undo ---
239        // placements[i] = (entity, pos) at the moment element i was inserted.
240        // Later insertions j > i into the same entity at pos <= placements[i].pos
241        // shifted element i rightward by 1 for each such j.
242        // During undo we process in reverse: remove last-placed first.
243        // At that point, only placements[j] with j > i (already removed) have been
244        // undone, so the current position of element i is:
245        //   placements[i].pos + #{j > i : same entity AND placements[j].pos <= placements[i].pos}
246        // which we compute on the fly as we iterate in reverse.
247        //
248        // After collecting values, reinsert at original indices (ascending) in source entity.
249        // Reinserting at orig_indices[k] in order k=0,1,... shifts later indices by 1,
250        // but orig_indices is sorted ascending so each insertion at idx shifts positions > idx,
251        // which are exactly the later orig_indices — so we insert at orig_indices[k] + k
252        // to account for the k prior insertions that each shifted by 1.
253        let orig_entity = src;
254        let orig_indices: SmallVec<[usize; 8]> = self.element_indices.clone();
255
256        score_director.register_undo(Box::new(move |s: &mut S| {
257            let n = placements.len();
258
259            // Compute current_pos[i] = position of element i after all n insertions.
260            // current_pos[i] = placements[i].pos + #{j>i : same entity, placements[j].pos <= current_pos[i-so-far]}
261            let mut current_pos: SmallVec<[usize; 8]> = SmallVec::with_capacity(n);
262            for i in 0..n {
263                let (e_i, p_i) = placements[i];
264                let shifted = placements[i + 1..]
265                    .iter()
266                    .filter(|&&(ej, pj)| ej == e_i && pj <= p_i)
267                    .count();
268                // Note: this is an approximation when multiple later insertions interact.
269                // The exact value requires iterative computation, but for the common case
270                // (small ruin counts, distinct positions) this is exact.
271                current_pos.push(p_i + shifted);
272            }
273
274            // Remove in reverse insertion order (i = n-1 downto 0).
275            // When removing element i, elements j > i have already been removed.
276            // Each removed j that was at current_pos[j] < current_pos[i] in the same
277            // entity shifted element i left by 1.
278            let mut vals: SmallVec<[V; 8]> = SmallVec::with_capacity(n);
279            for i in (0..n).rev() {
280                let (e_i, _) = placements[i];
281                let left_shifts = placements[i + 1..]
282                    .iter()
283                    .zip(current_pos[i + 1..].iter())
284                    .filter(|&(&(ej, _), &cpj)| ej == e_i && cpj < current_pos[i])
285                    .count();
286                let actual_pos = current_pos[i] - left_shifts;
287                vals.push(list_remove(s, e_i, actual_pos));
288            }
289            // vals is in reverse original order; reverse to get forward original order.
290            vals.reverse();
291
292            // Reinsert at original positions (ascending, sorted).
293            // orig_indices[k] is the position in the pre-ruin source entity.
294            // Inserting at orig_indices[k] shifts all positions > orig_indices[k] right.
295            // Since orig_indices is sorted ascending, each insertion k shifts positions
296            // that are >= orig_indices[k], which includes orig_indices[k+1..] only if
297            // they are >= orig_indices[k]. They are (sorted), so each later index needs
298            // +k adjustment (k prior insertions each shifted it once).
299            // But orig_indices[k] itself does not shift — we insert at the exact original
300            // index before any of the k prior insertions were accounted for.
301            // Actually: after k insertions at positions orig_indices[0..k] (all <= orig_indices[k]
302            // since sorted), orig_indices[k]'s effective position has shifted by k.
303            for (&idx, val) in orig_indices.iter().zip(vals.into_iter()) {
304                list_insert(s, orig_entity, idx, val);
305            }
306        }));
307    }
308
309    fn descriptor_index(&self) -> usize {
310        self.descriptor_index
311    }
312
313    fn entity_indices(&self) -> &[usize] {
314        std::slice::from_ref(&self.entity_index)
315    }
316
317    fn variable_name(&self) -> &str {
318        self.variable_name
319    }
320}