Skip to main content

solverforge_solver/heuristic/selector/
list_change.rs

1//! List change move selector for element relocation.
2//!
3//! Generates `ListChangeMove`s that relocate elements within or between list variables.
4//! Essential for vehicle routing and scheduling problems.
5//!
6//! # Example
7//!
8//! ```
9//! use solverforge_solver::heuristic::selector::list_change::ListChangeMoveSelector;
10//! use solverforge_solver::heuristic::selector::entity::FromSolutionEntitySelector;
11//! use solverforge_solver::heuristic::selector::MoveSelector;
12//! use solverforge_core::domain::PlanningSolution;
13//! use solverforge_core::score::SimpleScore;
14//!
15//! #[derive(Clone, Debug)]
16//! struct Vehicle { visits: Vec<i32> }
17//!
18//! #[derive(Clone, Debug)]
19//! struct Solution { vehicles: Vec<Vehicle>, score: Option<SimpleScore> }
20//!
21//! impl PlanningSolution for Solution {
22//!     type Score = SimpleScore;
23//!     fn score(&self) -> Option<Self::Score> { self.score }
24//!     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
25//! }
26//!
27//! fn list_len(s: &Solution, entity_idx: usize) -> usize {
28//!     s.vehicles.get(entity_idx).map_or(0, |v| v.visits.len())
29//! }
30//! fn list_remove(s: &mut Solution, entity_idx: usize, pos: usize) -> Option<i32> {
31//!     s.vehicles.get_mut(entity_idx).map(|v| v.visits.remove(pos))
32//! }
33//! fn list_insert(s: &mut Solution, entity_idx: usize, pos: usize, val: i32) {
34//!     if let Some(v) = s.vehicles.get_mut(entity_idx) { v.visits.insert(pos, val); }
35//! }
36//!
37//! let selector = ListChangeMoveSelector::<Solution, i32, _>::new(
38//!     FromSolutionEntitySelector::new(0),
39//!     list_len,
40//!     list_remove,
41//!     list_insert,
42//!     "visits",
43//!     0,
44//! );
45//! ```
46
47use std::fmt::Debug;
48use std::marker::PhantomData;
49
50use solverforge_core::domain::PlanningSolution;
51use solverforge_scoring::ScoreDirector;
52
53use crate::heuristic::r#move::ListChangeMove;
54
55use super::entity::EntitySelector;
56use super::typed_move_selector::MoveSelector;
57
58/// A move selector that generates list change moves.
59///
60/// Enumerates all valid (source_entity, source_pos, dest_entity, dest_pos)
61/// combinations for relocating elements within or between list variables.
62///
63/// # Type Parameters
64/// * `S` - The solution type
65/// * `V` - The list element type
66///
67/// # Complexity
68///
69/// For n entities with average route length m:
70/// - Intra-entity moves: O(n * m * m)
71/// - Inter-entity moves: O(n * n * m * m)
72/// - Total: O(n² * m²) worst case
73///
74/// Use with a forager that quits early for better performance.
75pub struct ListChangeMoveSelector<S, V, ES> {
76    /// Selects entities (vehicles) for moves.
77    entity_selector: ES,
78    /// Get list length for an entity.
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: ScoreDirector<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                    if src_pos == dst_pos || dst_pos == src_pos + 1 {
174                        continue;
175                    }
176
177                    moves.push(ListChangeMove::new(
178                        src_entity,
179                        src_pos,
180                        src_entity,
181                        dst_pos,
182                        list_len,
183                        list_remove,
184                        list_insert,
185                        variable_name,
186                        descriptor_index,
187                    ));
188                }
189
190                // Inter-entity moves
191                for (dst_idx, &dst_entity) in entities.iter().enumerate() {
192                    if dst_idx == src_idx {
193                        continue;
194                    }
195
196                    let dst_len = route_lens[dst_idx];
197                    // Can insert at any position from 0 to dst_len inclusive
198                    for dst_pos in 0..=dst_len {
199                        moves.push(ListChangeMove::new(
200                            src_entity,
201                            src_pos,
202                            dst_entity,
203                            dst_pos,
204                            list_len,
205                            list_remove,
206                            list_insert,
207                            variable_name,
208                            descriptor_index,
209                        ));
210                    }
211                }
212            }
213        }
214
215        moves.into_iter()
216    }
217
218    fn size<D: ScoreDirector<S>>(&self, score_director: &D) -> usize {
219        let solution = score_director.working_solution();
220        let list_len = self.list_len;
221
222        let entities: Vec<usize> = self
223            .entity_selector
224            .iter(score_director)
225            .map(|r| r.entity_index)
226            .collect();
227
228        let route_lens: Vec<usize> = entities.iter().map(|&e| list_len(solution, e)).collect();
229        let total_elements: usize = route_lens.iter().sum();
230
231        // Approximate: each element can move to any position in any entity
232        // Intra: ~m positions per entity
233        // Inter: ~(n-1) * m positions
234        let n = entities.len();
235        if n == 0 || total_elements == 0 {
236            return 0;
237        }
238
239        let avg_len = total_elements / n;
240        // Intra moves: n * m * m
241        // Inter moves: n * (n-1) * m * m
242        n * avg_len * (avg_len + (n - 1) * avg_len)
243    }
244}