Skip to content

mamut_routing_lib.solvers.external.adapter

ExternalSolver: run a described solver executable on a library instance.

One solve, in order:

  1. hydrate the instance (collection matrices from their sidecars) and refuse what the solver cannot take: depot not at index 0, asymmetric costs for a symmetric solver, demands or distances beyond its limits;
  2. pick the integer scale (scaling) and write the input files with fixed names into the work directory (problem.vrp, problem.par);
  3. run the executable (process): own process group, budget + grace, cooperative stop through the monitor, progress lines as live incumbents;
  4. read the solution file (solutions parsers), map its ids onto the library's, and check an integer cost report against the weights in the exported matrix.

The routes still go through the reference checker afterwards (solvers.run.run_solver): a solver's own cost is never trusted.

PROBLEM_FILE module-attribute

PROBLEM_FILE = 'problem.vrp'

PARAMS_FILE module-attribute

PARAMS_FILE = 'problem.par'

LOG_FILE module-attribute

LOG_FILE = 'solver.log'

PreparedInput dataclass

PreparedInput(
    workdir: Path,
    problem: Path,
    params: Path | None,
    solution: Path,
    plan: ScalePlan,
    vehicles: int | None,
    fixed_fleet: int | None,
    problem_type_line: str,
    checkable: Any,
)

Input files written for one run, and how the data was scaled.

workdir instance-attribute

workdir: Path

problem instance-attribute

problem: Path

params instance-attribute

params: Path | None

solution instance-attribute

solution: Path

plan instance-attribute

plan: ScalePlan

vehicles instance-attribute

vehicles: int | None

fixed_fleet instance-attribute

fixed_fleet: int | None

problem_type_line instance-attribute

problem_type_line: str

checkable instance-attribute

checkable: Any

ExternalSolver

ExternalSolver(
    descriptor: ExternalSolverDescriptor,
    *,
    config_path: str | None = None,
)

A Solver backed by an executable described by an ExternalSolverDescriptor.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def __init__(self, descriptor: ExternalSolverDescriptor, *, config_path: str | None = None):
    self.descriptor = descriptor
    self.name = descriptor.name
    self.label = descriptor.label
    self.capabilities = descriptor.capabilities
    self._config_path = config_path

descriptor instance-attribute

descriptor = descriptor

name instance-attribute

name = descriptor.name

label instance-attribute

label = descriptor.label

capabilities instance-attribute

capabilities = descriptor.capabilities

resolve_executable

resolve_executable() -> tuple[str | None, str | None]

(absolute executable, jar or Python script, reason when missing).

A Python solver names its script in executable. Without one, its argv names a module or a script by itself, and this is the interpreter that runs it.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def resolve_executable(self) -> tuple[str | None, str | None]:
    """(absolute executable, jar or Python script, reason when missing).

    A Python solver names its script in ``executable``. Without one, its argv names a module or a
    script by itself, and this is the interpreter that runs it.
    """
    descriptor = self.descriptor
    if descriptor.runtime == "python":
        if not descriptor.executable:
            return sys.executable, None
        script = Path(descriptor.executable).expanduser()
        if not script.is_absolute() or not script.is_file():
            return None, f"script not found: {script}" + ("" if script.is_absolute() else " (give an absolute path)")
        return str(script.resolve()), None
    if descriptor.runtime == "java":
        if not descriptor.jar:
            return None, "no jar configured"
        jar = Path(descriptor.jar).expanduser()
        if not jar.is_absolute() or not jar.is_file():
            return None, f"jar not found: {jar}" + ("" if jar.is_absolute() else " (give an absolute path)")
        return str(jar), None
    if descriptor.executable:
        # A configured executable is the only candidate: falling back to another build found on
        # PATH (an unpatched HGS, an older FILO2) would run, and credit, the wrong solver.
        configured = descriptor.executable
        path = Path(configured).expanduser()
        if os.sep in configured or path.is_absolute():
            if path.is_file() and os.access(path, os.X_OK):
                return str(path.resolve()), None
            return None, f"executable not found or not executable: {path}"
        found, relative_hit = find_on_path(configured)
        if found:
            return str(Path(found).resolve()), None
        return None, f"configured executable {configured!r} is not on PATH" + _relative_hit_note(relative_hit)
    relative_hit = None
    for candidate in descriptor.executable_names:
        found, elsewhere = find_on_path(candidate)
        if found:
            return str(Path(found).resolve()), None
        relative_hit = relative_hit or elsewhere
    return None, "executable not found" + _relative_hit_note(relative_hit)

