Expand description
SolverForge is a constraint solver for planning and scheduling problems: you describe what may change and what makes a plan good or bad, and the solver searches for the best plan it can find in the time you give it.
This crate is the facade: it re-exports the model macros, score types,
constraint streams, configuration and the SolverManager that runs
solves. The repository README walks through the concepts, and
examples/ holds complete applications.
§Quick Start
A model is a directory of ordinary Rust modules (src/domain in an
application). Problem facts are the inputs the solver reads:
use solverforge::prelude::*;
#[problem_fact]
pub struct Employee {
#[planning_id]
pub id: usize,
pub name: String,
}Planning entities hold the planning variables the solver assigns. A scalar planning variable stores the index of its value in a solution collection:
use solverforge::prelude::*;
#[planning_entity]
pub struct Shift {
#[planning_id]
pub id: usize,
pub day: u32,
// The index of the assigned employee in `Schedule::employees`.
#[planning_variable(value_range_provider = "employees", allows_unassigned = true)]
pub employee_idx: Option<usize>,
}The planning solution owns the collections, the score and the
constraints, and links the solver configuration (solver.toml holds
[termination] seconds_spent_limit = 5):
use solverforge::prelude::*;
use super::{Employee, Shift};
#[planning_solution(constraints = "define_constraints", solver_toml = "solver.toml")]
pub struct Schedule {
#[problem_fact_collection]
pub employees: Vec<Employee>,
#[planning_entity_collection]
pub shifts: Vec<Shift>,
#[planning_score]
pub score: Option<HardSoftScore>,
}
#[solverforge_constraints]
fn define_constraints() -> impl ConstraintSet<Schedule, HardSoftScore> {
let unassigned = ConstraintFactory::<Schedule, HardSoftScore>::new()
.for_each(Schedule::shifts())
.filter(|shift: &Shift| shift.employee_idx.is_none())
.penalize(HardSoftScore::ONE_HARD)
.named("Unassigned shift");
let two_shifts_a_day = ConstraintFactory::<Schedule, HardSoftScore>::new()
.for_each(Schedule::shifts())
.join((
ConstraintFactory::<Schedule, HardSoftScore>::new().for_each(Schedule::shifts()),
|left: &Shift, right: &Shift| {
left.id < right.id
&& left.day == right.day
&& left.employee_idx.is_some()
&& left.employee_idx == right.employee_idx
},
))
.penalize(HardSoftScore::ONE_SOFT)
.named("Two shifts on one day");
(unassigned, two_shifts_a_day)
}planning_model! in the domain’s mod.rs lists those modules, and
SolverManager solves a problem on a background thread, streaming
progress and the final solution as SolverEvents. The three files
above are this example’s doc/quick_start directory, so it compiles
against exactly the code shown:
solverforge::planning_model! {
root = "doc/quick_start";
mod employee;
mod schedule;
mod shift;
pub use employee::Employee;
pub use schedule::Schedule;
pub use shift::Shift;
}
use solverforge::{SolverEvent, SolverManager};
static MANAGER: SolverManager<Schedule> = SolverManager::new();
fn main() {
let schedule = Schedule {
employees: ["Amina", "Bruno"]
.iter()
.enumerate()
.map(|(id, name)| Employee { id, name: name.to_string() })
.collect(),
shifts: (0..4)
.map(|id| Shift { id, day: id as u32 / 2, employee_idx: None })
.collect(),
score: None,
};
let (job_id, mut events) = MANAGER.solve(schedule).expect("solver job should start");
while let Some(event) = events.blocking_recv() {
match event {
SolverEvent::Completed { solution, .. } => {
println!("score: {:?}", solution.score);
break;
}
SolverEvent::Failed { error, .. } => panic!("solve failed: {error}"),
_ => {}
}
}
MANAGER.delete(job_id).expect("finished job should delete");
}Modules§
- analysis
- Score analysis types returned by constraints and score directors.
- builder
- Search declaration building blocks behind
SearchContextandSearch. - config
- Every solver configuration type: phases, move selectors, acceptors, foragers, termination and the configuration error.
- constraint
- Built-in constraint implementations that the stream builders produce.
- cvrp
- Stock CVRP profile: problem data, distance meters and route hooks.
- director
- Score directors and their weight modes.
- domain
- Planning-model traits and runtime descriptors (
PlanningSolution,SolutionDescriptor, entity and variable descriptors). - heuristic
- Moves, move selectors and move cursors for custom search.
- phase
- Phases and their parts: local search acceptors and foragers, exhaustive search deciders, partitioned search.
- planning
- Scalar and repair planning types and source-to-target helpers.
- prelude
- Glob import for domain models and constraint providers.
- stats
- Solver and phase statistics, telemetry and candidate-trace types.
- stream
- Fluent constraint stream API.
Macros§
- planning_
model - Declares a domain’s model manifest: the solution, entity and fact modules that make up one planning model.
Structs§
- Applied
Move Telemetry - One committed local-search step, kept in a bounded trace.
- Bendable
Score - A score with a configurable number of hard and soft levels.
- Candidate
Pull Telemetry - One ordered candidate pull retained by an enabled trace.
- Candidate
Trace Composite Identity - Canonical identity for a compound/cartesian move.
- Candidate
Trace Config - Opt-in bounded candidate-pull trace configuration.
- Candidate
Trace Construction Target - A descriptor/entity location that a construction candidate was generated for. It is absent for local-search candidates.
- Candidate
Trace Digest - Stable, non-cryptographic digest used to quickly reject mismatched trace provenance or prefixes.
- Candidate
Trace Execution Policy - The execution policy the solver actually installed for this run.
- Candidate
Trace External Digest - Digest value supplied by an external fixture or integration boundary.
- Candidate
Trace Header - Immutable provenance emitted once for an opt-in candidate trace.
- Candidate
Trace Input Attestation - Origin of supplied run-input provenance.
- Candidate
Trace Input Provenance - Immutable caller-supplied context for a diagnostic run.
- Candidate
Trace Operation Identity - Canonical identity for an explicit non-cursor operation performed by a specialized list construction/search engine.
- Candidate
Trace Phase Attribute - One canonical resolved-plan attribute.
- Candidate
Trace Phase Plan - A resolved solver phase plan used as candidate-trace provenance.
- Candidate
Trace Provenance Status - Separate execution/input provenance status for benchmark qualification.
- Candidate
Trace Telemetry - Bounded trace emitted in final/pause snapshots for an enabled run.
- Closure
Problem Change - A problem change implemented as a one-shot closure.
- Conflict
Repair - A repair provider registered for a named constraint.
- Constraint
Analysis - Analysis of a single constraint’s contribution to the score.
- Constraint
Metadata - Immutable public metadata for a scoring constraint.
- Constraint
Ref - Reference to a constraint for identification.
- Constraint
Result - Result of evaluating a single constraint.
- Constraint
Weights - Per-constraint multipliers keyed by
ConstraintRef::full_name(). - Default
Distance Meter - Default distance meter using position difference.
- Entity
Class Id - Logical planning-entity class identifier.
- Exhaustive
Search Config - Settings of an exhaustive search phase.
- Exhaustive
Search Phase - Exhaustive search phase that explores all possible solutions.
- Fixed
Weight - Public wrapper for fixed score weights that are not one of the built-in score types.
- Functional
Partitioner - A simple partitioner that creates a specified number of partitions.
- Hard
Medium Soft Score - A score with hard, medium, and soft constraint levels.
- Hard
Soft Decimal Score - A score with separate hard and soft constraint levels, using i64 with x100000 scaling.
- Hard
Soft Score - A score with separate hard and soft constraint levels.
- Hard
Weight - Public wrapper that marks a fixed or dynamic weight as hard metadata.
- Incremental
UniConstraint - Zero-erasure incremental uni-constraint.
- List
Precedence Makespan Constraint - Stock incremental constraint that scores list-variable routes against fixed
precedence edges, over
HardSoftScore. - Move
Telemetry - Counters for one move kind, keyed by the move’s telemetry label.
- Partitioned
Search Phase - Partitioned search phase that solves partitions in parallel.
- Phase
Scope - Scope for a single phase of solving.
- Phase
Telemetry - Counters for one phase of a solve, as published in
SolverTelemetry::phases. - Problem
Change Id - Acknowledges one problem change queued on a retained job.
- Problem
Fact Class Id - Logical problem-fact class identifier.
- Qualified
Candidate Trace RunProvenance - Immutable attestation required before a caller may request a qualified diagnostic run.
- Repair
Candidate - One repair proposed by a provider: a reason and the scalar edits applied together.
- Repair
Limits - Limits a conflict-repair provider must respect per step.
- Scalar
Candidate - A group candidate: scalar edits applied together, with optional construction ordering keys.
- Scalar
Edit - One scalar variable edit: set an entity’s variable to a value (
Noneunassigns). Built withScalarTarget::set. - Scalar
Group - A named group of scalar variables that construction and local search change together, either from provider candidates or as an assignment.
- Scalar
Group Limits - Limits for a scalar group. A
Nonefield leaves the engine default. - Scalar
Target - One scalar planning variable a group targets, identified by entity descriptor and variable name.
- Score
Analysis - Result of analyzing a solution’s constraints.
- Score
Director - A zero-erasure score director for incremental scoring.
- Score
Parse Error - Error when parsing a score from string
- Search
Context - A model bound to its solution descriptor plus the solve’s random seed: the input custom phases and the configured runtime build from.
- Selector
Telemetry - Counters for one move selector of a phase, keyed by its index.
- Shared
Node Diagnostics - A single shared node’s diagnostics: its shared consumers and root notification bookkeeping while the terminal was incrementally live.
- Shared
Node Id - Identity of the shared node within the compiled constraint program.
- Simple
Decider - A simple value-based decider that works with any value type.
- Soft
Score - A simple score with a single integer value.
- Solver
Config - Main solver configuration.
- Solver
Config Override - Runtime configuration overrides, applied with
SolverConfig::with_overrideor to a retained job throughSolverManager::solve_with_override. - Solver
Event Metadata - Fields shared by every
SolverEvent. - Solver
Event Receiver - The owned stream of lifecycle events for one retained solve job.
- Solver
Manager - Manages retained async solve jobs with lifecycle-complete event streaming.
- Solver
Progress Ref - A progress report passed to a
ProgressCallback; borrows the scope’s solution and scores for the duration of the call. - Solver
Runtime - Runtime context for a retained solve job.
- Solver
Scope - Solver-wide state of one solve: the score director with the working solution, the best solution and scores, the seeded random generator, termination limits, lifecycle control and statistics.
- Solver
Snapshot - A retained copy of a job’s solution with the state it was published in.
- Solver
Snapshot Analysis - Constraint analysis of a retained snapshot.
- Solver
Status - Point-in-time status of a retained job.
- Solver
Telemetry - Solve-wide counters published with progress events, snapshots and the final result.
- Solver
Telemetry Detail - One atomically retained diagnostic view of a job.
- Step
Scope - Scope for a single step within a phase.
- Variable
Id - Logical planning-variable identifier.
Enums§
- Acceptor
Config - Acceptor configuration.
- Candidate
Trace Coordinate - One explicitly framed logical-coordinate component.
- Candidate
Trace Disposition - One state transition for a retained candidate-pull entry.
- Candidate
Trace Identity - Canonical, owned identity for one traced candidate.
- Candidate
Trace Input Provenance Status - Trust state of optional caller-supplied run-input provenance.
- Candidate
Trace Qualification Error - Why qualified candidate-trace provenance could not be built or read.
- Candidate
Trace Qualification Status - Whether a trace explicitly requested qualified run provenance.
- Candidate
Trace Source - The engine path that consumed a candidate.
- Constraint
Weight Error - Error reported when constraint weights do not fit the model’s constraints.
- Construction
Heuristic Type - Construction heuristic types.
- Construction
Obligation - Construction obligation for nullable scalar variables.
- Environment
Mode - Environment mode affecting solver behavior.
- Exploration
Type - Order in which exhaustive search expands the frontier.
- Forager
Config - Forager configuration.
- Hard
Regression Policy Config - Whether simulated annealing may accept a move that worsens a hard level.
- Impact
Type - Type of impact a constraint has on the score.
- Move
Selector Config - Move selector configuration.
- Move
Thread Count - Move thread count configuration.
- Phase
Config - Phase configuration.
- Recreate
Heuristic Type - How a ruin-and-recreate move reassigns the entities it unassigned.
- Runtime
Build Error - Error returned while a configured runtime is being declared, compiled, or prepared for one solve.
- Score
Level - Score level representing different constraint priorities.
- Shared
Node Operation - The relational family of the shared node, named for diagnostics only.
- Solver
Event - A lifecycle event of a retained solve job, delivered in publication order
through a
SolverEventReceiver. - Solver
Event TryRecv Error - Why
SolverEventReceiver::try_recvreturned no event. - Solver
Lifecycle State - Lifecycle state of a retained solve job.
- Solver
Manager Error - Errors returned by
SolverManageroperations. - Solver
Progress Kind - What a
SolverProgressRefreports. - Solver
Terminal Reason - Why a job reached its terminal state.
- Thread
Count - Thread count configuration for partitioned search.
- Union
Selection Order - How a union interleaves its child selectors.
Constants§
- CANDIDATE_
TRACE_ FORMAT_ VERSION - Wire-format version for
CandidateTraceHeaderand every framed value in this module. - MAX_
CONSTRAINT_ WEIGHT_ MULTIPLIER - Largest accepted constraint weight multiplier.
- REPRODUCIBLE_
RANDOM_ SEED - The seed a solve without
random_seeduses in every mode exceptnon_reproducible.
Traits§
- Analyzable
- Trait for solutions that can be analyzed for constraint violations.
- Constraint
Set - A set of constraints that can be evaluated together.
- Constraint
Weight - The weight a
penalizeorrewardcall scores each match with. - Cross
Entity Distance Meter - Measures distance between two list positions, potentially across entities.
- Custom
Search Phase - A user-defined phase registered on a search declaration by name and run
by the configured runtime where
solver.tomlnames it. - Director
- The score director manages solution state and score calculation.
- Incremental
Constraint - One named constraint whose score is kept up to date incrementally.
- Parseable
Score - Scores with a text form that can be parsed and rendered.
- Planning
Solution - Marker trait for planning solutions.
- Problem
Change - A change to the problem that can be applied during solving.
- Progress
Callback - Receives progress and best-solution reports from a running solve.
- Projection
- Retained projection for
UniConstraintStream::project: maps one entity to a bounded number of scoring rows. - Projection
Sink - Receives the rows a
Projectionemits. - Score
- Core trait for all score types in SolverForge.
- Search
- Typed search authoring declaration consumed by the configured runtime.
- Single
Constraint - Marks a type as one constraint.
- Solution
Partitioner - Splits a solution into independent partitions for parallel solving.
- Solvable
- Trait for solutions that can run inside the retained lifecycle manager.
Functions§
- analyze
- Analyzes a solution for constraint violations.
- fixed_
weight - Wraps a fixed score weight while preserving static dispatch.
- hard_
weight - Wraps a weight and forces hard constraint metadata while preserving static dispatch.
- local_
search - Builds a local search phase from a move selector, an acceptor and a forager, with no step limit.
Type Aliases§
- Repair
Provider - Proposes repairs for
solutionwithin the limits. - Runtime
Build Result - Result returned by the one configured-runtime declaration/preparation path.
- Scalar
Assignment Rule - Whether
left_entityholdingleft_valuemay directly precederight_entityholdingright_valuein a sequence. Arguments:(solution, left_entity, left_value, right_entity, right_value). - Scalar
Candidate Provider - Proposes candidates for
solutionwithin the group limits.
Attribute Macros§
- planning_
entity - Derives planning-entity metadata for a struct: its
#[planning_id], scalar and list planning variables, and shadow variables. - planning_
solution - Derives the planning solution: entity and fact collections, the score
field, the runtime model and the generated
Solvablesolve entry point. - problem_
fact - Derives problem-fact metadata for an immutable input struct.
- solverforge_
constraints - Compiles a constraint-provider function’s constraint streams into one shared, incremental constraint set.