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 /// Returns true if this solution is fully initialized.
121 ///
122 /// A solution is initialized when all planning variables have been assigned.
123 fn is_initialized(&self) -> bool {
124 // Default implementation - can be overridden by derived code
125 true
126 }
127}
128
129/// Marker trait for planning entities.
130///
131/// A planning entity is something that gets planned/optimized.
132/// It contains one or more planning variables that the solver will change.
133///
134/// # Example
135///
136/// ```
137/// use std::any::Any;
138/// use solverforge_core::PlanningEntity;
139///
140/// #[derive(Clone)]
141/// struct Queen {
142/// column: i32,
143/// row: Option<i32>,
144/// }
145///
146/// impl PlanningEntity for Queen {
147/// fn as_any(&self) -> &dyn Any { self }
148/// fn as_any_mut(&mut self) -> &mut dyn Any { self }
149/// }
150/// ```
151///
152/// For complex entities, use the `#[derive(PlanningEntity)]` macro from `solverforge-macros`.
153///
154/// # Pinning
155///
156/// Entities can be "pinned" to preserve their input genuine planning variables
157/// during solving. Override `is_pinned()` to return true for pinned entities;
158/// manually assembled entity descriptors must also supply a pin predicate.
159pub trait PlanningEntity: Clone + Send + Sync + Any + 'static {
160 /// Returns true if this entity is pinned (should not be changed).
161 ///
162 /// Default implementation returns false (entity can be changed).
163 fn is_pinned(&self) -> bool {
164 false
165 }
166
167 /// Cast to Any for dynamic typing support.
168 fn as_any(&self) -> &dyn Any;
169
170 /// Cast to mutable Any for dynamic typing support.
171 fn as_any_mut(&mut self) -> &mut dyn Any;
172}
173
174/// Marker trait for problem facts.
175///
176/// Problem facts are immutable input data that define the problem.
177/// They are used by constraints but not changed during solving.
178///
179/// # Example
180///
181/// ```
182/// use std::any::Any;
183/// use solverforge_core::ProblemFact;
184///
185/// #[derive(Clone)]
186/// struct Room {
187/// id: i64,
188/// capacity: usize,
189/// }
190///
191/// impl ProblemFact for Room {
192/// fn as_any(&self) -> &dyn Any { self }
193/// }
194/// ```
195pub trait ProblemFact: Clone + Send + Sync + Any + 'static {
196 /// Cast to Any for dynamic typing support.
197 fn as_any(&self) -> &dyn Any;
198}
199
200/// Trait for unique identification of entities and facts.
201///
202/// Used for looking up working copies during solving and rebasing moves.
203///
204/// # Example
205///
206/// ```
207/// use solverforge_core::PlanningId;
208///
209/// #[derive(Clone)]
210/// struct Task {
211/// id: i64,
212/// name: String,
213/// }
214///
215/// impl PlanningId for Task {
216/// type Id = i64;
217/// fn planning_id(&self) -> i64 { self.id }
218/// }
219/// ```
220///
221/// The ID type must be `Eq + Hash + Clone`.
222pub trait PlanningId {
223 /// The type of the unique identifier.
224 type Id: Eq + Hash + Clone + Send + Sync + 'static;
225
226 /// Returns the unique identifier for this object.
227 ///
228 /// This must never return a value that changes during solving.
229 fn planning_id(&self) -> Self::Id;
230}