mal_core.scoring

Post-run scoring subpackage: scorers, registry, config, runner, LLM judge.

 1"""Post-run scoring subpackage: scorers, registry, config, runner, LLM judge."""
 2from .config import ScoringConfig, load_config
 3from .feedback import get_feedback
 4from .llm_scorer import Verdict, score_with_llm
 5from .registry import build_registry, list_scorers
 6from .runner import format_summary, run_scoring
 7
 8__all__ = [
 9    "ScoringConfig",
10    "load_config",
11    "get_feedback",
12    "Verdict",
13    "score_with_llm",
14    "build_registry",
15    "list_scorers",
16    "format_summary",
17    "run_scoring",
18]
@dataclass
class ScoringConfig:
26@dataclass
27class ScoringConfig:
28    """Effective scoring configuration: which scorers run and their weights.
29
30    Built by :func:`load_config` from the registry defaults, an optional
31    YAML file and the CLI overrides.
32    """
33
34    enabled: set[str] = field(default_factory=set)
35    weights: dict[str, float] = field(default_factory=dict)
36
37    def weight_of(self, name: str) -> float:
38        """Composite weight of one scorer, falling back to the registry default."""
39        return self.weights.get(name, COMPOSITE_WEIGHTS.get(name, 1.0))

Effective scoring configuration: which scorers run and their weights.

Built by load_config() from the registry defaults, an optional YAML file and the CLI overrides.

ScoringConfig(enabled: set[str] = <factory>, weights: dict[str, float] = <factory>)
enabled: set[str]
weights: dict[str, float]
def weight_of(self, name: str) -> float:
37    def weight_of(self, name: str) -> float:
38        """Composite weight of one scorer, falling back to the registry default."""
39        return self.weights.get(name, COMPOSITE_WEIGHTS.get(name, 1.0))

Composite weight of one scorer, falling back to the registry default.

def load_config( config_path: pathlib.Path | None = None, only: list[str] | None = None, skip: list[str] | None = None, enable: list[str] | None = None) -> ScoringConfig:
 59def load_config(
 60    config_path: Path | None = None,
 61    only: list[str] | None = None,
 62    skip: list[str] | None = None,
 63    enable: list[str] | None = None,
 64) -> ScoringConfig:
 65    """Resolve the scoring configuration from defaults, YAML and CLI flags.
 66
 67    Precedence, weakest first: registry defaults, then the YAML file
 68    given by ``config_path``, then ``enable``/``only``/``skip``. An
 69    unknown scorer name in any of them raises ValueError; a missing
 70    config file raises FileNotFoundError.
 71    """
 72    cfg = default_config()
 73    registry = build_registry()
 74    canonical = {name.lower(): name for name in registry}
 75
 76    def _resolve(names: list[str]) -> list[str]:
 77        """Map CLI scorer names to canonical registry names.
 78
 79        Matching is case-insensitive and blank names are dropped; an
 80        unknown name raises ValueError (there is no fallback name).
 81        """
 82        resolved = []
 83        for raw in names:
 84            name = raw.strip()
 85            if not name:
 86                continue
 87            canon = canonical.get(name.lower())
 88            if canon is None:
 89                raise ValueError(
 90                    f"unknown scorer '{name}' (see: malariasim score --list)"
 91                )
 92            resolved.append(canon)
 93        return resolved
 94
 95    if enable:
 96        cfg.enabled.update(_resolve(enable))
 97    if config_path is not None:
 98        if not config_path.exists():
 99            raise FileNotFoundError(f"scoring config not found: {config_path}")
100        raw: dict[str, Any] = yaml.safe_load(config_path.read_text()) or {}
101        for name, spec in (raw.get("scorers") or {}).items():
102            if not isinstance(spec, dict) or name not in registry:
103                continue
104            if spec.get("enabled") is True:
105                cfg.enabled.add(name)
106            elif spec.get("enabled") is False:
107                cfg.enabled.discard(name)
108            if "weight" in spec:
109                cfg.weights[name] = float(spec["weight"])
110    if only:
111        keep = set(_resolve(only))
112        cfg.enabled &= keep
113    if skip:
114        cfg.enabled -= set(_resolve(skip))
115    return cfg

Resolve the scoring configuration from defaults, YAML and CLI flags.

