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 and its `Debug` rendering, taken when the match
13/// is explained. It holds no copy of the entity, so explaining a match
14/// requires only `Debug` on the entity type.
15#[derive(Clone, PartialEq, Eq, Hash)]
16pub struct EntityRef {
17    /// Type name of the entity (e.g., "Shift", "Employee").
18    pub type_name: String,
19    /// String representation for display.
20    pub display: String,
21}
22
23impl EntityRef {
24    /// Describes `entity` by its type name and `Debug` rendering.
25    pub fn new<T: Debug + ?Sized>(entity: &T) -> Self {
26        Self {
27            type_name: std::any::type_name::<T>().to_string(),
28            display: format!("{entity:?}"),
29        }
30    }
31
32    /// Returns the short type name (without module path).
33    pub fn short_type_name(&self) -> &str {
34        self.type_name
35            .rsplit("::")
36            .next()
37            .unwrap_or(&self.type_name)
38    }
39}
40
41impl Debug for EntityRef {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("EntityRef")
44            .field("type", &self.short_type_name())
45            .field("display", &self.display)
46            .finish()
47    }
48}
49
50/// Justification for why a constraint matched.
51#[derive(Debug, Clone)]
52pub struct ConstraintJustification {
53    /// Entities involved in the match.
54    pub entities: Vec<EntityRef>,
55    /// Human-readable description of why the constraint matched.
56    pub description: String,
57}
58
59impl ConstraintJustification {
60    /// Creates a justification from entities, auto-generating description.
61    pub fn new(entities: Vec<EntityRef>) -> Self {
62        let description = if entities.is_empty() {
63            "No entities".to_string()
64        } else {
65            entities
66                .iter()
67                .map(|e| e.display.as_str())
68                .collect::<Vec<_>>()
69                .join(", ")
70        };
71        Self {
72            entities,
73            description,
74        }
75    }
76
77    /// Creates a justification with a custom description.
78    pub fn with_description(entities: Vec<EntityRef>, description: String) -> Self {
79        Self {
80            entities,
81            description,
82        }
83    }
84}
85
86/// A detailed constraint match with entity information.
87#[derive(Debug, Clone)]
88pub struct DetailedConstraintMatch<'a, Sc: Score> {
89    /// Reference to the constraint that matched.
90    pub constraint_ref: &'a ConstraintRef,
91    /// Score impact of this match.
92    pub score: Sc,
93    /// Justification with involved entities.
94    pub justification: ConstraintJustification,
95}
96
97impl<'a, Sc: Score> DetailedConstraintMatch<'a, Sc> {
98    /// Creates a new detailed constraint match.
99    pub fn new(
100        constraint_ref: &'a ConstraintRef,
101        score: Sc,
102        justification: ConstraintJustification,
103    ) -> Self {
104        Self {
105            constraint_ref,
106            score,
107            justification,
108        }
109    }
110}
111
112/// Per-constraint breakdown in a score explanation.
113#[derive(Debug, Clone)]
114pub struct ConstraintAnalysis<'a, Sc: Score> {
115    /// Constraint reference.
116    pub constraint_ref: &'a ConstraintRef,
117    /// Bound runtime weight multiplier; `0` means the constraint is disabled.
118    pub weight_multiplier: u32,
119    /// Total (weighted) score from this constraint.
120    pub score: Sc,
121    /// All matches for this constraint.
122    pub matches: Vec<DetailedConstraintMatch<'a, Sc>>,
123    /// Whether this is a hard constraint.
124    pub is_hard: bool,
125}
126
127impl<'a, Sc: Score> ConstraintAnalysis<'a, Sc> {
128    /// Creates a new constraint analysis.
129    pub fn new(
130        constraint_ref: &'a ConstraintRef,
131        weight_multiplier: u32,
132        score: Sc,
133        matches: Vec<DetailedConstraintMatch<'a, Sc>>,
134        is_hard: bool,
135    ) -> Self {
136        Self {
137            constraint_ref,
138            weight_multiplier,
139            score,
140            matches,
141            is_hard,
142        }
143    }
144
145    /// Returns the number of matches.
146    pub fn match_count(&self) -> usize {
147        self.matches.len()
148    }
149
150    /// Returns the constraint name.
151    pub fn name(&self) -> &str {
152        &self.constraint_ref.name
153    }
154}