Skip to content

mamut_routing_lib.solvers.pyvrp

PyVRP-backed solver integration for mamut-routing-lib.

Importing this module requires the [pyvrp] optional dependency:

pip install "mamut-routing-lib[pyvrp]"
Public API

to_vrplib_dict, to_pyvrp_problem -- conversion helpers MethodResult -- solver result dataclass SolveTick, SolveMonitor -- live progress / cancellation hook solve_cvrp, solve_vrptw, solve_instance -- single-instance solvers solve_and_update_bks -- solve + write BKS if improved

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-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-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-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-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-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-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-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

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

MethodResult dataclass

MethodResult(
    method: str,
    problem_type: str,
    objective_function: str,
    instance_id: str,
    seed: int,
    time_limit_s: int,
    wall_time: float,
    solver_is_feasible: bool,
    routes: list[list[int]] = list(),
    solver_report: dict[str, Any] | None = None,
    route_count: int = 0,
    vehicle_penalty: int = 0,
    metadata: dict[str, Any] = dict(),
)

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: int

wall_time instance-attribute

wall_time: float

solver_is_feasible instance-attribute

solver_is_feasible: bool

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

route_count class-attribute instance-attribute

route_count: int = 0

vehicle_penalty class-attribute instance-attribute

vehicle_penalty: int = 0

metadata class-attribute instance-attribute

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

solver_cost property

solver_cost: float | None

Display the reported routing cost in family units.

hydrate_collection_instance