Precedence, weakest first: registry defaults, then the YAML file given by config_path, then enable/only/skip. An unknown scorer name in any of them raises ValueError; a missing config file raises FileNotFoundError.

def get_feedback( scorecard: dict[str, typing.Any], baseline: dict[str, typing.Any] | None = None) -> str:
18def get_feedback(scorecard: dict[str, Any], baseline: dict[str, Any] | None = None) -> str:
19    """Render a scorecard as Markdown feedback for a human reader.
20
21    Reports the composite and its verdict, the failed gates, the skipped
22    scorers, the weakest composite dimensions and — when a baseline
23    scorecard is given — the composite delta and the dimensions that
24    regressed against it.
25    """
26    lines = ["## Scoring Feedback", ""]
27    composite = scorecard.get("composite", 0.0)
28    verdict = scorecard.get("verdict", "?")
29    lines.append(f"Composite: {composite:.4f} ({verdict})")
30
31    failed_gates = [
32        name for name, g in scorecard.get("gates", {}).items() if not g.get("passed")
33    ]
34    if failed_gates:
35        lines.append(f"Failed gates: {', '.join(failed_gates)}")
36    skipped = scorecard.get("skipped", {})
37    if skipped:
38        lines.append(f"Skipped scorers: {', '.join(sorted(skipped))}")
39    lines.append("")
40
41    if baseline is not None:
42        base = baseline.get("composite", 0.0)
43        delta = composite - base
44        lines.append("### Delta vs baseline")
45        lines.append(f"Baseline composite: {base:.4f} -> {delta:+.4f}")
46        base_dims = baseline.get("composite_dimensions", {})
47        cur_dims = scorecard.get("composite_dimensions", {})
48        regressions = []
49        for name, info in cur_dims.items():
50            if name in base_dims:
51                d = info["score"] - base_dims[name]["score"]
52                if d < -0.05:
53                    regressions.append(f"{name} ({d:+.3f})")
54        if regressions:
55            lines.append(f"Regressed dimensions: {', '.join(regressions)}")
56        lines.append("")
57
58    lines.append("### Weakest dimensions")
59    for name, score in _lowest(scorecard):
60        target = scorecard.get("scores", {}).get(name, {}).get("target", "")
61        lines.append(f"- {name}: {score:.3f} (target {target})")
62    return "\n".join(lines)

Render a scorecard as Markdown feedback for a human reader.

Reports the composite and its verdict, the failed gates, the skipped scorers, the weakest composite dimensions and — when a baseline scorecard is given — the composite delta and the dimensions that regressed against it.

class Verdict(pydantic.main.BaseModel):
 83class Verdict(BaseModel):
 84    """Structured LLM verdict on a calibration report."""
 85
 86    verdict: Literal["viable", "borderline", "regressed", "collapsed"]
 87    """One of the four qualitative categories. ``unknown`` is reserved for
 88    the deterministic fallback and is not a valid LLM response."""
 89
 90    composite_estimate: float = Field(ge=0.0, le=1.0)
 91    """The LLM's holistic read of the report, in [0.0, 1.0]. Allowed to
 92    deviate from the deterministic composite by up to 0.10."""
 93
 94    concerns: list[str] = Field(default_factory=list)
 95    """Specific dimensions that are out-of-range or suspicious. Each entry
 96    should cite the dimension id (e.g. ``D1``) and the observed value."""
 97
 98    recommendations: list[str] = Field(default_factory=list)
 99    """Concrete, runnable actions a human or another agent can take to
100    address the concerns."""
101
102    literature_grounding: list[str] = Field(default_factory=list)
103    """One short sentence per paper / source the LLM relied on. In-text
104    citation in parentheses, e.g. ``Mordecai 2013``."""

Structured LLM verdict on a calibration report.

verdict: Literal['viable', 'borderline', 'regressed', 'collapsed'] = PydanticUndefined

One of the four qualitative categories. unknown is reserved for the deterministic fallback and is not a valid LLM response.

composite_estimate: float = PydanticUndefined

The LLM's holistic read of the report, in [0.0, 1.0]. Allowed to deviate from the deterministic composite by up to 0.10.

concerns: list[str] = PydanticUndefined

Specific dimensions that are out-of-range or suspicious. Each entry should cite the dimension id (e.g. D1) and the observed value.

recommendations: list[str] = PydanticUndefined

Concrete, runnable actions a human or another agent can take to address the concerns.

