diff --git a/AGENTS.md b/AGENTS.md index 2855ccf2a..190a1c806 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,8 +178,9 @@ All hot-path code must stay monomorphized. - Avoid `.clone()` in move evaluation and scoring paths. Scoring streams do not require `Clone` on entity types, so generic scoring code cannot clone an entity; do not add a `Clone` bound to make one compile. Constraint analysis - describes an entity by its type name and `Debug` rendering (`EntityRef`) and - keeps no copy of it. + describes an entity by its type name, `Debug` rendering and source-rendered + planning id (`EntityRef`) and keeps no copy of it; planning ids are read + only on the cold explanation path. - Preserve concrete types through the full solver pipeline. Intentional type-erasure boundaries that should not be "fixed": diff --git a/crates/solverforge-macros/WIREFRAME.md b/crates/solverforge-macros/WIREFRAME.md index 2da3e284d..0d76a18b8 100644 --- a/crates/solverforge-macros/WIREFRAME.md +++ b/crates/solverforge-macros/WIREFRAME.md @@ -197,6 +197,7 @@ runtime scalar surface is candidate-index based. **Generated code:** - `impl PlanningEntity for T` — `is_pinned()`, `as_any()`, `as_any_mut()` - `impl PlanningId for T` (if `#[planning_id]` present) — `type Id` set to field type, `planning_id()` returns field value +- `impl __internal::AnalysisPlanningId for T` (always) — the `#[planning_id]` field rendered for constraint analysis (`Display`, else `Debug`, else `None`), or `None` without a `#[planning_id]` field; read only when a match is explained - `impl T { #[doc(hidden)] pub fn entity_descriptor(solution_field: &'static str) -> EntityDescriptor }` — builds descriptor with all variable descriptors (genuine, list, shadow) and preserves `#[planning_id]` metadata; `#[planning_pin]` supplies both the pin field name and a typed predicate that calls `PlanningEntity::is_pinned()` - Hidden scalar metadata bridge: private indexed helpers for scalar variable count, name, allows-unassigned, value-source metadata, getter/setter, and entity-local value slices. Helper order matches `entity_descriptor()` genuine scalar variable order; the index is used for generated getter/setter dispatch, while manifest hook attachment resolves descriptor variables by descriptor index plus variable name. - Hidden list metadata bridge (when the entity has a `#[planning_list_variable]` field): public cross-module `#[doc(hidden)]` `__SOLVERFORGE_LIST_VARIABLE_COUNT` (also emitted as `0` for entities without a list variable) plus private `__SOLVERFORGE_LIST_VARIABLE_NAME`, `__SOLVERFORGE_LIST_ELEMENT_COLLECTION`, `__solverforge_list_field()`, `__solverforge_list_field_mut()`, `__solverforge_list_metadata()` @@ -274,7 +275,7 @@ owner. - `impl T { pub fn validate_constraint_weights(&ConstraintWeights) -> Result<(), ConstraintWeightError> }` (when constraints path specified) — builds the constraint set once and runs the same checks a solve runs at start, so callers can reject a typo before submitting - `pub fn solve_with_config(self, config: SolverConfig) -> RuntimeBuildResult` (when constraints path specified) — solves on the calling thread with exactly `config` (neither `solver_toml` nor the `config` callback is applied) through a detached `SolverRuntime`, returning the best solution or the build error - `fn solve_internal(self, runtime: SolverRuntime, qualified_candidate_trace_provenance: Option) -> RuntimeBuildResult` (when constraints path specified) — starts from the embedded `solver_toml` config (parsed once; a parse error returns `RuntimeBuildError::Configuration` with the error's `Display` text) or `SolverConfig::default()` without reading the working directory, applies the optional `config = "..."` callback, and calls hidden `try_run_solver_with_config_and_search` — or hidden `try_run_weighted_solver_with_config_and_search` when a `#[constraint_weights]` field exists, so only weighted models ever instantiate the weighted solver — passing the constraints function as the constraint-set constructor (`fn(&Self) -> _`) used for the working solution and every evaluator replica. The generated `__solverforge_search_declaration(config, descriptor)` builds one `RuntimeModel` containing scalar slots plus zero or more owner-specific list slots, delegates scalar hook and scalar-group attachment to the `planning_model!` support impl, sorts those variable slots to the descriptor-backed variable order emitted by the macros, constructs `SearchContext` with the fallible `SearchContext::new`, and returns the selected custom `Search` declaration or canonical defaults. The compiled runtime owns phase preparation, source binding, construction, local search, and terminal lifecycle; no macro-generated phase sequence exists. -- Public solution source methods for all `#[planning_entity_collection]`, `#[problem_fact_collection]`, and streamable `#[planning_list_element_collection]` fields. Each method is inherent on the solution type, for example `Plan::tasks()`, returns the concrete hidden `SourceExtract &[Task]>` wrapper, and carries hidden `ChangeSource::Descriptor(idx)` for planning entities or `ChangeSource::Static` for facts and list elements. User constraints can call the explicit form `ConstraintFactory::new().for_each(Plan::tasks())` or import the generated `PlanConstraintStreams` trait and call `ConstraintFactory::new().tasks()`. Both paths use the same source metadata and concrete stream types. The source methods, the trait and its methods carry generated docs, and the plumbing above is `#[doc(hidden)]`, so a user crate that enables `missing_docs` gets no warnings from generated items. +- Public solution source methods for all `#[planning_entity_collection]`, `#[problem_fact_collection]`, and streamable `#[planning_list_element_collection]` fields. Each method is inherent on the solution type, for example `Plan::tasks()`, returns the concrete hidden `SourceExtract &[Task], ModelPlanningIds>` wrapper for entity and fact collections (so their rows report their `#[planning_id]` in constraint analysis) or `SourceExtract &[usize]>` for list-element collections, and carries hidden `ChangeSource::Descriptor(idx)` for planning entities or `ChangeSource::Static` for facts and list elements. User constraints can call the explicit form `ConstraintFactory::new().for_each(Plan::tasks())` or import the generated `PlanConstraintStreams` trait and call `ConstraintFactory::new().tasks()`. Both paths use the same source metadata and concrete stream types. The source methods, the trait and its methods carry generated docs, and the plumbing above is `#[doc(hidden)]`, so a user crate that enables `missing_docs` gets no warnings from generated items. ### Problem Fact Support Derive @@ -284,6 +285,7 @@ owner. **Generated code:** - `impl ProblemFact for T` — `as_any()` - `impl PlanningId for T` (if `#[planning_id]` present) — same as entity version +- `impl __internal::AnalysisPlanningId for T` (always) — same as entity version - `impl T { #[doc(hidden)] pub fn problem_fact_descriptor(solution_field: &'static str) -> ProblemFactDescriptor }` ## Shared Helper Functions (`entrypoints.rs` / `attr_parse.rs` / `attr_validation.rs`, private) diff --git a/crates/solverforge-macros/src/planning_entity/expand/derive.rs b/crates/solverforge-macros/src/planning_entity/expand/derive.rs index 848a8f183..da960a40a 100644 --- a/crates/solverforge-macros/src/planning_entity/expand/derive.rs +++ b/crates/solverforge-macros/src/planning_entity/expand/derive.rs @@ -384,6 +384,29 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result { TokenStream::new() }; + let analysis_planning_id_impl = if let Some(field) = id_field { + let field_name = field.ident.as_ref().unwrap(); + quote! { + impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause { + fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> { + #[allow(unused_imports)] + use ::solverforge::__internal::{ + RenderPlanningIdDebug as _, RenderPlanningIdDisplay as _, RenderPlanningIdNone as _, + }; + (&&&::solverforge::__internal::RenderPlanningId(&self.#field_name)).render_planning_id() + } + } + } + } else { + quote! { + impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause { + fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> { + ::core::option::Option::None + } + } + } + }; + let id_field_descriptor = if let Some(field) = id_field { let field_name = field.ident.as_ref().unwrap(); quote! { desc = desc.with_id_field(stringify!(#field_name)); } @@ -413,6 +436,8 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result { #planning_id_impl + #analysis_planning_id_impl + impl #impl_generics #name #ty_generics #where_clause { #(#variable_helpers)* #scalar_helpers diff --git a/crates/solverforge-macros/src/planning_solution/stream_extensions.rs b/crates/solverforge-macros/src/planning_solution/stream_extensions.rs index b26a435de..8c6c81388 100644 --- a/crates/solverforge-macros/src/planning_solution/stream_extensions.rs +++ b/crates/solverforge-macros/src/planning_solution/stream_extensions.rs @@ -38,8 +38,11 @@ pub(super) fn generate_collection_source_methods( source_methods.push(quote! { #[doc = concat!("Constraint-stream source over the `", stringify!(#field_name), "` collection.")] - pub fn #field_name() -> ::solverforge::__internal::SourceExtract &[#element_type]> { - ::solverforge::__internal::source( + pub fn #field_name() -> ::solverforge::__internal::SourceExtract< + fn(&Self) -> &[#element_type], + ::solverforge::__internal::ModelPlanningIds, + > { + ::solverforge::__internal::model_source( (|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type], ::solverforge::__internal::ChangeSource::Descriptor(#descriptor_index_lit), ) @@ -60,8 +63,11 @@ pub(super) fn generate_collection_source_methods( let change_source = unowned_change_source("e! { Self }, field_name); source_methods.push(quote! { #[doc = concat!("Constraint-stream source over the `", stringify!(#field_name), "` collection.")] - pub fn #field_name() -> ::solverforge::__internal::SourceExtract &[#element_type]> { - ::solverforge::__internal::source( + pub fn #field_name() -> ::solverforge::__internal::SourceExtract< + fn(&Self) -> &[#element_type], + ::solverforge::__internal::ModelPlanningIds, + > { + ::solverforge::__internal::model_source( (|s: &Self| s.#field_name.as_slice()) as fn(&Self) -> &[#element_type], #change_source, ) @@ -139,10 +145,15 @@ pub(super) fn generate_constraint_stream_extensions( field_name, element_type, change_source, + true, ); } - for f in fact_fields.iter().chain(list_element_fields.iter()) { + let unowned = fact_fields + .iter() + .map(|f| (f, true)) + .chain(list_element_fields.iter().map(|f| (f, false))); + for (f, planning_ids) in unowned { let field_name = match f.ident.as_ref() { Some(n) => n, None => continue, @@ -160,6 +171,7 @@ pub(super) fn generate_constraint_stream_extensions( field_name, element_type, change_source, + planning_ids, ); } @@ -184,12 +196,32 @@ fn push_stream_extension_method( field_name: &Ident, element_type: &syn::Type, change_source: TokenStream, + planning_ids: bool, ) { + // Entity and fact collections hold macro-annotated types, so their rows + // report their `#[planning_id]` in constraint analysis; list-element + // collections hold plain values and report none. + let (source_extract, source_fn) = if planning_ids { + ( + quote! { + ::solverforge::__internal::SourceExtract< + fn(&#solution_name) -> &[#element_type], + ::solverforge::__internal::ModelPlanningIds, + > + }, + quote! { ::solverforge::__internal::model_source }, + ) + } else { + ( + quote! { ::solverforge::__internal::SourceExtract &[#element_type]> }, + quote! { ::solverforge::__internal::source }, + ) + }; let return_type = quote! { ::solverforge::__internal::UniConstraintStream< #solution_name, #element_type, - ::solverforge::__internal::SourceExtract &[#element_type]>, + #source_extract, ::solverforge::__internal::TrueFilter, Sc, > @@ -204,7 +236,7 @@ fn push_stream_extension_method( fn #field_name(self) -> #return_type { ::solverforge::stream::ConstraintFactory::for_each( self, - ::solverforge::__internal::source( + #source_fn( (|s: &#solution_name| s.#field_name.as_slice()) as fn(&#solution_name) -> &[#element_type], #change_source, diff --git a/crates/solverforge-macros/src/planning_solution_tests.rs b/crates/solverforge-macros/src/planning_solution_tests.rs index 3c28aa692..68bf8f1e7 100644 --- a/crates/solverforge-macros/src/planning_solution_tests.rs +++ b/crates/solverforge-macros/src/planning_solution_tests.rs @@ -21,11 +21,12 @@ fn golden_solution_expansion_emits_model_sources_and_descriptor() { assert!(expanded.contains("impl :: solverforge :: __internal :: PlanningSolution for Plan")); assert!(expanded.contains( - "pub fn workers () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Worker] >" + "pub fn workers () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Worker] , :: solverforge :: __internal :: ModelPlanningIds , >" )); assert!(expanded.contains( - "pub fn tasks () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Task] >" + "pub fn tasks () -> :: solverforge :: __internal :: SourceExtract < fn (& Self) -> & [Task] , :: solverforge :: __internal :: ModelPlanningIds , >" )); + assert!(expanded.contains(":: solverforge :: __internal :: model_source (")); assert!(expanded.contains("ChangeSource :: Static")); assert!(expanded.contains("ChangeSource :: Descriptor (0)")); assert!(expanded diff --git a/crates/solverforge-macros/src/problem_fact.rs b/crates/solverforge-macros/src/problem_fact.rs index 5a07686c5..dd19f2c68 100644 --- a/crates/solverforge-macros/src/problem_fact.rs +++ b/crates/solverforge-macros/src/problem_fact.rs @@ -53,6 +53,29 @@ pub fn expand_derive(input: DeriveInput) -> Result { TokenStream::new() }; + let analysis_planning_id_impl = if let Some(field) = id_field { + let field_name = field.ident.as_ref().unwrap(); + quote! { + impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause { + fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> { + #[allow(unused_imports)] + use ::solverforge::__internal::{ + RenderPlanningIdDebug as _, RenderPlanningIdDisplay as _, RenderPlanningIdNone as _, + }; + (&&&::solverforge::__internal::RenderPlanningId(&self.#field_name)).render_planning_id() + } + } + } + } else { + quote! { + impl #impl_generics ::solverforge::__internal::AnalysisPlanningId for #name #ty_generics #where_clause { + fn analysis_planning_id(&self) -> ::core::option::Option<::std::string::String> { + ::core::option::Option::None + } + } + } + }; + let id_field_descriptor = if let Some(field) = id_field { let field_name = field.ident.as_ref().unwrap(); quote! { desc = desc.with_id_field(stringify!(#field_name)); } @@ -67,6 +90,8 @@ pub fn expand_derive(input: DeriveInput) -> Result { #planning_id_impl + #analysis_planning_id_impl + impl #impl_generics #name #ty_generics #where_clause { #[doc(hidden)] pub fn problem_fact_descriptor( diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index f40461a48..9fadb0e58 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -103,10 +103,14 @@ migration of the fluent stream families: - `constraint::relational::OperatorTerminal::new(constraint_ref, impact, operator, weight, hard)` scores a generic operator; its weight takes `(&S, &O::View<'a>)`. It implements incremental scoring, reset, full counts, - and cold explanations. `ExplainRow::explain(&self, entities)` appends the - entities a row view was built from; terminals call it only on the cold - explanation path, and a custom operator implements it for its `View` to make - its matches explainable. + and cold explanations. `ExplainOperator::explain(&self, solution, row, + origin, entities)` appends the entities a row was built from, each with the + planning id its source renders; `origin` (`RowOrigin::Retained(handle)` or + `RowOrigin::Evaluation(&evaluation)`) says where the row came from, so an + operator maps it to the input rows it derives from. Explanation belongs to + the operator, not the row view, because the operator owns the sources. + Terminals call it only on the cold explanation path, and a custom operator + implements it to make its matches explainable. - `stream::joiner::plan::{CompileCondition, IndexedPlan, ExecutablePlan}` separates condition compilation, owned index state, and borrowed-row execution. Candidate probes return `Cow<'i, [RowHandle]>`: equality borrows an exact @@ -313,7 +317,8 @@ src/ │ ├── projected_stream/source/filtered.rs — Row-level filtered projected source │ ├── projected_stream/source/merged.rs — Merged projected sources with source-slot offsets │ ├── projected_stream/source/joined.rs — Cross-join `.project(...)` projected source -│ ├── collection_extract.rs — CollectionExtract trait, hidden source metadata and FilteredExtract membership adapter, source() constructor +│ ├── collection_extract.rs — CollectionExtract trait, hidden source metadata and FilteredExtract membership adapter, source() and model_source() constructors +│ ├── collection_extract/planning_id.rs — Hidden planning-id rendering for analysis: AnalysisPlanningId, SourcePlanningIds, NoPlanningIds, ModelPlanningIds, RenderPlanningId │ ├── 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 @@ -717,10 +722,11 @@ 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 `Debug` entities -(projected `Out` rows excepted: they justify nothing themselves). No stream -requires `Clone` on an entity type. +A shared terminal requires its operator to implement `ExplainOperator`, so +every grouped and complemented builder's `named` requires `Debug` entities. +A projected row is justified by the entities it was projected from (its +coordinate's owners, read from the projected source); its `Out` value needs no +`Debug`. No stream requires `Clone` on an entity type. 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 @@ -749,9 +755,10 @@ Constraints own their `ConstraintRef` once. Metadata and analysis types borrow t **`ConstraintMetadata<'a>`** — `{ constraint_ref: &'a ConstraintRef, is_hard: bool }`; `name()` returns the short constraint name, and `full_name()` returns the package-qualified identity used for exact matching. -**`EntityRef`** — `{ type_name: String, display: String }`: the entity's type name and `Debug` rendering, taken when a match is explained. It keeps no copy of the entity. -- Methods: `new(&T)`, `short_type_name()` -- Implements `Hash + Eq` (by display string) +**`EntityRef`** — `{ type_name: String, display: String, planning_id: Option }`: the entity's type name, `Debug` rendering and planning id, taken when a match is explained. It keeps no copy of the entity. +- `planning_id` is the record's `#[planning_id]` rendered as a string: the id's `Display` output when its type implements `Display` (`7`, `anna`), otherwise its `Debug` output (e.g. a tuple-struct id renders as ShiftId(7)), and `None` for an id type with neither. Equal ids render equally, so it is a lookup key within the entity's type. It is set for entities streamed from planning-model entity and fact collections (`#[planning_entity]` / `#[problem_fact]` types with a `#[planning_id]` field) and `None` otherwise, including for plain values streamed from a hand-built source; stream elements need no new bound. +- Methods: `new(&T)` (no planning id), `with_planning_id(Option)`, `short_type_name()` +- Implements `Hash + Eq` (by all three fields) **`ConstraintJustification`** — `{ entities: Vec, description: String }`. Construct with `new(entities)` or `with_description(entities, description)`. @@ -911,14 +918,17 @@ further joins); low-level constructors are `new_self_join()` and - Method: `fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item]` - Method: `fn contains(&self, s: &S, item: &Self::Item) -> bool` — source-level membership predicate; defaults to `true`, while `UniConstraintStream` delegates to its accumulated source filter. - Required method: `fn change_source(&self) -> ChangeSource` — the descriptor that owns the source's rows, or `Static`. +- Provided method: `fn planning_id(&self, item: &Self::Item) -> Option` — the planning id constraint analysis reports for `item` (see `EntityRef`); read only while explaining a match. Defaults to `None`. - Implemented by `SourceExtract` (generated accessors), `FilteredExtract` and `UniConstraintStream`. -**`SourceExtract`** — Hidden descriptor-aware collection extraction wrapper used by macro-generated solution source methods. It satisfies `CollectionExtract` and preserves source metadata for raw keyed joins. +**`SourceExtract`** — Hidden descriptor-aware collection extraction wrapper used by macro-generated solution source methods. It satisfies `CollectionExtract` and preserves source metadata for raw keyed joins. The zero-sized `I` picks how constraint analysis renders its items' planning ids: `NoPlanningIds` reports none, `ModelPlanningIds` reads the `AnalysisPlanningId` that `#[planning_entity]` and `#[problem_fact]` implement. **`ChangeSource`** — Hidden enum naming which descriptor owns a stream source's rows: `Static` or `Descriptor(idx)`. `Descriptor(idx)` owns localized events for that descriptor; `Static` ignores every descriptor notification. **`source(...)`** — Hidden constructor for descriptor-aware collection extraction used by macro-generated solution source methods. Planning entity collections carry `ChangeSource::Descriptor(idx)`; static fact and list-element collections carry `ChangeSource::Static`. This symbol is not part of the facade stream workflow. +**`model_source(...)`** — Hidden constructor like `source(...)` whose items report their `#[planning_id]` in constraint analysis (`SourceExtract`). Generated entity and fact collection accessors use it; list-element collections, which hold plain values, use `source(...)`. + **`FlattenExtract

