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
MappingProxyTypesingleton, - 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()
Base class of model-constants failures.
104class SchemaError(ConfigError): 105 """The YAML does not satisfy the declared schema/invariants."""
The YAML does not satisfy the declared schema/invariants.
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).
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).
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.
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).
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).
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).
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).