Skip to content

mamut_routing_lib.models

Pydantic models of the static benchmark contract (CVRP, VRPTW).

Every artifact is validated on load with extra="forbid": an instance file (BenchmarkInstanceVRPTW for VRPTW, BenchmarkInstanceCVRP for CVRP, both with an embedded (n+1) x (n+1) arc_costs matrix), a slim collection instance (BenchmarkInstanceCVRPCollection / BenchmarkInstanceVRPTWCollection, whose matrix comes from an arc_costs_source: a sha-pinned distances sidecar or the euclidean rule), a solution (BenchmarkSolution), a best-known solution (BenchmarkBKS, a solution plus its objective) and a solver claim of optimality (SolverReportedOptimality, validated inside metadata["optimality"]). Node index 0 is the depot, and validation rejects any other depot value and a nonzero depot service time. Customers are 1..num_customers. Time-dependent instances live in mamut_routing_lib.td.models.

NumericOperand module-attribute

NumericOperand: TypeAlias = StrictInt | StrictFloat

Coordinate module-attribute

Coordinate: TypeAlias = tuple[
    NumericOperand, NumericOperand
]

ArcCost module-attribute

ArcCost: TypeAlias = NumericOperand

NonnegativeInteger module-attribute

NonnegativeInteger: TypeAlias = Annotated[
    StrictInt, Field(ge=0)
]

ARC_COSTS_DISTANCES_MODEL module-attribute

ARC_COSTS_DISTANCES_MODEL = 'distances-sidecar'

ARC_COSTS_EUCLIDEAN_MODEL module-attribute

ARC_COSTS_EUCLIDEAN_MODEL = 'euclidean'

AnyArcCostsSource module-attribute

AnyArcCostsSource = Annotated[
    ArcCostsDistancesRef | ArcCostsEuclidean,
    Field(discriminator="model"),
]

LoadedStaticInstance module-attribute

LoadedStaticInstance: TypeAlias = (
    BenchmarkInstanceCVRP | BenchmarkInstanceVRPTW
)

AnyCollectionStaticInstance module-attribute

AnyCollectionStaticInstance: TypeAlias = (
    BenchmarkInstanceCVRPCollection
    | BenchmarkInstanceVRPTWCollection
)

AnyStaticBenchmarkInstance module-attribute

AnyStaticBenchmarkInstance: TypeAlias = (
    LoadedStaticInstance | AnyCollectionStaticInstance
)

LEGACY_OPTIMALITY_CLAIM_MESSAGE module-attribute

LEGACY_OPTIMALITY_CLAIM_MESSAGE = "metadata.optimality holds a claim in the format of mamut-routing-lib versions before 0.13 (a 'proven: true' stamp). This library does not read that format. Read such historical files with mamut-routing-lib 0.12.0."

BenchmarkInstance module-attribute

BenchmarkInstance = BenchmarkInstanceVRPTW

ArtifactPaths

Bases: BaseModel

Repository-relative paths of the four artifacts of a generated instance (.vrp.json, .vrp, meta, manifest).

vrp_json instance-attribute

vrp_json: str

vrp instance-attribute

vrp: str

meta instance-attribute

meta: str

manifest instance-attribute

manifest: str

validate_relative_paths classmethod

validate_relative_paths(value: str) -> str
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("vrp_json", "vrp", "meta", "manifest")
@classmethod
def validate_relative_paths(cls, value: str) -> str:
    return _validate_relative_path(value)

InstanceMetadata

Bases: BaseModel

Structured metadata of a generated (OSM-derived) instance.

Historic families carry a free-form dict instead; artifacts.has_structured_metadata tells the two apart. num_vehicles_lb is the bin-packing lower bound on the route count that the -k<K> name suffix advertises.

authors instance-attribute

authors: str

generated_at instance-attribute

generated_at: str

problem_type instance-attribute

problem_type: ProblemType

metric_variant instance-attribute

metric_variant: MetricVariant

place_slug instance-attribute

place_slug: str

source_base_name instance-attribute

source_base_name: str

source_city instance-attribute

source_city: str

source_seed instance-attribute

source_seed: int

source_folder instance-attribute

source_folder: str

num_vehicles_lb class-attribute instance-attribute

