Skip to content

mamut_routing_lib.solvers

Solver integrations: a registry of solvers behind one protocol.

from mamut_routing_lib.solvers import run_solver

solved = run_solver("pyvrp", "path/to/instance.vrp.json", time_limit_s=30, seed=1)
solved.valid, solved.cost, solved.result.routes

Importing this package never imports PyVRP or KAYROS; see solvers.registry for the solver sources and solvers.base for the protocol.

BUILTIN_SOLVERS module-attribute

BUILTIN_SOLVERS = (
    "pyvrp",
    "kayros",
    "filo2",
    "hgs-cvrp",
    "ails2",
    "lkh3",
)

IN_PROCESS_SOLVERS module-attribute

IN_PROCESS_SOLVERS = ('pyvrp', 'kayros')

Availability dataclass

Availability(
    available: bool,
    reason: str | None = None,
    version: str | None = None,
    executable: str | None = None,
    hint: str | None = None,
    note: str | None = None,
)

Whether a solver can run here (reason explains a False).

hint says how to make it available (install, configure); note is a standing requirement worth knowing either way (a patched build, for instance).

available instance-attribute

available: bool

reason class-attribute instance-attribute

reason: str | None = None

version class-attribute instance-attribute

version: str | None = None

executable class-attribute instance-attribute

executable: str | None = None

hint class-attribute instance-attribute

hint: str | None = None

note class-attribute instance-attribute

note: str | None = None

describe

describe() -> str

reason (hint). note -- one line for an error message.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def describe(self) -> str:
    """``reason (hint). note`` -- one line for an error message."""
    text = self.reason or ("available" if self.available else "not available")
    if self.hint:
        text = f"{text} ({self.hint})"
    if self.note:
        text = f"{text}. {self.note[0].upper()}{self.note[1:]}"
    return text

to_json

