Skip to content

mamut_routing_tools.bks_campaign.harvest

Baseline, harvest and reports of a campaign.

  • write_baseline freezes the stored BKS of every selected instance before the campaign (baseline.csv) and refuses to overwrite it: gains are measured against what was published, not against the campaign's own writes.
  • harvest is the only step that writes BKS files, and it records what the store did even when it does not finish (a store error, a store process that died, Ctrl-C): BKS written before the failure are in the history. It sets aside the runs whose instance file changed. For each instance and objective, it reprices the distinct archived routes under the current exact profile, including routes checked by an earlier release. With a verified manifest it retains the TD arcs used by those routes. The lowest exact objective wins, with the first run key breaking ties. If the frozen baseline BKS bytes remain available, harvest also reprices its routes and offers a winner that matches or beats it. Otherwise it offers the winner directly. --offer-all skips the baseline filter. The store re-validates the selected routes, compares exact binary64 costs and keeps the incumbent on a tie. Every harvest is kept in harvests/<NNNN>-<time>.json; harvest.json is the latest one.
  • write_reports writes ledger.csv (one row per run; bks_action is what the store did with the run in any harvest, created over a later kept_existing) and cross-solver.csv (per instance: best per kind, gap to the best, seed spread), ranked by the checker cost recorded at run time.

write_baseline

write_baseline(
    spec: CampaignSpec, *, force: bool = False
) -> Path

Snapshot the stored BKS of the selected instances into baseline.csv.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def write_baseline(spec: CampaignSpec, *, force: bool = False) -> Path:
    """Snapshot the stored BKS of the selected instances into ``baseline.csv``."""
    from mamut_routing_lib.artifacts import get_bks_path_for_instance, load_benchmark_instance, load_bks
    from mamut_routing_lib.objectives import base_objective
    from mamut_routing_lib.solvers.provenance import file_sha256

    from mamut_routing_tools.bks_campaign.plan import select_instances

    path = spec.out / "baseline.csv"
    if path.exists() and not force:
        raise FileExistsError(f"{path} exists: the baseline must predate the campaign (pass --force to replace it)")
    rows = []
    recorded = datetime.now(UTC).isoformat(timespec="seconds")
    for item in select_instances(spec):
        instance = load_benchmark_instance(item.instance_path)
        objective = spec.select.objective.get(item.problem_type) or base_objective(instance)
        bks_path = get_bks_path_for_instance(item.instance_path, objective)
        row = {
            "instance_id": item.instance_id,
            "objective_function": objective.value,
            "cost": "",
            "num_routes": "",
            "method": "",
            "bks_sha256": "",
            "bks_path": str(bks_path),
            "recorded": recorded,
        }
        if bks_path.is_file():
            bks = load_bks(bks_path)
            row.update(cost=bks.cost, num_routes=bks.num_routes, method=bks.metadata.get("method") or "", bks_sha256=file_sha256(bks_path))
        rows.append(row)
    spec.out.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=BASELINE_FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    return path

harvest

harvest(
    spec: CampaignSpec,
    *,
    offer_all: bool = False,
    dry_run: bool = False,
    workers: int = 1,
) -> list[dict[str, Any]]

Offer each instance's best run to the BKS store (the campaign's only writer).

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def harvest(
    spec: CampaignSpec,
    *,
    offer_all: bool = False,
    dry_run: bool = False,
    workers: int = 1,
) -> list[dict[str, Any]]:
    """Offer each instance's best run to the BKS store (the campaign's only writer)."""
    runs, stale = _current_runs(iter_runs(spec.out))
    baseline = read_baseline(spec.out)
    results: list[dict[str, Any]] = []
    groups: dict[tuple[str, str], list[dict]] = {}
    for record in runs:
        if record.get("routes"):
            groups.setdefault((record["instance_id"], record["objective_function"]), []).append(record)
    for group, record in sorted(_best_runs(stale).items()):
        if group not in groups:
            results.append({"key": record["key"], "instance_id": group[0], "action": "skipped",
                            "reason": "the instance file changed after the run (plan runs it again)"})
    jobs = [
        {"records": records, "authors": spec.campaign.authors, "campaign": spec.campaign.name,
         "baseline": None if offer_all else baseline.get(group), "dry_run": dry_run}
        for group, records in sorted(groups.items())
    ]
    try:
        if workers > 1 and len(jobs) > 1:
            import multiprocessing as mp

            with ProcessPoolExecutor(max_workers=workers, mp_context=mp.get_context("spawn")) as pool:
                futures = [pool.submit(_submit_one, job) for job in jobs]
                for job, future in zip(jobs, futures):
                    try:
                        results.append(future.result())
                    except Exception as error:  # noqa: BLE001 - the store process died (out of memory, killed)
                        results.append(
                            _store_error(
                                job["records"][0],
                                f"the store process failed ({type(error).__name__}: {error}); check the BKS file before harvesting again",
                            )
                        )
        else:
            for job in jobs:
                results.append(_submit_one(job))
    finally:
        # Also on Ctrl-C or an unexpected error: the BKS files written so far must be in the history.
        if not dry_run:
            _record_harvest(spec.out, results)
    return results

