Skip to content

mamut_routing_lib.solvers.run

Run any registered solver on one instance and check its routes.

run_solver is the one entry point the CLIs, the tools GUI and campaign runners share:

  1. load the instance (static or time-dependent) unless it is given;
  2. pick the objective (objectives.default_objective when none is given);
  3. refuse an unavailable solver (SolverUnavailableError) or an instance the solver cannot take (InstanceNotSupportedError), before any work;
  4. solve, with the monitor's clock restarted and its budget set;
  5. price the routes with the reference checker (solutions.check_routes).

The checker's verdict and cost are authoritative; the solver's own cost is kept in the result for information. Storing a BKS is the caller's decision (solutions.submit_bks / bks.save_solution_as_bks_if_improved), so that a campaign can keep a single writer per instance.

BKS_PROVENANCE_KEYS module-attribute

BKS_PROVENANCE_KEYS = (
    "method",
    "solver",
    "solver_version",
    "seed",
    "time_limit_s",
    "wall_time",
    "solver_cost",
    "solver_report",
    "machine",
    "vehicle_penalty",
    "executable_sha256",
    "input_sha256",
)

CheckedSolve dataclass

CheckedSolve(
    result: SolveResult,
    check: Any | None,
    objective: ObjectiveFunction,
    instance_path: Path,
    instance_name: str,
    support_warnings: tuple[str, ...] = (),
    extra: dict[str, Any] = dict(),
    checkable: Any = None,
)

A solver result plus the reference checker's verdict on its routes.

result instance-attribute

result: SolveResult

check instance-attribute

check: Any | None

objective instance-attribute

objective: ObjectiveFunction

instance_path instance-attribute

instance_path: Path

instance_name instance-attribute

instance_name: str

support_warnings class-attribute instance-attribute

support_warnings: tuple[str, ...] = ()

extra class-attribute instance-attribute

extra: dict[str, Any] = field(default_factory=dict)

checkable class-attribute instance-attribute

checkable: Any = field(
    default=None, repr=False, compare=False
)

valid property

valid: bool

cost property

cost: int | float | None

The checker's cost of the routes (None unless valid).

num_routes property

num_routes: int

validation_status property

validation_status: str

to_solution

to_solution(
    *, metadata: Mapping[str, Any] | None = None
) -> Any

The routes as a BenchmarkSolution (cost left to the checker).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/run.py
def to_solution(self, *, metadata: Mapping[str, Any] | None = None) -> Any:
    """The routes as a ``BenchmarkSolution`` (cost left to the checker)."""
    from mamut_routing_lib.models import BenchmarkSolution

    return BenchmarkSolution(
        instance_name=self.instance_name,
        routes=[list(route) for route in self.result.routes],
        cost=None,
        metadata=dict(metadata or {}),
    )

bks_metadata

bks_metadata(**extra: Any) -> dict[str, Any]

Provenance for a BKS built from this solve (no hostname: BKS files are published).

The keys are :data:BKS_PROVENANCE_KEYS. extra adds keys of the caller (a campaign name, a run key); it cannot replace a provenance key or set a key of the BKS store.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/run.py
def bks_metadata(self, **extra: Any) -> dict[str, Any]:
    """Provenance for a BKS built from this solve (no hostname: BKS files are published).

    The keys are :data:`BKS_PROVENANCE_KEYS`. ``extra`` adds keys of the caller (a campaign
    name, a run key); it cannot replace a provenance key or set a key of the BKS store.
    """
    from mamut_routing_lib.solutions import STORE_METADATA_KEYS

    clash = sorted(key for key in extra if key in BKS_PROVENANCE_KEYS or key in STORE_METADATA_KEYS or key == "cost_exact")
    if clash:
        raise ValueError(f"bks_metadata cannot override {', '.join(clash)}")
    result = self.result
    values: dict[str, Any] = {
        "method": result.method,
        "solver": result.solver,
        "solver_version": result.solver_version,
        "seed": result.seed,
        "time_limit_s": result.time_limit_s,
        "wall_time": round(result.wall_time, 3),
        **solver_report_metadata(result.solver_report),
        "machine": result.provenance.get("machine"),
    }
    if "vehicle_penalty" in result.metadata:
        values["vehicle_penalty"] = result.metadata["vehicle_penalty"]
    for key in ("executable_sha256", "input_sha256"):
        if result.provenance.get(key):
            values[key] = result.provenance[key]
    values.update(extra)
    return {key: value for key, value in values.items() if value is not None}

to_json

to_json() -> dict[str, Any]

