From 4d32fb3aef555c716b5950ebca0163df8bda54ca Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 13 Nov 2026 17:02:03 +0100 Subject: [PATCH] fix(scoring): report matches for grouped and complemented constraints Grouped and complemented constraints scored correctly but listed no matches in constraint analysis, so nothing named the entities behind a group's cost. Two defects caused it: - seven of the eight grouped builders never gave their shared terminal an explainer, and SharedOperatorTerminal::get_matches returned nothing without one; - OperatorScorer::evaluate_detailed always returned an empty match list, so every terminal on a compiler-shared grouped node (what #[solverforge_constraints] emits whenever a grouped stream has several terminals) had no matches even where an explainer existed. The shared terminal now requires its rows to implement ExplainRow, which replaces the optional per-builder explainer (SharedOperatorBuilder:: with_explainer is removed) and lets matches come from the rows themselves: - each terminal reports one match per row whose coded weight is not zero, scored at its multiplier and justified by the row's contributors: a group's entities, a complement row's target plus its group, a defaulted complement key by its target alone; - match scores sum to the terminal's score, from a full evaluation before initialization and from the retained rows afterwards; match_count still counts every row. Grouped and complemented builders therefore require Clone + Debug entities, as every ungrouped constraint already did; the projected complement target gains Clone + Debug. OperatorScorerSet::score_for had no caller left and is removed. Closes #261 --- ...orge_constraints_projected_complemented.rs | 1 + crates/solverforge-scoring/WIREFRAME.md | 13 + crates/solverforge-scoring/public-api.txt | 4 +- .../constraint/relational/operator_scorer.rs | 12 +- .../relational/operator_scorer/matches.rs | 75 +++++ .../relational/operator_scorer/set.rs | 10 +- .../constraint/relational/shared_terminal.rs | 33 +- .../src/constraint/tests/cross_grouped.rs | 4 +- .../src/constraint/tests/grouped.rs | 2 +- .../src/constraint/tests/grouped_analysis.rs | 312 ++++++++++++++++++ .../src/constraint/tests/mod.rs | 1 + .../src/constraint/tests/projected.rs | 1 + .../constraint/tests/projected/analysis.rs | 122 +++++++ .../src/constraint/tests/projected/support.rs | 2 +- .../src/stream/complemented_stream.rs | 8 +- .../cross_bi_stream/complemented_grouped.rs | 6 +- .../src/stream/cross_bi_stream/grouped.rs | 4 +- .../src/stream/grouped_stream/joined.rs | 4 +- .../src/stream/grouped_stream/weighting.rs | 2 +- .../src/stream/joined_grouped_stream.rs | 6 - .../projected_stream/complemented_grouped.rs | 2 +- .../tests/group_by_joined.rs | 44 +++ .../tests/grouped_constraint_analysis.rs | 70 ++++ .../tests/grouped_constraint_analysis/mod.rs | 11 + .../grouped_constraint_analysis/nurse.rs | 9 + .../grouped_constraint_analysis/roster.rs | 65 ++++ .../grouped_constraint_analysis/shift.rs | 15 + docs/constraints.md | 8 + 28 files changed, 777 insertions(+), 69 deletions(-) create mode 100644 crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs create mode 100644 crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs create mode 100644 crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs create mode 100644 crates/solverforge/tests/grouped_constraint_analysis.rs create mode 100644 crates/solverforge/tests/grouped_constraint_analysis/mod.rs create mode 100644 crates/solverforge/tests/grouped_constraint_analysis/nurse.rs create mode 100644 crates/solverforge/tests/grouped_constraint_analysis/roster.rs create mode 100644 crates/solverforge/tests/grouped_constraint_analysis/shift.rs diff --git a/crates/solverforge-macros/tests/ui/pass/solverforge_constraints_projected_complemented.rs b/crates/solverforge-macros/tests/ui/pass/solverforge_constraints_projected_complemented.rs index 3638f587c..78eb189ab 100644 --- a/crates/solverforge-macros/tests/ui/pass/solverforge_constraints_projected_complemented.rs +++ b/crates/solverforge-macros/tests/ui/pass/solverforge_constraints_projected_complemented.rs @@ -5,6 +5,7 @@ struct Entry { delta: i64, } +#[derive(Clone, Debug)] struct Employee { id: usize, } diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index 4295ce020..cfc5b00dd 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -208,6 +208,7 @@ src/ │ │ ├── mod.rs — Module declarations and selected re-exports │ │ ├── operator_terminal.rs — OperatorTerminal over one generic operator │ │ ├── operator_scorer.rs — OperatorScorer, ScorerChain, and RowWeight/AdaptWeight adapters +│ │ ├── operator_scorer/matches.rs — per-terminal match listing for shared-terminal analysis │ │ ├── operator_scorer/set.rs — OperatorScorerSet, the scorer-set contract shared terminals score through │ │ ├── shared_terminal.rs — SharedOperatorTerminal/Builder and chained terminal sharing │ │ └── grouped_weights.rs — Group/direct-complement/optional-complement weight adapters @@ -716,6 +717,18 @@ terminals of one shared node. Weight adapters (`GroupAdapter`/`GroupWeight`, `RowWeight`, `AdaptWeight`) adapt each family's weight closure to the shared row. Sharing is compiler-owned; there are no runtime node caches. +A shared terminal requires its operator's rows to implement `ExplainRow`, so +every grouped and complemented builder's `named` requires `Clone + Debug` +entities (projected `Out` rows excepted: they justify nothing themselves). +Detailed analysis (`get_matches`, `ConstraintSet::evaluate_detailed[_weighted]`) +reports, for every terminal on the node, one match per row whose coded weight +is not zero, scored at the terminal's multiplier and justified by the row's +contributors: a group's contributing entities, a complement row's target plus +its group's contributors, a defaulted complement key by its target alone. The +match scores sum to the terminal's score; before initialization they come from +a full evaluation, afterwards from the retained rows. `match_count` still +counts every row. + **`SharedNodeId(pub usize)`** — Stable diagnostic identifier for one shared compiler node. diff --git a/crates/solverforge-scoring/public-api.txt b/crates/solverforge-scoring/public-api.txt index 85ff95a8d..b9bce8a8a 100644 --- a/crates/solverforge-scoring/public-api.txt +++ b/crates/solverforge-scoring/public-api.txt @@ -51,7 +51,6 @@ struct constraint::relational::OptionalComplementAdapter: pub struct OptionalCom struct constraint::relational::ScorerChain: pub struct ScorerChain(/* private fields */); struct constraint::relational::SharedOperatorBuilder: pub struct SharedOperatorBuilder { /* private fields */ } constraint::relational::SharedOperatorBuilder: pub fn first(operator: O, adapter: A, impact: ImpactType, weight: W) -> Self - constraint::relational::SharedOperatorBuilder: pub fn with_explainer( self, explain: fn(&O, &S, RowHandle, &mut Vec), ) -> Self constraint::relational::SharedOperatorBuilder: pub fn first_with_hard( operator: O, adapter: A, impact: ImpactType, weight: W, hard: bool, ) -> Self constraint::relational::SharedOperatorBuilder: pub fn first_named( self, name: &str, ) -> SharedOperatorTerminal, Sc> constraint::relational::SharedOperatorBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal)>, Sc> @@ -485,7 +484,7 @@ trait constraint::relational::AdaptWeight: pub trait AdaptWeight constraint::relational::AdaptWeight: fn adapt(&self, weight: W) -> Self::RowWeight constraint::relational::AdaptWeight: fn is_hard(&self, weight: &W) -> bool -trait constraint::relational::OperatorScorerSet: pub trait OperatorScorerSet, Sc: Score>: Send + Sync { Show 15 methods // Required methods fn evaluate(&self, operator: &O, solution: &S) -> Sc; fn initialize(&mut self, operator: &O, solution: &S) -> Sc; fn apply_changes( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], ) -> (Sc, bool); fn constraint_count(&self) -> usize; fn metadata(&self) -> Vec>; fn evaluate_each<'a>( &'a self, operator: &O, solution: &S, ) -> Vec>; fn evaluate_detailed<'a>( &'a self, operator: &O, solution: &S, ) -> Vec>; fn reset(&mut self); fn weight_refs<'a>(&'a self, refs: &mut Vec<&'a ConstraintRef>); fn evaluate_weighted( &self, operator: &O, solution: &S, multipliers: &[u32], ) -> Sc; fn initialize_weighted( &mut self, operator: &O, solution: &S, multipliers: &[u32], ) -> Sc; fn apply_changes_weighted( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], multipliers: &[u32], ) -> (Sc, bool); fn evaluate_each_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec>; fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec>; // Provided method fn score_for(&self, _handle: RowHandle) -> Option { ... } } +trait constraint::relational::OperatorScorerSet: pub trait OperatorScorerSet, Sc: Score>: Send + Sync { Show 14 methods // Required methods fn evaluate(&self, operator: &O, solution: &S) -> Sc; fn initialize(&mut self, operator: &O, solution: &S) -> Sc; fn apply_changes( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], ) -> (Sc, bool); fn constraint_count(&self) -> usize; fn metadata(&self) -> Vec>; fn evaluate_each<'a>( &'a self, operator: &O, solution: &S, ) -> Vec>; fn evaluate_detailed<'a>( &'a self, operator: &O, solution: &S, ) -> Vec>; fn reset(&mut self); fn weight_refs<'a>(&'a self, refs: &mut Vec<&'a ConstraintRef>); fn evaluate_weighted( &self, operator: &O, solution: &S, multipliers: &[u32], ) -> Sc; fn initialize_weighted( &mut self, operator: &O, solution: &S, multipliers: &[u32], ) -> Sc; fn apply_changes_weighted( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], multipliers: &[u32], ) -> (Sc, bool); fn evaluate_each_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec>; fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec>; } constraint::relational::OperatorScorerSet: fn evaluate(&self, operator: &O, solution: &S) -> Sc constraint::relational::OperatorScorerSet: fn initialize(&mut self, operator: &O, solution: &S) -> Sc constraint::relational::OperatorScorerSet: fn apply_changes( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], ) -> (Sc, bool) @@ -500,7 +499,6 @@ trait constraint::relational::OperatorScorerSet: pub trait OperatorScorerSet (Sc, bool) constraint::relational::OperatorScorerSet: fn evaluate_each_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec> constraint::relational::OperatorScorerSet: fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec> - constraint::relational::OperatorScorerSet: fn score_for(&self, _handle: RowHandle) -> Option trait constraint::relational::RowWeight: pub trait RowWeight, Sc>: Send + Sync { // Required method fn score(&self, solution: &S, row: &O::View<'_>) -> Sc; } constraint::relational::RowWeight: fn score(&self, solution: &S, row: &O::View<'_>) -> Sc trait director::Director: pub trait Director: Send { Show 19 methods // Required methods fn working_solution(&self) -> &S; fn working_solution_mut(&mut self) -> &mut S; fn calculate_score(&mut self) -> S::Score; fn solution_descriptor(&self) -> &SolutionDescriptor; fn clone_working_solution(&self) -> S; fn before_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn after_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn entity_count(&self, descriptor_index: usize) -> Option; fn total_entity_count(&self) -> Option; fn constraint_metadata(&self) -> Vec>; // Provided methods fn fresh_score(&self) -> Option { ... } fn set_score_assertion(&mut self, enabled: bool) { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState { ... } fn restore_score_state(&mut self, state: DirectorScoreState) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option where Self: Sized { ... } fn fork_for_solution(&self, _solution: S) -> Option where Self: Sized { ... } } diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs b/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs index 50963d03e..803814486 100644 --- a/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs +++ b/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs @@ -13,9 +13,10 @@ use crate::api::{ scale_contribution, scale_contribution_parts, ConstraintMetadata, ConstraintResult, }, }; -use crate::stream::relational::operator::Operator; +use crate::stream::relational::operator::{ExplainRow, Operator}; use crate::stream::relational::{HandleMap, RowHandle}; +mod matches; mod set; pub use set::OperatorScorerSet; @@ -156,6 +157,7 @@ impl OperatorScorerSet for OperatorScorer where S: Send + Sync + 'static, O: Operator + Send + Sync, + for<'r> O::View<'r>: ExplainRow, W: RowWeight, Sc: Score, { @@ -214,10 +216,6 @@ where 1 } - fn score_for(&self, handle: RowHandle) -> Option { - self.scores.get(handle).map(|weight| self.signed(*weight)) - } - fn metadata(&self) -> Vec> { vec![ConstraintMetadata::new(&self.constraint_ref, self.hard)] } @@ -241,7 +239,7 @@ where &self.constraint_ref, 1, self.evaluate(operator, solution), - Vec::new(), + self.matches(operator, solution, 1), self.hard, )] } @@ -303,7 +301,7 @@ where &self.constraint_ref, multipliers[0], self.evaluate_weighted(operator, solution, multipliers), - Vec::new(), + self.matches(operator, solution, multipliers[0]), self.hard, )] } diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs new file mode 100644 index 000000000..3d86a16d7 --- /dev/null +++ b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs @@ -0,0 +1,75 @@ +//! Match listing for one shared-terminal scorer: the rows constraint +//! analysis reports and counts. + +use solverforge_core::score::Score; + +use super::{OperatorScorer, RowWeight}; +use crate::api::analysis::{ConstraintJustification, DetailedConstraintMatch}; +use crate::api::constraint_set::scale_contribution; +use crate::stream::relational::operator::{ExplainRow, Operator}; + +impl OperatorScorer { + /// Visits each row of `operator` with its signed score: the retained + /// rows and scores once the operator holds rows, a full evaluation of + /// `solution` before that, like [`OperatorScorerSet::evaluate`]. + fn visit_scored( + &self, + operator: &O, + solution: &S, + mut visit: impl FnMut(&O::View<'_>, Sc), + ) where + S: 'static, + O: Operator, + W: RowWeight, + { + let handles = operator.handles(); + if handles.is_empty() { + operator.visit_all(solution, &mut |row| { + visit(&row, self.signed(self.weight.score(solution, &row))); + }); + } else { + for handle in handles { + let row = operator + .resolve(solution, handle) + .expect("live shared terminal row"); + let weight = match self.scores.get(handle) { + Some(weight) => *weight, + None => self.weight.score(solution, &row), + }; + visit(&row, self.signed(weight)); + } + } + } + + /// One match per row of `operator` whose coded weight is not zero, + /// scored at `multiplier` and justified by the entities the row was built + /// from; the match scores sum to the terminal's total. + pub(in crate::constraint::relational) fn matches<'a, S, O>( + &'a self, + operator: &O, + solution: &S, + multiplier: u32, + ) -> Vec> + where + S: 'static, + O: Operator, + W: RowWeight, + for<'r> O::View<'r>: ExplainRow, + { + let mut matches = Vec::new(); + self.visit_scored(operator, solution, |row, score| { + if score == Sc::zero() { + return; + } + let score = scale_contribution(score, multiplier); + let mut entities = Vec::new(); + row.explain(&mut entities); + matches.push(DetailedConstraintMatch::new( + &self.constraint_ref, + score, + ConstraintJustification::new(entities), + )); + }); + matches + } +} diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_scorer/set.rs b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/set.rs index 309c29b50..e5c286f28 100644 --- a/crates/solverforge-scoring/src/constraint/relational/operator_scorer/set.rs +++ b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/set.rs @@ -42,7 +42,9 @@ pub trait OperatorScorerSet, Sc: Score>: Send + Sync fn metadata(&self) -> Vec>; /// Each terminal's total, in authored order. fn evaluate_each<'a>(&'a self, operator: &O, solution: &S) -> Vec>; - /// Each terminal's total with its matches, in authored order. + /// Each terminal's total with its matches, in authored order: one match + /// per row whose coded weight is not zero, justified by the entities the + /// row was built from, so a terminal's match scores sum to its total. fn evaluate_detailed<'a>( &'a self, operator: &O, @@ -50,12 +52,6 @@ pub trait OperatorScorerSet, Sc: Score>: Send + Sync ) -> Vec>; /// Drops every retained row score. fn reset(&mut self); - /// The retained signed score of row `handle` for a single-terminal set; - /// `None` when the set does not score rows on its own. - fn score_for(&self, _handle: RowHandle) -> Option { - None - } - /// Appends each terminal's constraint reference, one weight slot each. fn weight_refs<'a>(&'a self, refs: &mut Vec<&'a ConstraintRef>); /// [`evaluate`](Self::evaluate) with each terminal scaled by its multiplier. diff --git a/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs b/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs index 012835e73..3859b895e 100644 --- a/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs +++ b/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs @@ -6,15 +6,14 @@ use solverforge_core::{score::Score, ConstraintRef, ImpactType}; use super::operator_scorer::{ AdaptWeight, OperatorScorer, OperatorScorerSet, RowWeight, ScorerChain, }; -use crate::api::analysis::EntityRef; use crate::api::{ - analysis::{ConstraintAnalysis, ConstraintJustification, DetailedConstraintMatch}, + analysis::{ConstraintAnalysis, DetailedConstraintMatch}, constraint_set::{ ConstraintMetadata, ConstraintResult, ConstraintSet, IncrementalConstraint, SingleConstraint, }, }; -use crate::stream::relational::operator::GroupedOperator; +use crate::stream::relational::operator::{ExplainRow, GroupedOperator}; use crate::stream::relational::RowHandle; /// Scoring terminal that owns one operator tree and scores it for several named @@ -34,7 +33,6 @@ pub struct SharedOperatorTerminal { inserted: Vec, update_count: usize, changed_key_count: usize, - explain: Option)>, marker: PhantomData (S, Sc)>, } @@ -62,7 +60,6 @@ impl SharedOperatorBuilder { inserted: Vec::new(), update_count: 0, changed_key_count: 0, - explain: None, marker: PhantomData, }, impact, @@ -71,13 +68,6 @@ impl SharedOperatorBuilder { } } - /// Sets the function that lists the entities behind a row, used by - /// `get_matches`. Without it, `get_matches` returns no matches. - pub fn with_explainer(mut self, explain: fn(&O, &S, RowHandle, &mut Vec)) -> Self { - self.terminal.explain = Some(explain); - self - } - /// Like [`first`](Self::first), with explicit hardness. pub fn first_with_hard( operator: O, @@ -121,7 +111,6 @@ where inserted: self.terminal.inserted, update_count: self.terminal.update_count, changed_key_count: self.terminal.changed_key_count, - explain: self.terminal.explain, marker: PhantomData, } } @@ -291,7 +280,6 @@ where inserted: self.terminal.inserted, update_count: self.terminal.update_count, changed_key_count: self.terminal.changed_key_count, - explain: self.terminal.explain, marker: PhantomData, } } @@ -434,6 +422,7 @@ impl IncrementalConstraint where S: Send + Sync + 'static, O: GroupedOperator + Send + Sync, + for<'r> O::View<'r>: ExplainRow, A: Send + Sync, W: RowWeight, Sc: Score, @@ -472,20 +461,6 @@ where self.scorers.hard } fn get_matches<'a>(&'a self, solution: &S) -> Vec> { - let Some(explain) = self.explain else { - return Vec::new(); - }; - let mut matches = Vec::new(); - let handles = self.operator.handles(); - for handle in handles { - let mut entities = Vec::new(); - explain(&self.operator, solution, handle, &mut entities); - matches.push(DetailedConstraintMatch::new( - &self.scorers.constraint_ref, - self.scorers.score_for(handle).unwrap_or_else(Sc::zero), - ConstraintJustification::new(entities), - )); - } - matches + self.scorers.matches(&self.operator, solution, 1) } } diff --git a/crates/solverforge-scoring/src/constraint/tests/cross_grouped.rs b/crates/solverforge-scoring/src/constraint/tests/cross_grouped.rs index b7ff75cb1..5b142fba7 100644 --- a/crates/solverforge-scoring/src/constraint/tests/cross_grouped.rs +++ b/crates/solverforge-scoring/src/constraint/tests/cross_grouped.rs @@ -5,12 +5,12 @@ use crate::stream::joiner::equal_bi; use crate::stream::ConstraintFactory; use solverforge_core::score::SoftScore; -#[derive(Clone)] +#[derive(Clone, Debug)] struct Employee { id: usize, } -#[derive(Clone)] +#[derive(Clone, Debug)] struct Shift { employee_id: Option, } diff --git a/crates/solverforge-scoring/src/constraint/tests/grouped.rs b/crates/solverforge-scoring/src/constraint/tests/grouped.rs index 3e12d4d25..2ce70c7d9 100644 --- a/crates/solverforge-scoring/src/constraint/tests/grouped.rs +++ b/crates/solverforge-scoring/src/constraint/tests/grouped.rs @@ -10,7 +10,7 @@ use crate::stream::collection_extract::{source, ChangeSource}; use crate::stream::collector::{collect_vec, count, CollectedVec}; use crate::stream::ConstraintFactory; -#[derive(Clone)] +#[derive(Clone, Debug)] struct GroupedShift { employee_id: usize, } diff --git a/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs b/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs new file mode 100644 index 000000000..54edb2562 --- /dev/null +++ b/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs @@ -0,0 +1,312 @@ +/* Constraint analysis of grouped and complemented constraints. + +Every grouped and complemented builder must report one match per group whose +weight is not zero, justified by the group's contributors (and, for a +complement, by its target entity; a defaulted key by its target alone), and +the match scores must sum to the constraint's score: before initialization, +after it, and across mutations. Shared grouped nodes report matches for every +terminal they carry, scaled by each terminal's weight multiplier. + +Roster: nurse 0 works shifts 0 and 1, nurse 1 works shift 2, shift 3 is +unassigned, nurse 2 works nothing. +*/ + +use solverforge_core::score::SoftScore; + +use crate::api::analysis::DetailedConstraintMatch; +use crate::api::constraint_set::{ConstraintSet, IncrementalConstraint}; +use crate::stream::collection_extract::{source, ChangeSource}; +use crate::stream::collector::{count, sum}; +use crate::stream::joiner::equal_bi; +use crate::stream::ConstraintFactory; + +const UNASSIGNED: usize = usize::MAX; + +#[derive(Clone, Debug)] +struct Nurse { + id: usize, +} + +#[derive(Clone, Debug)] +struct Shift { + // Read only through `Debug`: it tells the shifts apart in justifications. + #[allow(dead_code)] + id: usize, + nurse: Option, +} + +#[derive(Clone)] +struct Roster { + shifts: Vec, + nurses: Vec, +} + +fn shifts(roster: &Roster) -> &[Shift] { + roster.shifts.as_slice() +} + +fn nurses(roster: &Roster) -> &[Nurse] { + roster.nurses.as_slice() +} + +fn roster() -> Roster { + Roster { + shifts: vec![ + Shift { + id: 0, + nurse: Some(0), + }, + Shift { + id: 1, + nurse: Some(0), + }, + Shift { + id: 2, + nurse: Some(1), + }, + Shift { id: 3, nurse: None }, + ], + nurses: vec![Nurse { id: 0 }, Nurse { id: 1 }, Nurse { id: 2 }], + } +} + +fn factory() -> ConstraintFactory { + ConstraintFactory::::new() +} + +fn shift_source() -> impl crate::stream::collection_extract::CollectionExtract +{ + source( + shifts as fn(&Roster) -> &[Shift], + ChangeSource::Descriptor(0), + ) +} + +fn nurse_source() -> impl crate::stream::collection_extract::CollectionExtract +{ + source( + nurses as fn(&Roster) -> &[Nurse], + ChangeSource::Descriptor(1), + ) +} + +fn nurse_key(shift: &Shift) -> usize { + shift.nurse.unwrap_or(UNASSIGNED) +} + +/// Each match as (score, displayed justification entities), sorted. +fn summary(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> Vec<(i64, Vec)> { + let mut rows = matches + .iter() + .map(|detailed| { + ( + detailed.score.score(), + detailed + .justification + .entities + .iter() + .map(|entity| entity.display.clone()) + .collect::>(), + ) + }) + .collect::>(); + rows.sort(); + rows +} + +fn match_sum(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> SoftScore { + matches + .iter() + .fold(SoftScore::of(0), |total, detailed| total + detailed.score) +} + +fn shift(id: usize, nurse: Option) -> String { + format!("{:?}", Shift { id, nurse }) +} + +fn nurse(id: usize) -> String { + format!("{:?}", Nurse { id }) +} + +/// Matches agree with the score before initialization, after it, after a +/// retraction and after the re-insertion, and are the expected rows. +fn assert_lifecycle(mut constraint: C, expected: Vec<(i64, Vec)>) +where + C: IncrementalConstraint, +{ + let mut plan = roster(); + let before = constraint.get_matches(&plan); + assert_eq!(match_sum(&before), constraint.evaluate(&plan)); + assert_eq!(summary(&before), expected, "before initialization"); + drop(before); + + let total = constraint.initialize(&plan); + let after = constraint.get_matches(&plan); + assert_eq!(match_sum(&after), total); + assert_eq!(summary(&after), expected, "after initialization"); + drop(after); + + // Unassign shift 1: nurse 0 drops to one shift. + let retracted = constraint.on_retract(&plan, 1, 0); + plan.shifts[1].nurse = None; + let inserted = constraint.on_insert(&plan, 1, 0); + let moved = constraint.get_matches(&plan); + assert_eq!(match_sum(&moved), total + retracted + inserted); + assert_eq!(match_sum(&moved), constraint.evaluate(&plan)); + drop(moved); + + constraint.on_retract(&plan, 1, 0); + plan.shifts[1].nurse = Some(0); + constraint.on_insert(&plan, 1, 0); + let restored = constraint.get_matches(&plan); + assert_eq!(match_sum(&restored), total); + assert_eq!(summary(&restored), expected, "after restoring"); +} + +#[test] +fn grouped_constraint_reports_each_costly_group_with_its_contributors() { + let constraint = factory() + .for_each(shift_source()) + .group_by(nurse_key, count()) + .penalize(|_nurse: &usize, shifts: &usize| SoftScore::of(shifts.saturating_sub(1) as i64)) + .named("Shifts per nurse beyond one"); + assert_lifecycle( + constraint, + vec![(-1, vec![shift(0, Some(0)), shift(1, Some(0))])], + ); +} + +#[test] +fn grouped_join_constraint_reports_the_group_and_the_joined_entity() { + let constraint = factory() + .for_each(shift_source()) + .group_by(nurse_key, count()) + .join((nurse_source(), |nurse: &Nurse| nurse.id)) + .penalize(|_id: &usize, shifts: &usize, _nurse: &Nurse| { + SoftScore::of(shifts.saturating_sub(1) as i64) + }) + .named("Shifts per known nurse beyond one"); + assert_lifecycle( + constraint, + vec![(-1, vec![shift(0, Some(0)), shift(1, Some(0)), nurse(0)])], + ); +} + +#[test] +fn complemented_constraint_justifies_defaulted_keys_by_their_target() { + let constraint = factory() + .for_each(shift_source()) + .group_by(nurse_key, count()) + .complement(nurse_source(), |nurse: &Nurse| nurse.id, |_nurse| 0usize) + .penalize(|_id: &usize, shifts: &usize| SoftScore::of(2 - *shifts as i64)) + .named("Distance from two shifts"); + // nurse 0: 2 shifts -> 0 (no match); nurse 1: 1 -> -1; nurse 2: default 0 -> -2. + assert_lifecycle( + constraint, + vec![ + (-2, vec![nurse(2)]), + (-1, vec![nurse(1), shift(2, Some(1))]), + ], + ); +} + +fn cross_join() -> impl Fn(&Shift) -> Option + Send + Sync + Clone { + |shift: &Shift| shift.nurse +} + +#[test] +fn cross_grouped_constraint_reports_every_contributing_pair() { + let constraint = factory() + .for_each(shift_source()) + .join(( + nurse_source(), + equal_bi(cross_join(), |nurse: &Nurse| Some(nurse.id)), + )) + .group_by( + |_shift: &Shift, nurse: &Nurse| nurse.id, + sum(|(_shift, _nurse): (&Shift, &Nurse)| 1i64), + ) + .penalize(|_id: &usize, shifts: &i64| SoftScore::of(shifts - 1)) + .named("Joined shifts per nurse beyond one"); + assert_lifecycle( + constraint, + vec![( + -1, + vec![shift(0, Some(0)), nurse(0), shift(1, Some(0)), nurse(0)], + )], + ); +} + +#[test] +fn cross_complemented_grouped_constraint_justifies_defaulted_keys_by_their_target() { + let constraint = factory() + .for_each(shift_source()) + .join(( + nurse_source(), + equal_bi(cross_join(), |nurse: &Nurse| Some(nurse.id)), + )) + .group_by( + |_shift: &Shift, nurse: &Nurse| nurse.id, + sum(|(_shift, _nurse): (&Shift, &Nurse)| 1i64), + ) + .complement(nurse_source(), |nurse: &Nurse| nurse.id, |_nurse| 0i64) + .penalize(|_id: &usize, shifts: &i64| SoftScore::of(2 - shifts)) + .named("Joined distance from two shifts"); + assert_lifecycle( + constraint, + vec![ + (-2, vec![nurse(2)]), + (-1, vec![nurse(1), shift(2, Some(1)), nurse(1)]), + ], + ); +} + +#[test] +fn shared_grouped_terminals_each_report_their_matches_under_their_multiplier() { + let mut constraints = factory() + .for_each(shift_source()) + .group_by(nurse_key, count()) + .penalize(|_nurse: &usize, shifts: &usize| SoftScore::of(shifts.saturating_sub(1) as i64)) + .named("Shifts beyond one") + .reward(|nurse: &usize, shifts: &usize| { + SoftScore::of(if *nurse == UNASSIGNED { + 0 + } else { + *shifts as i64 + }) + }) + .named("Assigned shifts"); + let plan = roster(); + constraints.initialize_all(&plan); + + let analyses = constraints.evaluate_detailed(&plan); + assert_eq!(analyses.len(), 2); + for analysis in &analyses { + assert_eq!(match_sum(&analysis.matches), analysis.score); + } + assert_eq!( + summary(&analyses[0].matches), + vec![(-1, vec![shift(0, Some(0)), shift(1, Some(0))])] + ); + assert_eq!( + summary(&analyses[1].matches), + vec![ + (1, vec![shift(2, Some(1))]), + (2, vec![shift(0, Some(0)), shift(1, Some(0))]), + ] + ); + + let weighted = constraints.evaluate_detailed_weighted(&plan, &[3, 2]); + assert_eq!(weighted[0].score, SoftScore::of(-3)); + assert_eq!(weighted[1].score, SoftScore::of(6)); + for analysis in &weighted { + assert_eq!(match_sum(&analysis.matches), analysis.score); + } + let disabled = constraints.evaluate_detailed_weighted(&plan, &[0, 2]); + assert_eq!(disabled[0].score, SoftScore::of(0)); + assert_eq!( + summary(&disabled[0].matches), + vec![(0, vec![shift(0, Some(0)), shift(1, Some(0))])], + "a disabled terminal still names its groups, at score zero" + ); +} diff --git a/crates/solverforge-scoring/src/constraint/tests/mod.rs b/crates/solverforge-scoring/src/constraint/tests/mod.rs index fed9f8868..6a1ed4654 100644 --- a/crates/solverforge-scoring/src/constraint/tests/mod.rs +++ b/crates/solverforge-scoring/src/constraint/tests/mod.rs @@ -7,6 +7,7 @@ mod cross_tri_stream_chain; mod exists; mod flattened_bi; mod grouped; +mod grouped_analysis; mod overflow; mod projected; mod relational; diff --git a/crates/solverforge-scoring/src/constraint/tests/projected.rs b/crates/solverforge-scoring/src/constraint/tests/projected.rs index f5b1517f4..e2de2c4b1 100644 --- a/crates/solverforge-scoring/src/constraint/tests/projected.rs +++ b/crates/solverforge-scoring/src/constraint/tests/projected.rs @@ -1,3 +1,4 @@ +mod analysis; mod emit_bound; mod joined; mod localization; diff --git a/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs b/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs new file mode 100644 index 000000000..edf7f2adb --- /dev/null +++ b/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs @@ -0,0 +1,122 @@ +/* Constraint analysis of projected grouped and complemented constraints. + +Projected rows carry no entity of their own, so a projected group justifies +itself with nothing beyond its complement target; what must hold is one match +per group whose weight is not zero, with match scores summing to the +constraint's score before and after initialization. +*/ + +use super::support::*; +use crate::api::analysis::DetailedConstraintMatch; + +fn plan() -> Plan { + Plan { + work: vec![ + Work { + bucket: 0, + demand: 5, + enabled: true, + }, + Work { + bucket: 1, + demand: 2, + enabled: true, + }, + Work { + bucket: 1, + demand: -2, + enabled: true, + }, + ], + capacity: vec![ + Capacity { + bucket: 0, + capacity: 0, + }, + Capacity { + bucket: 2, + capacity: 0, + }, + ], + } +} + +fn scores(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> Vec<(i64, usize)> { + let mut rows = matches + .iter() + .map(|detailed| { + ( + detailed.score.score(), + detailed.justification.entities.len(), + ) + }) + .collect::>(); + rows.sort(); + rows +} + +fn match_sum(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> SoftScore { + matches + .iter() + .fold(SoftScore::of(0), |total, detailed| total + detailed.score) +} + +fn assert_matches(mut constraint: C, expected: Vec<(i64, usize)>) +where + C: IncrementalConstraint, +{ + let plan = plan(); + let before = constraint.get_matches(&plan); + assert_eq!(match_sum(&before), constraint.evaluate(&plan)); + assert_eq!(scores(&before), expected, "before initialization"); + drop(before); + let total = constraint.initialize(&plan); + let after = constraint.get_matches(&plan); + assert_eq!(match_sum(&after), total); + assert_eq!(scores(&after), expected, "after initialization"); +} + +#[test] +fn projected_grouped_constraint_reports_each_costly_group() { + let constraint = ConstraintFactory::::new() + .for_each(source( + work as fn(&Plan) -> &[Work], + ChangeSource::Descriptor(0), + )) + .project(WorkEntryProjection) + .group_by( + |entry: &Entry| entry.bucket, + sum(|entry: &Entry| entry.delta), + ) + .penalize(|_bucket: &usize, demand: &i64| SoftScore::of(*demand)) + .named("projected demand"); + // bucket 0: 5; bucket 1: 2 - 2 = 0, no match. + assert_matches(constraint, vec![(-5, 0)]); +} + +#[test] +fn projected_complemented_constraint_justifies_each_group_by_its_target() { + let constraint = ConstraintFactory::::new() + .for_each(source( + work as fn(&Plan) -> &[Work], + ChangeSource::Descriptor(0), + )) + .project(WorkEntryProjection) + .group_by( + |entry: &Entry| entry.bucket, + sum(|entry: &Entry| entry.delta), + ) + .complement( + source( + capacity as fn(&Plan) -> &[Capacity], + ChangeSource::Descriptor(1), + ), + |capacity: &Capacity| capacity.bucket, + |_capacity: &Capacity| 3i64, + ) + .penalize(|_bucket: &usize, demand: &i64| SoftScore::of(*demand)) + .named("projected demand per capacity"); + // capacity bucket 0: real 5; capacity bucket 2: default 3. Bucket 1 has + // no capacity row, so it is no complemented row at all. + assert_matches(constraint, vec![(-5, 1), (-3, 1)]); +} diff --git a/crates/solverforge-scoring/src/constraint/tests/projected/support.rs b/crates/solverforge-scoring/src/constraint/tests/projected/support.rs index 12b926217..d24870597 100644 --- a/crates/solverforge-scoring/src/constraint/tests/projected/support.rs +++ b/crates/solverforge-scoring/src/constraint/tests/projected/support.rs @@ -20,7 +20,7 @@ pub(super) struct Work { pub(super) enabled: bool, } -#[derive(Clone)] +#[derive(Clone, Debug)] pub(super) struct Capacity { pub(super) bucket: usize, pub(super) capacity: i64, diff --git a/crates/solverforge-scoring/src/stream/complemented_stream.rs b/crates/solverforge-scoring/src/stream/complemented_stream.rs index 225c0f5bb..df15bb535 100644 --- a/crates/solverforge-scoring/src/stream/complemented_stream.rs +++ b/crates/solverforge-scoring/src/stream/complemented_stream.rs @@ -52,12 +52,12 @@ use crate::constraint::relational::{ /// use solverforge_scoring::stream::collector::count; /// use solverforge_scoring::stream::ConstraintFactory; /// -/// #[derive(Clone, Hash, PartialEq, Eq)] +/// #[derive(Clone, Debug, Hash, PartialEq, Eq)] /// struct Employee { /// id: usize, /// } /// -/// #[derive(Clone, Hash, PartialEq, Eq)] +/// #[derive(Clone, Debug, Hash, PartialEq, Eq)] /// struct Shift { /// employee_id: usize, /// } @@ -303,8 +303,8 @@ impl ComplementedConstraintBuilder where S: Send + Sync + 'static, - A: Clone + Send + Sync + 'static, - B: Clone + Send + Sync + 'static, + A: Clone + std::fmt::Debug + Send + Sync + 'static, + B: Clone + std::fmt::Debug + Send + Sync + 'static, K: Clone + Eq + Hash + Send + Sync + 'static, EA: CollectionExtract + 'static, EB: CollectionExtract + 'static, diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs index b61db955e..18db7929f 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs @@ -316,9 +316,9 @@ impl > where S: Send + Sync + 'static, - A: Clone + Send + Sync + 'static, - B: Clone + Send + Sync + 'static, - T: Clone + Send + Sync + 'static, + A: Clone + std::fmt::Debug + Send + Sync + 'static, + B: Clone + std::fmt::Debug + Send + Sync + 'static, + T: Clone + std::fmt::Debug + Send + Sync + 'static, JK: Eq + Hash + Clone + Send + Sync + 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, EA: CollectionExtract + Send + Sync + 'static, diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs index 75912a69d..600aadb32 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs @@ -233,8 +233,8 @@ impl GroupedBuilder where S: Send + Sync + 'static, - A: Clone + Send + Sync + 'static, - B: Clone + Send + Sync + 'static, + A: Clone + std::fmt::Debug + Send + Sync + 'static, + B: Clone + std::fmt::Debug + Send + Sync + 'static, JK: Eq + Hash + Clone + Send + Sync + 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, EA: CollectionExtract + Send + Sync + 'static, diff --git a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs index bf86a3a51..71568ff3c 100644 --- a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs +++ b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs @@ -217,8 +217,8 @@ impl GroupedJoinedBuilder where S: Send + Sync + 'static, - A: Clone + Send + Sync + 'static, - B: Clone + Send + Sync + 'static, + A: Clone + std::fmt::Debug + Send + Sync + 'static, + B: Clone + std::fmt::Debug + Send + Sync + 'static, K: Clone + Eq + Hash + Send + Sync + 'static, E: CollectionExtract + 'static, EB: CollectionExtract + 'static, diff --git a/crates/solverforge-scoring/src/stream/grouped_stream/weighting.rs b/crates/solverforge-scoring/src/stream/grouped_stream/weighting.rs index a71226224..3d90b543d 100644 --- a/crates/solverforge-scoring/src/stream/grouped_stream/weighting.rs +++ b/crates/solverforge-scoring/src/stream/grouped_stream/weighting.rs @@ -42,7 +42,7 @@ impl GroupedConstraintBuilder where S: Send + Sync + 'static, - A: Clone + Send + Sync + 'static, + A: Clone + std::fmt::Debug + Send + Sync + 'static, K: Clone + Eq + Hash + Send + Sync + 'static, E: CollectionExtract + 'static, Fi: UniFilter + 'static, diff --git a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs index ffed4aee6..e33ff8d1d 100644 --- a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs +++ b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs @@ -122,12 +122,6 @@ where self.weight, self.hard, ) - .with_explainer(|operator, solution, handle, entities| { - let row = operator - .resolve(solution, handle) - .expect("live grouped row"); - row.explain(entities); - }) .first_named(name) } } diff --git a/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs b/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs index 3ac8683eb..da39ada0e 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs @@ -195,7 +195,7 @@ impl where S: Send + Sync + 'static, Out: Send + Sync + 'static, - B: Send + Sync + 'static, + B: Clone + std::fmt::Debug + Send + Sync + 'static, K: Clone + Eq + Hash + Send + Sync + 'static, Src: Source + 'static, EB: CollectionExtract + 'static, diff --git a/crates/solverforge-scoring/tests/group_by_joined.rs b/crates/solverforge-scoring/tests/group_by_joined.rs index 183fc9c09..8c3025973 100644 --- a/crates/solverforge-scoring/tests/group_by_joined.rs +++ b/crates/solverforge-scoring/tests/group_by_joined.rs @@ -320,3 +320,47 @@ fn joined_group_by_preserves_reject_all_filters_at_every_arity() { assert_empty(quad); assert_empty(penta); } + +#[test] +fn self_join_tri_groups_justify_their_matches_with_every_combination() { + let mut constraint = solverforge_scoring::stream::TriConstraintStream::< + Model, + Item, + u32, + _, + _, + _, + SoftScore, + >::new_self_join( + source(a as fn(&Model) -> &[Item], ChangeSource::Descriptor(0)), + |_: &Model, i: &Item, _: usize| i.key, + ) + .group_by(|i: &Item, _: &Item, _: &Item| i.key, count()) + .penalize(|_: &u32, n: &usize| SoftScore::of(*n as i64 - 1)) + .named("self tri groups beyond one"); + let model = Model { + a: vec![ + Item { key: 1, value: 1 }, + Item { key: 1, value: 2 }, + Item { key: 1, value: 3 }, + Item { key: 2, value: 4 }, + Item { key: 2, value: 5 }, + Item { key: 2, value: 6 }, + ], + b: vec![], + c: vec![], + d: vec![], + e: vec![], + }; + // Each key has exactly one combination of three: weight 0, no match. + assert!(constraint.get_matches(&model).is_empty()); + let mut model = model; + model.a.push(Item { key: 1, value: 7 }); + let total = constraint.initialize(&model); + let matches = constraint.get_matches(&model); + // Key 1 now has four combinations of three items. + assert_eq!(total, SoftScore::of(-3)); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].score, total); + assert_eq!(matches[0].justification.entities.len(), 4 * 3); +} diff --git a/crates/solverforge/tests/grouped_constraint_analysis.rs b/crates/solverforge/tests/grouped_constraint_analysis.rs new file mode 100644 index 000000000..1b295367f --- /dev/null +++ b/crates/solverforge/tests/grouped_constraint_analysis.rs @@ -0,0 +1,70 @@ +//! Grouped constraints report their matches in constraint analysis: one +//! match per group with a non-zero weight, justified by the group's shifts, +//! for every terminal on a compiler-shared grouped node. + +#[path = "grouped_constraint_analysis/mod.rs"] +mod domain; + +pub use domain::{define_constraints, Nurse, Roster, Shift}; + +use solverforge::prelude::*; +use solverforge::ScoreDirector; + +fn roster() -> Roster { + Roster { + nurses: vec![Nurse { id: 0 }, Nurse { id: 1 }], + shifts: vec![ + Shift { + id: 0, + day: 0, + nurse_idx: Some(0), + }, + Shift { + id: 1, + day: 0, + nurse_idx: Some(0), + }, + Shift { + id: 2, + day: 1, + nurse_idx: Some(1), + }, + ], + score: None, + } +} + +#[test] +fn grouped_constraints_justify_their_score_like_the_equivalent_join() { + let mut director = ScoreDirector::new(roster(), define_constraints()); + assert_eq!(director.calculate_score(), HardSoftScore::of(-2, 3)); + + let analyses = director.constraint_analyses(); + assert_eq!(analyses.len(), 3); + for analysis in &analyses { + let total = analysis + .matches + .iter() + .fold(HardSoftScore::ZERO, |sum, detailed| sum + detailed.score); + assert_eq!(total, analysis.score, "{}", analysis.constraint_ref.name); + } + + let join = &analyses[0]; + let grouped = &analyses[1]; + assert_eq!(join.matches.len(), 1); + assert_eq!(grouped.score, HardSoftScore::of_hard(-1)); + assert_eq!(grouped.matches.len(), 1, "only nurse 0 costs score"); + let shifts = grouped.matches[0] + .justification + .entities + .iter() + .map(|entity| entity.display.clone()) + .collect::>(); + assert_eq!(shifts.len(), 2); + assert!(shifts + .iter() + .all(|shift| shift.contains("nurse_idx: Some(0)"))); + + let assigned = &analyses[2]; + assert_eq!(assigned.matches.len(), 2, "both nurses earn a reward"); +} diff --git a/crates/solverforge/tests/grouped_constraint_analysis/mod.rs b/crates/solverforge/tests/grouped_constraint_analysis/mod.rs new file mode 100644 index 000000000..4685e62cc --- /dev/null +++ b/crates/solverforge/tests/grouped_constraint_analysis/mod.rs @@ -0,0 +1,11 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/grouped_constraint_analysis"; + + mod nurse; + mod roster; + mod shift; + + pub use nurse::Nurse; + pub use roster::{define_constraints, Roster}; + pub use shift::Shift; +} diff --git a/crates/solverforge/tests/grouped_constraint_analysis/nurse.rs b/crates/solverforge/tests/grouped_constraint_analysis/nurse.rs new file mode 100644 index 000000000..dbf52817c --- /dev/null +++ b/crates/solverforge/tests/grouped_constraint_analysis/nurse.rs @@ -0,0 +1,9 @@ +use solverforge::prelude::*; + +/// A nurse shifts can be assigned to. +#[problem_fact] +pub struct Nurse { + /// Stable nurse id. + #[planning_id] + pub id: usize, +} diff --git a/crates/solverforge/tests/grouped_constraint_analysis/roster.rs b/crates/solverforge/tests/grouped_constraint_analysis/roster.rs new file mode 100644 index 000000000..2fa208583 --- /dev/null +++ b/crates/solverforge/tests/grouped_constraint_analysis/roster.rs @@ -0,0 +1,65 @@ +use solverforge::prelude::*; +use solverforge::stream::collector::count; +use solverforge::stream::ConstraintFactory; + +use crate::{Nurse, Shift}; + +/// Nurses and shifts for the grouped analysis tests. +#[planning_solution(constraints = "define_constraints")] +pub struct Roster { + /// Nurses shifts can be assigned to. + #[problem_fact_collection] + pub nurses: Vec, + + /// Shifts the solver assigns. + #[planning_entity_collection] + pub shifts: Vec, + + /// The roster's score. + #[planning_score] + pub score: Option, +} + +/// The same rule written as a join and as a group, plus a second terminal +/// on the shared grouped node. +#[solverforge_constraints] +pub fn define_constraints() -> impl ConstraintSet { + let same_day_join = ConstraintFactory::::new() + .for_each(Roster::shifts()) + .join(( + ConstraintFactory::::new().for_each(Roster::shifts()), + |left: &Shift, right: &Shift| { + left.id < right.id + && left.day == right.day + && left.nurse_idx.is_some() + && left.nurse_idx == right.nurse_idx + }, + )) + .penalize(HardSoftScore::ONE_HARD) + .named("Two shifts on one day (join)"); + + let per_nurse = ConstraintFactory::::new() + .for_each(Roster::shifts()) + .group_by( + |shift: &Shift| shift.nurse_idx.unwrap_or(usize::MAX), + count(), + ); + + ( + same_day_join, + per_nurse + .penalize(|nurse: &usize, shifts: &usize| { + HardSoftScore::of_hard(if *nurse == usize::MAX { + 0 + } else { + shifts.saturating_sub(1) as i64 + }) + }) + .named("Shifts per nurse beyond one (group_by)"), + per_nurse + .reward(|nurse: &usize, shifts: &usize| { + HardSoftScore::of_soft(if *nurse == usize::MAX { 0 } else { *shifts as i64 }) + }) + .named("Assigned shifts (group_by)"), + ) +} diff --git a/crates/solverforge/tests/grouped_constraint_analysis/shift.rs b/crates/solverforge/tests/grouped_constraint_analysis/shift.rs new file mode 100644 index 000000000..55aa75ac7 --- /dev/null +++ b/crates/solverforge/tests/grouped_constraint_analysis/shift.rs @@ -0,0 +1,15 @@ +use solverforge::prelude::*; + +/// A shift on one day. +#[planning_entity] +pub struct Shift { + /// Stable shift id. + #[planning_id] + pub id: usize, + /// Day of the shift. + pub day: usize, + + /// Assigned nurse. + #[planning_variable(value_range_provider = "nurses")] + pub nurse_idx: Option, +} diff --git a/docs/constraints.md b/docs/constraints.md index 3d2482575..1cc4cbc21 100644 --- a/docs/constraints.md +++ b/docs/constraints.md @@ -220,6 +220,14 @@ Each `ConstraintAnalysis` reports the weighted `score` and the constraint's satisfied one. For analysis of a running job, see [Running solves](running-solves.md). +`ScoreDirector::constraint_analyses()` also lists each constraint's matches +with the entities behind them. A grouped or complemented constraint reports one +match per group whose weight is not zero, justified by the entities in the +group (a complemented key without a group is justified by its target entity), +and the match scores add up to the constraint's score. Grouped and complemented +constraints therefore need entities that implement `Clone` and `Debug`, like +every other constraint. + ## Runtime constraint weights Mark one `ConstraintWeights` field with `#[constraint_weights]` to scale named