Skip to content

mamut_routing_lib.solvers.external.problem

Problem files for external solvers.

These are solver inputs, written into a scratch directory with fixed file names, not the published CVRPLIB export of mamut_routing_lib.cvrplib (whose bytes are pinned by the committed .vrp files and the website's writer). Each reader is stricter than the format suggests, which is why there are three writers:

  • cvrplib-x, the Uchoa X-set layout, for coordinate solvers. FILO2's fscanf parser needs exactly NAME, COMMENT, TYPE, DIMENSION, EDGE_WEIGHT_TYPE, CAPACITY in that order (no VEHICLES line) and a one-token name; HGS-CVRP skips the first three lines and throws on any header key other than DIMENSION, EDGE_WEIGHT_TYPE, CAPACITY, DISTANCE and SERVICE_TIME.
  • lkh: LKH-3 refuses NODE_COORD_SECTION next to explicit weights (it needs a coordinate type), reads VEHICLES and the VRPTW sections, and treats ACVRP and CVRPTW as asymmetric (CVRP as symmetric).
  • cvrplib-matrix, for HGS-CVRP with the MAMUT-routing reader patch (patches/hgs-cvrp-explicit-matrix.patch): the X-format header plus EDGE_WEIGHT_FORMAT : FULL_MATRIX and an EDGE_WEIGHT_SECTION of decimal (possibly asymmetric) costs before NODE_COORD_SECTION, whose coordinates only serve SWAP*'s polar sectors. No VEHICLES line: the fleet is -veh.
  • cvrplib-explicit: a generic CVRPLIB file with an integer FULL_MATRIX (for user-configured solvers), rendered by cvrplib.render_cvrplib.

Node i + 1 of a file is library node i; the depot is node 1.

LKH_RUN_PARAMETERS module-attribute

LKH_RUN_PARAMETERS = {
    "PROBLEM_FILE": "the input file of the run",
    "MTSP_SOLUTION_FILE": "the solution file of the run",
    "SEED": "the seed of the run",
    "TIME_LIMIT": "the time limit of the run",
    "PRECISION": "the scale of the costs",
    "SCALE": "the multiplier for input weights",
}

write_text

write_text(path: Path, lines: Iterable[str]) -> None

Write lines with a final newline, streaming (an n = 4000 matrix is ~130 MB of text).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def write_text(path: Path, lines: Iterable[str]) -> None:
    """Write lines with a final newline, streaming (an n = 4000 matrix is ~130 MB of text)."""
    with path.open("w", encoding="ascii", newline="\n") as handle:
        for line in lines:
            handle.write(line)
            handle.write("\n")

render_x_format

render_x_format(
    *,
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    coordinate_decimals: int,
    comment: str = "MAMUT-routing",
    name: str = "problem",
) -> Iterable[str]

Lines of an X-format CVRP (EUC_2D) with the depot as node 1.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def render_x_format(
    *,
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    coordinate_decimals: int,
    comment: str = "MAMUT-routing",
    name: str = "problem",
) -> Iterable[str]:
    """Lines of an X-format CVRP (EUC_2D) with the depot as node 1."""
    if " " in name:
        raise ValueError("the X-format name must be a single token")
    yield f"NAME : {name}"
    yield f"COMMENT : {comment.replace(chr(10), ' ')}"
    yield "TYPE : CVRP"
    yield f"DIMENSION : {len(coordinates)}"
    yield "EDGE_WEIGHT_TYPE : EUC_2D"
    yield f"CAPACITY : {int(capacity)}"
    yield "NODE_COORD_SECTION"
    for index, (x, y) in enumerate(coordinates):
        yield f"{index + 1} {_fmt(x, coordinate_decimals)} {_fmt(y, coordinate_decimals)}"
    yield "DEMAND_SECTION"
    for index, demand in enumerate(demands):
        yield f"{index + 1} {int(demand)}"
    yield "DEPOT_SECTION"
    yield "1"
    yield "-1"
    yield "EOF"

render_matrix_format

render_matrix_format(
    *,
    matrix_rows: Iterable[str],
    dimension: int,
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    comment: str = "MAMUT-routing",
    name: str = "problem",
) -> Iterable[str]

Lines of a full-matrix CVRP for the patched HGS-CVRP reader (depot = node 1).

The first three lines are skipped by the reader; the header keys it accepts are DIMENSION, EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, CAPACITY and the EDGE_WEIGHT_SECTION, which must come after DIMENSION.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def render_matrix_format(
    *,
    matrix_rows: Iterable[str],
    dimension: int,
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    comment: str = "MAMUT-routing",
    name: str = "problem",
) -> Iterable[str]:
    """Lines of a full-matrix CVRP for the patched HGS-CVRP reader (depot = node 1).

    The first three lines are skipped by the reader; the header keys it accepts are
    ``DIMENSION``, ``EDGE_WEIGHT_TYPE``, ``EDGE_WEIGHT_FORMAT``, ``CAPACITY`` and the
    ``EDGE_WEIGHT_SECTION``, which must come after ``DIMENSION``.
    """
    if " " in name:
        raise ValueError("the problem name must be a single token")
    yield f"NAME : {name}"
    yield f"COMMENT : {comment.replace(chr(10), ' ')}"
    yield "TYPE : CVRP"
    yield f"DIMENSION : {int(dimension)}"
    yield "EDGE_WEIGHT_TYPE : EXPLICIT"
    yield "EDGE_WEIGHT_FORMAT : FULL_MATRIX"
    yield f"CAPACITY : {int(capacity)}"
    yield "EDGE_WEIGHT_SECTION"
    yield from matrix_rows
    yield "NODE_COORD_SECTION"
    for index, (x, y) in enumerate(coordinates):
        yield f"{index + 1} {_fmt(x, 6)} {_fmt(y, 6)}"
    yield "DEMAND_SECTION"
    for index, demand in enumerate(demands):
        yield f"{index + 1} {int(demand)}"
    yield "DEPOT_SECTION"
    yield "1"
    yield "-1"
    yield "EOF"

render_lkh_problem

render_lkh_problem(
    *,
    problem_type: str,
    matrix: Sequence[Sequence[int]],
    demands: Sequence[int],
    capacity: int,
    vehicles: int,
    time_windows: Sequence[Sequence[int]] | None = None,
    service_times: Sequence[int] | None = None,
    name: str = "problem",
) -> Iterable[str]

Lines of an LKH-3 problem file: explicit integer FULL_MATRIX, no coordinates.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def render_lkh_problem(
    *,
    problem_type: str,
    matrix: Sequence[Sequence[int]],
    demands: Sequence[int],
    capacity: int,
    vehicles: int,
    time_windows: Sequence[Sequence[int]] | None = None,
    service_times: Sequence[int] | None = None,
    name: str = "problem",
) -> Iterable[str]:
    """Lines of an LKH-3 problem file: explicit integer FULL_MATRIX, no coordinates."""
    if problem_type not in ("CVRP", "ACVRP", "CVRPTW"):
        raise ValueError(f"unsupported LKH-3 type {problem_type!r}")
    if (time_windows is None) != (problem_type != "CVRPTW"):
        raise ValueError("CVRPTW needs time windows, and only CVRPTW takes them")
    yield f"NAME : {name}"
    yield f"TYPE : {problem_type}"
    yield f"DIMENSION : {len(matrix)}"
    yield f"VEHICLES : {int(vehicles)}"
    yield f"CAPACITY : {int(capacity)}"
    yield "EDGE_WEIGHT_TYPE : EXPLICIT"
    yield "EDGE_WEIGHT_FORMAT : FULL_MATRIX"
    yield "EDGE_WEIGHT_SECTION"
    for row in matrix:
        yield " ".join(str(int(value)) for value in row)
    yield "DEMAND_SECTION"
    for index, demand in enumerate(demands):
        yield f"{index + 1} {int(demand)}"
    if time_windows is not None:
        yield "SERVICE_TIME_SECTION"
        for index, service in enumerate(service_times or [0] * len(matrix)):
            yield f"{index + 1} {int(service)}"
        yield "TIME_WINDOW_SECTION"
        for index, (ready, due) in enumerate(time_windows):
            yield f"{index + 1} {int(ready)} {int(due)}"
    yield "DEPOT_SECTION"
    yield "1"
    yield "-1"
    yield "EOF"

lkh_parameter_key

lkh_parameter_key(line: str) -> str

The keyword of a parameter line as LKH-3 reads it: the first token, in upper case.

LKH-3 splits a line on = and white space. Empty for a blank line and for a comment (# ...).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def lkh_parameter_key(line: str) -> str:
    """The keyword of a parameter line as LKH-3 reads it: the first token, in upper case.

    LKH-3 splits a line on ``=`` and white space. Empty for a blank line and for a comment (``# ...``).
    """
    match = _LKH_KEYWORD.match(line)
    if match is None or match.group(1).startswith("#"):
        return ""
    return match.group(1).upper()

check_lkh_extra_lines

check_lkh_extra_lines(extra: Sequence[str]) -> None

Refuse (ValueError) an extra parameter line that sets a parameter of the run.

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def check_lkh_extra_lines(extra: Sequence[str]) -> None:
    """Refuse (``ValueError``) an extra parameter line that sets a parameter of the run."""
    for line in extra:
        if "\n" in line or "\r" in line:
            raise ValueError("Each LKH extra_args entry must contain one physical parameter line")
        key = lkh_parameter_key(line)
        if key in LKH_RUN_PARAMETERS:
            raise ValueError(
                f"{line!r} sets {key}, {LKH_RUN_PARAMETERS[key]}. The runner writes it, and LKH-3 keeps the last "
                "occurrence of a parameter: the run would not be the one that its result records"
            )

render_lkh_params

render_lkh_params(
    *,
    problem: Path,
    solution: Path,
    seed: int,
    time_limit_s: float,
    extra: Sequence[str] = (),
) -> Iterable[str]

Lines of an LKH-3 parameter file for one bounded VRP run.

SPECIAL selects LKH-3's VRP move settings; RUNS = 1 with a huge MAX_TRIALS makes TIME_LIMIT the stopping rule (in LKH-3.0.6 the limit counts from after reading the parameters, preprocessing included); PRECISION = 1 keeps scaled costs inside LKH's 32-bit C * PRECISION; MTSP_MIN_SIZE = 0 lets vehicles stay unused, so VEHICLES is an upper bound rather than an exact fleet. extra lines come last and may tune the search (RUNS = 10, POPULATION_SIZE = 10), not set a parameter of the run (:data:LKH_RUN_PARAMETERS).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def render_lkh_params(
    *,
    problem: Path,
    solution: Path,
    seed: int,
    time_limit_s: float,
    extra: Sequence[str] = (),
) -> Iterable[str]:
    """Lines of an LKH-3 parameter file for one bounded VRP run.

    ``SPECIAL`` selects LKH-3's VRP move settings; ``RUNS = 1`` with a huge
    ``MAX_TRIALS`` makes ``TIME_LIMIT`` the stopping rule (in LKH-3.0.6 the limit
    counts from after reading the parameters, preprocessing included);
    ``PRECISION = 1`` keeps scaled costs inside LKH's 32-bit ``C * PRECISION``;
    ``MTSP_MIN_SIZE = 0`` lets vehicles stay unused, so ``VEHICLES`` is an upper
    bound rather than an exact fleet. ``extra`` lines come last and may tune the
    search (``RUNS = 10``, ``POPULATION_SIZE = 10``), not set a parameter of the
    run (:data:`LKH_RUN_PARAMETERS`).
    """
    check_lkh_extra_lines(extra)
    yield "SPECIAL"
    yield f"PROBLEM_FILE = {problem}"
    yield f"MTSP_SOLUTION_FILE = {solution}"
    yield "RUNS = 1"
    yield "MAX_TRIALS = 1000000000"
    yield f"TIME_LIMIT = {float(time_limit_s):.1f}"
    yield f"SEED = {int(seed)}"
    yield "PRECISION = 1"
    yield "SCALE = 1"
    yield "MTSP_MIN_SIZE = 0"
    yield "TRACE_LEVEL = 1"
    yield from extra

render_explicit_cvrplib

render_explicit_cvrplib(
    *,
    matrix: Sequence[Sequence[int]],
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    num_vehicles: int | None,
    time_windows: Sequence[Sequence[int]] | None = None,
    service_times: Sequence[int] | None = None,
    name: str = "problem",
) -> str

A generic CVRPLIB file with an integer FULL_MATRIX (cvrplib.render_cvrplib).

Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/problem.py
def render_explicit_cvrplib(
    *,
    matrix: Sequence[Sequence[int]],
    coordinates: Sequence[Sequence[float]],
    demands: Sequence[int],
    capacity: int,
    num_vehicles: int | None,
    time_windows: Sequence[Sequence[int]] | None = None,
    service_times: Sequence[int] | None = None,
    name: str = "problem",
) -> str:
    """A generic CVRPLIB file with an integer FULL_MATRIX (``cvrplib.render_cvrplib``)."""
    from mamut_routing_lib.cvrplib import render_cvrplib

    return render_cvrplib(
        name=name,
        comment="MAMUT-routing (scaled integer costs)",
        coordinates=coordinates,
        demands=demands,
        capacity=capacity,
        depot=0,
        num_vehicles=num_vehicles,
        arc_costs=matrix,
        decimals=None,
        time_windows=time_windows,
        service_times=service_times,
        edge_weight_type="EXPLICIT",
    )