literature_grounding: list[str] = PydanticUndefined

One short sentence per paper / source the LLM relied on. In-text citation in parentheses, e.g. Mordecai 2013.

def score_with_llm( report: dict[str, typing.Any], *, model: str = 'minimax/minimax-m3', cache_dir: pathlib.Path | None = None, timeout_s: int = 180) -> dict[str, typing.Any]:
263def score_with_llm(
264    report: dict[str, Any],
265    *,
266    model: str = LLM_MODEL_DEFAULT,
267    cache_dir: Path | None = None,
268    timeout_s: int = LLM_TIMEOUT_S,
269) -> dict[str, Any]:
270    """Score a calibration report with the LLM judge.
271
272    The function:
273    1. Computes a content hash of the report + model id.
274    2. Checks the cache and returns a cached verdict if one exists.
275    3. Resolves the ``OPENROUTER_KEY``.
276    4. Posts a JSON payload to the OpenRouter ``chat/completions`` endpoint
277       (:data:`LLM_BASE_URL`) with :mod:`requests`, then parses the reply
278       into a :class:`Verdict`.
279    5. Caches the verdict and returns it.
280    6. On any failure, returns :func:`deterministic_fallback`.
281
282    Args:
283        report: The calibration report dict. Typically contains
284            ``experiment``, ``scores`` (one entry per registered scorer),
285            ``composite``, etc.
286        model: The model id to use. Defaults to
287            :data:`LLM_MODEL_DEFAULT`.
288        cache_dir: Override the cache directory. Defaults to
289            ``.cache/llm_verdicts`` under the current working directory.
290        timeout_s: Per-request timeout in seconds.
291
292    Returns:
293        A dict matching :class:`Verdict`. On LLM failure, a dict
294        matching :func:`deterministic_fallback` (with an extra
295        ``fallback`` field).
296    """
297    # 1. Hash + cache lookup
298    content_hash = _report_hash(report, model)
299    cache_root = Path(cache_dir) if cache_dir is not None else Path(LLM_CACHE_DIRNAME)
300    cache_file = _cache_path(cache_root, content_hash)
301    cached = _read_cache(cache_file)
302    if cached is not None:
303        cached["cache_hit"] = True
304        return cached
305
306    # 2. API key
307    api_key = _load_api_key()
308    if not api_key:
309        return deterministic_fallback(report, reason="OPENROUTER_KEY not set")
310
311    # 3. Call the OpenRouter API directly via requests + parse JSON response.
312
313    try:
314        import requests
315
316        headers = {
317            "Content-Type": "application/json",
318            "Authorization": f"Bearer {api_key}",
319        }
320        payload = {
321            "model": model,
322            "temperature": 0,
323            "timeout": timeout_s,
324            "messages": [
325                {"role": "system", "content": _get_system_prompt()},
326                {"role": "user", "content": f"Calibration report:\n```json\n{json.dumps(report, indent=2, default=str)}\n```\n\nReturn ONLY a JSON object matching this schema:\n{Verdict.model_json_schema()}"},
327            ],
328        }
329
330        started = time.monotonic()
331        resp = requests.post(
332            f"{LLM_BASE_URL}/chat/completions",
333            headers=headers,
334            json=payload,
335            timeout=timeout_s,
336        )
337        resp.raise_for_status()
338        elapsed = time.monotonic() - started
339
340        content = resp.json()["choices"][0]["message"]["content"]
341        # Strip markdown fences if present
342        content = content.strip()
343        if content.startswith("```"):
344            content = content.split("\n", 1)[1]
345            if content.endswith("```"):
346                content = content[:-3]
347            content = content.strip()
348
349        parsed = json.loads(content)
350        verdict_obj = Verdict(**parsed)
351        verdict_dict = verdict_obj.model_dump()
352        verdict_dict["latency_s"] = round(elapsed, 3)
353        verdict_dict["model"] = model
354        verdict_dict["cache_hit"] = False
355
356        # 4. Cache + return
357        _write_cache(cache_file, verdict_dict)
358        return verdict_dict
359
360    except ValidationError as exc:
361        return deterministic_fallback(
362            report,
363            reason=f"LLM output failed Pydantic validation: {exc}",
364        )
365    except Exception as exc:  # noqa: BLE001 — any LLM/transport failure
366        return deterministic_fallback(
367            report,
368            reason=f"LLM call failed: {type(exc).__name__}: {exc}",
369        )

