Skip to main content

solverforge_solver/heuristic/move/
pillar_change.rs

1/* PillarChangeMove - assigns a value to all entities in a pillar.
2
3A pillar is a group of entities that share the same variable value.
4This move changes all of them to a new value atomically.
5
6# Zero-Erasure Design
7
8PillarChangeMove uses concrete function pointers instead of `dyn Any` for complete
9compile-time type safety. No runtime type checks or downcasting.
10*/
11
12use std::fmt::Debug;
13
14use smallvec::{smallvec, SmallVec};
15use solverforge_core::domain::PlanningSolution;
16use solverforge_scoring::Director;
17
18use super::metadata::{
19    encode_option_debug, encode_usize, hash_str, MoveTabuScope, ScopedEntityTabuToken,
20};
21use super::{Move, MoveTabuSignature};
22
23/// A move that assigns a value to all entities in a pillar.
24///
25/// Stores entity indices and concrete function pointers for zero-erasure access.
26/// `do_move` returns the previous pillar values as typed undo data.
27///
28/// # Type Parameters
29/// * `S` - The planning solution type
30/// * `V` - The variable value type
31pub struct PillarChangeMove<S, V> {
32    entity_indices: Vec<usize>,
33    descriptor_index: usize,
34    variable_name: &'static str,
35    to_value: Option<V>,
36    // Concrete getter function pointer - zero erasure.
37    getter: fn(&S, usize, usize) -> Option<V>,
38    // Concrete setter function pointer - zero erasure.
39    setter: fn(&mut S, usize, usize, Option<V>),
40    variable_index: usize,
41}
42
43impl<S, V: Debug> Debug for PillarChangeMove<S, V> {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("PillarChangeMove")
46            .field("entity_indices", &self.entity_indices)
47            .field("descriptor_index", &self.descriptor_index)
48            .field("variable_index", &self.variable_index)
49            .field("variable_name", &self.variable_name)
50            .field("to_value", &self.to_value)
51            .finish()
52    }
53}
54
55impl<S, V> PillarChangeMove<S, V> {
56    /// Creates a new pillar change move with concrete function pointers.
57    ///
58    /// # Arguments
59    /// * `entity_indices` - Indices of entities in the pillar
60    /// * `to_value` - The new value to assign to all entities
61    /// * `getter` - Concrete getter function pointer
62    /// * `setter` - Concrete setter function pointer
63    /// * `variable_name` - Name of the variable being changed
64    /// * `descriptor_index` - Index in the entity descriptor
65    pub fn new(
66        entity_indices: Vec<usize>,
67        to_value: Option<V>,
68        getter: fn(&S, usize, usize) -> Option<V>,
69        setter: fn(&mut S, usize, usize, Option<V>),
70        variable_index: usize,
71        variable_name: &'static str,
72        descriptor_index: usize,
73    ) -> Self {
74        Self {
75            entity_indices,
76            descriptor_index,
77            variable_name,
78            to_value,
79            getter,
80            setter,
81            variable_index,
82        }
83    }
84
85    pub fn pillar_size(&self) -> usize {
86        self.entity_indices.len()
87    }
88
89    pub fn to_value(&self) -> Option<&V> {
90        self.to_value.as_ref()
91    }
92}
93
94impl<S, V> Move<S> for PillarChangeMove<S, V>
95where
96    S: PlanningSolution,
97    V: Clone + PartialEq + Send + Sync + Debug + 'static,
98{
99    type Undo = SmallVec<[(usize, Option<V>); 4]>;
100
101    fn is_doable<D: Director<S>>(&self, score_director: &D) -> bool {
102        if self.entity_indices.is_empty() {
103            return false;
104        }
105
106        // Check first entity exists
107        let count = score_director.entity_count(self.descriptor_index);
108        if let Some(&first_idx) = self.entity_indices.first() {
109            if count.is_none_or(|c| first_idx >= c) {
110                return false;
111            }
112
113            // Get current value using concrete getter - zero erasure
114            let current = (self.getter)(
115                score_director.working_solution(),
116                first_idx,
117                self.variable_index,
118            );
119
120            match (&current, &self.to_value) {
121                (None, None) => false,
122                (Some(cur), Some(target)) => cur != target,
123                _ => true,
124            }
125        } else {
126            false
127        }
128    }
129
130    fn do_move<D: Director<S>>(&self, score_director: &mut D) -> Self::Undo {
131        // Capture old values using concrete getter - zero erasure
132        let old_values: SmallVec<[(usize, Option<V>); 4]> = self
133            .entity_indices
134            .iter()
135            .map(|&idx| {
136                (
137                    idx,
138                    (self.getter)(score_director.working_solution(), idx, self.variable_index),
139                )
140            })
141            .collect();
142
143        // Notify before changes for all entities
144        for &idx in &self.entity_indices {
145            score_director.before_variable_changed(self.descriptor_index, idx);
146        }
147
148        // Apply new value to all entities using concrete setter - zero erasure
149        for &idx in &self.entity_indices {
150            (self.setter)(
151                score_director.working_solution_mut(),
152                idx,
153                self.variable_index,
154                self.to_value.clone(),
155            );
156        }
157
158        // Notify after changes
159        for &idx in &self.entity_indices {
160            score_director.after_variable_changed(self.descriptor_index, idx);
161        }
162
163        old_values
164    }
165
166    fn undo_move<D: Director<S>>(&self, score_director: &mut D, undo: Self::Undo) {
167        for (idx, _) in &undo {
168            score_director.before_variable_changed(self.descriptor_index, *idx);
169        }
170        for (idx, old_value) in undo {
171            (self.setter)(
172                score_director.working_solution_mut(),
173                idx,
174                self.variable_index,
175                old_value,
176            );
177        }
178        for &idx in &self.entity_indices {
179            score_director.after_variable_changed(self.descriptor_index, idx);
180        }
181    }
182
183    fn descriptor_index(&self) -> usize {
184        self.descriptor_index
185    }
186
187    fn entity_indices(&self) -> &[usize] {
188        &self.entity_indices
189    }
190
191    fn variable_name(&self) -> &str {
192        self.variable_name
193    }
194
195    fn tabu_signature<D: Director<S>>(&self, score_director: &D) -> MoveTabuSignature {
196        let from_value = self.entity_indices.first().and_then(|&idx| {
197            (self.getter)(score_director.working_solution(), idx, self.variable_index)
198        });
199        let from_id = encode_option_debug(from_value.as_ref());
200        let to_id = encode_option_debug(self.to_value.as_ref());
201        let variable_id = hash_str(self.variable_name);
202        let scope = MoveTabuScope::new(self.descriptor_index, self.variable_name);
203        let entity_ids: SmallVec<[u64; 2]> = self
204            .entity_indices
205            .iter()
206            .map(|&idx| encode_usize(idx))
207            .collect();
208        let entity_tokens: SmallVec<[ScopedEntityTabuToken; 2]> = entity_ids
209            .iter()
210            .copied()
211            .map(|entity_id| scope.entity_token(entity_id))
212            .collect();
213        let mut move_id = smallvec![
214            encode_usize(self.descriptor_index),
215            variable_id,
216            encode_usize(self.entity_indices.len()),
217            from_id,
218            to_id
219        ];
220        move_id.extend(entity_ids.iter().copied());
221
222        let mut undo_move_id = smallvec![
223            encode_usize(self.descriptor_index),
224            variable_id,
225            encode_usize(self.entity_indices.len()),
226            to_id,
227            from_id
228        ];
229        undo_move_id.extend(entity_ids.iter().copied());
230
231        MoveTabuSignature::new(scope, move_id, undo_move_id)
232            .with_entity_tokens(entity_tokens)
233            .with_destination_value_tokens([scope.value_token(to_id)])
234    }
235}