MalariaSentinel — C++ reference
The contract-defining headers of the ABM engine
Loading...
Searching...
No Matches
mal_abm_fast Namespace Reference

Classes

struct  AdultsCfg
struct  AOI
struct  AquaticStagesCfg
struct  AquaticStressCfg
struct  CapacityCfg
struct  ConfigError
struct  ContractsCfg
class  CoordinatorModel
struct  DensityGrid
struct  DispersalCfg
struct  EipCfg
struct  GeodesyCfg
struct  GonotrophicCfg
struct  HabitatCfg
class  HabitatEngine
struct  HabitatFeatures
 Static bundle of features read from the env contract (v3.0 planes). More...
struct  HabitatPatch
struct  HostSeekingCfg
struct  IngestCfg
struct  ModelConfig
struct  OvipositionCfg
struct  PairHash
struct  PatchState
struct  PluvialCfg
struct  RngCfg
struct  RuntimeOverrides
struct  SpeciesCfg
struct  SpeciesRow
struct  SuitabilityGrid
struct  ThermalCfg
struct  TransmissionCfg
struct  UrbanCfg

Enumerations

enum class  SpeciesId : std::size_t { FUNESTUS = 0 , GAMBIAE_SS , COLUZZII , ARABIENSIS }

Functions

double EIP_BASE_C ()
double EIP_THRESHOLD_GD ()
double ADULT_DISPERSE_PROB ()
double ADULT_DISPERSE_SIGMA_M ()
double ADULT_DISPERSE_MAX_M ()
double WIND_MIGRATION_PROB ()
double WIND_FLIGHT_HOURS ()
double WIND_SURVIVAL ()
double WIND_FLIGHT_SPEED_MS ()
int HOST_SEEKING_STARVATION_DAYS ()
double OVIPOSITION_SCALE_M ()
double OVIPOSITION_SEEKING_TIMEOUT_DAYS ()
double LARVA_BH_S0 ()
double LARVA_BH_ALPHA ()
double ADULT_DAILY_MORT_BASAL ()
double ADULT_OPT_C ()
double ADULT_SIGMA ()
double ADULT_MORT_CAP ()
double ADULT_MORT_FLOOR ()
double NODATA_SENTINEL ()
double kEarthRadiusM ()
double kMetresPerDegLat ()
std::string CONTRACT_VERSION ()
void write_state_cog (const std::string &path, const DensityGrid &density, const SuitabilityGrid &suit, const StateCogMetadata &meta)
void write_state_sidecar (const std::string &tif_path, const StateCogMetadata &meta)
std::string state_sidecar_path (const std::string &tif_path)
std::vector< std::string > state_reserved_sidecars (const std::string &tif_path)
std::array< float, kNumZoneId > habitat_potential (const HabitatFeatures &f)
float habitat_total_potential (const std::array< float, kNumZoneId > &h)
float update_z_step (float z, float rain_mm, float delta_days)
const char * species_name (SpeciesId id)
std::array< float, kNumZoneId > default_species_weights (SpeciesId s)
std::array< float, kNumZoneId > default_species_weights ()
float species_accuracy (const std::array< float, kNumZoneId > &h, const std::array< float, kNumZoneId > &w, float z_pluvial)
double k_habitat (double s, double cell_area_km2)
double cell_area_km2 (double lat_deg, double cell_size_m)
 Approximate cell area (km²) at a given latitude and edge cell size (m).
const ModelConfig & load_config ()
ModelConfig parse_config_file (const std::string &path)
 Explicit parse of a given path (tests / config_dump tool).
std::string resolve_config_path ()
std::optional< ZoneId > zone_id_of_habitat (const std::string &name)
float habitat_activation_min ()
float habitat_candidate_min_engine ()

Variables

constexpr int STATE_BAND_DENSITY = 1
constexpr int STATE_BAND_SUITABILITY = 2
constexpr const char * STATE_BAND_NAMES [2] = {"adult_patch_count", "adult_cell_count"}
constexpr const char * GENERATOR_VERSION = "proxy_habitat_v1"
constexpr double kPi = 3.14159265358979323846

Detailed Description

