solverforge_core/score/traits.rs
1//! Core Score trait definition
2
3use std::cmp::Ordering;
4use std::fmt::{Debug, Display};
5use std::ops::{Add, Neg, Sub};
6
7use super::ScoreLevel;
8
9/// Core trait for all score types in SolverForge.
10///
11/// Scores represent the quality of a planning solution. They are used to:
12/// - Compare solutions (better/worse/equal)
13/// - Guide the optimization process
14/// - Determine feasibility
15///
16/// All score implementations must be:
17/// - Immutable (operations return new instances)
18/// - Thread-safe (Send + Sync)
19/// - Comparable (total ordering)
20///
21/// # Score Levels
22///
23/// Scores can have multiple levels (e.g., hard/soft constraints):
24/// - Hard constraints: Must be satisfied for a solution to be feasible
25/// - Soft constraints: Optimization objectives to maximize/minimize
26///
27/// When comparing scores, higher-priority levels are compared first.
28///
29/// # Overflow
30///
31/// Score arithmetic never wraps. `Add`, `Sub`, `Neg`, [`Score::abs`],
32/// [`Score::scale`], [`Score::multiply`] and [`Score::divide`] on the built-in
33/// score types panic, in every build profile, when a level does not fit
34/// `i64`; `multiply` and `divide` also panic for a factor that is not finite
35/// (or a zero divisor). A wrapped level would flip sign and turn a penalty
36/// into a reward.
37pub trait Score:
38 Copy
39 + Debug
40 + Display
41 + Default
42 + Send
43 + Sync
44 + PartialEq
45 + Eq
46 + PartialOrd
47 + Ord
48 + Add<Output = Self>
49 + Sub<Output = Self>
50 + Neg<Output = Self>
51 + 'static
52{
53 /// Returns true if this score represents a feasible solution.
54 ///
55 /// A solution is feasible when all hard constraints are satisfied
56 /// (i.e., the hard score is >= 0).
57 fn is_feasible(&self) -> bool;
58
59 /// Returns the score with every level at zero.
60 fn zero() -> Self;
61
62 /// Returns the number of score levels.
63 ///
64 /// For example:
65 /// - SoftScore: 1 level
66 /// - HardSoftScore: 2 levels
67 /// - HardMediumSoftScore: 3 levels
68 fn levels_count() -> usize;
69
70 /// Returns the score value at a priority level.
71 ///
72 /// Level indices follow the same order as `to_level_numbers()` and
73 /// `level_label()`: highest priority first. This is the primitive
74 /// allocation-free score-level accessor used by score-level search behavior.
75 ///
76 /// # Panics
77 /// Panics if `index >= levels_count()`.
78 fn level_number(&self, index: usize) -> i64;
79
80 /// Returns the score values as a vector of i64.
81 ///
82 /// The order is from highest priority to lowest priority.
83 /// For HardSoftScore: [hard, soft].
84 ///
85 /// This is an allocating convenience view derived from `level_number()`.
86 fn to_level_numbers(&self) -> Vec<i64> {
87 let mut levels = Vec::with_capacity(Self::levels_count());
88 for index in 0..Self::levels_count() {
89 levels.push(self.level_number(index));
90 }
91 levels
92 }
93
94 /// Creates a score from level numbers.
95 ///
96 /// # Panics
97 /// Panics if the number of levels doesn't match `levels_count()`.
98 fn from_level_numbers(levels: &[i64]) -> Self;
99
100 /// Multiplies every level by a scalar, rounding to the nearest integer.
101 ///
102 /// # Panics
103 /// Panics when `multiplicand` is not finite or a rounded level is outside
104 /// `i64`.
105 fn multiply(&self, multiplicand: f64) -> Self;
106
107 /// Divides every level by a scalar, rounding to the nearest integer.
108 ///
109 /// # Panics
110 /// Panics when `divisor` is zero or not finite, or a rounded level is
111 /// outside `i64`.
112 fn divide(&self, divisor: f64) -> Self;
113
114 /// Multiplies every level by an exact integer factor.
115 ///
116 /// Unlike `multiply(f64)`, this never rounds and stays exact for every `i64`
117 /// level value. Constraint weight multipliers are applied through it.
118 ///
119 /// # Panics
120 /// Panics when any level overflows `i64`, in every build profile.
121 fn scale(&self, factor: i64) -> Self;
122
123 /// Returns the absolute value of every level.
124 ///
125 /// # Panics
126 /// Panics when a level is `i64::MIN`, whose absolute value is not an `i64`.
127 fn abs(&self) -> Self;
128
129 /// Adds `other` without panicking, returning the sum and whether any level
130 /// overflowed `i64` (the levels are then wrapped and meaningless).
131 ///
132 /// The scoring engine accumulates a batch of deltas this way and checks the
133 /// flag once, instead of branching on every addition. The default delegates
134 /// to `Add` and reports `false`, so a custom score keeps its own overflow
135 /// behavior.
136 #[inline]
137 fn overflowing_add(self, other: Self) -> (Self, bool) {
138 (self + other, false)
139 }
140
141 /// Subtracts `other` without panicking; see `overflowing_add`.
142 #[inline]
143 fn overflowing_sub(self, other: Self) -> (Self, bool) {
144 (self - other, false)
145 }
146
147 /// Negates without panicking; see `overflowing_add`.
148 #[inline]
149 fn overflowing_neg(self) -> (Self, bool) {
150 (-self, false)
151 }
152
153 /// `scale` without panicking: the flag is set when a level overflowed;
154 /// see `overflowing_add`.
155 #[inline]
156 fn overflowing_scale(&self, factor: i64) -> (Self, bool) {
157 (self.scale(factor), false)
158 }
159
160 /// `multiply` without panicking: the flag is set for a non-finite
161 /// multiplicand or a rounded level outside `i64`; see `overflowing_add`.
162 #[inline]
163 fn overflowing_multiply(&self, multiplicand: f64) -> (Self, bool) {
164 (self.multiply(multiplicand), false)
165 }
166
167 /// Converts this score to a single f64 scalar value.
168 ///
169 /// Higher-priority levels are weighted with larger multipliers to preserve
170 /// their dominance. Used for simulated annealing temperature calculations.
171 fn to_scalar(&self) -> f64;
172
173 /// Returns the semantic label for the score level at the given index.
174 ///
175 /// Level indices follow the same order as `to_level_numbers()`:
176 /// highest priority first.
177 ///
178 /// # Panics
179 /// Panics if `index >= levels_count()`.
180 fn level_label(index: usize) -> ScoreLevel;
181
182 /// Compares two scores, returning the ordering.
183 ///
184 /// Default implementation uses the Ord trait.
185 fn compare(&self, other: &Self) -> Ordering {
186 self.cmp(other)
187 }
188
189 /// Returns true if this score is better than the other score.
190 ///
191 /// In optimization, "better" typically means higher score.
192 fn is_better_than(&self, other: &Self) -> bool {
193 self > other
194 }
195
196 /// Returns true if this score is worse than the other score.
197 fn is_worse_than(&self, other: &Self) -> bool {
198 self < other
199 }
200
201 /// Returns true if this score is equal to the other score.
202 fn is_equal_to(&self, other: &Self) -> bool {
203 self == other
204 }
205
206 /// Returns a score with 1 at the first Hard-labeled level and 0 elsewhere.
207 fn one_hard() -> Self {
208 let mut levels = vec![0i64; Self::levels_count()];
209 if let Some(i) =
210 (0..Self::levels_count()).find(|&i| Self::level_label(i) == ScoreLevel::Hard)
211 {
212 levels[i] = 1;
213 }
214 Self::from_level_numbers(&levels)
215 }
216
217 /// Returns a score with 1 at the last Soft-labeled level and 0 elsewhere.
218 fn one_soft() -> Self {
219 let mut levels = vec![0i64; Self::levels_count()];
220 if let Some(i) = (0..Self::levels_count())
221 .rev()
222 .find(|&i| Self::level_label(i) == ScoreLevel::Soft)
223 {
224 levels[i] = 1;
225 }
226 Self::from_level_numbers(&levels)
227 }
228
229 /// Returns a score with 1 at the first Medium-labeled level and 0 elsewhere.
230 fn one_medium() -> Self {
231 let mut levels = vec![0i64; Self::levels_count()];
232 if let Some(i) =
233 (0..Self::levels_count()).find(|&i| Self::level_label(i) == ScoreLevel::Medium)
234 {
235 levels[i] = 1;
236 }
237 Self::from_level_numbers(&levels)
238 }
239}
240
241/// Scores with a text form that can be parsed and rendered.
242pub trait ParseableScore: Score {
243 /// Parses a score from a string representation.
244 ///
245 /// # Format
246 /// - SoftScore: "42" or "42init"
247 /// - HardSoftScore: "0hard/-100soft" or "-1hard/0soft"
248 /// - HardMediumSoftScore: "0hard/0medium/-100soft"
249 fn parse(s: &str) -> Result<Self, ScoreParseError>;
250
251 /// Renders the score in the format [`parse`](Self::parse) accepts.
252 fn to_string_repr(&self) -> String;
253}
254
255/// Error when parsing a score from string
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct ScoreParseError {
258 /// Describes why the input was rejected.
259 pub message: String,
260}
261
262impl std::fmt::Display for ScoreParseError {
263 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264 write!(f, "Score parse error: {}", self.message)
265 }
266}
267
268impl std::error::Error for ScoreParseError {}