mal_core.habitat.config

Thin loader of the single model constants YAML (plan constants-yaml §3).

mal-core/config/model_constants.yaml is the ONLY source of shared model parameters (py ⇄ C++). Schema and invariant checking live in ONE place: mal_core.config_validation (R2). This module only:

  • resolves the path (explicit > MAL_MODEL_CONSTANTS > default),
  • delegates validation to mal_core.config_validation.validate_model_config(),
  • exposes the validated tree as an immutable MappingProxyType singleton,
  • derives the ordered habitat names / dynamics helpers.

There are NO silent fallbacks and NO model-constant defaults here: the validator fails loudly and lists every problem in the file.

  1"""Thin loader of the single model constants YAML (plan constants-yaml §3).
  2
  3``mal-core/config/model_constants.yaml`` is the ONLY source of shared
  4model parameters (py ⇄ C++).  Schema and invariant checking live in ONE
  5place: :mod:`mal_core.config_validation` (R2).  This module only:
  6
  7* resolves the path (explicit > ``MAL_MODEL_CONSTANTS`` > default),
  8* delegates validation to :func:`mal_core.config_validation.validate_model_config`,
  9* exposes the validated tree as an immutable ``MappingProxyType`` singleton,
 10* derives the ordered habitat names / dynamics helpers.
 11
 12There are NO silent fallbacks and NO model-constant defaults here: the
 13validator fails loudly and lists every problem in the file.
 14"""
 15from __future__ import annotations
 16
 17import os
 18import types
 19from typing import Any
 20
 21from ..config_validation import (
 22    DEFAULT_PATH,
 23    ENV_VAR,
 24    SCHEMA,
 25    ConfigError,
 26    SchemaError,
 27    freeze,
 28    resolve_path,
 29    validate_model_config,
 30)
 31
 32__all__ = [
 33    "ConfigError",
 34    "SchemaError",
 35    "CONFIG",
 36    "SCHEMA",
 37    "ENV_VAR",
 38    "DEFAULT_PATH",
 39    "resolve_path",
 40    "load_config",
 41    "dump_raw",
 42    "habitat_names",
 43    "dynamics_map",
 44    "persistent_names",
 45    "pluvial_names",
 46]
 47
 48
 49def load_config(path: str | os.PathLike[str] | None = None) -> types.MappingProxyType:
 50    """Load + validate the model constants YAML (see module docstring)."""
 51    return freeze(validate_model_config(path).model_dump())
 52
 53
 54# Derived API (plan §3.) ---------------------------------------------------
 55
 56def dump_raw(path: str | os.PathLike[str] | None = None) -> dict[str, Any]:
 57    """Flat "dotted"-key view (plan §6 test 4) for the py⇄C++ parity test.
 58
 59    Species weight rows are emitted as LISTS in the canonical habitat
 60    order (the pre-transformed C++ std::array shape). Compare key-by-key
 61    (numeric tolerance 1e-9) against ``config_dump``'s JSON.
 62    """
 63    data = dict(load_config(path)) if path is not None else dict(CONFIG)
 64    types_list = data["habitat_types"]["types"]
 65    out: dict[str, Any] = {}
 66    out["version"] = data["version"]
 67    for k, v in data["contracts"].items():
 68        out[f"contracts.{k}"] = v
 69    for i, name in enumerate(types_list):
 70        out[f"habitat_types.types.{i}"] = name
 71    for k, v in data["habitat_types"]["dynamics"].items():
 72        out[f"habitat_types.dynamics.{k}"] = v
 73    out["habitat_types.num_persistent"] = sum(
 74        1 for v in data["habitat_types"]["dynamics"].values()
 75        if v == "persistent")
 76    for sec in ("habitat", "pluvial", "aquatic_stress", "urban", "capacity",
 77                "geodesy"):
 78        for k, v in data[sec].items():
 79            out[f"{sec}.{k}"] = v
 80    out["species.default_species"] = data["species"]["default_species"]
 81    out["species.k_ref"] = data["species"]["k_ref"]
 82    for name, row in data["species"].items():
 83        if name in ("default_species", "k_ref"):
 84            continue
 85        if "weights" not in row:
 86            continue
 87        out[f"species.{name}.weights"] = [
 88            float(row["weights"][g]) for g in types_list]
 89        for k in ("salinity_hi_tol_ppt", "host_seeking_scale_m",
 90                  "host_seeking_radius_m", "salinity_opt_ppt",
 91                  "salinity_slope"):
 92            if k in row:
 93                out[f"species.{name}.{k}"] = row[k]
 94        if "activity_weights" in row:
 95            out[f"species.{name}.activity_weights"] = [
 96                float(v) for v in row["activity_weights"]]
 97        if "pref" in row:
 98            # Parity with the C++ dump: the pref row as a HostType-ordered
 99            # array (human, cattle, goat, sheep, wildlife).
