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