to_json() -> dict[str, Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def to_json(self) -> dict[str, Any]:
    return {
        "available": self.available,
        "reason": self.reason,
        "version": self.version,
        "executable": self.executable,
        "hint": self.hint,
        "note": self.note,
    }

InstanceNotSupportedError

Bases: ValueError

The solver cannot take this instance/objective (see Support.reasons).

Distinct from cvrplib.UnsupportedInstanceError, which is about classic export formats.

InstanceProfile dataclass

InstanceProfile(
    problem_type: ProblemType,
    benchmark_name: str | None,
    metric_variant: str | None,
    num_customers: int,
    depot: int,
    fixed_fleet: int | None,
    has_coordinates: bool,
    coordinates_define_costs: bool,
    symmetric: bool | None,
    has_fleet_fixed_cost: bool = False,
)

Cheap facts about an instance, enough to decide solver support without solving.

symmetric is True for the euclidean metric (symmetric by construction), False or True when a matrix was inspected, and None when unknown; solvers that need symmetry check the matrix at solve time.

problem_type instance-attribute

problem_type: ProblemType

benchmark_name instance-attribute

benchmark_name: str | None

metric_variant instance-attribute

metric_variant: str | None

num_customers instance-attribute

num_customers: int

depot instance-attribute

depot: int

fixed_fleet instance-attribute

fixed_fleet: int | None

has_coordinates instance-attribute

has_coordinates: bool

coordinates_define_costs instance-attribute

coordinates_define_costs: bool

symmetric instance-attribute

symmetric: bool | None

has_fleet_fixed_cost class-attribute instance-attribute

has_fleet_fixed_cost: bool = False

SolveMonitor

SolveMonitor(
    on_tick: Callable[[SolveTick], bool] | None = None,
    *,
    scale: float = 1,
    interval_s: float = 1.0,
    budget_s: float | None = None,
    record_trajectory: bool = False,
    trajectory_min_gap_s: float = 0.5,
    cancelled: Callable[[], bool] | None = None,
)

Progress and cancellation hook shared by every solver driver.

  • observe(best_cost, iterations=...) is the generic entry point: it checks for a stop request on every call, records the trajectory, and relays a throttled :class:SolveTick to on_tick. It returns True when the solve must stop (on_tick returned True or request_stop was called).
  • __call__(best_cost) is the PyVRP stopping-criterion protocol: PyVRP calls it once per iteration with the incumbent's cost. It counts the iteration, maps PyVRP's infeasible sentinel to None and delegates to observe. Compose it before MaxRuntime in a MultipleCriteria: that class uses any(), which short-circuits, so a monitor placed second would go silent the moment the budget expires.

best_cost is in solver units; rescale sets the factor that brings it back to instance units.

cancelled is a cheap poll (a job's cancel flag, say) read by stop_requested and by every observe call, unthrottled: a driver checks it between its own steps (an external solver before and after writing a large input), not only when a tick is due.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def __init__(
    self,
    on_tick: Callable[[SolveTick], bool] | None = None,
    *,
    scale: float = 1,
    interval_s: float = 1.0,
    budget_s: float | None = None,
    record_trajectory: bool = False,
    trajectory_min_gap_s: float = 0.5,
    cancelled: Callable[[], bool] | None = None,
):
    self._on_tick = on_tick
    self._cancelled = cancelled
    self._scale = scale if scale and scale > 0 else 1
    self._interval_s = max(0.0, interval_s)
    self._budget_s = budget_s
    self._phase = "search"
    self._iterations = 0
    self._start = time.perf_counter()
    # -inf, not the start time: the first observation should report immediately rather than
    # leave the caller showing nothing for a whole interval.
    self._last_tick = float("-inf")
    self._stop = threading.Event()
    self._record = record_trajectory
    self._trajectory_gap = max(0.0, trajectory_min_gap_s)
    self.trajectory: list[tuple[float, float]] = []
    self.stopped_early = False
    self.best_cost: float | None = None

trajectory instance-attribute

trajectory: list[tuple[float, float]] = []

stopped_early instance-attribute

stopped_early = False

best_cost instance-attribute

best_cost: float | None = None

current_phase property

current_phase: str

elapsed_s property

elapsed_s: float

iterations property

iterations: int

stop_requested property

stop_requested: bool

phase

phase(name: str) -> None

Name the stage the solve has just entered, and tick on the next observation so the label lands.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def phase(self, name: str) -> None:
    """Name the stage the solve has just entered, and tick on the next observation so the label lands."""
    self._phase = name
    self._last_tick = float("-inf")
    # Phases can optimise different objectives (PyVRP's hierarchical solve adds a fleet cost in
    # its last phase), so the running best restarts with each phase.
    self.best_cost = None

rescale

rescale(scale: float | Fraction) -> None

Adopt the solve's cost scale, which is only known once the instance is converted.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def rescale(self, scale: float | Fraction) -> None:
    """Adopt the solve's cost scale, which is only known once the instance is converted."""
    self._scale = scale if scale and scale > 0 else 1

set_budget

set_budget(budget_s: float | None) -> None
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def set_budget(self, budget_s: float | None) -> None:
    self._budget_s = budget_s

restart_clock

restart_clock() -> None

Measure elapsed time from now (the monitor may be built well before the solve starts).

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def restart_clock(self) -> None:
    """Measure elapsed time from now (the monitor may be built well before the solve starts)."""
    self._start = time.perf_counter()
    self._last_tick = float("-inf")

request_stop

request_stop() -> None

Ask the solve to stop at its next observation (thread-safe).

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def request_stop(self) -> None:
    """Ask the solve to stop at its next observation (thread-safe)."""
    self._stop.set()

observe

observe(
    best_cost: float | None = None,
    *,
    iterations: int | None = None,
    force: bool = False,
) -> bool

Record one observation; True means the solve must stop.

best_cost is the incumbent in solver units (None when nothing feasible is known); iterations overrides the internal counter for drivers that report their own.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def observe(
    self,
    best_cost: float | None = None,
    *,
    iterations: int | None = None,
    force: bool = False,
) -> bool:
    """Record one observation; True means the solve must stop.

    ``best_cost`` is the incumbent in solver units (``None`` when nothing feasible is known);
    ``iterations`` overrides the internal counter for drivers that report their own.
    """
    if iterations is not None:
        self._iterations = iterations
    now = time.perf_counter()
    elapsed = now - self._start
    real_cost = None
    if best_cost is not None and best_cost < INFEASIBLE_COST:
        if isinstance(self._scale, Fraction):
            try:
                real_cost = float(Fraction(best_cost) / self._scale)
            except OverflowError:
                real_cost = None
        else:
            real_cost = best_cost / self._scale
        if real_cost is not None and (self.best_cost is None or real_cost < self.best_cost):
            self.best_cost = real_cost
            if self._record:
                self._record_point(elapsed, real_cost)
    if self.stop_requested:
        self.stopped_early = True
        return True
    if not force and now - self._last_tick < self._interval_s:
        return False
    self._last_tick = now
    if self._on_tick is None:
        return False
    tick = SolveTick(
        phase=self._phase,
        iterations=self._iterations if (iterations is not None or self._iterations) else None,
        elapsed_s=elapsed,
        best_cost=real_cost if real_cost is not None else self.best_cost,
        budget_s=self._budget_s,
    )
    if self._on_tick(tick):
        self._stop.set()
        self.stopped_early = True
        return True
    return False

SolveRequest dataclass

SolveRequest(
    instance: Any,
    instance_path: Path | None,
    objective: ObjectiveFunction,
    time_limit_s: float,
    seed: int = 42,
    initial_routes: list[list[int]] | None = None,
    workdir: Path | None = None,
    keep_artifacts: bool = False,
    display: bool = False,
    options: Mapping[str, Any] = dict(),
)

One solve: the instance (already loaded), where it lives, and the run parameters.

instance instance-attribute

instance: Any

instance_path instance-attribute

instance_path: Path | None

objective instance-attribute

objective: ObjectiveFunction

time_limit_s instance-attribute

time_limit_s: float

seed class-attribute instance-attribute

seed: int = 42

initial_routes class-attribute instance-attribute

initial_routes: list[list[int]] | None = None

workdir class-attribute instance-attribute

workdir: Path | None = None

keep_artifacts class-attribute instance-attribute

keep_artifacts: bool = False

display class-attribute instance-attribute

display: bool = False

options class-attribute instance-attribute

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

checkable

checkable() -> Any

The instance in the form the reference checker reads, loaded once per request.

A static instance with its collection matrix hydrated from the sidecar, or the LoadedTDInstance of a time-dependent one (solutions.load_checkable). The adapter that writes the solver's input and run_solver's check share it, so one solve reads a large matrix once. Raises what the loaders raise (a sidecar that is missing, say).

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def checkable(self) -> Any:
    """The instance in the form the reference checker reads, loaded once per request.

    A static instance with its collection matrix hydrated from the sidecar, or the
    ``LoadedTDInstance`` of a time-dependent one (``solutions.load_checkable``). The adapter that
    writes the solver's input and ``run_solver``'s check share it, so one solve reads a large
    matrix once. Raises what the loaders raise (a sidecar that is missing, say).
    """
    if self._checkable is None:
        from mamut_routing_lib.solutions import load_checkable

        object.__setattr__(self, "_checkable", load_checkable(self.instance, self.instance_path))
    return self._checkable

SolveResult dataclass

SolveResult(
    solver: str,
    method: str,
    problem_type: str,
    objective_function: str,
    instance_id: str,
    seed: int,
    time_limit_s: float,
    wall_time: float,
    status: SolveStatus,
    routes: list[list[int]] = list(),
    solver_report: dict[str, Any] | None = None,
    cost_scale: int | float | None = 1.0,
    stopped_early: bool = False,
    error: str | None = None,
    solver_version: str | None = None,
    metadata: dict[str, Any] = dict(),
    provenance: dict[str, Any] = dict(),
)

What a solver returned, before (and independent of) the reference checker's verdict.

solver_report preserves the reported objective, value, numeric encoding and unit. solver_cost is the optional nearest-binary64 projection of its routing component in family units. The checker computes the route set's authoritative cost separately.

solver instance-attribute

solver: str

method instance-attribute

method: str

problem_type instance-attribute

problem_type: str

objective_function instance-attribute

objective_function: str

instance_id instance-attribute

instance_id: str

seed instance-attribute

seed: int

time_limit_s instance-attribute

time_limit_s: float

wall_time instance-attribute

wall_time: float

status instance-attribute

status: SolveStatus

routes class-attribute instance-attribute

routes: list[list[int]] = field(default_factory=list)

solver_report class-attribute instance-attribute

solver_report: dict[str, Any] | None = None

cost_scale class-attribute instance-attribute

cost_scale: int | float | None = 1.0

stopped_early class-attribute instance-attribute

stopped_early: bool = False

error class-attribute instance-attribute

error: str | None = None

solver_version class-attribute instance-attribute

solver_version: str | None = None

metadata class-attribute instance-attribute

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

provenance class-attribute instance-attribute

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

solver_cost property

solver_cost: float | None

has_routes property

has_routes: bool

to_json

to_json() -> dict[str, Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def to_json(self) -> dict[str, Any]:
    return {
        "solver": self.solver,
        "method": self.method,
        "problem_type": self.problem_type,
        "objective_function": self.objective_function,
        "instance_id": self.instance_id,
        "seed": self.seed,
        "time_limit_s": self.time_limit_s,
        "wall_time": self.wall_time,
        "status": self.status,
        "routes": self.routes,
        **solver_report_metadata(self.solver_report),
        "cost_scale": self.cost_scale,
        "stopped_early": self.stopped_early,
        "error": self.error,
        "solver_version": self.solver_version,
        "metadata": self.metadata,
        "provenance": self.provenance,
    }

SolveTick dataclass

SolveTick(
    phase: str,
    iterations: int | None,
    elapsed_s: float,
    best_cost: float | None,
    budget_s: float | None = None,
)

One observation of a running solve.

phase instance-attribute

phase: str

iterations instance-attribute

iterations: int | None

elapsed_s instance-attribute

elapsed_s: float

best_cost instance-attribute

best_cost: float | None

budget_s class-attribute instance-attribute

budget_s: float | None = None

Solver

Bases: Protocol

A solver integration. solve never raises for a solver failure (timeout, crash, garbage output): it returns a SolveResult with status failed or timeout. It raises SolverUnavailableError / InstanceNotSupportedError only for usage errors.

name instance-attribute

name: str

label instance-attribute

label: str

capabilities instance-attribute

capabilities: SolverCapabilities

availability

availability() -> Availability
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def availability(self) -> Availability: ...

supports

supports(
    profile: InstanceProfile, objective: ObjectiveFunction
) -> Support
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def supports(self, profile: InstanceProfile, objective: ObjectiveFunction) -> Support: ...

solve

solve(
    request: SolveRequest,
    monitor: SolveMonitor | None = None,
) -> SolveResult
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def solve(self, request: SolveRequest, monitor: SolveMonitor | None = None) -> SolveResult: ...

SolverCapabilities dataclass

SolverCapabilities(
    objectives: Mapping[
        ProblemType, frozenset[ObjectiveFunction]
    ],
    input: Literal[
        "model", "coordinates", "explicit"
    ] = "model",
    symmetric_only: bool = False,
    integer_costs: bool = False,
    fleet_limit: bool = True,
    warm_start: bool = False,
    live_progress: Literal[
        "none", "elapsed", "incumbent"
    ] = "none",
    cancellable: bool = True,
    in_process: bool = False,
)

What a solver can take. objectives maps each supported problem type to its objectives.

objectives instance-attribute

objectives: Mapping[
    ProblemType, frozenset[ObjectiveFunction]
]

input class-attribute instance-attribute

input: Literal["model", "coordinates", "explicit"] = "model"

symmetric_only class-attribute instance-attribute

symmetric_only: bool = False

integer_costs class-attribute instance-attribute

integer_costs: bool = False

fleet_limit class-attribute instance-attribute

fleet_limit: bool = True

warm_start class-attribute instance-attribute

warm_start: bool = False

live_progress class-attribute instance-attribute

live_progress: Literal["none", "elapsed", "incumbent"] = (
    "none"
)

cancellable class-attribute instance-attribute

cancellable: bool = True

in_process class-attribute instance-attribute

in_process: bool = False

problem_types property

problem_types: frozenset[ProblemType]

time_dependent property

time_dependent: bool

to_json

to_json() -> dict[str, Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def to_json(self) -> dict[str, Any]:
    return {
        "objectives": {problem.value: sorted(obj.value for obj in objs) for problem, objs in self.objectives.items()},
        "input": self.input,
        "symmetric_only": self.symmetric_only,
        "integer_costs": self.integer_costs,
        "fleet_limit": self.fleet_limit,
        "warm_start": self.warm_start,
        "live_progress": self.live_progress,
        "cancellable": self.cancellable,
        "in_process": self.in_process,
        "time_dependent": self.time_dependent,
    }

SolverUnavailableError

Bases: RuntimeError

The solver cannot run here: missing Python extra, executable not found, bad configuration.

Support dataclass

Support(
    supported: bool,
    reasons: tuple[str, ...] = (),
    warnings: tuple[str, ...] = (),
)

Whether a solver can take one instance under one objective; warnings never block.

supported instance-attribute

supported: bool

reasons class-attribute instance-attribute

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

warnings class-attribute instance-attribute

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

ok classmethod

ok(*warnings: str) -> 'Support'
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
@classmethod
def ok(cls, *warnings: str) -> "Support":
    return cls(True, (), tuple(warnings))

refuse classmethod

refuse(*reasons: str) -> 'Support'
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
@classmethod
def refuse(cls, *reasons: str) -> "Support":
    return cls(False, tuple(reasons), ())

to_json

to_json() -> dict[str, Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def to_json(self) -> dict[str, Any]:
    return {"supported": self.supported, "reasons": list(self.reasons), "warnings": list(self.warnings)}

UnknownSolverError

Bases: ValueError

No solver of that name; the message lists the known ones.

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-tools/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-tools/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-tools/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"},
    }

profile_instance

profile_instance(
    instance: Any,
    instance_path: str | Path | None = None,
    *,
    inspect_matrix: bool = False,
) -> InstanceProfile

Profile an instance (static or time-dependent) for Solver.supports.

With inspect_matrix the arc costs are hydrated and checked for symmetry and for being a rounding of the coordinates' Euclidean distances (O(n²); done at solve time, not for listings).

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/base.py
def profile_instance(
    instance: Any,
    instance_path: str | Path | None = None,
    *,
    inspect_matrix: bool = False,
) -> InstanceProfile:
    """Profile an instance (static or time-dependent) for ``Solver.supports``.

    With ``inspect_matrix`` the arc costs are hydrated and checked for symmetry and for being a
    rounding of the coordinates' Euclidean distances (O(n²); done at solve time, not for listings).
    """
    from mamut_routing_lib.artifacts import instance_problem_type, is_collection_instance

    problem_type = instance_problem_type(instance)
    metadata = getattr(instance, "metadata", None)
    metric = getattr(instance, "metric_variant", None)
    if metric is None:
        if isinstance(metadata, Mapping):
            metric = metadata.get("metric_variant")
        else:
            metric = getattr(metadata, "metric_variant", None)
    metric_value = getattr(metric, "value", metric)
    benchmark = getattr(instance, "benchmark_name", None)
    benchmark_value = getattr(benchmark, "value", benchmark)
    coordinates = getattr(instance, "coordinates", None)
    time_dependent = problem_type in (ProblemType.TDVRP, ProblemType.TDVRPTW)

    symmetric: bool | None = True if metric_value == "euclidean" else None
    coords_define = False
    if not time_dependent:
        source = getattr(instance, "arc_costs_source", None)
        if is_collection_instance(instance) and getattr(source, "model", None) == "euclidean":
            coords_define = True
        elif inspect_matrix or not is_collection_instance(instance):
            try:
                from mamut_routing_lib.artifacts import resolve_arc_costs
                from mamut_routing_lib.cvrplib import coordinates_define_arc_costs, is_symmetric_matrix

                if is_collection_instance(instance):
                    if instance_path is None:
                        raise ValueError("collection instance without a path")
                    matrix = resolve_arc_costs(instance, instance_path)
                else:
                    matrix = instance.arc_costs
                coords_define = coordinates_define_arc_costs(instance, matrix)
                if inspect_matrix or not is_collection_instance(instance):
                    symmetric = is_symmetric_matrix(matrix)
            except (ValueError, OSError, FileNotFoundError):
                pass
    return InstanceProfile(
        problem_type=problem_type,
        benchmark_name=benchmark_value,
        metric_variant=metric_value,
        num_customers=int(getattr(instance, "num_customers", 0) or 0),
        depot=int(getattr(instance, "depot", 0) or 0),
        fixed_fleet=getattr(instance, "num_vehicles", None),
        has_coordinates=bool(coordinates),
        coordinates_define_costs=coords_define,
        symmetric=symmetric,
        has_fleet_fixed_cost=getattr(instance, "fleet_fixed_cost", None) is not None,
    )

get_solver

get_solver(
    name: str, *, config: ConfigPath = None
) -> Solver

The solver called name; UnknownSolverError lists the known names.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/registry.py
def get_solver(name: str, *, config: ConfigPath = None) -> Solver:
    """The solver called ``name``; ``UnknownSolverError`` lists the known names."""
    in_process = name in IN_PROCESS_SOLVERS
    key = ("" if in_process else _config_key(config), name)
    cached = _CACHE.get(key)
    if cached is not None:
        return cached
    sources = _sources(config, with_config=not in_process)
    if name not in sources:
        raise UnknownSolverError(f"unknown solver {name!r}; known solvers: {', '.join(solver_names(config=config))}")
    solver = _instantiate(sources[name])
    _CACHE[key] = solver
    return solver

list_solvers

list_solvers(*, config: ConfigPath = None) -> list[Solver]

Every known solver, available or not, in solver_names order.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/registry.py
def list_solvers(*, config: ConfigPath = None) -> list[Solver]:
    """Every known solver, available or not, in ``solver_names`` order."""
    return [get_solver(name, config=config) for name in solver_names(config=config)]

register_solver

register_solver(
    solver: SolverSource,
    *,
    name: str | None = None,
    replace: bool = False,
) -> None

Register a solver instance or zero-argument factory under name (default: its name).

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/registry.py
def register_solver(solver: SolverSource, *, name: str | None = None, replace: bool = False) -> None:
    """Register a solver instance or zero-argument factory under ``name`` (default: its ``name``)."""
    key = name or getattr(solver, "name", None)
    if not key:
        raise ValueError("register_solver needs a name (the solver has no 'name' attribute)")
    if key in _REGISTERED and not replace:
        raise ValueError(f"a solver named {key!r} is already registered (pass replace=True)")
    if key in BUILTIN_SOLVERS and not replace:
        raise ValueError(f"{key!r} is a built-in solver (pass replace=True to replace it on purpose)")
    _REGISTERED[key] = solver
    _CACHE.clear()

reload_solvers

reload_solvers() -> None

Forget cached solver objects, entry points and the parsed user config.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/registry.py
def reload_solvers() -> None:
    """Forget cached solver objects, entry points and the parsed user config."""
    global _ENTRY_POINTS
    _CACHE.clear()
    _ENTRY_POINTS = None
    try:
        from mamut_routing_lib.solvers.external import config as external_config

        external_config.clear_cache()
    except ImportError:  # pragma: no cover - the external package ships with the lib
        pass

solver_names

solver_names(*, config: ConfigPath = None) -> list[str]

Every known solver name: built-ins first, then plugins, registrations and configured solvers.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/solvers/registry.py
def solver_names(*, config: ConfigPath = None) -> list[str]:
    """Every known solver name: built-ins first, then plugins, registrations and configured solvers."""
    sources = _sources(config)
    names = [name for name in BUILTIN_SOLVERS if name in sources]
    for name in sources:
        if name not in names:
            names.append(name)
    return names

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-tools/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-tools/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,
    )