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::typed_move_selector::MoveSelector;
58
59/// A move selector that generates list change moves.
60///
61/// Enumerates all valid (source_entity, source_pos, dest_entity, dest_pos)
62/// combinations for relocating elements within or between list variables.
63///
64/// # Type Parameters
65/// * `S` - The solution type
66/// * `V` - The list element type
67///
68/// # Complexity
69///
70/// For n entities with average route length m:
71/// - Intra-entity moves: O(n * m * m)
72/// - Inter-entity moves: O(n * n * m * m)
73/// - Total: O(n² * m²) worst case
74///
75/// Use with a forager that quits early for better performance.
76pub struct ListChangeMoveSelector<S, V, ES> {
77 // Selects entities (vehicles) for moves.
78 entity_selector: ES,
79 list_len: fn(&S, usize) -> usize,
80 // Remove element at position.
81 list_remove: fn(&mut S, usize, usize) -> Option<V>,
82 // Insert element at position.
83 list_insert: fn(&mut S, usize, usize, V),
84 // Variable name for notifications.
85 variable_name: &'static str,
86 // Entity descriptor index.
87 descriptor_index: usize,
88 _phantom: PhantomData<(fn() -> S, fn() -> V)>,
89}
90
91impl<S, V: Debug, ES: Debug> Debug for ListChangeMoveSelector<S, V, ES> {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 f.debug_struct("ListChangeMoveSelector")
94 .field("entity_selector", &self.entity_selector)
95 .field("variable_name", &self.variable_name)
96 .field("descriptor_index", &self.descriptor_index)
97 .finish()
98 }
99}
100
101impl<S, V, ES> ListChangeMoveSelector<S, V, ES> {
102 /// Creates a new list change move selector.
103 ///
104 /// # Arguments
105 /// * `entity_selector` - Selects entities to consider for moves
106 /// * `list_len` - Function to get list length for an entity
107 /// * `list_remove` - Function to remove element at position
108 /// * `list_insert` - Function to insert element at position
109 /// * `variable_name` - Name of the list variable
110 /// * `descriptor_index` - Entity descriptor index
111 pub fn new(
112 entity_selector: ES,
113 list_len: fn(&S, usize) -> usize,
114 list_remove: fn(&mut S, usize, usize) -> Option<V>,
115 list_insert: fn(&mut S, usize, usize, V),
116 variable_name: &'static str,
117 descriptor_index: usize,
118 ) -> Self {
119 Self {
120 entity_selector,
121 list_len,
122 list_remove,
123 list_insert,
124 variable_name,
125 descriptor_index,
126 _phantom: PhantomData,
127 }
128 }
129}
130
131impl<S, V, ES> MoveSelector<S, ListChangeMove<S, V>> for ListChangeMoveSelector<S, V, ES>
132where
133 S: PlanningSolution,
134 V: Clone + PartialEq + Send + Sync + Debug + 'static,
135 ES: EntitySelector<S>,
136{
137 fn iter_moves<'a, D: Director<S>>(
138 &'a self,
139 score_director: &'a D,
140 ) -> impl Iterator<Item = ListChangeMove<S, V>> + 'a {
141 let solution = score_director.working_solution();
142 let list_len = self.list_len;
143 let list_remove = self.list_remove;
144 let list_insert = self.list_insert;
145 let variable_name = self.variable_name;
146 let descriptor_index = self.descriptor_index;
147
148 // Collect entities to allow multiple passes
149 let entities: Vec<usize> = self
150 .entity_selector
151 .iter(score_director)
152 .map(|r| r.entity_index)
153 .collect();
154
155 // Pre-compute route lengths
156 let route_lens: Vec<usize> = entities.iter().map(|&e| list_len(solution, e)).collect();
157
158 // Generate all valid moves
159 let mut moves = Vec::new();
160
161 for (src_idx, &src_entity) in entities.iter().enumerate() {
162 let src_len = route_lens[src_idx];
163 if src_len == 0 {
164 continue;
165 }
166
167 for src_pos in 0..src_len {
168 // Intra-entity moves
169 for dst_pos in 0..src_len {
170 /* Skip no-op moves:
171 - Same position is obviously a no-op
172 - Forward by 1 is a no-op due to index adjustment during do_move
173 */
174 if src_pos == dst_pos || dst_pos == src_pos + 1 {
175 continue;
176 }
177
178 moves.push(ListChangeMove::new(
179 src_entity,
180 src_pos,
181 src_entity,
182 dst_pos,
183 list_len,
184 list_remove,
185 list_insert,
186 variable_name,
187 descriptor_index,
188 ));
189 }
190
191 // Inter-entity moves
192 for (dst_idx, &dst_entity) in entities.iter().enumerate() {
193 if dst_idx == src_idx {
194 continue;
195 }
196
197 let dst_len = route_lens[dst_idx];
198 // Can insert at any position from 0 to dst_len inclusive
199 for dst_pos in 0..=dst_len {
200 moves.push(ListChangeMove::new(
201 src_entity,
202 src_pos,
203 dst_entity,
204 dst_pos,
205 list_len,
206 list_remove,
207 list_insert,
208 variable_name,
209 descriptor_index,
210 ));
211 }
212 }
213 }
214 }
215
216 moves.into_iter()
217 }
218
219 fn size<D: Director<S>>(&self, score_director: &D) -> usize {
220 let solution = score_director.working_solution();
221 let list_len = self.list_len;
222
223 let entities: Vec<usize> = self
224 .entity_selector
225 .iter(score_director)
226 .map(|r| r.entity_index)
227 .collect();
228
229 let route_lens: Vec<usize> = entities.iter().map(|&e| list_len(solution, e)).collect();
230 let total_elements: usize = route_lens.iter().sum();
231
232 /* Approximate: each element can move to any position in any entity
233 Intra: ~m positions per entity
234 Inter: ~(n-1) * m positions
235 */
236 let n = entities.len();
237 if n == 0 || total_elements == 0 {
238 return 0;
239 }
240
241 let avg_len = total_elements / n;
242 // Intra moves: n * m * m
243 // Inter moves: n * (n-1) * m * m
244 n * avg_len * (avg_len + (n - 1) * avg_len)
245 }
246}