Skip to main content

Crate solverforge

Crate solverforge 

Source
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 SearchContext and Search.
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§

AppliedMoveTelemetry
One committed local-search step, kept in a bounded trace.
BendableScore
A score with a configurable number of hard and soft levels.
CandidatePullTelemetry
One ordered candidate pull retained by an enabled trace.
CandidateTraceCompositeIdentity
Canonical identity for a compound/cartesian move.
CandidateTraceConfig
Opt-in bounded candidate-pull trace configuration.
CandidateTraceConstructionTarget
A descriptor/entity location that a construction candidate was generated for. It is absent for local-search candidates.
CandidateTraceDigest
Stable, non-cryptographic digest used to quickly reject mismatched trace provenance or prefixes.
CandidateTraceExecutionPolicy
The execution policy the solver actually installed for this run.
CandidateTraceExternalDigest
Digest value supplied by an external fixture or integration boundary.
CandidateTraceHeader
Immutable provenance emitted once for an opt-in candidate trace.
CandidateTraceInputAttestation
Origin of supplied run-input provenance.
CandidateTraceInputProvenance
Immutable caller-supplied context for a diagnostic run.
CandidateTraceOperationIdentity
Canonical identity for an explicit non-cursor operation performed by a specialized list construction/search engine.
CandidateTracePhaseAttribute
One canonical resolved-plan attribute.
CandidateTracePhasePlan
A resolved solver phase plan used as candidate-trace provenance.
CandidateTraceProvenanceStatus
Separate execution/input provenance status for benchmark qualification.
CandidateTraceTelemetry
Bounded trace emitted in final/pause snapshots for an enabled run.
ClosureProblemChange
A problem change implemented as a one-shot closure.
ConflictRepair
A repair provider registered for a named constraint.
ConstraintAnalysis
Analysis of a single constraint’s contribution to the score.
ConstraintMetadata
Immutable public metadata for a scoring constraint.
ConstraintRef
Reference to a constraint for identification.
ConstraintResult
Result of evaluating a single constraint.
ConstraintWeights
Per-constraint multipliers keyed by ConstraintRef::full_name().
DefaultDistanceMeter
Default distance meter using position difference.
EntityClassId
Logical planning-entity class identifier.
ExhaustiveSearchConfig
Settings of an exhaustive search phase.
ExhaustiveSearchPhase
Exhaustive search phase that explores all possible solutions.
FixedWeight
Public wrapper for fixed score weights that are not one of the built-in score types.
FunctionalPartitioner
A simple partitioner that creates a specified number of partitions.
HardMediumSoftScore
A score with hard, medium, and soft constraint levels.
HardSoftDecimalScore
A score with separate hard and soft constraint levels, using i64 with x100000 scaling.
HardSoftScore
A score with separate hard and soft constraint levels.
HardWeight
Public wrapper that marks a fixed or dynamic weight as hard metadata.
IncrementalUniConstraint
Zero-erasure incremental uni-constraint.
ListPrecedenceMakespanConstraint
Stock incremental constraint that scores list-variable routes against fixed precedence edges, over HardSoftScore.
MoveTelemetry
Counters for one move kind, keyed by the move’s telemetry label.
PartitionedSearchPhase
Partitioned search phase that solves partitions in parallel.
PhaseScope
Scope for a single phase of solving.
PhaseTelemetry
Counters for one phase of a solve, as published in SolverTelemetry::phases.
ProblemChangeId
Acknowledges one problem change queued on a retained job.
ProblemFactClassId
Logical problem-fact class identifier.
QualifiedCandidateTraceRunProvenance
Immutable attestation required before a caller may request a qualified diagnostic run.
RepairCandidate
One repair proposed by a provider: a reason and the scalar edits applied together.
RepairLimits
Limits a conflict-repair provider must respect per step.
ScalarCandidate
A group candidate: scalar edits applied together, with optional construction ordering keys.
ScalarEdit
One scalar variable edit: set an entity’s variable to a value (None unassigns). Built with ScalarTarget::set.
ScalarGroup
A named group of scalar variables that construction and local search change together, either from provider candidates or as an assignment.
ScalarGroupLimits
Limits for a scalar group. A None field leaves the engine default.
ScalarTarget
One scalar planning variable a group targets, identified by entity descriptor and variable name.
ScoreAnalysis
Result of analyzing a solution’s constraints.
ScoreDirector
A zero-erasure score director for incremental scoring.
ScoreParseError
Error when parsing a score from string
SearchContext
A model bound to its solution descriptor plus the solve’s random seed: the input custom phases and the configured runtime build from.
SelectorTelemetry
Counters for one move selector of a phase, keyed by its index.
SharedNodeDiagnostics
A single shared node’s diagnostics: its shared consumers and root notification bookkeeping while the terminal was incrementally live.
SharedNodeId
Identity of the shared node within the compiled constraint program.
SimpleDecider
A simple value-based decider that works with any value type.
SoftScore
A simple score with a single integer value.
SolverConfig
Main solver configuration.
SolverConfigOverride
Runtime configuration overrides, applied with SolverConfig::with_override or to a retained job through SolverManager::solve_with_override.
SolverEventMetadata
Fields shared by every SolverEvent.
SolverEventReceiver
The owned stream of lifecycle events for one retained solve job.
SolverManager
Manages retained async solve jobs with lifecycle-complete event streaming.
SolverProgressRef
A progress report passed to a ProgressCallback; borrows the scope’s solution and scores for the duration of the call.
SolverRuntime
Runtime context for a retained solve job.
SolverScope
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.
SolverSnapshot
A retained copy of a job’s solution with the state it was published in.
SolverSnapshotAnalysis
Constraint analysis of a retained snapshot.
SolverStatus
Point-in-time status of a retained job.
SolverTelemetry
Solve-wide counters published with progress events, snapshots and the final result.
SolverTelemetryDetail
One atomically retained diagnostic view of a job.
StepScope
Scope for a single step within a phase.
VariableId
Logical planning-variable identifier.