solver_file

solver_file() -> str | None

The file that is the solver: the native executable, the jar, or the script of a Python solver.

None for a Python solver that names no script: the interpreter is not the solver, and its hash would say nothing about the code that ran.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def solver_file(self) -> str | None:
    """The file that is the solver: the native executable, the jar, or the script of a Python solver.

    ``None`` for a Python solver that names no script: the interpreter is not the solver, and its
    hash would say nothing about the code that ran.
    """
    if self.descriptor.runtime == "python" and not self.descriptor.executable:
        return None
    return self.resolve_executable()[0]

availability

availability() -> Availability
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def availability(self) -> Availability:
    executable, reason = self.resolve_executable()
    note = self.descriptor.requires_note
    if executable is None:
        return Availability(False, reason=reason, hint=self._config_hint(), note=note)
    if self.descriptor.runtime == "java":
        java, java_reason = self._java()
        if java is None:
            return Availability(
                False, reason=java_reason, executable=executable, hint=f"install a JDK/JRE or set solvers.{self.name}.java", note=note
            )
    return Availability(True, version=self.descriptor.version, executable=executable, note=note)

supports

supports(
    profile: InstanceProfile, objective: ObjectiveFunction
) -> Support
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def supports(self, profile: InstanceProfile, objective: ObjectiveFunction) -> Support:
    return capability_support(self.capabilities, profile, objective, solver_label=self.label)

prepare

prepare(
    request: SolveRequest, workdir: Path
) -> PreparedInput

