Skip to content

mamut_routing_tools.generation.vrptw

VRPTW derivation from generated CVRP instances (port of the workbench route_centered / reachable_interval time-window synthesis).

Both methods persist capacity-, horizon- (and window-) feasible anchor routes in the derivation manifest; derive-td certifies the windows along them under traffic. route_centered centres each window on the customer's free-flow visit time along those routes (the family's construct_anchor_routes); before 0.6.0 it used a single capacity-agnostic nearest-neighbour tour, which ran past the horizon beyond about 80 customers and left most windows equal to the whole feasible interval.

stable_seed

stable_seed(*parts: Any) -> int

Deterministic cross-run seed from arbitrary parts (replaces Julia's hash(tuple); values differ from Julia by design, determinism within Python is the contract).

Source code in MAMUT-routing-tools/src/mamut_routing_tools/generation/vrptw.py
def stable_seed(*parts: Any) -> int:
    """Deterministic cross-run seed from arbitrary parts (replaces Julia's
    ``hash(tuple)``; values differ from Julia by design, determinism within
    Python is the contract)."""
    text = "".join(repr(part) for part in parts)
    return int.from_bytes(hashlib.sha256(text.encode()).digest()[:8], "big")

generate_tw_route_centered

generate_tw_route_centered(
    rng: Random,
    travel_times: list[list[int]],
    service_times: list[int],
    horizon_start: int,
    horizon_end: int,
    *,
    demands: list[int],
    capacity: int,
    depot: int = 0,
    width_ratio_mean: float = 0.2,
    width_ratio_std: float = 0.08,
) -> tuple[list[tuple[int, int]], list[list[int]], float]

Windows centred on free-flow visits along capacity-and-horizon-feasible anchor routes.

Returns (time_windows, anchor_routes, width_ratio_mean). The rng draws (one width per customer, in index order) are unchanged, so a seed still gives the same widths; only the centres moved to the feasible routes.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/generation/vrptw.py
def generate_tw_route_centered(
    rng: random.Random,
    travel_times: list[list[int]],
    service_times: list[int],
    horizon_start: int,
    horizon_end: int,
    *,
    demands: list[int],
    capacity: int,
    depot: int = 0,
    width_ratio_mean: float = 0.2,
    width_ratio_std: float = 0.08,
) -> tuple[list[tuple[int, int]], list[list[int]], float]:
    """Windows centred on free-flow visits along capacity-and-horizon-feasible anchor routes.

    Returns ``(time_windows, anchor_routes, width_ratio_mean)``. The rng draws
    (one width per customer, in index order) are unchanged, so a seed still
    gives the same widths; only the centres moved to the feasible routes.
    """
    if depot != 0:
        raise ValueError(f"route_centered windows need the depot at node 0, got {depot}")
    n = len(travel_times)
    horizon = float(horizon_end - horizon_start)
    anchor_routes, arrivals = construct_anchor_routes(
        travel_times, demands, capacity, service_times, horizon_start=horizon_start, horizon_end=horizon_end
    )

    time_windows: list[tuple[int, int]] = [(0, 0)] * n
    time_windows[depot] = (horizon_start, horizon_end)
    for i in range(n):
        if i == depot:
            continue
        center = arrivals[i]
        width_ratio = _clamp(rng.gauss(0.0, 1.0) * width_ratio_std + width_ratio_mean, 0.01, 1.0)
        width = max(1, round(horizon * width_ratio))
        e = round(center - width / 2)
        latest = round(center + width / 2)
        time_windows[i] = repair_time_window(
            e, latest, travel_times[depot][i], travel_times[i][depot], service_times[i], horizon_start, horizon_end
        )
    return time_windows, anchor_routes, width_ratio_mean

cvrptw_text

cvrptw_text(
    parsed: ParsedCvrpInstance,
    instance_name: str,
    comment: str,
    service_times: list[int],
    time_windows: list[tuple[int, int]],
) -> str

The CVRPTW .vrp text :func:write_cvrptw_vrp writes.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/generation/vrptw.py
def cvrptw_text(
    parsed: ParsedCvrpInstance,
    instance_name: str,
    comment: str,
    service_times: list[int],
    time_windows: list[tuple[int, int]],
) -> str:
    """The CVRPTW ``.vrp`` text :func:`write_cvrptw_vrp` writes."""
    lines = [f"NAME : {instance_name}", "TYPE : CVRPTW"]
    if comment:
        lines.append(f"COMMENT : {comment}")
    lines.extend(
        [
            f"DIMENSION : {parsed.dimension}",
            f"CAPACITY : {parsed.capacity}",
            "EDGE_WEIGHT_TYPE : EXPLICIT",
            "EDGE_WEIGHT_FORMAT : FULL_MATRIX",
            "EDGE_WEIGHT_SECTION",
        ]
    )
    lines.extend(" ".join(str(value) for value in row) for row in parsed.arc_costs)
    lines.append("NODE_COORD_SECTION")
    lines.extend(f"{i + 1} {x} {y}" for i, (x, y) in enumerate(parsed.coordinates))
    lines.append("DEMAND_SECTION")
    lines.extend(f"{i + 1} {demand}" for i, demand in enumerate(parsed.demands))
    lines.append("TIME_WINDOW_SECTION")
    lines.extend(f"{i + 1} {ready} {due}" for i, (ready, due) in enumerate(time_windows))
    lines.append("SERVICE_TIME_SECTION")
    lines.extend(f"{i + 1} {service}" for i, service in enumerate(service_times))
    lines.extend(["DEPOT_SECTION", str(parsed.depot_node_index), "-1", "EOF"])
    return "\n".join(lines) + "\n"

derive_vrptw_from_cvrp

derive_vrptw_from_cvrp(
    folder: str | Path,
    base: str,
    *,
    tw_method: str = DEFAULT_TW_METHOD,
    horizon_start: int = HORIZON_START,
    horizon_end: int = HORIZON_END,
    place_slug: str = "",
    source_seed: int = 0,
) -> dict[str, Any]

Derive the fastest-metric VRPTW twin next to a generated CVRP base.

Reads <base>_fastest.vrp, synthesizes service times + time windows on the fastest travel times, and writes <base>_fastest.cvrptw.vrp plus a <base>_vrptw_manifest.json describing the derivation.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/generation/vrptw.py
def derive_vrptw_from_cvrp(
    folder: str | Path,
    base: str,
    *,
    tw_method: str = DEFAULT_TW_METHOD,
    horizon_start: int = HORIZON_START,
    horizon_end: int = HORIZON_END,
    place_slug: str = "",
    source_seed: int = 0,
) -> dict[str, Any]:
    """Derive the fastest-metric VRPTW twin next to a generated CVRP base.

    Reads ``<base>_fastest.vrp``, synthesizes service times + time windows on
    the fastest travel times, and writes ``<base>_fastest.cvrptw.vrp`` plus a
    ``<base>_vrptw_manifest.json`` describing the derivation.
    """
    folder = Path(folder)
    fastest_path = folder / f"{base}_fastest.vrp"
    if not fastest_path.is_file():
        raise FileNotFoundError(f"CVRP fastest .vrp not found at {fastest_path}")
    parsed = parse_cvrp_vrp(fastest_path)
    depot_index = parsed.depot_node_index - 1

    seed_parts = (base, place_slug, source_seed, tw_method, horizon_start, horizon_end, "vrptw_workbench_v1")
    service_times, time_windows, stochastic_params = generate_vrptw_fields(
        seed_parts,
        parsed.arc_costs,
        horizon_start,
        horizon_end,
        tw_method,
        demands=[int(value) for value in parsed.demands],
        capacity=int(parsed.capacity),
        depot=depot_index,
    )

    vrptw_name = f"{base}_fastest_vrptw"
    vrptw_filename = f"{base}_fastest.cvrptw.vrp"
    text = cvrptw_text(
        parsed,
        vrptw_name,
        f"VRPTW derived from {base}_fastest ({tw_method})",
        service_times,
        time_windows,
    )
    manifest_path = folder / f"{base}_vrptw_manifest.json"
    twin_path = folder / vrptw_filename
    if twin_path.is_file() and manifest_path.is_file():
        # Deterministic: an identical derivation is left untouched, so its
        # files (and the fingerprints derive-td records) do not churn.
        try:
            previous = json.loads(manifest_path.read_text(encoding="utf-8"))
        except ValueError:
            previous = {}
        if twin_path.read_text(encoding="utf-8") == text and previous.get("derivation") == json.loads(
            json.dumps(stochastic_params)
        ):
            return {
                "ok": True,
                "action": "unchanged",
                "vrptw_file": vrptw_filename,
                "manifest": manifest_path.name,
                "derivation": stochastic_params,
            }
    twin_path.write_text(text, encoding="utf-8")
    manifest = {
        "generated_at": datetime.now().isoformat(),
        "base_name": base,
        "source_file": fastest_path.name,
        "vrptw_file": vrptw_filename,
        "derivation": stochastic_params,
    }
    write_json(manifest_path, manifest)
    return {
        "ok": True,
        "action": "derived",
        "vrptw_file": vrptw_filename,
        "manifest": f"{base}_vrptw_manifest.json",
        "derivation": stochastic_params,
    }