100            out[f"species.{name}.pref"] = [
101                float(row["pref"][h]) for h in
102                ("human", "cattle", "goat", "sheep", "wildlife")]
103    # Engine-consumed sections. ``wildlife`` is deliberately absent: it is a
104    # py-only input-loader section with no C++ consumer or config_dump entry
105    # (task-08), so emitting it would break the py⇄C++ key parity contract.
106    for sec in ("ingest", "adults", "eip", "transmission", "dispersal",
107                "host_seeking", "oviposition", "aquatic_stages", "thermal",
108                "gonotrophic", "rng"):
109        for k, v in data[sec].items():
110            out[f"{sec}.{k}"] = v
111    return out
112
113
114def habitat_names() -> tuple[str, ...]:
115    """Ordered habitat type names (frozen habitat_types.types)."""
116    return tuple(CONFIG["habitat_types"]["types"])
117
118
119def dynamics_map() -> dict[str, str]:
120    """Habitat type -> dynamics label (persistent|pluvial)."""
121    return dict(CONFIG["habitat_types"]["dynamics"])
122
123
124def persistent_names() -> frozenset[str]:
125    """Derived habitat subsets (replaces the old PERSISTENT_TYPES const)."""
126    return frozenset(
127        g for g, k in dynamics_map().items() if k == "persistent")
128
129
130def pluvial_names() -> frozenset[str]:
131    """Derived habitat subsets (replaces the old PLUVIAL_TYPES const)."""
132    return frozenset(
133        g for g, k in dynamics_map().items() if k == "pluvial")
134
135
136CONFIG = load_config()
class ConfigError(builtins.Exception):
100class ConfigError(Exception):
101    """Base class of model-constants failures."""

Base class of model-constants failures.

class SchemaError(mal_core.habitat.config.ConfigError):
104class SchemaError(ConfigError):
105    """The YAML does not satisfy the declared schema/invariants."""

The YAML does not satisfy the declared schema/invariants.