Enums§

AcceptorConfig
Acceptor configuration.
CandidateTraceCoordinate
One explicitly framed logical-coordinate component.
CandidateTraceDisposition
One state transition for a retained candidate-pull entry.
CandidateTraceIdentity
Canonical, owned identity for one traced candidate.
CandidateTraceInputProvenanceStatus
Trust state of optional caller-supplied run-input provenance.
CandidateTraceQualificationError
Why qualified candidate-trace provenance could not be built or read.
CandidateTraceQualificationStatus
Whether a trace explicitly requested qualified run provenance.
CandidateTraceSource
The engine path that consumed a candidate.
ConstraintWeightError
Error reported when constraint weights do not fit the model’s constraints.
ConstructionHeuristicType
Construction heuristic types.
ConstructionObligation
Construction obligation for nullable scalar variables.
EnvironmentMode
Environment mode affecting solver behavior.
ExplorationType
Order in which exhaustive search expands the frontier.
ForagerConfig
Forager configuration.
HardRegressionPolicyConfig
Whether simulated annealing may accept a move that worsens a hard level.
ImpactType
Type of impact a constraint has on the score.
MoveSelectorConfig
Move selector configuration.
MoveThreadCount
Move thread count configuration.
PhaseConfig
Phase configuration.
RecreateHeuristicType
How a ruin-and-recreate move reassigns the entities it unassigned.
RuntimeBuildError
Error returned while a configured runtime is being declared, compiled, or prepared for one solve.
ScoreLevel
Score level representing different constraint priorities.
SharedNodeOperation
The relational family of the shared node, named for diagnostics only.
SolverEvent
A lifecycle event of a retained solve job, delivered in publication order through a SolverEventReceiver.
SolverEventTryRecvError
Why SolverEventReceiver::try_recv returned no event.
SolverLifecycleState
Lifecycle state of a retained solve job.
SolverManagerError
Errors returned by SolverManager operations.
SolverProgressKind
What a SolverProgressRef reports.
SolverTerminalReason
Why a job reached its terminal state.
ThreadCount
Thread count configuration for partitioned search.
UnionSelectionOrder
How a union interleaves its child selectors.

Constants§

CANDIDATE_TRACE_FORMAT_VERSION
Wire-format version for CandidateTraceHeader and every framed value in this module.
MAX_CONSTRAINT_WEIGHT_MULTIPLIER
Largest accepted constraint weight multiplier.
REPRODUCIBLE_RANDOM_SEED
The seed a solve without random_seed uses in every mode except non_reproducible.

Traits§

Analyzable
Trait for solutions that can be analyzed for constraint violations.
ConstraintSet
A set of constraints that can be evaluated together.
ConstraintWeight
The weight a penalize or reward call scores each match with.
CrossEntityDistanceMeter
Measures distance between two list positions, potentially across entities.
CustomSearchPhase
A user-defined phase registered on a search declaration by name and run by the configured runtime where solver.toml names it.
Director
The score director manages solution state and score calculation.
IncrementalConstraint
One named constraint whose score is kept up to date incrementally.
ParseableScore
Scores with a text form that can be parsed and rendered.
PlanningSolution
Marker trait for planning solutions.
ProblemChange
A change to the problem that can be applied during solving.
ProgressCallback
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.
ProjectionSink
Receives the rows a Projection emits.
Score
Core trait for all score types in SolverForge.
Search
Typed search authoring declaration consumed by the configured runtime.
SingleConstraint
Marks a type as one constraint.
SolutionPartitioner
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§

RepairProvider
Proposes repairs for solution within the limits.
RuntimeBuildResult
Result returned by the one configured-runtime declaration/preparation path.
ScalarAssignmentRule
Whether left_entity holding left_value may directly precede right_entity holding right_value in a sequence. Arguments: (solution, left_entity, left_value, right_entity, right_value).
ScalarCandidateProvider
Proposes candidates for solution within 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 Solvable solve 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.
type Item = T;
","Iter":"

Notable traits for Iter<'a, T>

impl<'a, T> Iterator for Iter<'a, T>
type Item = &'a T;
","IterMut":"

Notable traits for IterMut<'a, T>

impl<'a, T> Iterator for IterMut<'a, T>
type Item = &'a mut T;
"}