"""Rehearse a submission on the practice instances. python3 /app/selfcheck.py rehearse [method dir] [--budget SECONDS] Runs build.sh if the method has one, then runs the method on every practice instance with grading's per-run limits (the per-instance time limit unless --budget changes it, the unprivileged account, a read-only copy of the inputs) and scores what it wrote with the same metric. With several practice instances each one is scored separately and printed on its own line, and the reported score aggregates them with `package_common.aggregate`, the function the grader applies to the sealed instances: the plain mean unless AGGREGATE is geometric. An instance whose run fails takes the floor instead of being dropped, so abandoning a hard one can never improve what you see. The last line printed is {"score": …, "status": …}. It is a rehearsal, not the score you will be given. """ from __future__ import annotations import argparse import json import shutil import sys import tempfile import time from pathlib import Path sys.path.insert(0, "/app") import package_common as pc # noqa: E402 (shared with the grader) import runner # noqa: E402 METHOD = Path("/app/methods/main") def final(value: float, status: str) -> int: print(json.dumps({"score": value, "status": status})) return 0 if status == "ok" else 1 def rehearse_one(method, solver, budget, iid: str, inputs: Path, answers_root: Path | None) -> dict: """One practice instance, run and scored exactly as grading does it.""" t0 = time.time() status, texts = runner.stage_and_run(method, inputs, pc.OUTPUTS, budget, solver) elapsed = time.time() - t0 if status != "ok": return {"id": iid, "score": pc.FLOOR, "status": status, "sec": elapsed, "stdout": ""} answers = pc.answers_for(answers_root, iid) if answers_root is not None else None if pc.SCOPE == "instance": m = pc.score_outputs(texts, inputs, answers) else: # the metric scores a set: a set of one instance root = Path(tempfile.mkdtemp(prefix="rehearsal_set_")) try: shutil.copytree(inputs, root / "instance" / iid) if answers is not None: # arranged as the grader's: / or / dst = root / "answers" / iid if answers.is_dir(): shutil.copytree(answers, dst) else: dst.mkdir(parents=True) shutil.copyfile(answers, dst / answers.name) pc.write_outputs(texts, root / "output" / iid) m = pc.metric_call(root / "instance", root / "answers" if answers is not None else None, root / "output") finally: shutil.rmtree(root, ignore_errors=True) return {"id": iid, "score": m["score"], "status": m["status"], "sec": elapsed, "stdout": m["stdout"]} def rehearse(args) -> int: method = Path(args.method) if args.method else METHOD solver = runner.solver_ids() ok, note = runner.build_submission(method, solver) if not ok: print(f"build.sh failed: {note}") return final(pc.FLOOR, "build_failed") instances = pc.practice_dirs() results = [rehearse_one(method, solver, args.budget, iid, inputs, answers) for iid, inputs, answers in instances] if len(results) == 1: r = results[0] print(f"method finished with status {r['status']} after {r['sec']:.1f} s " f"(budget {args.budget:g} s)") if r["stdout"]: print("metric output:") print(r["stdout"].rstrip()) return final(r["score"], r["status"]) failed = [r["id"] for r in results if r["status"] != "ok"] print(f"{len(results)} practice instances, budget {args.budget:g} s each " f"(a failed instance takes the floor, {pc.FLOOR!r}):") for r in results: mark = "" if r["status"] == "ok" else f" <- {r['status']}, floored" print(f" {r['id']:<16}{r['score']:>18.6g} ({r['sec']:.0f}s){mark}") mean = pc.aggregate([r["score"] for r in results]) print(f"\n {pc.AGGREGATE} over ALL {len(results)} instances: {mean:.6g}" f" <- the grader aggregates the sealed side the same way") if failed: print(f" {len(failed)} failed ({', '.join(failed)}); a failed instance cannot be made to " "disappear from this number.") return final(mean, "ok" if not failed else "partial") def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="command", required=True) r = sub.add_parser("rehearse") r.add_argument("method", nargs="?") r.add_argument("--budget", type=float, default=pc.PER_RUN_BUDGET_SEC) r.set_defaults(func=rehearse) args = ap.parse_args() return args.func(args) if __name__ == "__main__": sys.exit(main())