harvest_history

harvest_history(out: Path) -> list[dict[str, Any]]

Every recorded harvest, oldest first: {"harvested": time, "results": [...]}.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def harvest_history(out: Path) -> list[dict[str, Any]]:
    """Every recorded harvest, oldest first: ``{"harvested": time, "results": [...]}``."""
    history = sorted((out / "harvests").glob("[0-9][0-9][0-9][0-9]-*.json"))
    if history:
        return [json.loads(path.read_text(encoding="utf-8")) for path in history]
    latest = out / "harvest.json"  # a campaign harvested before the history existed
    if latest.is_file():
        return [{"harvested": None, "results": json.loads(latest.read_text(encoding="utf-8"))}]
    return []

write_reports

write_reports(spec: CampaignSpec) -> tuple[Path, Path]

ledger.csv (one row per run) and cross-solver.csv (per instance and objective).

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def write_reports(spec: CampaignSpec) -> tuple[Path, Path]:
    """``ledger.csv`` (one row per run) and ``cross-solver.csv`` (per instance and objective)."""
    from mamut_routing_lib.solvers.report import solver_report_metadata

    spec.out.mkdir(parents=True, exist_ok=True)  # before any `run`: empty reports, not a traceback
    runs = load_runs(spec.out)
    current, _stale = _current_runs(runs)
    baseline = read_baseline(spec.out)
    harvested = _harvested_actions(spec.out)
    best = {group: record["key"] for group, record in _best_runs(current).items()}

    ledger = spec.out / "ledger.csv"
    with ledger.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=LEDGER_FIELDS, extrasaction="ignore")
        writer.writeheader()
        for record in sorted(runs, key=lambda item: (item.get("instance_id", ""), item.get("kind", ""), item.get("seed", 0))):
            group = (record.get("instance_id"), record.get("objective_function"))
            reference = baseline.get(group, {}).get("cost")
            cost = record.get("validated_cost")
            gap = None
            if cost is not None and reference not in (None, ""):
                gap = round(100.0 * (float(cost) - float(reference)) / float(reference), 4) if float(reference) else None
            writer.writerow({
                **record,
                "solver_cost": solver_report_metadata(record.get("solver_report")).get("solver_cost"),
                "baseline_cost": reference,
                "vs_baseline_pct": gap,
                "is_best": best.get(group) == record.get("key"),
                "bks_action": harvested.get(record.get("key"), ("", None))[0],
                "bks_action_at": harvested.get(record.get("key"), ("", None))[1] or "",
            })

    groups: dict[tuple[str, str], list[dict[str, Any]]] = {}
    for record in current:  # runs of an instance file that changed since are not compared
        groups.setdefault((record.get("instance_id"), record.get("objective_function")), []).append(record)
    kinds = sorted({record.get("kind") for record in runs if record.get("kind")})
    compare = spec.out / "cross-solver.csv"
    fields = ["instance_id", "objective_function", "baseline_cost", "overall_best", "winner"]
    for kind in kinds:
        fields += [f"{kind}_best", f"{kind}_routes", f"{kind}_gap_pct", f"{kind}_spread_pct", f"{kind}_valid_runs"]
    with compare.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        for group, records in sorted(groups.items()):
            valid = [record for record in records if record.get("valid") and archived_cost(record) is not None]
            overall = min(valid, key=_objective_key, default=None)
            row: dict[str, Any] = {
                "instance_id": group[0],
                "objective_function": group[1],
                "baseline_cost": baseline.get(group, {}).get("cost"),
                "overall_best": overall["validated_cost"] if overall else None,
                "winner": overall["kind"] if overall else None,
            }
            for kind in kinds:
                kind_runs = [record for record in valid if record.get("kind") == kind]
                if not kind_runs:
                    row[f"{kind}_valid_runs"] = 0
                    continue
                costs = [record["validated_cost"] for record in kind_runs if record["validated_cost"] is not None]
                kind_best_run = min(kind_runs, key=_objective_key)
                kind_best = kind_best_run["validated_cost"]
                row[f"{kind}_best"] = kind_best
                row[f"{kind}_routes"] = kind_best_run.get("num_routes")
                row[f"{kind}_gap_pct"] = round(100.0 * (kind_best - float(overall["validated_cost"])) / float(overall["validated_cost"]), 4) if overall and overall["validated_cost"] and kind_best is not None else None
                row[f"{kind}_spread_pct"] = round(100.0 * (max(costs) - kind_best) / kind_best, 4) if costs and kind_best else None
                row[f"{kind}_valid_runs"] = len(kind_runs)
            writer.writerow(row)
    return ledger, compare