Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ struct Entry {
delta: i64,
}

#[derive(Clone, Debug)]
struct Employee {
id: usize,
}
Expand Down
13 changes: 13 additions & 0 deletions crates/solverforge-scoring/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ src/
│ │ ├── mod.rs — Module declarations and selected re-exports
│ │ ├── operator_terminal.rs — OperatorTerminal<S,O,W,Sc> 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
Expand Down Expand Up @@ -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.

Expand Down
4 changes: 1 addition & 3 deletions crates/solverforge-scoring/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ struct constraint::relational::OptionalComplementAdapter: pub struct OptionalCom
struct constraint::relational::ScorerChain: pub struct ScorerChain<T>(/* private fields */);
struct constraint::relational::SharedOperatorBuilder: pub struct SharedOperatorBuilder<S, O, A, Scorers, W, Sc> { /* 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<EntityRef>), ) -> 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<S, O, A, OperatorScorer<A::RowWeight, Sc>, Sc>
constraint::relational::SharedOperatorBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal<S, O, A, ScorerChain<(Scorers, OperatorScorer<A::RowWeight, Sc>)>, Sc>
Expand Down Expand Up @@ -485,7 +484,7 @@ trait constraint::relational::AdaptWeight: pub trait AdaptWeight<S: 'static, O:
constraint::relational::AdaptWeight: type RowWeight: RowWeight<S, O, Sc>
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<S: 'static, O: Operator<S>, 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<ConstraintMetadata<'_>>; fn evaluate_each<'a>( &'a self, operator: &O, solution: &S, ) -> Vec<ConstraintResult<'a, Sc>>; fn evaluate_detailed<'a>( &'a self, operator: &O, solution: &S, ) -> Vec<ConstraintAnalysis<'a, Sc>>; 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<ConstraintResult<'a, Sc>>; fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec<ConstraintAnalysis<'a, Sc>>; // Provided method fn score_for(&self, _handle: RowHandle) -> Option<Sc> { ... } }
trait constraint::relational::OperatorScorerSet: pub trait OperatorScorerSet<S: 'static, O: Operator<S>, 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<ConstraintMetadata<'_>>; fn evaluate_each<'a>( &'a self, operator: &O, solution: &S, ) -> Vec<ConstraintResult<'a, Sc>>; fn evaluate_detailed<'a>( &'a self, operator: &O, solution: &S, ) -> Vec<ConstraintAnalysis<'a, Sc>>; 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<ConstraintResult<'a, Sc>>; fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec<ConstraintAnalysis<'a, Sc>>; }
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)
Expand All @@ -500,7 +499,6 @@ trait constraint::relational::OperatorScorerSet: pub trait OperatorScorerSet<S:
constraint::relational::OperatorScorerSet: fn apply_changes_weighted( &mut self, operator: &O, solution: &S, removed: &[RowHandle], inserted: &[RowHandle], multipliers: &[u32], ) -> (Sc, bool)
constraint::relational::OperatorScorerSet: fn evaluate_each_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec<ConstraintResult<'a, Sc>>
constraint::relational::OperatorScorerSet: fn evaluate_detailed_weighted<'a>( &'a self, operator: &O, solution: &S, multipliers: &[u32], ) -> Vec<ConstraintAnalysis<'a, Sc>>
constraint::relational::OperatorScorerSet: fn score_for(&self, _handle: RowHandle) -> Option<Sc>
trait constraint::relational::RowWeight: pub trait RowWeight<S: 'static, O: Operator<S>, 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<S: PlanningSolution>: 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<usize>; fn total_entity_count(&self) -> Option<usize>; fn constraint_metadata(&self) -> Vec<ConstraintMetadata<'_>>; // Provided methods fn fresh_score(&self) -> Option<S::Score> { ... } fn set_score_assertion(&mut self, enabled: bool) { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option<bool> { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState<S::Score> { ... } fn restore_score_state(&mut self, state: DirectorScoreState<S::Score>) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option<Self> where Self: Sized { ... } fn fork_for_solution(&self, _solution: S) -> Option<Self> where Self: Sized { ... } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -156,6 +157,7 @@ impl<S, O, W, Sc> OperatorScorerSet<S, O, Sc> for OperatorScorer<W, Sc>
where
S: Send + Sync + 'static,
O: Operator<S> + Send + Sync,
for<'r> O::View<'r>: ExplainRow,
W: RowWeight<S, O, Sc>,
Sc: Score,
{
Expand Down Expand Up @@ -214,10 +216,6 @@ where
1
}

fn score_for(&self, handle: RowHandle) -> Option<Sc> {
self.scores.get(handle).map(|weight| self.signed(*weight))
}

fn metadata(&self) -> Vec<ConstraintMetadata<'_>> {
vec![ConstraintMetadata::new(&self.constraint_ref, self.hard)]
}
Expand All @@ -241,7 +239,7 @@ where
&self.constraint_ref,
1,
self.evaluate(operator, solution),
Vec::new(),
self.matches(operator, solution, 1),
self.hard,
)]
}
Expand Down Expand Up @@ -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,
)]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<W, Sc: Score> OperatorScorer<W, Sc> {
/// 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<S, O>(
&self,
operator: &O,
solution: &S,
mut visit: impl FnMut(&O::View<'_>, Sc),
) where
S: 'static,
O: Operator<S>,
W: RowWeight<S, O, Sc>,
{
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<DetailedConstraintMatch<'a, Sc>>
where
S: 'static,
O: Operator<S>,
W: RowWeight<S, O, Sc>,
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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,16 @@ pub trait OperatorScorerSet<S: 'static, O: Operator<S>, Sc: Score>: Send + Sync
fn metadata(&self) -> Vec<ConstraintMetadata<'_>>;
/// Each terminal's total, in authored order.
fn evaluate_each<'a>(&'a self, operator: &O, solution: &S) -> Vec<ConstraintResult<'a, Sc>>;
/// 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,
solution: &S,
) -> Vec<ConstraintAnalysis<'a, Sc>>;
/// 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<Sc> {
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -34,7 +33,6 @@ pub struct SharedOperatorTerminal<S, O, A, Scorers, Sc> {
inserted: Vec<RowHandle>,
update_count: usize,
changed_key_count: usize,
explain: Option<fn(&O, &S, RowHandle, &mut Vec<EntityRef>)>,
marker: PhantomData<fn() -> (S, Sc)>,
}

Expand Down Expand Up @@ -62,7 +60,6 @@ impl<S, O, A, W, Sc> SharedOperatorBuilder<S, O, A, (), W, Sc> {
inserted: Vec::new(),
update_count: 0,
changed_key_count: 0,
explain: None,
marker: PhantomData,
},
impact,
Expand All @@ -71,13 +68,6 @@ impl<S, O, A, W, Sc> SharedOperatorBuilder<S, O, A, (), W, Sc> {
}
}

/// 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<EntityRef>)) -> Self {
self.terminal.explain = Some(explain);
self
}

/// Like [`first`](Self::first), with explicit hardness.
pub fn first_with_hard(
operator: O,
Expand Down Expand Up @@ -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,
}
}
Expand Down Expand Up @@ -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,
}
}
Expand Down Expand Up @@ -434,6 +422,7 @@ impl<S, O, A, W, Sc> IncrementalConstraint<S, Sc>
where
S: Send + Sync + 'static,
O: GroupedOperator<S> + Send + Sync,
for<'r> O::View<'r>: ExplainRow,
A: Send + Sync,
W: RowWeight<S, O, Sc>,
Sc: Score,
Expand Down Expand Up @@ -472,20 +461,6 @@ where
self.scorers.hard
}
fn get_matches<'a>(&'a self, solution: &S) -> Vec<DetailedConstraintMatch<'a, Sc>> {
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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-scoring/src/constraint/tests/grouped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
Loading
Loading