num_vehicles_lb: int | None = None

submodule_git_commit class-attribute instance-attribute

submodule_git_commit: str | None = None

generator_version class-attribute instance-attribute

generator_version: str | None = None

artifact_paths instance-attribute

artifact_paths: ArtifactPaths

sibling_variant_paths class-attribute instance-attribute

sibling_variant_paths: dict[str, str] = Field(
    default_factory=dict
)

derived_problem_paths class-attribute instance-attribute

derived_problem_paths: dict[str, str] = Field(
    default_factory=dict
)

source_problem_paths class-attribute instance-attribute

source_problem_paths: dict[str, str] = Field(
    default_factory=dict
)

license class-attribute instance-attribute

license: str | None = None

license_url class-attribute instance-attribute

license_url: str | None = None

validate_path_map classmethod

validate_path_map(value: dict[str, str]) -> dict[str, str]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("sibling_variant_paths", "derived_problem_paths", "source_problem_paths")
@classmethod
def validate_path_map(cls, value: dict[str, str]) -> dict[str, str]:
    for path_value in value.values():
        _validate_relative_path(path_value)
    return value

validate_num_vehicles_lb classmethod

validate_num_vehicles_lb(value: int | None) -> int | None
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("num_vehicles_lb")
@classmethod
def validate_num_vehicles_lb(cls, value: int | None) -> int | None:
    if value is not None and value <= 0:
        raise ValueError("num_vehicles_lb must be positive")
    return value

ReferenceLLA

Bases: BaseModel

Geodetic origin (latitude, longitude, altitude) of the local ENU frame the coordinates are expressed in.

lat instance-attribute

lat: float

lon instance-attribute

lon: float

alt class-attribute instance-attribute

alt: float = 0.0

BenchmarkInstanceVRPTW

Bases: _InstanceValidationMixin

A VRPTW instance with an embedded arc-cost matrix.

Adds per-node service_times and time_windows ([ready, due], depot included) to the CVRP core. Historic families (Sintef2008, Dimacs2021, Ortec2022) and hydrated collection instances use this model; service starts at or after ready and at or before due.

instance_name instance-attribute

instance_name: str

instance_origin instance-attribute

instance_origin: InstanceOrigin

benchmark_name instance-attribute

benchmark_name: BenchmarkName

service_times instance-attribute

service_times: list[NumericOperand]

time_windows instance-attribute

time_windows: list[tuple[NumericOperand, NumericOperand]]

metadata class-attribute instance-attribute

metadata: InstanceMetadata | dict[str, Any] = Field(
    default_factory=dict, union_mode="left_to_right"
)

validate_depot_service classmethod

