utils
laser.cholera.metapop.utils
¶
Shared metapop helpers: seasonality, gravity-model mobility, and CLI-override coercion.
Three responsibilities live here:
get_daily_seasonality— bakes the per-tick / per-patch human-to-human transmission seasonality envelope from Fourier coefficients (a_1_j,b_1_j,a_2_j,b_2_j, periodp).get_pi_from_lat_long— builds the row-stochastic spatial-connectivity matrixpi_ijusing a gravity model over patch lat/long, attenuated bymobility_omega/mobility_gamma.override_helperand theUnknownOverrideKeyexception, used bycli_runto type-coerce and strictly validate--over key:valueoverrides against the parameter schema.
UnknownOverrideKey
¶
Bases: ValueError
Raised when override_helper receives a key that is not in its mapping.
Subclass of ValueError so callers that catch ValueError continue
to work. CLI front-ends (cli_run) catch this specific subclass and
re-raise as click.UsageError for a clean CLI presentation; other
ValueErrors (notably the _cli_unsupported rejections raised for
valid-but-non-scalar parameter keys) propagate as-is.
Source code in src/laser/cholera/metapop/utils.py
check_attr
¶
Raise AttributeError(message) when obj lacks attribute attr.
Concise replacement for the if not hasattr(obj, attr): raise
AttributeError(...) idiom that pipeline components' __init__ and
check methods use to verify that upstream components have set up
the model state this component will consume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
The object whose attribute presence is being checked. |
required |
attr
|
str
|
Attribute name. |
required |
message
|
str
|
Diagnostic message included in the raised exception. |
required |
Raises:
| Type | Description |
|---|---|
AttributeError
|
When |
Example
from types import SimpleNamespace from laser.cholera.metapop.utils import check_attr check_attr(SimpleNamespace(people=[]), "people", "model needs
people") # no-op check_attr(SimpleNamespace(), "people", "model needspeople") Traceback (most recent call last): ... AttributeError: model needspeople
Source code in src/laser/cholera/metapop/utils.py
check_key
¶
Raise ValueError(message) when mapping lacks key.
Concise replacement for the if key not in mapping: raise
ValueError(...) idiom used in pipeline components' __init__ and
check methods to verify that required entries are present in the
parameter set (PropertySet / PropertySetEx, plain dict, or
anything else supporting in).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
object
|
Any container that supports the |
required |
key
|
str
|
The key whose presence is being checked. |
required |
message
|
str
|
Diagnostic message included in the raised exception. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Example
from laser.cholera.metapop.utils import check_key check_key({"a": 1}, "a", "missing key 'a'") # no-op check_key({"a": 1}, "b", "missing key 'b'") Traceback (most recent call last): ... ValueError: missing key 'b'
Source code in src/laser/cholera/metapop/utils.py
get_daily_seasonality
¶
Build the per-tick, per-patch human-to-human transmission seasonality envelope.
Computes beta_j0_hum * (1 + a_1_j cos(2pi t/p) + b_1_j sin(2pi t/p)
+ a_2_j cos(4pi t/p) + b_2_j sin(4pi t/p)), returning a
(nticks, npatches) float32 array. t is 1-indexed to match the
R reference implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PropertySetEx
|
A |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A |
ndarray
|
seasonality envelope. Consumed once by |
ndarray
|
and stored on |
Source code in src/laser/cholera/metapop/utils.py
get_pi_from_lat_long
¶
Build the row-stochastic spatial-connectivity matrix pi_ij from a gravity model.
Computes x_ij = N_j^omega * d_ij^(-gamma) for each origin/dest
pair (excluding the self pair j == i), then row-normalizes:
pi_ij = x_ij / sum_j(x_ij). The diagonal is zero (no
self-mobility). The migrating fraction tau_i is not applied
here; it's factored in at runtime inside
HumanToHuman.__call__
so the migrating fraction can vary per patch without rebuilding
pi_ij.
Special-cases the single-location configuration: distance()
returns a 0-dim scalar that's promoted to a (1, 1) array so
downstream array operations keep working; the result is then
trivially [[0.0]].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PropertySetEx
|
A |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
An |
Source code in src/laser/cholera/metapop/utils.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
override_helper
¶
Coerce stringly-typed --over parameter overrides to their runtime types.
Called from cli_run against the parsed --over key:value payload
only (CLI flags like --seed / --hdf5-output are typed by click
itself and never reach this function). Each entry in the mapping
table is a unary callable invoked on the raw string value:
int-mapped keys (e.g.seed,p,delta_reporting_cases) →int(value).float-mapped keys (e.g.phi_1,sigma,rho,chi_endemic) →float(value).date_start/date_stop→datetimeparsed from"%Y-%m-%d".- "CLI-unsupported" keys (vectors, matrices, DataFrames such as
S_j_initial,b_jt,epidemic_peaks,return) — the coercer immediately raisesValueError. These are valid model parameters but cannot meaningfully be passed as a CLI string; use--paramsorget_parameters(mods=...)instead. - Unknown keys raise
UnknownOverrideKey(aValueErrorsubclass) with adifflib-derived "did you mean" suggestion when a close match exists.
The mapping is the source of truth for which parameter names exist;
every key in default_parameters.json is represented, plus the
cli_run-only sentinels (none, after the --hdf5-output / --compress
promotions in the same change).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overrides
|
dict
|
Mapping of override key → raw string value, as parsed
from |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new dict with the same keys as the input, values coerced per |
dict
|
the table. |
Raises:
| Type | Description |
|---|---|
UnknownOverrideKey
|
When an override key is not in the mapping. |
ValueError
|
When an override key is in the mapping but flagged as CLI-unsupported (vector / matrix / DataFrame). |
Example
from laser.cholera.metapop.utils import override_helper typed = override_helper({"phi_1": "0.65", "seed": "42"}) typed["phi_1"] == 0.65 and typed["seed"] == 42 True override_helper({"b_jt": "anything"}) Traceback (most recent call last): ... ValueError: Parameter 'b_jt' cannot be set via --over... override_helper({"date_strat": "2024-01-01"}) Traceback (most recent call last): ... laser.cholera.metapop.utils.UnknownOverrideKey: Unknown override key 'date_strat'. Did you mean 'date_start'?
Source code in src/laser/cholera/metapop/utils.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |