Skip to main content

solverforge_solver/heuristic/move/
sublist_swap.rs

1/* SublistSwapMove - swaps two contiguous sublists within or between list variables.
2
3This move exchanges two ranges of elements. Essential for vehicle routing
4where segments need to be swapped between vehicles.
5
6# Zero-Erasure Design
7
8Uses concrete function pointers for list operations. No `dyn Any`, no downcasting.
9*/
10
11use std::borrow::Cow;
12use std::fmt::Debug;
13use std::marker::PhantomData;
14
15use solverforge_core::domain::PlanningSolution;
16use solverforge_scoring::Director;
17
18use super::list_kernel::{
19    sublist_swap_candidate_trace_identity, sublist_swap_do_move, sublist_swap_is_doable,
20    sublist_swap_tabu_signature, sublist_swap_undo_move, StaticListWindowAccess,
21};
22use super::segment_layout::SegmentSwapCoords;
23use super::{Move, MoveTabuSignature};
24
25/// A move that swaps two contiguous sublists.
26///
27/// Supports both intra-list swaps (within same entity) and inter-list swaps
28/// (between different entities). Uses concrete function pointers for zero-erasure.
29///
30/// # Type Parameters
31/// * `S` - The planning solution type
32/// * `V` - The list element value type
33///
34/// # Example
35///
36/// ```
37/// use solverforge_solver::heuristic::r#move::SublistSwapMove;
38/// use solverforge_core::domain::PlanningSolution;
39/// use solverforge_core::score::SoftScore;
40///
41/// #[derive(Clone, Debug)]
42/// struct Vehicle { id: usize, visits: Vec<i32> }
43///
44/// #[derive(Clone, Debug)]
45/// struct Solution { vehicles: Vec<Vehicle>, score: Option<SoftScore> }
46///
47/// impl PlanningSolution for Solution {
48///     type Score = SoftScore;
49///     fn score(&self) -> Option<Self::Score> { self.score }
50///     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
51/// }
52///
53/// fn list_len(s: &Solution, entity_idx: usize) -> usize {
54///     s.vehicles.get(entity_idx).map_or(0, |v| v.visits.len())
55/// }
56/// fn list_get(s: &Solution, entity_idx: usize, pos: usize) -> Option<i32> {
57///     s.vehicles
58///         .get(entity_idx)
59///         .and_then(|v| v.visits.get(pos))
60///         .copied()
61/// }
62/// fn sublist_remove(s: &mut Solution, entity_idx: usize, start: usize, end: usize) -> Vec<i32> {
63///     s.vehicles.get_mut(entity_idx)
64///         .map(|v| v.visits.drain(start..end).collect())
65///         .unwrap_or_default()
66/// }
67/// fn sublist_insert(s: &mut Solution, entity_idx: usize, pos: usize, items: Vec<i32>) {
68///     if let Some(v) = s.vehicles.get_mut(entity_idx) {
69///         for (i, item) in items.into_iter().enumerate() {
70///             v.visits.insert(pos + i, item);
71///         }
72///     }
73/// }
74///
75/// // Swap [1..3) from vehicle 0 with [0..2) from vehicle 1
76/// let m = SublistSwapMove::<Solution, i32>::new(
77///     0, 1, 3,  // first: entity 0, range [1, 3)
78///     1, 0, 2,  // second: entity 1, range [0, 2)
79///     list_len, list_get, sublist_remove, sublist_insert,
80///     "visits", 0,
81/// );
82/// ```
83pub struct SublistSwapMove<S, V> {
84    // First entity index
85    first_entity_index: usize,
86    // Start of first range (inclusive)
87    first_start: usize,
88    // End of first range (exclusive)
89    first_end: usize,
90    // Second entity index
91    second_entity_index: usize,
92    // Start of second range (inclusive)
93    second_start: usize,
94    // End of second range (exclusive)
95    second_end: usize,
96    list_len: fn(&S, usize) -> usize,
97    list_get: fn(&S, usize, usize) -> Option<V>,
98    // Remove sublist [start, end), returns removed elements
99    sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
100    // Insert elements at position
101    sublist_insert: fn(&mut S, usize, usize, Vec<V>),
102    variable_name: &'static str,
103    descriptor_index: usize,
104    // Store indices for entity_indices()
105    indices: [usize; 2],
106    _phantom: PhantomData<fn() -> V>,
107}
108
109impl<S, V> Clone for SublistSwapMove<S, V> {
110    fn clone(&self) -> Self {
111        *self
112    }
113}
114
115impl<S, V> Copy for SublistSwapMove<S, V> {}
116
117impl<S, V: Debug> Debug for SublistSwapMove<S, V> {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        f.debug_struct("SublistSwapMove")
120            .field("first_entity", &self.first_entity_index)
121            .field("first_range", &(self.first_start..self.first_end))
122            .field("second_entity", &self.second_entity_index)
123            .field("second_range", &(self.second_start..self.second_end))
124            .field("variable_name", &self.variable_name)
125            .finish()
126    }
127}
128
129impl<S, V> SublistSwapMove<S, V> {
130    /* Creates a new sublist swap move with concrete function pointers.
131
132    # Arguments
133    * `first_entity_index` - First entity index
134    * `first_start` - Start of first range (inclusive)
135    * `first_end` - End of first range (exclusive)
136    * `second_entity_index` - Second entity index
137    * `second_start` - Start of second range (inclusive)
138    * `second_end` - End of second range (exclusive)
139    * `list_len` - Function to get list length
140    * `sublist_remove` - Function to remove range [start, end)
141    * `sublist_insert` - Function to insert elements at position
142    * `variable_name` - Name of the list variable
143    * `descriptor_index` - Entity descriptor index
144    */
145    #[allow(clippy::too_many_arguments)]
146    pub fn new(
147        first_entity_index: usize,
148        first_start: usize,
149        first_end: usize,
150        second_entity_index: usize,
151        second_start: usize,
152        second_end: usize,
153        list_len: fn(&S, usize) -> usize,
154        list_get: fn(&S, usize, usize) -> Option<V>,
155        sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
156        sublist_insert: fn(&mut S, usize, usize, Vec<V>),
157        variable_name: &'static str,
158        descriptor_index: usize,
159    ) -> Self {
160        Self {
161            first_entity_index,
162            first_start,
163            first_end,
164            second_entity_index,
165            second_start,
166            second_end,
167            list_len,
168            list_get,
169            sublist_remove,
170            sublist_insert,
171            variable_name,
172            descriptor_index,
173            indices: [first_entity_index, second_entity_index],
174            _phantom: PhantomData,
175        }
176    }
177
178    pub fn first_entity_index(&self) -> usize {
179        self.first_entity_index
180    }
181
182    pub fn first_start(&self) -> usize {
183        self.first_start
184    }
185
186    pub fn first_end(&self) -> usize {
187        self.first_end
188    }
189
190    pub fn first_len(&self) -> usize {
191        self.first_end.saturating_sub(self.first_start)
192    }
193
194    pub fn second_entity_index(&self) -> usize {
195        self.second_entity_index
196    }
197
198    pub fn second_start(&self) -> usize {
199        self.second_start
200    }
201
202    pub fn second_end(&self) -> usize {
203        self.second_end
204    }
205
206    pub fn second_len(&self) -> usize {
207        self.second_end.saturating_sub(self.second_start)
208    }
209
210    pub fn is_intra_list(&self) -> bool {
211        self.first_entity_index == self.second_entity_index
212    }
213
214    fn access(&self) -> StaticListWindowAccess<S, V> {
215        StaticListWindowAccess {
216            list_len: self.list_len,
217            list_get: self.list_get,
218            sublist_remove: self.sublist_remove,
219            sublist_insert: self.sublist_insert,
220            variable_name: self.variable_name,
221            descriptor_index: self.descriptor_index,
222        }
223    }
224
225    fn coordinates(&self) -> SegmentSwapCoords {
226        SegmentSwapCoords::new(
227            self.first_entity_index,
228            self.first_start,
229            self.first_end,
230            self.second_entity_index,
231            self.second_start,
232            self.second_end,
233        )
234    }
235}
236
237impl<S, V> Move<S> for SublistSwapMove<S, V>
238where
239    S: PlanningSolution,
240    V: Clone + Send + Sync + Debug + 'static,
241{
242    type Undo = ();
243
244    fn is_doable<D: Director<S>>(&self, score_director: &D) -> bool {
245        sublist_swap_is_doable(&self.access(), self.coordinates(), score_director)
246    }
247
248    fn do_move<D: Director<S>>(&self, score_director: &mut D) -> Self::Undo {
249        sublist_swap_do_move(&self.access(), self.coordinates(), score_director);
250    }
251
252    fn undo_move<D: Director<S>>(&self, score_director: &mut D, (): Self::Undo) {
253        sublist_swap_undo_move(&self.access(), self.coordinates(), score_director);
254    }
255
256    fn descriptor_index(&self) -> usize {
257        self.descriptor_index
258    }
259
260    fn entity_indices(&self) -> &[usize] {
261        if self.is_intra_list() {
262            &self.indices[0..1]
263        } else {
264            &self.indices
265        }
266    }
267
268    fn variable_name(&self) -> &str {
269        self.variable_name
270    }
271
272    fn telemetry_label(&self) -> &'static str {
273        "sublist_swap"
274    }
275
276    fn tabu_signature<D: Director<S>>(&self, score_director: &D) -> Cow<'_, MoveTabuSignature> {
277        Cow::Owned(sublist_swap_tabu_signature(
278            &self.access(),
279            self.coordinates(),
280            score_director,
281        ))
282    }
283
284    fn candidate_trace_identity(&self) -> Option<crate::stats::CandidateTraceIdentity> {
285        Some(sublist_swap_candidate_trace_identity(
286            &self.access(),
287            self.coordinates(),
288        ))
289    }
290}