Skip to main content

solverforge_solver/heuristic/selector/
list_change.rs

1/* List change move selector for element relocation.
2
3Generates `ListChangeMove`s that relocate elements within or between list variables.
4Essential for vehicle routing and scheduling problems.
5
6# Example
7
8```
9use solverforge_solver::heuristic::selector::list_change::ListChangeMoveSelector;
10use solverforge_solver::heuristic::selector::entity::FromSolutionEntitySelector;
11use solverforge_solver::heuristic::selector::MoveSelector;
12use solverforge_core::domain::PlanningSolution;
13use solverforge_core::score::SoftScore;
14
15#[derive(Clone, Debug)]
16struct Vehicle { visits: Vec<i32> }
17
18#[derive(Clone, Debug)]
19struct Solution { vehicles: Vec<Vehicle>, score: Option<SoftScore> }
20
21impl PlanningSolution for Solution {
22type Score = SoftScore;
23fn score(&self) -> Option<Self::Score> { self.score }
24fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
25}
26
27fn list_len(s: &Solution, entity_idx: usize) -> usize {
28s.vehicles.get(entity_idx).map_or(0, |v| v.visits.len())
29}
30fn list_remove(s: &mut Solution, entity_idx: usize, pos: usize) -> Option<i32> {
31s.vehicles.get_mut(entity_idx).map(|v| v.visits.remove(pos))
32}
33fn list_insert(s: &mut Solution, entity_idx: usize, pos: usize, val: i32) {
34if let Some(v) = s.vehicles.get_mut(entity_idx) { v.visits.insert(pos, val); }
35}
36
37let selector = ListChangeMoveSelector::<Solution, i32, _>::new(
38FromSolutionEntitySelector::new(0),
39list_len,
40list_remove,
41list_insert,
42"visits",
430,
44);
45```
46*/
47
48use std::fmt::Debug;
49use std::marker::PhantomData;
50
51use solverforge_core::domain::PlanningSolution;
52use solverforge_scoring::Director;
53
54use crate::heuristic::r#move::ListChangeMove;
55
56use super::entity::EntitySelector;
57use super::list_support::collect_selected_entities;
58use super::move_selector::{ArenaMoveCursor, MoveSelector};
59
60/// A move selector that generates list change moves.
61///
62/// Enumerates all valid (source_entity, source_pos, dest_entity, dest_pos)
63/// combinations for relocating elements within or between list variables.
64///
65/// # Type Parameters
66/// * `S` - The solution type
67/// * `V` - The list element type
68///
69/// # Complexity
70///
71/// For n entities with average route length m:
72/// - Intra-entity moves: O(n * m * m)
73/// - Inter-entity moves: O(n * n * m * m)
74/// - Total: O(n² * m²) worst case
75///
76/// Use with a forager that quits early for better performance.
77pub struct ListChangeMoveSelector<S, V, ES> {
78    // Selects entities (vehicles) for moves.
79    entity_selector: ES,
80    list_len: fn(&S, usize) -> usize,
81    // Read element by position for exact move/value tabu metadata.
82    list_get: fn(&S, usize, usize) -> Option<V>,
83    // Remove element at position.
84    list_remove: fn(&mut S, usize, usize) -> Option<V>,
85    // Insert element at position.
86    list_insert: fn(&mut S, usize, usize, V),
87    // Variable name for notifications.
88    variable_name: &'static str,
89    // Entity descriptor index.
90    descriptor_index: usize,
91    _phantom: PhantomData<(fn() -> S, fn() -> V)>,
92}
93
94impl<S, V: Debug, ES: Debug> Debug for ListChangeMoveSelector<S, V, ES> {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("ListChangeMoveSelector")
97            .field("entity_selector", &self.entity_selector)
98            .field("variable_name", &self.variable_name)
99            .field("descriptor_index", &self.descriptor_index)
100            .finish()
101    }
102}
103
104impl<S, V, ES> ListChangeMoveSelector<S, V, ES> {
105    /// Creates a new list change move selector.
106    ///
107    /// # Arguments
108    /// * `entity_selector` - Selects entities to consider for moves
109    /// * `list_len` - Function to get list length for an entity
110    /// * `list_remove` - Function to remove element at position
111    /// * `list_insert` - Function to insert element at position
112    /// * `variable_name` - Name of the list variable
113    /// * `descriptor_index` - Entity descriptor index
114    pub fn new(
115        entity_selector: ES,
116        list_len: fn(&S, usize) -> usize,
117        list_get: fn(&S, usize, usize) -> Option<V>,
118        list_remove: fn(&mut S, usize, usize) -> Option<V>,
119        list_insert: fn(&mut S, usize, usize, V),
120        variable_name: &'static str,
121        descriptor_index: usize,
122    ) -> Self {
123        Self {
124            entity_selector,
125            list_len,
126            list_get,
127            list_remove,
128            list_insert,
129            variable_name,
130            descriptor_index,
131            _phantom: PhantomData,
132        }
133    }
134}
135
136impl<S, V, ES> MoveSelector<S, ListChangeMove<S, V>> for ListChangeMoveSelector<S, V, ES>
137where
138    S: PlanningSolution,
139    V: Clone + PartialEq + Send + Sync + Debug + 'static,
140    ES: EntitySelector<S>,
141{
142    type Cursor<'a>
143        = ArenaMoveCursor<S, ListChangeMove<S, V>>
144    where
145        Self: 'a;
146
147    fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
148        let list_len = self.list_len;
149        let list_get = self.list_get;
150        let list_remove = self.list_remove;
151        let list_insert = self.list_insert;
152        let variable_name = self.variable_name;
153        let descriptor_index = self.descriptor_index;
154
155        let selected = collect_selected_entities(&self.entity_selector, score_director, list_len);
156        let move_capacity = selected.list_change_move_capacity();
157        let entities = selected.entities;
158        let route_lens = selected.route_lens;
159
160        let mut moves = Vec::with_capacity(move_capacity);
161
162        for (src_idx, &src_entity) in entities.iter().enumerate() {
163            let src_len = route_lens[src_idx];
164            if src_len == 0 {
165                continue;
166            }
167
168            for src_pos in 0..src_len {
169                // Intra-entity moves
170                for dst_pos in 0..src_len {
171                    /* Skip no-op moves:
172                    - Same position is obviously a no-op
173                    - Forward by 1 is a no-op due to index adjustment during do_move
174                    */
175                    if src_pos == dst_pos || dst_pos == src_pos + 1 {
176                        continue;
177                    }
178
179                    moves.push(ListChangeMove::new(
180                        src_entity,
181                        src_pos,
182                        src_entity,
183                        dst_pos,
184                        list_len,
185                        list_get,
186                        list_remove,
187                        list_insert,
188                        variable_name,
189                        descriptor_index,
190                    ));
191                }
192
193                // Inter-entity moves
194                for (dst_idx, &dst_entity) in entities.iter().enumerate() {
195                    if dst_idx == src_idx {
196                        continue;
197                    }
198
199                    let dst_len = route_lens[dst_idx];
200                    // Can insert at any position from 0 to dst_len inclusive
201                    for dst_pos in 0..=dst_len {
202                        moves.push(ListChangeMove::new(
203                            src_entity,
204                            src_pos,
205                            dst_entity,
206                            dst_pos,
207                            list_len,
208                            list_get,
209                            list_remove,
210                            list_insert,
211                            variable_name,
212                            descriptor_index,
213                        ));
214                    }
215                }
216            }
217        }
218
219        ArenaMoveCursor::from_moves(moves)
220    }
221
222    fn size<D: Director<S>>(&self, score_director: &D) -> usize {
223        collect_selected_entities(&self.entity_selector, score_director, self.list_len)
224            .list_change_move_capacity()
225    }
226}