validate_depot_service(value: list[Any]) -> list[Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("service_times")
@classmethod
def validate_depot_service(cls, value: list[Any]) -> list[Any]:
    return require_zero_depot_service(value)

validate_vrptw_node_vector_lengths classmethod

validate_vrptw_node_vector_lengths(
    value: list[Any], info: Any
) -> list[Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("service_times", "time_windows")
@classmethod
def validate_vrptw_node_vector_lengths(cls, value: list[Any], info: Any) -> list[Any]:
    if "num_customers" not in info.data:
        return value
    expected_length = info.data["num_customers"] + 1
    if len(value) != expected_length:
        raise ValueError(
            f"Length of {info.field_name} must be {expected_length} "
            f"(based on num_customers={info.data['num_customers']} + 1 for depot)"
        )
    return value

from_legacy_dict classmethod

from_legacy_dict(
    legacy_instance: dict[str, Any],
) -> "BenchmarkInstanceVRPTW"

Load a legacy VRPTW descriptor, renaming its arc_travel_times matrix to arc_costs.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@classmethod
def from_legacy_dict(cls, legacy_instance: dict[str, Any]) -> "BenchmarkInstanceVRPTW":
    """Load a legacy VRPTW descriptor, renaming its arc_travel_times matrix to arc_costs."""
    if "arc_costs" in legacy_instance:
        raise ValueError("Legacy instance already contains 'arc_costs'")
    if "arc_travel_times" not in legacy_instance:
        raise ValueError("Legacy instance is missing required field 'arc_travel_times'")

    migrated = dict(legacy_instance)
    migrated["arc_costs"] = migrated.pop("arc_travel_times")
    return cls(**migrated)

BenchmarkInstanceCVRP

Bases: _InstanceValidationMixin

A CVRP instance with an embedded arc-cost matrix (no service times, no time windows).

instance_name instance-attribute

instance_name: str

instance_origin instance-attribute

instance_origin: InstanceOrigin

benchmark_name instance-attribute

benchmark_name: BenchmarkName

metadata class-attribute instance-attribute

metadata: InstanceMetadata | dict[str, Any] = Field(
    default_factory=dict, union_mode="left_to_right"
)

ArcCostsDistancesRef

Bases: BaseModel

Arc costs by sha-pinned reference to a collection distances sidecar.

model class-attribute instance-attribute

model: Literal["distances-sidecar"] = (
    ARC_COSTS_DISTANCES_MODEL
)

distances instance-attribute

distances: SidecarRef

ArcCostsEuclidean

Bases: BaseModel

Arc costs materialized from the instance coordinates on load.

The canonical definition is round(hypot(dx, dy), decimals) on the stored ENU coordinates (IEEE-754 doubles, Python round-half-to-even), so no sidecar is needed for the euclidean metric variant.

model class-attribute instance-attribute

model: Literal['euclidean'] = ARC_COSTS_EUCLIDEAN_MODEL

decimals class-attribute instance-attribute

decimals: StrictInt = 3

validate_decimals classmethod

validate_decimals(value: int) -> int
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("decimals")
@classmethod
def validate_decimals(cls, value: int) -> int:
    if value < 0:
        raise ValueError("decimals must be >= 0")
    return value

BenchmarkInstanceCVRPCollection

Bases: _SlimInstanceValidationMixin

Slim CVRP instance of a family-first collection: arc costs by arc_costs_source, see artifacts.hydrate_collection_instance.

BenchmarkInstanceVRPTWCollection

Bases: _SlimInstanceValidationMixin

Slim VRPTW instance of a family-first collection (service times and windows may be fractional).

service_times instance-attribute

service_times: list[NumericOperand]

time_windows instance-attribute

time_windows: list[tuple[NumericOperand, NumericOperand]]

validate_depot_service classmethod

validate_depot_service(value: list[Any]) -> list[Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("service_times")
@classmethod
def validate_depot_service(cls, value: list[Any]) -> list[Any]:
    return require_zero_depot_service(value)

validate_vrptw_node_vector_lengths classmethod

validate_vrptw_node_vector_lengths(
    value: list[Any], info: Any
) -> list[Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("service_times", "time_windows")
@classmethod
def validate_vrptw_node_vector_lengths(cls, value: list[Any], info: Any) -> list[Any]:
    if "num_customers" not in info.data:
        return value
    expected_length = info.data["num_customers"] + 1
    if len(value) != expected_length:
        raise ValueError(
            f"Length of {info.field_name} must be {expected_length} "
            f"(based on num_customers={info.data['num_customers']} + 1 for depot)"
        )
    return value

validate_time_windows classmethod

validate_time_windows(value: list[Any]) -> list[Any]
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("time_windows")
@classmethod
def validate_time_windows(cls, value: list[Any]) -> list[Any]:
    for index, (earliest, latest) in enumerate(value):
        if earliest > latest:
            raise ValueError(f"time window at index {index} has earliest > latest")
    return value

ClaimEvidence

Bases: BaseModel

A file preserved as evidence of a solver claim, pinned by the sha256 of its bytes.

path class-attribute instance-attribute

path: str = Field(min_length=1)

sha256 class-attribute instance-attribute

sha256: str = Field(pattern='^[0-9a-f]{64}$')

scope class-attribute instance-attribute

scope: Literal['file'] = 'file'

validate_path classmethod

validate_path(value: str) -> str
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("path")
@classmethod
def validate_path(cls, value: str) -> str:
    return _validate_relative_path(value)

SolverReportedOptimality

Bases: BaseModel

An attributable solver self-report of optimality, stored under metadata["optimality"].

target_profile names the evaluation profile under which the solver claims optimality. The store requires it to equal the profile of the evaluated family. reported_primal and reported_dual are the solver's own bounds, in its own arithmetic, and evidence pins a preserved file of the run. The checker verifies the routes but not the claim.

status instance-attribute

status: Literal['solver-reported-optimal']

target_profile class-attribute instance-attribute

target_profile: str = Field(min_length=1)

solver class-attribute instance-attribute

solver: str = Field(min_length=1)

campaign class-attribute instance-attribute

campaign: str | None = None

reported_primal class-attribute instance-attribute

reported_primal: NumericOperand | None = None

reported_dual class-attribute instance-attribute

reported_dual: NumericOperand | None = None

evidence class-attribute instance-attribute

evidence: ClaimEvidence | None = None

validate_bound classmethod

validate_bound(value)
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@field_validator("reported_primal", "reported_dual")
@classmethod
def validate_bound(cls, value):
    if isinstance(value, float) and not isfinite(value):
        raise ValueError("a reported bound must be finite")
    return value

LegacyOptimalityClaimError

Bases: ValueError

A BKS or solution file carries an optimality claim in the format of library versions before 0.13.

BenchmarkSolution

Bases: _SolutionValidationMixin

A candidate solution: elementary routes of positive customer ids, optional cost.

cost may be None (the checker prices the routes) or the exact expected value (the checker then reports objective_value_mismatch on any deviation).

BenchmarkBKS

Bases: _SolutionValidationMixin

A best-known solution: a solution plus the objective_function it is best under.

Stored as <base>.bks.<ObjectiveFunction>.json next to the instance and written only through mamut_routing_lib.bks (checker cost, mandatory metadata.authors, replace-only-if-strictly-better).

objective_function instance-attribute

objective_function: ObjectiveFunction

from_legacy_dict classmethod

from_legacy_dict(
    legacy_bks: dict[str, Any],
    objective_function: ObjectiveFunction,
) -> "BenchmarkBKS"
Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
@classmethod
def from_legacy_dict(
    cls,
    legacy_bks: dict[str, Any],
    objective_function: ObjectiveFunction,
) -> "BenchmarkBKS":
    migrated = dict(legacy_bks)
    migrated["objective_function"] = objective_function
    return cls(**migrated)

require_depot_zero

require_depot_zero(value: int) -> int

Validate the depot index on load. The exact profiles place the depot at vertex 0.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
def require_depot_zero(value: int) -> int:
    """Validate the depot index on load. The exact profiles place the depot at vertex 0."""
    if value != 0:
        raise ValueError(f"depot must be vertex 0, got {value!r}")
    return value

require_zero_depot_service

require_zero_depot_service(value: list[Any]) -> list[Any]

Validate a service-time vector on load. The depot has no service duration.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
def require_zero_depot_service(value: list[Any]) -> list[Any]:
    """Validate a service-time vector on load. The depot has no service duration."""
    if value and value[0] != 0:
        raise ValueError(f"depot service time must be zero, got {value[0]!r}")
    return value

is_pre_013_optimality_claim

is_pre_013_optimality_claim(claim: Any) -> bool

True for the proven: true stamp that library versions before 0.13 wrote.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
def is_pre_013_optimality_claim(claim: Any) -> bool:
    """True for the ``proven: true`` stamp that library versions before 0.13 wrote."""
    return isinstance(claim, dict) and "proven" in claim and "status" not in claim

reject_pre_013_optimality_claim

reject_pre_013_optimality_claim(
    payload: Any, source: Any = None
) -> None

Raise LegacyOptimalityClaimError when payload["metadata"]["optimality"] has the pre-0.13 shape.

Source code in MAMUT-routing-tools/MAMUT-routing-lib/src/mamut_routing_lib/models.py
def reject_pre_013_optimality_claim(payload: Any, source: Any = None) -> None:
    """Raise ``LegacyOptimalityClaimError`` when ``payload["metadata"]["optimality"]`` has the pre-0.13 shape."""
    metadata = payload.get("metadata") if isinstance(payload, dict) else None
    if isinstance(metadata, dict) and is_pre_013_optimality_claim(metadata.get("optimality")):
        prefix = f"{source}: " if source is not None else ""
        raise LegacyOptimalityClaimError(prefix + LEGACY_OPTIMALITY_CLAIM_MESSAGE)