hydrate_collection_instance(
    instance: AnyStaticBenchmarkInstance,
    instance_path: str | Path | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> LoadedStaticInstance
hydrate_collection_instance(
    instance: AnyTDBenchmarkInstance,
    instance_path: str | Path | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> AnyTDBenchmarkInstance
hydrate_collection_instance(
    instance: AnyBenchmarkInstance,
    instance_path: str | Path | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> AnyBenchmarkInstance

An embedded-matrix view of a slim collection instance, usable with the checker.

Instances outside the static collection formats pass through unchanged. For a collection instance the matrix is arc_costs if given, else resolved from the instance's arc_costs_source (resolve_arc_costs, which needs instance_path for sidecar sources). Hydration preserves fractional service times and windows.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/artifacts.py
def hydrate_collection_instance(
    instance: AnyBenchmarkInstance,
    instance_path: str | Path | None = None,
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> AnyBenchmarkInstance:
    """An embedded-matrix view of a slim collection instance, usable with the checker.

    Instances outside the static collection formats pass through unchanged. For a collection
    instance the matrix is ``arc_costs`` if given, else resolved from the
    instance's ``arc_costs_source`` (``resolve_arc_costs``, which needs
    ``instance_path`` for sidecar sources). Hydration preserves fractional service times and windows.
    """
    if not isinstance(instance, AnyCollectionStaticInstance):
        return instance
    if arc_costs is None:
        if instance_path is None:
            raise ValueError(
                "Collection instances resolve arc costs from their sidecars; pass instance_path to hydrate them."
            )
        arc_costs = resolve_arc_costs(instance, instance_path)
    common: dict = {
        "instance_name": instance.instance_name,
        "instance_origin": instance.instance_origin,
        "benchmark_name": instance.benchmark_name,
        "num_customers": instance.num_customers,
        "num_vehicles": instance.num_vehicles,
        "vehicle_capacity": instance.vehicle_capacity,
        "coordinates": instance.coordinates,
        "demands": instance.demands,
        "depot": instance.depot,
        "arc_costs": arc_costs,
        "reference_lla": instance.reference_lla,
        "metadata": dict(instance.metadata),
    }
    if isinstance(instance, BenchmarkInstanceVRPTWCollection):
        return BenchmarkInstanceVRPTW(**common, service_times=instance.service_times, time_windows=instance.time_windows)
    return BenchmarkInstanceCVRP(**common)

to_vrplib_dict

to_vrplib_dict(
    instance: AnyStaticBenchmarkInstance,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> dict[str, Any]

Convert a benchmark instance into a VRPLIB-shaped dict consumable by PyVRP's parser.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def to_vrplib_dict(
    instance: AnyStaticBenchmarkInstance,
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> dict[str, Any]:
    """Convert a benchmark instance into a VRPLIB-shaped dict consumable by PyVRP's parser."""
    if arc_costs is None:
        arc_costs = instance.arc_costs
    weights = np.asarray(arc_costs)
    if _is_integral(weights):
        weights = weights.astype(int)
    payload: dict[str, Any] = {
        "name": get_instance_identifier(instance),
        "type": "CVRPTW" if _is_vrptw_like(instance) else "CVRP",
        "dimension": instance.num_customers + 1,
        "vehicles": instance.num_vehicles if instance.num_vehicles is not None else instance.num_customers,
        "capacity": instance.vehicle_capacity,
        "edge_weight_type": "EXPLICIT",
        "edge_weight_format": "FULL_MATRIX",
        "node_coord": np.asarray(instance.coordinates, dtype=float),
        "demand": np.asarray(instance.demands, dtype=int),
        "depot": np.array([instance.depot], dtype=int),
        "edge_weight": weights,
    }

    if _is_vrptw_like(instance):
        payload["time_window"] = np.asarray(instance.time_windows)
        payload["service_time"] = np.asarray(instance.service_times)

    return payload

to_pyvrp_problem

to_pyvrp_problem(
    instance: AnyStaticBenchmarkInstance,
    round_func: str | _RoundingFunc = "none",
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> ProblemData

Convert a benchmark instance into a PyVRP ProblemData.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def to_pyvrp_problem(
    instance: AnyStaticBenchmarkInstance,
    round_func: str | _RoundingFunc = "none",
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> ProblemData:
    """Convert a benchmark instance into a PyVRP `ProblemData`."""
    if (key := str(round_func)) in ROUND_FUNCS:
        round_func = ROUND_FUNCS[key]

    if not callable(round_func):
        raise TypeError(
            f"round_func = {round_func} is not understood. Can be a function, "
            f"or one of {list(ROUND_FUNCS.keys())}."
        )

    parser = _InstanceParser(to_vrplib_dict(instance, arc_costs), round_func)
    builder = _ProblemDataBuilder(parser)
    return builder.data()

extract_routes

extract_routes(pyvrp_solution: Any) -> list[list[int]]

Public name of _extract_routes: non-empty routes in library ids.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def extract_routes(pyvrp_solution: Any) -> list[list[int]]:
    """Public name of ``_extract_routes``: non-empty routes in library ids."""
    return _extract_routes(pyvrp_solution)

conversion_plan

conversion_plan(
    instance: AnyStaticBenchmarkInstance,
    instance_path: str | Path | None,
) -> tuple[list[list[int]] | list[list[float]], str, int]

Public name of _conversion_plan: (arc costs, round_func, cost scale).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def conversion_plan(
    instance: AnyStaticBenchmarkInstance,
    instance_path: str | Path | None,
) -> tuple[list[list[int]] | list[list[float]], str, int]:
    """Public name of ``_conversion_plan``: (arc costs, round_func, cost scale)."""
    return _conversion_plan(instance, instance_path)

solve_cvrp

solve_cvrp(
    instance: BenchmarkInstanceCVRP
    | BenchmarkInstanceCVRPCollection,
    *,
    time_limit_s: int,
    seed: int = 42,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> MethodResult

Solve a CVRP instance with PyVRP's ILS (mono-cost objective only).

initial_routes (library ids) warm-start the search. arc_costs is the instance's matrix when the caller already resolved it (a slim collection instance's sidecar is read here otherwise).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def solve_cvrp(
    instance: BenchmarkInstanceCVRP | BenchmarkInstanceCVRPCollection,
    *,
    time_limit_s: int,
    seed: int = 42,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> MethodResult:
    """Solve a CVRP instance with PyVRP's ILS (mono-cost objective only).

    ``initial_routes`` (library ids) warm-start the search. ``arc_costs`` is the instance's
    matrix when the caller already resolved it (a slim collection instance's sidecar is read
    here otherwise).
    """
    start_time = time.perf_counter()
    arc_costs, round_func, scale = _conversion_plan(instance, instance_path, arc_costs)
    if monitor is not None:
        monitor.rescale(scale)
    problem = to_pyvrp_problem(instance, round_func=round_func, arc_costs=arc_costs)
    result = pyvrp_solve(
        problem,
        stop=_stop_with(monitor, MaxRuntime(max(1, time_limit_s))),
        seed=seed,
        collect_stats=False,
        display=display,
        initial_solution=_warm_start(problem, initial_routes),
    )
    wall_time = time.perf_counter() - start_time
    is_feasible = result.is_feasible()
    routes = _extract_routes(result.best) if is_feasible else []
    return MethodResult(
        method="pyvrp-ils-v1",
        problem_type="CVRP",
        objective_function=ObjectiveFunction.MONO_COST.value,
        instance_id=instance.instance_name,
        seed=seed,
        time_limit_s=time_limit_s,
        wall_time=wall_time,
        solver_is_feasible=is_feasible,
        routes=routes,
        solver_report=_reported_objective(result, scale) if is_feasible else None,
        route_count=len(routes),
        vehicle_penalty=0,
        metadata=_build_method_metadata(
            instance,
            ObjectiveFunction.MONO_COST,
            seed=seed,
            time_limit_s=time_limit_s,
            extra={
                **({"arc_cost_scale": scale} if scale != 1 else {}),
                **({"warm_start": True} if initial_routes else {}),
            },
        ),
    )

solve_vrptw

solve_vrptw(
    instance: BenchmarkInstanceVRPTW
    | BenchmarkInstanceVRPTWCollection,
    *,
    objective_function: ObjectiveFunction,
    time_limit_s: int,
    seed: int = 42,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> MethodResult

Solve a VRPTW instance with PyVRP's ILS.

initial_routes (library ids) warm-start a MonoCost solve; the hierarchical solve builds its own warm start on the minimised fleet and ignores them. arc_costs is the instance's matrix when the caller already resolved it.

For ObjectiveFunction.MONO_COST, runs a single solve with the full time budget. For ObjectiveFunction.HIERARCHICAL_VEHICLE_COST, runs a two-phase solve: 1. Fleet minimization (PyVRP's minimise_fleet) within ~30% of the budget. 2. Cost optimization on the constrained fleet for the remaining budget, with a per-vehicle fixed cost large enough to dominate routing cost. Phase 2 is warm-started from a feasible solution re-found on the constrained fleet: the fixed cost dwarfs the solver's capped infeasibility penalties, so a cold start can otherwise stabilize on infeasible solutions that use fewer vehicles.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def solve_vrptw(
    instance: BenchmarkInstanceVRPTW | BenchmarkInstanceVRPTWCollection,
    *,
    objective_function: ObjectiveFunction,
    time_limit_s: int,
    seed: int = 42,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> MethodResult:
    """Solve a VRPTW instance with PyVRP's ILS.

    ``initial_routes`` (library ids) warm-start a MonoCost solve; the hierarchical
    solve builds its own warm start on the minimised fleet and ignores them.
    ``arc_costs`` is the instance's matrix when the caller already resolved it.

    For ObjectiveFunction.MONO_COST, runs a single solve with the full time budget.
    For ObjectiveFunction.HIERARCHICAL_VEHICLE_COST, runs a two-phase solve:
      1. Fleet minimization (PyVRP's `minimise_fleet`) within ~30% of the budget.
      2. Cost optimization on the constrained fleet for the remaining budget,
         with a per-vehicle fixed cost large enough to dominate routing cost.
         Phase 2 is warm-started from a feasible solution re-found on the
         constrained fleet: the fixed cost dwarfs the solver's capped
         infeasibility penalties, so a cold start can otherwise stabilize on
         infeasible solutions that use fewer vehicles.
    """
    start_time = time.perf_counter()
    arc_costs, round_func, scale = _conversion_plan(instance, instance_path, arc_costs)
    if monitor is not None:
        monitor.rescale(scale)
    problem = to_pyvrp_problem(instance, round_func=round_func, arc_costs=arc_costs)
    params = SolveParams()
    vehicle_penalty: int = 0

    if objective_function == ObjectiveFunction.MONO_COST:
        result = pyvrp_solve(
            problem,
            stop=_stop_with(monitor, MaxRuntime(max(1, time_limit_s))),
            seed=seed,
            collect_stats=False,
            display=display,
            params=params,
            initial_solution=_warm_start(problem, initial_routes),
        )
    else:
        fleet_budget = max(1.0, float(time_limit_s) * _FLEET_MIN_TIME_FRACTION)
        if monitor is not None:
            monitor.phase("minimising fleet")
        constrained_vehicle_type = minimise_fleet(
            problem,
            stop=_stop_with(monitor, MaxRuntime(fleet_budget)),
            seed=seed,
            params=params,
        )
        fleet_problem = problem.replace(vehicle_types=[constrained_vehicle_type])
        if monitor is not None:
            monitor.phase("warm start")
        warm_result = pyvrp_solve(
            fleet_problem,
            stop=_stop_with(monitor, FirstFeasible(), MaxRuntime(_WARM_START_MAX_TIME)),
            seed=seed,
            collect_stats=False,
            display=False,
            params=params,
        )
        vehicle_penalty = _get_vehicle_fixed_cost(instance.num_customers, arc_costs, scale)
        constrained_problem = problem.replace(
            vehicle_types=[constrained_vehicle_type.replace(fixed_cost=vehicle_penalty)]
        )
        remaining_time = max(1, time_limit_s - int(time.perf_counter() - start_time))
        if monitor is not None:
            monitor.phase("optimising cost")
        result = pyvrp_solve(
            constrained_problem,
            stop=_stop_with(monitor, MaxRuntime(remaining_time)),
            seed=seed,
            collect_stats=False,
            display=display,
            params=params,
            # A PyVRP Solution caches its fixed vehicle cost at construction. Rebuild the warm
            # routes against this phase's vehicle type so all its incumbents have the same objective.
            initial_solution=Solution(constrained_problem, _extract_routes(warm_result.best)) if warm_result.is_feasible() else None,
        )
        if not result.is_feasible() and warm_result.is_feasible():
            # The warm incumbent is a valid hierarchical solution even when
            # phase 2 degrades; never return worse than what phase 1 proved.
            result = warm_result
            vehicle_penalty = 0  # The warm solve used no fixed vehicle cost.

    wall_time = time.perf_counter() - start_time
    is_feasible = result.is_feasible()
    routes = _extract_routes(result.best) if is_feasible else []
    return MethodResult(
        method="pyvrp-ils-v3",
        problem_type="VRPTW",
        objective_function=objective_function.value,
        instance_id=get_instance_identifier(instance),
        seed=seed,
        time_limit_s=time_limit_s,
        wall_time=wall_time,
        solver_is_feasible=is_feasible,
        routes=routes,
        solver_report=_reported_objective(result, scale, vehicle_penalty=vehicle_penalty) if is_feasible else None,
        route_count=len(routes),
        vehicle_penalty=vehicle_penalty,
        metadata=_build_method_metadata(
            instance,
            objective_function,
            seed=seed,
            time_limit_s=time_limit_s,
            extra={
                "vehicle_penalty": vehicle_penalty,
                **({"arc_cost_scale": scale} if scale != 1 else {}),
                **(
                    {"warm_start": True}
                    if initial_routes and objective_function == ObjectiveFunction.MONO_COST
                    else {}
                ),
            },
        ),
    )

solve_instance

solve_instance(
    instance: AnyStaticBenchmarkInstance,
    *,
    time_limit_s: int,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]]
    | list[list[float]]
    | None = None,
) -> MethodResult

Dispatch to solve_cvrp or solve_vrptw based on instance type.

For VRPTW instances, objective_function defaults to MONO_COST when not provided. For CVRP instances, the objective is fixed to MONO_COST regardless of the argument. Slim collection instances need instance_path when their arc costs live in a distances sidecar, unless arc_costs hands the resolved matrix in. Pass a SolveMonitor to observe the search while it runs.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def solve_instance(
    instance: AnyStaticBenchmarkInstance,
    *,
    time_limit_s: int,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    display: bool = False,
    instance_path: str | Path | None = None,
    monitor: SolveMonitor | None = None,
    initial_routes: list[list[int]] | None = None,
    arc_costs: list[list[int]] | list[list[float]] | None = None,
) -> MethodResult:
    """Dispatch to `solve_cvrp` or `solve_vrptw` based on instance type.

    For VRPTW instances, `objective_function` defaults to MONO_COST when not provided.
    For CVRP instances, the objective is fixed to MONO_COST regardless of the argument.
    Slim collection instances need `instance_path` when their arc costs live in
    a distances sidecar, unless `arc_costs` hands the resolved matrix in. Pass a
    `SolveMonitor` to observe the search while it runs.
    """
    if isinstance(instance, (BenchmarkInstanceCVRP, BenchmarkInstanceCVRPCollection)):
        return solve_cvrp(
            instance,
            time_limit_s=time_limit_s,
            seed=seed,
            display=display,
            instance_path=instance_path,
            monitor=monitor,
            initial_routes=initial_routes,
            arc_costs=arc_costs,
        )

    if _is_vrptw_like(instance):
        objective = objective_function or ObjectiveFunction.MONO_COST
        return solve_vrptw(
            instance,
            objective_function=objective,
            time_limit_s=time_limit_s,
            seed=seed,
            display=display,
            instance_path=instance_path,
            monitor=monitor,
            initial_routes=initial_routes,
            arc_costs=arc_costs,
        )

    raise TypeError(f"Unsupported instance type: {type(instance).__name__}")

solve_and_update_bks

solve_and_update_bks(
    instance: AnyStaticBenchmarkInstance,
    *,
    instance_path: str | Path,
    time_limit_s: int,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    authors: str,
    display: bool = False,
) -> tuple[MethodResult, BKSUpdateResult | None]

Solve an instance and, if the solution is feasible, write a BKS file in place.

authors (who to credit in the BKS) is required: a stored BKS is published.

Returns the MethodResult and a BKSUpdateResult (or None if the solver did not return a feasible solution). The checked BKS submission uses the same solver metadata and family evaluation as the registry path.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/pyvrp.py
def solve_and_update_bks(
    instance: AnyStaticBenchmarkInstance,
    *,
    instance_path: str | Path,
    time_limit_s: int,
    seed: int = 42,
    objective_function: ObjectiveFunction | None = None,
    authors: str,
    display: bool = False,
) -> tuple[MethodResult, BKSUpdateResult | None]:
    """Solve an instance and, if the solution is feasible, write a BKS file in place.

    ``authors`` (who to credit in the BKS) is required: a stored BKS is published.

    Returns the `MethodResult` and a `BKSUpdateResult` (or None if the solver did not
    return a feasible solution). The checked BKS submission uses the same solver
    metadata and family evaluation as the registry path.
    """
    method_result = solve_instance(
        instance,
        time_limit_s=time_limit_s,
        seed=seed,
        objective_function=objective_function,
        display=display,
        instance_path=instance_path,
    )
    if not method_result.solver_is_feasible or not method_result.routes:
        return method_result, None

    resolved_objective = ObjectiveFunction(method_result.objective_function)
    path = Path(instance_path)
    checkable = hydrate_collection_instance(instance, path)
    check = check_routes(instance, path, method_result.routes, resolved_objective, checkable=checkable)
    if not check.is_valid():
        return method_result, None

    checked = CheckedSolve(
        result=method_result_to_solve_result(method_result),
        check=check,
        objective=resolved_objective,
        instance_path=path,
        instance_name=get_instance_identifier(instance),
        checkable=checkable,
    )
    update_result = submit_bks(
        path, method_result.routes, authors=authors, objective_function=resolved_objective,
        metadata=checked.bks_metadata(), instance=instance, checkable=checkable,
    )
    return method_result, update_result