Write the solver's input files into workdir; raises InstanceNotSupportedError.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def prepare(self, request: SolveRequest, workdir: Path) -> PreparedInput:
    """Write the solver's input files into ``workdir``; raises ``InstanceNotSupportedError``."""
    from mamut_routing_lib.artifacts import is_collection_instance
    from mamut_routing_lib.cvrplib import collection_cost_decimals, is_symmetric_matrix
    from mamut_routing_lib.solvers.external.problem import (
        render_explicit_cvrplib,
        render_lkh_params,
        render_lkh_problem,
        render_matrix_format,
        render_x_format,
        write_text,
    )

    descriptor = self.descriptor
    instance = request.instance
    checkable = request.checkable()  # hydrated once; run_solver's check reuses it
    if int(checkable.depot) != 0:
        raise InstanceNotSupportedError(f"{self.label} needs the depot at index 0 (it is {checkable.depot})")
    matrix = checkable.arc_costs
    demands = [int(value) for value in checkable.demands]
    limits = descriptor.limits
    if limits.max_demand is not None and max(demands) > limits.max_demand:
        raise InstanceNotSupportedError(f"{self.label} refuses demands above {limits.max_demand:g} (largest {max(demands)})")
    if self.capabilities.symmetric_only and not is_symmetric_matrix(matrix):
        raise InstanceNotSupportedError(f"{self.label} needs symmetric arc costs; this instance's are asymmetric")
    vrptw = hasattr(checkable, "time_windows")
    fixed_fleet = checkable.num_vehicles
    decimals_hint = collection_cost_decimals(instance) if is_collection_instance(instance) else None
    problem = workdir / PROBLEM_FILE
    params: Path | None = None
    solution = workdir / descriptor.solution_file.format(seed=request.seed)
    vehicles: int | None = None
    type_line = "CVRPTW" if vrptw else "CVRP"
    try:
        if descriptor.input_format == "cvrplib-x":
            if vrptw:
                raise InstanceNotSupportedError(f"{self.label} reads CVRP files; time windows would be dropped")
            published = decimals_hint if decimals_hint is not None else max_decimals(matrix)
            plan = plan_coordinate_scale(
                checkable.coordinates,
                candidates=descriptor.coordinate_scales,
                limits=limits,
                distance_model="nint" if descriptor.distance_model == "nint" else "float",
                published_decimals=published,
            )
            write_text(
                problem,
                render_x_format(
                    coordinates=scale_coordinates(checkable.coordinates, plan),
                    demands=demands,
                    capacity=int(checkable.vehicle_capacity),
                    coordinate_decimals=int(plan.coordinate_decimals or 0),
                    comment=f"MAMUT-routing-{plan.unit or plan.factor}",
                ),
            )
            vehicles = fixed_fleet
        elif descriptor.input_format == "cvrplib-matrix":
            if vrptw:
                raise InstanceNotSupportedError(f"{self.label} reads CVRP files; time windows would be dropped")
            plan = plan_float_matrix_scale(
                matrix,
                candidates=descriptor.matrix_scales,
                limits=limits,
                decimals_hint=decimals_hint,
            )
            write_text(
                problem,
                render_matrix_format(
                    matrix_rows=format_float_matrix(matrix, plan),
                    dimension=len(matrix),
                    coordinates=checkable.coordinates,
                    demands=demands,
                    capacity=int(checkable.vehicle_capacity),
                    comment=f"MAMUT-routing-x{plan.factor:g}",
                ),
            )
            vehicles = fixed_fleet
        else:
            windows = checkable.time_windows if vrptw else None
            services = checkable.service_times if vrptw else None
            plan = plan_explicit_scale(
                matrix,
                time_windows=windows,
                service_times=services,
                limits=limits,
                require_exact=descriptor.require_exact_scale,
                decimals_hint=decimals_hint,
            )
            scaled, scaled_windows, scaled_services = scale_explicit_data(
                plan, matrix, time_windows=windows, service_times=services
            )
            if descriptor.input_format == "lkh":
                if not vrptw:
                    type_line = "CVRP" if is_symmetric_matrix(matrix) else "ACVRP"
                vehicles = int(fixed_fleet) if fixed_fleet is not None else self._fleet_bound(
                    checkable, vrptw=vrptw, options=dict(request.options)
                )
                write_text(
                    problem,
                    render_lkh_problem(
                        problem_type=type_line,
                        matrix=scaled,
                        demands=demands,
                        capacity=int(checkable.vehicle_capacity),
                        vehicles=vehicles,
                        time_windows=scaled_windows,
                        service_times=scaled_services,
                    ),
                )
                params = workdir / PARAMS_FILE
                write_text(
                    params,
                    render_lkh_params(
                        problem=problem,
                        solution=solution,
                        seed=request.seed,
                        time_limit_s=request.time_limit_s,
                        extra=descriptor.extra_args,  # literal parameter-file lines for this format
                    ),
                )
            else:
                vehicles = fixed_fleet
                problem.write_text(
                    render_explicit_cvrplib(
                        matrix=scaled,
                        coordinates=checkable.coordinates,
                        demands=demands,
                        capacity=int(checkable.vehicle_capacity),
                        num_vehicles=fixed_fleet,
                        time_windows=scaled_windows,
                        service_times=scaled_services,
                    ),
                    encoding="ascii",
                )
    except ScaleError as error:
        raise InstanceNotSupportedError(f"{self.label}: {error}") from error
    return PreparedInput(
        workdir=workdir,
        problem=problem,
        params=params,
        solution=solution,
        plan=plan,
        vehicles=vehicles,
        fixed_fleet=fixed_fleet,
        problem_type_line=type_line,
        checkable=checkable,
    )

build_argv

build_argv(
    prepared: PreparedInput, request: SolveRequest
) -> list[str]
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def build_argv(self, prepared: PreparedInput, request: SolveRequest) -> list[str]:
    return self._invocation(prepared, request)[0]

solve