Score a calibration report with the LLM judge.

The function:

  1. Computes a content hash of the report + model id.
  2. Checks the cache and returns a cached verdict if one exists.
  3. Resolves the OPENROUTER_KEY.
  4. Posts a JSON payload to the OpenRouter chat/completions endpoint (LLM_BASE_URL) with requests, then parses the reply into a Verdict.
  5. Caches the verdict and returns it.
  6. On any failure, returns deterministic_fallback().

Args: report: The calibration report dict. Typically contains experiment, scores (one entry per registered scorer), composite, etc. model: The model id to use. Defaults to LLM_MODEL_DEFAULT. cache_dir: Override the cache directory. Defaults to .cache/llm_verdicts under the current working directory. timeout_s: Per-request timeout in seconds.

Returns: A dict matching Verdict. On LLM failure, a dict matching deterministic_fallback() (with an extra fallback field).

def build_registry() -> dict[str, mal_core.scoring.registry.ScorerSpec]:
 86def build_registry() -> dict[str, ScorerSpec]:
 87    """Instantiate every known scorer and map its name to its registry entry."""
 88    instances: list[Scorer] = [
 89        HabitatOccupancyScorer(),    # D1
 90        SurvivalScorer(),            # D2
 91        EIPScorer(),                 # D3
 92        StabilityScorer(),           # D4
 93        MoransScorer(),              # D5
 94        CouplingScorer(),            # D8
 95        AquaticStructureScorer(),    # D11
 96        PoolPersistenceScorer(),     # D19 (promoted 2026-10)
 97        WashoutResponseScorer(),     # D20 (promoted 2026-10)
 98        LongHorizonPersistenceScorer(),  # D15
 99        DetectionCoverageScorer(),   # D16
100        DispersalKernelScorer(),     # D21
101        CasesGhanaScorer(),          # D25
102        DataValidGate(),             # G6
103        DeterminismGate(),           # G7
104        PerformanceGate(),           # G10
105        HostInputGate(),             # G12
106        MobilityGate(),              # G14
107        UrbanProductivityGate(),     # G24
108    ]
109    registry: dict[str, ScorerSpec] = {}
110    for scorer in instances:
111        registry[scorer.name] = ScorerSpec(cls=type(scorer), kind=scorer.kind)
112    return registry

Instantiate every known scorer and map its name to its registry entry.

def list_scorers() -> list[dict[str, str | float | bool]]:
115def list_scorers() -> list[dict[str, str | float | bool]]:
116    """Human-readable listing for ``malariasim score --list``."""
117    rows: list[dict[str, str | float | bool]] = []
118    for name, spec in sorted(build_registry().items()):
119        scorer = spec.cls()
120        rows.append(
121            {
122                "name": name,
123                "kind": spec.kind,
124                "weight": COMPOSITE_WEIGHTS.get(name, 0.0),
125                "description": scorer.description,
126                "manual": scorer.manual,
127            }
128        )
129    return rows

Human-readable listing for malariasim score --list.

def format_summary(scorecard: dict[str, typing.Any]) -> str:
153def format_summary(scorecard: dict[str, Any]) -> str:
154    """Compact human-readable summary for the CLI."""
155    lines = [
156        f"Composite: {scorecard['composite']:.4f}  "
157        f"Verdict: {scorecard['verdict']}",
158        "",
159        "Composite dimensions:",
160    ]
161    for name, info in scorecard.get("composite_dimensions", {}).items():
162        s = scorecard["scores"][name]
163        marker = "ok " if s["passed"] else "LOW"
164        lines.append(
165            f"  [{marker}] {name:28s} {s['score']:.3f} "
166            f"(w={info['weight']}) value={s['value']} target={s['target']}"
167        )
168    if scorecard.get("gates"):
169        lines.append("")
170        lines.append("Gates (binary, outside composite):")
171        for name, g in scorecard["gates"].items():
172            marker = "PASS" if g["passed"] else "FAIL"
173            lines.append(f"  [{marker}] {name:28s} {g['score']:.3f}")
174    if scorecard.get("skipped"):
175        lines.append("")
176        lines.append("Skipped:")
177        for name, reason in scorecard["skipped"].items():
178            lines.append(f"  [SKIP] {name:28s} {reason}")
179    lines.append("")
180    lines.append(f"Scorecard saved: {Path(scorecard['run_dir']) / 'scorecard.json'}")
181    return "\n".join(lines)