SPDX-License-Identifier: MIT wire.hpp — single shared header for the C++ ABM engine (M-perf / mal-abm-fast).

This is the canonical "data contract" header. Every module in mal-abm-fast includes wire.hpp to pick up:

  • the model-constant accessors (EIP thresholds, dispersal kernel, birth rate, the no-data sentinel — all read from model_constants.yaml), the state-band names and the contract / generator version strings
  • the shared value types (AOI, HabitatPatch, PatchState, DensityGrid, SuitabilityGrid)

Historical note: bit-for-bit parity with the retired Python Mesa-Geo engine was the constraining invariant until proxy_habitat_v1 removed the Python engine (plan docs/plans/in-process/redesign/01-retirada-*.md §9). Parity tests compare against the historical baseline outputs.

The wire.hpp header is header-only. The AOI::cells_per_side() method is defined in aoi.hpp (separately compiled into the library, although header-only is also viable).

SPDX-License-Identifier: MIT output_contract.hpp — 2-band state COG writer + sidecar JSON writer.

The state COG is a 2-band GeoTIFF (band 1 = adult_patch_count, band 2 = adult_cell_count), tiled, deflate-compressed, 128x128 blocks, with nodata = NODATA_SENTINEL(). The band names are the single source of truth in wire.hpp (STATE_BAND_NAMES); the values are raw per-cell adult counts — no capacity normalisation. The sidecar JSON is a small metadata file written next to the .tif (e.g. ghana_regional_2024_06_seed0001.json for the COG ghana_regional_2024_06_seed0001.tif).

The sidecar is the F1.e parity test's primary input — it lists contract_version, generator_version, band_names, nodata, etc. (the k_max key was retired with contract 4.0). Two engines producing the same state COG bytes for the same inputs must also produce byte-equal sidecars.

SPDX-License-Identifier: MIT habitat_availability.hpp — the single number (0..1) that determines whether mosquitoes CAN breed in a cell right now. Contract v3.0.

habitat_potential : static per-cell amplitude, six habitat types update_z_step : one-day pluvial recursion (rain-driven) species_accuracy : daily accuracy, affinity × potential × availability k_habitat : absolute per-cell capacity in individual-equivalents

Legacy foreword (plan 01 §7): what was removed is what didn't belong — the pool water balance in mm and its constants, the TWI gate, the urban mm floor, and the urban capacity clamp K_eff. Rain only enters the pluvial reservoir as a forcing; total water is not reconstructed.

The urban persistent supply premise (user-fixed): leaks, seepage, drainage and human water storage support small dry-season breeding supply, represented by urban.beta_urban × lc_built (a proxy, not a measurement, not a forced depth).

SPDX-License-Identifier: MIT habitat_engine.hpp — candidate habitat patches reader (gpkg via OGR).

Contract v3.0: a single-layer OGR Point datasource; the loader reads

  • optional hab_type (string; accepted without filtering)
  • optional habitat_potential (float, [0,1]; default = full potential)
  • optional dynamics (int; 0 = persistent, 1 = pluvial)
  • optional row, col (int32; pre-computed cell index)
  • the Point geometry (lon, lat) Features below the habitat.candidate_min_engine floor are dropped.

SPDX-License-Identifier: MIT coordinator.hpp — Mesa-Geo half of the C++ ABM (the spatial layer).

Contract v3.0 (proxy_habitat_v1): the coordinator owns

  • the AOI (cell geometry + transform)
  • the ClimateEngine (env NC reader: daily rainfall + air temperature, five static habitat planes)
  • the HabitatEngine (candidate-patch gpkg reader)
  • a Prng (the per-rollout sub-stream; derived from --seed)
  • the shared temporal responses (one pluvial state z per cell, warm-up-integrated causally over the env-NC bands before the simulation start) and the per-cell species-neutral daily capacity K[i, t] = K_ref * cell_area_km2 * S[i, t]

There is NO per-patch water-balance solver, NO TWI gate, NO urban mm-floor and NO ndvi channel (plan docs/plans/in-process/redesign/ 01-retirada-hidrologia-dem-escorrentia.md §6-§8).

