Skip to main content

solverforge_core/domain/
traits.rs

1//! Core domain traits
2
3use std::any::Any;
4use std::hash::Hash;
5
6use crate::constraint_weights::ConstraintWeights;
7use crate::score::Score;
8
9/// Marker trait for planning solutions.
10///
11/// A planning solution represents both the problem definition and the
12/// (potentially partial) solution. It contains:
13/// - Problem facts: Immutable input data
14/// - Planning entities: Things to be optimized
15/// - Score: The quality of the current solution
16///
17/// # Example
18///
19/// ```
20/// use solverforge_core::{PlanningSolution, score::SoftScore};
21///
22/// #[derive(Clone)]
23/// struct NQueens {
24///     n: usize,
25///     rows: Vec<Option<usize>>,
26///     score: Option<SoftScore>,
27/// }
28///
29/// impl PlanningSolution for NQueens {
30///     type Score = SoftScore;
31///
32///     fn score(&self) -> Option<Self::Score> {
33///         self.score
34///     }
35///
36///     fn set_score(&mut self, score: Option<Self::Score>) {
37///         self.score = score;
38///     }
39/// }
40/// ```
41///
42/// For complex solutions, use the `#[derive(PlanningSolution)]` macro from `solverforge-macros`.
43///
44/// # Thread Safety
45///
46/// Planning solutions must be `Send + Sync` to support multi-threaded solving.
47pub trait PlanningSolution: Clone + Send + Sync + 'static {
48    /// The score type used to evaluate this solution.
49    type Score: Score;
50
51    /// Returns the current score of this solution, if calculated.
52    ///
53    /// Returns `None` if the solution has not been scored yet.
54    fn score(&self) -> Option<Self::Score>;
55
56    /// Stores the score; `None` marks the solution as unscored.
57    fn set_score(&mut self, score: Option<Self::Score>);
58
59    /// Updates shadow variables for the descriptor/entity pair.
60    ///
61    /// Default implementation is a no-op. Solutions with derived state can override
62    /// this to keep cached values synchronized during solving.
63    fn update_entity_shadows(&mut self, _descriptor_index: usize, _entity_index: usize) {}
64
65    /// Updates all shadow variables for the full solution.
66    ///
67    /// Default implementation is a no-op. Solutions with derived state can override
68    /// this to refresh all cached values before initialization.
69    fn update_all_shadows(&mut self) {}
70
71    /// Whether this solution type carries runtime constraint weights.
72    ///
73    /// Whether a value's weights apply is decided by the score director's weight
74    /// mode, a type chosen when the director is built; solves pick the weighted
75    /// mode only when this constant is `true` and some multiplier differs from
76    /// `1`. `#[planning_solution]` sets it to `true` exactly when a field is
77    /// marked `#[constraint_weights]`, and then also routes the solve through the
78    /// weighted entrypoint. A manual implementation that overrides
79    /// `constraint_weights` must set it to `true` as well, or the weights are
80    /// never applied.
81    const HAS_CONSTRAINT_WEIGHTS: bool = false;
82
83    /// Returns the runtime constraint weight multipliers carried by this solution.
84    ///
85    /// Default implementation returns `None`: every constraint keeps its coded
86    /// weight. `#[planning_solution]` generates this accessor for the field marked
87    /// `#[constraint_weights]`. Weighted-mode score directors bind these
88    /// multipliers on construction and on every (re)initialization, so a running
89    /// solve must reset its director after changing them.
90    fn constraint_weights(&self) -> Option<&ConstraintWeights> {
91        None
92    }
93
94    /// Returns the elements whose list shadows
95    /// `update_entity_shadows(descriptor_index, entity_index)` writes, with the
96    /// change source their stream rows are reported under.
97    ///
98    /// A score director retracts these rows before the shadow write and inserts
99    /// them after it, so streams that read element shadows stay incremental.
100    /// Default implementation reports no list shadows.
101    fn list_shadow_elements(
102        &self,
103        _descriptor_index: usize,
104        _entity_index: usize,
105    ) -> Option<(usize, &[usize])> {
106        None
107    }
108
109    /// Clears the list shadows of an element that no list holds any more.
110    ///
111    /// Default implementation is a no-op.
112    fn clear_list_shadows(&mut self, _element: usize) {}
113
114    /// Returns the change source under which rows of `collection` are reported
115    /// when they carry list shadows, or `None` when the collection holds none.
116    fn list_shadow_source(_collection: &str) -> Option<usize> {
117        None
118    }
119
120    /// Whether the list shadows include a cascading shadow: an element value
121    /// computed from the element's previous element in its list and from the
122    /// elements it declares it depends on, which may sit in other owners'
123    /// lists.
124    ///
125    /// `#[shadow_variable_updates(cascading_field = ...)]` sets it to `true`
126    /// and generates the `cascading_*` hooks below. When it is `false`
127    /// (the default) a score director compiles no cascading code into its
128    /// variable-change path.
129    const HAS_CASCADING_SHADOWS: bool = false;
130
131    /// Number of elements in the collection that carries the cascading
132    /// shadow.
133    fn cascading_element_count(&self) -> usize {
134        0
135    }
136
137    /// Whether `element` is held by a list.
138    fn cascading_assigned(&self, _element: usize) -> bool {
139        false
140    }
141
142    /// The element after `element` in its list, if any.
143    fn cascading_next(&self, _element: usize) -> Option<usize> {
144        None
145    }
146
147    /// Appends the elements `element`'s cascading value depends on, besides
148    /// its previous element in its list, to `dependencies`. Dependencies are
149    /// problem facts: moves never change them.
150    fn cascading_dependencies(&self, _element: usize, _dependencies: &mut Vec<usize>) {}
151
152    /// Whether `element`'s cascading value is unset.
153    fn cascading_unset(&self, _element: usize) -> bool {
154        true
155    }
156
157    /// Recomputes `element`'s cascading value, or unsets it when
158    /// `computable` is `false` (the element is in no list, or on a
159    /// dependency cycle). When the value changes, calls `before_write` with
160    /// the solution still holding the old value, then writes the new one and
161    /// returns `true`.
162    fn update_cascading_shadow<W: FnOnce(&Self)>(
163        &mut self,
164        _element: usize,
165        _computable: bool,
166        _before_write: W,
167    ) -> bool {
168        false
169    }
170
171    /// Updates the list shadows of one owner that describe list structure
172    /// (inverse, index, previous, next) without the cascading shadow, which
173    /// the caller propagates afterwards. Defaults to `update_entity_shadows`.
174    fn update_list_structure_shadows(&mut self, descriptor_index: usize, entity_index: usize) {
175        self.update_entity_shadows(descriptor_index, entity_index);
176    }
177
178    /// Returns true if this solution is fully initialized.
179    ///
180    /// A solution is initialized when all planning variables have been assigned.
181    fn is_initialized(&self) -> bool {
182        // Default implementation - can be overridden by derived code
183        true
184    }
185}
186
187/// Marker trait for planning entities.
188///
189/// A planning entity is something that gets planned/optimized.
190/// It contains one or more planning variables that the solver will change.
191///
192/// # Example
193///
194/// ```
195/// use std::any::Any;
196/// use solverforge_core::PlanningEntity;
197///
198/// #[derive(Clone)]
199/// struct Queen {
200///     column: i32,
201///     row: Option<i32>,
202/// }
203///
204/// impl PlanningEntity for Queen {
205///     fn as_any(&self) -> &dyn Any { self }
206///     fn as_any_mut(&mut self) -> &mut dyn Any { self }
207/// }
208/// ```
209///
210/// For complex entities, use the `#[derive(PlanningEntity)]` macro from `solverforge-macros`.
211///
212/// # Pinning
213///
214/// Entities can be "pinned" to preserve their input genuine planning variables
215/// during solving. Override `is_pinned()` to return true for pinned entities;
216/// manually assembled entity descriptors must also supply a pin predicate.
217pub trait PlanningEntity: Clone + Send + Sync + Any + 'static {
218    /// Returns true if this entity is pinned (should not be changed).
219    ///
220    /// Default implementation returns false (entity can be changed).
221    fn is_pinned(&self) -> bool {
222        false
223    }
224
225    /// Cast to Any for dynamic typing support.
226    fn as_any(&self) -> &dyn Any;
227
228    /// Cast to mutable Any for dynamic typing support.
229    fn as_any_mut(&mut self) -> &mut dyn Any;
230}
231
232/// Marker trait for problem facts.
233///
234/// Problem facts are immutable input data that define the problem.
235/// They are used by constraints but not changed during solving.
236///
237/// # Example
238///
239/// ```
240/// use std::any::Any;
241/// use solverforge_core::ProblemFact;
242///
243/// #[derive(Clone)]
244/// struct Room {
245///     id: i64,
246///     capacity: usize,
247/// }
248///
249/// impl ProblemFact for Room {
250///     fn as_any(&self) -> &dyn Any { self }
251/// }
252/// ```
253pub trait ProblemFact: Clone + Send + Sync + Any + 'static {
254    /// Cast to Any for dynamic typing support.
255    fn as_any(&self) -> &dyn Any;
256}
257
258/// Trait for unique identification of entities and facts.
259///
260/// Used for looking up working copies during solving and rebasing moves.
261///
262/// # Example
263///
264/// ```
265/// use solverforge_core::PlanningId;
266///
267/// #[derive(Clone)]
268/// struct Task {
269///     id: i64,
270///     name: String,
271/// }
272///
273/// impl PlanningId for Task {
274///     type Id = i64;
275///     fn planning_id(&self) -> i64 { self.id }
276/// }
277/// ```
278///
279/// The ID type must be `Eq + Hash + Clone`.
280pub trait PlanningId {
281    /// The type of the unique identifier.
282    type Id: Eq + Hash + Clone + Send + Sync + 'static;
283
284    /// Returns the unique identifier for this object.
285    ///
286    /// This must never return a value that changes during solving.
287    fn planning_id(&self) -> Self::Id;
288}