mal_core.abm
ABM subpackage — C++ simulation engine + Python wrapper.
1"""ABM subpackage — C++ simulation engine + Python wrapper.""" 2from .compile import compile_abm, get_abm_dirs, resolve_abm_dirs 3from .runner import run_abm 4from .wrapper import CppAbmWrapper, run_abm_from_manifest 5 6__all__ = [ 7 "CppAbmWrapper", 8 "compile_abm", 9 "get_abm_dirs", 10 "resolve_abm_dirs", 11 "run_abm", 12 "run_abm_from_manifest", 13]
13class CppAbmWrapper: 14 """Thin Python wrapper that drives the compiled C++ ABM binary. 15 16 It locates the binary, translates keyword arguments into the 17 binary's command-line flags and runs it, returning the captured 18 process output. 19 """ 20 21 def __init__( 22 self, 23 binary_path: Path | None = None, 24 worktree: str | Path | None = None, 25 ): 26 """Bind the wrapper to a binary, resolving one when none is given. 27 28 Args: 29 binary_path: explicit path to the compiled binary. 30 worktree: root of a worktree whose build directory may hold the 31 binary; used when the installed package does not ship one. 32 """ 33 self.worktree = Path(worktree).resolve() if worktree else None 34 self.binary = binary_path or self._resolve_binary() 35 self._flags_schema: dict[str, dict[str, Any]] | None = None 36 37 def _resolve_binary(self) -> Path: 38 """Locate the compiled ABM binary. 39 40 Looks in the worktree (if given) and then in the installed package 41 directory, preferring the platform-named binary under ``bin/`` over 42 the generic one under ``build/src/``. Raises FileNotFoundError with 43 the compile command when no binary is found. 44 """ 45 candidate_dirs: list[Path] = [] 46 worktree = getattr(self, "worktree", None) 47 if worktree: 48 wt_abm = worktree / "mal-core" / "src" / "mal_core" / "abm" 49 if wt_abm.is_dir(): 50 candidate_dirs.append(wt_abm) 51 elif (worktree / "CMakeLists.txt").is_file(): 52 candidate_dirs.append(worktree) 53 else: 54 candidate_dirs.append(wt_abm) 55 pkg_dir = Path(__file__).parent 56 candidate_dirs.append(pkg_dir) 57 58 for base in candidate_dirs: 59 bin_path = base / "bin" / f"mal_abm_fast_{sys.platform}" 60 if bin_path.exists(): 61 return bin_path 62 build_path = base / "build" / "src" / "mal_abm_fast" 63 if build_path.exists(): 64 return build_path 65 66 err_hint = "malariasim abm --compile" 67 if worktree: 68 err_hint += f" --worktree {worktree}" 69 raise FileNotFoundError(f"ABM binary not found. Run: {err_hint}") 70 71 def _introspect_flags(self) -> dict[str, dict[str, Any]]: 72 """Parse the binary's ``--help`` output into a flag schema. 73 74 Returns a mapping of flag name (underscored) to its type, default 75 and help text. An empty mapping is returned when the binary cannot 76 be executed or times out. 77 """ 78 try: 79 result = subprocess.run([str(self.binary), "--help"], capture_output=True, text=True) 80 output = result.stdout + result.stderr 81 except (subprocess.TimeoutExpired, FileNotFoundError): 82 return {} 83 flags: dict[str, dict[str, Any]] = {} 84 for match in re.finditer(r"--([\w-]+)\s+(?:<(\w+)>)?\s*(.*)", output): 85 name = match.group(1).replace("-", "_") 86 ftype = match.group(2) or "bool" 87 desc = match.group(3).strip() 88 tmap = {"int": int, "float": float, "str": str, "string": str, "bool": bool} 89 flags[name] = {"type": tmap.get(ftype, str), "default": None, "help": desc} 90 return flags 91 92 def run(self, _timeout: int | None = None, **flags) -> dict[str, Any]: 93 """Run the binary in its ``run`` subcommand with the given flags. 94 95 Keyword names become dashed command-line flags; ``None`` values are 96 dropped and booleans are passed only when true. 97 98 Returns: 99 A dict with the captured ``stdout``, ``stderr`` and the process 100 ``returncode``. 101 """ 102 if self._flags_schema is None: 103 self._flags_schema = self._introspect_flags() 104 cmd = [str(self.binary), "run"] 105 for name, value in flags.items(): 106 if value is None: 107 continue 108 cli = f"--{name.replace('_', '-')}" 109 if isinstance(value, bool): 110 if value: 111 cmd.append(cli) 112 else: 113 cmd.extend([cli, str(value)]) 114 result = subprocess.run(cmd, capture_output=True, text=True, timeout=_timeout, check=False) 115 return {"stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode} 116 117 def get_flags_schema(self) -> dict[str, dict[str, Any]]: 118 """Return the flag schema of the binary, introspecting it once.""" 119 if self._flags_schema is None: 120 self._flags_schema = self._introspect_flags() 121 return self._flags_schema
Thin Python wrapper that drives the compiled C++ ABM binary.
It locates the binary, translates keyword arguments into the binary's command-line flags and runs it, returning the captured process output.
21 def __init__( 22 self, 23 binary_path: Path | None = None, 24 worktree: str | Path | None = None, 25 ): 26 """Bind the wrapper to a binary, resolving one when none is given. 27 28 Args: 29 binary_path: explicit path to the compiled binary. 30 worktree: root of a worktree whose build directory may hold the 31 binary; used when the installed package does not ship one. 32 """ 33 self.worktree = Path(worktree).resolve() if worktree else None 34 self.binary = binary_path or self._resolve_binary() 35 self._flags_schema: dict[str, dict[str, Any]] | None = None
Bind the wrapper to a binary, resolving one when none is given.
Args: binary_path: explicit path to the compiled binary. worktree: root of a worktree whose build directory may hold the binary; used when the installed package does not ship one.
92 def run(self, _timeout: int | None = None, **flags) -> dict[str, Any]: 93 """Run the binary in its ``run`` subcommand with the given flags. 94 95 Keyword names become dashed command-line flags; ``None`` values are 96 dropped and booleans are passed only when true. 97 98 Returns: 99 A dict with the captured ``stdout``, ``stderr`` and the process 100 ``returncode``. 101 """ 102 if self._flags_schema is None: 103 self._flags_schema = self._introspect_flags() 104 cmd = [str(self.binary), "run"] 105 for name, value in flags.items(): 106 if value is None: 107 continue 108 cli = f"--{name.replace('_', '-')}" 109 if isinstance(value, bool): 110 if value: 111 cmd.append(cli) 112 else: 113 cmd.extend([cli, str(value)]) 114 result = subprocess.run(cmd, capture_output=True, text=True, timeout=_timeout, check=False) 115 return {"stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode}
Run the binary in its run subcommand with the given flags.
Keyword names become dashed command-line flags; None values are
dropped and booleans are passed only when true.
Returns:
A dict with the captured stdout, stderr and the process
returncode.
117 def get_flags_schema(self) -> dict[str, dict[str, Any]]: 118 """Return the flag schema of the binary, introspecting it once.""" 119 if self._flags_schema is None: 120 self._flags_schema = self._introspect_flags() 121 return self._flags_schema
Return the flag schema of the binary, introspecting it once.
72def compile_abm( 73 *, 74 worktree: str | Path | None = None, 75 clean: bool = False, 76 build_type: str = "Release", 77 target: str | None = None, 78 timeout: int | None = None, 79 verbose: bool = False, 80) -> tuple[bool, str]: 81 """Compile the C++ ABM binary (mal_abm_fast). 82 83 Args: 84 worktree: Optional path to a gawt worktree root or ABM source directory. 85 clean: If True, removes the build directory before configuring. 86 build_type: CMake build type ("Release", "Debug", etc.). 87 target: Specific CMake target to build (default: all). 88 timeout: Subprocess timeout in seconds. 89 verbose: If True, enables verbose build output. 90 91 Returns: 92 (success, message_or_binary_path) 93 """ 94 src_dir, build_dir, bin_dir = resolve_abm_dirs(worktree) 95 96 if not (src_dir / "CMakeLists.txt").is_file(): 97 return False, f"CMakeLists.txt not found in {src_dir}" 98 99 cmake_bin = shutil.which("cmake") 100 if not cmake_bin: 101 return False, "CMake executable not found in PATH. Please install CMake." 102 103 if clean and build_dir.exists(): 104 try: 105 shutil.rmtree(build_dir) 106 except OSError as e: 107 return False, f"Failed to clean build directory {build_dir}: {e}" 108 109 # Configure step if CMakeCache.txt does not exist 110 cache_file = build_dir / "CMakeCache.txt" 111 if not cache_file.exists(): 112 build_dir.mkdir(parents=True, exist_ok=True) 113 configure_cmd = [ 114 cmake_bin, 115 "-S", str(src_dir), 116 "-B", str(build_dir), 117 f"-DCMAKE_BUILD_TYPE={build_type}", 118 ] 119 if shutil.which("ninja"): 120 configure_cmd.extend(["-G", "Ninja"]) 121 122 if sys.platform == "darwin": 123 prefixes = _find_macos_prefixes() 124 if prefixes: 125 configure_cmd.append(f"-DCMAKE_PREFIX_PATH={';'.join(prefixes)}") 126 127 try: 128 proc = subprocess.run( 129 configure_cmd, 130 capture_output=True, 131 text=True, 132 timeout=timeout, 133 check=False, 134 ) 135 if proc.returncode != 0: 136 err_msg = proc.stderr.strip() or proc.stdout.strip() 137 return False, f"CMake configuration failed (exit {proc.returncode}):\n{err_msg}" 138 except subprocess.TimeoutExpired: 139 return False, f"CMake configuration timed out after {timeout}s." 140 except OSError as e: 141 return False, f"Failed to execute cmake: {e}" 142 143 # Build step 144 jobs = str(_detect_nproc()) 145 build_cmd = [cmake_bin, "--build", str(build_dir)] 146 if target: 147 build_cmd.extend(["--target", target]) 148 if verbose: 149 build_cmd.append("--verbose") 150 build_cmd.extend(["--", f"-j{jobs}"]) 151 152 try: 153 proc = subprocess.run( 154 build_cmd, 155 capture_output=True, 156 text=True, 157 timeout=timeout, 158 check=False, 159 ) 160 if proc.returncode != 0: 161 err_msg = proc.stderr.strip() or proc.stdout.strip() 162 return False, f"Compilation failed (exit {proc.returncode}):\n{err_msg}" 163 except subprocess.TimeoutExpired: 164 return False, f"Compilation timed out after {timeout}s." 165 except OSError as e: 166 return False, f"Failed to execute cmake build: {e}" 167 168 # Locate the built binary 169 candidate_bins = [ 170 build_dir / "src" / "mal_abm_fast", 171 build_dir / "mal_abm_fast", 172 ] 173 built_bin: Path | None = None 174 for cand in candidate_bins: 175 if cand.is_file(): 176 built_bin = cand 177 break 178 179 if not built_bin: 180 return False, f"Build succeeded but binary not found in {build_dir / 'src'}" 181 182 # Copy binary to bin/mal_abm_fast_<platform> 183 bin_dir.mkdir(parents=True, exist_ok=True) 184 dest_bin = bin_dir / f"mal_abm_fast_{sys.platform}" 185 try: 186 shutil.copy2(built_bin, dest_bin) 187 dest_bin.chmod(0o755) 188 except OSError as e: 189 log.warning("Could not copy binary to %s: %s", dest_bin, e) 190 # Fall back to returning the built binary directly 191 return True, str(built_bin) 192 193 return True, str(dest_bin)
Compile the C++ ABM binary (mal_abm_fast).
Args: worktree: Optional path to a gawt worktree root or ABM source directory. clean: If True, removes the build directory before configuring. build_type: CMake build type ("Release", "Debug", etc.). target: Specific CMake target to build (default: all). timeout: Subprocess timeout in seconds. verbose: If True, enables verbose build output.
Returns: (success, message_or_binary_path)
46def get_abm_dirs(worktree: str | Path | None = None) -> tuple[Path, Path, Path]: 47 """Return (source_dir, build_dir, bin_dir) as absolute Paths.""" 48 return resolve_abm_dirs(worktree)
Return (source_dir, build_dir, bin_dir) as absolute Paths.
22def resolve_abm_dirs(worktree: str | Path | None = None) -> tuple[Path, Path, Path]: 23 """Resolve (source_dir, build_dir, bin_dir) as absolute Paths. 24 25 If worktree is provided, looks for the ABM package inside the worktree 26 (e.g. <worktree>/mal-core/src/mal_core/abm or directly at <worktree>). 27 Otherwise defaults to the installed ABM_PKG_DIR. 28 """ 29 if worktree: 30 wt = Path(worktree).resolve() 31 nested_abm = wt / "mal-core" / "src" / "mal_core" / "abm" 32 if (nested_abm / "CMakeLists.txt").is_file(): 33 src_dir = nested_abm 34 elif (wt / "CMakeLists.txt").is_file(): 35 src_dir = wt 36 else: 37 src_dir = nested_abm 38 else: 39 src_dir = ABM_PKG_DIR 40 41 build_dir = src_dir / "build" 42 bin_dir = src_dir / "bin" 43 return src_dir, build_dir, bin_dir
Resolve (source_dir, build_dir, bin_dir) as absolute Paths.
If worktree is provided, looks for the ABM package inside the worktree
(e.g.
26def run_abm( 27 aoi: str, 28 year: int = 2024, 29 month: int = 1, 30 seed: int = 1, 31 days: int = 30, 32 n_rollouts: int = 1, 33 snapshot_every: int = 7, 34 output_dir: Path | None = None, 35 timeout: int | None = None, 36 worktree: str | Path | None = None, 37 **extra_flags, 38) -> dict[str, Any]: 39 """Run the ABM for a single contiguous period. 40 41 Parameters 42 ---------- 43 aoi : str 44 Area-of-interest slug (e.g. ``"ghana"``). 45 year, month : int 46 Start year and month (1-indexed). 47 seed : int 48 RNG seed. 49 days : int 50 Number of simulation days (max 731 per C++ binary). 51 n_rollouts : int 52 Number of parallel rollouts. 53 snapshot_every : int 54 Write an intermediate ``*_dayNNN.tif`` every N days. 55 Use ``1`` for daily snapshots. 56 output_dir : Path | None 57 Directory for output files. Created if it does not exist. 58 timeout : int 59 Subprocess timeout in seconds (default 600). 60 worktree : str | Path | None 61 Optional path to a gawt worktree root for isolated binary resolution. 62 **extra_flags 63 Forwarded to the C++ binary as CLI flags. 64 65 Returns 66 ------- 67 dict 68 Keys: ``stdout``, ``stderr``, ``returncode``, ``output_path``. 69 """ 70 if days < 1 or days > _CPP_MAX_DAYS: 71 raise ValueError(f"days must be 1..{_CPP_MAX_DAYS}, got {days}") 72 73 wrapper = CppAbmWrapper(worktree=worktree) 74 flags: dict[str, Any] = { 75 "aoi": aoi, 76 "year": year, 77 "month": month, 78 "seed": seed, 79 "days": days, 80 "n_rollouts": n_rollouts, 81 "snapshot_every": snapshot_every, 82 } 83 if output_dir is not None: 84 out = Path(output_dir) 85 out.mkdir(parents=True, exist_ok=True) 86 flags["output"] = str(out / f"{aoi}_abm_seed{seed:04d}.tif") 87 flags.update(extra_flags) 88 89 log.info( 90 "run_abm: %s year=%d month=%d days=%d seed=%d snapshot_every=%d", 91 aoi, year, month, days, seed, snapshot_every, 92 ) 93 return wrapper.run(**flags, _timeout=timeout)
Run the ABM for a single contiguous period.
Parameters
aoi : str
Area-of-interest slug (e.g. "ghana").
year, month : int
Start year and month (1-indexed).
seed : int
RNG seed.
days : int
Number of simulation days (max 731 per C++ binary).
n_rollouts : int
Number of parallel rollouts.
snapshot_every : int
Write an intermediate *_dayNNN.tif every N days.
Use 1 for daily snapshots.
output_dir : Path | None
Directory for output files. Created if it does not exist.
timeout : int
Subprocess timeout in seconds (default 600).
worktree : str | Path | None
Optional path to a gawt worktree root for isolated binary resolution.
**extra_flags
Forwarded to the C++ binary as CLI flags.
Returns
dict
Keys: stdout, stderr, returncode, output_path.
124def run_abm_from_manifest( 125 aoi: str, 126 year: int = 2024, 127 month: int = 1, 128 days: int = 30, 129 seed: int = 1, 130 n_rollouts: int = 1, 131 output_dir: str | Path | None = None, 132 data_root: str | Path | None = None, 133 timeout: int | None = None, 134 worktree: str | Path | None = None, 135 **kwargs, 136) -> dict[str, Any]: 137 """Run ABM using manifest to resolve data paths. 138 139 Reads manifest, validates completeness, resolves paths, 140 then calls the C++ binary via CppAbmWrapper. 141 142 When ``enable_transmission`` is true, the binary also writes a versioned 143 per-run JSONL debug artifact beside its automatic transmission GIF: 144 ``<transmission-GIF-stem>_debug.jsonl`` (for the default output this is 145 ``<aoi>_abm_seedNNNN_transmission_debug.jsonl``). It contains one metadata 146 record and one daily record with compartment counts, bites by host group, 147 and vector seeding/exposure/EIP event counts. This is distinct from the 148 legacy ``emit_transmission_log`` daily summary JSON. 149 """ 150 from mal_core.download.catalog import INGEST_ARTIFACTS, resolve 151 from mal_core.download.manifest import validate_completeness 152 153 data_root = Path(data_root) if data_root else None 154 complete = validate_completeness(aoi, data_root=data_root) 155 if complete: # non-empty list = missing files 156 raise FileNotFoundError( 157 f"Missing required ABM data for AOI '{aoi}': {complete}. " 158 f"Run: malariasim download --aoi {aoi} --all" 159 ) 160 161 data_dir = (data_root or Path("data")) / aoi 162 163 # The C++ engine only knows "ghana" natively; for any other catalog slug 164 # forward the aois.yaml bbox/resolution/scale. Custom slugs keep using the 165 # caller-provided --bbox. 166 catalog_aoi = None 167 if not kwargs.get("bbox"): 168 try: 169 from mal_commonlib.aoi import AOI 170 171 catalog_aoi = AOI.from_slug(str(aoi)) 172 except ValueError: 173 catalog_aoi = None 174 175 env_path = resolve( 176 aoi, INGEST_ARTIFACTS["env"].key, year=year, 177 data_dir=data_dir, data_root=data_root, 178 ) 179 habitat_path = resolve( 180 aoi, INGEST_ARTIFACTS["habitat"].key, data_dir=data_dir, 181 data_root=data_root, 182 ) 183 hosts_path = resolve( 184 aoi, INGEST_ARTIFACTS["host_static"].key, data_dir=data_dir, 185 data_root=data_root, 186 ) 187 wind_path = resolve( 188 aoi, "wind", year=year, data_dir=data_dir, data_root=data_root 189 ) # era5 manifest key ("wind" = wind_6hourly output) 190 mobility_day_path = resolve( 191 aoi, INGEST_ARTIFACTS["mobility_day"].key, data_dir=data_dir, 192 data_root=data_root, 193 ) 194 mobility_night_path = resolve( 195 aoi, INGEST_ARTIFACTS["mobility_night"].key, data_dir=data_dir, 196 data_root=data_root, 197 ) 198 livestock_mobility_path = resolve( 199 aoi, INGEST_ARTIFACTS["livestock_mobility"].key, data_dir=data_dir, 200 data_root=data_root, 201 ) 202 203 if not env_path: 204 raise FileNotFoundError( 205 f"No env data found for AOI '{aoi}', year {year} " 206 f"(manifest key '{INGEST_ARTIFACTS['env'].key}')" 207 ) 208 if not habitat_path: 209 raise FileNotFoundError( 210 f"No habitat data found for AOI '{aoi}' " 211 f"(manifest key '{INGEST_ARTIFACTS['habitat'].key}')" 212 ) 213 214 if output_dir is None: 215 output_dir = Path("runs") / aoi 216 output_dir = Path(output_dir) 217 output_dir.mkdir(parents=True, exist_ok=True) 218 output_path = output_dir / f"{aoi}_abm_seed{seed:04d}.tif" 219 220 flags: dict[str, Any] = { 221 "aoi": aoi, 222 "env": env_path, 223 "habitat": habitat_path, 224 "year": year, 225 "month": month, 226 "days": days, 227 "seed": seed, 228 "n_rollouts": n_rollouts, 229 "snapshot_every": kwargs.pop("snapshot_every", 1), # default daily 230 "output": str(output_path), 231 } 232 cohort_log = kwargs.pop("cohort_log", None) 233 if cohort_log is None: 234 cohort_log = output_dir / f"{aoi}_abm_seed{seed:04d}_cohort.json" 235 flags["emit_cohort_log"] = str(cohort_log) 236 237 if catalog_aoi is not None: 238 flags["bbox"] = ",".join(f"{coord:g}" for coord in catalog_aoi.bbox) 239 flags["resolution_m"] = catalog_aoi.resolution_m 240 flags["scale"] = catalog_aoi.scale.value 241 242 if kwargs.get("enable_transmission") or kwargs.get("enable-transmission"): 243 trans_log = kwargs.pop("emit_transmission_log", None) or kwargs.pop("transmission_log", None) 244 if trans_log is None: 245 trans_log = output_dir / f"{aoi}_abm_seed{seed:04d}_transmission_daily.json" 246 flags["emit_transmission_log"] = str(trans_log) 247 248 if hosts_path: 249 flags["hosts"] = hosts_path 250 if mobility_day_path: 251 flags["human_mobility_day"] = mobility_day_path 252 if mobility_night_path: 253 flags["human_mobility_night"] = mobility_night_path 254 if livestock_mobility_path: 255 flags["livestock_mobility"] = livestock_mobility_path 256 if wind_path: 257 flags["wind_field"] = wind_path 258 259 # Native in-process GIF (plan 04). `gif` arrives in three shapes: 260 # None/False -> no GIF 261 # "" -> bare `--gif`: default `<output_dir>/<aoi>_abm_seedNNNN.gif` 262 # str/Path -> explicit output path, forwarded verbatim 263 # The render knobs are forwarded to the C++ CLI in all enabled cases. 264 # 265 # TRANSMISSION GIF (plan 05): when the run has enable_transmission, the 266 # C++ binary ALSO emits a second, automatic GIF named 267 # `<stem>_transmission.gif` (sibling of the habitat GIF, or of `--output` 268 # when `--gif` is absent). It shares --gif-every/--gif-fps/--gif-max-width 269 # and needs NO new kwarg here — its path is computed inside the binary. 270 # The binary writes the structured sibling `<stem>_transmission_debug.jsonl` 271 # automatically as well; each rollout gets its own seed-suffixed artifact. 272 gif = kwargs.pop("gif", None) 273 if gif is not None and gif is not False: 274 gif_path = ( 275 Path(gif) 276 if isinstance(gif, (str, Path)) and str(gif) != "" 277 else output_dir / f"{aoi}_abm_seed{seed:04d}.gif" 278 ) 279 flags["gif"] = str(gif_path) 280 for key in ("gif_every", "gif_fps", "gif_max_width"): 281 value = kwargs.pop(key, None) 282 if value is not None: 283 flags[key] = value 284 285 flags.update(kwargs) 286 287 log.info("Running ABM for %s (year=%d, seed=%d)", aoi, year, seed) 288 wrapper = CppAbmWrapper(worktree=worktree) 289 result = wrapper.run(**flags, _timeout=timeout) 290 291 return {"output_path": str(output_path), **result}
Run ABM using manifest to resolve data paths.
Reads manifest, validates completeness, resolves paths, then calls the C++ binary via CppAbmWrapper.
When enable_transmission is true, the binary also writes a versioned
per-run JSONL debug artifact beside its automatic transmission GIF:
<transmission-GIF-stem>_debug.jsonl (for the default output this is
<aoi>_abm_seedNNNN_transmission_debug.jsonl). It contains one metadata
record and one daily record with compartment counts, bites by host group,
and vector seeding/exposure/EIP event counts. This is distinct from the
legacy emit_transmission_log daily summary JSON.