CONFIG = mappingproxy({'version': 2, 'contracts': mappingproxy({'env_nc': '3.0', 'cogs_state': '4.0'}), 'habitat_types': mappingproxy({'types': ['surface_persistent', 'wetland_persistent', 'urban_persistent', 'wetland_pluvial', 'open_pluvial', 'crop_pluvial'], 'dynamics': mappingproxy({'surface_persistent': 'persistent', 'wetland_persistent': 'persistent', 'urban_persistent': 'persistent', 'wetland_pluvial': 'pluvial', 'open_pluvial': 'pluvial', 'crop_pluvial': 'pluvial'})}), 'habitat': mappingproxy({'activation_min_engine': 0.01, 'candidate_min_engine': 0.01}), 'pluvial': mappingproxy({'rain_scale_mm': 2.5, 'dry_memory_days': 5.0, 'delta_days': 1.0, 'cold_start_z': 0.0}), 'aquatic_stress': mappingproxy({'desicc_grace_days': 5.0, 'desicc_base_daily': 0.1, 'desicc_ramp_decay': 0.3, 'wash_threshold_mm': 40.0, 'wash_fraction_max': 0.6, 'vulnerable_instar_max': 2}), 'urban': mappingproxy({'beta_urban': 0.75, 'rain_pools_built_damage': 0.3}), 'species': mappingproxy({'default_species': 'coluzzii', 'k_ref': 50.0, 'coluzzii': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.4, 'wetland_persistent': 0.1, 'urban_persistent': 0.2, 'wetland_pluvial': 0.0, 'open_pluvial': 0.25, 'crop_pluvial': 0.05}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.99, 'cattle': 0.005, 'goat': 0.003, 'sheep': 0.001, 'wildlife': 0.001}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 30.0, 'salinity_slope': 0.08, 'host_seeking_scale_m': 300.0, 'host_seeking_radius_m': 1500.0}), 'gambiae_ss': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.05, 'wetland_persistent': 0.05, 'urban_persistent': 0.15, 'wetland_pluvial': 0.0, 'open_pluvial': 0.65, 'crop_pluvial': 0.1}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.99, 'cattle': 0.005, 'goat': 0.003, 'sheep': 0.001, 'wildlife': 0.001}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 20.0, 'salinity_slope': 0.12, 'host_seeking_scale_m': 300.0, 'host_seeking_radius_m': 1500.0}), 'funestus': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.45, 'wetland_persistent': 0.3, 'urban_persistent': 0.1, 'wetland_pluvial': 0.0, 'open_pluvial': 0.1, 'crop_pluvial': 0.05}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.99, 'cattle': 0.005, 'goat': 0.003, 'sheep': 0.001, 'wildlife': 0.001}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 15.0, 'salinity_slope': 0.15, 'host_seeking_scale_m': 300.0, 'host_seeking_radius_m': 1500.0}), 'arabiensis': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.1, 'wetland_persistent': 0.1, 'urban_persistent': 0.15, 'wetland_pluvial': 0.0, 'open_pluvial': 0.55, 'crop_pluvial': 0.1}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.5, 'cattle': 0.2, 'goat': 0.15, 'sheep': 0.1, 'wildlife': 0.05}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 15.0, 'salinity_slope': 0.15, 'host_seeking_scale_m': 120.0, 'host_seeking_radius_m': 1500.0}), 'melas': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.25, 'wetland_persistent': 0.15, 'urban_persistent': 0.15, 'wetland_pluvial': 0.0, 'open_pluvial': 0.4, 'crop_pluvial': 0.05}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.99, 'cattle': 0.005, 'goat': 0.003, 'sheep': 0.001, 'wildlife': 0.001}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 38.0, 'salinity_slope': 0.02, 'host_seeking_scale_m': 300.0, 'host_seeking_radius_m': 1500.0}), 'stephensi': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.25, 'wetland_persistent': 0.15, 'urban_persistent': 0.15, 'wetland_pluvial': 0.0, 'open_pluvial': 0.4, 'crop_pluvial': 0.05}), 'activity_weights': [0.02, 0.1, 0.8, 0.08], 'pref': mappingproxy({'human': 0.7, 'cattle': 0.15, 'goat': 0.05, 'sheep': 0.05, 'wildlife': 0.05}), 'salinity_opt_ppt': 0.0, 'salinity_hi_tol_ppt': 20.0, 'salinity_slope': 0.15, 'host_seeking_scale_m': 300.0, 'host_seeking_radius_m': 1500.0}), 'neutral': mappingproxy({'weights': mappingproxy({'surface_persistent': 0.25, 'wetland_persistent': 0.15, 'urban_persistent': 0.15, 'wetland_pluvial': 0.0, 'open_pluvial': 0.4, 'crop_pluvial': 0.05})})}), 'capacity': mappingproxy({'persistent_availability': 1.0}), 'geodesy': mappingproxy({'earth_radius_m': 6371008.8, 'metres_per_deg_lat': 111195.08023353292}), 'ingest': mappingproxy({'nodata_sentinel': -9999.0, 'nodata_sentinel_int': -9999, 'residential_from_indoor_frac': 0.8, 'coastline_buffer_m': 2000.0, 'coastline_resolution': 'f', 'sea_water_floor': 0.05, 'cell_size_hint_m': 1000.0, 'candidate_min_ingest': 1e-06, 'min_dilation_radius_cells': 1, 'fill_frac_valid_max': 0.5, 'ocean_mask_threshold': 0.5, 'land_mask_threshold': 0.5, 'valid_count_epsilon': 1e-09, 'grid_degrees_step_max': 1, 'nc_compression_level': 4}), 'wildlife': mappingproxy({'class_suitability': mappingproxy({'water': 0.0, 'trees': 0.9, 'grass': 0.6, 'flooded_vegetation': 0.45, 'crops': 0.3, 'shrub_and_scrub': 0.7, 'built': 0.05, 'bare': 0.2, 'snow_and_ice': 0.1}), 'weights': mappingproxy({'habitat': 0.5, 'water': 0.3, 'remoteness': 0.2})}), 'adults': mappingproxy({'daily_mort_basal': 0.87, 'opt_c': 25.0, 'sigma_c': 15.0, 'mort_cap': 0.93, 'mort_floor': 0.6}), 'eip': mappingproxy({'base_c': 16.0, 'threshold_gd': 110.0}), 'transmission': mappingproxy({'beta_hv': 0.4, 'beta_vh': 0.5, 'human_incubation_days': 12, 'human_infectious_days': 20, 'human_immunity_days': 180, 'initial_human_prevalence': 0.05, 'initial_vector_infected_frac': 0.0}), 'dispersal': mappingproxy({'adult_prob_day': 0.05, 'adult_sigma_m': 450.0, 'adult_max_m': 2000.0, 'wind_migration_prob': 0.05, 'wind_flight_hours': 4.0, 'wind_survival': 0.85, 'wind_self_speed_ms': 1.0, 'flight_hour': 20, 'host_flight_step_m': 500.0, 'snap_radius_m': 500.0, 'night_start_hour': 18, 'night_end_hour': 6}), 'host_seeking': mappingproxy({'starvation_days': 7, 'indoor_attraction_add': 0.72, 'urbanicity_add': 0.2, 'indoor_fraction_urban': 0.72, 'indoor_fraction_rural': 0.3, 'detect_range_m': 2000.0, 'approach_step_m': 50.0}), 'oviposition': mappingproxy({'scale_m': 50.0, 'detect_range_m': 2000.0, 'step_m': 50.0, 'min_attraction': 0.3, 'timeout_days': 7}), 'aquatic_stages': mappingproxy({'egg_daily_mort': 0.08, 'pupa_daily_mort': 0.05, 'larva_bh_s0': 0.95, 'larva_bh_alpha': 0.05, 'last_larval_instar': 4, 'salinity_missing_psu': 0.0}), 'thermal': mappingproxy({'efd_max_eggs_per_day': 0.5, 'efd_tmin_c': 16.0, 'efd_tmax_c': 34.0, 'efd_topt_c': 25.0, 'egg_development_tmin_c': 10.0, 'egg_development_tmax_c': 40.0, 'egg_development_scale': 0.00062, 'larva_development_tmin_c': 10.0, 'larva_development_tmax_c': 40.0, 'larva_development_scale': 0.001, 'pupa_development_tmin_c': 12.0, 'pupa_development_tmax_c': 40.0, 'pupa_development_scale': 0.00066}), 'gonotrophic': mappingproxy({'cycle_duration_days': 2.0, 'first_cycle_days': 4.0, 'feeding_success_rate': 0.825, 'egg_batch_mean': 120, 'egg_batch_n': 240, 'egg_batch_min': 30, 'egg_batch_max': 170, 'resting_duration_days': 0.5}), 'rng': mappingproxy({'aquatic_seed_washout': 789, 'aquatic_seed_stage_mortality': 42, 'aquatic_seed_larva_mortality': 123})})
SCHEMA = {'version': <class 'int'>, 'contracts': {'env_nc': <class 'str'>, 'cogs_state': <class 'str'>}, 'habitat_types': {'types': list[str], 'dynamics': dict[str, typing.Literal['persistent', 'pluvial']]}, 'habitat': {'activation_min_engine': <class 'float'>, 'candidate_min_engine': <class 'float'>}, 'pluvial': {'rain_scale_mm': <class 'float'>, 'dry_memory_days': <class 'float'>, 'delta_days': <class 'float'>, 'cold_start_z': <class 'float'>}, 'aquatic_stress': {'desicc_grace_days': <class 'float'>, 'desicc_base_daily': <class 'float'>, 'desicc_ramp_decay': <class 'float'>, 'wash_threshold_mm': <class 'float'>, 'wash_fraction_max': <class 'float'>, 'vulnerable_instar_max': <class 'int'>}, 'urban': {'beta_urban': <class 'float'>, 'rain_pools_built_damage': <class 'float'>}, 'species': {'default_species': <class 'str'>, 'k_ref': <class 'float'>, 'coluzzii': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'gambiae_ss': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'funestus': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'arabiensis': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'melas': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'stephensi': {'weights': dict[str, float], 'activity_weights': list[float], 'pref': dict[str, float], 'salinity_opt_ppt': <class 'float'>, 'salinity_hi_tol_ppt': <class 'float'>, 'salinity_slope': <class 'float'>, 'host_seeking_scale_m': <class 'float'>, 'host_seeking_radius_m': <class 'float'>}, 'neutral': {'weights': dict[str, float]}}, 'capacity': {'persistent_availability': <class 'float'>}, 'geodesy': {'earth_radius_m': <class 'float'>, 'metres_per_deg_lat': <class 'float'>}, 'ingest': {'nodata_sentinel': <class 'float'>, 'nodata_sentinel_int': <class 'int'>, 'residential_from_indoor_frac': <class 'float'>, 'coastline_buffer_m': <class 'float'>, 'coastline_resolution': <class 'str'>, 'sea_water_floor': <class 'float'>, 'cell_size_hint_m': <class 'float'>, 'candidate_min_ingest': <class 'float'>, 'min_dilation_radius_cells': <class 'int'>, 'fill_frac_valid_max': <class 'float'>, 'ocean_mask_threshold': <class 'float'>, 'land_mask_threshold': <class 'float'>, 'valid_count_epsilon': <class 'float'>, 'grid_degrees_step_max': <class 'int'>, 'nc_compression_level': <class 'int'>}, 'wildlife': {'class_suitability': dict[str, float], 'weights': {'habitat': <class 'float'>, 'water': <class 'float'>, 'remoteness': <class 'float'>}}, 'adults': {'daily_mort_basal': <class 'float'>, 'opt_c': <class 'float'>, 'sigma_c': <class 'float'>, 'mort_cap': <class 'float'>, 'mort_floor': <class 'float'>}, 'eip': {'base_c': <class 'float'>, 'threshold_gd': <class 'float'>}, 'transmission': {'beta_hv': <class 'float'>, 'beta_vh': <class 'float'>, 'human_incubation_days': <class 'int'>, 'human_infectious_days': <class 'int'>, 'human_immunity_days': <class 'int'>, 'initial_human_prevalence': <class 'float'>, 'initial_vector_infected_frac': <class 'float'>}, 'dispersal': {'adult_prob_day': <class 'float'>, 'adult_sigma_m': <class 'float'>, 'adult_max_m': <class 'float'>, 'wind_migration_prob': <class 'float'>, 'wind_flight_hours': <class 'float'>, 'wind_survival': <class 'float'>, 'wind_self_speed_ms': <class 'float'>, 'flight_hour': <class 'int'>, 'host_flight_step_m': <class 'float'>, 'snap_radius_m': <class 'float'>, 'night_start_hour': <class 'int'>, 'night_end_hour': <class 'int'>}, 'host_seeking': {'starvation_days': <class 'int'>, 'indoor_attraction_add': <class 'float'>, 'urbanicity_add': <class 'float'>, 'indoor_fraction_urban': <class 'float'>, 'indoor_fraction_rural': <class 'float'>, 'detect_range_m': <class 'float'>, 'approach_step_m': <class 'float'>}, 'oviposition': {'scale_m': <class 'float'>, 'detect_range_m': <class 'float'>, 'step_m': <class 'float'>, 'min_attraction': <class 'float'>, 'timeout_days': <class 'int'>}, 'aquatic_stages': {'egg_daily_mort': <class 'float'>, 'pupa_daily_mort': <class 'float'>, 'larva_bh_s0': <class 'float'>, 'larva_bh_alpha': <class 'float'>, 'last_larval_instar': <class 'int'>, 'salinity_missing_psu': <class 'float'>}, 'thermal': {'efd_max_eggs_per_day': <class 'float'>, 'efd_tmin_c': <class 'float'>, 'efd_tmax_c': <class 'float'>, 'efd_topt_c': <class 'float'>, 'egg_development_tmin_c': <class 'float'>, 'egg_development_tmax_c': <class 'float'>, 'egg_development_scale': <class 'float'>, 'larva_development_tmin_c': <class 'float'>, 'larva_development_tmax_c': <class 'float'>, 'larva_development_scale': <class 'float'>, 'pupa_development_tmin_c': <class 'float'>, 'pupa_development_tmax_c': <class 'float'>, 'pupa_development_scale': <class 'float'>}, 'gonotrophic': {'cycle_duration_days': <class 'float'>, 'first_cycle_days': <class 'float'>, 'feeding_success_rate': <class 'float'>, 'egg_batch_mean': <class 'int'>, 'egg_batch_n': <class 'int'>, 'egg_batch_min': <class 'int'>, 'egg_batch_max': <class 'int'>, 'resting_duration_days': <class 'float'>}, 'rng': {'aquatic_seed_washout': <class 'int'>, 'aquatic_seed_stage_mortality': <class 'int'>, 'aquatic_seed_larva_mortality': <class 'int'>}}
ENV_VAR = 'MAL_MODEL_CONSTANTS'
DEFAULT_PATH = PosixPath('/Users/davidflorezmazuera/Downloads/MalariaSentinel/mal-core/config/model_constants.yaml')
def resolve_path(path: str | os.PathLike[str] | None = None) -> pathlib.Path:
688def resolve_path(path: str | os.PathLike[str] | None = None) -> pathlib.Path:
689    """Resolve the constants path (explicit > env var > repo default)."""
690    if path is not None:
691        return pathlib.Path(path)
692    env = os.environ.get(ENV_VAR)
693    if env:
694        return pathlib.Path(env)
695    return DEFAULT_PATH

