The user solvers config: where external solvers live, and extra solvers.
Looked up, in order: an explicit path (--solvers-config), the
MAMUT_ROUTING_SOLVERS_CONFIG environment variable (an empty value disables
the config), then $XDG_CONFIG_HOME/mamut-routing/solvers.toml (default
~/.config; %APPDATA% on Windows). It is never read from the working
directory or a benchmark tree: the file names executables that will be run.
.. code-block:: toml
schema_version = 1
[solvers.filo2] # override a built-in
executable = "/opt/filo2/build/filo2"
version = "43653e2"
[solvers.ails2]
jar = "/opt/ails2/AILSII.jar"
java = "/opt/jdk-21/bin/java"
[solvers.lkh3]
executable = "~/bin/LKH"
extra_args = ["POPULATION_SIZE = 10"] # LKH-3: extra parameter-file lines (not SEED, TIME_LIMIT,
# PRECISION or the file names: the runner sets those)
[solvers.hgs-fork] # a variant of a built-in
extends = "hgs-cvrp"
executable = "/opt/hgs-fork/hgs"
label = "HGS fork"
[solvers.my-solver] # a new solver
label = "My solver"
executable = "/opt/mine/solve"
argv = ["{executable}", "{problem}", "{solution}", "{time_limit_s}", "{seed}"]
input_format = "cvrplib-explicit" # cvrplib-x | cvrplib-matrix | cvrplib-explicit | lkh
output_format = "cvrplib-sol" # cvrplib-sol | lkh-mtsp
problem_types = ["CVRP", "VRPTW"]
objectives = ["MonoCost"]
symmetric_only = false # it reads asymmetric FULL_MATRIX files (default: true)
id_convention = "zero-based" # its .sol numbers customers 0..n-1 (default: one-based)
mamut-routing solvers init writes a commented starter file (starter_config_text).
Paths: ~ is expanded, and a relative path is read from the config file's folder,
never the working directory: jar = "AILSII.jar", executable = "./bin/filo2".
A bare executable or java name (filo2, java) is looked up on PATH, in
its absolute entries only: a relative entry (.) is the working directory.
With runtime = "python", executable is the solver's script (a file, read
from the config file's folder when relative): argv = ["{python}", "{executable}", ...].
The script is what the provenance hashes; a solver whose argv names its code by
itself ("-m", "package.module") records no executable hash.
Unknown keys and mistyped values (fleet_limit = "false") are errors, so a typo
never silently runs a different command. An error in one [solvers.<name>] table
disables that solver only: it is listed as unavailable with the error, and every
other solver keeps working (a file that is not valid TOML disables all of them).
extends may name a solver defined anywhere in the file. A new solver is symmetric_only = true unless it declares otherwise: road-network
variants (fastest, shortest) are asymmetric and are refused for it, and
the generic explicit file says TYPE : CVRP whatever the matrix. A solver
that extends a built-in inherits the built-in's value (LKH-3 takes
asymmetric matrices, and so does HGS-CVRP in a build with the shipped
full-matrix reader patch. FILO2 and AILS-II do not).
id_convention says how a cvrplib-sol solution file numbers its stops:
one-based (the default: customers 1..n as CVRPLIB writes them, a 0 is the
depot), zero-based (customers 0..n-1) or auto (guess from the file). The
guess reads a one-based file that writes the depot and misses the last customer
as a complete zero-based one, so a solver's convention is better declared.
CONFIG_ENV
module-attribute
CONFIG_ENV = 'MAMUT_ROUTING_SOLVERS_CONFIG'
SCHEMA_VERSION
module-attribute
SolverConfig
dataclass
SolverConfig(
path: Path | None,
descriptors: dict[
str, ExternalSolverDescriptor
] = dict(),
errors: dict[str, str] = dict(),
)
A parsed solvers config: the solvers it defines, and the tables that could not be read.
descriptors
class-attribute
instance-attribute
descriptors: dict[str, ExternalSolverDescriptor] = field(
default_factory=dict
)
errors
class-attribute
instance-attribute
errors: dict[str, str] = field(default_factory=dict)
SolverConfigError
Bases: ValueError
The solvers config cannot be read or describes an impossible solver.
BrokenSolver
BrokenSolver(
name: str,
error: str,
*,
config_path: str,
base: ExternalSolverDescriptor | None = None,
)
Placeholder for a [solvers.<name>] table the config could not read: never available.
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def __init__(self, name: str, error: str, *, config_path: str, base: ExternalSolverDescriptor | None = None):
self.name = name
self.label = base.label if base is not None and base.name == name else name
self.capabilities = base.capabilities if base is not None else SolverCapabilities(objectives={}, in_process=False)
self.error = error
self.config_path = config_path
self.descriptor = base.with_overrides(source=config_path) if base is not None else None
|
label
instance-attribute
label = (
base.label
if base is not None and base.name == name
else name
)
capabilities
instance-attribute
capabilities = (
base.capabilities
if base is not None
else SolverCapabilities(objectives={}, in_process=False)
)
config_path
instance-attribute
config_path = config_path
descriptor
instance-attribute
descriptor = (
base.with_overrides(source=config_path)
if base is not None
else None
)
availability
availability() -> Availability
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def availability(self) -> Availability:
return Availability(False, reason=f"config error: {self.error}", hint=f"fix [solvers.{self.name}] in {self.config_path}")
|
supports
supports(profile: Any, objective: Any) -> Support
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def supports(self, profile: Any, objective: Any) -> Support:
return Support.refuse(f"{self.name}: config error: {self.error}")
|
solve
solve(request: Any, monitor: Any = None) -> Any
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def solve(self, request: Any, monitor: Any = None) -> Any:
raise SolverUnavailableError(f"{self.name}: config error: {self.error} (fix [solvers.{self.name}] in {self.config_path})")
|
default_config_path
default_config_path() -> Path
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def default_config_path() -> Path:
if sys.platform == "win32": # pragma: no cover
base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
else:
base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
return base / "mamut-routing" / "solvers.toml"
|
resolve_config_path
resolve_config_path(
config: str | Path | None = None,
) -> Path | None
The config file to read, or None (an explicit path must exist).
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def resolve_config_path(config: str | Path | None = None) -> Path | None:
"""The config file to read, or ``None`` (an explicit path must exist)."""
if config is not None and str(config) != "":
path = Path(config).expanduser()
if not path.is_file():
raise SolverConfigError(f"solvers config not found: {path}")
return path.resolve()
if CONFIG_ENV in os.environ:
value = os.environ[CONFIG_ENV]
if not value:
return None
path = Path(value).expanduser()
if not path.is_file():
raise SolverConfigError(f"${CONFIG_ENV} points at a missing file: {path}")
return path.resolve()
path = default_config_path()
return path.resolve() if path.is_file() else None
|
config_cache_key
config_cache_key(config: str | Path | None = None) -> str
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def config_cache_key(config: str | Path | None = None) -> str:
try:
path = resolve_config_path(config)
except SolverConfigError:
return f"error:{config}"
if path is None:
return ""
try:
return f"{path}:{path.stat().st_mtime_ns}"
except OSError:
return str(path)
|
clear_cache
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def clear_cache() -> None:
_CACHE.clear()
|
load_config
load_config(
config: str | Path | None = None,
) -> SolverConfig
Parse the solvers config. File-level problems (not TOML, wrong schema) raise
SolverConfigError; a bad [solvers.<name>] table only lands in errors.
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def load_config(config: str | Path | None = None) -> SolverConfig:
"""Parse the solvers config. File-level problems (not TOML, wrong schema) raise
``SolverConfigError``; a bad ``[solvers.<name>]`` table only lands in ``errors``."""
path = resolve_config_path(config)
if path is None:
return SolverConfig(None)
key = (str(path), path.stat().st_mtime_ns)
cached = _CACHE.get(key)
if cached is not None:
return cached
try:
data = tomllib.loads(path.read_text(encoding="utf-8"))
except (OSError, tomllib.TOMLDecodeError) as error:
raise SolverConfigError(f"{path}: {error}") from error
version = data.get("schema_version", SCHEMA_VERSION)
if version != SCHEMA_VERSION:
raise SolverConfigError(f"{path}: schema_version {version} is not supported (expected {SCHEMA_VERSION})")
unknown = sorted(set(data) - {"schema_version", "solvers"})
if unknown:
details = ", ".join(f"{key!r}{_did_you_mean(key, ('schema_version', 'solvers'))}" for key in unknown)
raise SolverConfigError(f"{path}: unknown top-level key(s) {details}; solvers go in [solvers.<name>] tables")
solvers = data.get("solvers", {})
if not isinstance(solvers, dict):
raise SolverConfigError(f"{path}: [solvers] must be a table")
descriptors: dict[str, ExternalSolverDescriptor] = {}
errors: dict[str, str] = {}
def resolve(name: str, chain: tuple[str, ...]) -> None:
if name in descriptors or name in errors:
return
table = solvers[name]
if name in ("pyvrp", "kayros"):
errors[name] = f"solvers.{name}: in-process solvers are not configured here"
return
if not isinstance(table, dict):
errors[name] = f"solvers.{name} must be a table ([solvers.{name}])"
return
parent_name = table.get("extends")
if isinstance(parent_name, str) and parent_name != name and parent_name in solvers:
if parent_name in chain:
errors[name] = f"solvers.{name}.extends: circular ({' -> '.join((*chain, name, parent_name))})"
return
resolve(parent_name, (*chain, name))
if parent_name in errors:
parent_error = errors[parent_name]
errors[name] = parent_error if "circular" in parent_error else (
f"solvers.{name}.extends: [solvers.{parent_name}] has a config error"
)
return
try:
descriptors[name] = _descriptor(name, table, source=str(path), known=descriptors, base_dir=path.parent)
except SolverConfigError as error:
errors[name] = str(error)
for name in solvers:
resolve(name, ())
ordered = {name: descriptors[name] for name in solvers if name in descriptors}
loaded = SolverConfig(path, ordered, {name: errors[name] for name in solvers if name in errors})
_CACHE[key] = loaded
return loaded
|
configured_descriptors(
config: str | Path | None = None,
) -> dict[str, ExternalSolverDescriptor]
Descriptors defined or overridden by the config (empty without a config).
Strict: raises SolverConfigError for the first table with an error. The registry
uses load_config instead, so one bad table does not hide the other solvers.
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def configured_descriptors(config: str | Path | None = None) -> dict[str, ExternalSolverDescriptor]:
"""Descriptors defined or overridden by the config (empty without a config).
Strict: raises ``SolverConfigError`` for the first table with an error. The registry
uses ``load_config`` instead, so one bad table does not hide the other solvers.
"""
loaded = load_config(config)
if loaded.errors:
raise SolverConfigError(next(iter(loaded.errors.values())))
return loaded.descriptors
|
configured_solvers(
config: str | Path | None = None,
) -> dict[str, Callable[[], Any]]
Registry factories for every configured external solver; a table with an error
yields a BrokenSolver that reports it.
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def configured_solvers(config: str | Path | None = None) -> dict[str, Callable[[], Any]]:
"""Registry factories for every configured external solver; a table with an error
yields a ``BrokenSolver`` that reports it."""
from mamut_routing_lib.solvers.external.adapter import ExternalSolver
from mamut_routing_lib.solvers.external.catalog import BUILTIN_DESCRIPTORS
loaded = load_config(config)
path = str(loaded.path)
factories: dict[str, Callable[[], Any]] = {
name: (lambda descriptor=descriptor: ExternalSolver(descriptor, config_path=path))
for name, descriptor in loaded.descriptors.items()
}
for name, error in loaded.errors.items():
if name in ("pyvrp", "kayros"):
continue # never shadows the in-process solver; ``solvers list`` reports the error
factories[name] = lambda name=name, error=error: BrokenSolver(
name, error, config_path=path, base=BUILTIN_DESCRIPTORS.get(name)
)
return factories
|
starter_config_text
starter_config_text(*, detect: bool = True) -> str
A commented solvers config: one table per built-in external solver, all commented out.
With detect, a solver already found on PATH is marked as such (it needs no table).
The text parses as a valid config that defines no solver.
Source code in MAMUT-routing-lib/src/mamut_routing_lib/solvers/external/config.py
| def starter_config_text(*, detect: bool = True) -> str:
"""A commented solvers config: one table per built-in external solver, all commented out.
With ``detect``, a solver already found on PATH is marked as such (it needs no table).
The text parses as a valid config that defines no solver.
"""
from shlex import quote
from mamut_routing_lib.solvers.external.adapter import find_on_path
from mamut_routing_lib.solvers.external.catalog import BUILTIN_DESCRIPTORS, patch_path
parts = [_STARTER_HEADER]
for name, about, lines in _STARTER_SOLVERS:
descriptor = BUILTIN_DESCRIPTORS[name]
text = about.format(homepage=descriptor.homepage or "", hgs_patch=quote(patch_path("hgs-cvrp-explicit-matrix.patch")),
ails_patch=quote(patch_path("ails2-seed-out.patch")))
block = [_comment(text)]
if detect and descriptor.runtime == "native":
found = next((hit for candidate in descriptor.executable_names if (hit := find_on_path(candidate)[0])), None)
if found:
block.append(f"# Found on PATH: {found} (used as is; a table is only needed to pin a version).")
block.append(f"# [solvers.{name}]")
block.extend(f"# {line}" for line in lines)
parts.append("\n" + "\n".join(block) + "\n")
parts.append(_STARTER_FOOTER)
return "".join(parts)
|