solve(
    request: SolveRequest,
    monitor: SolveMonitor | None = None,
) -> SolveResult
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def solve(self, request: SolveRequest, monitor: SolveMonitor | None = None) -> SolveResult:
    descriptor = self.descriptor
    started = time.perf_counter()
    own_workdir = request.workdir is None
    workdir = Path(request.workdir or tempfile.mkdtemp(prefix=f"mamut-{self.name}-")).resolve()
    workdir.mkdir(parents=True, exist_ok=True)
    base = dict(
        solver=self.name,
        method=descriptor.method,
        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=descriptor.version,
    )
    provenance: dict[str, Any] = {**environment(), "descriptor_sha256": descriptor.sha256(), "descriptor_source": descriptor.source}
    try:
        if monitor is not None:
            if monitor.stop_requested:  # cancelled before anything was written
                return SolveResult(**base, wall_time=time.perf_counter() - started, status="cancelled", stopped_early=True,
                                   provenance=provenance)
            monitor.phase("preparing input")
        prepared = self.prepare(request, workdir)
        argv, solver_file, identity = self._invocation(prepared, request)
        provenance.update(
            argv=argv,
            executable=solver_file or argv[0],
            executable_sha256=file_sha256(solver_file) if solver_file else None,
            **identity,
            input_sha256=file_sha256(prepared.problem, cache=False),
            params_sha256=file_sha256(prepared.params, cache=False) if prepared.params else None,
            scale=prepared.plan.to_json(),
            problem_type_line=prepared.problem_type_line,
            vehicles=prepared.vehicles,
        )
        if monitor is not None:
            if monitor.stop_requested:
                return SolveResult(**base, wall_time=time.perf_counter() - started, status="cancelled",
                                   stopped_early=True, provenance=provenance)
            scale = 1 / prepared.plan.cost_unit if prepared.plan.cost_unit is not None else prepared.plan.factor
            assert scale is not None
            monitor.rescale(scale)
            monitor.phase("solving")
        # A solution left by an earlier run in a reused workdir (--keep-artifacts, a resumed campaign)
        # must never be read back as this run's answer when the solver writes nothing.
        prepared.solution.unlink(missing_ok=True)
        grace = max(descriptor.timeout_grace_s, descriptor.timeout_grace_fraction * float(request.time_limit_s))
        env = dict(os.environ)
        env.update(descriptor.env)
        outcome = run_process(
            argv,
            cwd=workdir,
            log_path=workdir / LOG_FILE,
            time_limit_s=float(request.time_limit_s),
            grace_s=grace,
            term_grace_s=descriptor.term_grace_s,
            env=env,
            monitor=monitor,
            progress_pattern=descriptor.progress_pattern,
        )
        provenance.update(
            returncode=outcome.returncode,
            termination=outcome.termination,
            hard_timeout_s=float(request.time_limit_s) + grace,
            log_tail=outcome.log_tail[-2000:],
        )
        if monitor is not None:
            monitor.phase("reading solution")
        return self._result(base, prepared, outcome, provenance, started, monitor)
    finally:
        if own_workdir and not request.keep_artifacts:
            shutil.rmtree(workdir, ignore_errors=True)
        elif request.keep_artifacts or not own_workdir:
            provenance["artifacts_dir"] = str(workdir)

find_on_path

find_on_path(name: str) -> tuple[str | None, str | None]

(the command name on PATH, or a hit that only a relative PATH entry gives).

Only the absolute entries of PATH are searched. A relative entry (., an empty one, bin) is the working directory, which the solvers config never reads on purpose: a file called filo2 in a benchmark tree would run, and be credited, as the solver. Such a hit is returned apart, for the message that says why the solver is not available.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/adapter.py
def find_on_path(name: str) -> tuple[str | None, str | None]:
    """(the command ``name`` on PATH, or a hit that only a relative PATH entry gives).

    Only the absolute entries of PATH are searched. A relative entry (``.``, an empty one, ``bin``)
    is the working directory, which the solvers config never reads on purpose: a file called
    ``filo2`` in a benchmark tree would run, and be credited, as the solver. Such a hit is
    returned apart, for the message that says why the solver is not available.
    """
    entries = os.environ.get("PATH", os.defpath).split(os.pathsep)
    absolute = [entry for entry in entries if entry and os.path.isabs(entry)]
    found = shutil.which(name, path=os.pathsep.join(absolute)) if absolute else None
    if found and os.path.isabs(found):
        return found, None
    return None, (shutil.which(name) if len(absolute) < len(entries) else None)