`** — Trait for flattening a parent entity into a child slice for existence filtering. Blanket impl for `Fn(&P) -> &[B] + Send + Sync`; `FlattenVecExtract` adapts `Fn(&P) -> &Vec`. **`ExistenceTarget`** — Trait for `.if_exists(...)` / `.if_not_exists(...)` dispatch on `UniConstraintStream`. diff --git a/crates/solverforge-scoring/public-api.txt b/crates/solverforge-scoring/public-api.txt index cfd7374e1..ca8272fd3 100644 --- a/crates/solverforge-scoring/public-api.txt +++ b/crates/solverforge-scoring/public-api.txt @@ -7,8 +7,9 @@ struct api::analysis::ConstraintJustification: pub struct ConstraintJustificatio api::analysis::ConstraintJustification: pub fn with_description(entities: Vec, description: String) -> Self struct api::analysis::DetailedConstraintMatch: pub struct DetailedConstraintMatch<'a, Sc: Score> { pub constraint_ref: &'a ConstraintRef, pub score: Sc, pub justification: ConstraintJustification, } api::analysis::DetailedConstraintMatch: pub fn new( constraint_ref: &'a ConstraintRef, score: Sc, justification: ConstraintJustification, ) -> Self -struct api::analysis::EntityRef: pub struct EntityRef { pub type_name: String, pub display: String, } +struct api::analysis::EntityRef: pub struct EntityRef { pub type_name: String, pub display: String, pub planning_id: Option, } api::analysis::EntityRef: pub fn new(entity: &T) -> Self + api::analysis::EntityRef: pub fn with_planning_id(self, planning_id: Option) -> Self api::analysis::EntityRef: pub fn short_type_name(&self) -> &str struct api::constraint_set::ConstraintMetadata: pub struct ConstraintMetadata<'a> { pub constraint_ref: &'a ConstraintRef, pub is_hard: bool, } api::constraint_set::ConstraintMetadata: pub fn new(constraint_ref: &'a ConstraintRef, is_hard: bool) -> Self @@ -541,11 +542,12 @@ trait stream::ProjectionSink: pub trait ProjectionSink { // Required method stream::ProjectionSink: fn emit(&mut self, output: Out) trait stream::UnassignedEntity: pub trait UnassignedEntity: Clone + Send + Sync + 'static { // Required method fn is_unassigned(solution: &S, entity: &Self) -> bool; } stream::UnassignedEntity: fn is_unassigned(solution: &S, entity: &Self) -> bool -trait stream::collection_extract::CollectionExtract: pub trait CollectionExtract: Send + Sync { type Item; // Required methods fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item]; fn change_source(&self) -> ChangeSource; // Provided method fn contains(&self, _s: &S, _item: &Self::Item) -> bool { ... } } +trait stream::collection_extract::CollectionExtract: pub trait CollectionExtract: Send + Sync { type Item; // Required methods fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item]; fn change_source(&self) -> ChangeSource; // Provided methods fn contains(&self, _s: &S, _item: &Self::Item) -> bool { ... } fn planning_id(&self, _item: &Self::Item) -> Option { ... } } stream::collection_extract::CollectionExtract: type Item stream::collection_extract::CollectionExtract: fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item] stream::collection_extract::CollectionExtract: fn change_source(&self) -> ChangeSource stream::collection_extract::CollectionExtract: fn contains(&self, _s: &S, _item: &Self::Item) -> bool + stream::collection_extract::CollectionExtract: fn planning_id(&self, _item: &Self::Item) -> Option trait stream::collection_extract::FlattenExtract: pub trait FlattenExtract

: Send + Sync { type Item; // Required method fn extract<'s>(&self, parent: &'s P) -> &'s [Self::Item]; } stream::collection_extract::FlattenExtract: type Item stream::collection_extract::FlattenExtract: fn extract<'s>(&self, parent: &'s P) -> &'s [Self::Item] diff --git a/crates/solverforge-scoring/src/api/analysis.rs b/crates/solverforge-scoring/src/api/analysis.rs index eaf9ac9e1..a02aeec00 100644 --- a/crates/solverforge-scoring/src/api/analysis.rs +++ b/crates/solverforge-scoring/src/api/analysis.rs @@ -9,26 +9,47 @@ use solverforge_core::score::Score; use solverforge_core::ConstraintRef; /// An entity involved in a constraint match, as constraint analysis reports -/// it: the entity's type name and its `Debug` rendering, taken when the match -/// is explained. It holds no copy of the entity, so explaining a match -/// requires only `Debug` on the entity type. +/// it: the entity's type name, its `Debug` rendering and, when its type has a +/// `#[planning_id]`, its planning id, all taken when the match is explained. +/// It holds no copy of the entity, so explaining a match requires only +/// `Debug` on the entity type. #[derive(Clone, PartialEq, Eq, Hash)] pub struct EntityRef { /// Type name of the entity (e.g., "Shift", "Employee"). pub type_name: String, - /// String representation for display. + /// String representation for display. It is a rendering, not an + /// identifier: look records up by [`planning_id`](Self::planning_id). pub display: String, + /// The entity's planning id, rendered as a string: the id's `Display` + /// output when its type implements `Display` (`7`, `shift-7`), otherwise + /// its `Debug` output (`ShiftId(7)`). Equal ids render equally, so it is + /// a lookup key for the record within its type. + /// + /// Set for entities streamed from a planning model collection whose type + /// has a `#[planning_id]` field (`#[planning_entity]`, `#[problem_fact]`); + /// `None` for every other entity, including plain values streamed through + /// a hand-built source. + pub planning_id: Option, } impl EntityRef { - /// Describes `entity` by its type name and `Debug` rendering. + /// Describes `entity` by its type name and `Debug` rendering, with no + /// planning id. pub fn new(entity: &T) -> Self { Self { type_name: std::any::type_name::().to_string(), display: format!("{entity:?}"), + planning_id: None, } } + /// Sets the entity's rendered planning id (see + /// [`planning_id`](Self::planning_id)). + pub fn with_planning_id(mut self, planning_id: Option) -> Self { + self.planning_id = planning_id; + self + } + /// Returns the short type name (without module path). pub fn short_type_name(&self) -> &str { self.type_name @@ -43,6 +64,7 @@ impl Debug for EntityRef { f.debug_struct("EntityRef") .field("type", &self.short_type_name()) .field("display", &self.display) + .field("planning_id", &self.planning_id) .finish() } } diff --git a/crates/solverforge-scoring/src/constraint/incremental.rs b/crates/solverforge-scoring/src/constraint/incremental.rs index d294c48a0..c1113722f 100644 --- a/crates/solverforge-scoring/src/constraint/incremental.rs +++ b/crates/solverforge-scoring/src/constraint/incremental.rs @@ -198,7 +198,8 @@ where .iter() .filter(|e| self.matches(solution, e)) .map(|entity| { - let entity_ref = EntityRef::new(entity); + let entity_ref = + EntityRef::new(entity).with_planning_id(self.extractor.planning_id(entity)); let justification = ConstraintJustification::new(vec![entity_ref]); DetailedConstraintMatch::new(cref, self.compute_delta(entity), justification) }) diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs b/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs index 803814486..d318c492c 100644 --- a/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs +++ b/crates/solverforge-scoring/src/constraint/relational/operator_scorer.rs @@ -13,7 +13,7 @@ use crate::api::{ scale_contribution, scale_contribution_parts, ConstraintMetadata, ConstraintResult, }, }; -use crate::stream::relational::operator::{ExplainRow, Operator}; +use crate::stream::relational::operator::{ExplainOperator, Operator}; use crate::stream::relational::{HandleMap, RowHandle}; mod matches; @@ -156,8 +156,7 @@ where impl OperatorScorerSet for OperatorScorer where S: Send + Sync + 'static, - O: Operator + Send + Sync, - for<'r> O::View<'r>: ExplainRow, + O: ExplainOperator + Send + Sync, W: RowWeight, Sc: Score, { diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs index 3d86a16d7..733f83289 100644 --- a/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs +++ b/crates/solverforge-scoring/src/constraint/relational/operator_scorer/matches.rs @@ -6,17 +6,18 @@ 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}; +use crate::stream::relational::operator::{ExplainOperator, Operator, RowOrigin}; impl OperatorScorer { - /// Visits each row of `operator` with its signed score: the retained - /// rows and scores once the operator holds rows, a full evaluation of - /// `solution` before that, like [`OperatorScorerSet::evaluate`]. + /// Visits each row of `operator` with its origin and signed score: the + /// retained rows and scores once the operator holds rows, a full + /// evaluation of `solution` before that, like + /// [`OperatorScorerSet::evaluate`]. fn visit_scored( &self, operator: &O, solution: &S, - mut visit: impl FnMut(&O::View<'_>, Sc), + mut visit: impl FnMut(&O::View<'_>, RowOrigin<'_, O::Evaluation>, Sc), ) where S: 'static, O: Operator, @@ -24,8 +25,13 @@ impl OperatorScorer { { let handles = operator.handles(); if handles.is_empty() { - operator.visit_all(solution, &mut |row| { - visit(&row, self.signed(self.weight.score(solution, &row))); + let evaluation = operator.prepare_evaluation(solution); + operator.visit_evaluation(solution, &evaluation, &mut |row| { + visit( + &row, + RowOrigin::Evaluation(&evaluation), + self.signed(self.weight.score(solution, &row)), + ); }); } else { for handle in handles { @@ -36,7 +42,7 @@ impl OperatorScorer { Some(weight) => *weight, None => self.weight.score(solution, &row), }; - visit(&row, self.signed(weight)); + visit(&row, RowOrigin::Retained(handle), self.signed(weight)); } } } @@ -52,18 +58,17 @@ impl OperatorScorer { ) -> Vec> where S: 'static, - O: Operator, + O: ExplainOperator, W: RowWeight, - for<'r> O::View<'r>: ExplainRow, { let mut matches = Vec::new(); - self.visit_scored(operator, solution, |row, score| { + self.visit_scored(operator, solution, |row, origin, score| { if score == Sc::zero() { return; } let score = scale_contribution(score, multiplier); let mut entities = Vec::new(); - row.explain(&mut entities); + operator.explain(solution, row, origin, &mut entities); matches.push(DetailedConstraintMatch::new( &self.constraint_ref, score, diff --git a/crates/solverforge-scoring/src/constraint/relational/operator_terminal.rs b/crates/solverforge-scoring/src/constraint/relational/operator_terminal.rs index 6733a8791..f4067b31c 100644 --- a/crates/solverforge-scoring/src/constraint/relational/operator_terminal.rs +++ b/crates/solverforge-scoring/src/constraint/relational/operator_terminal.rs @@ -4,7 +4,7 @@ use crate::api::{ }; use crate::constraint::score_sum::{checked, ScoreSum}; use crate::stream::relational::{ - operator::{ExplainRow, Operator}, + operator::{ExplainOperator, Operator, RowOrigin}, HandleMap, RowHandle, }; use solverforge_core::{score::Score, ConstraintRef, ImpactType}; @@ -101,7 +101,7 @@ where O: Operator + Send + Sync, W: for<'a> Fn(&S, &O::View<'a>) -> Sc + Send + Sync, Sc: Score, - for<'a> O::View<'a>: ExplainRow, + O: ExplainOperator, { fn evaluate(&self, solution: &S) -> Sc { let mut score = ScoreSum::new(); @@ -196,9 +196,9 @@ where } fn get_matches<'a>(&'a self, solution: &S) -> Vec> { let mut matches = Vec::new(); - let mut record = |row: O::View<'_>, score| { + let mut record = |row: O::View<'_>, origin: RowOrigin<'_, O::Evaluation>, score| { let mut entities = Vec::new(); - row.explain(&mut entities); + self.operator.explain(solution, &row, origin, &mut entities); matches.push(DetailedConstraintMatch::new( &self.constraint_ref, score, @@ -213,13 +213,17 @@ where .expect("live explanation row"); record( row, + RowOrigin::Retained(handle), self.signed_checked(*self.scores.get(handle).expect("live terminal score")), ); } } else { - self.operator.visit_all(solution, &mut |row| { - record(row, self.signed_checked((self.weight)(solution, &row))); - }); + let evaluation = self.operator.prepare_evaluation(solution); + self.operator + .visit_evaluation(solution, &evaluation, &mut |row| { + let score = self.signed_checked((self.weight)(solution, &row)); + record(row, RowOrigin::Evaluation(&evaluation), score); + }); } matches } diff --git a/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs b/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs index 3859b895e..aae6490d7 100644 --- a/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs +++ b/crates/solverforge-scoring/src/constraint/relational/shared_terminal.rs @@ -13,7 +13,7 @@ use crate::api::{ SingleConstraint, }, }; -use crate::stream::relational::operator::{ExplainRow, GroupedOperator}; +use crate::stream::relational::operator::{ExplainOperator, GroupedOperator}; use crate::stream::relational::RowHandle; /// Scoring terminal that owns one operator tree and scores it for several named @@ -421,8 +421,7 @@ impl IncrementalConstraint for SharedOperatorTerminal, Sc> where S: Send + Sync + 'static, - O: GroupedOperator + Send + Sync, - for<'r> O::View<'r>: ExplainRow, + O: GroupedOperator + ExplainOperator + Send + Sync, A: Send + Sync, W: RowWeight, Sc: Score, diff --git a/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs b/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs index fd5d11378..ea9c1a51e 100644 --- a/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs +++ b/crates/solverforge-scoring/src/constraint/tests/grouped_analysis.rs @@ -17,7 +17,7 @@ use solverforge_core::score::SoftScore; use crate::api::analysis::DetailedConstraintMatch; use crate::api::constraint_set::{ConstraintSet, IncrementalConstraint}; -use crate::stream::collection_extract::{source, ChangeSource}; +use crate::stream::collection_extract::{source, ChangeSource, SourceExtract, SourcePlanningIds}; use crate::stream::collector::{count, sum}; use crate::stream::joiner::equal_bi; use crate::stream::ConstraintFactory; @@ -311,3 +311,72 @@ fn shared_grouped_terminals_each_report_their_matches_under_their_multiplier() { "a disabled terminal still names its groups, at score zero" ); } + +struct ShiftIds; + +impl SourcePlanningIds for ShiftIds { + fn planning_id(shift: &Shift) -> Option { + Some(format!("shift-{}", shift.id)) + } +} + +#[test] +fn shared_grouped_terminals_report_their_contributors_planning_ids() { + let shifts_with_ids: SourceExtract &[Shift], ShiftIds> = SourceExtract::new( + shifts as fn(&Roster) -> &[Shift], + ChangeSource::Descriptor(0), + ); + let mut constraints = factory() + .for_each(shifts_with_ids) + .group_by(nurse_key, count()) + .penalize(|_nurse: &usize, shifts: &usize| SoftScore::of(shifts.saturating_sub(1) as i64)) + .named("Shifts beyond one") + .reward(|nurse: &usize, shifts: &usize| { + SoftScore::of(if *nurse == UNASSIGNED { + 0 + } else { + *shifts as i64 + }) + }) + .named("Assigned shifts"); + let plan = roster(); + let planning_ids = |analysis: &crate::api::analysis::ConstraintAnalysis<'_, SoftScore>| { + let mut rows = analysis + .matches + .iter() + .map(|detailed| { + detailed + .justification + .entities + .iter() + .map(|entity| entity.planning_id.clone().unwrap_or_default()) + .collect::>() + }) + .collect::>(); + rows.sort(); + rows + }; + let expected = [ + vec![vec!["shift-0".to_string(), "shift-1".to_string()]], + vec![ + vec!["shift-0".to_string(), "shift-1".to_string()], + vec!["shift-2".to_string()], + ], + ]; + + // Before initialization (a full evaluation) and after it (retained rows). + for initialized in [false, true] { + if initialized { + constraints.initialize_all(&plan); + } + let analyses = constraints.evaluate_detailed(&plan); + for (analysis, expected) in analyses.iter().zip(&expected) { + assert_eq!(match_sum(&analysis.matches), analysis.score); + assert_eq!( + &planning_ids(analysis), + expected, + "initialized: {initialized}" + ); + } + } +} diff --git a/crates/solverforge-scoring/src/constraint/tests/mod.rs b/crates/solverforge-scoring/src/constraint/tests/mod.rs index 6a1ed4654..b70760ee5 100644 --- a/crates/solverforge-scoring/src/constraint/tests/mod.rs +++ b/crates/solverforge-scoring/src/constraint/tests/mod.rs @@ -9,6 +9,7 @@ mod flattened_bi; mod grouped; mod grouped_analysis; mod overflow; +mod planning_id_analysis; mod projected; mod relational; mod weights; diff --git a/crates/solverforge-scoring/src/constraint/tests/planning_id_analysis.rs b/crates/solverforge-scoring/src/constraint/tests/planning_id_analysis.rs new file mode 100644 index 000000000..f3ebb1f64 --- /dev/null +++ b/crates/solverforge-scoring/src/constraint/tests/planning_id_analysis.rs @@ -0,0 +1,293 @@ +/* Planning ids in constraint analysis. + +Every entity a match names carries the planning id its source renders: here +`shift-` and `nurse-` from test renderings, and none from a plain +source. Each operator family must hand the right source row to the +explanation, on both explanation paths: a full evaluation before +initialization, and the retained rows after it, including after a mutation +has moved rows around. Match scores keep summing to the constraint's score. + +Roster: nurse 0 works shifts 0 and 1 (day 0), nurse 1 works shift 2 (day 1), +shift 3 is unassigned (day 1). Nurse 1 is unavailable on day 1. +*/ + +use solverforge_core::score::SoftScore; + +use crate::api::analysis::DetailedConstraintMatch; +use crate::api::constraint_set::IncrementalConstraint; +use crate::stream::collection_extract::{source, ChangeSource, SourceExtract, SourcePlanningIds}; +use crate::stream::collector::count; +use crate::stream::joiner::{equal, equal_bi}; +use crate::stream::ConstraintFactory; + +#[derive(Debug)] +struct Nurse { + id: usize, + unavailable_days: Vec, +} + +// The self-join stream keys its pairs by entity, so shifts are `Hash + Eq`. +#[derive(Debug, Hash, PartialEq, Eq)] +struct Shift { + id: usize, + day: usize, + nurse: Option, +} + +struct Roster { + shifts: Vec, + nurses: Vec, +} + +struct ShiftIds; + +impl SourcePlanningIds for ShiftIds { + fn planning_id(shift: &Shift) -> Option { + Some(format!("shift-{}", shift.id)) + } +} + +struct NurseIds; + +impl SourcePlanningIds for NurseIds { + fn planning_id(nurse: &Nurse) -> Option { + Some(format!("nurse-{}", nurse.id)) + } +} + +fn shifts(roster: &Roster) -> &[Shift] { + roster.shifts.as_slice() +} + +fn nurses(roster: &Roster) -> &[Nurse] { + roster.nurses.as_slice() +} + +fn shift_source() -> SourceExtract &[Shift], ShiftIds> { + SourceExtract::new( + shifts as fn(&Roster) -> &[Shift], + ChangeSource::Descriptor(0), + ) +} + +fn nurse_source() -> SourceExtract &[Nurse], NurseIds> { + SourceExtract::new( + nurses as fn(&Roster) -> &[Nurse], + ChangeSource::Descriptor(1), + ) +} + +fn roster() -> Roster { + let shift = |id, day, nurse| Shift { id, day, nurse }; + Roster { + shifts: vec![ + shift(0, 0, Some(0)), + shift(1, 0, Some(0)), + shift(2, 1, Some(1)), + shift(3, 1, None), + ], + nurses: vec![ + Nurse { + id: 0, + unavailable_days: Vec::new(), + }, + Nurse { + id: 1, + unavailable_days: vec![1], + }, + ], + } +} + +fn factory() -> ConstraintFactory { + ConstraintFactory::::new() +} + +/// Each match as (score, planning ids of its entities), sorted. +fn ids(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> Vec<(i64, Vec>)> { + let mut rows = matches + .iter() + .map(|detailed| { + ( + detailed.score.score(), + detailed + .justification + .entities + .iter() + .map(|entity| entity.planning_id.clone()) + .collect(), + ) + }) + .collect::>(); + rows.sort(); + rows +} + +fn id(name: &str) -> Option { + Some(name.to_string()) +} + +fn match_sum(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> SoftScore { + matches + .iter() + .fold(SoftScore::of(0), |total, detailed| total + detailed.score) +} + +/// Matches carry `expected` ids before and after initialization, and +/// `moved` ids after shift 1 moves from nurse 0 to nurse 1 on day 1. +fn assert_ids( + mut constraint: C, + expected: Vec<(i64, Vec>)>, + moved: Vec<(i64, Vec>)>, +) where + C: IncrementalConstraint, +{ + let mut plan = roster(); + let before = constraint.get_matches(&plan); + assert_eq!(match_sum(&before), constraint.evaluate(&plan)); + assert_eq!(ids(&before), expected, "before initialization"); + drop(before); + + let total = constraint.initialize(&plan); + let after = constraint.get_matches(&plan); + assert_eq!(match_sum(&after), total); + assert_eq!(ids(&after), expected, "after initialization"); + drop(after); + + constraint.on_retract(&plan, 1, 0); + plan.shifts[1].nurse = Some(1); + plan.shifts[1].day = 1; + constraint.on_insert(&plan, 1, 0); + let after_move = constraint.get_matches(&plan); + assert_eq!(match_sum(&after_move), constraint.evaluate(&plan)); + assert_eq!(ids(&after_move), moved, "after the move"); +} + +#[test] +fn filtered_entities_report_their_planning_id() { + let constraint = factory() + .for_each(shift_source()) + .filter(|shift: &Shift| shift.nurse.is_none()) + .penalize(SoftScore::of(1)) + .named("Unassigned shift"); + assert_ids( + constraint, + vec![(-1, vec![id("shift-3")])], + vec![(-1, vec![id("shift-3")])], + ); +} + +#[test] +fn plain_sources_report_no_planning_id() { + let constraint = factory() + .for_each(source( + shifts as fn(&Roster) -> &[Shift], + ChangeSource::Descriptor(0), + )) + .filter(|shift: &Shift| shift.nurse.is_none()) + .penalize(SoftScore::of(1)) + .named("Unassigned shift"); + assert_ids(constraint, vec![(-1, vec![None])], vec![(-1, vec![None])]); +} + +#[test] +fn self_joined_pairs_report_both_planning_ids() { + let constraint = factory() + .for_each(shift_source()) + .join(equal(|shift: &Shift| (shift.day, shift.nurse))) + .filter(|left: &Shift, right: &Shift| left.nurse.is_some() && left.id < right.id) + .penalize(SoftScore::of(1)) + .named("Two shifts on one day"); + assert_ids( + constraint, + vec![(-1, vec![id("shift-0"), id("shift-1")])], + vec![(-1, vec![id("shift-1"), id("shift-2")])], + ); +} + +#[test] +fn cross_joined_pairs_report_both_planning_ids() { + let constraint = factory() + .for_each(shift_source()) + .join(( + nurse_source(), + equal_bi(|shift: &Shift| shift.nurse, |nurse: &Nurse| Some(nurse.id)), + )) + .filter(|shift: &Shift, nurse: &Nurse| nurse.unavailable_days.contains(&shift.day)) + .penalize(SoftScore::of(1)) + .named("Shift on an unavailable day"); + assert_ids( + constraint, + vec![(-1, vec![id("shift-2"), id("nurse-1")])], + vec![ + (-1, vec![id("shift-1"), id("nurse-1")]), + (-1, vec![id("shift-2"), id("nurse-1")]), + ], + ); +} + +#[test] +fn existence_filtered_entities_report_their_planning_id() { + let constraint = factory() + .for_each(shift_source()) + .if_exists(( + factory() + .for_each(nurse_source()) + .filter(|nurse: &Nurse| !nurse.unavailable_days.is_empty()), + equal_bi(|shift: &Shift| shift.nurse, |nurse: &Nurse| Some(nurse.id)), + )) + .penalize(SoftScore::of(1)) + .named("Shift of a nurse with unavailable days"); + assert_ids( + constraint, + vec![(-1, vec![id("shift-2")])], + vec![(-1, vec![id("shift-1")]), (-1, vec![id("shift-2")])], + ); +} + +#[test] +fn flattened_pairs_report_the_owners_planning_ids() { + let constraint = factory() + .for_each(shift_source()) + .join(( + nurse_source(), + equal_bi(|shift: &Shift| shift.nurse, |nurse: &Nurse| Some(nurse.id)), + )) + .flatten_last( + |nurse: &Nurse| nurse.unavailable_days.as_slice(), + |day: &usize| *day, + |shift: &Shift| shift.day, + ) + .penalize(SoftScore::of(1)) + .named("Shift on an unavailable day (flattened)"); + assert_ids( + constraint, + vec![(-1, vec![id("shift-2"), id("nurse-1")])], + vec![ + (-1, vec![id("shift-1"), id("nurse-1")]), + (-1, vec![id("shift-2"), id("nurse-1")]), + ], + ); +} + +#[test] +fn groups_and_complements_report_their_contributors_planning_ids() { + let constraint = factory() + .for_each(shift_source()) + .group_by(|shift: &Shift| shift.nurse.unwrap_or(usize::MAX), count()) + .complement(nurse_source(), |nurse: &Nurse| nurse.id, |_nurse| 0usize) + .penalize(|_nurse: &usize, shifts: &usize| SoftScore::of(*shifts as i64)) + .named("Shifts per nurse"); + assert_ids( + constraint, + vec![ + (-2, vec![id("nurse-0"), id("shift-0"), id("shift-1")]), + (-1, vec![id("nurse-1"), id("shift-2")]), + ], + // Contributors keep contribution order: shift 1 joined nurse 1 last. + vec![ + (-2, vec![id("nurse-1"), id("shift-2"), id("shift-1")]), + (-1, vec![id("nurse-0"), id("shift-0")]), + ], + ); +} diff --git a/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs b/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs index edf7f2adb..f9ad6dc34 100644 --- a/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs +++ b/crates/solverforge-scoring/src/constraint/tests/projected/analysis.rs @@ -1,13 +1,26 @@ /* Constraint analysis of projected grouped and complemented constraints. -Projected rows carry no entity of their own, so a projected group justifies -itself with nothing beyond its complement target; what must hold is one match -per group whose weight is not zero, with match scores summing to the -constraint's score before and after initialization. +A projected row is justified by the entities it was projected from, read +through its source, so a projected group names the work items that feed it +(with their planning ids) and a complemented group adds its target first. The +match scores must sum to the constraint's score before and after +initialization. + +Work rows report the planning id `work--`; capacity rows come +from a plain source and report none. */ use super::support::*; use crate::api::analysis::DetailedConstraintMatch; +use crate::stream::collection_extract::{SourceExtract, SourcePlanningIds}; + +struct WorkIds; + +impl SourcePlanningIds for WorkIds { + fn planning_id(work: &Work) -> Option { + Some(format!("work-{}-{}", work.bucket, work.demand)) + } +} fn plan() -> Plan { Plan { @@ -41,13 +54,26 @@ fn plan() -> Plan { } } -fn scores(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> Vec<(i64, usize)> { +fn work_source() -> SourceExtract &[Work], WorkIds> { + SourceExtract::new(work as fn(&Plan) -> &[Work], ChangeSource::Descriptor(0)) +} + +/// One justification entity: its display and planning id. +type Entity = (String, Option); + +/// Each match as (score, justification entities), sorted. +fn summary(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> Vec<(i64, Vec)> { let mut rows = matches .iter() .map(|detailed| { ( detailed.score.score(), - detailed.justification.entities.len(), + detailed + .justification + .entities + .iter() + .map(|entity| (entity.display.clone(), entity.planning_id.clone())) + .collect(), ) }) .collect::>(); @@ -61,28 +87,47 @@ fn match_sum(matches: &[DetailedConstraintMatch<'_, SoftScore>]) -> SoftScore { .fold(SoftScore::of(0), |total, detailed| total + detailed.score) } -fn assert_matches(mut constraint: C, expected: Vec<(i64, usize)>) +fn work_entity(bucket: usize, demand: i64) -> Entity { + let work = Work { + bucket, + demand, + enabled: true, + }; + (format!("{work:?}"), Some(format!("work-{bucket}-{demand}"))) +} + +fn capacity_entity(bucket: usize) -> Entity { + ( + format!( + "{:?}", + Capacity { + bucket, + capacity: 0 + } + ), + None, + ) +} + +fn assert_matches(mut constraint: C, expected: Vec<(i64, Vec)>) where C: IncrementalConstraint, { let plan = plan(); let before = constraint.get_matches(&plan); assert_eq!(match_sum(&before), constraint.evaluate(&plan)); - assert_eq!(scores(&before), expected, "before initialization"); + assert_eq!(summary(&before), expected, "before initialization"); drop(before); let total = constraint.initialize(&plan); let after = constraint.get_matches(&plan); assert_eq!(match_sum(&after), total); - assert_eq!(scores(&after), expected, "after initialization"); + assert_eq!(summary(&after), expected, "after initialization"); } #[test] -fn projected_grouped_constraint_reports_each_costly_group() { +fn projected_grouped_constraint_reports_each_costly_group_with_its_owners() { let constraint = ConstraintFactory::::new() - .for_each(source( - work as fn(&Plan) -> &[Work], - ChangeSource::Descriptor(0), - )) + .for_each(work_source()) .project(WorkEntryProjection) .group_by( |entry: &Entry| entry.bucket, @@ -91,16 +136,13 @@ fn projected_grouped_constraint_reports_each_costly_group() { .penalize(|_bucket: &usize, demand: &i64| SoftScore::of(*demand)) .named("projected demand"); // bucket 0: 5; bucket 1: 2 - 2 = 0, no match. - assert_matches(constraint, vec![(-5, 0)]); + assert_matches(constraint, vec![(-5, vec![work_entity(0, 5)])]); } #[test] -fn projected_complemented_constraint_justifies_each_group_by_its_target() { +fn projected_complemented_constraint_justifies_each_group_by_its_target_and_owners() { let constraint = ConstraintFactory::::new() - .for_each(source( - work as fn(&Plan) -> &[Work], - ChangeSource::Descriptor(0), - )) + .for_each(work_source()) .project(WorkEntryProjection) .group_by( |entry: &Entry| entry.bucket, @@ -118,5 +160,11 @@ fn projected_complemented_constraint_justifies_each_group_by_its_target() { .named("projected demand per capacity"); // capacity bucket 0: real 5; capacity bucket 2: default 3. Bucket 1 has // no capacity row, so it is no complemented row at all. - assert_matches(constraint, vec![(-5, 1), (-3, 1)]); + assert_matches( + constraint, + vec![ + (-5, vec![capacity_entity(0), work_entity(0, 5)]), + (-3, vec![capacity_entity(2)]), + ], + ); } diff --git a/crates/solverforge-scoring/src/stream/chain_stream.rs b/crates/solverforge-scoring/src/stream/chain_stream.rs index 72ec35d82..de4cd09d8 100644 --- a/crates/solverforge-scoring/src/stream/chain_stream.rs +++ b/crates/solverforge-scoring/src/stream/chain_stream.rs @@ -162,7 +162,7 @@ where O: Operator + Send + Sync, W: for<'a> Fn(&S, &O::View<'a>) -> Sc + Send + Sync, Sc: Score + 'static, - for<'a> O::View<'a>: super::relational::operator::ExplainRow, + O: super::relational::operator::ExplainOperator, { /// Marks the constraint hard. pub fn hard(mut self) -> Self { diff --git a/crates/solverforge-scoring/src/stream/collection_extract.rs b/crates/solverforge-scoring/src/stream/collection_extract.rs index 605b7db4a..0f6f0b51e 100644 --- a/crates/solverforge-scoring/src/stream/collection_extract.rs +++ b/crates/solverforge-scoring/src/stream/collection_extract.rs @@ -7,6 +7,16 @@ //! changes. A raw closure or `fn` item carries no such identity and is not a //! source. +use std::marker::PhantomData; + +mod planning_id; + +#[doc(hidden)] +pub use planning_id::{ + AnalysisPlanningId, ModelPlanningIds, NoPlanningIds, RenderPlanningId, RenderPlanningIdDebug, + RenderPlanningIdDisplay, RenderPlanningIdNone, SourcePlanningIds, +}; + /// Extracts a slice of entities from the solution. /// /// The associated type `Item` names the entity type, allowing callers to @@ -33,6 +43,15 @@ pub trait CollectionExtract: Send + Sync { /// planning-variable change can alter them. Macro-generated solution source /// methods attach it through hidden internal support. fn change_source(&self) -> ChangeSource; + + /// The planning id constraint analysis reports for `item`, rendered as + /// described on [`EntityRef::planning_id`](crate::api::analysis::EntityRef::planning_id). + /// Read only while explaining a match, never while scoring. Planning-model + /// entity and fact collections report their `#[planning_id]`; the default + /// reports none. + fn planning_id(&self, _item: &Self::Item) -> Option { + None + } } /// Preserves a unary stream's membership at the source boundary, before @@ -68,6 +87,10 @@ where fn change_source(&self) -> ChangeSource { self.extractor.change_source() } + + fn planning_id(&self, item: &Self::Item) -> Option { + self.extractor.planning_id(item) + } } #[doc(hidden)] @@ -126,18 +149,34 @@ where } } +/// A collection source: the slice accessor, the descriptor that owns its +/// rows, and, in `I`, how analysis renders its items' planning ids (a +/// zero-sized [`SourcePlanningIds`] choice, so it adds nothing to the source). #[doc(hidden)] -#[derive(Clone, Copy)] -pub struct SourceExtract { +pub struct SourceExtract { extractor: E, change_source: ChangeSource, + planning_ids: PhantomData I>, } -impl SourceExtract { +impl Clone for SourceExtract { + fn clone(&self) -> Self { + Self { + extractor: self.extractor.clone(), + change_source: self.change_source, + planning_ids: PhantomData, + } + } +} + +impl Copy for SourceExtract {} + +impl SourceExtract { pub fn new(extractor: E, change_source: ChangeSource) -> Self { Self { extractor, change_source, + planning_ids: PhantomData, } } @@ -146,9 +185,10 @@ impl SourceExtract { } } -impl CollectionExtract for SourceExtract +impl CollectionExtract for SourceExtract where E: for<'a> Fn(&'a S) -> &'a [A] + Send + Sync, + I: SourcePlanningIds, { type Item = A; @@ -160,9 +200,23 @@ where fn change_source(&self) -> ChangeSource { self.change_source } + + fn planning_id(&self, item: &A) -> Option { + I::planning_id(item) + } } #[doc(hidden)] pub fn source(extractor: E, change_source: ChangeSource) -> SourceExtract { SourceExtract::new(extractor, change_source) } + +/// A planning-model entity or fact collection source: like [`source`], and +/// its items report their `#[planning_id]` in constraint analysis. +#[doc(hidden)] +pub fn model_source( + extractor: E, + change_source: ChangeSource, +) -> SourceExtract { + SourceExtract::new(extractor, change_source) +} diff --git a/crates/solverforge-scoring/src/stream/collection_extract/planning_id.rs b/crates/solverforge-scoring/src/stream/collection_extract/planning_id.rs new file mode 100644 index 000000000..c65aae483 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/collection_extract/planning_id.rs @@ -0,0 +1,111 @@ +//! Planning-id rendering for constraint analysis: how a stream source names +//! the record behind each of its items. +//! +//! The macros pick the rendering for each planning-model collection: +//! entity and fact collections render through [`ModelPlanningIds`], which +//! reads the [`AnalysisPlanningId`] that `#[planning_entity]` and +//! `#[problem_fact]` implement for every type they annotate; every other +//! source renders through [`NoPlanningIds`]. Both are zero-sized, so a source +//! carries its rendering in its type and no stream element needs a new bound. +//! Nothing here runs while scoring. + +use std::fmt::{Debug, Display}; +use std::marker::PhantomData; + +#[cfg(test)] +mod tests; + +/// The planning id an annotated model type reports in constraint analysis: +/// its `#[planning_id]` field rendered as a string, or `None` when the type +/// has no `#[planning_id]` field. +/// +/// `#[planning_entity]` and `#[problem_fact]` implement it for every type +/// they annotate. +#[doc(hidden)] +pub trait AnalysisPlanningId { + /// The rendered planning id, or `None` when the type has none. + fn analysis_planning_id(&self) -> Option; +} + +/// How a source renders the planning id of one of its items. +#[doc(hidden)] +pub trait SourcePlanningIds: Send + Sync + 'static { + /// The item's rendered planning id, or `None`. + fn planning_id(item: &A) -> Option; +} + +/// Rendering for sources whose items have no planning id. +#[doc(hidden)] +pub struct NoPlanningIds(PhantomData); + +impl SourcePlanningIds for NoPlanningIds { + #[inline] + fn planning_id(_item: &A) -> Option { + None + } +} + +/// Rendering for planning-model entity and fact collections: the item +/// type's [`AnalysisPlanningId`]. +#[doc(hidden)] +pub struct ModelPlanningIds(PhantomData); + +impl SourcePlanningIds for ModelPlanningIds { + #[inline] + fn planning_id(item: &A) -> Option { + item.analysis_planning_id() + } +} + +/// Renders a planning id for [`AnalysisPlanningId`]: through `Display` when +/// the id type implements it, otherwise through `Debug`, otherwise not at +/// all (`None`), since `PlanningId::Id` requires neither. +/// +/// The macros call `(&&RenderPlanningId(&id)).render_planning_id()` on the +/// concrete id type, with the three rendering traits in scope. Method +/// resolution tries the receiver with the fewest references first: the +/// `Display` impl is on `&RenderPlanningId`, the `Debug` impl on +/// `&&RenderPlanningId`, and the fallback on `&&&RenderPlanningId`, so the +/// first rendering the id type supports wins. +#[doc(hidden)] +pub struct RenderPlanningId<'a, T: ?Sized>(pub &'a T); + +/// The `Display` rendering of [`RenderPlanningId`]. +#[doc(hidden)] +pub trait RenderPlanningIdDisplay { + /// Renders the id with `Display`. + fn render_planning_id(&self) -> Option; +} + +impl RenderPlanningIdDisplay for &&RenderPlanningId<'_, T> { + fn render_planning_id(&self) -> Option { + Some(self.0.to_string()) + } +} + +/// The `Debug` rendering of [`RenderPlanningId`], for ids without `Display`. +#[doc(hidden)] +pub trait RenderPlanningIdDebug { + /// Renders the id with `Debug`. + fn render_planning_id(&self) -> Option; +} + +impl RenderPlanningIdDebug for &RenderPlanningId<'_, T> { + fn render_planning_id(&self) -> Option { + Some(format!("{:?}", self.0)) + } +} + +/// The fallback of [`RenderPlanningId`] for ids with neither `Display` nor +/// `Debug`: no rendering. +#[doc(hidden)] +pub trait RenderPlanningIdNone { + /// Reports no rendering. + fn render_planning_id(&self) -> Option; +} + +impl RenderPlanningIdNone for RenderPlanningId<'_, T> { + fn render_planning_id(&self) -> Option { + None + } +} diff --git a/crates/solverforge-scoring/src/stream/collection_extract/planning_id/tests.rs b/crates/solverforge-scoring/src/stream/collection_extract/planning_id/tests.rs new file mode 100644 index 000000000..38edf4970 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/collection_extract/planning_id/tests.rs @@ -0,0 +1,52 @@ +// The planning-id rendering the macros generate: `Display` first, then +// `Debug`, then none, chosen per concrete id type by method resolution. + +use super::{ + RenderPlanningId, RenderPlanningIdDebug, RenderPlanningIdDisplay, RenderPlanningIdNone, +}; + +/// The expression `#[planning_entity]` and `#[problem_fact]` expand to. +macro_rules! render { + ($id:expr) => { + (&&&RenderPlanningId(&$id)).render_planning_id() + }; +} + +// The field is read only through `Debug`. +#[derive(Debug)] +#[allow(dead_code)] +struct DebugOnly(u32); + +struct Neither; + +struct Both; + +impl std::fmt::Display for Both { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("display") + } +} + +impl std::fmt::Debug for Both { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("debug") + } +} + +#[test] +fn display_ids_render_with_display() { + assert_eq!(render!(7usize), Some("7".to_string())); + assert_eq!(render!("anna".to_string()), Some("anna".to_string())); + assert_eq!(render!(Both), Some("display".to_string())); +} + +#[test] +fn ids_without_display_render_with_debug() { + assert_eq!(render!(DebugOnly(3)), Some("DebugOnly(3)".to_string())); + assert_eq!(render!(Some(4u8)), Some("Some(4)".to_string())); +} + +#[test] +fn ids_without_display_or_debug_render_as_none() { + assert_eq!(render!(Neither), None); +} diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs index 18658535a..40b81a940 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs @@ -18,6 +18,8 @@ use super::super::joiner::Joiner; use super::super::relational::index::HashIndex; use super::super::relational::operator::{CollectionNode, JoinNode, Operator, Pair}; use super::super::relational::{HandleMap, Leaf, RowHandle}; +use crate::api::analysis::EntityRef; +use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; /// The predicate first-join plan: an explicit opposite-input scan. /// @@ -410,3 +412,27 @@ where f.debug_struct("BiScored").finish() } } + +impl ExplainOperator for BiScored +where + S: Send + Sync + 'static, + A: Send + Sync + 'static, + B: Send + Sync + 'static, + P: IndexedPlan + 'static, + EA: CollectionExtract, + EB: CollectionExtract, + for<'a> P: ExecutablePlan, Leaf<'a, B>>, + for<'a> JoinNode, CollectionNode, P>: + ExplainOperator = Pair, Leaf<'a, B>>>, + F: BiFilter + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.inner.explain(solution, row, origin, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs index 6db73efe7..da3e1ae1d 100644 --- a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs @@ -17,7 +17,7 @@ use solverforge_core::{ConstraintRef, ImpactType}; use super::filter::{AndPentaFilter, FnPentaFilter, PentaFilter}; use super::joiner::plan::{CompileCondition, IndexedPlan}; -use super::relational::operator::{CollectionNode, ExplainRow, JoinNode, Operator, Pair}; +use super::relational::operator::{CollectionNode, ExplainOperator, JoinNode, Operator, Pair}; use super::relational::{HandleMap, Leaf, RowHandle}; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -393,7 +393,7 @@ where Leaf<'a, E>, >, >, - for<'a> PentaRow<'a, S, EA, EB, EC, ED, EE, P1, P2, P3, P4>: ExplainRow, + BuiltPenta: ExplainOperator, F: PentaFilter + 'static, W: Fn(&A, &B, &C, &D, &E) -> Sc + Send + Sync, Sc: Score + 'static, diff --git a/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs index 49d0656c3..5e8f61c07 100644 --- a/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs @@ -1,4 +1,6 @@ use super::*; +use crate::api::analysis::EntityRef; +use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; /// Scored penta operator: the tree plus the authored filter as one row producer. pub struct PentaScored< @@ -283,3 +285,36 @@ where .test(solution, a, b, c, d, e, ai, bi, ci, di, ei) } } + +impl ExplainOperator + for PentaScored +where + S: Send + Sync + 'static, + A: Send + Sync + 'static, + B: Send + Sync + 'static, + C: Send + Sync + 'static, + D: Send + Sync + 'static, + E: Send + Sync + 'static, + P1: CompileCondition + 'static, + P2: CompileCondition + 'static, + P3: CompileCondition + 'static, + P4: CompileCondition + 'static, + for<'a> BuiltPenta: ExplainOperator< + S, + View<'a> = Pair< + Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, + Leaf<'a, E>, + >, + >, + F: PentaFilter + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.inner.explain(solution, row, origin, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs index 4992e0265..2420823a9 100644 --- a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs @@ -17,7 +17,7 @@ use solverforge_core::{ConstraintRef, ImpactType}; use super::filter::{AndQuadFilter, FnQuadFilter, QuadAsPentaFilter, QuadFilter}; use super::joiner::plan::{CompileCondition, IndexedPlan}; -use super::relational::operator::{CollectionNode, ExplainRow, JoinNode, Operator, Pair}; +use super::relational::operator::{CollectionNode, ExplainOperator, JoinNode, Operator, Pair}; use super::relational::{HandleMap, Leaf, RowHandle}; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -337,7 +337,7 @@ where S, View<'a> = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, >, - for<'a> QuadRow<'a, S, EA, EB, EC, ED, P1, P2, P3>: ExplainRow, + BuiltQuad: ExplainOperator, F: QuadFilter + 'static, W: Fn(&A, &B, &C, &D) -> Sc + Send + Sync, Sc: Score + 'static, diff --git a/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs index 2fbc48935..e2a4ccc1f 100644 --- a/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs @@ -1,4 +1,6 @@ use super::*; +use crate::api::analysis::EntityRef; +use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; /// Scored quad operator: the tree plus the authored filter as one row producer. pub struct QuadScored< @@ -203,3 +205,31 @@ where self.filter.test(solution, a, b, c, d, ai, bi, ci, di) } } + +impl ExplainOperator + for QuadScored +where + S: Send + Sync + 'static, + A: Send + Sync + 'static, + B: Send + Sync + 'static, + C: Send + Sync + 'static, + D: Send + Sync + 'static, + P1: CompileCondition + 'static, + P2: CompileCondition + 'static, + P3: CompileCondition + 'static, + for<'a> BuiltQuad: ExplainOperator< + S, + View<'a> = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, + >, + F: QuadFilter + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.inner.explain(solution, row, origin, entities); + } +} 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 10b4df876..e56665e0f 100644 --- a/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs @@ -19,7 +19,9 @@ use solverforge_core::{ConstraintRef, ImpactType}; use super::super::collection_extract::CollectionExtract; use super::super::filter::{AndTriFilter, FnTriFilter, TriAsQuadFilter, TriFilter}; use super::super::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; -use super::super::relational::operator::{CollectionNode, ExplainRow, JoinNode, Operator, Pair}; +use super::super::relational::operator::{ + CollectionNode, ExplainOperator, JoinNode, Operator, Pair, +}; use super::super::relational::{HandleMap, Leaf, RowHandle}; use super::super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -344,7 +346,7 @@ where Operator = Pair, Leaf<'a, B>>>, for<'a> BuiltTri: Operator = Pair, Leaf<'a, B>>, Leaf<'a, C>>>, - for<'a> TriRow<'a, S, EA, EB, EC, P1, P2>: ExplainRow, + BuiltTri: ExplainOperator, F: TriFilter + 'static, W: Fn(&A, &B, &C) -> Sc + Send + Sync, Sc: Score + 'static, diff --git a/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs b/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs index bede9d203..1a8c6593f 100644 --- a/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs @@ -1,4 +1,6 @@ use super::*; +use crate::api::analysis::EntityRef; +use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; /// Scored tri operator: the tree plus the authored filter as one row producer. /// @@ -197,3 +199,29 @@ where self.filter.test(solution, a, b, c, ai, bi, ci) } } + +impl ExplainOperator + for TriScored +where + S: Send + Sync + 'static, + A: Send + Sync + 'static, + B: Send + Sync + 'static, + C: Send + Sync + 'static, + P1: CompileCondition + 'static, + P2: CompileCondition + 'static, + for<'a> JoinNode, CollectionNode, ::Plan>: + Operator = Pair, Leaf<'a, B>>>, + for<'a> BuiltTri: + ExplainOperator = Pair, Leaf<'a, B>>, Leaf<'a, C>>>, + F: TriFilter + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.inner.explain(solution, row, origin, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs b/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs index 5bd72092a..47f0fa093 100644 --- a/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs @@ -11,6 +11,8 @@ use std::marker::PhantomData; use super::super::filter::BiFilter; use super::super::relational::operator::{FlattenView, Operator, Pair}; use super::super::relational::{HandleMap, Leaf, RowHandle}; +use crate::api::analysis::EntityRef; +use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; /// Borrowed (A, C) pair plus the A and owning-B source indexes. pub(super) trait FlattenedBiEntities<'a, A, B, C> { @@ -214,3 +216,24 @@ impl std::fmt::Debug for FlattenedBiScored { f.debug_struct("FlattenedBiScored").finish() } } + +impl ExplainOperator for FlattenedBiScored +where + S: Send + Sync + 'static, + A: 'static, + B: 'static, + C: 'static, + O: ExplainOperator, + for<'a> O: Operator = Pair, FlattenView<'a, Leaf<'a, B>, C>>>, + F: BiFilter + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.inner.explain(solution, row, origin, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs index e33ff8d1d..ec56e0806 100644 --- a/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs +++ b/crates/solverforge-scoring/src/stream/joined_grouped_stream.rs @@ -2,7 +2,7 @@ use std::hash::Hash; use std::marker::PhantomData; use super::collector::{Accumulator, Collector}; -use super::relational::operator::{ExplainRow, GroupNode, Operator}; +use super::relational::operator::{ExplainOperator, GroupNode, Operator}; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::{GroupAdapter, SharedOperatorBuilder, SharedOperatorTerminal}; use solverforge_core::{score::Score, ImpactType}; @@ -85,8 +85,7 @@ pub struct JoinedGroupedBuilder, W, impl JoinedGroupedBuilder where S: Send + Sync + 'static, - O: Operator + Send + Sync, - for<'a> O::View<'a>: ExplainRow, + O: ExplainOperator + Send + Sync, F: for<'a> Fn(&O::View<'a>) -> K + Send + Sync + 'static, C: for<'a> Collector, Value = V, Result = R, Accumulator = Acc> + 'static, K: Eq + Hash + Clone + Send + Sync + 'static, diff --git a/crates/solverforge-scoring/src/stream/mod.rs b/crates/solverforge-scoring/src/stream/mod.rs index 1bd623caf..70346d687 100644 --- a/crates/solverforge-scoring/src/stream/mod.rs +++ b/crates/solverforge-scoring/src/stream/mod.rs @@ -126,7 +126,9 @@ pub mod projected; pub use balance_stream::{BalanceConstraintBuilder, BalanceConstraintStream}; pub use bi_stream::{BiConstraintBuilder, BiConstraintStream}; pub use collection_extract::{ - source, ChangeSource, CollectionExtract, FlattenExtract, SourceExtract, + model_source, source, AnalysisPlanningId, ChangeSource, CollectionExtract, FlattenExtract, + ModelPlanningIds, NoPlanningIds, RenderPlanningId, RenderPlanningIdDebug, + RenderPlanningIdDisplay, RenderPlanningIdNone, SourceExtract, SourcePlanningIds, }; pub use complemented_stream::{ComplementedConstraintBuilder, ComplementedConstraintStream}; pub use existence_stream::{ExistenceMode, ExistsConstraintBuilder, ExistsConstraintStream}; diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source.rs b/crates/solverforge-scoring/src/stream/projected_stream/source.rs index faf56e3ed..00859c8eb 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source.rs @@ -11,6 +11,7 @@ pub(super) use merged::MergedSource; pub(super) use operator::{ProjectedCollector, ProjectedRow, SourceNode}; pub(super) use single::SingleSource; +use crate::api::analysis::EntityRef; use crate::stream::collection_extract::ChangeSource; /// Receives the rows a [`Projection`] emits. @@ -226,3 +227,12 @@ pub trait Source: Send + Sync { entity_index: usize, ); } + +/// A [`Source`] that can name the entity behind each owner of its rows, for +/// score explanation. Read only while explaining a match, never while +/// scoring. +pub trait ExplainSource: Source { + /// Appends the entity `owner` names, with its planning id when its + /// collection reports one, to `entities`. + fn explain_owner(&self, solution: &S, owner: RowOwner, entities: &mut Vec); +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source/filtered.rs b/crates/solverforge-scoring/src/stream/projected_stream/source/filtered.rs index 16d1fcbd9..849fd1d9e 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source/filtered.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source/filtered.rs @@ -3,7 +3,8 @@ use std::marker::PhantomData; use crate::stream::collection_extract::ChangeSource; use crate::stream::filter::UniFilter; -use super::{RowCoordinate, Source}; +use super::{ExplainSource, RowCoordinate, RowOwner, Source}; +use crate::api::analysis::EntityRef; pub struct FilteredSource { source: Src, @@ -96,3 +97,15 @@ where .retract_entity_state(solution, state, slot, entity_index); } } + +impl ExplainSource for FilteredSource +where + S: Send + Sync + 'static, + Out: Send + Sync + 'static, + Src: ExplainSource, + F: UniFilter, +{ + fn explain_owner(&self, solution: &S, owner: RowOwner, entities: &mut Vec) { + self.source.explain_owner(solution, owner, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source/joined.rs b/crates/solverforge-scoring/src/stream/projected_stream/source/joined.rs index 81e150b92..6f61131a5 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source/joined.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source/joined.rs @@ -5,7 +5,8 @@ use crate::stream::collection_extract::{ChangeSource, CollectionExtract}; use crate::stream::filter::BiFilter; use crate::stream::relational::{DenseRowStore, HashIndex}; -use super::{RowCoordinate, Source}; +use super::{ExplainSource, RowCoordinate, RowOwner, Source}; +use crate::api::analysis::EntityRef; /// Projected source over a keyed cross join: each accepted `(A, B)` pair with /// equal keys emits one `Out` row. Built by `stream::cross::Bi::project`. @@ -334,3 +335,41 @@ where visit(coordinate, (self.project)(a, b)); } } + +impl ExplainSource + for JoinedSource +where + S: Send + Sync + 'static, + A: std::fmt::Debug + Send + Sync + 'static, + B: std::fmt::Debug + Send + Sync + 'static, + K: Eq + Hash + Clone + Send + Sync + 'static, + EA: CollectionExtract, + EB: CollectionExtract, + KA: Fn(&A) -> K + Send + Sync, + KB: Fn(&B) -> K + Send + Sync, + F: BiFilter, + P: Fn(&A, &B) -> Out + Send + Sync, + Out: Send + Sync + 'static, +{ + fn explain_owner(&self, solution: &S, owner: RowOwner, entities: &mut Vec) { + match owner.source_slot { + 0 => { + if let Some(entity) = self.extractor_a.extract(solution).get(owner.entity_index) { + entities.push( + EntityRef::new(entity) + .with_planning_id(self.extractor_a.planning_id(entity)), + ); + } + } + 1 => { + if let Some(entity) = self.extractor_b.extract(solution).get(owner.entity_index) { + entities.push( + EntityRef::new(entity) + .with_planning_id(self.extractor_b.planning_id(entity)), + ); + } + } + _ => {} + } + } +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source/merged.rs b/crates/solverforge-scoring/src/stream/projected_stream/source/merged.rs index 5c1d3742c..d415dc8ab 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source/merged.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source/merged.rs @@ -1,6 +1,7 @@ use crate::stream::collection_extract::ChangeSource; -use super::{RowCoordinate, Source}; +use super::{ExplainSource, RowCoordinate, RowOwner, Source}; +use crate::api::analysis::EntityRef; pub struct MergedSource { left: Left, @@ -122,3 +123,24 @@ where } } } + +impl ExplainSource for MergedSource +where + S: Send + Sync + 'static, + Out: Send + Sync + 'static, + Left: ExplainSource, + Right: ExplainSource, +{ + fn explain_owner(&self, solution: &S, owner: RowOwner, entities: &mut Vec) { + let left_count = self.left.source_count(); + if owner.source_slot < left_count { + self.left.explain_owner(solution, owner, entities); + } else { + let owner = RowOwner { + source_slot: owner.source_slot - left_count, + entity_index: owner.entity_index, + }; + self.right.explain_owner(solution, owner, entities); + } + } +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source/operator.rs b/crates/solverforge-scoring/src/stream/projected_stream/source/operator.rs index 2324fd3b9..8f53289f8 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source/operator.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source/operator.rs @@ -5,12 +5,12 @@ use crate::stream::{ collector::{Accumulator, Collector}, relational::{ hash::{FastMap, FastSet}, - operator::{ExplainRow, Operator}, + operator::{ExplainOperator, Operator, RowOrigin}, DenseRowStore, RowHandle, }, }; -use super::{RowCoordinate, RowOwner, Source}; +use super::{ExplainSource, RowCoordinate, RowOwner, Source}; #[doc(hidden)] pub struct ProjectedRow<'a, Out> { @@ -23,9 +23,6 @@ impl Clone for ProjectedRow<'_, Out> { *self } } -impl ExplainRow for ProjectedRow<'_, Out> { - fn explain(&self, _entities: &mut Vec) {} -} struct StoredRow { coordinate: RowCoordinate, @@ -286,3 +283,39 @@ where self.inner.create_accumulator() } } + +/// A projected row is explained by the entities it was projected from: its +/// coordinate's owners, read from the source. +impl ExplainOperator for SourceNode +where + S: Send + Sync + 'static, + Out: Send + Sync + 'static, + Src: ExplainSource + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let coordinate = match origin { + RowOrigin::Retained(handle) => self.rows.get(handle).map(|stored| stored.coordinate), + RowOrigin::Evaluation((_, rows)) => evaluated_coordinate(rows, row.value), + }; + if let Some(coordinate) = coordinate { + coordinate.for_each_owner(|owner| self.source.explain_owner(solution, owner, entities)); + } + } +} + +/// The coordinate of the evaluated row whose value `value` borrows. The +/// value lives in `rows`, so its offset from the first row's value gives its +/// position directly; the address check rejects a value from anywhere else. +fn evaluated_coordinate(rows: &[(RowCoordinate, Out)], value: &Out) -> Option { + let first = &rows.first()?.1; + let stride = std::mem::size_of::<(RowCoordinate, Out)>(); + let offset = (value as *const Out as usize).checked_sub(first as *const Out as usize)?; + let (coordinate, candidate) = rows.get(offset / stride)?; + std::ptr::eq(candidate, value).then_some(*coordinate) +} diff --git a/crates/solverforge-scoring/src/stream/projected_stream/source/single.rs b/crates/solverforge-scoring/src/stream/projected_stream/source/single.rs index acbe03b34..5886ad0d5 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/source/single.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/source/single.rs @@ -3,7 +3,8 @@ use std::marker::PhantomData; use crate::stream::collection_extract::{ChangeSource, CollectionExtract}; use crate::stream::filter::UniFilter; -use super::{project_bounded, Projection, RowCoordinate, Source}; +use super::{project_bounded, ExplainSource, Projection, RowCoordinate, RowOwner, Source}; +use crate::api::analysis::EntityRef; pub struct SingleSource { extractor: E, @@ -107,3 +108,23 @@ where ) { } } + +impl ExplainSource for SingleSource +where + S: Send + Sync + 'static, + A: std::fmt::Debug + Send + Sync + 'static, + E: CollectionExtract, + F: UniFilter, + P: Projection, + Out: Send + Sync + 'static, +{ + fn explain_owner(&self, solution: &S, owner: RowOwner, entities: &mut Vec) { + if owner.source_slot != 0 { + return; + } + if let Some(entity) = self.extractor.extract(solution).get(owner.entity_index) { + entities + .push(EntityRef::new(entity).with_planning_id(self.extractor.planning_id(entity))); + } + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator.rs b/crates/solverforge-scoring/src/stream/relational/operator.rs index cf59e954d..37a657af7 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator.rs @@ -30,7 +30,7 @@ pub use filter::{FilterNode, FilterPredicate}; pub use self_join::SelfJoinNode; #[doc(hidden)] -pub use analysis::ExplainRow; +pub use analysis::{ExplainOperator, RowOrigin}; pub use collection::CollectionNode; pub use join::JoinNode; diff --git a/crates/solverforge-scoring/src/stream/relational/operator/analysis.rs b/crates/solverforge-scoring/src/stream/relational/operator/analysis.rs index 87b1161e6..f2d550922 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/analysis.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/analysis.rs @@ -1,38 +1,57 @@ // Cold explanation boundary, separate from borrowed hot-path row traversal. -use super::{super::Leaf, Pair}; +use super::super::RowHandle; +use super::Operator; use crate::api::analysis::EntityRef; -use std::fmt::Debug; -/// A row view that can name the entities it was built from, for score -/// explanation. -/// -/// Terminals call it on the cold explanation path only (`get_matches`, -/// detailed analysis), never while scoring. Leaves push their entity, pairs -/// and arrays push each part in order, and grouped, projected, flattened and -/// complemented views push the rows they derive from. Implement it for the -/// `View` of a custom [`Operator`](super::Operator) so terminals over that -/// operator can justify their matches. -pub trait ExplainRow { - /// Appends a reference to every entity this row was built from to - /// `entities`, in row order. - fn explain(&self, entities: &mut Vec); +/// Where an explained row came from: a retained row by its handle, or a row +/// visited from a full evaluation. +pub enum RowOrigin<'a, E> { + /// A retained row ([`Operator::resolve`]) with this handle. + Retained(RowHandle), + /// A row visited from this evaluation ([`Operator::visit_evaluation`]). + Evaluation(&'a E), } -impl ExplainRow for Leaf<'_, T> { - fn explain(&self, entities: &mut Vec) { - entities.push(EntityRef::new(self.entity)); - } -} -impl ExplainRow for Pair { - fn explain(&self, entities: &mut Vec) { - self.left.explain(entities); - self.right.explain(entities); + +impl Copy for RowOrigin<'_, E> {} + +impl Clone for RowOrigin<'_, E> { + fn clone(&self) -> Self { + *self } } -impl ExplainRow for [E; N] { - fn explain(&self, entities: &mut Vec) { - for row in self { - row.explain(entities); +impl<'a, E> RowOrigin<'a, E> { + /// The origin of an input row: the same handle for a retained row, or + /// the part of the evaluation `part` selects. + pub fn map(self, part: impl FnOnce(&'a E) -> &'a F) -> RowOrigin<'a, F> { + match self { + Self::Retained(handle) => RowOrigin::Retained(handle), + Self::Evaluation(evaluation) => RowOrigin::Evaluation(part(evaluation)), } } } + +/// An operator that can name the entities each of its rows was built from, +/// for score explanation. +/// +/// Terminals call it on the cold explanation path only (`get_matches`, +/// detailed analysis), never while scoring. Explanation belongs to the +/// operator rather than the row view because the operator owns the sources: +/// a collection leaf reads its source's planning-id rendering, so each +/// [`EntityRef`] carries the record's planning id when its type has one. +/// Joins push both sides in order, and grouped, projected, flattened, +/// filtered and complemented operators push the rows they derive from by +/// asking their inputs, mapping a retained handle to the input handles the +/// row was built from. Implement it for a custom [`Operator`] so terminals +/// over that operator can justify their matches. +pub trait ExplainOperator: Operator { + /// Appends a reference to every entity `row` was built from to + /// `entities`, in row order. `origin` says where `row` came from. + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ); +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/collection.rs b/crates/solverforge-scoring/src/stream/relational/operator/collection.rs index 6d0ae6bd3..f7aa24dde 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/collection.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/collection.rs @@ -1,5 +1,7 @@ use super::super::{BindingId, DenseRowStore, Leaf, RowHandle}; use super::Operator; +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::collection_extract::CollectionExtract; use std::marker::PhantomData; @@ -131,3 +133,20 @@ where } } } + +impl + 'static> ExplainOperator for CollectionNode +where + E::Item: std::fmt::Debug + 'static, +{ + fn explain( + &self, + _solution: &S, + row: &Self::View<'_>, + _origin: RowOrigin<'_, ()>, + entities: &mut Vec, + ) { + entities.push( + EntityRef::new(row.entity).with_planning_id(self.extractor.planning_id(row.entity)), + ); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs index 107c85ebb..e518f8663 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs @@ -5,6 +5,7 @@ use crate::stream::relational::keyed_plan::{KeyOf, RightKeyOf}; use crate::stream::relational::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; use std::marker::PhantomData; +mod explain; mod outputs; struct Output { diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs new file mode 100644 index 000000000..37d194949 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs @@ -0,0 +1,56 @@ +// Cold explanation of complement rows: a real row by its target and its +// result row, a defaulted key by its target alone. +use super::super::{ComplementView, ExplainOperator, RowOrigin}; +use super::{ComplementNode, OutputValue}; +use crate::api::analysis::EntityRef; +use crate::stream::joiner::plan::{ExecutablePlan, IndexedPlan}; +use crate::stream::relational::keyed_plan::{KeyOf, RightKeyOf}; + +impl< + S: 'static, + L: ExplainOperator, + R: ExplainOperator, + P: IndexedPlan + KeyOf + RightKeyOf::Key> + 'static, + F: 'static, + T: 'static, + > ExplainOperator for ComplementNode +where + for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> Fn(&S, &L::View<'a>) -> T, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let (target, result) = match origin { + RowOrigin::Retained(handle) => match self.rows.get(handle).map(|row| &row.value) { + Some(OutputValue::Real(id)) => ( + RowOrigin::Retained(id.left()), + Some(RowOrigin::Retained(id.right())), + ), + Some(OutputValue::Default(input, _)) => (RowOrigin::Retained(*input), None), + None => return, + }, + RowOrigin::Evaluation(evaluation) => ( + RowOrigin::Evaluation(&evaluation.left.0), + Some(RowOrigin::Evaluation(&evaluation.left.1)), + ), + }; + match row { + ComplementView::Real(pair) => { + self.targets.explain(solution, &pair.left, target, entities); + if let Some(result) = result { + self.results + .explain(solution, &pair.right, result, entities); + } + } + ComplementView::Default(default) => { + self.targets + .explain(solution, &default.input, target, entities); + } + } + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement_view.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement_view.rs index bb6f25395..502b923f1 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement_view.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement_view.rs @@ -1,5 +1,4 @@ -use super::{ExplainRow, Pair, ProjectView}; -use crate::api::analysis::EntityRef; +use super::{Pair, ProjectView}; /// A real target/result pair or an owned default associated with one target row. pub enum ComplementView<'a, L, R, T> { @@ -14,11 +13,3 @@ impl Clone for ComplementView<'_, L, R, T> { *self } } -impl ExplainRow for ComplementView<'_, L, R, T> { - fn explain(&self, entities: &mut Vec) { - match self { - Self::Real(pair) => pair.explain(entities), - Self::Default(projected) => projected.explain(entities), - } - } -} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/existence.rs b/crates/solverforge-scoring/src/stream/relational/operator/existence.rs index 101d35504..21fbeb2e7 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/existence.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/existence.rs @@ -1,5 +1,7 @@ use super::group_view::GroupView; +use super::{ExplainOperator, RowOrigin}; use super::{Operator, PairDelta}; +use crate::api::analysis::EntityRef; use crate::stream::collection_extract::FlattenExtract; use crate::stream::collector::Accumulator; use crate::stream::relational::count_state::KeyState; @@ -457,3 +459,24 @@ where self.notify(solution, descriptor, index, false, removed, inserted); } } + +impl, R: Operator, K, LK, RK> ExplainOperator + for ExistenceNode +where + K: Eq + Hash + Clone + 'static, + LK: Send + Sync + 'static, + RK: Send + Sync + 'static, + for<'a> LK: ViewKey, Key = K>, + for<'a> RK: RightKeySet, Key = K>, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.left + .explain(solution, row, origin.map(|(left, _)| left), entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/filter.rs b/crates/solverforge-scoring/src/stream/relational/operator/filter.rs index d49eeab48..eecb74db3 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/filter.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/filter.rs @@ -16,6 +16,8 @@ where self(solution, row) } } +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::relational::{HandleMap, RowHandle}; /// Membership filter retaining input identities, not copied row payloads. @@ -183,3 +185,19 @@ where self.child_inserted = in_inserted; } } + +impl ExplainOperator for FilterNode +where + O: ExplainOperator, + F: for<'a> FilterPredicate> + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.input.explain(solution, row, origin, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/flatten.rs b/crates/solverforge-scoring/src/stream/relational/operator/flatten.rs index 0f294989c..4c979ac9f 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/flatten.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/flatten.rs @@ -1,4 +1,5 @@ -use super::{ExplainRow, Operator}; +use super::Operator; +use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; use crate::stream::relational::{DenseRowStore, HandleMap, Leaf, RowHandle}; @@ -17,11 +18,6 @@ impl Clone for FlattenView<'_, V, T> { *self } } -impl ExplainRow for FlattenView<'_, V, T> { - fn explain(&self, entities: &mut Vec) { - self.input.explain(entities); - } -} /// Named source of borrowed children for one input operator. /// @@ -278,3 +274,24 @@ impl, F: FlattenSource + 'static> Operator self.child_inserted = in_inserted; } } + +impl, F: FlattenSource + 'static> ExplainOperator + for FlattenNode +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let input = match origin { + RowOrigin::Retained(handle) => match self.rows.get(handle) { + Some(child) => RowOrigin::Retained(child.input), + None => return, + }, + RowOrigin::Evaluation(evaluation) => RowOrigin::Evaluation(evaluation), + }; + self.input.explain(solution, &row.input, input, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/group.rs b/crates/solverforge-scoring/src/stream/relational/operator/group.rs index 0c1501032..bfbbfb064 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/group.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/group.rs @@ -1,4 +1,6 @@ use super::{group_view::Contributors, GroupView, GroupedOperator, Operator}; +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::collector::{Accumulator, Collector}; use crate::stream::relational::{DenseRowStore, FastMap, HandleMap, RowHandle}; use solverforge_core::fast_hash::FastHasher; @@ -214,7 +216,7 @@ where } fn visit_evaluation<'a>( &'a self, - solution: &'a S, + _solution: &'a S, evaluation: &'a Self::Evaluation, visitor: &mut impl FnMut(Self::View<'a>), ) { @@ -222,8 +224,6 @@ where visitor(GroupView { key: &group.key, accumulator: &group.accumulator, - input: &self.input, - solution, contributors: Contributors::Evaluation(&evaluation.input, &group.ordinals), marker: PhantomData, }); @@ -260,13 +260,11 @@ where fn handles(&self) -> Vec { self.rows.iter().map(|(h, _)| h).collect() } - fn resolve<'a>(&'a self, solution: &'a S, h: RowHandle) -> Option> { + fn resolve<'a>(&'a self, _solution: &'a S, h: RowHandle) -> Option> { let group = self.groups.get(*self.rows.get(h)?)?; Some(GroupView { key: &group.key, accumulator: &group.accumulator, - input: &self.input, - solution, contributors: Contributors::Retained(&group.inputs), marker: PhantomData, }) @@ -345,3 +343,55 @@ where self.changed_group_count } } + +impl ExplainOperator + for GroupNode +where + O: ExplainOperator, + F: for<'a> Fn(&O::View<'a>) -> K + 'static, + for<'a> C: Collector, Value = V, Result = R, Accumulator = A> + 'static, + K: Eq + Hash + 'static, + A: Accumulator + 'static, +{ + /// A group is explained by the input rows that contribute to it, in + /// contribution order; the view itself records them. + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + _origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + match row.contributors { + Contributors::Retained(handles) => { + for &handle in handles { + let contributor = self + .input + .resolve(solution, handle) + .expect("live group contributor"); + self.input.explain( + solution, + &contributor, + RowOrigin::Retained(handle), + entities, + ); + } + } + Contributors::Evaluation(evaluation, ordinals) => { + let mut ordinal = 0; + self.input + .visit_evaluation(solution, evaluation, &mut |contributor| { + if ordinals.contains(&ordinal) { + self.input.explain( + solution, + &contributor, + RowOrigin::Evaluation(evaluation), + entities, + ); + } + ordinal += 1; + }); + } + } + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/group_view.rs b/crates/solverforge-scoring/src/stream/relational/operator/group_view.rs index d9efa92e6..5dd33ac69 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/group_view.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/group_view.rs @@ -1,5 +1,4 @@ -use super::{ExplainRow, Operator}; -use crate::api::analysis::EntityRef; +use super::Operator; use crate::stream::collector::Accumulator; use crate::stream::relational::RowHandle; use std::marker::PhantomData; @@ -20,8 +19,6 @@ pub struct GroupView<'a, S: 'static, O: Operator, K, A, V, R> { /// The group's key. pub key: &'a K, pub(super) accumulator: &'a A, - pub(super) input: &'a O, - pub(super) solution: &'a S, pub(super) contributors: Contributors<'a, S, O>, pub(super) marker: PhantomData (V, R)>, } @@ -37,30 +34,3 @@ impl, K, A: Accumulator, V, R> GroupView<'_, S, self.accumulator.with_result(f) } } -impl, K, A, V, R> ExplainRow for GroupView<'_, S, O, K, A, V, R> -where - for<'a> O::View<'a>: ExplainRow, -{ - fn explain(&self, entities: &mut Vec) { - match self.contributors { - Contributors::Retained(handles) => { - for &h in handles { - self.input - .resolve(self.solution, h) - .expect("live group contributor") - .explain(entities); - } - } - Contributors::Evaluation(evaluation, ordinals) => { - let mut ordinal = 0; - self.input - .visit_evaluation(self.solution, evaluation, &mut |row| { - if ordinals.contains(&ordinal) { - row.explain(entities); - } - ordinal += 1; - }); - } - } - } -} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/join.rs b/crates/solverforge-scoring/src/stream/relational/operator/join.rs index 7242a0443..0b0832994 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/join.rs @@ -1,5 +1,7 @@ use super::super::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; use super::{links::remove_link, GroupedOperator, Operator, Pair, PairDelta}; +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; use crate::stream::relational::hash::FastMap; use std::marker::PhantomData; @@ -407,3 +409,34 @@ where self.left.changed_group_count() } } + +impl, R: ExplainOperator, P: IndexedPlan + 'static> + ExplainOperator for JoinNode +where + for<'a> P: ExecutablePlan, R::View<'a>>, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let (left, right) = match origin { + RowOrigin::Retained(handle) => { + let Some(joined) = self.rows.get(handle) else { + return; + }; + ( + RowOrigin::Retained(joined.identity.left()), + RowOrigin::Retained(joined.identity.right()), + ) + } + RowOrigin::Evaluation((left, right)) => { + (RowOrigin::Evaluation(left), RowOrigin::Evaluation(right)) + } + }; + self.left.explain(solution, &row.left, left, entities); + self.right.explain(solution, &row.right, right, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs b/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs index 25ba4596d..4f88a7ee3 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs @@ -1,4 +1,6 @@ use super::Operator; +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; use crate::stream::relational::{FastSet, HandleMap, RowHandle}; use std::marker::PhantomData; @@ -360,3 +362,20 @@ where self.apply_changes(solution, left, right, removed, inserted); } } + +impl, R: Operator, P: IndexedPlan + 'static> ExplainOperator + for JoinerExistenceNode +where + for<'a> P: ExecutablePlan, R::View<'a>>, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + self.left + .explain(solution, row, origin.map(|(left, _)| left), entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/project.rs b/crates/solverforge-scoring/src/stream/relational/operator/project.rs index 25e0bc978..e9fd4e7cb 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/project.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/project.rs @@ -1,4 +1,5 @@ -use super::{ExplainRow, Operator}; +use super::Operator; +use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; use crate::stream::relational::{DenseRowStore, HandleMap, RowHandle}; @@ -17,11 +18,6 @@ impl Clone for ProjectView<'_, V, T> { *self } } -impl ExplainRow for ProjectView<'_, V, T> { - fn explain(&self, entities: &mut Vec) { - self.input.explain(entities); - } -} struct Output { input: RowHandle, @@ -218,3 +214,26 @@ where self.child_inserted = in_inserted; } } + +impl ExplainOperator for ProjectNode +where + O: ExplainOperator, + F: for<'a> Fn(&S, &O::View<'a>) -> Vec + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let input = match origin { + RowOrigin::Retained(handle) => match self.rows.get(handle) { + Some(output) => RowOrigin::Retained(output.input), + None => return, + }, + RowOrigin::Evaluation(evaluation) => RowOrigin::Evaluation(&evaluation.input), + }; + self.input.explain(solution, &row.input, input, entities); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs b/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs index 3584d6fd1..8b9bc93a1 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs @@ -10,6 +10,8 @@ //! each member's own provenance. use super::Operator; +use super::{ExplainOperator, RowOrigin}; +use crate::api::analysis::EntityRef; use crate::stream::key_extract::KeyExtract; use crate::stream::relational::{DenseRowStore, FastMap, HandleMap, Leaf, RowHandle}; use std::marker::PhantomData; @@ -326,3 +328,32 @@ where inserted } } + +impl ExplainOperator for SelfJoinNode +where + S: Send + Sync + 'static, + A: 'static, + O: ExplainOperator, + for<'a> O: Operator = Leaf<'a, A>>, + K: Eq + std::hash::Hash + Clone + Send + Sync + 'static, + KE: KeyExtract + 'static, +{ + fn explain( + &self, + solution: &S, + row: &Self::View<'_>, + origin: RowOrigin<'_, Self::Evaluation>, + entities: &mut Vec, + ) { + let inputs = match origin { + RowOrigin::Retained(handle) => match self.rows.get(handle) { + Some(inputs) => inputs.map(RowOrigin::Retained), + None => return, + }, + RowOrigin::Evaluation(evaluation) => [RowOrigin::Evaluation(evaluation); N], + }; + for (leaf, input) in row.iter().zip(inputs) { + self.input.explain(solution, leaf, input, entities); + } + } +} diff --git a/crates/solverforge-scoring/src/stream/uni_stream/base.rs b/crates/solverforge-scoring/src/stream/uni_stream/base.rs index 1f82a4d63..bdd4c7951 100644 --- a/crates/solverforge-scoring/src/stream/uni_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/uni_stream/base.rs @@ -225,4 +225,8 @@ where fn change_source(&self) -> ChangeSource { self.extractor.change_source() } + + fn planning_id(&self, item: &A) -> Option { + self.extractor.planning_id(item) + } } diff --git a/crates/solverforge/src/__internal.rs b/crates/solverforge/src/__internal.rs index e8fce935c..523fc4b32 100644 --- a/crates/solverforge/src/__internal.rs +++ b/crates/solverforge/src/__internal.rs @@ -41,5 +41,7 @@ pub use solverforge_config::SolverConfig; // Stream types needed for macro-generated source methods pub use solverforge_scoring::stream::filter::TrueFilter; pub use solverforge_scoring::stream::{ - source, ChangeSource, SourceExtract, UnassignedEntity, UniConstraintStream, + model_source, source, AnalysisPlanningId, ChangeSource, ModelPlanningIds, RenderPlanningId, + RenderPlanningIdDebug, RenderPlanningIdDisplay, RenderPlanningIdNone, SourceExtract, + UnassignedEntity, UniConstraintStream, }; diff --git a/crates/solverforge/tests/planning_id_constraint_analysis.rs b/crates/solverforge/tests/planning_id_constraint_analysis.rs new file mode 100644 index 000000000..38bd50f83 --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis.rs @@ -0,0 +1,166 @@ +//! Constraint matches name each entity by its planning id when its type has +//! a `#[planning_id]`: `Display` ids render with `Display`, others with +//! `Debug`, and types without one report none. Every stream family carries +//! the ids, before and after the director initializes its constraints. + +#[path = "planning_id_constraint_analysis/mod.rs"] +mod domain; + +pub use domain::{define_constraints, Nurse, Roster, Shift, ShiftId, Ward}; + +use solverforge::prelude::*; +use solverforge::ScoreDirector; + +fn roster() -> Roster { + let shift = |id, day, nurse_idx| Shift { + id: ShiftId(id), + day, + nurse_idx, + }; + Roster { + nurses: vec![ + Nurse { + name: "anna".to_string(), + index: 0, + unavailable_day: 5, + }, + Nurse { + name: "bruno".to_string(), + index: 1, + unavailable_day: 1, + }, + Nurse { + name: "carla".to_string(), + index: 2, + unavailable_day: 5, + }, + ], + wards: vec![ + Ward { + name: "north".to_string(), + unstaffed: true, + }, + Ward { + name: "south".to_string(), + unstaffed: false, + }, + ], + shifts: vec![ + shift(10, 0, Some(0)), + shift(11, 0, Some(0)), + shift(12, 1, Some(1)), + shift(13, 1, None), + ], + score: None, + } +} + +/// A match as its score and the planning ids of its entities. +type MatchIds = (HardSoftScore, Vec>); + +/// Each constraint's matches as (score, planning ids of the match's +/// entities), sorted by match. +fn planning_ids( + director: &ScoreDirector>, +) -> Vec<(String, Vec)> { + director + .constraint_analyses() + .into_iter() + .map(|analysis| { + let total = analysis + .matches + .iter() + .fold(HardSoftScore::ZERO, |sum, detailed| sum + detailed.score); + assert_eq!(total, analysis.score, "{}", analysis.constraint_ref.name); + let mut matches = analysis + .matches + .iter() + .map(|detailed| { + let ids = detailed + .justification + .entities + .iter() + .map(|entity| entity.planning_id.clone()) + .collect::>(); + (detailed.score, ids) + }) + .collect::>(); + matches.sort_by(|left, right| left.1.cmp(&right.1)); + (analysis.constraint_ref.name.to_string(), matches) + }) + .collect() +} + +fn id(text: &str) -> Option { + Some(text.to_string()) +} + +#[test] +fn every_stream_family_reports_planning_ids() { + let mut director = ScoreDirector::new(roster(), define_constraints()); + let before = planning_ids(&director); + director.calculate_score(); + let after = planning_ids(&director); + assert_eq!(before, after, "evaluation and retained rows agree"); + + let expected = vec![ + ( + "Unassigned shift".to_string(), + vec![(HardSoftScore::of_hard(-1), vec![id("ShiftId(13)")])], + ), + ( + "Shift on an unavailable day".to_string(), + vec![( + HardSoftScore::of_hard(-1), + vec![id("ShiftId(12)"), id("bruno")], + )], + ), + ( + "Shifts per nurse beyond one".to_string(), + vec![( + HardSoftScore::of_soft(-1), + vec![id("ShiftId(10)"), id("ShiftId(11)")], + )], + ), + ( + "Shifts per nurse".to_string(), + vec![ + ( + HardSoftScore::of_soft(2), + vec![id("anna"), id("ShiftId(10)"), id("ShiftId(11)")], + ), + ( + HardSoftScore::of_soft(1), + vec![id("bruno"), id("ShiftId(12)")], + ), + ], + ), + ( + "Projected shifts per nurse beyond one".to_string(), + vec![( + HardSoftScore::of_soft(-1), + vec![id("ShiftId(10)"), id("ShiftId(11)")], + )], + ), + ( + "Unstaffed ward".to_string(), + vec![(HardSoftScore::of_soft(-1), vec![None])], + ), + ]; + assert_eq!(after, expected); +} + +#[test] +fn entities_without_a_planning_id_still_report_their_display() { + let director = ScoreDirector::new(roster(), define_constraints()); + let analyses = director.constraint_analyses(); + let ward = &analyses + .iter() + .find(|analysis| analysis.constraint_ref.name == "Unstaffed ward") + .expect("ward constraint") + .matches[0] + .justification + .entities[0]; + assert_eq!(ward.planning_id, None); + assert!(ward.display.contains("north"), "{}", ward.display); +} diff --git a/crates/solverforge/tests/planning_id_constraint_analysis/mod.rs b/crates/solverforge/tests/planning_id_constraint_analysis/mod.rs new file mode 100644 index 000000000..578518f98 --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis/mod.rs @@ -0,0 +1,13 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/planning_id_constraint_analysis"; + + mod nurse; + mod roster; + mod shift; + mod ward; + + pub use nurse::Nurse; + pub use roster::{define_constraints, Roster}; + pub use shift::{Shift, ShiftId}; + pub use ward::Ward; +} diff --git a/crates/solverforge/tests/planning_id_constraint_analysis/nurse.rs b/crates/solverforge/tests/planning_id_constraint_analysis/nurse.rs new file mode 100644 index 000000000..13b3aebe4 --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis/nurse.rs @@ -0,0 +1,13 @@ +use solverforge::prelude::*; + +/// A nurse, identified by name: a `Display` planning id. +#[problem_fact] +pub struct Nurse { + /// Stable nurse name. + #[planning_id] + pub name: String, + /// Index of the nurse in the roster, which shifts refer to. + pub index: usize, + /// The day the nurse cannot work. + pub unavailable_day: usize, +} diff --git a/crates/solverforge/tests/planning_id_constraint_analysis/roster.rs b/crates/solverforge/tests/planning_id_constraint_analysis/roster.rs new file mode 100644 index 000000000..d655d9e8f --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis/roster.rs @@ -0,0 +1,113 @@ +use solverforge::prelude::*; +use solverforge::stream::collector::count; +use solverforge::stream::{joiner, ConstraintFactory, Projection, ProjectionSink}; + +use crate::{Nurse, Shift, Ward}; + +/// Nurses, wards and shifts for the planning-id analysis tests. +#[planning_solution(constraints = "define_constraints")] +pub struct Roster { + /// Nurses shifts can be assigned to. + #[problem_fact_collection] + pub nurses: Vec, + + /// Wards of the hospital. + #[problem_fact_collection] + pub wards: Vec, + + /// Shifts the solver assigns. + #[planning_entity_collection] + pub shifts: Vec, + + /// The roster's score. + #[planning_score] + pub score: Option, +} + +/// Projects each assigned shift to its nurse index. +pub struct AssignedNurse; + +impl Projection for AssignedNurse { + type Out = usize; + const MAX_EMITS: usize = 1; + + fn project(&self, shift: &Shift, sink: &mut Sink) + where + Sink: ProjectionSink, + { + if let Some(nurse) = shift.nurse_idx { + sink.emit(nurse); + } + } +} + +fn factory() -> ConstraintFactory { + ConstraintFactory::new() +} + +/// One constraint per stream family, in this order: filter, join, +/// group_by, complement, projection, and a filter over a fact without a +/// planning id. +#[solverforge_constraints] +pub fn define_constraints() -> impl ConstraintSet { + let unassigned = factory() + .for_each(Roster::shifts()) + .filter(|shift: &Shift| shift.nurse_idx.is_none()) + .penalize(HardSoftScore::ONE_HARD) + .named("Unassigned shift"); + + let unavailable = factory() + .for_each(Roster::shifts()) + .join(( + Roster::nurses(), + joiner::equal_bi( + |shift: &Shift| shift.nurse_idx, + |nurse: &Nurse| Some(nurse.index), + ), + )) + .filter(|shift: &Shift, nurse: &Nurse| shift.day == nurse.unavailable_day) + .penalize(HardSoftScore::ONE_HARD) + .named("Shift on an unavailable day"); + + let per_nurse = factory() + .for_each(Roster::shifts()) + .group_by( + |shift: &Shift| shift.nurse_idx.unwrap_or(usize::MAX), + count(), + ) + .penalize(|nurse: &usize, shifts: &usize| { + HardSoftScore::of_soft(if *nurse == usize::MAX { + 0 + } else { + shifts.saturating_sub(1) as i64 + }) + }) + .named("Shifts per nurse beyond one"); + + let idle = factory() + .for_each(Roster::shifts()) + .group_by( + |shift: &Shift| shift.nurse_idx.unwrap_or(usize::MAX), + count(), + ) + .complement(Roster::nurses(), |nurse: &Nurse| nurse.index, |_nurse| 0usize) + .reward(|_nurse: &usize, shifts: &usize| HardSoftScore::of_soft(*shifts as i64)) + .named("Shifts per nurse"); + + let projected = factory() + .for_each(Roster::shifts()) + .project(AssignedNurse) + .group_by(|nurse: &usize| *nurse, count()) + .penalize(|_nurse: &usize, shifts: &usize| { + HardSoftScore::of_soft(shifts.saturating_sub(1) as i64) + }) + .named("Projected shifts per nurse beyond one"); + + let unstaffed = factory() + .for_each(Roster::wards()) + .filter(|ward: &Ward| ward.unstaffed) + .penalize(HardSoftScore::ONE_SOFT) + .named("Unstaffed ward"); + + (unassigned, unavailable, per_nurse, idle, projected, unstaffed) +} diff --git a/crates/solverforge/tests/planning_id_constraint_analysis/shift.rs b/crates/solverforge/tests/planning_id_constraint_analysis/shift.rs new file mode 100644 index 000000000..daf6f2d17 --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis/shift.rs @@ -0,0 +1,20 @@ +use solverforge::prelude::*; + +/// A shift id with no `Display` implementation: its planning id renders with +/// `Debug`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ShiftId(pub u32); + +/// A shift on one day. +#[planning_entity] +pub struct Shift { + /// Stable shift id. + #[planning_id] + pub id: ShiftId, + /// Day of the shift. + pub day: usize, + + /// Assigned nurse. + #[planning_variable(value_range_provider = "nurses")] + pub nurse_idx: Option, +} diff --git a/crates/solverforge/tests/planning_id_constraint_analysis/ward.rs b/crates/solverforge/tests/planning_id_constraint_analysis/ward.rs new file mode 100644 index 000000000..94da3caf7 --- /dev/null +++ b/crates/solverforge/tests/planning_id_constraint_analysis/ward.rs @@ -0,0 +1,10 @@ +use solverforge::prelude::*; + +/// A ward with no planning id. +#[problem_fact] +pub struct Ward { + /// Ward name, not a planning id. + pub name: String, + /// Whether the ward lacks a head nurse. + pub unstaffed: bool, +} diff --git a/docs/constraints.md b/docs/constraints.md index 924dd687d..bd3f800e7 100644 --- a/docs/constraints.md +++ b/docs/constraints.md @@ -227,7 +227,16 @@ group (a complemented key without a group is justified by its target entity), and the match scores add up to the constraint's score. Each entity appears as its type name and `Debug` rendering, so constraints need entities that implement `Debug`; no constraint requires `Clone`, and analysis keeps no copy -of your entities. +of your entities. A projected row is justified by the entities it was +projected from. + +An entity streamed from a model collection whose type has a `#[planning_id]` +field also carries that id in `EntityRef::planning_id`, rendered as a string: +with `Display` when the id type implements it (`7`, `anna`), otherwise with +`Debug` (a tuple-struct id renders as ShiftId(7)). Use it to look up the +record behind a match instead of parsing `display`. Types without a +`#[planning_id]`, and values streamed from a hand-built source, report +`None`. Ids are read only when matches are explained, never while scoring. ## Runtime constraint weights diff --git a/docs/extend-scoring.md b/docs/extend-scoring.md index 50aa092b5..4badd2a35 100644 --- a/docs/extend-scoring.md +++ b/docs/extend-scoring.md @@ -96,9 +96,14 @@ unlocalized source and no rebuild fallback. side-table. Return the inverse retained score on retraction; do not recompute it from changed entities. Accumulate callbacks as `retract_delta + insert_delta`. Full evaluation and match counting are meaningful before initialization. -Explanation is confined to the cold `EntityRef` conversion: a type name and -a `Debug` rendering per entity, no copy and no type erasure. Do not add a -`Clone` bound on entity types; no stream needs one. +Explanation is confined to the cold `EntityRef` conversion: a type name, a +`Debug` rendering and the source's planning-id rendering per entity, no copy +and no type erasure. A custom operator explains its rows by implementing +`ExplainOperator`: it maps the row's `RowOrigin` (a retained handle, or the +evaluation it was visited from) to its input rows and asks its inputs to +explain them, so the collection leaves read the planning ids from their +sources. Do not add a `Clone` bound on entity types; no stream needs one, and +do not read planning ids while scoring. Runtime constraint weights never touch that signing step. A score director's weight mode is a type (`ScoreDirector`, `M` = `UnweightedMode`