Skip to content

mamut_routing_lib.solvers.kayros

KAYROS as a registry solver (kayros): time-dependent TDVRP / TDVRPTW with Duration or FleetCostDuration.

KAYROS is a separate package (pip install kayros, or the tools' [kayros] extra) that implements the lib's TD checker contract. Its search is one native call whose only way back into Python is the on_incumbent hook: a stop request raised from the hook is not seen once the search stops improving, which can be the rest of the time limit.

The adapter therefore runs each solve in a child Python process (solvers._kayros_worker) through the external-solver process runner: its own process group, a hard timeout, and a stop request (the monitor, Ctrl-C, a GUI cancel) that kills the process within a poll. The worker saves every incumbent before reporting it, so a stopped solve still returns its last incumbent's routes. So does a solve whose worker dies without a result -- the system kills a process that runs out of memory, and native code can crash: the run then ends as feasible with stopped_early, its error says how the worker ended, and the provenance has recovered_from_checkpoint. An error that the worker reports itself stays a failed result. The routes are re-checked by the lib's TD checker afterwards (solvers.run.run_solver), like every other solver's.

CHECKPOINT_FILE module-attribute

CHECKPOINT_FILE = 'kayros-incumbent.json'

RESULT_FILE module-attribute

RESULT_FILE = 'kayros-result.json'

LOG_FILE module-attribute

LOG_FILE = 'kayros.log'

WORKER_MODULE module-attribute

WORKER_MODULE = 'mamut_routing_lib.solvers._kayros_worker'

PROGRESS_PATTERN module-attribute

PROGRESS_PATTERN = "^incumbent cost=(?P<cost>\\S+) iterations=(?P<iterations>\\d+)$"

HARD_TIMEOUT_GRACE_S module-attribute

HARD_TIMEOUT_GRACE_S = 600.0

KayrosSolver

KAYROS for the Duration and FleetCostDuration objectives on time-dependent instances.

name class-attribute instance-attribute

name = 'kayros'

label class-attribute instance-attribute

label = 'KAYROS'

capabilities class-attribute instance-attribute

capabilities = _CAPABILITIES

availability

availability() -> Availability
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/kayros.py
def availability(self) -> Availability:
    try:
        spec = importlib.util.find_spec("kayros")
    except (ValueError, ImportError):
        spec = None
    if spec is None:
        return Availability(
            False,
            reason="the kayros package is not installed",
            hint="pip install kayros (a release whose mamut-routing-lib requirement admits this version)",
        )
    return Availability(True, version=package_version("kayros"), note=_requirement_note())

supports

supports(
    profile: InstanceProfile, objective: ObjectiveFunction
) -> Support
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/kayros.py
def supports(self, profile: InstanceProfile, objective: ObjectiveFunction) -> Support:
    support = capability_support(self.capabilities, profile, objective, solver_label=self.label)
    if support.supported and objective is ObjectiveFunction.FLEET_COST_DURATION and not profile.has_fleet_fixed_cost:
        return Support.refuse("FleetCostDuration requires the instance to specify fleet_fixed_cost")
    return support

solve

solve(
    request: SolveRequest,
    monitor: SolveMonitor | None = None,
) -> SolveResult
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/kayros.py
def solve(self, request: SolveRequest, monitor: SolveMonitor | None = None) -> SolveResult:
    from mamut_routing_lib.solvers.external.process import run_process

    started = time.perf_counter()
    version = package_version("kayros")
    provenance: dict[str, Any] = {**environment(), "kayros_version": version}
    requirement = declared_requirement("kayros", "mamut-routing-lib")
    if requirement is not None:
        provenance["kayros_requires_lib"] = requirement
        provenance["kayros_requirement_met"] = satisfies(lib_version(), requirement)
    base = dict(
        solver=self.name,
        method="kayros",
        problem_type=type(request.instance).__name__,
        objective_function=request.objective.value,
        instance_id=str(getattr(request.instance, "instance_name", "")),
        seed=int(request.seed),
        time_limit_s=float(request.time_limit_s),
        solver_version=version,
        provenance=provenance,
    )
    if request.instance_path is None:
        return SolveResult(**base, wall_time=0.0, status="failed", error="KAYROS reads the instance from its file: no instance path")
    if monitor is not None:
        if monitor.stop_requested:  # cancelled before anything started
            return SolveResult(**base, wall_time=time.perf_counter() - started, status="cancelled", stopped_early=True)
        monitor.phase("solving")
    own_workdir = request.workdir is None
    workdir = Path(request.workdir or tempfile.mkdtemp(prefix="mamut-kayros-")).resolve()
    workdir.mkdir(parents=True, exist_ok=True)
    checkpoint, result_file = workdir / CHECKPOINT_FILE, workdir / RESULT_FILE
    try:
        # Files left by an earlier run in a reused workdir must never be read as this run's answer.
        checkpoint.unlink(missing_ok=True)
        result_file.unlink(missing_ok=True)
        grace = max(HARD_TIMEOUT_GRACE_S, float(request.time_limit_s))
        outcome = run_process(
            [
                sys.executable,
                "-P",  # the work directory must not shadow the library or kayros
                "-m",
                WORKER_MODULE,
                str(Path(request.instance_path).resolve()),
                "--time-limit",
                repr(float(request.time_limit_s)),
                "--objective",
                request.objective.value,
                "--seed",
                str(int(request.seed)),
                "--checkpoint",
                str(checkpoint),
                "--result",
                str(result_file),
            ],
            cwd=workdir,
            log_path=workdir / LOG_FILE,
            time_limit_s=float(request.time_limit_s),
            grace_s=grace,
            env=_worker_environment(),
            monitor=monitor,
            progress_pattern=PROGRESS_PATTERN,
        )
        provenance.update(
            returncode=outcome.returncode,
            termination=outcome.termination,
            hard_timeout_s=float(request.time_limit_s) + grace,
        )
        result = _read_json(result_file)
        if result is not None and result.get("lib_path"):
            # The worker is another interpreter: record which library it ran, and whether it is this one.
            provenance["worker_lib_version"] = result.get("lib_version")
            provenance["worker_lib_is_parent_lib"] = Path(str(result["lib_path"])) == _LIB_PACKAGE_DIR
        return self._result(base, outcome, result, _read_json(checkpoint), time.perf_counter() - started)
    finally:
        if own_workdir and not request.keep_artifacts:
            shutil.rmtree(workdir, ignore_errors=True)
        else:
            provenance["artifacts_dir"] = str(workdir)