A JSON-ready summary: the checker's verdict next to the solver result.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/run.py
def to_json(self) -> dict[str, Any]:
    """A JSON-ready summary: the checker's verdict next to the solver result."""
    check = None
    if self.check is not None:
        check = self.check.model_dump(mode="json")
    return {
        "ok": self.valid and self.result.status in ("feasible", "timeout"),
        "valid": self.valid,
        "cost": self.cost,
        "validation": self.validation_status,
        "objective_function": self.objective.value,
        "instance_name": self.instance_name,
        "instance_path": str(self.instance_path),
        "support_warnings": list(self.support_warnings),
        "check": check,
        **{key: value for key, value in self.result.to_json().items() if key != "objective_function"},
    }

prepare_solve

prepare_solve(
    solver: str | Solver,
    instance_path: str | Path,
    *,
    objective_function: ObjectiveFunction | None = None,
    instance: Any = None,
    config: Any = None,
) -> tuple[Solver, Any, ObjectiveFunction, tuple[str, ...]]

Resolve and vet a solve without running it: (solver, instance, objective, support warnings).

Raises SolverUnavailableError or InstanceNotSupportedError with the reasons.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/run.py
def prepare_solve(
    solver: str | Solver,
    instance_path: str | Path,
    *,
    objective_function: ObjectiveFunction | None = None,
    instance: Any = None,
    config: Any = None,
) -> tuple[Solver, Any, ObjectiveFunction, tuple[str, ...]]:
    """Resolve and vet a solve without running it: (solver, instance, objective, support warnings).

    Raises ``SolverUnavailableError`` or ``InstanceNotSupportedError`` with the reasons.
    """
    from mamut_routing_lib.artifacts import load_benchmark_instance
    from mamut_routing_lib.objectives import default_objective

    solver_obj = _resolve_solver(solver, config)
    path = Path(instance_path)
    loaded = instance if instance is not None else load_benchmark_instance(path)
    objective = objective_function or default_objective(loaded)
    availability = solver_obj.availability()
    if not availability.available:
        raise SolverUnavailableError(f"{solver_obj.name}: {availability.describe()}")
    support = solver_obj.supports(profile_instance(loaded, path), objective)
    if not support.supported:
        raise InstanceNotSupportedError(f"{solver_obj.name}: " + "; ".join(support.reasons))
    return solver_obj, loaded, objective, support.warnings

run_solver

run_solver(
    solver: str | Solver,
    instance_path: str | Path,
    *,
    time_limit_s: float,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    instance: Any = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    workdir: str | Path | None = None,
    keep_artifacts: bool = False,
    display: bool = False,
    options: Mapping[str, Any] | None = None,
    config: Any = None,
) -> CheckedSolve

Solve the instance at instance_path with solver (a name or a Solver) and check it.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/run.py
def run_solver(
    solver: str | Solver,
    instance_path: str | Path,
    *,
    time_limit_s: float,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    instance: Any = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    workdir: str | Path | None = None,
    keep_artifacts: bool = False,
    display: bool = False,
    options: Mapping[str, Any] | None = None,
    config: Any = None,
) -> CheckedSolve:
    """Solve the instance at ``instance_path`` with ``solver`` (a name or a ``Solver``) and check it."""
    from mamut_routing_lib.artifacts import get_instance_identifier
    from mamut_routing_lib.solutions import check_routes

    if not time_limit_s or time_limit_s <= 0:
        raise ValueError("time_limit_s must be positive")
    solver_obj, loaded, objective, warnings = prepare_solve(
        solver,
        instance_path,
        objective_function=objective_function,
        instance=instance,
        config=config,
    )
    path = Path(instance_path)
    if monitor is not None:
        monitor.restart_clock()
        monitor.set_budget(float(time_limit_s))
    request = SolveRequest(
        instance=loaded,
        instance_path=path,
        objective=objective,
        time_limit_s=float(time_limit_s),
        seed=int(seed),
        initial_routes=[list(route) for route in initial_routes] if initial_routes else None,
        workdir=Path(workdir) if workdir is not None else None,
        keep_artifacts=keep_artifacts,
        display=display,
        options=dict(options or {}),
    )
    result = solver_obj.solve(request, monitor)
    check = checkable = None
    if result.routes:
        checkable = request.checkable()  # already loaded when the adapter needed it for its input
        check = check_routes(loaded, path, result.routes, objective, checkable=checkable)
    return CheckedSolve(
        result=result,
        check=check,
        objective=objective,
        instance_path=path,
        instance_name=get_instance_identifier(loaded),
        support_warnings=tuple(warnings),
        checkable=checkable,
    )