solverforge_core/domain/traits.rs
1// Core domain traits
2
3use std::any::Any;
4use std::hash::Hash;
5
6use crate::score::Score;
7
8/// Marker trait for planning solutions.
9///
10/// A planning solution represents both the problem definition and the
11/// (potentially partial) solution. It contains:
12/// - Problem facts: Immutable input data
13/// - Planning entities: Things to be optimized
14/// - Score: The quality of the current solution
15///
16/// # Example
17///
18/// ```
19/// use solverforge_core::{PlanningSolution, score::SoftScore};
20///
21/// #[derive(Clone)]
22/// struct NQueens {
23/// n: usize,
24/// rows: Vec<Option<usize>>,
25/// score: Option<SoftScore>,
26/// }
27///
28/// impl PlanningSolution for NQueens {
29/// type Score = SoftScore;
30///
31/// fn score(&self) -> Option<Self::Score> {
32/// self.score
33/// }
34///
35/// fn set_score(&mut self, score: Option<Self::Score>) {
36/// self.score = score;
37/// }
38/// }
39/// ```
40///
41/// For complex solutions, use the `#[derive(PlanningSolution)]` macro from `solverforge-macros`.
42///
43/// # Thread Safety
44///
45/// Planning solutions must be `Send + Sync` to support multi-threaded solving.
46pub trait PlanningSolution: Clone + Send + Sync + 'static {
47 // The score type used to evaluate this solution.
48 type Score: Score;
49
50 /* Returns the current score of this solution, if calculated.
51
52 Returns `None` if the solution has not been scored yet.
53 */
54 fn score(&self) -> Option<Self::Score>;
55
56 fn set_score(&mut self, score: Option<Self::Score>);
57
58 /* Updates shadow variables for the descriptor/entity pair.
59
60 Default implementation is a no-op. Solutions with derived state can override
61 this to keep cached values synchronized during solving.
62 */
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 */
70 fn update_all_shadows(&mut self) {}
71
72 /* Returns the elements whose list shadows
73 `update_entity_shadows(descriptor_index, entity_index)` writes, with the
74 change source their stream rows are reported under.
75
76 A score director retracts these rows before the shadow write and inserts
77 them after it, so streams that read element shadows stay incremental.
78 Default implementation reports no list shadows.
79 */
80 fn list_shadow_elements(
81 &self,
82 _descriptor_index: usize,
83 _entity_index: usize,
84 ) -> Option<(usize, &[usize])> {
85 None
86 }
87
88 /* Clears the list shadows of an element that no list holds any more.
89
90 Default implementation is a no-op.
91 */
92 fn clear_list_shadows(&mut self, _element: usize) {}
93
94 /* Returns the change source under which rows of `collection` are reported
95 when they carry list shadows, or `None` when the collection holds none.
96 */
97 fn list_shadow_source(_collection: &str) -> Option<usize> {
98 None
99 }
100
101 /* Returns true if this solution is fully initialized.
102
103 A solution is initialized when all planning variables have been assigned.
104 */
105 fn is_initialized(&self) -> bool {
106 // Default implementation - can be overridden by derived code
107 true
108 }
109}
110
111/// Marker trait for planning entities.
112///
113/// A planning entity is something that gets planned/optimized.
114/// It contains one or more planning variables that the solver will change.
115///
116/// # Example
117///
118/// ```
119/// use std::any::Any;
120/// use solverforge_core::PlanningEntity;
121///
122/// #[derive(Clone)]
123/// struct Queen {
124/// column: i32,
125/// row: Option<i32>,
126/// }
127///
128/// impl PlanningEntity for Queen {
129/// fn as_any(&self) -> &dyn Any { self }
130/// fn as_any_mut(&mut self) -> &mut dyn Any { self }
131/// }
132/// ```
133///
134/// For complex entities, use the `#[derive(PlanningEntity)]` macro from `solverforge-macros`.
135///
136/// # Pinning
137///
138/// Entities can be "pinned" to preserve their input genuine planning variables
139/// during solving. Override `is_pinned()` to return true for pinned entities;
140/// manually assembled entity descriptors must also supply a pin predicate.
141pub trait PlanningEntity: Clone + Send + Sync + Any + 'static {
142 /* Returns true if this entity is pinned (should not be changed).
143
144 Default implementation returns false (entity can be changed).
145 */
146 fn is_pinned(&self) -> bool {
147 false
148 }
149
150 // Cast to Any for dynamic typing support.
151 fn as_any(&self) -> &dyn Any;
152
153 // Cast to mutable Any for dynamic typing support.
154 fn as_any_mut(&mut self) -> &mut dyn Any;
155}
156
157/// Marker trait for problem facts.
158///
159/// Problem facts are immutable input data that define the problem.
160/// They are used by constraints but not changed during solving.
161///
162/// # Example
163///
164/// ```
165/// use std::any::Any;
166/// use solverforge_core::ProblemFact;
167///
168/// #[derive(Clone)]
169/// struct Room {
170/// id: i64,
171/// capacity: usize,
172/// }
173///
174/// impl ProblemFact for Room {
175/// fn as_any(&self) -> &dyn Any { self }
176/// }
177/// ```
178pub trait ProblemFact: Clone + Send + Sync + Any + 'static {
179 // Cast to Any for dynamic typing support.
180 fn as_any(&self) -> &dyn Any;
181}
182
183/// Trait for unique identification of entities and facts.
184///
185/// Used for looking up working copies during solving and rebasing moves.
186///
187/// # Example
188///
189/// ```
190/// use solverforge_core::PlanningId;
191///
192/// #[derive(Clone)]
193/// struct Task {
194/// id: i64,
195/// name: String,
196/// }
197///
198/// impl PlanningId for Task {
199/// type Id = i64;
200/// fn planning_id(&self) -> i64 { self.id }
201/// }
202/// ```
203///
204/// The ID type must be `Eq + Hash + Clone`.
205pub trait PlanningId {
206 // The type of the unique identifier.
207 type Id: Eq + Hash + Clone + Send + Sync + 'static;
208
209 /* Returns the unique identifier for this object.
210
211 This must never return a value that changes during solving.
212 */
213 fn planning_id(&self) -> Self::Id;
214}
215
216/// Trait for solutions with list-based planning variables.
217///
218/// Used for problems like VRP where entities (vehicles) have ordered lists
219/// of elements (visits) that can be inserted, removed, or reordered.
220///
221/// # Examples
222///
223/// ```
224/// use solverforge_core::domain::ListVariableSolution;
225/// use solverforge_core::PlanningSolution;
226/// use solverforge_core::score::SoftScore;
227///
228/// #[derive(Clone)]
229/// struct Vehicle {
230/// visits: Vec<usize>,
231/// }
232///
233/// #[derive(Clone)]
234/// struct VrpSolution {
235/// vehicles: Vec<Vehicle>,
236/// visit_count: usize,
237/// score: Option<SoftScore>,
238/// }
239///
240/// impl PlanningSolution for VrpSolution {
241/// type Score = SoftScore;
242/// fn score(&self) -> Option<Self::Score> { self.score }
243/// fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
244/// }
245///
246/// impl ListVariableSolution for VrpSolution {
247/// type Element = usize;
248///
249/// fn entity_count(&self) -> usize {
250/// self.vehicles.len()
251/// }
252///
253/// fn list_len(&self, entity_idx: usize) -> usize {
254/// self.vehicles[entity_idx].visits.len()
255/// }
256///
257/// fn list_get(&self, entity_idx: usize, position: usize) -> Self::Element {
258/// self.vehicles[entity_idx].visits[position]
259/// }
260///
261/// fn list_push(&mut self, entity_idx: usize, elem: Self::Element) {
262/// self.vehicles[entity_idx].visits.push(elem);
263/// }
264///
265/// fn list_insert(&mut self, entity_idx: usize, position: usize, elem: Self::Element) {
266/// self.vehicles[entity_idx].visits.insert(position, elem);
267/// }
268///
269/// fn list_remove(&mut self, entity_idx: usize, position: usize) -> Self::Element {
270/// self.vehicles[entity_idx].visits.remove(position)
271/// }
272///
273/// fn list_reverse(&mut self, entity_idx: usize, start: usize, end: usize) {
274/// self.vehicles[entity_idx].visits[start..end].reverse();
275/// }
276///
277/// fn unassigned_elements(&self) -> Vec<Self::Element> {
278/// use std::collections::HashSet;
279/// let assigned: HashSet<usize> = self.vehicles
280/// .iter()
281/// .flat_map(|v| v.visits.iter().copied())
282/// .collect();
283/// (0..self.visit_count)
284/// .filter(|i| !assigned.contains(i))
285/// .collect()
286/// }
287/// }
288/// ```
289pub trait ListVariableSolution: PlanningSolution {
290 // The type of elements in the list (typically an index or ID).
291 type Element: Copy + Send + Sync;
292
293 fn entity_count(&self) -> usize;
294
295 fn list_len(&self, entity_idx: usize) -> usize;
296
297 fn list_get(&self, entity_idx: usize, position: usize) -> Self::Element;
298
299 // Appends an element to the end of the entity's list.
300 fn list_push(&mut self, entity_idx: usize, elem: Self::Element);
301
302 // Inserts an element at the given position in the entity's list.
303 fn list_insert(&mut self, entity_idx: usize, position: usize, elem: Self::Element);
304
305 // Removes and returns the element at the given position.
306 fn list_remove(&mut self, entity_idx: usize, position: usize) -> Self::Element;
307
308 // Reverses the elements in the range [start, end) for the entity's list.
309 fn list_reverse(&mut self, entity_idx: usize, start: usize, end: usize);
310
311 // Returns all elements not currently assigned to any entity.
312 fn unassigned_elements(&self) -> Vec<Self::Element>;
313}