Per-day contract (matching the retired Python engine's surface):

  1. coordinator.update_habitat_day() — z/S/K update from rain
  2. patch_states = coordinator.to_dataframe()
  3. submodel.advance_day(aoi, patch_states)
  4. density/suitability aggregation
  5. coordinator.write_state_cog(...)

SPDX-License-Identifier: MIT config.hpp — single model-constants source for the C++ engine (plan constants-yaml §4). mal-core/config/model_constants.yaml is the ONLY source of shared py⇄C++ parameters. The loader:

  • parses a PLAIN YAML SUBSET with a hand-written micro-parser (no yaml-cpp dependency; see config.cc SupportedSubsetData rules);
  • fails LOUDLY: missing keys are reported as a COMPLETE list, unknown keys (typos) are an error, wrong types are an error, duplicate keys inside the file are an error;
  • embeds NO default for any model key — the YAML is the source;
  • pre-transforms species weight rows by habitat NAME → ZoneId once at load time (the day-loop consumes a plain std::array);
  • derives num_persistent from habitat_types.dynamics (no "the first three are persistent" positional rule).

singleton: load_config() reads once per process (env MAL_MODEL_CONSTANTS overrides the default search).

Enumeration Type Documentation

◆ SpeciesId

enum class mal_abm_fast::SpeciesId : std::size_t
strong

– species affinities ----------------------------------------------------— Species affinity w[s, g]; each row sums to 1. Anchored on 1.0 × the plant list (order, habitat-preference context; plan 02 §8).

Function Documentation

◆ ADULT_DAILY_MORT_BASAL()

double mal_abm_fast::ADULT_DAILY_MORT_BASAL ( )
inline

Basal daily survival probability of adult mosquitoes (config key: adults.daily_mort_basal); the key name is historical — it holds a survival probability, not a mortality rate.

◆ ADULT_DISPERSE_MAX_M()

double mal_abm_fast::ADULT_DISPERSE_MAX_M ( )
inline

Radius at which the Gaussian adult dispersal step is clipped to a disc, in metres (config key: dispersal.adult_max_m).

◆ ADULT_DISPERSE_PROB()

double mal_abm_fast::ADULT_DISPERSE_PROB ( )
inline

Daily probability that an adult mosquito disperses, in 1/day (config key: dispersal.adult_prob_day).

◆ ADULT_DISPERSE_SIGMA_M()

double mal_abm_fast::ADULT_DISPERSE_SIGMA_M ( )
inline

Standard deviation of the isotropic Gaussian adult dispersal step, in metres (config key: dispersal.adult_sigma_m).

◆ ADULT_MORT_CAP()

double mal_abm_fast::ADULT_MORT_CAP ( )
inline

Upper clamp applied to the computed daily adult survival probability, a fraction in [0,1] (config key: adults.mort_cap).

◆ ADULT_MORT_FLOOR()

double mal_abm_fast::ADULT_MORT_FLOOR ( )
inline

Lower clamp applied to the computed daily adult survival probability, a fraction in [0,1] (config key: adults.mort_floor).

◆ ADULT_OPT_C()

double mal_abm_fast::ADULT_OPT_C ( )
inline

Centre of the Gaussian thermal survival curve of adults, in degrees Celsius (config key: adults.opt_c).

◆ ADULT_SIGMA()

double mal_abm_fast::ADULT_SIGMA ( )
inline

Width of the Gaussian thermal survival curve of adults, in degrees Celsius (config key: adults.sigma_c).

◆ CONTRACT_VERSION()

std::string mal_abm_fast::CONTRACT_VERSION ( )
inline

Version string of the state-COG + sidecar contract, written into the sidecar JSON so consumers can gate on it (config key: contracts.cogs_state).

◆ default_species_weights() [1/2]

std::array< float, kNumZoneId > mal_abm_fast::default_species_weights ( )
inline

Species-neutral default (single-engine runs): the neutral row loaded from model_constants.yaml (species.neutral.weights).

◆ default_species_weights() [2/2]

std::array< float, kNumZoneId > mal_abm_fast::default_species_weights ( SpeciesId s)
inline

One vector per species; each row sums to 1.0 (plan 02 §8 calibration). Loaded BY NAME from model_constants.yaml (species.<name>.weights), pre-transformed at load time to ZoneId order.

◆ EIP_BASE_C()

double mal_abm_fast::EIP_BASE_C ( )
inline

Values live in mal-core/config/model_constants.yaml; accessors read the load_config() singleton (plan constants-yaml §4 — no compiled defaults).

◆ EIP_THRESHOLD_GD()

double mal_abm_fast::EIP_THRESHOLD_GD ( )
inline

Infectivity threshold of the extrinsic incubation period, in growing-degree days (config key: eip.threshold_gd); a mosquito is infective once its accumulated EIP progress reaches it.

◆ habitat_activation_min()

float mal_abm_fast::habitat_activation_min ( )
inline

Habitat-accuracy threshold S above which a cell counts as a live (activated) patch; reads habitat.activation_min_engine from the configuration singleton.

◆ habitat_candidate_min_engine()

float mal_abm_fast::habitat_candidate_min_engine ( )
inline

Habitat-potential floor a cell must clear to become a candidate patch; reads habitat.candidate_min_engine from the configuration singleton.

◆ habitat_potential()

std::array< float, kNumZoneId > mal_abm_fast::habitat_potential ( const HabitatFeatures & f)
inline

Assemble H[i, g] (the static potential in [0,1] per habitat type) from the feature bundle. One explicit rule per habitat type.

◆ habitat_total_potential()

float mal_abm_fast::habitat_total_potential ( const std::array< float, kNumZoneId > & h)
inline

Total static amplitude of the cell: sum_g H[i, g] capped on 1. Used by the candidate floor (the urban_capacity_factor consumer retired with contract 4.0).

◆ HOST_SEEKING_STARVATION_DAYS()

int mal_abm_fast::HOST_SEEKING_STARVATION_DAYS ( )
inline

Maximum number of days a female may remain in the HOST_SEEKING state without finding a host before she is killed by starvation (config key: host_seeking.starvation_days).

◆ k_habitat()

double mal_abm_fast::k_habitat ( double s,
double cell_area_km2 )
inline

Absolute capacity (individual-equivalent units; plan §5.4): K[i, s, t] = K_ref[s] * cell_area_km2 * S[i, s, t] cell_area_km2 handles cut AOI edge cells; the return is a plain multiplier the cohort bank uses as-is (ABSOLUTE K — not K_MAX × f, the removed urban clamp).

◆ kEarthRadiusM()

double mal_abm_fast::kEarthRadiusM ( )
inline

Mean Earth radius used by the geodesy helpers, in metres (config key: geodesy.earth_radius_m).

◆ kMetresPerDegLat()

double mal_abm_fast::kMetresPerDegLat ( )
inline

Metres covered by one degree of latitude, used to convert metric offsets into degrees (config key: geodesy.metres_per_deg_lat).

◆ LARVA_BH_ALPHA()

double mal_abm_fast::LARVA_BH_ALPHA ( )
inline

Competition coefficient of the Beverton-Holt larval density-dependence, dimensionless (config key: aquatic_stages.larva_bh_alpha).

◆ LARVA_BH_S0()

double mal_abm_fast::LARVA_BH_S0 ( )
inline

Basal daily survival of larvae in the absence of density dependence, a fraction in [0,1] (config key: aquatic_stages.larva_bh_s0).

◆ load_config()

const ModelConfig & mal_abm_fast::load_config ( )

Parse + validate the model constants YAML (singleton; loads once). Throws ConfigError with the full missing/unknown/type lists.

◆ NODATA_SENTINEL()

double mal_abm_fast::NODATA_SENTINEL ( )
inline

Value written into NoData pixels of the raster outputs (state COG, transmission GeoTIFF, env NC), in the units of the band (config key: ingest.nodata_sentinel).

◆ OVIPOSITION_SCALE_M()

double mal_abm_fast::OVIPOSITION_SCALE_M ( )
inline

E-folding length of the breeding-site attraction plume around a habitat patch, in metres (config key: oviposition.scale_m).

◆ OVIPOSITION_SEEKING_TIMEOUT_DAYS()

double mal_abm_fast::OVIPOSITION_SEEKING_TIMEOUT_DAYS ( )
inline

Number of days a female may spend walking towards a breeding site before she gives up and returns to HOST_SEEKING without ovipositing (config key: oviposition.timeout_days).

◆ resolve_config_path()

std::string mal_abm_fast::resolve_config_path ( )

Resolve the constants path: MAL_MODEL_CONSTANTS env override, else a search upward from the executable directory (bin/config/model_constants.yaml, ../config/, ../../config/, mal-core/config/). Throws when nothing found.

◆ species_accuracy()

float mal_abm_fast::species_accuracy ( const std::array< float, kNumZoneId > & h,
const std::array< float, kNumZoneId > & w,
float z_pluvial )
inline

– the day formula -------------------------------------------------------— Static sum_k w[g] * H[*, g] * A[*, k] accuracy: persistent habitats ride at capacity.persistent_availability (A = that constant whenever their potential > 0); pluvial habitats use the rain-driven z. No path takes S above 1.

◆ species_name()

const char * mal_abm_fast::species_name ( SpeciesId id)
inline

Configuration key of a species: the name under which its affinity row lives in model_constants.yaml (species.<name>.weights). Returns "unknown" for an out-of-range id.

◆ state_reserved_sidecars()

std::vector< std::string > mal_abm_fast::state_reserved_sidecars ( const std::string & tif_path)

Every JSON file the engine reserves next to a state COG: the metadata sidecar plus the _aquatic.json and _foci.json diagnostics. The CLI rejects a transmission log that would overwrite any of them.

◆ state_sidecar_path()

std::string mal_abm_fast::state_sidecar_path ( const std::string & tif_path)

Path of the sidecar written next to a state COG: .tif -> .json (case-insensitive), otherwise <path>.json. Exposed so the CLI can refuse an --emit-transmission-log path that would be overwritten by the state sidecar (task-06 decision 5).

◆ update_z_step()

float mal_abm_fast::update_z_step ( float z,
float rain_mm,
float delta_days )
inline

One-day pluvial recursion (rain-driven; contract v3.0 floors of the two-forcing design). Called per-step and during warm-up.

z_dry = z * exp(-delta_days / pluvial.dry_memory_days) z = z_dry + (1 - z_dry) * (1 - exp(-rain_mm / pluvial.rain_scale_mm))

◆ WIND_FLIGHT_HOURS()

double mal_abm_fast::WIND_FLIGHT_HOURS ( )
inline

Duration of the windborne flight, in hours (config key: dispersal.wind_flight_hours).

◆ WIND_FLIGHT_SPEED_MS()

double mal_abm_fast::WIND_FLIGHT_SPEED_MS ( )
inline

Self-propelled flight speed added to the wind speed during the windborne flight, in m/s (config key: dispersal.wind_self_speed_ms).

◆ WIND_MIGRATION_PROB()

double mal_abm_fast::WIND_MIGRATION_PROB ( )
inline

Daily probability that a gravid female attempts a windborne migration, in 1/day (config key: dispersal.wind_migration_prob).

◆ WIND_SURVIVAL()

double mal_abm_fast::WIND_SURVIVAL ( )
inline

Probability that a mosquito survives the windborne flight, a fraction in [0,1] (config key: dispersal.wind_survival).

◆ write_state_cog()

void mal_abm_fast::write_state_cog ( const std::string & path,
const DensityGrid & density,
const SuitabilityGrid & suit,
const StateCogMetadata & meta )

Write the 2-band state COG. The implementation subagent uses GDAL (GTiff driver) with:

  • tiled = true
  • compress = deflate
  • blockxsize = blockysize = 128
  • nodata = NODATA_SENTINEL()
  • band descriptions = band_names[0], band_names[1]

Returns the .tif path on success. Throws std::runtime_error on GDAL failure.

◆ write_state_sidecar()

void mal_abm_fast::write_state_sidecar ( const std::string & tif_path,
const StateCogMetadata & meta )

Write the sidecar JSON (e.g. <tif_path>.json for a .tif path). The keys in the JSON are the parity test's contract: the writer emits them in the fixed order below (the order is part of the contract, so that two engines produce byte-equal sidecars). The contract version itself comes from model_constants.yaml (contracts.cogs_state).

◆ zone_id_of_habitat()

std::optional< ZoneId > mal_abm_fast::zone_id_of_habitat ( const std::string & name)

Habitat-type name → ZoneId (static mapping table; throws ConfigError on an unknown name). wetland_pluvial has NO ZoneId — nullopt.

Variable Documentation

◆ GENERATOR_VERSION

const char* mal_abm_fast::GENERATOR_VERSION = "proxy_habitat_v1"
inlineconstexpr

Contract and generator version strings — written into the sidecar JSON and used by the Python parity test (F1.e) to verify engine equivalence.

CONTRACT_VERSION bumped to "1.1" in F1.c, to "2.0" in M7.1+M7.2, to "3.0" with proxy_habitat_v1 (contract docs/plans/in-process/ redesign/02-oferta-criaderos-proxies-download-ingest-abm.md §5: the ingested env NC planes and the habitat gpkg schema changed), and to "4.0" with the K_MAX retirement (plan 03-retirada-k-max): the state COG bands are raw per-cell adult counts, the sidecar no longer carries k_max, and the band names changed. Consumers must version-gate on the sidecar string.

◆ kPi

double mal_abm_fast::kPi = 3.14159265358979323846
inlineconstexpr

Inline method definitions

AOI::cells_per_side — number of cells along the east-west axis (WIDTH). The full derivation lives here (rather than in aoi.hpp) so that every translation unit pulling in wire.hpp sees the inline definition and the linker does not have to find a separate .cpp definition. aoi.hpp contains the related free function cells_per_side_h (H dimension).

Parity with the Python reference (mal_commonlib.aoi.AOI.cells_per_side): m_per_deg_lat = π · R / 180 from geodesy.* (WGS84 mean Earth radius) width_m = (east - west) * m_per_deg_lat * cos(centroid_lat_rad) cells_per_side = ceil(width_m / resolution_m) (NOT lround — see parity note)

F1.b parity note: Python's mal_commonlib.aoi.AOI.cells_per_side uses math.ceil (not round); we use std::ceil to match. For the Ghana regional AOI both formulas agree; for AOIs near a cell boundary the rounding mode diverges.

◆ STATE_BAND_DENSITY

int mal_abm_fast::STATE_BAND_DENSITY = 1
inlineconstexpr

Adult daily mortality: thermo-dependent survival with a basal cap (values in adults.*; formula in mosquito_submodel.cpp). Temperature NaN policy (2026-10-13): the legacy per-lookup temperature fallback constant was removed. Out-of-coverage / sea-mask NaN pixels in the env NC water_temp_c channel are imputed at load time by neighbor-mean wavefront fill (climate.cpp impute_temp_nans) — each imputed cell inherits the same day's spatial temperature field, so it tracks the seasonal cycle instead of pinning a fixed value year-round (the fixed fallback put out-of-place values on coastal/edge cells in hot and cold seasons). temp_at() clamps off-grid (row, col) to the border cell; the only remaining fallback is a documented degenerate-engine guard for an all-NaN slice or an unloaded engine. Larva desiccation: grace + daily rate live in aquatic_stress.* (see aquatic_stress.hpp). proxy_habitat_v1: habitat availability is the static H[i, g] over the six habitat types; the biological stress bits (rain wash, desiccation) live in aquatic_stress.hpp. No-data sentinel for the 2-band state COG. State COG band identifiers. Contract 4.0: both bands are RAW per-cell adult counts (individuals), NOT normalized by any capacity constant (K_MAX retired). In order: band 1 (STATE_BAND_DENSITY) — adults associated with each cell via their patch (post-dispersal) band 2 (STATE_BAND_SUITABILITY) — adults counted at their current position (lon/lat snap)

◆ STATE_BAND_NAMES

const char* mal_abm_fast::STATE_BAND_NAMES[2] = {"adult_patch_count", "adult_cell_count"}
inlineconstexpr

Band names of the state COG, indexed by band number minus one; written as the GDAL band descriptions of the output COG (contract 4.0).

◆ STATE_BAND_SUITABILITY

int mal_abm_fast::STATE_BAND_SUITABILITY = 2
inlineconstexpr

Band 2 of the state COG: raw per-cell count of adults at their current position (contract 4.0).