Resolve the constants path (explicit > env var > repo default).

def load_config(path: str | os.PathLike[str] | None = None) -> mappingproxy:
50def load_config(path: str | os.PathLike[str] | None = None) -> types.MappingProxyType:
51    """Load + validate the model constants YAML (see module docstring)."""
52    return freeze(validate_model_config(path).model_dump())

Load + validate the model constants YAML (see module docstring).

def dump_raw(path: str | os.PathLike[str] | None = None) -> dict[str, typing.Any]:
 57def dump_raw(path: str | os.PathLike[str] | None = None) -> dict[str, Any]:
 58    """Flat "dotted"-key view (plan §6 test 4) for the py⇄C++ parity test.
 59
 60    Species weight rows are emitted as LISTS in the canonical habitat
 61    order (the pre-transformed C++ std::array shape). Compare key-by-key
 62    (numeric tolerance 1e-9) against ``config_dump``'s JSON.
 63    """
 64    data = dict(load_config(path)) if path is not None else dict(CONFIG)
 65    types_list = data["habitat_types"]["types"]
 66    out: dict[str, Any] = {}
 67    out["version"] = data["version"]
 68    for k, v in data["contracts"].items():
 69        out[f"contracts.{k}"] = v
 70    for i, name in enumerate(types_list):
 71        out[f"habitat_types.types.{i}"] = name
 72    for k, v in data["habitat_types"]["dynamics"].items():
 73        out[f"habitat_types.dynamics.{k}"] = v
 74    out["habitat_types.num_persistent"] = sum(
 75        1 for v in data["habitat_types"]["dynamics"].values()
 76        if v == "persistent")
 77    for sec in ("habitat", "pluvial", "aquatic_stress", "urban", "capacity",
 78                "geodesy"):
 79        for k, v in data[sec].items():
 80            out[f"{sec}.{k}"] = v
 81    out["species.default_species"] = data["species"]["default_species"]
 82    out["species.k_ref"] = data["species"]["k_ref"]
 83    for name, row in data["species"].items():
 84        if name in ("default_species", "k_ref"):
 85            continue
 86        if "weights" not in row:
 87            continue
 88        out[f"species.{name}.weights"] = [
 89            float(row["weights"][g]) for g in types_list]
 90        for k in ("salinity_hi_tol_ppt", "host_seeking_scale_m",
 91                  "host_seeking_radius_m", "salinity_opt_ppt",
 92                  "salinity_slope"):
 93            if k in row:
 94                out[f"species.{name}.{k}"] = row[k]
 95        if "activity_weights" in row:
 96            out[f"species.{name}.activity_weights"] = [
 97                float(v) for v in row["activity_weights"]]
 98        if "pref" in row:
 99            # Parity with the C++ dump: the pref row as a HostType-ordered
