Skip to main content

solverforge_core/
constraint_weights.rs

1//! Runtime per-constraint weight multipliers.
2//!
3//! `ConstraintWeights` lives on a planning solution (through the
4//! `#[constraint_weights]` field attribute) and scales each named constraint's
5//! coded contribution by a non-negative integer multiplier.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use crate::constraint::ConstraintRef;
10
11/// Largest accepted constraint weight multiplier.
12///
13/// Multipliers scale exact `i64` score levels. Capping them at one million keeps
14/// a coded per-match contribution of up to about 9.2e12 per level (for example
15/// 92 million hard units of a `HardSoftDecimalScore`, which stores five decimal
16/// places) representable after scaling, while still letting UIs ship baseline
17/// multipliers such as `{"Travel time": 10}` with generous slider ranges.
18/// Score scaling itself stays strict and panics on any remaining overflow.
19pub const MAX_CONSTRAINT_WEIGHT_MULTIPLIER: u32 = 1_000_000;
20
21/// Per-constraint multipliers keyed by `ConstraintRef::full_name()`.
22///
23/// A constraint that is not listed keeps multiplier `1`, its coded behavior.
24/// Multiplier `0` disables the constraint and `n` scales its contribution `n`
25/// times. An override applies to every terminal carrying that constraint name.
26///
27/// # Example
28///
29/// ```
30/// use solverforge_core::{ConstraintRef, ConstraintWeights};
31///
32/// let mut weights = ConstraintWeights::new();
33/// weights.set("Travel time", 10).set("Overtime", 0);
34///
35/// assert_eq!(weights.get("Travel time"), Some(10));
36/// assert_eq!(weights.multiplier_for(&ConstraintRef::new("", "Overtime")), 0);
37/// assert_eq!(weights.multiplier_for(&ConstraintRef::new("", "Unlisted")), 1);
38///
39/// let known = [
40///     ConstraintRef::new("", "Travel time"),
41///     ConstraintRef::new("", "Overtime"),
42/// ];
43/// assert!(weights.validate(&known).is_ok());
44///
45/// weights.set("Travle time", 2);
46/// let error = weights.validate(&known).unwrap_err();
47/// assert!(error.to_string().contains("did you mean \"Travel time\""));
48/// ```
49#[derive(Clone, Debug, Default, PartialEq, Eq)]
50#[cfg_attr(
51    feature = "serde",
52    derive(serde::Serialize, serde::Deserialize),
53    serde(transparent)
54)]
55pub struct ConstraintWeights {
56    multipliers: BTreeMap<String, u32>,
57}
58
59impl ConstraintWeights {
60    /// Creates an empty set of weights, under which every constraint keeps multiplier `1`.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// Sets the multiplier for the constraint whose full name is `constraint`,
66    /// replacing any previous value.
67    ///
68    /// The multiplier is only range-checked by [`validate`](Self::validate).
69    pub fn set(&mut self, constraint: impl Into<String>, multiplier: u32) -> &mut Self {
70        self.multipliers.insert(constraint.into(), multiplier);
71        self
72    }
73
74    /// Removes the override for `constraint`, returning its previous multiplier.
75    pub fn remove(&mut self, constraint: &str) -> Option<u32> {
76        self.multipliers.remove(constraint)
77    }
78
79    /// Returns the explicit multiplier for `constraint`, or `None` when it is not listed.
80    pub fn get(&self, constraint: &str) -> Option<u32> {
81        self.multipliers.get(constraint).copied()
82    }
83
84    /// Returns the multiplier for `constraint`, `1` when it is not listed.
85    pub fn multiplier_for(&self, constraint: &ConstraintRef) -> u32 {
86        if self.multipliers.is_empty() {
87            return 1;
88        }
89        self.get(&constraint.full_name()).unwrap_or(1)
90    }
91
92    /// Returns `true` when no constraint has an override.
93    pub fn is_empty(&self) -> bool {
94        self.multipliers.is_empty()
95    }
96
97    /// Returns the number of constraints with an override.
98    pub fn len(&self) -> usize {
99        self.multipliers.len()
100    }
101
102    /// Iterates over `(constraint full name, multiplier)` pairs in name order.
103    pub fn iter(&self) -> impl Iterator<Item = (&str, u32)> {
104        self.multipliers
105            .iter()
106            .map(|(name, multiplier)| (name.as_str(), *multiplier))
107    }
108
109    /// Checks every listed name against the known constraints and every
110    /// multiplier against `MAX_CONSTRAINT_WEIGHT_MULTIPLIER`.
111    ///
112    /// Names are checked in sorted order, so the reported error is deterministic.
113    pub fn validate<'a>(
114        &self,
115        known: impl IntoIterator<Item = &'a ConstraintRef>,
116    ) -> Result<(), ConstraintWeightError> {
117        let known: BTreeSet<String> = known.into_iter().map(ConstraintRef::full_name).collect();
118        for (name, &multiplier) in &self.multipliers {
119            if !known.contains(name) {
120                return Err(ConstraintWeightError::UnknownConstraint {
121                    name: name.clone(),
122                    suggestions: close_matches(name, &known),
123                    known: known.iter().cloned().collect(),
124                });
125            }
126            if multiplier > MAX_CONSTRAINT_WEIGHT_MULTIPLIER {
127                return Err(ConstraintWeightError::MultiplierTooLarge {
128                    name: name.clone(),
129                    multiplier,
130                    max: MAX_CONSTRAINT_WEIGHT_MULTIPLIER,
131                });
132            }
133        }
134        Ok(())
135    }
136}
137
138/// Error reported when constraint weights do not fit the model's constraints.
139#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
140pub enum ConstraintWeightError {
141    /// A listed name matches no constraint in the model.
142    #[error(
143        "constraint weight names unknown constraint \"{name}\"{}; known constraints: {}",
144        suggestion_text(suggestions),
145        known_text(known)
146    )]
147    UnknownConstraint {
148        /// The unknown constraint name.
149        name: String,
150        /// Known names within a small edit distance of `name`, for a "did you mean" hint.
151        suggestions: Vec<String>,
152        /// Full names of every constraint in the model, sorted.
153        known: Vec<String>,
154    },
155    /// A multiplier exceeds [`MAX_CONSTRAINT_WEIGHT_MULTIPLIER`].
156    #[error("constraint weight multiplier {multiplier} for \"{name}\" exceeds the maximum {max}")]
157    MultiplierTooLarge {
158        /// The constraint whose multiplier is too large.
159        name: String,
160        /// The rejected multiplier.
161        multiplier: u32,
162        /// The largest accepted multiplier.
163        max: u32,
164    },
165}
166
167fn suggestion_text(suggestions: &[String]) -> String {
168    match suggestions {
169        [] => String::new(),
170        [only] => format!(" (did you mean \"{only}\"?)"),
171        many => format!(
172            " (did you mean one of {}?)",
173            many.iter()
174                .map(|name| format!("\"{name}\""))
175                .collect::<Vec<_>>()
176                .join(", ")
177        ),
178    }
179}
180
181fn known_text(known: &[String]) -> String {
182    if known.is_empty() {
183        return "none".to_string();
184    }
185    known
186        .iter()
187        .map(|name| format!("\"{name}\""))
188        .collect::<Vec<_>>()
189        .join(", ")
190}
191
192fn close_matches(name: &str, known: &BTreeSet<String>) -> Vec<String> {
193    let lowered = name.to_lowercase();
194    let limit = (name.chars().count() / 3).max(1);
195    known
196        .iter()
197        .filter(|candidate| {
198            let candidate = candidate.to_lowercase();
199            candidate == lowered || edit_distance(&candidate, &lowered) <= limit
200        })
201        .cloned()
202        .collect()
203}
204
205fn edit_distance(left: &str, right: &str) -> usize {
206    let right: Vec<char> = right.chars().collect();
207    let mut previous: Vec<usize> = (0..=right.len()).collect();
208    let mut current = vec![0; right.len() + 1];
209    for (i, l) in left.chars().enumerate() {
210        current[0] = i + 1;
211        for (j, r) in right.iter().enumerate() {
212            let substitution = previous[j] + usize::from(l != *r);
213            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
214        }
215        std::mem::swap(&mut previous, &mut current);
216    }
217    previous[right.len()]
218}