Skip to main content

solverforge_solver/phase/construction/
placer.rs

1/* Entity placers for construction heuristic
2
3Placers enumerate the entities that need values assigned and
4generate candidate moves for each entity.
5*/
6
7use std::fmt::Debug;
8use std::marker::PhantomData;
9
10use solverforge_core::domain::PlanningSolution;
11use solverforge_scoring::Director;
12
13use crate::heuristic::r#move::{ChangeMove, Move};
14use crate::heuristic::selector::{EntityReference, EntitySelector, ValueSelector};
15
16use super::ConstructionSlotId;
17
18/// A placement represents an entity that needs a value assigned,
19/// along with the candidate moves to assign values.
20///
21/// # Type Parameters
22/// * `S` - The planning solution type
23/// * `M` - The move type
24pub struct Placement<S, M>
25where
26    S: PlanningSolution,
27    M: Move<S>,
28{
29    // The entity reference.
30    pub entity_ref: EntityReference,
31    // Candidate moves for this placement.
32    pub moves: Vec<M>,
33    // Whether keeping the current value is a legal construction choice.
34    keep_current_legal: bool,
35    slot_id: Option<ConstructionSlotId>,
36    _phantom: PhantomData<fn() -> S>,
37}
38
39impl<S, M> Placement<S, M>
40where
41    S: PlanningSolution,
42    M: Move<S>,
43{
44    pub fn new(entity_ref: EntityReference, moves: Vec<M>) -> Self {
45        Self {
46            entity_ref,
47            moves,
48            keep_current_legal: false,
49            slot_id: None,
50            _phantom: PhantomData,
51        }
52    }
53
54    pub fn is_empty(&self) -> bool {
55        self.moves.is_empty()
56    }
57
58    pub fn with_keep_current_legal(mut self, legal: bool) -> Self {
59        self.keep_current_legal = legal;
60        self
61    }
62
63    pub fn keep_current_legal(&self) -> bool {
64        self.keep_current_legal
65    }
66
67    pub(crate) fn with_slot_id(mut self, slot_id: ConstructionSlotId) -> Self {
68        self.slot_id = Some(slot_id);
69        self
70    }
71
72    pub(crate) fn slot_id(&self) -> Option<ConstructionSlotId> {
73        self.slot_id
74    }
75
76    /// Takes ownership of a move at the given index.
77    ///
78    /// Uses swap_remove for O(1) removal.
79    pub fn take_move(&mut self, index: usize) -> M {
80        self.moves.swap_remove(index)
81    }
82}
83
84impl<S, M> Debug for Placement<S, M>
85where
86    S: PlanningSolution,
87    M: Move<S>,
88{
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Placement")
91            .field("entity_ref", &self.entity_ref)
92            .field("move_count", &self.moves.len())
93            .field("keep_current_legal", &self.keep_current_legal)
94            .field("slot_id", &self.slot_id)
95            .finish()
96    }
97}
98
99/// Trait for placing entities during construction.
100///
101/// Entity placers iterate over uninitialized entities and generate
102/// candidate moves for each.
103///
104/// # Type Parameters
105/// * `S` - The planning solution type
106/// * `M` - The move type
107pub trait EntityPlacer<S, M>: Send + Debug
108where
109    S: PlanningSolution,
110    M: Move<S>,
111{
112    // Returns all placements (entities + their candidate moves).
113    fn get_placements<D: Director<S>>(&self, score_director: &D) -> Vec<Placement<S, M>>;
114}
115
116/// A queued entity placer that processes entities in order.
117///
118/// For each uninitialized entity, generates change moves for all possible values.
119/// Uses typed function pointers for zero-erasure access.
120///
121/// # Type Parameters
122/// * `S` - The planning solution type
123/// * `V` - The value type
124/// * `ES` - The entity selector type
125/// * `VS` - The value selector type
126pub struct QueuedEntityPlacer<S, V, ES, VS>
127where
128    S: PlanningSolution,
129    ES: EntitySelector<S>,
130    VS: ValueSelector<S, V>,
131{
132    // The entity selector.
133    entity_selector: ES,
134    // The value selector.
135    value_selector: VS,
136    // Typed getter function pointer.
137    getter: fn(&S, usize) -> Option<V>,
138    // Typed setter function pointer.
139    setter: fn(&mut S, usize, Option<V>),
140    // The variable name.
141    variable_name: &'static str,
142    // The descriptor index.
143    descriptor_index: usize,
144    // Whether the variable can remain unassigned during construction.
145    allows_unassigned: bool,
146    _phantom: PhantomData<fn() -> V>,
147}
148
149impl<S, V, ES, VS> QueuedEntityPlacer<S, V, ES, VS>
150where
151    S: PlanningSolution,
152    ES: EntitySelector<S>,
153    VS: ValueSelector<S, V>,
154{
155    pub fn new(
156        entity_selector: ES,
157        value_selector: VS,
158        getter: fn(&S, usize) -> Option<V>,
159        setter: fn(&mut S, usize, Option<V>),
160        descriptor_index: usize,
161        variable_name: &'static str,
162    ) -> Self {
163        Self {
164            entity_selector,
165            value_selector,
166            getter,
167            setter,
168            variable_name,
169            descriptor_index,
170            allows_unassigned: false,
171            _phantom: PhantomData,
172        }
173    }
174
175    pub fn with_allows_unassigned(mut self, allows_unassigned: bool) -> Self {
176        self.allows_unassigned = allows_unassigned;
177        self
178    }
179}
180
181impl<S, V, ES, VS> Debug for QueuedEntityPlacer<S, V, ES, VS>
182where
183    S: PlanningSolution,
184    ES: EntitySelector<S> + Debug,
185    VS: ValueSelector<S, V> + Debug,
186{
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        f.debug_struct("QueuedEntityPlacer")
189            .field("entity_selector", &self.entity_selector)
190            .field("value_selector", &self.value_selector)
191            .field("variable_name", &self.variable_name)
192            .field("allows_unassigned", &self.allows_unassigned)
193            .finish()
194    }
195}
196
197impl<S, V, ES, VS> EntityPlacer<S, ChangeMove<S, V>> for QueuedEntityPlacer<S, V, ES, VS>
198where
199    S: PlanningSolution,
200    V: Clone + PartialEq + Send + Sync + Debug + 'static,
201    ES: EntitySelector<S>,
202    VS: ValueSelector<S, V>,
203{
204    fn get_placements<D: Director<S>>(
205        &self,
206        score_director: &D,
207    ) -> Vec<Placement<S, ChangeMove<S, V>>> {
208        let variable_name = self.variable_name;
209        let descriptor_index = self.descriptor_index;
210        let getter = self.getter;
211        let setter = self.setter;
212        let allows_unassigned = self.allows_unassigned;
213
214        self.entity_selector
215            .iter(score_director)
216            .filter_map(|entity_ref| {
217                // Check if entity is uninitialized using typed getter - zero erasure
218                let current_value =
219                    getter(score_director.working_solution(), entity_ref.entity_index);
220
221                // Only include uninitialized entities
222                if current_value.is_some() {
223                    return None;
224                }
225
226                // Generate moves for all possible values
227                let moves: Vec<ChangeMove<S, V>> = self
228                    .value_selector
229                    .iter_typed(
230                        score_director,
231                        entity_ref.descriptor_index,
232                        entity_ref.entity_index,
233                    )
234                    .map(|value| {
235                        ChangeMove::new(
236                            entity_ref.entity_index,
237                            Some(value),
238                            getter,
239                            setter,
240                            variable_name,
241                            descriptor_index,
242                        )
243                    })
244                    .collect();
245
246                if moves.is_empty() {
247                    None
248                } else {
249                    Some(
250                        Placement::new(entity_ref, moves)
251                            .with_keep_current_legal(allows_unassigned),
252                    )
253                }
254            })
255            .collect()
256    }
257}
258
259/// Entity placer that sorts placements by a comparator function.
260///
261/// Wraps an inner placer and sorts its placements using a typed comparator.
262/// This enables FIRST_FIT_DECREASING and similar construction variants.
263///
264/// # Example
265///
266/// ```
267/// use solverforge_solver::phase::construction::{SortedEntityPlacer, QueuedEntityPlacer, EntityPlacer};
268/// use solverforge_solver::heuristic::r#move::ChangeMove;
269/// use solverforge_solver::heuristic::selector::{FromSolutionEntitySelector, StaticValueSelector};
270/// use solverforge_core::domain::PlanningSolution;
271/// use solverforge_core::score::SoftScore;
272/// use solverforge_scoring::ScoreDirector;
273/// use std::cmp::Ordering;
274///
275/// #[derive(Clone, Debug)]
276/// struct Task { difficulty: i32, assigned: Option<i32> }
277///
278/// #[derive(Clone, Debug)]
279/// struct Solution { tasks: Vec<Task>, score: Option<SoftScore> }
280///
281/// impl PlanningSolution for Solution {
282///     type Score = SoftScore;
283///     fn score(&self) -> Option<Self::Score> { self.score }
284///     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
285/// }
286///
287/// fn get_assigned(s: &Solution, i: usize) -> Option<i32> {
288///     s.tasks.get(i).and_then(|t| t.assigned)
289/// }
290/// fn set_assigned(s: &mut Solution, i: usize, v: Option<i32>) {
291///     if let Some(t) = s.tasks.get_mut(i) { t.assigned = v; }
292/// }
293///
294/// // Sort entities by difficulty (descending) for FIRST_FIT_DECREASING
295/// fn difficulty_descending(s: &Solution, a: usize, b: usize) -> Ordering {
296///     let da = s.tasks.get(a).map(|t| t.difficulty).unwrap_or(0);
297///     let db = s.tasks.get(b).map(|t| t.difficulty).unwrap_or(0);
298///     db.cmp(&da)  // Descending order
299/// }
300/// ```
301pub struct SortedEntityPlacer<S, M, Inner>
302where
303    S: PlanningSolution,
304    M: Move<S>,
305    Inner: EntityPlacer<S, M>,
306{
307    inner: Inner,
308    // Comparator function: takes (solution, entity_index_a, entity_index_b) -> Ordering
309    comparator: fn(&S, usize, usize) -> std::cmp::Ordering,
310    _phantom: PhantomData<fn() -> (S, M)>,
311}
312
313impl<S, M, Inner> SortedEntityPlacer<S, M, Inner>
314where
315    S: PlanningSolution,
316    M: Move<S>,
317    Inner: EntityPlacer<S, M>,
318{
319    /// Creates a new sorted entity placer.
320    ///
321    /// # Arguments
322    /// * `inner` - The inner placer to wrap
323    /// * `comparator` - Function to compare entities: `(solution, idx_a, idx_b) -> Ordering`
324    pub fn new(inner: Inner, comparator: fn(&S, usize, usize) -> std::cmp::Ordering) -> Self {
325        Self {
326            inner,
327            comparator,
328            _phantom: PhantomData,
329        }
330    }
331}
332
333impl<S, M, Inner> Debug for SortedEntityPlacer<S, M, Inner>
334where
335    S: PlanningSolution,
336    M: Move<S>,
337    Inner: EntityPlacer<S, M>,
338{
339    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
340        f.debug_struct("SortedEntityPlacer")
341            .field("inner", &self.inner)
342            .finish()
343    }
344}
345
346impl<S, M, Inner> EntityPlacer<S, M> for SortedEntityPlacer<S, M, Inner>
347where
348    S: PlanningSolution,
349    M: Move<S>,
350    Inner: EntityPlacer<S, M>,
351{
352    fn get_placements<D: Director<S>>(&self, score_director: &D) -> Vec<Placement<S, M>> {
353        let mut placements = self.inner.get_placements(score_director);
354        let solution = score_director.working_solution();
355        let cmp = self.comparator;
356
357        placements.sort_by(|a, b| {
358            cmp(
359                solution,
360                a.entity_ref.entity_index,
361                b.entity_ref.entity_index,
362            )
363        });
364
365        placements
366    }
367}
368
369#[cfg(test)]
370#[path = "placer_tests.rs"]
371mod tests;