100            # array (human, cattle, goat, sheep, wildlife).
101            out[f"species.{name}.pref"] = [
102                float(row["pref"][h]) for h in
103                ("human", "cattle", "goat", "sheep", "wildlife")]
104    # Engine-consumed sections. ``wildlife`` is deliberately absent: it is a
105    # py-only input-loader section with no C++ consumer or config_dump entry
106    # (task-08), so emitting it would break the py⇄C++ key parity contract.
107    for sec in ("ingest", "adults", "eip", "transmission", "dispersal",
108                "host_seeking", "oviposition", "aquatic_stages", "thermal",
109                "gonotrophic", "rng"):
110        for k, v in data[sec].items():
111            out[f"{sec}.{k}"] = v
112    return out

Flat "dotted"-key view (plan §6 test 4) for the py⇄C++ parity test.

Species weight rows are emitted as LISTS in the canonical habitat order (the pre-transformed C++ std::array shape). Compare key-by-key (numeric tolerance 1e-9) against config_dump's JSON.

def habitat_names() -> tuple[str, ...]:
115def habitat_names() -> tuple[str, ...]:
116    """Ordered habitat type names (frozen habitat_types.types)."""
117    return tuple(CONFIG["habitat_types"]["types"])

Ordered habitat type names (frozen habitat_types.types).

def dynamics_map() -> dict[str, str]:
120def dynamics_map() -> dict[str, str]:
121    """Habitat type -> dynamics label (persistent|pluvial)."""
122    return dict(CONFIG["habitat_types"]["dynamics"])

Habitat type -> dynamics label (persistent|pluvial).

def persistent_names() -> frozenset[str]:
125def persistent_names() -> frozenset[str]:
126    """Derived habitat subsets (replaces the old PERSISTENT_TYPES const)."""
127    return frozenset(
128        g for g, k in dynamics_map().items() if k == "persistent")

Derived habitat subsets (replaces the old PERSISTENT_TYPES const).

def pluvial_names() -> frozenset[str]:
131def pluvial_names() -> frozenset[str]:
132    """Derived habitat subsets (replaces the old PLUVIAL_TYPES const)."""
133    return frozenset(
134        g for g, k in dynamics_map().items() if k == "pluvial")

Derived habitat subsets (replaces the old PLUVIAL_TYPES const).