diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index 2b5a5b03..ad1e3c23 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -243,8 +243,8 @@ src/ │ ├── traits.rs — Director trait │ ├── score_director.rs — Re-exports ScoreDirector pieces │ │ ├── score_director/incremental.rs — ScoreDirector (zero-erasure incremental) -│ │ ├── score_director/constructors.rs — ScoreDirector constructors, weighted constructors, into_weight_mode -│ │ ├── score_director/descriptor.rs — DirectorDescriptor, ReplicaDescriptor +│ │ ├── score_director/constructors.rs — ScoreDirector constructors, weighted constructors, replica-forking constructors, into_weight_mode +│ │ ├── score_director/descriptor.rs — DirectorDescriptor (owned or borrowed SolutionDescriptor) │ │ ├── score_director/list_shadows.rs — Retract/insert of list-shadowed element rows around owner shadow updates │ │ ├── score_director/weight_mode.rs — WeightMode (sealed), UnweightedMode, WeightedMode, requires_weighted_mode, static per-mode scoring dispatch │ │ ├── score_director/analysis.rs — ScoreDirector constraint_results/constraint_analyses/constraint_match_totals @@ -304,6 +304,7 @@ src/ │ ├── projected_stream/bi.rs — stream::projected::Bi and terminal builder │ ├── projected_stream/directed_bi.rs — stream::projected::DirectedBi and terminal builder for directed projected self-joins │ ├── projected_stream/join_target.rs — ProjectedJoinTarget dispatch for symmetric and directed projected self-joins +│ ├── projected_stream/row_closures.rs — Filter and key closures over projected rows, generic only over what they capture │ ├── projected_stream/grouped.rs — stream::projected::Grouped, reward, complement, and terminal builder │ ├── projected_stream/complemented_grouped.rs — stream::projected::ComplementedGrouped and builder │ ├── projected_stream/source.rs — Projection, projected row coordinates, Source trait @@ -314,6 +315,7 @@ src/ │ ├── collection_extract.rs — CollectionExtract trait, hidden source metadata and FilteredExtract membership adapter, source() constructor │ ├── unassigned.rs — UnassignedEntity and the `.unassigned()` stream method │ ├── weighting_support.rs — ConstraintWeight, FixedWeight, HardWeight, and dynamic closure-weight adapters +│ ├── closures.rs — Filter, key and weight closures built in functions generic only over what they capture, so constraint types do not repeat upstream stream types │ ├── join_target.rs — JoinTarget/ToViewPlan dispatch for self-join, keyed cross-join, comparison, overlap, composed, and predicate cross-join │ ├── key_extract.rs — KeyExtract trait, EntityKeyAdapter struct │ ├── arity_stream_macros/ @@ -374,7 +376,7 @@ pub use api::constraint_set::{ pub use api::node_sharing::{SharedNodeDiagnostics, SharedNodeId, SharedNodeOperation}; // Score Directors -pub use director::score_director::{DirectorDescriptor, ReplicaDescriptor, ScoreDirector}; +pub use director::score_director::{DirectorDescriptor, ScoreDirector}; pub use director::{Director, DirectorScoreState, SolvableSolution}; // Analysis @@ -622,22 +624,20 @@ Stock collectors include `count()`, `sum()`, `load_balance()`, - Returns borrowed constraint metadata views from the monomorphized `ConstraintSet` on demand. - `simple(solution, descriptor, entity_counter)` — creates `ScoreDirector` with empty constraint set - `simple_zero(solution)` — creates `ScoreDirector` with empty descriptor and zero entity counter -- `with_descriptor(solution, constraints, descriptor: Desc, entity_counter)` — `Desc` is an owned `SolutionDescriptor` or a `ReplicaDescriptor`; `new()`, `simple()` and `simple_zero()` build owned-descriptor directors. -- `Director::fork_replica` forks only directors holding a `ReplicaDescriptor`, in the same weight mode: the replica clones the working solution, builds its constraint set from that clone with the recorded constructor, initializes it, and shares the same borrowed descriptor. Owned-descriptor directors return `None`. -- `Director::fork_for_solution` forks the same way over a given solution instead of a clone of the working solution, and leaves the incremental state uninitialized so the first score calculation, on the thread that solves it, initializes it. Owned-descriptor directors return `None`. -- `reset()` discards incremental state after an external rewrite of the working solution. Directors holding a `ReplicaDescriptor` rebuild their constraint set from the current working solution with the recorded constructor, so solution-derived constraint plans follow fact and entity changes; owned-descriptor directors reset their existing set. +- `with_descriptor(solution, constraints, descriptor: Desc, entity_counter)` — `Desc` is an owned `SolutionDescriptor` or a borrowed `&SolutionDescriptor`; `new()`, `simple()` and `simple_zero()` build owned-descriptor directors. +- `with_replicas(solution, constraints, constraint_builder: fn(&S) -> C, descriptor: &'d SolutionDescriptor, entity_counter)` (plus `with_replicas_weighted` and `with_replicas_in_mode`) — a director that records `constraint_builder` and borrows the descriptor, so it can fork replicas. The constructor is a field of the director rather than part of its descriptor type, so `C` appears once in the director's type and debug-info type names stay proportional to the constraint set. +- `Director::fork_replica` forks only directors built with `with_replicas`, in the same weight mode: the replica clones the working solution, builds its constraint set from that clone with the recorded constructor, initializes it, and shares the same borrowed descriptor. Other directors return `None`. +- `Director::fork_for_solution` forks the same way over a given solution instead of a clone of the working solution, and leaves the incremental state uninitialized so the first score calculation, on the thread that solves it, initializes it. Other directors return `None`. +- `reset()` discards incremental state after an external rewrite of the working solution. Directors built with `with_replicas` rebuild their constraint set from the current working solution with the recorded constructor, so solution-derived constraint plans follow fact and entity changes; other directors reset their existing set. - Implements `Director` **`WeightMode`** (sealed trait) — `const WEIGHTED: bool`; implemented only by `UnweightedMode` (zero-sized, no weight storage) and `WeightedMode` (bound per-slot multipliers). **`requires_weighted_mode(solution: &S) -> bool`** — `S::HAS_CONSTRAINT_WEIGHTS` and some multiplier of `solution.constraint_weights()` differs from `1`. -**`DirectorDescriptor`** (trait) — how a `ScoreDirector` holds its descriptor. +**`DirectorDescriptor`** (trait) — how a `ScoreDirector` holds its descriptor; implemented for an owned `SolutionDescriptor` and a borrowed `&SolutionDescriptor`. - `solution_descriptor(&self) -> &SolutionDescriptor` -- `replica(&self) -> Option<(Self, fn(&S) -> C)>` — the handle and constraint-set constructor for an evaluator replica; `None` for an owned `SolutionDescriptor`. - -**`ReplicaDescriptor<'d, S, C>`** — `Copy`; a borrowed `&'d SolutionDescriptor` plus the constraint-set constructor `fn(&S) -> C`. -- `new(descriptor: &'d SolutionDescriptor, constraints: fn(&S) -> C)` +- `share(&self) -> Option` — the same descriptor for an evaluator replica: `Some` for a borrowed descriptor, `None` for an owned one. ### Constraint Types @@ -1004,6 +1004,8 @@ The entire pipeline from stream builder to constraint evaluation is fully monomo All closures are stored as concrete generic type parameters. No `Box`, no `Arc`. The constraint types carry the full closure types through their generics. +A closure written inside a generic method has a type naming every generic parameter of that method, and debug info prints that type in full. Combinators therefore never build the closures they store inline: `stream/closures.rs`, `projected_stream/row_closures.rs` and the `narrow*` functions inside the n-ary stream macros build them in functions generic only over what the closure captures, so a filter chain or weight names its own parts once instead of repeating the whole upstream stream type at every stage. + ### Incremental Scoring Protocol Score directors use a retract-then-insert protocol: diff --git a/crates/solverforge-scoring/public-api.txt b/crates/solverforge-scoring/public-api.txt index ddceb978..85ff95a8 100644 --- a/crates/solverforge-scoring/public-api.txt +++ b/crates/solverforge-scoring/public-api.txt @@ -65,9 +65,7 @@ struct constraint::relational::SharedOperatorTerminal: pub struct SharedOperator constraint::relational::SharedOperatorTerminal: pub fn update_count(&self) -> usize constraint::relational::SharedOperatorTerminal: pub fn changed_key_count(&self) -> usize struct director::DirectorScoreState: pub struct DirectorScoreState { pub solution_score: Option, pub committed_score: Option, pub initialized: bool, } -struct director::score_director::ReplicaDescriptor: pub struct ReplicaDescriptor<'d, S, C> { /* private fields */ } - director::score_director::ReplicaDescriptor: pub fn new(descriptor: &'d SolutionDescriptor, constraints: fn(&S) -> C) -> Self -struct director::score_director::ScoreDirector: pub struct ScoreDirector where S: PlanningSolution, C: ConstraintSet, Desc: DirectorDescriptor, M: WeightMode,{ /* private fields */ } +struct director::score_director::ScoreDirector: pub struct ScoreDirector where S: PlanningSolution, C: ConstraintSet, Desc: DirectorDescriptor, M: WeightMode,{ /* private fields */ } director::score_director::ScoreDirector: pub fn constraint_results(&self) -> Vec> director::score_director::ScoreDirector: pub fn constraint_analyses(&self) -> Vec> director::score_director::ScoreDirector: pub fn constraint_match_totals(&self) -> Vec<(String, u32, S::Score, usize)> @@ -77,6 +75,9 @@ struct director::score_director::ScoreDirector: pub struct ScoreDirector usize, ) -> Self director::score_director::ScoreDirector: pub fn with_descriptor_in_mode( solution: S, constraints: C, solution_descriptor: Desc, entity_counter: fn(&S, usize) -> usize, ) -> Self director::score_director::ScoreDirector: pub fn into_weight_mode(self) -> ScoreDirector + director::score_director::ScoreDirector: pub fn with_replicas_in_mode( solution: S, constraints: C, constraint_builder: fn(&S) -> C, solution_descriptor: &'d SolutionDescriptor, entity_counter: fn(&S, usize) -> usize, ) -> Self + director::score_director::ScoreDirector: pub fn with_replicas( solution: S, constraints: C, constraint_builder: fn(&S) -> C, solution_descriptor: &'d SolutionDescriptor, entity_counter: fn(&S, usize) -> usize, ) -> Self + director::score_director::ScoreDirector: pub fn with_replicas_weighted( solution: S, constraints: C, constraint_builder: fn(&S) -> C, solution_descriptor: &'d SolutionDescriptor, entity_counter: fn(&S, usize) -> usize, ) -> Self director::score_director::ScoreDirector: pub fn simple( solution: S, descriptor: SolutionDescriptor, entity_counter: fn(&S, usize) -> usize, ) -> Self director::score_director::ScoreDirector: pub fn simple_zero(solution: S) -> Self director::score_director::ScoreDirector: pub fn working_solution(&self) -> &S @@ -522,9 +523,9 @@ trait director::Director: pub trait Director: Send { Show 1 director::Director: fn reset(&mut self) director::Director: fn fork_replica(&self) -> Option where Self: Sized, director::Director: fn fork_for_solution(&self, _solution: S) -> Option where Self: Sized, -trait director::score_director::DirectorDescriptor: pub trait DirectorDescriptor { // Required methods fn solution_descriptor(&self) -> &SolutionDescriptor; fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized; } +trait director::score_director::DirectorDescriptor: pub trait DirectorDescriptor { // Required methods fn solution_descriptor(&self) -> &SolutionDescriptor; fn share(&self) -> Option where Self: Sized; } director::score_director::DirectorDescriptor: fn solution_descriptor(&self) -> &SolutionDescriptor - director::score_director::DirectorDescriptor: fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized, + director::score_director::DirectorDescriptor: fn share(&self) -> Option where Self: Sized, trait director::score_director::WeightMode: pub trait WeightMode: Mode + Send + Sync + Sized + 'static { const WEIGHTED: bool; } director::score_director::WeightMode: const WEIGHTED: bool trait director::shadow_aware::SolvableSolution: pub trait SolvableSolution: PlanningSolution { // Required methods fn descriptor() -> SolutionDescriptor; fn entity_count(solution: &Self, descriptor_index: usize) -> usize; } diff --git a/crates/solverforge-scoring/src/constraint/tests/weights/modes.rs b/crates/solverforge-scoring/src/constraint/tests/weights/modes.rs index 28cd7fd1..a1e02c45 100644 --- a/crates/solverforge-scoring/src/constraint/tests/weights/modes.rs +++ b/crates/solverforge-scoring/src/constraint/tests/weights/modes.rs @@ -4,7 +4,7 @@ use std::any::TypeId; use super::support::*; use crate::api::constraint_set::IncrementalConstraint; -use crate::director::score_director::{requires_weighted_mode, ReplicaDescriptor, UnweightedMode}; +use crate::director::score_director::{requires_weighted_mode, UnweightedMode}; use solverforge_core::domain::SolutionDescriptor; fn unassigned() -> impl IncrementalConstraint { @@ -63,10 +63,11 @@ fn fork_replica_keeps_the_weighted_mode() { let descriptor = SolutionDescriptor::new("", TypeId::of::<()>()); let build = (|_: &Plan| (unassigned(),)) as fn(&Plan) -> _; let solution = unassigned_weighted(5); - let director = ScoreDirector::with_descriptor_weighted( + let director = ScoreDirector::with_replicas_weighted( solution.clone(), build(&solution), - ReplicaDescriptor::new(&descriptor, build), + build, + &descriptor, |_, _| 0, ); diff --git a/crates/solverforge-scoring/src/director/score_director.rs b/crates/solverforge-scoring/src/director/score_director.rs index 1dbf13b0..25a2b933 100644 --- a/crates/solverforge-scoring/src/director/score_director.rs +++ b/crates/solverforge-scoring/src/director/score_director.rs @@ -11,6 +11,6 @@ mod incremental; mod list_shadows; mod weight_mode; -pub use descriptor::{DirectorDescriptor, ReplicaDescriptor}; +pub use descriptor::DirectorDescriptor; pub use incremental::ScoreDirector; pub use weight_mode::{requires_weighted_mode, UnweightedMode, WeightMode, WeightedMode}; diff --git a/crates/solverforge-scoring/src/director/score_director/adapters.rs b/crates/solverforge-scoring/src/director/score_director/adapters.rs index 140898f4..1e91cb89 100644 --- a/crates/solverforge-scoring/src/director/score_director/adapters.rs +++ b/crates/solverforge-scoring/src/director/score_director/adapters.rs @@ -12,7 +12,7 @@ where S: PlanningSolution + std::fmt::Debug, S::Score: std::fmt::Debug, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, M: WeightMode, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -23,7 +23,7 @@ where .field("weighted", &M::WEIGHTED) .field( "forks_replicas", - &self.solution_descriptor.replica().is_some(), + &(self.constraint_builder.is_some() && self.solution_descriptor.share().is_some()), ) .finish() } @@ -34,7 +34,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet + Send, - Desc: DirectorDescriptor + Send, + Desc: DirectorDescriptor + Send, M: WeightMode, { fn working_solution(&self) -> &S { diff --git a/crates/solverforge-scoring/src/director/score_director/analysis.rs b/crates/solverforge-scoring/src/director/score_director/analysis.rs index d743de5c..5ecab9ef 100644 --- a/crates/solverforge-scoring/src/director/score_director/analysis.rs +++ b/crates/solverforge-scoring/src/director/score_director/analysis.rs @@ -18,7 +18,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, M: WeightMode, { /// Evaluates every constraint of the working solution under the director's weight mode. diff --git a/crates/solverforge-scoring/src/director/score_director/constructors.rs b/crates/solverforge-scoring/src/director/score_director/constructors.rs index 28299af9..90992a21 100644 --- a/crates/solverforge-scoring/src/director/score_director/constructors.rs +++ b/crates/solverforge-scoring/src/director/score_director/constructors.rs @@ -37,7 +37,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, { /// Creates a new zero-erasure unweighted score director with a solution /// descriptor; see `with_descriptor_in_mode`. @@ -75,7 +75,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, { /// Creates a weighted score director with a solution descriptor: the /// weighted counterpart of `with_descriptor`. @@ -94,7 +94,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, M: WeightMode, { /// Creates a new zero-erasure score director in weight mode `M` with a @@ -108,7 +108,8 @@ where /// * `solution` - The initial solution /// * `constraints` - Tuple of monomorphized constraints (e.g., `(C1, C2, C3)`) /// * `solution_descriptor` - Metadata for solver infrastructure: an owned - /// `SolutionDescriptor`, or a `ReplicaDescriptor` to fork evaluator replicas + /// `SolutionDescriptor` or a borrowed one; `with_replicas_in_mode` builds + /// a director that forks evaluator replicas /// * `entity_counter` - Function returning entity count for descriptor index pub fn with_descriptor_in_mode( solution: S, @@ -127,6 +128,7 @@ where list_shadow_rows: ListShadowRows::default(), weight_mode, solution_descriptor, + constraint_builder: None, entity_counter, _phantom: PhantomData, } @@ -148,12 +150,95 @@ where list_shadow_rows: self.list_shadow_rows, weight_mode, solution_descriptor: self.solution_descriptor, + constraint_builder: self.constraint_builder, entity_counter: self.entity_counter, _phantom: PhantomData, } } } +impl<'d, S, C, M> ScoreDirector +where + S: PlanningSolution, + S::Score: Score, + C: ConstraintSet, + M: WeightMode, +{ + /// Creates a score director in weight mode `M` that forks evaluator + /// replicas: each replica shares `solution_descriptor` and gets a + /// constraint set built by `constraint_builder` from its own working + /// solution. `constraints` is the set for `solution`, normally + /// `constraint_builder(&solution)`. Reset rebuilds the set the same way, + /// because constraint sets may compile solution-derived plans that a plain + /// reset would keep stale. + pub fn with_replicas_in_mode( + solution: S, + constraints: C, + constraint_builder: fn(&S) -> C, + solution_descriptor: &'d SolutionDescriptor, + entity_counter: fn(&S, usize) -> usize, + ) -> Self { + let mut director = Self::with_descriptor_in_mode( + solution, + constraints, + solution_descriptor, + entity_counter, + ); + director.constraint_builder = Some(constraint_builder); + director + } +} + +impl<'d, S, C> ScoreDirector +where + S: PlanningSolution, + S::Score: Score, + C: ConstraintSet, +{ + /// Creates an unweighted score director that forks evaluator replicas; + /// see `with_replicas_in_mode`. + pub fn with_replicas( + solution: S, + constraints: C, + constraint_builder: fn(&S) -> C, + solution_descriptor: &'d SolutionDescriptor, + entity_counter: fn(&S, usize) -> usize, + ) -> Self { + Self::with_replicas_in_mode( + solution, + constraints, + constraint_builder, + solution_descriptor, + entity_counter, + ) + } +} + +impl<'d, S, C> ScoreDirector +where + S: PlanningSolution, + S::Score: Score, + C: ConstraintSet, +{ + /// Creates a weighted score director that forks evaluator replicas; see + /// `with_replicas_in_mode`. + pub fn with_replicas_weighted( + solution: S, + constraints: C, + constraint_builder: fn(&S) -> C, + solution_descriptor: &'d SolutionDescriptor, + entity_counter: fn(&S, usize) -> usize, + ) -> Self { + Self::with_replicas_in_mode( + solution, + constraints, + constraint_builder, + solution_descriptor, + entity_counter, + ) + } +} + impl ScoreDirector where S: PlanningSolution, diff --git a/crates/solverforge-scoring/src/director/score_director/descriptor.rs b/crates/solverforge-scoring/src/director/score_director/descriptor.rs index 894bec11..961234ea 100644 --- a/crates/solverforge-scoring/src/director/score_director/descriptor.rs +++ b/crates/solverforge-scoring/src/director/score_director/descriptor.rs @@ -1,71 +1,40 @@ -use std::marker::PhantomData; - use solverforge_core::domain::SolutionDescriptor; /// How a `ScoreDirector` holds its solution descriptor. /// -/// An owned `SolutionDescriptor` serves a single director. A -/// `ReplicaDescriptor` borrows the descriptor and carries the constraint-set -/// constructor, so the director can fork evaluator replicas that share the same +/// An owned `SolutionDescriptor` serves a single director. A borrowed +/// `&SolutionDescriptor` can be shared, so a director built with +/// `ScoreDirector::with_replicas` forks evaluator replicas that share the same /// descriptor without copying it. -pub trait DirectorDescriptor { +pub trait DirectorDescriptor { /// Returns the solution descriptor. fn solution_descriptor(&self) -> &SolutionDescriptor; - /// A handle for an evaluator replica plus the constructor that builds the - /// replica's constraint set from its own working solution. `None` when - /// this director cannot fork replicas. - fn replica(&self) -> Option<(Self, fn(&S) -> C)> + /// The same descriptor for an evaluator replica, or `None` when this + /// descriptor cannot be shared. + fn share(&self) -> Option where Self: Sized; } -impl DirectorDescriptor for SolutionDescriptor { +impl DirectorDescriptor for SolutionDescriptor { #[inline] fn solution_descriptor(&self) -> &SolutionDescriptor { self } - fn replica(&self) -> Option<(Self, fn(&S) -> C)> { + fn share(&self) -> Option { None } } -/// A borrowed solution descriptor plus the constraint-set constructor used for -/// the working solution and every evaluator replica. -pub struct ReplicaDescriptor<'d, S, C> { - descriptor: &'d SolutionDescriptor, - constraints: fn(&S) -> C, - _phantom: PhantomData (S, C)>, -} - -impl<'d, S, C> ReplicaDescriptor<'d, S, C> { - /// Borrows `descriptor` and records `constraints`, which builds the constraint - /// set for the working solution and for every replica. - pub fn new(descriptor: &'d SolutionDescriptor, constraints: fn(&S) -> C) -> Self { - Self { - descriptor, - constraints, - _phantom: PhantomData, - } - } -} - -impl Clone for ReplicaDescriptor<'_, S, C> { - fn clone(&self) -> Self { - *self - } -} - -impl Copy for ReplicaDescriptor<'_, S, C> {} - -impl DirectorDescriptor for ReplicaDescriptor<'_, S, C> { +impl DirectorDescriptor for &SolutionDescriptor { #[inline] fn solution_descriptor(&self) -> &SolutionDescriptor { - self.descriptor + self } - fn replica(&self) -> Option<(Self, fn(&S) -> C)> { - Some((*self, self.constraints)) + fn share(&self) -> Option { + Some(*self) } } diff --git a/crates/solverforge-scoring/src/director/score_director/incremental.rs b/crates/solverforge-scoring/src/director/score_director/incremental.rs index e7dc1b43..12650f2a 100644 --- a/crates/solverforge-scoring/src/director/score_director/incremental.rs +++ b/crates/solverforge-scoring/src/director/score_director/incremental.rs @@ -20,7 +20,7 @@ use crate::api::constraint_set::{ConstraintMetadata, ConstraintSet}; /// - `S`: The solution type (must implement `PlanningSolution`) /// - `C`: The constraint set type (tuple of monomorphized constraints) /// - `Desc`: How the solution descriptor is held; an owned `SolutionDescriptor` -/// by default, or a `ReplicaDescriptor` for directors that fork evaluator +/// by default, or a borrowed `&SolutionDescriptor` for directors that fork evaluator /// replicas /// - `M`: The runtime constraint weight mode, fixed for the director's lifetime: /// `UnweightedMode` by default (coded weights, no weight storage), or @@ -90,7 +90,7 @@ pub struct ScoreDirector where S: PlanningSolution, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, M: WeightMode, { pub(super) working_solution: S, @@ -103,6 +103,9 @@ where /// The weight mode and, for `WeightedMode`, its bound multipliers. pub(super) weight_mode: M, pub(super) solution_descriptor: Desc, + /// Builds the constraint set for a solution: set by `with_replicas`, used + /// to fork evaluator replicas and to rebuild the set on reset. + pub(super) constraint_builder: Option C>, /// Entity counter function. /// /// Returns the number of entities for the given descriptor index. @@ -117,7 +120,7 @@ where S: PlanningSolution, S::Score: Score, C: ConstraintSet, - Desc: DirectorDescriptor, + Desc: DirectorDescriptor, M: WeightMode, { /// Builds an initialized evaluator replica: a clone of the working @@ -137,14 +140,16 @@ where /// score assertion. Its incremental state is uninitialized; the first /// score calculation initializes it, on whichever thread runs it. pub(crate) fn fork_for_solution_impl(&self, solution: S) -> Option { - let (descriptor, constraints) = self.solution_descriptor.replica()?; - let replica_constraints = constraints(&solution); + let descriptor = self.solution_descriptor.share()?; + let constraint_builder = self.constraint_builder?; + let replica_constraints = constraint_builder(&solution); let mut director = Self::with_descriptor_in_mode( solution, replica_constraints, descriptor, self.entity_counter, ); + director.constraint_builder = Some(constraint_builder); director.score_assertion = self.score_assertion; Some(director) } @@ -245,8 +250,10 @@ where /// because constraint sets may compile solution-derived plans that a plain /// reset would keep stale. pub(crate) fn reset_impl(&mut self) { - match self.solution_descriptor.replica() { - Some((_, constraints)) => self.constraints = constraints(&self.working_solution), + match self.constraint_builder { + Some(constraint_builder) => { + self.constraints = constraint_builder(&self.working_solution) + } None => self.constraints.reset_all(), } self.list_shadow_rows.clear(); diff --git a/crates/solverforge-scoring/src/director/tests/score_director.rs b/crates/solverforge-scoring/src/director/tests/score_director.rs index 2987d058..199f80b7 100644 --- a/crates/solverforge-scoring/src/director/tests/score_director.rs +++ b/crates/solverforge-scoring/src/director/tests/score_director.rs @@ -2,7 +2,7 @@ use crate::api::constraint_set::IncrementalConstraint; use crate::constraint::incremental::IncrementalUniConstraint; -use crate::director::score_director::{ReplicaDescriptor, ScoreDirector}; +use crate::director::score_director::ScoreDirector; use crate::stream::collection_extract::{source, ChangeSource}; use crate::Director; use solverforge_core::domain::{PlanningSolution, SolutionDescriptor}; @@ -344,10 +344,11 @@ fn reset_rebuilds_replica_constraints_from_the_rewritten_solution() { score: None, }; let descriptor = test_descriptor(); - let mut director = ScoreDirector::with_descriptor( + let mut director = ScoreDirector::with_replicas( solution.clone(), solution_weighted_constraints(&solution), - ReplicaDescriptor::new(&descriptor, solution_weighted_constraints), + solution_weighted_constraints, + &descriptor, |_, _| 0, ); assert_eq!(director.calculate_score(), SoftScore::of(-2)); @@ -379,10 +380,11 @@ fn fork_replica_matches_score_and_stays_independent() { score: None, }; let descriptor = test_descriptor(); - let mut director = ScoreDirector::with_descriptor( + let mut director = ScoreDirector::with_replicas( solution.clone(), unassigned_constraints(&solution), - ReplicaDescriptor::new(&descriptor, unassigned_constraints), + unassigned_constraints, + &descriptor, |_, _| 0, ); let main_score = director.calculate_score(); @@ -416,10 +418,11 @@ fn fork_for_solution_scores_its_own_solution_independently() { score: None, }; let descriptor = test_descriptor(); - let mut director = ScoreDirector::with_descriptor( + let mut director = ScoreDirector::with_replicas( solution.clone(), unassigned_constraints(&solution), - ReplicaDescriptor::new(&descriptor, unassigned_constraints), + unassigned_constraints, + &descriptor, |_, _| 0, ); let main_score = director.calculate_score(); @@ -463,10 +466,11 @@ fn fork_of_uninitialized_director_initializes_the_replica() { score: None, }; let descriptor = test_descriptor(); - let director = ScoreDirector::with_descriptor( + let director = ScoreDirector::with_replicas( solution.clone(), unassigned_constraints(&solution), - ReplicaDescriptor::new(&descriptor, unassigned_constraints), + unassigned_constraints, + &descriptor, |_, _| 0, ); assert!(!director.is_initialized()); diff --git a/crates/solverforge-scoring/src/lib.rs b/crates/solverforge-scoring/src/lib.rs index cc17cd2d..393c2a2e 100644 --- a/crates/solverforge-scoring/src/lib.rs +++ b/crates/solverforge-scoring/src/lib.rs @@ -46,8 +46,8 @@ Score Directors */ pub use director::score_director::{ - requires_weighted_mode, DirectorDescriptor, ReplicaDescriptor, ScoreDirector, UnweightedMode, - WeightMode, WeightedMode, + requires_weighted_mode, DirectorDescriptor, ScoreDirector, UnweightedMode, WeightMode, + WeightedMode, }; pub use director::{Director, DirectorScoreState, SolvableSolution}; diff --git a/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs b/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs index a4ef32a8..48f707b7 100644 --- a/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs +++ b/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs @@ -162,14 +162,24 @@ macro_rules! impl_nary_arity_stream_common { key_extractor: self.key_extractor, filter: super::filter::$and_filter::new( self.filter, - super::filter::$fn_filter::new( - move |_s: &S, - $($entity: &A),+ - $(, $filter_idx: usize)*| { - let _ = ($($filter_idx),*); - predicate($($entity),+) - }, - ), + super::filter::$fn_filter::new({ + fn narrow( + predicate: P, + ) -> impl Fn( + &S, + $(repeat_tokens!($entity => &A)),+ + $(, repeat_tokens!($filter_idx => usize))* + ) -> bool + Send + Sync + where + P: Fn($(repeat_tokens!($entity => &A)),+) -> bool + Send + Sync, + { + move |_s: &S, $($entity: &A),+ $(, $filter_idx: usize)*| { + let _ = ($($filter_idx),*); + predicate($($entity),+) + } + } + narrow::(predicate) + }), ), _phantom: std::marker::PhantomData, } @@ -199,18 +209,33 @@ macro_rules! impl_nary_arity_stream_common { for<'i> crate::stream::relational::TupleCollector: super::collector::Collector<[crate::stream::relational::Leaf<'i, A>; $arity], Value = V, Result = R, Accumulator = Acc>, { - let filter = self.filter; - let input = crate::stream::relational::operator::SelfJoinNode::new( - crate::stream::relational::operator::CollectionNode::new(self.extractor, 0), self.key_extractor); - let filtered = crate::stream::relational::operator::FilterNode::new(input, + fn narrow_filter( + filter: F, + ) -> impl Fn(&S, &[crate::stream::relational::Leaf<'_, A>; $arity]) -> bool + Send + Sync + where + F: super::filter::$filter_trait A)),+>, + { move |s: &S, row: &[crate::stream::relational::Leaf<'_, A>; $arity]| { filter.test(s, $(row[repeat_nary_arity_position!($entity)].entity,)+ $(row[repeat_nary_arity_position!($filter_idx)].index),+) - }); - super::JoinedGroupedStream::new(filtered, + } + } + fn narrow_key( + key: GF, + ) -> impl Fn(&[crate::stream::relational::Leaf<'_, A>; $arity]) -> GK + Send + Sync + where + GF: Fn($(repeat_tokens!($entity => &A)),+) -> GK + Send + Sync, + { move |row: &[crate::stream::relational::Leaf<'_, A>; $arity]| { key($(row[repeat_nary_arity_position!($entity)].entity),+) - }, crate::stream::relational::TupleCollector::new(collector)) + } + } + let input = crate::stream::relational::operator::SelfJoinNode::new( + crate::stream::relational::operator::CollectionNode::new(self.extractor, 0), self.key_extractor); + let filtered = crate::stream::relational::operator::FilterNode::new(input, + narrow_filter::(self.filter)); + super::JoinedGroupedStream::new(filtered, + narrow_key::(key), crate::stream::relational::TupleCollector::new(collector)) } /// Penalizes each match by `weight`. @@ -240,8 +265,20 @@ macro_rules! impl_nary_arity_stream_common { let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |$($entity: &A),+| { - weight.score(($($entity),+)) + { + fn narrow( + weight: W, + ) -> impl Fn($(repeat_tokens!($entity => &A)),+) -> Sc + Send + Sync + where + Sc: solverforge_core::score::Score, + W: for<'w> super::weighting_support::ConstraintWeight< + ($(repeat_tokens!($entity => &'w A)),+), + Sc, + > + Send + Sync, + { + move |$($entity: &A),+| weight.score(($($entity),+)) + } + narrow::(weight) }, is_hard, ) @@ -274,8 +311,20 @@ macro_rules! impl_nary_arity_stream_common { let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |$($entity: &A),+| { - weight.score(($($entity),+)) + { + fn narrow( + weight: W, + ) -> impl Fn($(repeat_tokens!($entity => &A)),+) -> Sc + Send + Sync + where + Sc: solverforge_core::score::Score, + W: for<'w> super::weighting_support::ConstraintWeight< + ($(repeat_tokens!($entity => &'w A)),+), + Sc, + > + Send + Sync, + { + move |$($entity: &A),+| weight.score(($($entity),+)) + } + narrow::(weight) }, is_hard, ) @@ -348,15 +397,12 @@ macro_rules! impl_nary_arity_stream_common { + Sync, Sc, > { - let filter = self.filter; - let user_weight = self.weight; - let input = crate::stream::relational::operator::CollectionNode::new(self.extractor, 0); - let node = crate::stream::relational::operator::SelfJoinNode::new( - input, - self.key_extractor, - ); - let scored = crate::stream::relational::operator::FilterNode::new( - node, + fn narrow_filter( + filter: F, + ) -> impl for<'a, 'b> Fn(&'a S, &[crate::stream::relational::Leaf<'b, A>; $arity]) -> bool + Send + Sync + where + F: super::filter::$filter_trait A)),+>, + { move |s: &S, view: &[crate::stream::relational::Leaf<'_, A>; $arity]| { let arr = view; filter.test( @@ -364,15 +410,29 @@ macro_rules! impl_nary_arity_stream_common { $(&arr[repeat_nary_arity_position!($entity)].entity,)+ $(arr[repeat_nary_arity_position!($filter_idx)].index),+ ) - }, + } + } + fn narrow_weight( + user_weight: W, + ) -> impl for<'a, 'b> Fn(&'a S, &[crate::stream::relational::Leaf<'b, A>; $arity]) -> Sc + Send + Sync + where + W: Fn($(repeat_tokens!($entity => &A)),+) -> Sc + Send + Sync, + { + move |_s: &S, view: &[crate::stream::relational::Leaf<'_, A>; $arity]| { + let arr = view; + user_weight($(&arr[repeat_nary_arity_position!($entity)].entity),+) + } + } + let input = crate::stream::relational::operator::CollectionNode::new(self.extractor, 0); + let node = crate::stream::relational::operator::SelfJoinNode::new( + input, + self.key_extractor, + ); + let scored = crate::stream::relational::operator::FilterNode::new( + node, + narrow_filter::(self.filter), ); - let weight_fn = move | - _s: &S, - view: &[crate::stream::relational::Leaf<'_, A>; $arity], - | { - let arr = view; - user_weight($(&arr[repeat_nary_arity_position!($entity)].entity),+) - }; + let weight_fn = narrow_weight::(self.weight); crate::constraint::relational::OperatorTerminal::new( solverforge_core::ConstraintRef::new("", name), self.impact_type, diff --git a/crates/solverforge-scoring/src/stream/bi_stream.rs b/crates/solverforge-scoring/src/stream/bi_stream.rs index 501f2b8d..639b5f15 100644 --- a/crates/solverforge-scoring/src/stream/bi_stream.rs +++ b/crates/solverforge-scoring/src/stream/bi_stream.rs @@ -124,11 +124,8 @@ where J: Joiner + 'static, F: 'static, { - let filter = self.filter; let combined_filter = - move |s: &S, a: &A, b: &A, c: &A, a_idx: usize, b_idx: usize, _c_idx: usize| { - filter.test(s, a, b, a_idx, b_idx) && joiner.matches(a, c) - }; + crate::stream::closures::self_join_triple_filter::(self.filter, joiner); TriConstraintStream::new_self_join_with_filter( self.extractor, diff --git a/crates/solverforge-scoring/src/stream/closures.rs b/crates/solverforge-scoring/src/stream/closures.rs new file mode 100644 index 00000000..7a0e7a63 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/closures.rs @@ -0,0 +1,460 @@ +//! Closures the stream builders hand to constraints and filter nodes. +//! +//! A closure written inside a generic method has a type that names every +//! generic parameter of that method, used or not, so a closure created by a +//! stream combinator would spell out the whole upstream stream type (its +//! extractor, its filter chain, ...) again. Debug info prints these types in +//! full, and nested combinators made single type names megabytes long. Each +//! function here is generic only over what its closure captures and takes, so +//! the closure type names exactly those parts. + +use solverforge_core::score::Score; + +use super::filter::{BiFilter, PentaFilter, QuadFilter, TriFilter, UniFilter}; +use super::joiner::Joiner; +use super::relational::operator::{FlattenView, Pair}; +use super::relational::Leaf; +use super::weighting_support::ConstraintWeight; + +/// A uni filter that ignores the solution. +pub(crate) fn entity_filter(predicate: P) -> impl Fn(&S, &A) -> bool + Send + Sync +where + P: Fn(&A) -> bool + Send + Sync, +{ + move |_s: &S, a: &A| predicate(a) +} + +/// A pair filter that ignores the solution and the row indexes. +pub(crate) fn pair_filter( + predicate: P, +) -> impl Fn(&S, &A, &B, usize, usize) -> bool + Send + Sync +where + P: Fn(&A, &B) -> bool + Send + Sync, +{ + move |_s: &S, a: &A, b: &B, _a_idx: usize, _b_idx: usize| predicate(a, b) +} + +/// A triple filter that ignores the solution and the row indexes. +pub(crate) fn triple_filter( + predicate: P, +) -> impl Fn(&S, &A, &B, &C, usize, usize, usize) -> bool + Send + Sync +where + P: Fn(&A, &B, &C) -> bool + Send + Sync, +{ + move |_s: &S, a: &A, b: &B, c: &C, _a_idx: usize, _b_idx: usize, _c_idx: usize| { + predicate(a, b, c) + } +} + +/// A quadruple filter that ignores the solution and the row indexes. +#[allow(clippy::type_complexity)] +pub(crate) fn quad_filter( + predicate: P, +) -> impl Fn(&S, &A, &B, &C, &D, usize, usize, usize, usize) -> bool + Send + Sync +where + P: Fn(&A, &B, &C, &D) -> bool + Send + Sync, +{ + move |_s: &S, a: &A, b: &B, c: &C, d: &D, _ai: usize, _bi: usize, _ci: usize, _di: usize| { + predicate(a, b, c, d) + } +} + +/// A quintuple filter that ignores the solution and the row indexes. +#[allow(clippy::type_complexity)] +pub(crate) fn penta_filter( + predicate: P, +) -> impl Fn(&S, &A, &B, &C, &D, &E, usize, usize, usize, usize, usize) -> bool + Send + Sync +where + P: Fn(&A, &B, &C, &D, &E) -> bool + Send + Sync, +{ + move |_s: &S, + a: &A, + b: &B, + c: &C, + d: &D, + e: &E, + _ai: usize, + _bi: usize, + _ci: usize, + _di: usize, + _ei: usize| predicate(a, b, c, d, e) +} + +/// A uni filter as the closure an `IncrementalUniConstraint` tests. +pub(crate) fn uni_filter_fn(filter: F) -> impl Fn(&S, &A) -> bool + Send + Sync +where + F: UniFilter, +{ + move |s: &S, a: &A| filter.test(s, a) +} + +/// `key` wrapped so every row has a key. +pub(crate) fn some_key(key: F) -> impl Fn(&A) -> Option + Send + Sync +where + F: Fn(&A) -> K + Send + Sync, +{ + move |a: &A| Some(key(a)) +} + +/// `weight` scored on a leaf row's entity. +pub(crate) fn leaf_weight(weight: W) -> impl Fn(&S, &Leaf<'_, A>) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync, +{ + move |_s: &S, row: &Leaf<'_, A>| weight.score((row.entity,)) +} + +/// `default` applied to a leaf row's entity. +pub(crate) fn leaf_default(default: F) -> impl Fn(&S, &Leaf<'_, B>) -> R + Send + Sync +where + F: Fn(&B) -> R + Send + Sync, +{ + move |_s: &S, row: &Leaf<'_, B>| default(row.entity) +} + +/// `weight` applied to the two entities of a joined pair row. +pub(crate) fn pair_row_weight( + weight: W, +) -> impl Fn(&S, &Pair, Leaf<'_, B>>) -> Sc + Send + Sync +where + W: Fn(&A, &B) -> Sc + Send + Sync, +{ + move |_s: &S, row: &Pair, Leaf<'_, B>>| weight(row.left.entity, row.right.entity) +} + +/// `key` applied to the two entities of a joined pair row. +pub(crate) fn pair_row_key( + key: G, +) -> impl Fn(&Pair, Leaf<'_, B>>) -> K + Send + Sync +where + G: Fn(&A, &B) -> K + Send + Sync, +{ + move |row: &Pair, Leaf<'_, B>>| key(row.left.entity, row.right.entity) +} + +/// `weight` applied to the three entities of a joined triple row. +#[allow(clippy::type_complexity)] +pub(crate) fn triple_row_weight( + weight: W, +) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> Sc + Send + Sync +where + W: Fn(&A, &B, &C) -> Sc + Send + Sync, +{ + move |_s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>| { + weight( + row.left.left.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// `weight` applied to the four entities of a joined quadruple row. +#[allow(clippy::type_complexity)] +pub(crate) fn quad_row_weight( + weight: W, +) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> Sc + Send + Sync +where + W: Fn(&A, &B, &C, &D) -> Sc + Send + Sync, +{ + move |_s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>| { + weight( + row.left.left.left.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// `weight` applied to the five entities of a joined quintuple row. +#[allow(clippy::type_complexity)] +pub(crate) fn penta_row_weight( + weight: W, +) -> impl Fn( + &S, + &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>, +) -> Sc + + Send + + Sync +where + W: Fn(&A, &B, &C, &D, &E) -> Sc + Send + Sync, +{ + move |_s: &S, + row: &Pair< + Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, + Leaf<'_, E>, + >| { + weight( + row.left.left.left.left.entity, + row.left.left.left.right.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// `weight` applied to the parent entity and flattened item of a flattened +/// pair row. +pub(crate) fn flattened_row_weight( + weight: W, +) -> impl Fn(&S, &Pair, FlattenView<'_, Leaf<'_, B>, C>>) -> Sc + Send + Sync +where + W: Fn(&A, &C) -> Sc + Send + Sync, +{ + move |_s: &S, row: &Pair, FlattenView<'_, Leaf<'_, B>, C>>| { + weight(row.left.entity, row.right.value) + } +} + +/// A bi filter extended by a self-join joiner into a triple filter. +pub(crate) fn self_join_triple_filter( + filter: F, + joiner: J, +) -> impl Fn(&S, &A, &A, &A, usize, usize, usize) -> bool + Send + Sync +where + F: BiFilter, + J: Joiner, +{ + move |s: &S, a: &A, b: &A, c: &A, a_idx: usize, b_idx: usize, _c_idx: usize| { + filter.test(s, a, b, a_idx, b_idx) && joiner.matches(a, c) + } +} + +/// A tri filter extended by a self-join joiner into a quadruple filter. +#[allow(clippy::type_complexity)] +pub(crate) fn self_join_quad_filter( + filter: F, + joiner: J, +) -> impl Fn(&S, &A, &A, &A, &A, usize, usize, usize, usize) -> bool + Send + Sync +where + F: TriFilter, + J: Joiner, +{ + move |s: &S, + a: &A, + b: &A, + c: &A, + d: &A, + a_idx: usize, + b_idx: usize, + c_idx: usize, + _d_idx: usize| { + filter.test(s, a, b, c, a_idx, b_idx, c_idx) && joiner.matches(a, d) + } +} + +/// A quad filter extended by a self-join joiner into a quintuple filter. +#[allow(clippy::type_complexity)] +pub(crate) fn self_join_penta_filter( + filter: F, + joiner: J, +) -> impl Fn(&S, &A, &A, &A, &A, &A, usize, usize, usize, usize, usize) -> bool + Send + Sync +where + F: QuadFilter, + J: Joiner, +{ + move |s: &S, + a: &A, + b: &A, + c: &A, + d: &A, + e: &A, + a_idx: usize, + b_idx: usize, + c_idx: usize, + d_idx: usize, + _e_idx: usize| { + filter.test(s, a, b, c, d, a_idx, b_idx, c_idx, d_idx) && joiner.matches(a, e) + } +} + +/// A tri filter tested on a joined triple row. +#[allow(clippy::type_complexity)] +pub(crate) fn triple_row_filter( + filter: F, +) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> bool + Send + Sync +where + F: TriFilter, +{ + move |s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>| { + filter.test( + s, + row.left.left.entity, + row.left.right.entity, + row.right.entity, + row.left.left.index, + row.left.right.index, + row.right.index, + ) + } +} + +/// `key` applied to the three entities of a joined triple row. +#[allow(clippy::type_complexity)] +pub(crate) fn triple_row_key( + key: G, +) -> impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> K + Send + Sync +where + G: Fn(&A, &B, &C) -> K + Send + Sync, +{ + move |row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>| { + key( + row.left.left.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// A quad filter tested on a joined quadruple row. +#[allow(clippy::type_complexity)] +pub(crate) fn quad_row_filter( + filter: F, +) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> bool + + Send + + Sync +where + F: QuadFilter, +{ + move |s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>| { + filter.test( + s, + row.left.left.left.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + row.left.left.left.index, + row.left.left.right.index, + row.left.right.index, + row.right.index, + ) + } +} + +/// `key` applied to the four entities of a joined quadruple row. +#[allow(clippy::type_complexity)] +pub(crate) fn quad_row_key( + key: G, +) -> impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> K + Send + Sync +where + G: Fn(&A, &B, &C, &D) -> K + Send + Sync, +{ + move |row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>| { + key( + row.left.left.left.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// A penta filter tested on a joined quintuple row. +#[allow(clippy::type_complexity)] +pub(crate) fn penta_row_filter( + filter: F, +) -> impl Fn( + &S, + &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>, +) -> bool + + Send + + Sync +where + F: PentaFilter, +{ + move |s: &S, + row: &Pair< + Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, + Leaf<'_, E>, + >| { + filter.test( + s, + row.left.left.left.left.entity, + row.left.left.left.right.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + row.left.left.left.left.index, + row.left.left.left.right.index, + row.left.left.right.index, + row.left.right.index, + row.right.index, + ) + } +} + +/// `key` applied to the five entities of a joined quintuple row. +#[allow(clippy::type_complexity)] +pub(crate) fn penta_row_key( + key: G, +) -> impl Fn( + &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>, +) -> K + + Send + + Sync +where + G: Fn(&A, &B, &C, &D, &E) -> K + Send + Sync, +{ + move |row: &Pair< + Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, + Leaf<'_, E>, + >| { + key( + row.left.left.left.left.entity, + row.left.left.left.right.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + ) + } +} + +/// `weight` as a closure over 1 matched row. +pub(crate) fn weight1(weight: W) -> impl Fn(&A) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync, +{ + move |a: &A| weight.score((a,)) +} + +/// `weight` as a closure over 2 matched rows. +pub(crate) fn weight2(weight: W) -> impl Fn(&A, &B) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A, &'w B), Sc> + Send + Sync, +{ + move |a: &A, b: &B| weight.score((a, b)) +} + +/// `weight` as a closure over 3 matched rows. +pub(crate) fn weight3(weight: W) -> impl Fn(&A, &B, &C) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C), Sc> + Send + Sync, +{ + move |a: &A, b: &B, c: &C| weight.score((a, b, c)) +} + +/// `weight` as a closure over 4 matched rows. +pub(crate) fn weight4(weight: W) -> impl Fn(&A, &B, &C, &D) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D), Sc> + Send + Sync, +{ + move |a: &A, b: &B, c: &C, d: &D| weight.score((a, b, c, d)) +} + +/// `weight` as a closure over 5 matched rows. +pub(crate) fn weight5( + weight: W, +) -> impl Fn(&A, &B, &C, &D, &E) -> Sc + Send + Sync +where + Sc: Score, + W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D, &'w E), Sc> + Send + Sync, +{ + move |a: &A, b: &B, c: &C, d: &D, e: &E| weight.score((a, b, c, d, e)) +} diff --git a/crates/solverforge-scoring/src/stream/complemented_stream.rs b/crates/solverforge-scoring/src/stream/complemented_stream.rs index 4edb85d4..225c0f5b 100644 --- a/crates/solverforge-scoring/src/stream/complemented_stream.rs +++ b/crates/solverforge-scoring/src/stream/complemented_stream.rs @@ -223,7 +223,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -259,7 +259,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -359,7 +359,7 @@ where targets, group, ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey), - move |_s: &S, row: &Leaf<'_, B>| default_fn(row.entity), + crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( tree, diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/base.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/base.rs index 3fc1138f..c9149164 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/base.rs @@ -142,9 +142,9 @@ where plan: self.plan, filter: AndBiFilter::new( self.filter, - FnBiFilter::new(move |_s: &S, a: &A, b: &B, _a_idx: usize, _b_idx: usize| { - predicate(a, b) - }), + FnBiFilter::new(crate::stream::closures::pair_filter::( + predicate, + )), ), _phantom: PhantomData, } 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 c9d605a3..b61db955 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 @@ -188,7 +188,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |key: &GK, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -230,7 +230,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |key: &GK, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -379,9 +379,7 @@ where let group_key = self.group_key_fn; let group = GroupNode::new( input, - move |row: &Pair, Leaf<'_, B>>| { - group_key(row.left.entity, row.right.entity) - }, + crate::stream::closures::pair_row_key::(group_key), TupleCollector::new(self.collector), ); let key_t = self.key_t; @@ -390,7 +388,7 @@ where CollectionNode::new(self.extractor_t, 2), group, ViewEqualPlan::new(EntityKey::new(key_t.clone()), GroupKey), - move |_solution: &S, row: &Leaf<'_, T>| default_fn(row.entity), + crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( tree, 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 fbcb09ed..75912a69 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs @@ -126,7 +126,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |key: &GK, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -164,7 +164,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |key: &GK, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -285,9 +285,7 @@ where let group_key = self.group_key_fn; let tree = GroupNode::new( input, - move |row: &Pair, Leaf<'_, B>>| { - group_key(row.left.entity, row.right.entity) - }, + crate::stream::closures::pair_row_key::(group_key), TupleCollector::new(self.collector), ); SharedOperatorBuilder::first_with_hard( diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs index 8080db55..c3534d16 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs @@ -10,7 +10,7 @@ use super::super::relational::operator::{CollectionNode, JoinNode, Operator, Pai use super::super::relational::Leaf; use super::super::weighting_support::ConstraintWeight; use super::base::Bi; -use super::scored::{BiEntities, BiScored}; +use super::scored::BiScored; use crate::constraint::relational::OperatorTerminal; impl Bi @@ -62,7 +62,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A, b: &B| weight.score((a, b)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -82,7 +82,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |a: &A, b: &B| weight.score((a, b)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -143,10 +143,7 @@ where ); let scored = BiScored::new(tree, self.filter); let weight = self.weight; - let weight_fn = move |_: &S, row: &Pair, Leaf<'_, B>>| { - let (a, b) = row.entities(); - weight(a, b) - }; + let weight_fn = crate::stream::closures::pair_row_weight::(weight); OperatorTerminal::new( ConstraintRef::new("", name), self.impact_type, diff --git a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs index c3bba11c..1d1b01cd 100644 --- a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs @@ -164,17 +164,7 @@ where filter: AndPentaFilter::new( self.filter, FnPentaFilter::new( - move |_s: &S, - a: &A, - b: &B, - c: &C, - d: &D, - e: &E, - _ai: usize, - _bi: usize, - _ci: usize, - _di: usize, - _ei: usize| { predicate(a, b, c, d, e) }, + crate::stream::closures::penta_filter::(predicate), ), ), _phantom: PhantomData, @@ -235,7 +225,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A, b: &B, c: &C, d: &D, e: &E| weight.score((a, b, c, d, e)), + crate::stream::closures::weight5::(weight), is_hard, ) } @@ -275,7 +265,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |a: &A, b: &B, c: &C, d: &D, e: &E| weight.score((a, b, c, d, e)), + crate::stream::closures::weight5::(weight), is_hard, ) } @@ -422,10 +412,8 @@ where let is_hard = self.is_hard; let constraint_ref = ConstraintRef::new("", name); let scored = PentaScored::new(self.tree, self.filter); - let weight_fn = move |_: &S, row: &PentaRow<'_, S, EA, EB, EC, ED, EE, P1, P2, P3, P4>| { - let (a, b, c, d, e) = PentaEntities::entities(row); - weight(a, b, c, d, e) - }; + let weight_fn = + crate::stream::closures::penta_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) } } diff --git a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs index 0e23b9d6..1bdc2473 100644 --- a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs @@ -141,17 +141,9 @@ where tree: self.tree, filter: AndQuadFilter::new( self.filter, - FnQuadFilter::new( - move |_s: &S, - a: &A, - b: &B, - c: &C, - d: &D, - _ai: usize, - _bi: usize, - _ci: usize, - _di: usize| { predicate(a, b, c, d) }, - ), + FnQuadFilter::new(crate::stream::closures::quad_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -265,7 +257,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A, b: &B, c: &C, d: &D| weight.score((a, b, c, d)), + crate::stream::closures::weight4::(weight), is_hard, ) } @@ -301,7 +293,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |a: &A, b: &B, c: &C, d: &D| weight.score((a, b, c, d)), + crate::stream::closures::weight4::(weight), is_hard, ) } @@ -371,10 +363,7 @@ where child_inserted: Vec::new(), marker: PhantomData, }; - let weight_fn = move |_: &S, row: &QuadRow<'_, S, EA, EB, EC, ED, P1, P2, P3>| { - let (a, b, c, d) = QuadEntities::entities(row); - weight(a, b, c, d) - }; + let weight_fn = crate::stream::closures::quad_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) } } diff --git a/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs b/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs index de061069..f4df5b1c 100644 --- a/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs @@ -186,15 +186,9 @@ where tree: self.tree, filter: AndTriFilter::new( self.filter, - FnTriFilter::new( - move |_s: &S, - a: &A, - b: &B, - c: &C, - _a_idx: usize, - _b_idx: usize, - _c_idx: usize| { predicate(a, b, c) }, - ), + FnTriFilter::new(crate::stream::closures::triple_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -296,7 +290,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A, b: &B, c: &C| weight.score((a, b, c)), + crate::stream::closures::weight3::(weight), is_hard, ) } @@ -317,7 +311,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |a: &A, b: &B, c: &C| weight.score((a, b, c)), + crate::stream::closures::weight3::(weight), is_hard, ) } @@ -380,10 +374,7 @@ where child_inserted: Vec::new(), marker: PhantomData, }; - let weight_fn = move |_: &S, row: &TriRow<'_, S, EA, EB, EC, P1, P2>| { - let (a, b, c) = TriEntities::entities(row); - weight(a, b, c) - }; + let weight_fn = crate::stream::closures::triple_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) } } diff --git a/crates/solverforge-scoring/src/stream/existence_stream.rs b/crates/solverforge-scoring/src/stream/existence_stream.rs index 348b7d74..10315585 100644 --- a/crates/solverforge-scoring/src/stream/existence_stream.rs +++ b/crates/solverforge-scoring/src/stream/existence_stream.rs @@ -122,7 +122,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |_s: &S, row: &Leaf<'_, A>| weight.score((row.entity,)), + crate::stream::closures::leaf_weight::(weight), is_hard, ) } @@ -152,7 +152,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |_s: &S, row: &Leaf<'_, A>| weight.score((row.entity,)), + crate::stream::closures::leaf_weight::(weight), is_hard, ) } diff --git a/crates/solverforge-scoring/src/stream/flattened_bi_stream/base.rs b/crates/solverforge-scoring/src/stream/flattened_bi_stream/base.rs index 1ffa95f8..0add2f11 100644 --- a/crates/solverforge-scoring/src/stream/flattened_bi_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/flattened_bi_stream/base.rs @@ -166,9 +166,9 @@ where a_lookup_fn: self.a_lookup_fn, filter: AndBiFilter::new( self.filter, - FnBiFilter::new(move |_s: &S, a: &A, c: &C, _a_idx: usize, _b_idx: usize| { - predicate(a, c) - }), + FnBiFilter::new(crate::stream::closures::pair_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -248,7 +248,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A, c: &C| weight.score((a, c)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -285,7 +285,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |a: &A, c: &C| weight.score((a, c)), + crate::stream::closures::weight2::(weight), is_hard, ) } diff --git a/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs b/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs index b9ce63ef..3e84d471 100644 --- a/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs +++ b/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs @@ -137,10 +137,7 @@ where let tree = super::super::relational::operator::JoinNode::new(left, right, plan); let scored = FlattenedBiScored::new(tree, self.filter); let weight = self.weight; - let weight_fn = move |_: &S, row: &Pair, FlattenView<'_, Leaf<'_, B>, C>>| { - let (a, c) = super::scored::FlattenedBiEntities::entities(row); - weight(a, c) - }; + let weight_fn = crate::stream::closures::flattened_row_weight::(weight); OperatorTerminal::new( ConstraintRef::new("", name), self.impact_type, diff --git a/crates/solverforge-scoring/src/stream/group_by_penta.rs b/crates/solverforge-scoring/src/stream/group_by_penta.rs index 78b5c7a3..2be80e78 100644 --- a/crates/solverforge-scoring/src/stream/group_by_penta.rs +++ b/crates/solverforge-scoring/src/stream/group_by_penta.rs @@ -65,33 +65,13 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let filter = self.filter; - let input = FilterNode::new(self.tree, move |s: &S, row: &Row<'_, A, B, C, D, E>| { - filter.test( - s, - row.left.left.left.left.entity, - row.left.left.left.right.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - row.left.left.left.left.index, - row.left.left.left.right.index, - row.left.left.right.index, - row.left.right.index, - row.right.index, - ) - }); + let input = FilterNode::new( + self.tree, + crate::stream::closures::penta_row_filter::(self.filter), + ); JoinedGroupedStream::new( input, - move |row: &Row<'_, A, B, C, D, E>| { - key( - row.left.left.left.left.entity, - row.left.left.left.right.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - ) - }, + crate::stream::closures::penta_row_key::(key), TupleCollector::new(collector), ) } diff --git a/crates/solverforge-scoring/src/stream/group_by_quad.rs b/crates/solverforge-scoring/src/stream/group_by_quad.rs index 9c935e51..b51b58c6 100644 --- a/crates/solverforge-scoring/src/stream/group_by_quad.rs +++ b/crates/solverforge-scoring/src/stream/group_by_quad.rs @@ -61,30 +61,13 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let filter = self.filter; - let input = FilterNode::new(self.tree, move |s: &S, row: &Row<'_, A, B, C, D>| { - filter.test( - s, - row.left.left.left.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - row.left.left.left.index, - row.left.left.right.index, - row.left.right.index, - row.right.index, - ) - }); + let input = FilterNode::new( + self.tree, + crate::stream::closures::quad_row_filter::(self.filter), + ); JoinedGroupedStream::new( input, - move |row: &Row<'_, A, B, C, D>| { - key( - row.left.left.left.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - ) - }, + crate::stream::closures::quad_row_key::(key), TupleCollector::new(collector), ) } diff --git a/crates/solverforge-scoring/src/stream/group_by_tri.rs b/crates/solverforge-scoring/src/stream/group_by_tri.rs index f5fc1d5f..7fab594d 100644 --- a/crates/solverforge-scoring/src/stream/group_by_tri.rs +++ b/crates/solverforge-scoring/src/stream/group_by_tri.rs @@ -53,27 +53,13 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let filter = self.filter; - let input = FilterNode::new(self.tree, move |s: &S, row: &Row<'_, A, B, C>| { - filter.test( - s, - row.left.left.entity, - row.left.right.entity, - row.right.entity, - row.left.left.index, - row.left.right.index, - row.right.index, - ) - }); + let input = FilterNode::new( + self.tree, + crate::stream::closures::triple_row_filter::(self.filter), + ); JoinedGroupedStream::new( input, - move |row: &Row<'_, A, B, C>| { - key( - row.left.left.entity, - row.left.right.entity, - row.right.entity, - ) - }, + crate::stream::closures::triple_row_key::(key), TupleCollector::new(collector), ) } diff --git a/crates/solverforge-scoring/src/stream/grouped_stream/base.rs b/crates/solverforge-scoring/src/stream/grouped_stream/base.rs index cfe4de38..b01f6487 100644 --- a/crates/solverforge-scoring/src/stream/grouped_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/grouped_stream/base.rs @@ -109,7 +109,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -142,7 +142,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -176,7 +176,7 @@ where D: Fn(&B) -> R + Send + Sync + 'static, { let key_fn = self.key_fn; - let wrapped_key_fn = move |a: &A| Some((key_fn)(a)); + let wrapped_key_fn = crate::stream::closures::some_key::(key_fn); ComplementedConstraintStream::new( self.extractor, extractor_b, diff --git a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs index 9f8f68e0..bf86a3a5 100644 --- a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs +++ b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs @@ -151,7 +151,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |k: &K, r: &R, b: &B| weight.score((k, r, b)), + crate::stream::closures::weight3::(weight), is_hard, ) } @@ -182,7 +182,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |k: &K, r: &R, b: &B| weight.score((k, r, b)), + crate::stream::closures::weight3::(weight), is_hard, ) } diff --git a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs index 43b45e05..ffed4aee 100644 --- a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs +++ b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs @@ -47,7 +47,7 @@ where let hard = weight.is_hard(); JoinedGroupedBuilder { node: self.node, - weight: move |k: &K, r: &R| weight.score((k, r)), + weight: crate::stream::closures::weight2::(weight), impact: ImpactType::Penalty, hard, marker: PhantomData, @@ -65,7 +65,7 @@ where let hard = weight.is_hard(); JoinedGroupedBuilder { node: self.node, - weight: move |k: &K, r: &R| weight.score((k, r)), + weight: crate::stream::closures::weight2::(weight), impact: ImpactType::Reward, hard, marker: PhantomData, diff --git a/crates/solverforge-scoring/src/stream/mod.rs b/crates/solverforge-scoring/src/stream/mod.rs index aa2cfb88..1bd623ca 100644 --- a/crates/solverforge-scoring/src/stream/mod.rs +++ b/crates/solverforge-scoring/src/stream/mod.rs @@ -80,6 +80,7 @@ mod arity_stream_macros; mod balance_stream; mod bi_stream; mod chain_stream; +mod closures; pub mod collection_extract; pub mod collector; mod complemented_stream; diff --git a/crates/solverforge-scoring/src/stream/projected_stream.rs b/crates/solverforge-scoring/src/stream/projected_stream.rs index 17dcff3f..703cd35b 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream.rs @@ -3,6 +3,7 @@ mod complemented_grouped; mod directed_bi; mod grouped; mod join_target; +mod row_closures; mod source; mod uni; diff --git a/crates/solverforge-scoring/src/stream/projected_stream/bi.rs b/crates/solverforge-scoring/src/stream/projected_stream/bi.rs index ff817d63..37b58829 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/bi.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/bi.rs @@ -58,11 +58,9 @@ where key_fn: self.key_fn, pair_filter: AndBiFilter::new( self.pair_filter, - FnBiFilter::new( - move |_s: &S, left: &Out, right: &Out, _left_idx: usize, _right_idx: usize| { - predicate(left, right) - }, - ), + FnBiFilter::new(crate::stream::closures::pair_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -104,7 +102,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |left: &Out, right: &Out| weight.score((left, right)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -124,7 +122,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |left: &Out, right: &Out| weight.score((left, right)), + crate::stream::closures::weight2::(weight), is_hard, ) } 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 bf24dcaa..3ac8683e 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs @@ -119,7 +119,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -156,7 +156,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Reward, - move |key: &K, result: &R| weight.score((key, result)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -248,9 +248,9 @@ where let group = GroupNode::new( FilterNode::new( SourceNode::new(self.source), - move |solution: &S, row: &ProjectedRow<'_, Out>| filter.test(solution, row.value), + super::row_closures::projected_row_filter::(filter), ), - move |row: &ProjectedRow<'_, Out>| key_a(row.value), + super::row_closures::projected_row_key::, _>(key_a), ProjectedCollector::new(self.collector), ); let key_b = self.key_b; @@ -259,7 +259,7 @@ where CollectionNode::new(self.extractor_b, target_binding), group, ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey), - move |_solution: &S, row: &Leaf<'_, B>| default_fn(row.entity), + crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( tree, diff --git a/crates/solverforge-scoring/src/stream/projected_stream/directed_bi.rs b/crates/solverforge-scoring/src/stream/projected_stream/directed_bi.rs index fc38c300..3d6fa035 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/directed_bi.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/directed_bi.rs @@ -60,11 +60,9 @@ where right_key_fn: self.right_key_fn, pair_filter: AndBiFilter::new( self.pair_filter, - FnBiFilter::new( - move |_s: &S, left: &Out, right: &Out, _left_idx: usize, _right_idx: usize| { - predicate(left, right) - }, - ), + FnBiFilter::new(crate::stream::closures::pair_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -107,7 +105,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |left: &Out, right: &Out| weight.score((left, right)), + crate::stream::closures::weight2::(weight), is_hard, ) } @@ -127,7 +125,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |left: &Out, right: &Out| weight.score((left, right)), + crate::stream::closures::weight2::(weight), is_hard, ) } diff --git a/crates/solverforge-scoring/src/stream/projected_stream/grouped.rs b/crates/solverforge-scoring/src/stream/projected_stream/grouped.rs index 483a029a..06207e60 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/grouped.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/grouped.rs @@ -85,7 +85,7 @@ where let is_hard = weight_fn.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |key: &K, result: &R| weight_fn.score((key, result)), + crate::stream::closures::weight2::(weight_fn), is_hard, ) } @@ -105,7 +105,7 @@ where let is_hard = weight_fn.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |key: &K, result: &R| weight_fn.score((key, result)), + crate::stream::closures::weight2::(weight_fn), is_hard, ) } @@ -142,7 +142,7 @@ where D: Fn(&B) -> R + Send + Sync, { let key_fn = self.key_fn; - let key_a = move |output: &Out| Some((key_fn)(output)); + let key_a = crate::stream::closures::some_key::(key_fn); ComplementedGrouped { source: self.source, extractor_b, @@ -253,9 +253,9 @@ where let tree = GroupNode::new( FilterNode::new( SourceNode::new(self.source), - move |solution: &S, row: &ProjectedRow<'_, Out>| filter.test(solution, row.value), + super::row_closures::projected_row_filter::(filter), ), - move |row: &ProjectedRow<'_, Out>| key(row.value), + super::row_closures::projected_row_key::(key), ProjectedCollector::new(self.collector), ); SharedOperatorBuilder::first_with_hard( diff --git a/crates/solverforge-scoring/src/stream/projected_stream/row_closures.rs b/crates/solverforge-scoring/src/stream/projected_stream/row_closures.rs new file mode 100644 index 00000000..49cefea3 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/projected_stream/row_closures.rs @@ -0,0 +1,26 @@ +//! Closures over projected rows, built in functions generic only over what +//! they capture so their types do not repeat the projected stream's type (see +//! `stream::closures`). + +use super::super::filter::UniFilter; +use super::source::ProjectedRow; + +/// A uni filter tested on a projected row's value. +pub(crate) fn projected_row_filter( + filter: F, +) -> impl Fn(&S, &ProjectedRow<'_, Out>) -> bool + Send + Sync +where + F: UniFilter, +{ + move |solution: &S, row: &ProjectedRow<'_, Out>| filter.test(solution, row.value) +} + +/// `key` applied to a projected row's value. +pub(crate) fn projected_row_key( + key: G, +) -> impl Fn(&ProjectedRow<'_, Out>) -> K + Send + Sync +where + G: Fn(&Out) -> K + Send + Sync, +{ + move |row: &ProjectedRow<'_, Out>| key(row.value) +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/uni.rs b/crates/solverforge-scoring/src/stream/projected_stream/uni.rs index 58f5df02..b5ba0346 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/uni.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/uni.rs @@ -57,7 +57,9 @@ where source: self.source, filter: AndUniFilter::new( self.filter, - FnUniFilter::new(move |_s: &S, output: &Out| predicate(output)), + FnUniFilter::new(crate::stream::closures::entity_filter::( + predicate, + )), ), _phantom: PhantomData, } @@ -157,7 +159,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Penalty, - move |output: &Out| weight.score((output,)), + crate::stream::closures::weight1::(weight), is_hard, ) } @@ -177,7 +179,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( solverforge_core::ImpactType::Reward, - move |output: &Out| weight.score((output,)), + crate::stream::closures::weight1::(weight), is_hard, ) } diff --git a/crates/solverforge-scoring/src/stream/quad_stream.rs b/crates/solverforge-scoring/src/stream/quad_stream.rs index a595d731..dc224169 100644 --- a/crates/solverforge-scoring/src/stream/quad_stream.rs +++ b/crates/solverforge-scoring/src/stream/quad_stream.rs @@ -137,20 +137,8 @@ where J: Joiner + 'static, F: 'static, { - let filter = self.filter; - let combined_filter = move |s: &S, - a: &A, - b: &A, - c: &A, - d: &A, - e: &A, - a_idx: usize, - b_idx: usize, - c_idx: usize, - d_idx: usize, - _e_idx: usize| { - filter.test(s, a, b, c, d, a_idx, b_idx, c_idx, d_idx) && joiner.matches(a, e) - }; + let combined_filter = + crate::stream::closures::self_join_penta_filter::(self.filter, joiner); PentaConstraintStream::new_self_join_with_filter( self.extractor, diff --git a/crates/solverforge-scoring/src/stream/tri_stream.rs b/crates/solverforge-scoring/src/stream/tri_stream.rs index e7523ea7..c42893a4 100644 --- a/crates/solverforge-scoring/src/stream/tri_stream.rs +++ b/crates/solverforge-scoring/src/stream/tri_stream.rs @@ -133,18 +133,8 @@ where J: Joiner + 'static, F: 'static, { - let filter = self.filter; - let combined_filter = move |s: &S, - a: &A, - b: &A, - c: &A, - d: &A, - a_idx: usize, - b_idx: usize, - c_idx: usize, - _d_idx: usize| { - filter.test(s, a, b, c, a_idx, b_idx, c_idx) && joiner.matches(a, d) - }; + let combined_filter = + crate::stream::closures::self_join_quad_filter::(self.filter, joiner); QuadConstraintStream::new_self_join_with_filter( self.extractor, diff --git a/crates/solverforge-scoring/src/stream/uni_stream/base.rs b/crates/solverforge-scoring/src/stream/uni_stream/base.rs index c8abadc3..71342b06 100644 --- a/crates/solverforge-scoring/src/stream/uni_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/uni_stream/base.rs @@ -98,7 +98,7 @@ where extractor: self.extractor, filter: AndUniFilter::new( self.filter, - FnUniFilter::new(move |_s: &S, a: &A| predicate(a)), + FnUniFilter::new(crate::stream::closures::entity_filter::(predicate)), ), _phantom: PhantomData, } diff --git a/crates/solverforge-scoring/src/stream/uni_stream/weighting.rs b/crates/solverforge-scoring/src/stream/uni_stream/weighting.rs index aa17803d..0959278b 100644 --- a/crates/solverforge-scoring/src/stream/uni_stream/weighting.rs +++ b/crates/solverforge-scoring/src/stream/uni_stream/weighting.rs @@ -52,7 +52,7 @@ where let is_hard = weight.is_hard(); self.into_weighted_builder( ImpactType::Penalty, - move |a: &A| weight.score((a,)), + crate::stream::closures::weight1::(weight), is_hard, ) } @@ -70,7 +70,11 @@ where W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync, { let is_hard = weight.is_hard(); - self.into_weighted_builder(ImpactType::Reward, move |a: &A| weight.score((a,)), is_hard) + self.into_weighted_builder( + ImpactType::Reward, + crate::stream::closures::weight1::(weight), + is_hard, + ) } } @@ -101,8 +105,7 @@ where self, name: &str, ) -> IncrementalUniConstraint bool + Send + Sync, W, Sc> { - let filter = self.filter; - let combined_filter = move |s: &S, a: &A| filter.test(s, a); + let combined_filter = crate::stream::closures::uni_filter_fn::(self.filter); IncrementalUniConstraint::new( ConstraintRef::new("", name), diff --git a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs index dca1cf07..3a9b549e 100644 --- a/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs +++ b/crates/solverforge-solver/src/phase/localsearch/parallel/tests/support.rs @@ -54,13 +54,11 @@ macro_rules! forkable_director { ($solution:expr, $descriptor:expr) => {{ let solution: crate::test_utils::NQueensSolution = $solution; let constraints = super::support::queen_constraints(&solution); - solverforge_scoring::ScoreDirector::with_descriptor( + solverforge_scoring::ScoreDirector::with_replicas( solution, constraints, - solverforge_scoring::ReplicaDescriptor::new( - $descriptor, - super::support::queen_constraints, - ), + super::support::queen_constraints, + $descriptor, |s: &NQueensSolution, _| s.queens.len(), ) }}; diff --git a/crates/solverforge-solver/src/run.rs b/crates/solverforge-solver/src/run.rs index a62c5975..ccfc0d4b 100644 --- a/crates/solverforge-solver/src/run.rs +++ b/crates/solverforge-solver/src/run.rs @@ -10,8 +10,8 @@ use solverforge_config::{SolverConfig, TerminationConfig}; use solverforge_core::domain::{PlanningSolution, SolutionDescriptor}; use solverforge_core::score::{ParseableScore, Score}; use solverforge_scoring::{ - requires_weighted_mode, ConstraintSet, Director, ReplicaDescriptor, ScoreDirector, - UnweightedMode, WeightMode, WeightedMode, + requires_weighted_mode, ConstraintSet, Director, ScoreDirector, UnweightedMode, WeightMode, + WeightedMode, }; use tracing::info; @@ -301,13 +301,10 @@ where W: WeightMode, Runner: for<'d> Phase< S, - ScoreDirector, UnweightedMode>, + ScoreDirector, ChannelProgressCallback, - > + for<'d> Phase< - S, - ScoreDirector, W>, - ChannelProgressCallback, - > + Send + > + for<'d> Phase, ChannelProgressCallback> + + Send + std::fmt::Debug, BuildRunner: FnOnce(&SolverConfig, &SolutionDescriptor) -> RuntimeBuildResult, { @@ -343,7 +340,8 @@ where weight_modes::ModeSolve { solution, constraints: main_constraints, - descriptor: ReplicaDescriptor::new(&descriptor, constraints), + constraint_builder: constraints, + descriptor: &descriptor, entity_count_by_descriptor, runtime, config: &config, diff --git a/crates/solverforge-solver/src/run/weight_modes.rs b/crates/solverforge-solver/src/run/weight_modes.rs index e20cf5cd..0c5aca8d 100644 --- a/crates/solverforge-solver/src/run/weight_modes.rs +++ b/crates/solverforge-solver/src/run/weight_modes.rs @@ -14,7 +14,7 @@ use super::*; use crate::scope::WeightModeControl; use crate::solver::SolveSession; -type ModeDirector<'d, S, C, M> = ScoreDirector, M>; +type ModeDirector<'d, S, C, M> = ScoreDirector; type ModeSession<'d, S, C, M, Runner> = SolveSession< 'static, @@ -83,7 +83,8 @@ enum Running { pub(super) struct ModeSolve<'d, 'c, S: PlanningSolution, C> { pub(super) solution: S, pub(super) constraints: C, - pub(super) descriptor: ReplicaDescriptor<'d, S, C>, + pub(super) constraint_builder: fn(&S) -> C, + pub(super) descriptor: &'d SolutionDescriptor, pub(super) entity_count_by_descriptor: fn(&S, usize) -> usize, pub(super) runtime: SolverRuntime, pub(super) config: &'c SolverConfig, @@ -105,6 +106,7 @@ where let ModeSolve { solution, constraints, + constraint_builder, descriptor, entity_count_by_descriptor, runtime, @@ -127,19 +129,19 @@ where control, }; let mut running = if start_weighted { - Running::Weighted( - start.session::(ScoreDirector::with_descriptor_in_mode( - solution, - constraints, - descriptor, - entity_count_by_descriptor, - )), - ) + Running::Weighted(start.session::(ScoreDirector::with_replicas_in_mode( + solution, + constraints, + constraint_builder, + descriptor, + entity_count_by_descriptor, + ))) } else { Running::Unweighted(start.session::( - ScoreDirector::with_descriptor_in_mode( + ScoreDirector::with_replicas_in_mode( solution, constraints, + constraint_builder, descriptor, entity_count_by_descriptor, ), diff --git a/crates/solverforge-solver/src/scope/tests/environment_mode.rs b/crates/solverforge-solver/src/scope/tests/environment_mode.rs index dc3bc20a..a3abb143 100644 --- a/crates/solverforge-solver/src/scope/tests/environment_mode.rs +++ b/crates/solverforge-solver/src/scope/tests/environment_mode.rs @@ -9,7 +9,7 @@ use solverforge_core::score::SoftScore; use solverforge_core::{ConstraintRef, ImpactType}; use solverforge_scoring::constraint::incremental::IncrementalUniConstraint; use solverforge_scoring::stream::collection_extract::{source, ChangeSource}; -use solverforge_scoring::{ConstraintSet, Director, ReplicaDescriptor, ScoreDirector}; +use solverforge_scoring::{ConstraintSet, Director, ScoreDirector}; use crate::scope::SolverScope; @@ -64,12 +64,8 @@ fn drifted_scope( score: None, }; let constraints = unassigned_for(&solution); - let director = ScoreDirector::with_descriptor( - solution, - constraints, - ReplicaDescriptor::new(descriptor, unassigned_for), - |_, _| 0, - ); + let director = + ScoreDirector::with_replicas(solution, constraints, unassigned_for, descriptor, |_, _| 0); let mut scope = SolverScope::new(director).with_environment_mode(mode); scope.start_solving(); assert_eq!(scope.calculate_score(), SoftScore::of(-1));