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 /// Appends the peers of `element` to `peers`: elements computed together
153 /// with it, joined transitively into a joint group. A member's value is
154 /// computed after the previous elements and dependencies of every member
155 /// hold their final values, so it may read them; it must not read
156 /// another member's cascading value. Peers are problem facts: moves
157 /// never change them.
158 fn cascading_peers(&self, _element: usize, _peers: &mut Vec<usize>) {}
159
160 /// Whether `element`'s list structure shadows already describe the place
161 /// `owner_descriptor`/`owner_index`, position `index`, between `previous`
162 /// and `next`: its owner, previous and next shadows (and index shadow,
163 /// when declared) hold those values.
164 ///
165 /// A score director with a cascading shadow asks this before rewriting an
166 /// owner's structure and keeps the stream row of an element that answers
167 /// `true` and whose cascading value does not change. `false` (the default)
168 /// rescores the element. `#[shadow_variable_updates(cascading_field =
169 /// ...)]` generates it from the configured structure fields.
170 fn list_structure_unchanged(
171 &self,
172 _element: usize,
173 _owner_descriptor: usize,
174 _owner_index: usize,
175 _index: usize,
176 _previous: Option<usize>,
177 _next: Option<usize>,
178 ) -> bool {
179 false
180 }
181
182 /// Whether `element`'s cascading value is unset.
183 fn cascading_unset(&self, _element: usize) -> bool {
184 true
185 }
186
187 /// Recomputes `element`'s cascading value, or unsets it when
188 /// `computable` is `false` (the element is in no list, or on a
189 /// dependency cycle). When the value changes, calls `before_write` with
190 /// the solution still holding the old value, then writes the new one and
191 /// returns `true`.
192 fn update_cascading_shadow<W: FnOnce(&Self)>(
193 &mut self,
194 _element: usize,
195 _computable: bool,
196 _before_write: W,
197 ) -> bool {
198 false
199 }
200
201 /// Updates the list shadows of one owner that describe list structure
202 /// (inverse, index, previous, next) without the cascading shadow, which
203 /// the caller propagates afterwards. Defaults to `update_entity_shadows`.
204 fn update_list_structure_shadows(&mut self, descriptor_index: usize, entity_index: usize) {
205 self.update_entity_shadows(descriptor_index, entity_index);
206 }
207
208 /// Returns true if this solution is fully initialized.
209 ///
210 /// A solution is initialized when all planning variables have been assigned.
211 fn is_initialized(&self) -> bool {
212 // Default implementation - can be overridden by derived code
213 true
214 }
215}
216
217/// Marker trait for planning entities.
218///
219/// A planning entity is something that gets planned/optimized.
220/// It contains one or more planning variables that the solver will change.
221///
222/// # Example
223///
224/// ```
225/// use std::any::Any;
226/// use solverforge_core::PlanningEntity;
227///
228/// #[derive(Clone)]
229/// struct Queen {
230/// column: i32,
231/// row: Option<i32>,
232/// }
233///
234/// impl PlanningEntity for Queen {
235/// fn as_any(&self) -> &dyn Any { self }
236/// fn as_any_mut(&mut self) -> &mut dyn Any { self }
237/// }
238/// ```
239///
240/// For complex entities, use the `#[derive(PlanningEntity)]` macro from `solverforge-macros`.
241///
242/// # Pinning
243///
244/// Entities can be "pinned" to preserve their input genuine planning variables
245/// during solving. Override `is_pinned()` to return true for pinned entities;
246/// manually assembled entity descriptors must also supply a pin predicate.
247pub trait PlanningEntity: Clone + Send + Sync + Any + 'static {
248 /// Returns true if this entity is pinned (should not be changed).
249 ///
250 /// Default implementation returns false (entity can be changed).
251 fn is_pinned(&self) -> bool {
252 false
253 }
254
255 /// Cast to Any for dynamic typing support.
256 fn as_any(&self) -> &dyn Any;
257
258 /// Cast to mutable Any for dynamic typing support.
259 fn as_any_mut(&mut self) -> &mut dyn Any;
260}
261
262/// Marker trait for problem facts.
263///
264/// Problem facts are immutable input data that define the problem.
265/// They are used by constraints but not changed during solving.
266///
267/// # Example
268///
269/// ```
270/// use std::any::Any;
271/// use solverforge_core::ProblemFact;
272///
273/// #[derive(Clone)]
274/// struct Room {
275/// id: i64,
276/// capacity: usize,
277/// }
278///
279/// impl ProblemFact for Room {
280/// fn as_any(&self) -> &dyn Any { self }
281/// }
282/// ```
283pub trait ProblemFact: Clone + Send + Sync + Any + 'static {
284 /// Cast to Any for dynamic typing support.
285 fn as_any(&self) -> &dyn Any;
286}
287
288/// Trait for unique identification of entities and facts.
289///
290/// Used for looking up working copies during solving and rebasing moves.
291///
292/// # Example
293///
294/// ```
295/// use solverforge_core::PlanningId;
296///
297/// #[derive(Clone)]
298/// struct Task {
299/// id: i64,
300/// name: String,
301/// }
302///
303/// impl PlanningId for Task {
304/// type Id = i64;
305/// fn planning_id(&self) -> i64 { self.id }
306/// }
307/// ```
308///
309/// The ID type must be `Eq + Hash + Clone`.
310pub trait PlanningId {
311 /// The type of the unique identifier.
312 type Id: Eq + Hash + Clone + Send + Sync + 'static;
313
314 /// Returns the unique identifier for this object.
315 ///
316 /// This must never return a value that changes during solving.
317 fn planning_id(&self) -> Self::Id;
318}