Skip to main content

solverforge_scoring/api/
analysis.rs

1//! Score analysis types for detailed constraint tracking.
2//!
3//! This module provides types for analyzing constraint matches in detail:
4//! each match's score and the entities that caused it.
5
6use std::fmt::Debug;
7
8use solverforge_core::score::Score;
9use solverforge_core::ConstraintRef;
10
11/// An entity involved in a constraint match, as constraint analysis reports
12/// it: the entity's type name, its `Debug` rendering and, when its type has a
13/// `#[planning_id]`, its planning id, all taken when the match is explained.
14/// It holds no copy of the entity, so explaining a match requires only
15/// `Debug` on the entity type.
16#[derive(Clone, PartialEq, Eq, Hash)]
17pub struct EntityRef {
18    /// Type name of the entity (e.g., "Shift", "Employee").
19    pub type_name: String,
20    /// String representation for display. It is a rendering, not an
21    /// identifier: look records up by [`planning_id`](Self::planning_id).
22    pub display: String,
23    /// The entity's planning id, rendered as a string: the id's `Display`
24    /// output when its type implements `Display` (`7`, `shift-7`), otherwise
25    /// its `Debug` output (`ShiftId(7)`). Equal ids render equally, so it is
26    /// a lookup key for the record within its type.
27    ///
28    /// Set for entities streamed from a planning model collection whose type
29    /// has a `#[planning_id]` field (`#[planning_entity]`, `#[problem_fact]`);
30    /// `None` for every other entity, including plain values streamed through
31    /// a hand-built source.
32    pub planning_id: Option<String>,
33}
34
35impl EntityRef {
36    /// Describes `entity` by its type name and `Debug` rendering, with no
37    /// planning id.
38    pub fn new<T: Debug + ?Sized>(entity: &T) -> Self {
39        Self {
40            type_name: std::any::type_name::<T>().to_string(),
41            display: format!("{entity:?}"),
42            planning_id: None,
43        }
44    }
45
46    /// Sets the entity's rendered planning id (see
47    /// [`planning_id`](Self::planning_id)).
48    pub fn with_planning_id(mut self, planning_id: Option<String>) -> Self {
49        self.planning_id = planning_id;
50        self
51    }
52
53    /// Returns the short type name (without module path).
54    pub fn short_type_name(&self) -> &str {
55        self.type_name
56            .rsplit("::")
57            .next()
58            .unwrap_or(&self.type_name)
59    }
60}
61
62impl Debug for EntityRef {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("EntityRef")
65            .field("type", &self.short_type_name())
66            .field("display", &self.display)
67            .field("planning_id", &self.planning_id)
68            .finish()
69    }
70}
71
72/// Justification for why a constraint matched.
73#[derive(Debug, Clone)]
74pub struct ConstraintJustification {
75    /// Entities involved in the match.
76    pub entities: Vec<EntityRef>,
77    /// Human-readable description of why the constraint matched.
78    pub description: String,
79}
80
81impl ConstraintJustification {
82    /// Creates a justification from entities, auto-generating description.
83    pub fn new(entities: Vec<EntityRef>) -> Self {
84        let description = if entities.is_empty() {
85            "No entities".to_string()
86        } else {
87            entities
88                .iter()
89                .map(|e| e.display.as_str())
90                .collect::<Vec<_>>()
91                .join(", ")
92        };
93        Self {
94            entities,
95            description,
96        }
97    }
98
99    /// Creates a justification with a custom description.
100    pub fn with_description(entities: Vec<EntityRef>, description: String) -> Self {
101        Self {
102            entities,
103            description,
104        }
105    }
106}
107
108/// A detailed constraint match with entity information.
109#[derive(Debug, Clone)]
110pub struct DetailedConstraintMatch<'a, Sc: Score> {
111    /// Reference to the constraint that matched.
112    pub constraint_ref: &'a ConstraintRef,
113    /// Score impact of this match.
114    pub score: Sc,
115    /// Justification with involved entities.
116    pub justification: ConstraintJustification,
117}
118
119impl<'a, Sc: Score> DetailedConstraintMatch<'a, Sc> {
120    /// Creates a new detailed constraint match.
121    pub fn new(
122        constraint_ref: &'a ConstraintRef,
123        score: Sc,
124        justification: ConstraintJustification,
125    ) -> Self {
126        Self {
127            constraint_ref,
128            score,
129            justification,
130        }
131    }
132}
133
134/// Per-constraint breakdown in a score explanation.
135#[derive(Debug, Clone)]
136pub struct ConstraintAnalysis<'a, Sc: Score> {
137    /// Constraint reference.
138    pub constraint_ref: &'a ConstraintRef,
139    /// Bound runtime weight multiplier; `0` means the constraint is disabled.
140    pub weight_multiplier: u32,
141    /// Total (weighted) score from this constraint.
142    pub score: Sc,
143    /// All matches for this constraint.
144    pub matches: Vec<DetailedConstraintMatch<'a, Sc>>,
145    /// Whether this is a hard constraint.
146    pub is_hard: bool,
147}
148
149impl<'a, Sc: Score> ConstraintAnalysis<'a, Sc> {
150    /// Creates a new constraint analysis.
151    pub fn new(
152        constraint_ref: &'a ConstraintRef,
153        weight_multiplier: u32,
154        score: Sc,
155        matches: Vec<DetailedConstraintMatch<'a, Sc>>,
156        is_hard: bool,
157    ) -> Self {
158        Self {
159            constraint_ref,
160            weight_multiplier,
161            score,
162            matches,
163            is_hard,
164        }
165    }
166
167    /// Returns the number of matches.
168    pub fn match_count(&self) -> usize {
169        self.matches.len()
170    }
171
172    /// Returns the constraint name.
173    pub fn name(&self) -> &str {
174        &self.constraint_ref.name
175    }
176}