Skip to content

mineproductivity.optimization

Auto-generated API reference for the Optimization package, rendered from the package's own docstrings. For the narrative overview, dependency rules, and extension guide, see Packages -> Optimization.

optimization

mineproductivity.optimization -- the platform's prescriptive search layer, built directly on top of simulation.

Answers: given a governed problem statement -- objectives, constraints, decision variables -- what is the best feasible plan? The package is an orchestration layer over six pluggable, interface-only solving paradigms (linear programming, mixed-integer programming, constraint programming, multi-objective, evolutionary/ metaheuristic, network optimization, design spec §11-§16); it never imports a solver library (third-party solver libraries -- §17's adapter pattern), never recomputes a KPI/statistic/decision/twin-state/ simulation fact (§3.2), and delegates every statistical judgment on its outputs to analytics (§19-§20).

The complete design spec §6 module list (twenty modules) is implemented: OptimizationModel/OptimizationContext (§8); OptimizationMetadata/OptimizationCategory (§29); the full problem-definition family -- Objective/ObjectiveDirection, Constraint/ConstraintOperator, DecisionVariable/ VariableDomain, OptimizationProblem/ProblemStatus as a versioned, governed artifact (§9); OptimizationRun/RunStatus/ OptimizationExecutor (§10); OptimizationState (§10); the six interface-only category ABCs with zero concrete subclasses by design (§11-§16, ADR-0010); PlanComparator/SensitivityAnalyzer (§19-§20); by_category/by_scope (§22); OptimizationRunRepository as a literal type alias over core.BaseRepository[OptimizationRun, str] (§24); the OptimizationResult/ParetoResult family (§18); REGISTRY/register (§21); and the full exception hierarchy. No caching module exists, deliberately (§26's documented non-need).

optimization depends on core through simulation -- and MUST NEVER import agents or visualization.

OptimizationRunRepository

OptimizationRunRepository = BaseRepository[OptimizationRun, str]

The storage contract for run instances, keyed by their own identity (design spec §24).

OptimizationContext

OptimizationContext(*, kpi_results=(), analytics_results=(), decision_results=(), twin_snapshot=None, simulation_results=())

Bundles the evidence an OptimizationModel may need (design spec §8) -- carried once, at construction; the executor never reaches back into a lower package on its own initiative.

Examples:

>>> context = OptimizationContext()
>>> context.kpi_results
()
>>> context.twin_snapshot is None
True

OptimizationModel

Bases: ABC

The root of every registrable optimization model type (design spec §8). Deliberately carries no shared abstract solve method; each category base (§11-§16) declares its own.

Statelessness. Every subclass, of every category, is stateless -- no instance attribute is mutated by any category method (§29, §32); statefulness lives entirely in OptimizationRun (§10). An EvolutionaryMetaheuristicModel in particular derives all randomness from a seed carried in problem.parameters/ state.attributes, never internal generator state (§33, §34).

PlanComparator

Compares OptimizationResult collections across two or more problems or solver configurations by delegating statistical treatment to analytics (design spec §19).

compare

compare(results_by_problem, *, variable=None)

For each problem key, extracts objective_value (or, when variable names one, that solution variable's value) from its result sequence and calls analytics.describe() -- never re-implements mean/percentile computation here (§19).

ConstraintProgrammingModel

Bases: OptimizationModel, ABC

The contract a future constraint-programming adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §13, §35's interface-purity proof).

EvolutionaryMetaheuristicModel

Bases: OptimizationModel, ABC

The contract a future evolutionary/metaheuristic adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §15, §35's interface-purity proof).

OptimizationExecutionError

OptimizationExecutionError(message, *, details=None)

Bases: MineProductivityError

OptimizationExecutor raised for a solve/iteration that should have been structurally valid -- distinct from a legitimately infeasible problem (design spec §28), which returns an OptimizationResult(feasible=False, ...) carrying a warning instead of raising.

OptimizationRunNotFoundError

OptimizationRunNotFoundError(message, *, details=None)

Bases: NotFoundError

OptimizationRunRepository.get(run_id) found no run for that id, or REGISTRY.get(code) found no registered OptimizationModel for that code (design spec §6).

OptimizationValidationError

OptimizationValidationError(message, *, details=None)

Bases: ValidationError

An OptimizationMetadata, OptimizationProblem, or OptimizationState failed validation (design spec §29, §9, §10), or a problem/category pairing violates §11/§14's variable-domain and objective-count rules.

OptimizationVersionConflictError

OptimizationVersionConflictError(message, *, details=None)

Bases: RegistrationError

A plugin attempted to re-register an existing OptimizationModel type code with materially different metadata without a version bump, mirroring simulation.SimulationVersionConflictError (spec 09 §6).

ProblemConflictError

ProblemConflictError(message, *, details=None)

Bases: RegistrationError

A governance action attempted to re-register an existing, Active OptimizationProblem code with different objectives/ constraints/variables without a version bump and a Superseded transition for the prior version (design spec §9, §25).

OptimizationExecutor

OptimizationExecutor(*, repository)

Orchestrates one OptimizationRun: fetches the current instance, validates the problem/category pairing (§11's variable-domain rule, §14's objective-count rule), dispatches to the registered model's category-specific method -- looping iterative categories to convergence or the termination bound -- and persists the resulting state (design spec §10's sequence diagram).

execute

execute(run_id, problem, *, context)

Solve problem for the run stored under run_id.

A run already Completed/Failed is terminal (design spec §10): execution is skipped and a warning-carrying result returned. A legitimately infeasible problem returns feasible=False plus a warning, never a raise (§28).

Raises:

Type Description
OptimizationRunNotFoundError

If no run is stored under run_id, or no OptimizationModel is registered for problem.model_code.

OptimizationValidationError

If the problem/category pairing violates §11's variable-domain rule or §14's objective-count rule.

OptimizationExecutionError

If the model's category method raised for a structurally valid input (the run is marked Failed first, §10), or the repository's per-id write serialization contract was violated mid-swap (§32).

LinearProgrammingModel

Bases: OptimizationModel, ABC

The contract a future linear-programming adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §11, §35's interface-purity proof).

OptimizationCategory

Bases: Enum

Closed enum -- adding a member is a governance-reviewed change, mirroring simulation.SimulationCategory's closed-enum rule (spec 09 §29).

OptimizationMetadata dataclass

OptimizationMetadata(code, *, name='', description, tags=frozenset(), attributes=dict(), category, version='1.0.0')

Bases: BaseMetadata

The minimal registration schema for a discoverable OptimizationModel type (design spec §29). code names a type (e.g. "MIP.FleetAllocation"), never a run.

Examples:

>>> meta = OptimizationMetadata(
...     code="MIP.FleetAllocation",
...     category=OptimizationCategory.MIXED_INTEGER_PROGRAMMING,
...     description="Fleet/shift allocation as a MIP.",
... )
>>> meta.name
'MIP.FleetAllocation'

MixedIntegerProgrammingModel

Bases: OptimizationModel, ABC

The contract a future mixed-integer-programming adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §12, §35's interface-purity proof).

MultiObjectiveModel

Bases: OptimizationModel, ABC

The contract a future multi-objective adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §14, §35's interface-purity proof).

NetworkOptimizationModel

Bases: OptimizationModel, ABC

The contract a future network-optimization adapter plugin implements. THIS MODULE SHIPS NO CONCRETE SUBCLASS (design spec §16, §35's interface-purity proof).

Constraint dataclass

Constraint(name, expression, operator, bound)

Bases: BaseValueObject

One constraint the feasible region must satisfy (design spec §9). expression is a solver-independent string this package never parses or evaluates -- a concrete OptimizationModel adapter's own translation is where it is interpreted (§17).

Examples:

>>> Constraint(
...     name="truck_budget", expression="trucks_route_a + trucks_route_b",
...     operator=ConstraintOperator.LESS_EQUAL, bound=27.0,
... ).bound
27.0

ConstraintOperator

Bases: Enum

The relational operator a Constraint enforces between its expression and its bound.

DecisionVariable dataclass

DecisionVariable(name, domain, *, lower_bound=None, upper_bound=None)

Bases: BaseValueObject

One variable an OptimizationModel solves for (design spec §9). lower_bound/upper_bound default to None (unbounded), matching core's None-over-sentinel convention.

Examples:

>>> DecisionVariable(name="trucks_route_a", domain=VariableDomain.INTEGER).lower_bound

Objective dataclass

Objective(name, direction, *, weight=1.0)

Bases: BaseValueObject

One term of an OptimizationProblem's objective function (design spec §9). A single-objective problem declares exactly one; a multi-objective problem (§14) declares two or more, each with an optional weight a scalarizing implementation may use -- and a Pareto-search implementation is free to ignore.

Examples:

>>> Objective(name="tonnes_moved", direction=ObjectiveDirection.MAXIMIZE).weight
1.0

ObjectiveDirection

Bases: Enum

Whether an Objective is minimized or maximized.

OptimizationProblem dataclass

OptimizationProblem(code, *, version='1.0.0', status=(lambda: ProblemStatus.PROPOSED)(), model_code, objectives, constraints=(), variables, parameters=dict(), initial_state=None, as_of=None)

Bases: BaseValueObject

A named, versioned optimization problem statement -- the governed artifact this package owns, analogous to simulation.Scenario (spec 09 §9) one layer down. An Active problem is never edited in place: a changed problem is a new version, the prior one Superseded (§9, §25).

Examples:

>>> problem = OptimizationProblem(
...     code="FLEET.NightShiftAllocation",
...     model_code="MIP.FleetAllocation",
...     objectives=(Objective(name="tonnes", direction=ObjectiveDirection.MAXIMIZE),),
...     variables=(DecisionVariable(name="trucks", domain=VariableDomain.INTEGER),),
... )
>>> problem.status
<ProblemStatus.PROPOSED: 'proposed'>

ProblemStatus

Bases: Enum

The OptimizationProblem lifecycle -- mirrors simulation.ScenarioStatus (spec 09 §9) exactly.

VariableDomain

Bases: Enum

The domain a DecisionVariable's optimal value is drawn from.

OptimizationResult dataclass

OptimizationResult(run_id='', computed_at=(lambda: datetime.now(timezone.utc))(), warnings=(), *, feasible=True, objective_value=None, solution=dict())

Bases: BaseValueObject

The shared envelope every concrete optimization outcome composes -- mirrors simulation.SimulationResult's role (spec 09 §18).

Examples:

>>> result = OptimizationResult(objective_value=42.0, solution={"trucks": 7.0})
>>> result.feasible, result.solution["trucks"]
(True, 7.0)

ParetoResult dataclass

ParetoResult(run_id='', computed_at=(lambda: datetime.now(timezone.utc))(), warnings=(), *, feasible=True, objective_value=None, solution=dict(), front)

Bases: OptimizationResult

The outcome of a MultiObjectiveModel search (design spec §14, §18) -- a set of mutually non-dominated candidates, not a single winner; the trade-off surface lives entirely in front.

Examples:

>>> pareto = ParetoResult(front=(OptimizationResult(objective_value=1.0),))
>>> len(pareto.front)
1

OptimizationRun dataclass

OptimizationRun(id, problem_code, state, status=RunStatus.SCHEDULED)

Bases: BaseEntity[str]

The root of one executing or completed optimization attempt -- 'Run-as-entity,' following simulation.SimulationRun's own precedent (spec 09 §10) exactly. Immutable; trivially safe to read and share across threads (design spec §32).

Examples:

>>> run = OptimizationRun(
...     id="RUN-1",
...     problem_code="FLEET.NightShiftAllocation",
...     state=OptimizationState(attributes={"provisioned": True}),
... )
>>> run.status
<RunStatus.SCHEDULED: 'scheduled'>
>>> run.with_state(run.state, status=RunStatus.RUNNING).status
<RunStatus.RUNNING: 'running'>
>>> run.status  # the original instance is untouched
<RunStatus.SCHEDULED: 'scheduled'>

with_state

with_state(state, *, status=None)

Returns a NEW OptimizationRun with state (and optionally status) replacing the current ones -- identical to SimulationRun.with_state() (spec 09 §10).

RunStatus

Bases: Enum

An OptimizationRun's own operational lifecycle -- mirrors simulation.RunStatus (spec 09 §10) exactly in shape. COMPLETED and FAILED are terminal (design spec §10's state diagram).

SensitivityAnalyzer

SensitivityAnalyzer(*, executor, repository)

Performs post-optimality analysis on a solved problem: how the optimal objective and feasibility respond to perturbing a named constraint's bound or objective's weight (design spec §20). Not to be confused with simulation.SensitivityAnalyzer -- two domain-appropriate uses of the same operations-research term in two packages' own namespaces.

sweep

sweep(base_problem, *, target, values, context)

Produces one re-solve per value in values, each a copy of base_problem with the named constraint bound or objective weight (target) overridden -- ordered to match values' order (design spec §20). Zero values is a legitimately incomplete input: an empty sequence is returned, never a raise (§28).

summarize

summarize(outcomes, *, confidence=0.95)

Hands a sweep's numeric outcomes to analytics for distributional treatment -- this method owns no arithmetic of its own (design spec §20, §35).

OptimizationState dataclass

OptimizationState(attributes)

Bases: BaseValueObject

One run's attributes as of the last executed solve or iteration -- a frozen value object; the entity is OptimizationRun (design spec §10). Deliberately not an OptimizationResult subclass (§18).

Examples:

>>> OptimizationState(attributes={"incumbent": 42.0}).attributes["incumbent"]
42.0

register

register(cls)

Register cls into :data:REGISTRY, keyed by cls.meta.code.

Raises:

Type Description
OptimizationValidationError

If cls.meta.code is empty (defensive, redundant guard -- OptimizationMetadata.validate() already rejects it).

OptimizationVersionConflictError

If cls.meta.code is already registered -- add-only, raised at registration time, never deferred (design spec §25).

by_category

by_category(category)

A specification satisfied by every run whose published problem's registered model belongs to category -- compose with OptimizationRunRepository.list() freely; an empty result is a legitimate answer, never a raise (design spec §22).

Examples:

>>> from mineproductivity.core import InMemoryRepository
>>> repository: InMemoryRepository[OptimizationRun, str] = InMemoryRepository()
>>> repository.list(by_category(OptimizationCategory.LINEAR_PROGRAMMING))
[]

by_scope

by_scope(scope)

A specification satisfied by every run carrying every key/value pair in scope, resolved against problem_code/status first and the open state.attributes mapping otherwise.

Examples:

>>> from mineproductivity.core import InMemoryRepository
>>> repository: InMemoryRepository[OptimizationRun, str] = InMemoryRepository()
>>> repository.list(by_scope({"problem_code": "FLEET.NightShiftAllocation"}))
[]