Compact human-readable summary for the CLI.

def run_scoring( run_dir: str | pathlib.Path, aoi: str | None = None, config_path: str | pathlib.Path | None = None, only: list[str] | None = None, skip: list[str] | None = None, enable: list[str] | None = None, ctx_extras: dict[str, typing.Any] | None = None) -> dict[str, typing.Any]:
 58def run_scoring(
 59    run_dir: str | Path,
 60    aoi: str | None = None,
 61    config_path: str | Path | None = None,
 62    only: list[str] | None = None,
 63    skip: list[str] | None = None,
 64    enable: list[str] | None = None,
 65    ctx_extras: dict[str, Any] | None = None,
 66) -> dict[str, Any]:
 67    """Score one ABM run directory and save ``scorecard.json`` inside it."""
 68    run_dir = Path(run_dir)
 69    if not run_dir.is_dir():
 70        raise NotADirectoryError(f"run dir not found: {run_dir}")
 71
 72    cfg: ScoringConfig = load_config(
 73        config_path=Path(config_path) if config_path else None,
 74        only=only,
 75        skip=skip,
 76        enable=enable,
 77    )
 78    registry = build_registry()
 79    ctx = _build_ctx(run_dir, aoi)
 80    if ctx_extras:
 81        ctx.update(ctx_extras)
 82
 83    composite_scores: dict[str, float] = {}
 84    gates: dict[str, dict[str, Any]] = {}
 85    skipped: dict[str, str] = {}
 86    details: dict[str, dict[str, Any]] = {}
 87
 88    for name, spec in sorted(registry.items()):
 89        if name not in cfg.enabled:
 90            scorer = spec.cls()
 91            reason = (
 92                "manual (AOI-dependent) — activate with --enable or scoring YAML"
 93                if scorer.manual
 94                else "disabled by config"
 95            )
 96            skipped[name] = reason
 97            continue
 98        scorer: Scorer = spec.cls()
 99        try:
100            result = scorer.score(run_dir, ctx)
101        except Exception as e:  # a broken scorer must not sink the run
102            result = ScorerResult.skipped(f"scorer raised: {e}", target=scorer.name)
103        details[name] = _result_to_dict(result)
104        if result.status == "skipped":
105            skipped[name] = result.diagnostics.get("skipped_reason", "unknown")
106            continue
107        if spec.kind == "composite":
108            composite_scores[name] = result.score
109        else:
110            gates[name] = _result_to_dict(result)
111
112    # weighted geometric mean over available dimensions only;
113    # any zero dimension collapses the composite (geometric-mean semantics)
114    composite = 0.0
115    if composite_scores and all(s > 0 for s in composite_scores.values()):
116        total_weight = sum(cfg.weight_of(n) for n in composite_scores)
117        if total_weight > 0:
118            log_sum = sum(
119                cfg.weight_of(n) * math.log(s)
120                for n, s in composite_scores.items()
121            )
122            composite = math.exp(log_sum / total_weight)
123
124    scorecard: dict[str, Any] = {
125        "run_dir": str(run_dir),
126        "aoi": ctx.get("aoi"),
127        "composite": round(composite, 4),
128        "verdict": _verdict(composite),
129        "scores": details,
130        "composite_dimensions": {
131            name: {"score": s, "weight": cfg.weight_of(name)}
132            for name, s in sorted(composite_scores.items())
133        },
134        "gates": gates,
135        "skipped": skipped,
136        "timestamp": datetime.now(timezone.utc).isoformat(),
137    }
138
139    # LLM qualitative judge (draft spec v1.2): appends `verdict_llm` when
140    # the OpenRouter key is present and the call succeeds; silently absent
141    # otherwise (a deterministic fallback stays local to the LLM module).
142    from .llm_scorer import score_with_llm
143
144    llm_result = score_with_llm(scorecard)
145    if "fallback" not in llm_result:
146        scorecard["verdict_llm"] = llm_result
147
148    out_path = run_dir / "scorecard.json"
149    out_path.write_text(json.dumps(scorecard, indent=2, default=str))
150    return scorecard

Score one ABM run directory and save scorecard.json inside it.