mal_core.scoring.scorers
Post-run ABM scorers (canonical home; promoted from the calibration harness).
1"""Post-run ABM scorers (canonical home; promoted from the calibration harness).""" 2from .base import Scorer, ScorerResult 3from .d1_habitat_occupancy import HabitatOccupancyScorer 4from .d2_survival import SurvivalScorer 5from .d3_eip import EIPScorer 6from .d4_stability import StabilityScorer 7from .d5_morans import MoransScorer 8from .d8_coupling import CouplingScorer 9from .d11_aquatic_structure import AquaticStructureScorer 10from .d19_pool_persistence import PoolPersistenceScorer 11from .d20_washout_response import WashoutResponseScorer 12from .d15_persistence import LongHorizonPersistenceScorer 13from .d16_detection_coverage import DetectionCoverageScorer 14from .d21_dispersal_kernel import DispersalKernelScorer 15from .d25_cases_ghana import CasesGhanaScorer 16from .gates import ( 17 DataValidGate, 18 DeterminismGate, 19 HostInputGate, 20 MobilityGate, 21 PerformanceGate, 22 UrbanProductivityGate, 23) 24 25__all__ = [ 26 "Scorer", 27 "ScorerResult", 28 "HabitatOccupancyScorer", 29 "SurvivalScorer", 30 "EIPScorer", 31 "StabilityScorer", 32 "MoransScorer", 33 "CouplingScorer", 34 "AquaticStructureScorer", 35 "PoolPersistenceScorer", 36 "WashoutResponseScorer", 37 "LongHorizonPersistenceScorer", 38 "DetectionCoverageScorer", 39 "DispersalKernelScorer", 40 "CasesGhanaScorer", 41 "DataValidGate", 42 "DeterminismGate", 43 "HostInputGate", 44 "MobilityGate", 45 "PerformanceGate", 46 "UrbanProductivityGate", 47]
62class Scorer(ABC): 63 """One scoring dimension or gate. 64 65 kind: 66 - "composite": biological/external-validation signal, weighted into 67 the composite (weighted geometric mean). 68 - "gate": binary engineering/input invariant, reported separately; 69 never contributes to the composite. 70 """ 71 72 name: str = "" 73 kind: str = "composite" # "composite" | "gate" 74 weight: float = 1.0 75 description: str = "" 76 min_score: float = 0.0 77 hard_floor: float = 0.0 78 manual: bool = False 79 """AOI-dependent scorer (needs per-AOI datasets such as occurrence 80 tables, urban rasters, case series). NEVER runs by default: it must 81 be explicitly activated via ``--enable`` or the scoring YAML, by an 82 operator who knows the AOI has the required data.""" 83 84 @abstractmethod 85 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 86 """Measure this dimension against one ABM run directory. 87 88 Returns a :class:`ScorerResult` whose ``score`` is in [0, 1] 89 (higher is better), whose ``value`` is the raw measured quantity 90 and whose ``target`` describes the expected range. Implementations 91 must return ``ScorerResult.skipped`` rather than fail when the 92 artifacts or datasets they need are missing. 93 """ 94 ...
One scoring dimension or gate.
kind:
- "composite": biological/external-validation signal, weighted into the composite (weighted geometric mean).
- "gate": binary engineering/input invariant, reported separately; never contributes to the composite.
AOI-dependent scorer (needs per-AOI datasets such as occurrence
tables, urban rasters, case series). NEVER runs by default: it must
be explicitly activated via --enable or the scoring YAML, by an
operator who knows the AOI has the required data.
84 @abstractmethod 85 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 86 """Measure this dimension against one ABM run directory. 87 88 Returns a :class:`ScorerResult` whose ``score`` is in [0, 1] 89 (higher is better), whose ``value`` is the raw measured quantity 90 and whose ``target`` describes the expected range. Implementations 91 must return ``ScorerResult.skipped`` rather than fail when the 92 artifacts or datasets they need are missing. 93 """ 94 ...
Measure this dimension against one ABM run directory.
Returns a ScorerResult whose score is in [0, 1]
(higher is better), whose value is the raw measured quantity
and whose target describes the expected range. Implementations
must return ScorerResult.skipped rather than fail when the
artifacts or datasets they need are missing.
26@dataclass 27class ScorerResult: 28 """Outcome of one scorer against one run directory. 29 30 status: 31 - "ok": the scorer measured something real. 32 - "skipped": required artifacts/dependencies are missing. Skipped 33 composite dimensions are excluded from the composite (and from 34 its weight sum) instead of silently scoring 1.0 ("assumed OK") 35 or 0.0. 36 """ 37 38 score: float = 0.0 39 value: float = 0.0 40 target: str = "" 41 diagnostics: dict[str, Any] = field(default_factory=dict) 42 passed: bool = True 43 status: str = "ok" # "ok" | "skipped" 44 45 @classmethod 46 def skipped(cls, reason: str, target: str = "") -> "ScorerResult": 47 """Build a "skipped" result carrying the reason it was skipped. 48 49 The reason is stored in the diagnostics under ``skipped_reason`` 50 so the scorecard can explain why the dimension is missing. 51 """ 52 return cls( 53 score=0.0, 54 value=0.0, 55 target=target, 56 diagnostics={"skipped_reason": reason}, 57 passed=False, 58 status="skipped", 59 )
Outcome of one scorer against one run directory.
status:
- "ok": the scorer measured something real.
- "skipped": required artifacts/dependencies are missing. Skipped composite dimensions are excluded from the composite (and from its weight sum) instead of silently scoring 1.0 ("assumed OK") or 0.0.
45 @classmethod 46 def skipped(cls, reason: str, target: str = "") -> "ScorerResult": 47 """Build a "skipped" result carrying the reason it was skipped. 48 49 The reason is stored in the diagnostics under ``skipped_reason`` 50 so the scorecard can explain why the dimension is missing. 51 """ 52 return cls( 53 score=0.0, 54 value=0.0, 55 target=target, 56 diagnostics={"skipped_reason": reason}, 57 passed=False, 58 status="skipped", 59 )
Build a "skipped" result carrying the reason it was skipped.
The reason is stored in the diagnostics under skipped_reason
so the scorecard can explain why the dimension is missing.
39class HabitatOccupancyScorer(Scorer): 40 """Measures the share of aquatic-capable habitat cells that are 41 actually occupied by adults in the final snapshot. 42 43 This is the field "larval-habitat occupancy" fraction reported by 44 longitudinal surveys (Bogh 2004; Ndenga 2011). A score of 1 means 45 the occupancy falls inside the literature band declared in 46 ``OCC_BAND``; outside it the score falls off as a Gaussian around 47 ``OCC_CENTER``, so 0 (no habitat occupied) scores 0. 48 """ 49 50 name = "D1_habitat_occupancy" 51 kind = "composite" 52 weight = 1.0 53 description = "Occupied habitat cells vs literature 20-70% (Bogh 2004; Ndenga 2011)" 54 min_score = 0.5 55 hard_floor = 0.2 56 57 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 58 """Compute the habitat occupancy fraction and its score. 59 60 Returns the occupied share of habitat cells as the value, or a 61 skipped result when the run has no state snapshot or no habitat 62 cells at all. 63 """ 64 target = "0.20-0.70 of habitat cells occupied" 65 final = find_final_state(run_dir) 66 if final is None: 67 return ScorerResult.skipped("no state files", target) 68 with rasterio.open(final) as ds: 69 density = ds.read(1) 70 habitat = ds.read(2) 71 valid_d = np.isfinite(density) & (density != NODATA) 72 valid_h = np.isfinite(habitat) & (habitat != NODATA) 73 habitat_cells = valid_h & (habitat > 0) 74 n_habitat = int(habitat_cells.sum()) 75 if n_habitat == 0: 76 return ScorerResult.skipped("no habitat cells (band 2 empty)", target) 77 occupied = valid_d & (density > 0) & habitat_cells 78 occupancy = int(occupied.sum()) / n_habitat 79 lo, hi = OCC_BAND 80 if lo <= occupancy <= hi: 81 score = 1.0 82 else: 83 score = max(0.0, math.exp(-((occupancy - OCC_CENTER) / OCC_SIGMA) ** 2)) 84 return ScorerResult( 85 score=round(score, 4), 86 value=float(occupancy), 87 target=target, 88 diagnostics={ 89 "occupied_habitat_cells": int(occupied.sum()), 90 "habitat_cells": n_habitat, 91 "final_file": final.name, 92 }, 93 passed=score >= self.min_score, 94 )
Measures the share of aquatic-capable habitat cells that are actually occupied by adults in the final snapshot.
This is the field "larval-habitat occupancy" fraction reported by
longitudinal surveys (Bogh 2004; Ndenga 2011). A score of 1 means
the occupancy falls inside the literature band declared in
OCC_BAND; outside it the score falls off as a Gaussian around
OCC_CENTER, so 0 (no habitat occupied) scores 0.
57 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 58 """Compute the habitat occupancy fraction and its score. 59 60 Returns the occupied share of habitat cells as the value, or a 61 skipped result when the run has no state snapshot or no habitat 62 cells at all. 63 """ 64 target = "0.20-0.70 of habitat cells occupied" 65 final = find_final_state(run_dir) 66 if final is None: 67 return ScorerResult.skipped("no state files", target) 68 with rasterio.open(final) as ds: 69 density = ds.read(1) 70 habitat = ds.read(2) 71 valid_d = np.isfinite(density) & (density != NODATA) 72 valid_h = np.isfinite(habitat) & (habitat != NODATA) 73 habitat_cells = valid_h & (habitat > 0) 74 n_habitat = int(habitat_cells.sum()) 75 if n_habitat == 0: 76 return ScorerResult.skipped("no habitat cells (band 2 empty)", target) 77 occupied = valid_d & (density > 0) & habitat_cells 78 occupancy = int(occupied.sum()) / n_habitat 79 lo, hi = OCC_BAND 80 if lo <= occupancy <= hi: 81 score = 1.0 82 else: 83 score = max(0.0, math.exp(-((occupancy - OCC_CENTER) / OCC_SIGMA) ** 2)) 84 return ScorerResult( 85 score=round(score, 4), 86 value=float(occupancy), 87 target=target, 88 diagnostics={ 89 "occupied_habitat_cells": int(occupied.sum()), 90 "habitat_cells": n_habitat, 91 "final_file": final.name, 92 }, 93 passed=score >= self.min_score, 94 )
Compute the habitat occupancy fraction and its score.
Returns the occupied share of habitat cells as the value, or a skipped result when the run has no state snapshot or no habitat cells at all.
21class SurvivalScorer(Scorer): 22 """Measures the mean adult lifespan of the simulated population. 23 24 The lifespan is derived from the mean daily adult survival rate of 25 the steady-state half of the run. The score is 1 when the lifespan 26 sits at the centre of the accepted field window and decays as a 27 Gaussian away from it, so a population that dies out too fast 28 scores near 0. 29 """ 30 31 name = "D2_survival" 32 kind = "composite" 33 weight = 4.0 34 description = "Mean adult lifespan vs 8-15 d (Saarman 2019, Midega 2007)" 35 min_score = 0.5 36 hard_floor = 0.2 37 38 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 39 """Compute the mean adult lifespan in days and its score. 40 41 Returns the lifespan as the value, or a skipped result when the 42 cohort log is missing, unreadable or too short to have a 43 steady-state phase. 44 """ 45 cohort_path = find_cohort_file(run_dir) 46 if cohort_path is None: 47 return ScorerResult.skipped( 48 "no cohort file (*_cohort.json)", target="8-15 days" 49 ) 50 try: 51 data = json.loads(cohort_path.read_text()) 52 except (json.JSONDecodeError, OSError) as e: 53 return ScorerResult.skipped(f"cohort unreadable: {e}", target="8-15 days") 54 daily = data.get("daily", []) 55 if len(daily) < 8: 56 return ScorerResult.skipped( 57 f"cohort too short ({len(daily)} days)", target="8-15 days" 58 ) 59 steady = daily[len(daily) // 2 :] 60 rates = [ 61 1.0 - (e.get("n_deaths", 0) / e["n_adults"]) 62 for e in steady 63 if e.get("n_adults", 0) > 0 64 ] 65 if not rates: 66 return ScorerResult.skipped( 67 "no valid adult survival days", target="8-15 days" 68 ) 69 p_d = sum(rates) / len(rates) 70 mean_life = 1.0 / (1.0 - p_d) if p_d < 1.0 else float("inf") 71 score = math.exp(-((mean_life - 11.0) / 4.0) ** 2) 72 return ScorerResult( 73 score=round(score, 4), 74 value=round(mean_life, 2), 75 target="8-15 days", 76 diagnostics={ 77 "p_d_mean": round(p_d, 4), 78 "n_steady_days": len(steady), 79 }, 80 passed=score >= self.min_score, 81 )
Measures the mean adult lifespan of the simulated population.
The lifespan is derived from the mean daily adult survival rate of the steady-state half of the run. The score is 1 when the lifespan sits at the centre of the accepted field window and decays as a Gaussian away from it, so a population that dies out too fast scores near 0.
38 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 39 """Compute the mean adult lifespan in days and its score. 40 41 Returns the lifespan as the value, or a skipped result when the 42 cohort log is missing, unreadable or too short to have a 43 steady-state phase. 44 """ 45 cohort_path = find_cohort_file(run_dir) 46 if cohort_path is None: 47 return ScorerResult.skipped( 48 "no cohort file (*_cohort.json)", target="8-15 days" 49 ) 50 try: 51 data = json.loads(cohort_path.read_text()) 52 except (json.JSONDecodeError, OSError) as e: 53 return ScorerResult.skipped(f"cohort unreadable: {e}", target="8-15 days") 54 daily = data.get("daily", []) 55 if len(daily) < 8: 56 return ScorerResult.skipped( 57 f"cohort too short ({len(daily)} days)", target="8-15 days" 58 ) 59 steady = daily[len(daily) // 2 :] 60 rates = [ 61 1.0 - (e.get("n_deaths", 0) / e["n_adults"]) 62 for e in steady 63 if e.get("n_adults", 0) > 0 64 ] 65 if not rates: 66 return ScorerResult.skipped( 67 "no valid adult survival days", target="8-15 days" 68 ) 69 p_d = sum(rates) / len(rates) 70 mean_life = 1.0 / (1.0 - p_d) if p_d < 1.0 else float("inf") 71 score = math.exp(-((mean_life - 11.0) / 4.0) ** 2) 72 return ScorerResult( 73 score=round(score, 4), 74 value=round(mean_life, 2), 75 target="8-15 days", 76 diagnostics={ 77 "p_d_mean": round(p_d, 4), 78 "n_steady_days": len(steady), 79 }, 80 passed=score >= self.min_score, 81 )
Compute the mean adult lifespan in days and its score.
Returns the lifespan as the value, or a skipped result when the cohort log is missing, unreadable or too short to have a steady-state phase.
23class EIPScorer(Scorer): 24 """Measures how far the infected mosquito cohort has progressed 25 through the extrinsic incubation period. 26 27 The value is the fraction of infected mosquitoes whose EIP has 28 completed at the measurement day. The score is 1 when that fraction 29 falls inside the accepted window and decays as a Gaussian around 30 the window centre otherwise. Runs without transmission dynamics 31 (a constant fraction) are skipped rather than scored. 32 """ 33 34 name = "D3_eip" 35 kind = "composite" 36 weight = 3.0 37 description = "Completed-EIP fraction at day 30 vs 0.20-0.50 (transmission runs)" 38 min_score = 0.3 39 hard_floor = 0.1 40 41 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 42 """Compute the completed-EIP fraction at the measurement day and its score. 43 44 Returns the completed fraction as the value, or a skipped result 45 when the cohort log is missing or carries no EIP dynamics. 46 """ 47 cohort_path = find_cohort_file(run_dir) 48 if cohort_path is None: 49 return ScorerResult.skipped( 50 "no cohort file (*_cohort.json)", target="0.20-0.50" 51 ) 52 try: 53 data = json.loads(cohort_path.read_text()) 54 except (json.JSONDecodeError, OSError) as e: 55 return ScorerResult.skipped(f"cohort unreadable: {e}", target="0.20-0.50") 56 daily = data.get("daily", []) 57 if not daily: 58 return ScorerResult.skipped("empty cohort", target="0.20-0.50") 59 60 eip_values = [e.get("eip_frac", 0.0) for e in daily] 61 if len(set(eip_values)) <= 1: 62 return ScorerResult.skipped( 63 "eip_frac is constant — transmission dynamics not recorded " 64 "(enable --enable-transmission)", 65 target="0.20-0.50", 66 ) 67 68 day30 = next((e for e in daily if e.get("day") == 30), daily[-1]) 69 eip_frac = day30.get("eip_frac", 0.0) 70 if 0.20 <= eip_frac <= 0.50: 71 score = 1.0 72 else: 73 score = math.exp(-((eip_frac - 0.35) / 0.15) ** 2) 74 return ScorerResult( 75 score=round(score, 4), 76 value=round(eip_frac, 4), 77 target="0.20-0.50", 78 diagnostics={"day": day30.get("day"), "n_days": len(daily)}, 79 passed=score >= self.min_score, 80 )
Measures how far the infected mosquito cohort has progressed through the extrinsic incubation period.
The value is the fraction of infected mosquitoes whose EIP has completed at the measurement day. The score is 1 when that fraction falls inside the accepted window and decays as a Gaussian around the window centre otherwise. Runs without transmission dynamics (a constant fraction) are skipped rather than scored.
41 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 42 """Compute the completed-EIP fraction at the measurement day and its score. 43 44 Returns the completed fraction as the value, or a skipped result 45 when the cohort log is missing or carries no EIP dynamics. 46 """ 47 cohort_path = find_cohort_file(run_dir) 48 if cohort_path is None: 49 return ScorerResult.skipped( 50 "no cohort file (*_cohort.json)", target="0.20-0.50" 51 ) 52 try: 53 data = json.loads(cohort_path.read_text()) 54 except (json.JSONDecodeError, OSError) as e: 55 return ScorerResult.skipped(f"cohort unreadable: {e}", target="0.20-0.50") 56 daily = data.get("daily", []) 57 if not daily: 58 return ScorerResult.skipped("empty cohort", target="0.20-0.50") 59 60 eip_values = [e.get("eip_frac", 0.0) for e in daily] 61 if len(set(eip_values)) <= 1: 62 return ScorerResult.skipped( 63 "eip_frac is constant — transmission dynamics not recorded " 64 "(enable --enable-transmission)", 65 target="0.20-0.50", 66 ) 67 68 day30 = next((e for e in daily if e.get("day") == 30), daily[-1]) 69 eip_frac = day30.get("eip_frac", 0.0) 70 if 0.20 <= eip_frac <= 0.50: 71 score = 1.0 72 else: 73 score = math.exp(-((eip_frac - 0.35) / 0.15) ** 2) 74 return ScorerResult( 75 score=round(score, 4), 76 value=round(eip_frac, 4), 77 target="0.20-0.50", 78 diagnostics={"day": day30.get("day"), "n_days": len(daily)}, 79 passed=score >= self.min_score, 80 )
Compute the completed-EIP fraction at the measurement day and its score.
Returns the completed fraction as the value, or a skipped result when the cohort log is missing or carries no EIP dynamics.
21class StabilityScorer(Scorer): 22 """Measures whether the adult population stays stable over the run. 23 24 Two failure modes are scored separately: collapse (the population 25 falling to a small fraction of its day-0 size) and explosion (the 26 population growing many-fold); the score is the mean of the two 27 sub-scores, each of which is 1 inside its accepted range and 28 decays smoothly outside it. 29 """ 30 31 name = "D4_stability" 32 kind = "composite" 33 weight = 2.0 34 description = "Adult population within collapse/explosion bounds" 35 min_score = 0.7 36 hard_floor = 0.3 37 38 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 39 """Compute the adult-population collapse and explosion ratios and their score. 40 41 Returns the collapse ratio as the value, or a skipped result when 42 the cohort log is missing or too short to assess stability. 43 """ 44 cohort_path = find_cohort_file(run_dir) 45 if cohort_path is None: 46 return ScorerResult.skipped( 47 "no cohort file (*_cohort.json)", 48 target="collapse 0.10-0.80, explosion <=5x", 49 ) 50 try: 51 data = json.loads(cohort_path.read_text()) 52 except (json.JSONDecodeError, OSError) as e: 53 return ScorerResult.skipped( 54 f"cohort unreadable: {e}", 55 target="collapse 0.10-0.80, explosion <=5x", 56 ) 57 daily = data.get("daily", []) 58 if len(daily) < 8: 59 return ScorerResult.skipped( 60 f"cohort too short ({len(daily)} days)", 61 target="collapse 0.10-0.80, explosion <=5x", 62 ) 63 series = [e.get("n_alive", 0) for e in daily] 64 n_day0 = series[0] if series[0] > 0 else 1 65 check_days = [min(d, len(series) - 1) for d in (30, 60, 90)] 66 min_alive = min(series[d] for d in check_days) 67 max_alive = max(series) 68 collapse_ratio = min_alive / n_day0 69 explosion_ratio = max_alive / n_day0 70 71 if 0.10 <= collapse_ratio <= 0.80: 72 collapse_ok = 1.0 73 elif collapse_ratio > 0.80: 74 collapse_ok = math.exp(-((collapse_ratio - 0.80) / 0.20) ** 2) 75 else: 76 collapse_ok = math.exp(-((collapse_ratio - 0.10) / 0.10) ** 2) 77 78 if explosion_ratio <= 5.0: 79 explosion_ok = 1.0 80 else: 81 explosion_ok = math.exp(-((explosion_ratio - 5.0) / 5.0) ** 2) 82 83 score = (collapse_ok + explosion_ok) / 2.0 84 return ScorerResult( 85 score=round(score, 4), 86 value=round(collapse_ratio, 4), 87 target="collapse 0.10-0.80, explosion <=5x", 88 diagnostics={ 89 "collapse_ratio": round(collapse_ratio, 4), 90 "explosion_ratio": round(explosion_ratio, 4), 91 "n_day0": n_day0, 92 "n_min": min_alive, 93 "n_max": max_alive, 94 }, 95 passed=score >= self.min_score, 96 )
Measures whether the adult population stays stable over the run.
Two failure modes are scored separately: collapse (the population falling to a small fraction of its day-0 size) and explosion (the population growing many-fold); the score is the mean of the two sub-scores, each of which is 1 inside its accepted range and decays smoothly outside it.
38 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 39 """Compute the adult-population collapse and explosion ratios and their score. 40 41 Returns the collapse ratio as the value, or a skipped result when 42 the cohort log is missing or too short to assess stability. 43 """ 44 cohort_path = find_cohort_file(run_dir) 45 if cohort_path is None: 46 return ScorerResult.skipped( 47 "no cohort file (*_cohort.json)", 48 target="collapse 0.10-0.80, explosion <=5x", 49 ) 50 try: 51 data = json.loads(cohort_path.read_text()) 52 except (json.JSONDecodeError, OSError) as e: 53 return ScorerResult.skipped( 54 f"cohort unreadable: {e}", 55 target="collapse 0.10-0.80, explosion <=5x", 56 ) 57 daily = data.get("daily", []) 58 if len(daily) < 8: 59 return ScorerResult.skipped( 60 f"cohort too short ({len(daily)} days)", 61 target="collapse 0.10-0.80, explosion <=5x", 62 ) 63 series = [e.get("n_alive", 0) for e in daily] 64 n_day0 = series[0] if series[0] > 0 else 1 65 check_days = [min(d, len(series) - 1) for d in (30, 60, 90)] 66 min_alive = min(series[d] for d in check_days) 67 max_alive = max(series) 68 collapse_ratio = min_alive / n_day0 69 explosion_ratio = max_alive / n_day0 70 71 if 0.10 <= collapse_ratio <= 0.80: 72 collapse_ok = 1.0 73 elif collapse_ratio > 0.80: 74 collapse_ok = math.exp(-((collapse_ratio - 0.80) / 0.20) ** 2) 75 else: 76 collapse_ok = math.exp(-((collapse_ratio - 0.10) / 0.10) ** 2) 77 78 if explosion_ratio <= 5.0: 79 explosion_ok = 1.0 80 else: 81 explosion_ok = math.exp(-((explosion_ratio - 5.0) / 5.0) ** 2) 82 83 score = (collapse_ok + explosion_ok) / 2.0 84 return ScorerResult( 85 score=round(score, 4), 86 value=round(collapse_ratio, 4), 87 target="collapse 0.10-0.80, explosion <=5x", 88 diagnostics={ 89 "collapse_ratio": round(collapse_ratio, 4), 90 "explosion_ratio": round(explosion_ratio, 4), 91 "n_day0": n_day0, 92 "n_min": min_alive, 93 "n_max": max_alive, 94 }, 95 passed=score >= self.min_score, 96 )
Compute the adult-population collapse and explosion ratios and their score.
Returns the collapse ratio as the value, or a skipped result when the cohort log is missing or too short to assess stability.
59class MoransScorer(Scorer): 60 """Measures the spatial autocorrelation of the adult population. 61 62 The value is Moran's I computed on the occupied cells only, so it 63 describes how clustered the adult distribution is rather than the 64 mostly-empty background. The score is 1 when the index falls 65 inside the accepted band — clustered but not pathologically so — 66 and decays as a Gaussian outside it; a spatially random 67 configuration scores near 0. 68 """ 69 70 name = "D5_morans" 71 kind = "composite" 72 weight = 1.0 73 description = "Spatial autocorrelation of active habitat (Moran's I)" 74 min_score = 0.5 75 hard_floor = 0.2 76 77 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 78 """Compute Moran's I of the occupied cells and its score. 79 80 Returns the index as the value, or a skipped result when there 81 is no state snapshot or too few occupied cells for a spatial 82 statistic. 83 """ 84 final = find_final_state(run_dir) 85 if final is None: 86 return ScorerResult.skipped("no state files", target="0.20-0.85") 87 with rasterio.open(final) as ds: 88 band = ds.read(1) # adult_occupancy density 89 active = np.isfinite(band) & (band != NODATA) & (band > 0) 90 if int(active.sum()) < 9: 91 return ScorerResult.skipped( 92 f"too few active cells ({int(active.sum())}) for spatial statistics", 93 target="0.20-0.85", 94 ) 95 i_value = morans_i_active(band) 96 if 0.20 <= i_value <= 0.85: 97 score = 1.0 98 else: 99 score = max(0.0, math.exp(-((i_value - 0.5) / 0.25) ** 2)) 100 return ScorerResult( 101 score=round(score, 4), 102 value=round(i_value, 4), 103 target="0.20-0.85", 104 diagnostics={"n_active_pixels": int(active.sum()), "final_file": final.name}, 105 passed=score >= self.min_score, 106 )
Measures the spatial autocorrelation of the adult population.
The value is Moran's I computed on the occupied cells only, so it describes how clustered the adult distribution is rather than the mostly-empty background. The score is 1 when the index falls inside the accepted band — clustered but not pathologically so — and decays as a Gaussian outside it; a spatially random configuration scores near 0.
77 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 78 """Compute Moran's I of the occupied cells and its score. 79 80 Returns the index as the value, or a skipped result when there 81 is no state snapshot or too few occupied cells for a spatial 82 statistic. 83 """ 84 final = find_final_state(run_dir) 85 if final is None: 86 return ScorerResult.skipped("no state files", target="0.20-0.85") 87 with rasterio.open(final) as ds: 88 band = ds.read(1) # adult_occupancy density 89 active = np.isfinite(band) & (band != NODATA) & (band > 0) 90 if int(active.sum()) < 9: 91 return ScorerResult.skipped( 92 f"too few active cells ({int(active.sum())}) for spatial statistics", 93 target="0.20-0.85", 94 ) 95 i_value = morans_i_active(band) 96 if 0.20 <= i_value <= 0.85: 97 score = 1.0 98 else: 99 score = max(0.0, math.exp(-((i_value - 0.5) / 0.25) ** 2)) 100 return ScorerResult( 101 score=round(score, 4), 102 value=round(i_value, 4), 103 target="0.20-0.85", 104 diagnostics={"n_active_pixels": int(active.sum()), "final_file": final.name}, 105 passed=score >= self.min_score, 106 )
Compute Moran's I of the occupied cells and its score.
Returns the index as the value, or a skipped result when there is no state snapshot or too few occupied cells for a spatial statistic.
21class CouplingScorer(Scorer): 22 """Measures how well the adult density follows the habitat field. 23 24 The value is the Pearson correlation between adult density and 25 host-seeking pressure over the occupied cells of the final 26 snapshot. A score of 1 means a perfect positive coupling, so the 27 score is the correlation rescaled against the target correlation 28 declared in ``score()``; a population that ignores the habitat 29 field scores 0. 30 """ 31 32 name = "D8_coupling" 33 kind = "composite" 34 weight = 2.0 35 description = "Correlation density vs habitat pressure on active cells" 36 min_score = 0.4 37 hard_floor = 0.1 38 39 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 40 """Compute the density-versus-habitat correlation and its score. 41 42 Returns the correlation coefficient as the value, or a skipped 43 result when there is no state snapshot or too few occupied 44 cells to correlate. 45 """ 46 final = find_final_state(run_dir) 47 if final is None: 48 return ScorerResult.skipped("no state files", target=">=0.30 r") 49 with rasterio.open(final) as ds: 50 b1 = ds.read(1) 51 b2 = ds.read(2) 52 mask = ( 53 np.isfinite(b1) 54 & np.isfinite(b2) 55 & (b1 != NODATA) 56 & (b2 != NODATA) 57 & (b1 > 0) 58 ) 59 if int(mask.sum()) < 2: 60 return ScorerResult.skipped( 61 "too few active pixels", target=">=0.30 r" 62 ) 63 d = b1[mask].astype(np.float64) 64 s = b2[mask].astype(np.float64) 65 if d.std() == 0 or s.std() == 0: 66 r = 0.0 67 else: 68 r = float(np.corrcoef(d, s)[0, 1]) 69 if np.isnan(r): 70 r = 0.0 71 score = max(0.0, min(1.0, r / 0.50)) 72 return ScorerResult( 73 score=round(score, 4), 74 value=round(r, 4), 75 target=">=0.30 r", 76 diagnostics={"n_active": int(mask.sum())}, 77 passed=r >= 0.30, 78 )
Measures how well the adult density follows the habitat field.
The value is the Pearson correlation between adult density and
host-seeking pressure over the occupied cells of the final
snapshot. A score of 1 means a perfect positive coupling, so the
score is the correlation rescaled against the target correlation
declared in score(); a population that ignores the habitat
field scores 0.
39 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 40 """Compute the density-versus-habitat correlation and its score. 41 42 Returns the correlation coefficient as the value, or a skipped 43 result when there is no state snapshot or too few occupied 44 cells to correlate. 45 """ 46 final = find_final_state(run_dir) 47 if final is None: 48 return ScorerResult.skipped("no state files", target=">=0.30 r") 49 with rasterio.open(final) as ds: 50 b1 = ds.read(1) 51 b2 = ds.read(2) 52 mask = ( 53 np.isfinite(b1) 54 & np.isfinite(b2) 55 & (b1 != NODATA) 56 & (b2 != NODATA) 57 & (b1 > 0) 58 ) 59 if int(mask.sum()) < 2: 60 return ScorerResult.skipped( 61 "too few active pixels", target=">=0.30 r" 62 ) 63 d = b1[mask].astype(np.float64) 64 s = b2[mask].astype(np.float64) 65 if d.std() == 0 or s.std() == 0: 66 r = 0.0 67 else: 68 r = float(np.corrcoef(d, s)[0, 1]) 69 if np.isnan(r): 70 r = 0.0 71 score = max(0.0, min(1.0, r / 0.50)) 72 return ScorerResult( 73 score=round(score, 4), 74 value=round(r, 4), 75 target=">=0.30 r", 76 diagnostics={"n_active": int(mask.sum())}, 77 passed=r >= 0.30, 78 )
Compute the density-versus-habitat correlation and its score.
Returns the correlation coefficient as the value, or a skipped result when there is no state snapshot or too few occupied cells to correlate.
51class AquaticStructureScorer(Scorer): 52 """Measures the stage composition of the aquatic (immature) population. 53 54 The value is the share of the aquatic population that is in the 55 larval stage, as expected from stage-duration data (Bayoh & 56 Lindsay 2003); the pupal share is scored alongside it. Each 57 sub-score is 1 inside its accepted band and decays smoothly 58 outside, and the reported score is the mean of the two. 59 """ 60 61 name = "D11_aquatic_structure" 62 kind = "composite" 63 weight = 1.0 64 description = "Larval/pupal share of aquatic population vs stage-duration data (Bayoh 2003)" 65 min_score = 0.7 66 hard_floor = 0.3 67 68 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 69 """Compute the larval and pupal shares of the aquatic population and their score. 70 71 Returns the mean larval share as the value, or a skipped result 72 when the run has no aquatic JSONs or they carry no stage 73 breakdown. 74 """ 75 target = f"larva {LARVA_BAND[0]}-{LARVA_BAND[1]}, pupa {PUPA_BAND[0]}-{PUPA_BAND[1]}" 76 daily = find_aquatic_day_files(run_dir) 77 sources = daily[-30:] if daily else [] 78 final = find_final_aquatic(run_dir) 79 if not sources and final is not None: 80 sources = [final] 81 if not sources: 82 return ScorerResult.skipped( 83 "no aquatic JSONs (*_dayNNN_aquatic.json / *_aquatic.json)", 84 target=target, 85 ) 86 larva_fracs: list[float] = [] 87 pupa_fracs: list[float] = [] 88 for path in sources: 89 try: 90 data = json.loads(path.read_text()) 91 except (json.JSONDecodeError, OSError): 92 continue 93 pair = _structure_from(data) 94 if pair is not None: 95 larva_fracs.append(pair[0]) 96 pupa_fracs.append(pair[1]) 97 if not larva_fracs: 98 return ScorerResult.skipped( 99 "aquatic JSONs lack by_stage/total_aquatic", 100 target=target, 101 ) 102 larva_frac = sum(larva_fracs) / len(larva_fracs) 103 pupa_frac = sum(pupa_fracs) / len(pupa_fracs) 104 105 # stage-duration expectation (Bayoh & Lindsay 2003); bands widened 106 # for temperature-driven ratio drift (LARVA_BAND / PUPA_BAND) 107 lo, hi = LARVA_BAND 108 if lo <= larva_frac <= hi: 109 larva_ok = 1.0 110 elif larva_frac < lo: 111 larva_ok = max(0.0, larva_frac / lo) 112 else: 113 larva_ok = max(0.0, (1.0 - larva_frac) / (1.0 - hi)) 114 115 plo, phi = PUPA_BAND 116 if plo <= pupa_frac <= phi: 117 pupa_ok = 1.0 118 else: 119 edge = plo if pupa_frac < plo else phi 120 pupa_ok = max(0.0, math.exp(-((pupa_frac - edge) / 0.08) ** 2)) 121 122 score = (larva_ok + pupa_ok) / 2.0 123 return ScorerResult( 124 score=round(score, 4), 125 value=round(larva_frac, 4), 126 target=target, 127 diagnostics={ 128 "larva_frac": round(larva_frac, 4), 129 "pupa_frac": round(pupa_frac, 4), 130 "n_files": len(larva_fracs), 131 }, 132 passed=score >= self.min_score, 133 )
Measures the stage composition of the aquatic (immature) population.
The value is the share of the aquatic population that is in the larval stage, as expected from stage-duration data (Bayoh & Lindsay 2003); the pupal share is scored alongside it. Each sub-score is 1 inside its accepted band and decays smoothly outside, and the reported score is the mean of the two.
68 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 69 """Compute the larval and pupal shares of the aquatic population and their score. 70 71 Returns the mean larval share as the value, or a skipped result 72 when the run has no aquatic JSONs or they carry no stage 73 breakdown. 74 """ 75 target = f"larva {LARVA_BAND[0]}-{LARVA_BAND[1]}, pupa {PUPA_BAND[0]}-{PUPA_BAND[1]}" 76 daily = find_aquatic_day_files(run_dir) 77 sources = daily[-30:] if daily else [] 78 final = find_final_aquatic(run_dir) 79 if not sources and final is not None: 80 sources = [final] 81 if not sources: 82 return ScorerResult.skipped( 83 "no aquatic JSONs (*_dayNNN_aquatic.json / *_aquatic.json)", 84 target=target, 85 ) 86 larva_fracs: list[float] = [] 87 pupa_fracs: list[float] = [] 88 for path in sources: 89 try: 90 data = json.loads(path.read_text()) 91 except (json.JSONDecodeError, OSError): 92 continue 93 pair = _structure_from(data) 94 if pair is not None: 95 larva_fracs.append(pair[0]) 96 pupa_fracs.append(pair[1]) 97 if not larva_fracs: 98 return ScorerResult.skipped( 99 "aquatic JSONs lack by_stage/total_aquatic", 100 target=target, 101 ) 102 larva_frac = sum(larva_fracs) / len(larva_fracs) 103 pupa_frac = sum(pupa_fracs) / len(pupa_fracs) 104 105 # stage-duration expectation (Bayoh & Lindsay 2003); bands widened 106 # for temperature-driven ratio drift (LARVA_BAND / PUPA_BAND) 107 lo, hi = LARVA_BAND 108 if lo <= larva_frac <= hi: 109 larva_ok = 1.0 110 elif larva_frac < lo: 111 larva_ok = max(0.0, larva_frac / lo) 112 else: 113 larva_ok = max(0.0, (1.0 - larva_frac) / (1.0 - hi)) 114 115 plo, phi = PUPA_BAND 116 if plo <= pupa_frac <= phi: 117 pupa_ok = 1.0 118 else: 119 edge = plo if pupa_frac < plo else phi 120 pupa_ok = max(0.0, math.exp(-((pupa_frac - edge) / 0.08) ** 2)) 121 122 score = (larva_ok + pupa_ok) / 2.0 123 return ScorerResult( 124 score=round(score, 4), 125 value=round(larva_frac, 4), 126 target=target, 127 diagnostics={ 128 "larva_frac": round(larva_frac, 4), 129 "pupa_frac": round(pupa_frac, 4), 130 "n_files": len(larva_fracs), 131 }, 132 passed=score >= self.min_score, 133 )
Compute the larval and pupal shares of the aquatic population and their score.
Returns the mean larval share as the value, or a skipped result when the run has no aquatic JSONs or they carry no stage breakdown.
40class PoolPersistenceScorer(Scorer): 41 """D19: pluvial persistence and drying-memory dynamics (composite).""" 42 43 name = "D19_pool_persistence" 44 kind = "composite" 45 weight = 1.0 46 description = ( 47 "Proxy habitat: 30mm pulse keeps z active >=4 days; z decays " 48 "thereafter; persistent-floor accuracy stays > 0 in drought" 49 ) 50 min_score = 0.70 51 52 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 53 """Score habitat persistence with the shared pluvial recursion. 54 55 Scenario: 56 Day 0-2: rain pulses (recharge; the activation pulse) 57 Day 3-12: 0 mm (drying memory) 58 59 Checks: 60 1. z stays above the activation floor for several days 61 2. z falls below the floor inside 3 * pluvial.dry_memory_days 62 3. monotone decay through the no-rain phase 63 4. persistent floor: species accuracy at z = 0 stays positive 64 (human dry-season supply) and short of the z = 1 value 65 """ 66 def step(z: float, rain: float, days: float = 1.0) -> float: 67 """One scalar pluvial step — the contract recursion, written 68 in-place here because the scorer exercises a single cell (the 69 array form lives in habitat.availability with identical math).""" 70 z_dry = z * math.exp(-days / _PLUVIAL_DRY_MEMORY_DAYS) 71 fill = 1.0 - math.exp(-max(0.0, rain) / _PLUVIAL_RAIN_SCALE_MM) 72 return min(1.0, max(0.0, z_dry + (1.0 - z_dry) * fill)) 73 74 z = 0.0 75 z_series: list[float] = [] 76 active_days = 0 77 dry_day = -1 78 79 for _ in range(3): 80 z = step(z, 30.0) 81 z_series.append(z) 82 if z >= 0.05: 83 active_days += 1 84 85 for d in range(10): 86 z = step(z, 0.0) 87 z_series.append(z) 88 if z >= 0.05: 89 active_days += 1 90 if z < 0.05 and dry_day < 0: 91 dry_day = d + 3 92 93 diagnostics: dict[str, Any] = { 94 "active_days": active_days, 95 "dry_day": dry_day, 96 "z_series": [round(v, 3) for v in z_series], 97 "rain_scale_mm": _PLUVIAL_RAIN_SCALE_MM, 98 "dry_memory_days": _PLUVIAL_DRY_MEMORY_DAYS, 99 } 100 101 # 1. Persistence: a single 30 mm pulse is enough for >= 4 days. 102 persistence_ok = active_days >= 4 103 # 2. Drying: z falls under the floor within the memory scale. 104 dries_out = dry_day >= 0 and dry_day <= int(3 * _PLUVIAL_DRY_MEMORY_DAYS) 105 # 3. Monotone decay after the last recharge. 106 decay_levels = z_series[3:] 107 monotone = all( 108 decay_levels[i + 1] <= decay_levels[i] + 1e-6 109 for i in range(len(decay_levels) - 1) 110 ) 111 # 4. Persistent floor (the user-fixed urban premise: at z = 0 the 112 # built/wetland/JRC columns keep a positive supply). 113 h_map = { 114 g: float(v) 115 for g, v in zip(CONFIG["habitat_types"]["types"], _MIXED_CELL_H) 116 } 117 w_map = { 118 g: float(v) 119 for g, v in zip(CONFIG["habitat_types"]["types"], _MIXED_CELL_W) 120 } 121 floor = float(species_accuracy(h_map, 0.0, w_map)) 122 ceiling = float(species_accuracy(h_map, 1.0, w_map)) 123 floor_ok = ( 124 math.isfinite(floor) and 0.0 < floor < ceiling <= 1.0 125 ) 126 127 score = 0.0 128 if persistence_ok: 129 score += 0.3 130 if dries_out: 131 score += 0.2 132 if monotone: 133 score += 0.2 134 if floor_ok: 135 score += 0.3 136 137 return ScorerResult( 138 score=round(score, 4), 139 value=float(active_days), 140 target=( 141 "active >= 4 days; dries inside 3*DRY_MEMORY; monotone " 142 "decay; persistent floor in (0, ceiling]" 143 ), 144 diagnostics=diagnostics, 145 passed=score >= 0.70, 146 )
D19: pluvial persistence and drying-memory dynamics (composite).
52 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 53 """Score habitat persistence with the shared pluvial recursion. 54 55 Scenario: 56 Day 0-2: rain pulses (recharge; the activation pulse) 57 Day 3-12: 0 mm (drying memory) 58 59 Checks: 60 1. z stays above the activation floor for several days 61 2. z falls below the floor inside 3 * pluvial.dry_memory_days 62 3. monotone decay through the no-rain phase 63 4. persistent floor: species accuracy at z = 0 stays positive 64 (human dry-season supply) and short of the z = 1 value 65 """ 66 def step(z: float, rain: float, days: float = 1.0) -> float: 67 """One scalar pluvial step — the contract recursion, written 68 in-place here because the scorer exercises a single cell (the 69 array form lives in habitat.availability with identical math).""" 70 z_dry = z * math.exp(-days / _PLUVIAL_DRY_MEMORY_DAYS) 71 fill = 1.0 - math.exp(-max(0.0, rain) / _PLUVIAL_RAIN_SCALE_MM) 72 return min(1.0, max(0.0, z_dry + (1.0 - z_dry) * fill)) 73 74 z = 0.0 75 z_series: list[float] = [] 76 active_days = 0 77 dry_day = -1 78 79 for _ in range(3): 80 z = step(z, 30.0) 81 z_series.append(z) 82 if z >= 0.05: 83 active_days += 1 84 85 for d in range(10): 86 z = step(z, 0.0) 87 z_series.append(z) 88 if z >= 0.05: 89 active_days += 1 90 if z < 0.05 and dry_day < 0: 91 dry_day = d + 3 92 93 diagnostics: dict[str, Any] = { 94 "active_days": active_days, 95 "dry_day": dry_day, 96 "z_series": [round(v, 3) for v in z_series], 97 "rain_scale_mm": _PLUVIAL_RAIN_SCALE_MM, 98 "dry_memory_days": _PLUVIAL_DRY_MEMORY_DAYS, 99 } 100 101 # 1. Persistence: a single 30 mm pulse is enough for >= 4 days. 102 persistence_ok = active_days >= 4 103 # 2. Drying: z falls under the floor within the memory scale. 104 dries_out = dry_day >= 0 and dry_day <= int(3 * _PLUVIAL_DRY_MEMORY_DAYS) 105 # 3. Monotone decay after the last recharge. 106 decay_levels = z_series[3:] 107 monotone = all( 108 decay_levels[i + 1] <= decay_levels[i] + 1e-6 109 for i in range(len(decay_levels) - 1) 110 ) 111 # 4. Persistent floor (the user-fixed urban premise: at z = 0 the 112 # built/wetland/JRC columns keep a positive supply). 113 h_map = { 114 g: float(v) 115 for g, v in zip(CONFIG["habitat_types"]["types"], _MIXED_CELL_H) 116 } 117 w_map = { 118 g: float(v) 119 for g, v in zip(CONFIG["habitat_types"]["types"], _MIXED_CELL_W) 120 } 121 floor = float(species_accuracy(h_map, 0.0, w_map)) 122 ceiling = float(species_accuracy(h_map, 1.0, w_map)) 123 floor_ok = ( 124 math.isfinite(floor) and 0.0 < floor < ceiling <= 1.0 125 ) 126 127 score = 0.0 128 if persistence_ok: 129 score += 0.3 130 if dries_out: 131 score += 0.2 132 if monotone: 133 score += 0.2 134 if floor_ok: 135 score += 0.3 136 137 return ScorerResult( 138 score=round(score, 4), 139 value=float(active_days), 140 target=( 141 "active >= 4 days; dries inside 3*DRY_MEMORY; monotone " 142 "decay; persistent floor in (0, ceiling]" 143 ), 144 diagnostics=diagnostics, 145 passed=score >= 0.70, 146 )
Score habitat persistence with the shared pluvial recursion.
Scenario: Day 0-2: rain pulses (recharge; the activation pulse) Day 3-12: 0 mm (drying memory)
Checks:
- z stays above the activation floor for several days
- z falls below the floor inside 3 * pluvial.dry_memory_days
- monotone decay through the no-rain phase
- persistent floor: species accuracy at z = 0 stays positive (human dry-season supply) and short of the z = 1 value
29class WashoutResponseScorer(Scorer): 30 """D20: washout response to heavy rain (weighted composite).""" 31 32 name = "D20_washout_response" 33 kind = "composite" 34 weight = 1.0 35 description = ( 36 f"Heavy rain washes out cohorts: 50mm -> >=0.15 (cap " 37 f"{_WASH_MAX} at 80mm); flat below " 38 f"{_WASH_MM}mm" 39 ) 40 min_score = 0.70 41 42 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 43 """Score washout response with the aquatic-stress contract.""" 44 diagnostics: dict[str, Any] = {} 45 46 # 1. 50 mm -> real washout. 47 frac_50 = washout_fraction(50.0) 48 diagnostics["frac_50mm"] = round(frac_50, 4) 49 test1_ok = frac_50 >= 0.15 50 51 # 2. 30 mm -> no washout (below threshold). 52 frac_30 = washout_fraction(30.0) 53 diagnostics["frac_30mm"] = round(frac_30, 4) 54 test2_ok = frac_30 == 0.0 55 56 # 3. 80 mm -> cap. 57 frac_80 = washout_fraction(80.0) 58 diagnostics["frac_80mm"] = round(frac_80, 4) 59 test3_ok = abs(frac_80 - _WASH_MAX) < 0.001 60 61 # 4. 40 mm -> exactly at threshold (~0). 62 frac_40 = washout_fraction(40.0) 63 diagnostics["frac_40mm"] = round(frac_40, 4) 64 test4_ok = frac_40 <= 0.01 65 66 score = 0.0 67 if test1_ok: 68 score += 0.3 69 if test2_ok: 70 score += 0.3 71 if test3_ok: 72 score += 0.2 73 if test4_ok: 74 score += 0.2 75 76 return ScorerResult( 77 score=round(score, 4), 78 value=round(frac_50, 4), 79 target=( 80 f"washout at 50mm >= 0.15; none at 30mm; cap at 80mm = " 81 f"{_WASH_MAX}" 82 ), 83 diagnostics=diagnostics, 84 passed=score >= 0.70, 85 )
D20: washout response to heavy rain (weighted composite).
42 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 43 """Score washout response with the aquatic-stress contract.""" 44 diagnostics: dict[str, Any] = {} 45 46 # 1. 50 mm -> real washout. 47 frac_50 = washout_fraction(50.0) 48 diagnostics["frac_50mm"] = round(frac_50, 4) 49 test1_ok = frac_50 >= 0.15 50 51 # 2. 30 mm -> no washout (below threshold). 52 frac_30 = washout_fraction(30.0) 53 diagnostics["frac_30mm"] = round(frac_30, 4) 54 test2_ok = frac_30 == 0.0 55 56 # 3. 80 mm -> cap. 57 frac_80 = washout_fraction(80.0) 58 diagnostics["frac_80mm"] = round(frac_80, 4) 59 test3_ok = abs(frac_80 - _WASH_MAX) < 0.001 60 61 # 4. 40 mm -> exactly at threshold (~0). 62 frac_40 = washout_fraction(40.0) 63 diagnostics["frac_40mm"] = round(frac_40, 4) 64 test4_ok = frac_40 <= 0.01 65 66 score = 0.0 67 if test1_ok: 68 score += 0.3 69 if test2_ok: 70 score += 0.3 71 if test3_ok: 72 score += 0.2 73 if test4_ok: 74 score += 0.2 75 76 return ScorerResult( 77 score=round(score, 4), 78 value=round(frac_50, 4), 79 target=( 80 f"washout at 50mm >= 0.15; none at 30mm; cap at 80mm = " 81 f"{_WASH_MAX}" 82 ), 83 diagnostics=diagnostics, 84 passed=score >= 0.70, 85 )
Score washout response with the aquatic-stress contract.
66class LongHorizonPersistenceScorer(Scorer): 67 """Measures whether the population survives over the whole run. 68 69 Three sub-scores are combined with a geometric mean: the population 70 at the last day relative to its peak, the absence of any day with a 71 dead aquatic population, and the expansion of the occupied area 72 relative to the horizon day. Each sub-score is 1 when the 73 population is healthy and falls towards 0 as it deteriorates, so a 74 run that dies out late scores 0. 75 """ 76 77 name = "D15_persistence" 78 kind = "composite" 79 weight = 3.0 80 description = "Population survives the horizon: no extinction, 30% of peak, expansion" 81 min_score = 0.7 82 hard_floor = 0.4 83 84 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 85 """Compute the persistence sub-scores and their geometric mean. 86 87 Returns the final aquatic population size as the value, or a 88 skipped result when the run has no aquatic day logs or is too 89 short to have a persistence horizon. 90 """ 91 pops = _load_aquatic_pop(run_dir) 92 if not pops: 93 return ScorerResult.skipped( 94 "no aquatic day JSONs", 95 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 96 ) 97 last_day = max(pops) 98 if last_day < 30: 99 return ScorerResult.skipped( 100 f"run too short for persistence check (last day {last_day} < 30)", 101 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 102 ) 103 max_pop = max(pops.values()) 104 pop_last = pops[last_day] 105 106 survival = min(pop_last / max_pop / 0.30, 1.0) if max_pop > 0 else 0.0 107 108 days_30_plus = [d for d in pops if d >= 30] 109 no_ext = 1.0 if days_30_plus and all(pops[d] > 0 for d in days_30_plus) else 0.0 110 111 # expansion: occupied cells last vs day 30 112 expansion = 0.0 113 cogs = find_state_files(run_dir) 114 cog_by_day: dict[int, Path] = {} 115 for c in cogs: 116 m = re.search(r"_day(\d+)\.tif$", c.name) 117 if m: 118 cog_by_day[int(m.group(1))] = c 119 base_day = min(d for d in cog_by_day if d >= 30) if any( 120 d >= 30 for d in cog_by_day 121 ) else None 122 if base_day is not None and last_day in cog_by_day: 123 cells_base = _count_occupied(cog_by_day[base_day]) 124 cells_last = _count_occupied(cog_by_day[last_day]) 125 if cells_base and cells_last is not None and cells_base > 0: 126 expansion = min((cells_last / cells_base) / 0.20, 1.0) 127 if expansion == 0.0: 128 # fallback: top_patches counts from the aquatic JSONs 129 def _patches_from(day: int) -> int: 130 """Number of top_patches listed in the aquatic JSON of that day (0 if absent).""" 131 for p in find_aquatic_day_files(run_dir): 132 if _parse_day(p) == day: 133 try: 134 return len(json.loads(p.read_text()).get("top_patches", [])) 135 except (json.JSONDecodeError, OSError): 136 return 0 137 return 0 138 139 p_base = _patches_from(base_day) if base_day is not None else 0 140 p_last = _patches_from(last_day) 141 if p_base > 0: 142 expansion = min((p_last / p_base) / 0.20, 1.0) 143 144 subs = [survival, no_ext, expansion] 145 geo = ( 146 math.prod(subs) ** (1.0 / len(subs)) if all(s > 0 for s in subs) else 0.0 147 ) 148 return ScorerResult( 149 score=round(geo, 4), 150 value=float(pop_last), 151 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 152 diagnostics={ 153 "sub_scores": {k: round(v, 4) for k, v in zip( 154 ("survival", "no_extinction", "expansion"), subs)}, 155 "last_day": last_day, 156 "pop_last": pop_last, 157 "pop_peak": max_pop, 158 "days_sampled": len(pops), 159 }, 160 passed=geo >= self.min_score, 161 )
Measures whether the population survives over the whole run.
Three sub-scores are combined with a geometric mean: the population at the last day relative to its peak, the absence of any day with a dead aquatic population, and the expansion of the occupied area relative to the horizon day. Each sub-score is 1 when the population is healthy and falls towards 0 as it deteriorates, so a run that dies out late scores 0.
84 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 85 """Compute the persistence sub-scores and their geometric mean. 86 87 Returns the final aquatic population size as the value, or a 88 skipped result when the run has no aquatic day logs or is too 89 short to have a persistence horizon. 90 """ 91 pops = _load_aquatic_pop(run_dir) 92 if not pops: 93 return ScorerResult.skipped( 94 "no aquatic day JSONs", 95 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 96 ) 97 last_day = max(pops) 98 if last_day < 30: 99 return ScorerResult.skipped( 100 f"run too short for persistence check (last day {last_day} < 30)", 101 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 102 ) 103 max_pop = max(pops.values()) 104 pop_last = pops[last_day] 105 106 survival = min(pop_last / max_pop / 0.30, 1.0) if max_pop > 0 else 0.0 107 108 days_30_plus = [d for d in pops if d >= 30] 109 no_ext = 1.0 if days_30_plus and all(pops[d] > 0 for d in days_30_plus) else 0.0 110 111 # expansion: occupied cells last vs day 30 112 expansion = 0.0 113 cogs = find_state_files(run_dir) 114 cog_by_day: dict[int, Path] = {} 115 for c in cogs: 116 m = re.search(r"_day(\d+)\.tif$", c.name) 117 if m: 118 cog_by_day[int(m.group(1))] = c 119 base_day = min(d for d in cog_by_day if d >= 30) if any( 120 d >= 30 for d in cog_by_day 121 ) else None 122 if base_day is not None and last_day in cog_by_day: 123 cells_base = _count_occupied(cog_by_day[base_day]) 124 cells_last = _count_occupied(cog_by_day[last_day]) 125 if cells_base and cells_last is not None and cells_base > 0: 126 expansion = min((cells_last / cells_base) / 0.20, 1.0) 127 if expansion == 0.0: 128 # fallback: top_patches counts from the aquatic JSONs 129 def _patches_from(day: int) -> int: 130 """Number of top_patches listed in the aquatic JSON of that day (0 if absent).""" 131 for p in find_aquatic_day_files(run_dir): 132 if _parse_day(p) == day: 133 try: 134 return len(json.loads(p.read_text()).get("top_patches", [])) 135 except (json.JSONDecodeError, OSError): 136 return 0 137 return 0 138 139 p_base = _patches_from(base_day) if base_day is not None else 0 140 p_last = _patches_from(last_day) 141 if p_base > 0: 142 expansion = min((p_last / p_base) / 0.20, 1.0) 143 144 subs = [survival, no_ext, expansion] 145 geo = ( 146 math.prod(subs) ** (1.0 / len(subs)) if all(s > 0 for s in subs) else 0.0 147 ) 148 return ScorerResult( 149 score=round(geo, 4), 150 value=float(pop_last), 151 target="pop(last) >=30% peak, no extinction, 20% cells vs day30", 152 diagnostics={ 153 "sub_scores": {k: round(v, 4) for k, v in zip( 154 ("survival", "no_extinction", "expansion"), subs)}, 155 "last_day": last_day, 156 "pop_last": pop_last, 157 "pop_peak": max_pop, 158 "days_sampled": len(pops), 159 }, 160 passed=geo >= self.min_score, 161 )
Compute the persistence sub-scores and their geometric mean.
Returns the final aquatic population size as the value, or a skipped result when the run has no aquatic day logs or is too short to have a persistence horizon.
54class DetectionCoverageScorer(Scorer): 55 """Measures the share of real detection points the simulated 56 population reaches. 57 58 The run is expected to come from ``malariasim validate-detections``, 59 which seeds mosquitoes at the AOI's real detection points; a spot 60 counts as covered when the final snapshot holds at least one 61 occupied cell within the detection radius. The value is the covered 62 fraction of spots and the score is that fraction rescaled against 63 the coverage target, so a population that never establishes scores 64 0. 65 """ 66 67 name = "D16_detection_coverage" 68 kind = "composite" 69 weight = 4.0 70 description = "Fraction of detection spots reached by a seeded 1-year run (validate-detections)" 71 min_score = 0.5 72 hard_floor = 0.2 73 manual = True # AOI-dependent: needs the AOI's occurrence dataset 74 75 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 76 """Compute the detection-point coverage and its score. 77 78 Returns the covered fraction of detection spots as the value. 79 The result is skipped when the AOI, its occurrence table or the 80 grid transform cannot be resolved; a population with no 81 occupied cell at all scores 0 and is flagged as extinct. 82 """ 83 target = f"coverage >= {COVERAGE_TARGET} @ r={RADIUS_KM_DEFAULT}km" 84 aoi = require_aoi(ctx) 85 if not aoi: 86 return ScorerResult.skipped( 87 "requires explicit --aoi (never inferred)", target 88 ) 89 occ = ctx.get("occurrence_path") or resolve_aoi_artifact( 90 aoi, OCCURRENCE_CANDIDATES 91 ) 92 if occ is None or not Path(occ).exists(): 93 return ScorerResult.skipped( 94 f"occurrence file not resolved for AOI {aoi!r}", target 95 ) 96 final = find_final_state(run_dir) 97 if final is None: 98 return ScorerResult.skipped("no state files", target) 99 transform = grid_transform(run_dir, ctx) 100 if transform is None: 101 return ScorerResult.skipped("no usable grid transform", target) 102 103 lats, lons = load_occurrence_spots(Path(occ)) 104 if len(lats) == 0: 105 return ScorerResult.skipped("no valid detection spots", target) 106 107 with rasterio.open(final) as ds: 108 band = ds.read(1) 109 h, w = band.shape 110 111 from rasterio.transform import rowcol 112 113 rows, cols = rowcol(transform, lons, lats) 114 rows = np.asarray(rows) 115 cols = np.asarray(cols) 116 in_grid = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w) 117 if not in_grid.any(): 118 return ScorerResult.skipped("no detection spots inside the run grid", target) 119 120 occupied_mask = np.isfinite(band) & (band != NODATA) & (band > 0) 121 occ_rows, occ_cols = np.where(occupied_mask) 122 if len(occ_rows) == 0: 123 # distinguish extinction from genuine zero-coverage 124 extinct = self._extinct(run_dir) 125 result_target = target 126 return ScorerResult( 127 score=0.0, 128 value=0.0, 129 target=result_target, 130 diagnostics={ 131 "extinct": extinct, 132 "n_spots": int(len(lats)), 133 "n_in_grid": int(in_grid.sum()), 134 "final_file": final.name, 135 }, 136 passed=False, 137 ) 138 139 # cell size in km (degrees grid: mean cell extent) 140 cell_km = self._cell_size_km(transform) 141 cov_by_radius: dict[str, float] = {} 142 for r_km in SENSITIVITY_RADII_KM: 143 r_cells = r_km / cell_km 144 cov = self._coverage(rows, cols, in_grid, occ_rows, occ_cols, r_cells) 145 cov_by_radius[f"coverage_r{int(r_km)}km"] = round(cov, 4) 146 coverage = cov_by_radius[f"coverage_r{int(RADIUS_KM_DEFAULT)}km"] 147 148 score = 1.0 if coverage >= COVERAGE_TARGET else round(coverage / COVERAGE_TARGET, 4) 149 return ScorerResult( 150 score=round(float(score), 4), 151 value=float(coverage), 152 target=target, 153 diagnostics={ 154 "n_spots": int(len(lats)), 155 "n_in_grid": int(in_grid.sum()), 156 "n_occupied_cells": int(len(occ_rows)), 157 "cell_km": round(cell_km, 3), 158 "extinct": False, 159 "final_file": final.name, 160 **cov_by_radius, 161 }, 162 passed=float(score) >= self.min_score, 163 ) 164 165 @staticmethod 166 def _extinct(run_dir: Path) -> bool | None: 167 """True when the run's last cohort day reports zero adults, None if the cohort log is unreadable.""" 168 cohort = find_cohort_file(run_dir) 169 if cohort is None: 170 return None 171 try: 172 import json 173 174 data = json.loads(cohort.read_text()) 175 daily = data.get("daily", []) 176 return bool(daily) and daily[-1].get("n_adults", 0) == 0 177 except (OSError, ValueError): 178 return None 179 180 @staticmethod 181 def _cell_size_km(transform: Any) -> float: 182 """Mean cell edge length in km, assuming a degrees-based grid.""" 183 import math 184 185 a = abs(transform.a) 186 e = abs(transform.e) 187 return (a + e) / 2.0 * 111.32 188 189 @staticmethod 190 def _coverage( 191 rows: np.ndarray, 192 cols: np.ndarray, 193 in_grid: np.ndarray, 194 occ_rows: np.ndarray, 195 occ_cols: np.ndarray, 196 r_cells: float, 197 ) -> float: 198 """Fraction of the in-grid detection spots lying within r_cells of an occupied cell.""" 199 if len(occ_rows) == 0 or not in_grid.any(): 200 return 0.0 201 r2 = float(r_cells * r_cells) 202 covered = 0 203 total = 0 204 for spot_row, spot_col, ok in zip(rows, cols, in_grid): 205 if not ok: 206 continue 207 total += 1 208 d2 = (occ_rows - spot_row) ** 2 + (occ_cols - spot_col) ** 2 209 if bool((d2 <= r2).any()): 210 covered += 1 211 return covered / total if total else 0.0
Measures the share of real detection points the simulated population reaches.
The run is expected to come from malariasim validate-detections,
which seeds mosquitoes at the AOI's real detection points; a spot
counts as covered when the final snapshot holds at least one
occupied cell within the detection radius. The value is the covered
fraction of spots and the score is that fraction rescaled against
the coverage target, so a population that never establishes scores
0.
AOI-dependent scorer (needs per-AOI datasets such as occurrence
tables, urban rasters, case series). NEVER runs by default: it must
be explicitly activated via --enable or the scoring YAML, by an
operator who knows the AOI has the required data.
75 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 76 """Compute the detection-point coverage and its score. 77 78 Returns the covered fraction of detection spots as the value. 79 The result is skipped when the AOI, its occurrence table or the 80 grid transform cannot be resolved; a population with no 81 occupied cell at all scores 0 and is flagged as extinct. 82 """ 83 target = f"coverage >= {COVERAGE_TARGET} @ r={RADIUS_KM_DEFAULT}km" 84 aoi = require_aoi(ctx) 85 if not aoi: 86 return ScorerResult.skipped( 87 "requires explicit --aoi (never inferred)", target 88 ) 89 occ = ctx.get("occurrence_path") or resolve_aoi_artifact( 90 aoi, OCCURRENCE_CANDIDATES 91 ) 92 if occ is None or not Path(occ).exists(): 93 return ScorerResult.skipped( 94 f"occurrence file not resolved for AOI {aoi!r}", target 95 ) 96 final = find_final_state(run_dir) 97 if final is None: 98 return ScorerResult.skipped("no state files", target) 99 transform = grid_transform(run_dir, ctx) 100 if transform is None: 101 return ScorerResult.skipped("no usable grid transform", target) 102 103 lats, lons = load_occurrence_spots(Path(occ)) 104 if len(lats) == 0: 105 return ScorerResult.skipped("no valid detection spots", target) 106 107 with rasterio.open(final) as ds: 108 band = ds.read(1) 109 h, w = band.shape 110 111 from rasterio.transform import rowcol 112 113 rows, cols = rowcol(transform, lons, lats) 114 rows = np.asarray(rows) 115 cols = np.asarray(cols) 116 in_grid = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w) 117 if not in_grid.any(): 118 return ScorerResult.skipped("no detection spots inside the run grid", target) 119 120 occupied_mask = np.isfinite(band) & (band != NODATA) & (band > 0) 121 occ_rows, occ_cols = np.where(occupied_mask) 122 if len(occ_rows) == 0: 123 # distinguish extinction from genuine zero-coverage 124 extinct = self._extinct(run_dir) 125 result_target = target 126 return ScorerResult( 127 score=0.0, 128 value=0.0, 129 target=result_target, 130 diagnostics={ 131 "extinct": extinct, 132 "n_spots": int(len(lats)), 133 "n_in_grid": int(in_grid.sum()), 134 "final_file": final.name, 135 }, 136 passed=False, 137 ) 138 139 # cell size in km (degrees grid: mean cell extent) 140 cell_km = self._cell_size_km(transform) 141 cov_by_radius: dict[str, float] = {} 142 for r_km in SENSITIVITY_RADII_KM: 143 r_cells = r_km / cell_km 144 cov = self._coverage(rows, cols, in_grid, occ_rows, occ_cols, r_cells) 145 cov_by_radius[f"coverage_r{int(r_km)}km"] = round(cov, 4) 146 coverage = cov_by_radius[f"coverage_r{int(RADIUS_KM_DEFAULT)}km"] 147 148 score = 1.0 if coverage >= COVERAGE_TARGET else round(coverage / COVERAGE_TARGET, 4) 149 return ScorerResult( 150 score=round(float(score), 4), 151 value=float(coverage), 152 target=target, 153 diagnostics={ 154 "n_spots": int(len(lats)), 155 "n_in_grid": int(in_grid.sum()), 156 "n_occupied_cells": int(len(occ_rows)), 157 "cell_km": round(cell_km, 3), 158 "extinct": False, 159 "final_file": final.name, 160 **cov_by_radius, 161 }, 162 passed=float(score) >= self.min_score, 163 )
Compute the detection-point coverage and its score.
Returns the covered fraction of detection spots as the value. The result is skipped when the AOI, its occurrence table or the grid transform cannot be resolved; a population with no occupied cell at all scores 0 and is flagged as extinct.
60class DispersalKernelScorer(Scorer): 61 """Measures the displacement distribution of the adult population 62 relative to its seeding origin. 63 64 The value is the 90th-percentile displacement at the measurement 65 day; the median displacement is scored alongside it. Each 66 sub-score is 1 inside its mark-release-recapture band and decays as 67 a Gaussian outside it, so both an immobile and an over-dispersing 68 population are penalised. 69 """ 70 71 name = "D21_dispersal_kernel" 72 kind = "composite" 73 weight = 1.0 74 description = "p50/p90 displacement at day 30 vs MRR kernels (Thomas 2013; Costantini 1996)" 75 min_score = 0.7 76 hard_floor = 0.3 77 78 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 79 """Compute the p50/p90 displacement at the measurement day and its score. 80 81 Returns the p90 displacement in km as the value, or a skipped 82 result when there are no day snapshots, no usable grid 83 transform, or no occupied cells to measure. 84 """ 85 target = f"p50 {P50_BAND[0]}-{P50_BAND[1]} km, p90 {P90_BAND[0]}-{P90_BAND[1]} km @ day30" 86 files = find_state_files(run_dir) 87 if not files: 88 return ScorerResult.skipped("no state files", target) 89 transform = grid_transform(run_dir, ctx) 90 if transform is None: 91 return ScorerResult.skipped("no usable grid transform", target) 92 93 day_files: dict[int, Path] = {} 94 for f in files: 95 m = re.search(r"_day(\d+)\.tif$", f.name) 96 if m: 97 day_files[int(m.group(1))] = f 98 if not day_files: 99 return ScorerResult.skipped("no day snapshots", target) 100 101 # seeding origin = centroid of occupied cells in the FIRST snapshot 102 first_day = min(day_files) 103 origin_file = day_files[first_day] 104 with rasterio.open(origin_file) as ds: 105 band0 = ds.read(1) 106 mask0 = np.isfinite(band0) & (band0 != NODATA) & (band0 > 0) 107 if not mask0.any(): 108 return ScorerResult.skipped("no occupied cells in first snapshot", target) 109 rows0, cols0 = np.where(mask0) 110 lon0, lat0 = transform * (float(cols0.mean()), float(rows0.mean())) 111 112 # measurement snapshot: nearest available day <= 30 113 horizon = max((d for d in day_files if d <= 30), default=None) 114 if horizon is None or horizon == first_day: 115 return ScorerResult.skipped( 116 f"no snapshot between day {first_day + 1} and 30", target 117 ) 118 with rasterio.open(day_files[horizon]) as ds: 119 band = ds.read(1) 120 mask = np.isfinite(band) & (band != NODATA) & (band > 0) 121 rows, cols = np.where(mask) 122 if len(rows) < 3: 123 return ScorerResult.skipped( 124 f"too few occupied cells at day {horizon}", target 125 ) 126 distances = np.empty(len(rows), dtype=np.float64) 127 for i in range(len(rows)): 128 lon_i, lat_i = transform * (cols[i], rows[i]) 129 distances[i] = _haversine_km(lat0, lon0, lat_i, lon_i) 130 p50 = float(np.percentile(distances, 50)) 131 p90 = float(np.percentile(distances, 90)) 132 133 lo, hi = P50_BAND 134 if lo <= p50 <= hi: 135 p50_ok = 1.0 136 else: 137 p50_ok = max(0.0, math.exp(-((p50 - P50_CENTER) / P50_SIGMA) ** 2)) 138 lo, hi = P90_BAND 139 if lo <= p90 <= hi: 140 p90_ok = 1.0 141 else: 142 p90_ok = max(0.0, math.exp(-((p90 - P90_CENTER) / P90_SIGMA) ** 2)) 143 144 score = (p50_ok + p90_ok) / 2.0 145 return ScorerResult( 146 score=round(score, 4), 147 value=round(p90, 3), 148 target=target, 149 diagnostics={ 150 "p50_km": round(p50, 3), 151 "p90_km": round(p90, 3), 152 "horizon_day": horizon, 153 "origin_day": first_day, 154 "n_cells": int(len(rows)), 155 }, 156 passed=score >= self.min_score, 157 )
Measures the displacement distribution of the adult population relative to its seeding origin.
The value is the 90th-percentile displacement at the measurement day; the median displacement is scored alongside it. Each sub-score is 1 inside its mark-release-recapture band and decays as a Gaussian outside it, so both an immobile and an over-dispersing population are penalised.
78 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 79 """Compute the p50/p90 displacement at the measurement day and its score. 80 81 Returns the p90 displacement in km as the value, or a skipped 82 result when there are no day snapshots, no usable grid 83 transform, or no occupied cells to measure. 84 """ 85 target = f"p50 {P50_BAND[0]}-{P50_BAND[1]} km, p90 {P90_BAND[0]}-{P90_BAND[1]} km @ day30" 86 files = find_state_files(run_dir) 87 if not files: 88 return ScorerResult.skipped("no state files", target) 89 transform = grid_transform(run_dir, ctx) 90 if transform is None: 91 return ScorerResult.skipped("no usable grid transform", target) 92 93 day_files: dict[int, Path] = {} 94 for f in files: 95 m = re.search(r"_day(\d+)\.tif$", f.name) 96 if m: 97 day_files[int(m.group(1))] = f 98 if not day_files: 99 return ScorerResult.skipped("no day snapshots", target) 100 101 # seeding origin = centroid of occupied cells in the FIRST snapshot 102 first_day = min(day_files) 103 origin_file = day_files[first_day] 104 with rasterio.open(origin_file) as ds: 105 band0 = ds.read(1) 106 mask0 = np.isfinite(band0) & (band0 != NODATA) & (band0 > 0) 107 if not mask0.any(): 108 return ScorerResult.skipped("no occupied cells in first snapshot", target) 109 rows0, cols0 = np.where(mask0) 110 lon0, lat0 = transform * (float(cols0.mean()), float(rows0.mean())) 111 112 # measurement snapshot: nearest available day <= 30 113 horizon = max((d for d in day_files if d <= 30), default=None) 114 if horizon is None or horizon == first_day: 115 return ScorerResult.skipped( 116 f"no snapshot between day {first_day + 1} and 30", target 117 ) 118 with rasterio.open(day_files[horizon]) as ds: 119 band = ds.read(1) 120 mask = np.isfinite(band) & (band != NODATA) & (band > 0) 121 rows, cols = np.where(mask) 122 if len(rows) < 3: 123 return ScorerResult.skipped( 124 f"too few occupied cells at day {horizon}", target 125 ) 126 distances = np.empty(len(rows), dtype=np.float64) 127 for i in range(len(rows)): 128 lon_i, lat_i = transform * (cols[i], rows[i]) 129 distances[i] = _haversine_km(lat0, lon0, lat_i, lon_i) 130 p50 = float(np.percentile(distances, 50)) 131 p90 = float(np.percentile(distances, 90)) 132 133 lo, hi = P50_BAND 134 if lo <= p50 <= hi: 135 p50_ok = 1.0 136 else: 137 p50_ok = max(0.0, math.exp(-((p50 - P50_CENTER) / P50_SIGMA) ** 2)) 138 lo, hi = P90_BAND 139 if lo <= p90 <= hi: 140 p90_ok = 1.0 141 else: 142 p90_ok = max(0.0, math.exp(-((p90 - P90_CENTER) / P90_SIGMA) ** 2)) 143 144 score = (p50_ok + p90_ok) / 2.0 145 return ScorerResult( 146 score=round(score, 4), 147 value=round(p90, 3), 148 target=target, 149 diagnostics={ 150 "p50_km": round(p50, 3), 151 "p90_km": round(p90, 3), 152 "horizon_day": horizon, 153 "origin_day": first_day, 154 "n_cells": int(len(rows)), 155 }, 156 passed=score >= self.min_score, 157 )
Compute the p50/p90 displacement at the measurement day and its score.
Returns the p90 displacement in km as the value, or a skipped result when there are no day snapshots, no usable grid transform, or no occupied cells to measure.
180class CasesGhanaScorer(Scorer): 181 """Measures how well the simulated transmission seasonality matches 182 the reported malaria cases in Ghana. 183 184 The value is the Pearson correlation between the simulated 185 calendar-month climatology and the observed reported-case series 186 (or the aligned single-year series when the run covers one full 187 post-warm-up year). The score is 1 at or above the target 188 correlation and decays as a Gaussian below it, so an uncorrelated 189 seasonality scores near 0. 190 """ 191 192 name = "D25_cases_ghana" 193 kind = "composite" 194 weight = 2.0 195 description = "Seasonality match vs DHIMS-II reported cases, Ghana-only (Seidu 2026)" 196 min_score = 0.5 197 hard_floor = 0.2 198 manual = True # Ghana-only: fixed national dataset, not generalizable 199 200 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 201 """Compute the seasonality correlation against reported cases and its score. 202 203 Returns the correlation coefficient as the value. The result is 204 skipped for any AOI other than Ghana, when the run has no 205 transmission log, when the observed dataset cannot be fetched, 206 or when either series has no variance. 207 """ 208 aoi = require_aoi(ctx) 209 if not aoi: 210 return ScorerResult.skipped( 211 "requires explicit --aoi (never inferred)", target="seasonality r" 212 ) 213 if aoi != "ghana": 214 return ScorerResult.skipped( 215 f"Ghana-only score: dataset covers Ashanti/Eastern/Volta (Ghana), " 216 f"not AOI {aoi!r}", 217 target="seasonality r", 218 ) 219 220 run_meta = ctx.get("run_meta") or {} 221 start_year = int(run_meta.get("year", 2024) or 2024) 222 start_month = int(run_meta.get("month", 1) or 1) 223 monthly = _simulated_monthly_totals( 224 run_dir, start_year=start_year, start_month=start_month 225 ) 226 if monthly is None: 227 return ScorerResult.skipped( 228 "no *_transmission_daily.json — requires a run with " 229 "--enable-transmission", 230 target="seasonality r", 231 ) 232 try: 233 path = ensure_dataset() 234 except Exception as e: 235 return ScorerResult.skipped(f"dataset unavailable: {e}", target="seasonality r") 236 237 warmup = int(ctx.get("warmup_months", 12) or 0) 238 sim_totals, sim_years = monthly 239 n_blocks = len(sim_totals) 240 # aligned mode: compare the LAST full 12 blocks (post warm-up) with 241 # the observed series of their calendar year, when that year exists 242 # in the dataset and the tail covers one full year. 243 tail_year = sim_years[n_blocks - 1] 244 full_year_tail = ( 245 n_blocks >= warmup + 12 246 and len(set(sim_years[n_blocks - 12 : n_blocks])) == 1 247 ) 248 if full_year_tail and _observed_year_series(path, tail_year) is not None: 249 sim = sim_totals[n_blocks - 12 : n_blocks] 250 obs = _observed_year_series(path, tail_year) 251 assert obs is not None # narrowed above 252 mode = f"aligned-{tail_year}" 253 target = f"seasonality r >= {R_TARGET} vs observed {tail_year}" 254 else: 255 # fallback: month-of-year climatology vs 2016-2023 pooled 256 sims = np.zeros(12) 257 counts = np.zeros(12) 258 for b in range(warmup, n_blocks): 259 cal_month = (start_month - 1 + b) % 12 260 sims[cal_month] += sim_totals[b] 261 counts[cal_month] += 1 262 counts[counts == 0] = 1 263 sim = sims / counts 264 obs = _observed_climatology(path) 265 mode = "climatology" 266 target = f"seasonality r >= {R_TARGET} (monthly climatology)" 267 268 if obs.std() == 0 or sim.std() == 0: 269 return ScorerResult.skipped( 270 "degenerate series (zero variance)", target 271 ) 272 r = float(np.corrcoef(sim, obs)[0, 1]) 273 if np.isnan(r): 274 r = 0.0 275 if r >= R_TARGET: 276 score = 1.0 277 else: 278 score = max(0.0, math.exp(-((r - R_TARGET) / 0.20) ** 2)) 279 return ScorerResult( 280 score=round(score, 4), 281 value=round(r, 4), 282 target=target, 283 diagnostics={ 284 "mode": mode, 285 "dataset": str(path.name), 286 "warmup_months": warmup, 287 "observed": [round(float(v), 1) for v in obs], 288 "simulated": [round(float(v), 6) for v in sim], 289 "covid_2020_excluded": True, 290 }, 291 passed=score >= self.min_score, 292 )
Measures how well the simulated transmission seasonality matches the reported malaria cases in Ghana.
The value is the Pearson correlation between the simulated calendar-month climatology and the observed reported-case series (or the aligned single-year series when the run covers one full post-warm-up year). The score is 1 at or above the target correlation and decays as a Gaussian below it, so an uncorrelated seasonality scores near 0.
AOI-dependent scorer (needs per-AOI datasets such as occurrence
tables, urban rasters, case series). NEVER runs by default: it must
be explicitly activated via --enable or the scoring YAML, by an
operator who knows the AOI has the required data.
200 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 201 """Compute the seasonality correlation against reported cases and its score. 202 203 Returns the correlation coefficient as the value. The result is 204 skipped for any AOI other than Ghana, when the run has no 205 transmission log, when the observed dataset cannot be fetched, 206 or when either series has no variance. 207 """ 208 aoi = require_aoi(ctx) 209 if not aoi: 210 return ScorerResult.skipped( 211 "requires explicit --aoi (never inferred)", target="seasonality r" 212 ) 213 if aoi != "ghana": 214 return ScorerResult.skipped( 215 f"Ghana-only score: dataset covers Ashanti/Eastern/Volta (Ghana), " 216 f"not AOI {aoi!r}", 217 target="seasonality r", 218 ) 219 220 run_meta = ctx.get("run_meta") or {} 221 start_year = int(run_meta.get("year", 2024) or 2024) 222 start_month = int(run_meta.get("month", 1) or 1) 223 monthly = _simulated_monthly_totals( 224 run_dir, start_year=start_year, start_month=start_month 225 ) 226 if monthly is None: 227 return ScorerResult.skipped( 228 "no *_transmission_daily.json — requires a run with " 229 "--enable-transmission", 230 target="seasonality r", 231 ) 232 try: 233 path = ensure_dataset() 234 except Exception as e: 235 return ScorerResult.skipped(f"dataset unavailable: {e}", target="seasonality r") 236 237 warmup = int(ctx.get("warmup_months", 12) or 0) 238 sim_totals, sim_years = monthly 239 n_blocks = len(sim_totals) 240 # aligned mode: compare the LAST full 12 blocks (post warm-up) with 241 # the observed series of their calendar year, when that year exists 242 # in the dataset and the tail covers one full year. 243 tail_year = sim_years[n_blocks - 1] 244 full_year_tail = ( 245 n_blocks >= warmup + 12 246 and len(set(sim_years[n_blocks - 12 : n_blocks])) == 1 247 ) 248 if full_year_tail and _observed_year_series(path, tail_year) is not None: 249 sim = sim_totals[n_blocks - 12 : n_blocks] 250 obs = _observed_year_series(path, tail_year) 251 assert obs is not None # narrowed above 252 mode = f"aligned-{tail_year}" 253 target = f"seasonality r >= {R_TARGET} vs observed {tail_year}" 254 else: 255 # fallback: month-of-year climatology vs 2016-2023 pooled 256 sims = np.zeros(12) 257 counts = np.zeros(12) 258 for b in range(warmup, n_blocks): 259 cal_month = (start_month - 1 + b) % 12 260 sims[cal_month] += sim_totals[b] 261 counts[cal_month] += 1 262 counts[counts == 0] = 1 263 sim = sims / counts 264 obs = _observed_climatology(path) 265 mode = "climatology" 266 target = f"seasonality r >= {R_TARGET} (monthly climatology)" 267 268 if obs.std() == 0 or sim.std() == 0: 269 return ScorerResult.skipped( 270 "degenerate series (zero variance)", target 271 ) 272 r = float(np.corrcoef(sim, obs)[0, 1]) 273 if np.isnan(r): 274 r = 0.0 275 if r >= R_TARGET: 276 score = 1.0 277 else: 278 score = max(0.0, math.exp(-((r - R_TARGET) / 0.20) ** 2)) 279 return ScorerResult( 280 score=round(score, 4), 281 value=round(r, 4), 282 target=target, 283 diagnostics={ 284 "mode": mode, 285 "dataset": str(path.name), 286 "warmup_months": warmup, 287 "observed": [round(float(v), 1) for v in obs], 288 "simulated": [round(float(v), 6) for v in sim], 289 "covid_2020_excluded": True, 290 }, 291 passed=score >= self.min_score, 292 )
Compute the seasonality correlation against reported cases and its score.
Returns the correlation coefficient as the value. The result is skipped for any AOI other than Ghana, when the run has no transmission log, when the observed dataset cannot be fetched, or when either series has no variance.
36class DataValidGate(Scorer): 37 """G6 (ex-D6): every state band value finite and non-negative. 38 39 Contract 4.0: state bands are raw per-cell adult counts — values 40 above 1 are expected, so the old [0, 1] envelope no longer applies. 41 """ 42 43 name = "G6_data_valid" 44 kind = "gate" 45 weight = 0.0 46 description = "All state bands finite and >= 0 (COG/NaN write integrity)" 47 aoi_generalizable = True 48 49 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 50 """Check that every state band value is finite and non-negative. 51 52 Returns the share of valid cell values as the value and score; 53 the gate passes only when every sampled value is valid. 54 """ 55 tifs = find_state_files(run_dir) 56 if not tifs: 57 return ScorerResult.skipped("no state files", target="finite & >= 0") 58 if len(tifs) > 48: # uniform sample — full sweep belongs to pytest 59 step = len(tifs) / 48.0 60 tifs = [tifs[int(i * step)] for i in range(48)] 61 total_valid = 0 62 total = 0 63 bad_files: list[str] = [] 64 for tif in tifs: 65 with rasterio.open(tif) as ds: 66 for bidx in range(1, ds.count + 1): 67 band = ds.read(bidx) 68 finite = np.isfinite(band) & (band != NODATA) 69 if ds.nodata is not None: 70 finite &= band != ds.nodata 71 ok = finite & (band >= 0.0) 72 if int(ok.sum()) != band.size: 73 bad_files.append(tif.name) 74 total_valid += int(ok.sum()) 75 total += band.size 76 frac = total_valid / total if total else 0.0 77 return ScorerResult( 78 score=frac, 79 value=frac, 80 target="finite & >= 0", 81 diagnostics={"files_with_bad_values": bad_files[:10]}, 82 passed=frac == 1.0, 83 )
G6 (ex-D6): every state band value finite and non-negative.
Contract 4.0: state bands are raw per-cell adult counts — values above 1 are expected, so the old [0, 1] envelope no longer applies.
49 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 50 """Check that every state band value is finite and non-negative. 51 52 Returns the share of valid cell values as the value and score; 53 the gate passes only when every sampled value is valid. 54 """ 55 tifs = find_state_files(run_dir) 56 if not tifs: 57 return ScorerResult.skipped("no state files", target="finite & >= 0") 58 if len(tifs) > 48: # uniform sample — full sweep belongs to pytest 59 step = len(tifs) / 48.0 60 tifs = [tifs[int(i * step)] for i in range(48)] 61 total_valid = 0 62 total = 0 63 bad_files: list[str] = [] 64 for tif in tifs: 65 with rasterio.open(tif) as ds: 66 for bidx in range(1, ds.count + 1): 67 band = ds.read(bidx) 68 finite = np.isfinite(band) & (band != NODATA) 69 if ds.nodata is not None: 70 finite &= band != ds.nodata 71 ok = finite & (band >= 0.0) 72 if int(ok.sum()) != band.size: 73 bad_files.append(tif.name) 74 total_valid += int(ok.sum()) 75 total += band.size 76 frac = total_valid / total if total else 0.0 77 return ScorerResult( 78 score=frac, 79 value=frac, 80 target="finite & >= 0", 81 diagnostics={"files_with_bad_values": bad_files[:10]}, 82 passed=frac == 1.0, 83 )
Check that every state band value is finite and non-negative.
Returns the share of valid cell values as the value and score; the gate passes only when every sampled value is valid.
86class DeterminismGate(Scorer): 87 """G7 (ex-D7): same-seed outputs byte-identical.""" 88 89 name = "G7_determinism" 90 kind = "gate" 91 weight = 0.0 92 description = "Same-seed state files hash-identical" 93 aoi_generalizable = True 94 95 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 96 """Check that repeated runs with the same seed are byte-identical. 97 98 Returns the number of mismatching seed groups as the value; the 99 gate passes when there are none. 100 """ 101 tifs = sorted(p for p in run_dir.glob("state_seed*.tif") if "_day" not in p.stem) 102 if not tifs: 103 return ScorerResult.skipped( 104 "no per-seed state files (determinism covered by pytest suite)", 105 target="identical per seed", 106 ) 107 groups: dict[str, list[Path]] = defaultdict(list) 108 for t in tifs: 109 m = re.search(r"seed(\d+)", t.name) 110 groups[m.group(0) if m else "default"].append(t) 111 mismatches = 0 112 for files in groups.values(): 113 if len(files) < 2: 114 continue 115 hashes = {hashlib.md5(f.read_bytes()).hexdigest() for f in files} 116 if len(hashes) > 1: 117 mismatches += 1 118 return ScorerResult( 119 score=0.0 if mismatches else 1.0, 120 value=float(mismatches), 121 target="identical per seed", 122 diagnostics={"mismatches": mismatches}, 123 passed=mismatches == 0, 124 )
G7 (ex-D7): same-seed outputs byte-identical.
95 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 96 """Check that repeated runs with the same seed are byte-identical. 97 98 Returns the number of mismatching seed groups as the value; the 99 gate passes when there are none. 100 """ 101 tifs = sorted(p for p in run_dir.glob("state_seed*.tif") if "_day" not in p.stem) 102 if not tifs: 103 return ScorerResult.skipped( 104 "no per-seed state files (determinism covered by pytest suite)", 105 target="identical per seed", 106 ) 107 groups: dict[str, list[Path]] = defaultdict(list) 108 for t in tifs: 109 m = re.search(r"seed(\d+)", t.name) 110 groups[m.group(0) if m else "default"].append(t) 111 mismatches = 0 112 for files in groups.values(): 113 if len(files) < 2: 114 continue 115 hashes = {hashlib.md5(f.read_bytes()).hexdigest() for f in files} 116 if len(hashes) > 1: 117 mismatches += 1 118 return ScorerResult( 119 score=0.0 if mismatches else 1.0, 120 value=float(mismatches), 121 target="identical per seed", 122 diagnostics={"mismatches": mismatches}, 123 passed=mismatches == 0, 124 )
Check that repeated runs with the same seed are byte-identical.
Returns the number of mismatching seed groups as the value; the gate passes when there are none.
163class HostInputGate(Scorer): 164 """G12 (ex-D12): input host grid total matches the census reference.""" 165 166 name = "G12_host_input" 167 kind = "gate" 168 weight = 0.0 169 description = "Input human grid total ~ census reference (input validation)" 170 aoi_generalizable = True 171 172 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 173 """Check that the input host grid totals close to the census reference. 174 175 Returns the grid population total as the value; the gate passes 176 when the total stays within the tolerance band around the 177 reference. 178 """ 179 aoi = require_aoi(ctx) 180 if not aoi: 181 return ScorerResult.skipped( 182 "requires explicit --aoi (never inferred)", target="~ reference census total" 183 ) 184 hosts = ctx.get("hosts_path") or resolve_aoi_artifact( 185 aoi, ["data/{aoi}/{aoi}_host_static.nc", "data/{aoi}/host_static.nc"] 186 ) 187 if hosts is None or not Path(hosts).exists(): 188 return ScorerResult.skipped( 189 f"host_static.nc not resolved for AOI {aoi!r}", 190 target="~ reference census total", 191 ) 192 ref_total = float(ctx.get("human_reference_total", 27_000_000)) 193 try: 194 import xarray as xr 195 except ImportError: 196 return ScorerResult.skipped("missing dependency: xarray", target="~ 27M") 197 ds = xr.open_dataset(str(hosts)) 198 human = ds["human"].values 199 valid = human[human != _INGEST_NODATA] 200 total = float(valid.sum()) if valid.size else 0.0 201 ds.close() 202 if ref_total <= 0 or total <= 0: 203 return ScorerResult( 204 score=0.0, value=total, target=f"~ {ref_total:,.0f}", passed=False, 205 ) 206 ratio = total / ref_total 207 score = 1.0 if 0.9 <= ratio <= 1.1 else max( 208 0.0, 1.0 - abs(ratio - 1.0) 209 ) 210 return ScorerResult( 211 score=round(score, 4), 212 value=round(total, 0), 213 target=f"~ {ref_total:,.0f}", 214 diagnostics={"ratio": round(ratio, 4)}, 215 passed=0.8 <= ratio <= 1.2, 216 )
G12 (ex-D12): input host grid total matches the census reference.
172 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 173 """Check that the input host grid totals close to the census reference. 174 175 Returns the grid population total as the value; the gate passes 176 when the total stays within the tolerance band around the 177 reference. 178 """ 179 aoi = require_aoi(ctx) 180 if not aoi: 181 return ScorerResult.skipped( 182 "requires explicit --aoi (never inferred)", target="~ reference census total" 183 ) 184 hosts = ctx.get("hosts_path") or resolve_aoi_artifact( 185 aoi, ["data/{aoi}/{aoi}_host_static.nc", "data/{aoi}/host_static.nc"] 186 ) 187 if hosts is None or not Path(hosts).exists(): 188 return ScorerResult.skipped( 189 f"host_static.nc not resolved for AOI {aoi!r}", 190 target="~ reference census total", 191 ) 192 ref_total = float(ctx.get("human_reference_total", 27_000_000)) 193 try: 194 import xarray as xr 195 except ImportError: 196 return ScorerResult.skipped("missing dependency: xarray", target="~ 27M") 197 ds = xr.open_dataset(str(hosts)) 198 human = ds["human"].values 199 valid = human[human != _INGEST_NODATA] 200 total = float(valid.sum()) if valid.size else 0.0 201 ds.close() 202 if ref_total <= 0 or total <= 0: 203 return ScorerResult( 204 score=0.0, value=total, target=f"~ {ref_total:,.0f}", passed=False, 205 ) 206 ratio = total / ref_total 207 score = 1.0 if 0.9 <= ratio <= 1.1 else max( 208 0.0, 1.0 - abs(ratio - 1.0) 209 ) 210 return ScorerResult( 211 score=round(score, 4), 212 value=round(total, 0), 213 target=f"~ {ref_total:,.0f}", 214 diagnostics={"ratio": round(ratio, 4)}, 215 passed=0.8 <= ratio <= 1.2, 216 )
Check that the input host grid totals close to the census reference.
Returns the grid population total as the value; the gate passes when the total stays within the tolerance band around the reference.
219class MobilityGate(Scorer): 220 """G14 (ex-D14): OD matrix rows are row-stochastic (sum to 1.0).""" 221 222 name = "G14_mobility" 223 kind = "gate" 224 weight = 0.0 225 description = "Mobility OD matrix rows sum to 1.0 (input validation)" 226 aoi_generalizable = True 227 228 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 229 """Check that the mobility origin-destination matrix is row-stochastic. 230 231 Returns the smallest fraction of rows summing to one across the 232 checked files as the value; the gate passes when every file 233 clears the tolerance. 234 """ 235 csr_files = sorted(run_dir.glob("*.csr")) 236 if not csr_files: 237 for parent in (run_dir.parent, run_dir.parent / "hosts"): 238 csr_files = sorted(parent.glob("*.csr")) 239 if csr_files: 240 break 241 if not csr_files: 242 return ScorerResult.skipped( 243 "no .csr files near run dir", target="rows sum to 1.0" 244 ) 245 min_fraction = 1.0 246 checked = 0 247 for csr in csr_files: 248 try: 249 with open(csr, "rb") as f: 250 n_rows = struct.unpack("i", f.read(4))[0] 251 n_cols = struct.unpack("i", f.read(4))[0] 252 nnz = struct.unpack("i", f.read(4))[0] 253 row_ptr = np.frombuffer(f.read(4 * (n_rows + 1)), dtype=np.int32) 254 col_idx = np.frombuffer(f.read(4 * nnz), dtype=np.int32) 255 values = np.frombuffer(f.read(4 * nnz), dtype=np.float32) 256 del n_cols, col_idx 257 sums = np.add.reduceat( 258 values, row_ptr[:-1].clip(max=len(values)) 259 ) if nnz else np.zeros(n_rows) 260 frac = float( 261 (np.abs(sums - 1.0) < 0.01).sum() / max(n_rows, 1) 262 ) 263 min_fraction = min(min_fraction, frac) 264 checked += 1 265 except Exception as e: 266 return ScorerResult.skipped(f"csr unreadable: {e}", target="rows sum to 1.0") 267 return ScorerResult( 268 score=round(min_fraction, 4), 269 value=round(min_fraction, 4), 270 target="rows sum to 1.0 (all files)", 271 diagnostics={"files_checked": checked}, 272 passed=min_fraction >= 0.99, 273 )
G14 (ex-D14): OD matrix rows are row-stochastic (sum to 1.0).
228 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 229 """Check that the mobility origin-destination matrix is row-stochastic. 230 231 Returns the smallest fraction of rows summing to one across the 232 checked files as the value; the gate passes when every file 233 clears the tolerance. 234 """ 235 csr_files = sorted(run_dir.glob("*.csr")) 236 if not csr_files: 237 for parent in (run_dir.parent, run_dir.parent / "hosts"): 238 csr_files = sorted(parent.glob("*.csr")) 239 if csr_files: 240 break 241 if not csr_files: 242 return ScorerResult.skipped( 243 "no .csr files near run dir", target="rows sum to 1.0" 244 ) 245 min_fraction = 1.0 246 checked = 0 247 for csr in csr_files: 248 try: 249 with open(csr, "rb") as f: 250 n_rows = struct.unpack("i", f.read(4))[0] 251 n_cols = struct.unpack("i", f.read(4))[0] 252 nnz = struct.unpack("i", f.read(4))[0] 253 row_ptr = np.frombuffer(f.read(4 * (n_rows + 1)), dtype=np.int32) 254 col_idx = np.frombuffer(f.read(4 * nnz), dtype=np.int32) 255 values = np.frombuffer(f.read(4 * nnz), dtype=np.float32) 256 del n_cols, col_idx 257 sums = np.add.reduceat( 258 values, row_ptr[:-1].clip(max=len(values)) 259 ) if nnz else np.zeros(n_rows) 260 frac = float( 261 (np.abs(sums - 1.0) < 0.01).sum() / max(n_rows, 1) 262 ) 263 min_fraction = min(min_fraction, frac) 264 checked += 1 265 except Exception as e: 266 return ScorerResult.skipped(f"csr unreadable: {e}", target="rows sum to 1.0") 267 return ScorerResult( 268 score=round(min_fraction, 4), 269 value=round(min_fraction, 4), 270 target="rows sum to 1.0 (all files)", 271 diagnostics={"files_checked": checked}, 272 passed=min_fraction >= 0.99, 273 )
Check that the mobility origin-destination matrix is row-stochastic.
Returns the smallest fraction of rows summing to one across the checked files as the value; the gate passes when every file clears the tolerance.
127class PerformanceGate(Scorer): 128 """G10 (ex-D10): wall time from run_metadata.json, if recorded.""" 129 130 name = "G10_perf" 131 kind = "gate" 132 weight = 0.0 133 description = "Wall time <= 30 s (when run_metadata.json records it)" 134 aoi_generalizable = True 135 136 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 137 """Check the recorded wall time of the run against the budget. 138 139 Returns the wall time in seconds as the value; the gate is 140 skipped when the run metadata does not record a wall time. 141 """ 142 meta_path = run_dir / "run_metadata.json" 143 if not meta_path.exists(): 144 return ScorerResult.skipped( 145 "no run_metadata.json (perf covered by benchmark tier)", 146 target="<=30 s", 147 ) 148 try: 149 meta = json.loads(meta_path.read_text()) 150 except (json.JSONDecodeError, OSError): 151 return ScorerResult.skipped("run_metadata unreadable", target="<=30 s") 152 wall_s = meta.get("wall_s", 0.0) 153 if wall_s <= 0: 154 return ScorerResult.skipped("wall_s not recorded", target="<=30 s") 155 return ScorerResult( 156 score=min(1.0, 30.0 / wall_s), 157 value=float(wall_s), 158 target="<=30 s", 159 passed=wall_s <= 30.0, 160 )
G10 (ex-D10): wall time from run_metadata.json, if recorded.
136 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 137 """Check the recorded wall time of the run against the budget. 138 139 Returns the wall time in seconds as the value; the gate is 140 skipped when the run metadata does not record a wall time. 141 """ 142 meta_path = run_dir / "run_metadata.json" 143 if not meta_path.exists(): 144 return ScorerResult.skipped( 145 "no run_metadata.json (perf covered by benchmark tier)", 146 target="<=30 s", 147 ) 148 try: 149 meta = json.loads(meta_path.read_text()) 150 except (json.JSONDecodeError, OSError): 151 return ScorerResult.skipped("run_metadata unreadable", target="<=30 s") 152 wall_s = meta.get("wall_s", 0.0) 153 if wall_s <= 0: 154 return ScorerResult.skipped("wall_s not recorded", target="<=30 s") 155 return ScorerResult( 156 score=min(1.0, 30.0 / wall_s), 157 value=float(wall_s), 158 target="<=30 s", 159 passed=wall_s <= 30.0, 160 )
Check the recorded wall time of the run against the budget.
Returns the wall time in seconds as the value; the gate is skipped when the run metadata does not record a wall time.
276class UrbanProductivityGate(Scorer): 277 """G24 (ex-D24): urban cells carry less density than rural cells. 278 279 AOI-specific: requires an ``<aoi>_urban_class.tif`` next to the AOI 280 env inputs. Skipped (not failed) when the raster is absent. 281 """ 282 283 name = "G24_urban_ratio" 284 kind = "gate" 285 weight = 0.0 286 description = "Urban/rural density ratio <= 0.7 (capacity-scaling guardrail)" 287 manual = True # AOI-dependent: needs the AOI's urban class raster 288 289 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 290 """Check that urban cells carry less adult density than rural cells. 291 292 Returns the urban-to-rural mean density ratio as the value; the 293 gate passes when the ratio stays at or below the bound. The 294 result is skipped when the urban class raster or enough active 295 cells of each class are missing. 296 """ 297 aoi = require_aoi(ctx) 298 urban_raster = ctx.get("urban_class_path") or resolve_aoi_artifact( 299 aoi, ["data/{aoi}/{aoi}_urban_class.tif", "data/{aoi}/urban_class.tif"] 300 ) 301 if urban_raster is None or not Path(urban_raster).exists(): 302 return ScorerResult.skipped( 303 f"urban class raster not resolved for AOI {aoi!r}", 304 target="<= 0.7", 305 ) 306 files = find_state_files(run_dir) 307 if not files: 308 return ScorerResult.skipped("no state files", target="<= 0.7") 309 with rasterio.open(files[-1]) as ds: 310 density = ds.read(1) 311 with rasterio.open(urban_raster) as ds: 312 urban_class = ds.read(1) 313 nodata = ds.nodata 314 if density.shape != urban_class.shape: 315 return ScorerResult.skipped("raster shape mismatch", target="<= 0.7") 316 mask_d = np.isfinite(density) & (density != NODATA) & (density > 0) 317 urban_mask = mask_d & (urban_class == 30) 318 rural_mask = mask_d & (urban_class == 50) 319 if urban_mask.sum() < 10 or rural_mask.sum() < 10: 320 return ScorerResult.skipped( 321 "insufficient urban/rural active cells", target="<= 0.7" 322 ) 323 urban_mean = float(density[urban_mask].mean()) 324 rural_mean = float(density[rural_mask].mean()) 325 if rural_mean <= 0: 326 return ScorerResult.skipped("rural mean <= 0", target="<= 0.7") 327 ratio = urban_mean / rural_mean 328 score = 1.0 if ratio <= 0.7 else max(0.0, 1.0 - (ratio - 0.7) / 0.3) 329 return ScorerResult( 330 score=round(score, 4), 331 value=round(ratio, 4), 332 target="<= 0.7", 333 diagnostics={ 334 "n_urban": int(urban_mask.sum()), 335 "n_rural": int(rural_mask.sum()), 336 }, 337 passed=ratio <= 0.7, 338 )
G24 (ex-D24): urban cells carry less density than rural cells.
AOI-specific: requires an <aoi>_urban_class.tif next to the AOI
env inputs. Skipped (not failed) when the raster is absent.
AOI-dependent scorer (needs per-AOI datasets such as occurrence
tables, urban rasters, case series). NEVER runs by default: it must
be explicitly activated via --enable or the scoring YAML, by an
operator who knows the AOI has the required data.
289 def score(self, run_dir: Path, ctx: dict[str, Any]) -> ScorerResult: 290 """Check that urban cells carry less adult density than rural cells. 291 292 Returns the urban-to-rural mean density ratio as the value; the 293 gate passes when the ratio stays at or below the bound. The 294 result is skipped when the urban class raster or enough active 295 cells of each class are missing. 296 """ 297 aoi = require_aoi(ctx) 298 urban_raster = ctx.get("urban_class_path") or resolve_aoi_artifact( 299 aoi, ["data/{aoi}/{aoi}_urban_class.tif", "data/{aoi}/urban_class.tif"] 300 ) 301 if urban_raster is None or not Path(urban_raster).exists(): 302 return ScorerResult.skipped( 303 f"urban class raster not resolved for AOI {aoi!r}", 304 target="<= 0.7", 305 ) 306 files = find_state_files(run_dir) 307 if not files: 308 return ScorerResult.skipped("no state files", target="<= 0.7") 309 with rasterio.open(files[-1]) as ds: 310 density = ds.read(1) 311 with rasterio.open(urban_raster) as ds: 312 urban_class = ds.read(1) 313 nodata = ds.nodata 314 if density.shape != urban_class.shape: 315 return ScorerResult.skipped("raster shape mismatch", target="<= 0.7") 316 mask_d = np.isfinite(density) & (density != NODATA) & (density > 0) 317 urban_mask = mask_d & (urban_class == 30) 318 rural_mask = mask_d & (urban_class == 50) 319 if urban_mask.sum() < 10 or rural_mask.sum() < 10: 320 return ScorerResult.skipped( 321 "insufficient urban/rural active cells", target="<= 0.7" 322 ) 323 urban_mean = float(density[urban_mask].mean()) 324 rural_mean = float(density[rural_mask].mean()) 325 if rural_mean <= 0: 326 return ScorerResult.skipped("rural mean <= 0", target="<= 0.7") 327 ratio = urban_mean / rural_mean 328 score = 1.0 if ratio <= 0.7 else max(0.0, 1.0 - (ratio - 0.7) / 0.3) 329 return ScorerResult( 330 score=round(score, 4), 331 value=round(ratio, 4), 332 target="<= 0.7", 333 diagnostics={ 334 "n_urban": int(urban_mask.sum()), 335 "n_rural": int(rural_mask.sum()), 336 }, 337 passed=ratio <= 0.7, 338 )
Check that urban cells carry less adult density than rural cells.
Returns the urban-to-rural mean density ratio as the value; the gate passes when the ratio stays at or below the bound. The result is skipped when the urban class raster or enough active cells of each class are missing.