diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 48163c1..c0a8585 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -16,7 +16,7 @@ on: - '**' jobs: run-tests: - name: Run tests on ${{ matrix.os }} + name: Run ${{ matrix.shard.name }} tests on ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -25,6 +25,13 @@ jobs: - ubuntu-latest python-version: - '3.14' + # The medical-cost timing module compiles and simulates a model of its + # own, which takes longer than any other module; it runs in parallel. + shard: + - name: main + args: -n 4 --dist loadscope --ignore=tests/test_medical_cost_timing.py tests + - name: timing + args: tests/test_medical_cost_timing.py steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 @@ -35,8 +42,8 @@ jobs: # install; keep it compatible with the model's graph declarations. run: >- pip install "pylcm @ - git+https://github.com/OpenSourceEconomics/pylcm.git@eea73a8f0e301e88f02278df3595c797fdba24df" + git+https://github.com/OpenSourceEconomics/pylcm.git@318324f6bce1487178714b047211ce1245d170a8" - name: Install aca-model with test deps - run: pip install -e . pytest pdbp + run: pip install -e . pytest pytest-xdist pdbp - name: Run pytest - run: pytest tests + run: pytest --durations=40 ${{ matrix.shard.args }} diff --git a/README.md b/README.md index f22ff8f..0c7ef6d 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,23 @@ Core lifecycle model for the ACA structural retirement project. -The benchmark folds the IID transitory medical-cost shock and declares its asset -transition as resources plus the negated medical bill. Production grid defaults remain -unfolded. To measure the unfolded benchmark control, pass -`grid_config=replace(BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False)` -to `create_benchmark_model`. Pass the same grid configuration to -`get_benchmark_initial_conditions`; both routes retain identical seeded draws for their -shared initial states. - -Model factories accept `execution_config=ExecutionConfig(...)`. An omitted policy uses -the smallest JAX allocator `bytes_limit` among the selected accelerators as an explicit -per-device budget. This enables budget-aware width selection; CPU construction remains -unbudgeted. Missing accelerator limits require an explicit policy instead of silently -falling back to unbudgeted execution. +The IID transitory medical-cost shock is read only as its draw `next_hcc_transitory`, so +pylcm integrates it out and no regime carries it as a state. The benchmark declares the +asset transition as resources plus the negated medical bill; to measure the plain asset +law instead, pass `grid_config=replace(BENCHMARK_GRID_CONFIG, subtract_hcc_bill=False)` +to `create_benchmark_model`, and the same grid configuration to +`get_benchmark_initial_conditions`. + +`build_model_spec(...)` returns the model's domain: regimes, ages, edges, broadcast +slots and the default entry `initial_nodes`. `policy=None` builds the baseline; a +`PolicyVariant` overlays its ACA schedules. +`create_model(spec=..., fixed_params=..., **model_options)` forwards every other +`lcm.Model` option unchanged, and an option the spec also holds, such as +`initial_nodes`, overrides it. `create_benchmark_model` takes the same options. + +Without `execution_config`, pylcm's default applies: the budget is the smallest selected +device pool limit less headroom, which requires a preallocated allocator pool +(`XLA_PYTHON_CLIENT_PREALLOCATE` not `false`); CPU runs unbudgeted. To combine a measured budget with device selection and sharding: @@ -29,14 +33,15 @@ execution_config = replace( ) ``` -Pass this policy to the baseline, ACA or benchmark factory. Record its exact -`device_memory_bytes`, the selected devices' allocator observations, executed precision -and selected program widths with performance evidence. The budget is an allocator -ceiling; it does not establish that all workload phases fit. +Pass this policy as `execution_config` to `create_model` or `create_benchmark_model`. +Record its exact `device_memory_bytes`, the selected devices' allocator observations, +executed precision and selected program widths with performance evidence. The budget is +an allocator ceiling; it does not establish that all workload phases fit. -Explicit policies pass through unchanged. In particular, `ExecutionConfig()` is an -unbudgeted control and retains pylcm's bootstrap width selection. Economic grids, -numerical solver settings and result retention are separate choices. +Explicit policies pass through unchanged. In particular, +`ExecutionConfig(device_memory_bytes=None)` is an unbudgeted control and retains pylcm's +bootstrap width selection. Economic grids, numerical solver settings and result +retention are separate choices. `GridConfig` accepts economic grid sizes and numerical solver choices only. Execution controls belong to `ExecutionConfig`: sharded state names go in `sharded_states`, diff --git a/docs/dag-migration.md b/docs/dag-migration.md index 5e4650f..0f43357 100644 --- a/docs/dag-migration.md +++ b/docs/dag-migration.md @@ -1,6 +1,6 @@ # ACA: one structural stage table, existing numerical programs -Both factories declare the same admissible starts, `INITIAL_NODES`: ages 51–60 +Both factories admit the same starts by default, from `build_entry_initial_nodes`: ages 51–60 as explicit `(age, regime)` pairs in the five `*_inelig_canwork` regimes, 50 pairs. Every later age, and `dead` at any age, is reached only through transitions; the engine derives the solved domain from these roots, **184** nodes. @@ -10,7 +10,7 @@ admission. `simulate_with_dense_index` drops initial-condition rows older than the last admissible start age and raises on any kept row outside `model.initial_nodes`. -`_AGE_STAGES` and the host-side clock supply both numerical next-age routing and +`age_stages` and the host-side clock supply both numerical next-age routing and `Model.edges` source-age selectors, grouped by destination. Each source has one mapping of `StochasticTransition` probability cells; the model graph selects the cells allowed at each source age. Code order/global regime IDs and parameter diff --git a/src/aca_model/aca/model.py b/src/aca_model/aca/model.py deleted file mode 100644 index 971b8b0..0000000 --- a/src/aca_model/aca/model.py +++ /dev/null @@ -1,110 +0,0 @@ -"""ACA structural retirement model variants. - -Creates model variants for counterfactual ACA policy analysis by applying -function overrides on top of baseline regimes. -""" - -from collections.abc import Mapping -from typing import Any - -from lcm import AgeGrid, DiscreteGrid, ExecutionConfig, InitialNodes, Model -from lcm.typing import UserParams - -from aca_model.aca import PolicyVariant -from aca_model.aca.regimes import build_all_regimes -from aca_model.baseline.model import _fail_if_dcegm_without_consumption_points -from aca_model.baseline.regimes import ( - INITIAL_NODES, - RegimeId, - SolverName, - build_model_slots, -) -from aca_model.config import MODEL_AGES, GridConfig -from aca_model.execution import execution_config_for_devices - - -def create_model( - *, - policy: PolicyVariant, - fixed_params: UserParams, - wage_params: Mapping[str, Any], - derived_categoricals: Mapping[str, DiscreteGrid], - grid_config: GridConfig, - pref_type_grid: DiscreteGrid, - solver: SolverName = "brute_force", - consumption_dollars_points: tuple[float, ...] | None = None, - execution_config: ExecutionConfig | None = None, - initial_nodes: InitialNodes = INITIAL_NODES, -) -> Model: - """Create an ACA policy variant model. - - Args: - policy: Which ACA policy combination to apply (e.g. - `PolicyVariant.ACA`). - fixed_params: Parameters to fix at model creation time. Pass - data-derived constants here; only estimation parameters - should go through `model.simulate(params=...)`. - wage_params: Data-derived wage profile dict (`log_ft_wage_mean`, - `log_ft_wage_std`, `adj_wage_hours_*`) used only at grid-build - time to size the assets-floor to `-max_annual_labor_income`. - Not routed to the pylcm Model. - derived_categoricals: Categorical mappings for `pd.Series` - fixed_params index levels that aren't model state/action - grids — `target_his`, `his`, `good_health`, `is_married`, - `pref_type`. - grid_config: Continuous-grid point counts. - pref_type_grid: Pref-type `DiscreteGrid`. - solver: `"brute_force"` (the default) or `"dcegm"`; see - `aca_model.baseline.model.create_model`. - consumption_dollars_points: Construction-time consumption action - gridpoints; required under DC-EGM. See - `aca_model.baseline.model.create_model`. - execution_config: Explicit hardware-local policy forwarded unchanged. - None uses the smallest selected accelerator allocator limit as the - device-memory budget; CPU construction remains unbudgeted. - initial_nodes: Admissible starting `(age, regime)` pairs. The default - admits the estimation sample's entry ages and regimes; pass - `build_restart_initial_nodes` to restart simulations mid-life. - - Returns: - pylcm Model. - - """ - ages = AgeGrid(exact_values=MODEL_AGES) - _fail_if_dcegm_without_consumption_points( - solver=solver, consumption_dollars_points=consumption_dollars_points - ) - regimes = build_all_regimes( - policy=policy, - grid_config=grid_config, - fixed_params=fixed_params, - wage_params=wage_params, - pref_type_grid=pref_type_grid, - solver=solver, - consumption_dollars_points=consumption_dollars_points, - ) - # The overlay swaps only regime-level functions; the broadcast slots - # are policy-invariant. - model_slots = build_model_slots( - grid_config=grid_config, - fixed_params=fixed_params, - wage_params=wage_params, - pref_type_grid=pref_type_grid, - solver=solver, - ) - - return Model( - regimes=regimes, - initial_nodes=initial_nodes, - ages=ages, - regime_id_class=RegimeId, - description=f"Structural retirement model ({policy.name})", - fixed_params=fixed_params, - derived_categoricals=derived_categoricals, - execution_config=( - execution_config_for_devices() - if execution_config is None - else execution_config - ), - **model_slots, - ) diff --git a/src/aca_model/aca/regimes/__init__.py b/src/aca_model/aca/regimes/__init__.py index bd9d237..747ce1e 100644 --- a/src/aca_model/aca/regimes/__init__.py +++ b/src/aca_model/aca/regimes/__init__.py @@ -6,8 +6,8 @@ from collections.abc import Mapping from typing import Any +from jax.typing import ArrayLike from lcm import DiscreteGrid, Regime -from lcm.typing import UserParams from aca_model.aca.health_insurance import PolicyVariant from aca_model.aca.regimes._overrides import apply_aca_overrides @@ -22,7 +22,7 @@ def build_all_regimes( *, policy: PolicyVariant, grid_config: GridConfig, - fixed_params: UserParams, + pia_aime_grid: ArrayLike, wage_params: Mapping[str, Any], pref_type_grid: DiscreteGrid, solver: SolverName = "brute_force", @@ -31,7 +31,7 @@ def build_all_regimes( """Build all 19 regimes with ACA policy overrides.""" regimes = baseline_build_all_regimes( grid_config=grid_config, - fixed_params=fixed_params, + pia_aime_grid=pia_aime_grid, wage_params=wage_params, pref_type_grid=pref_type_grid, solver=solver, diff --git a/src/aca_model/aca/regimes/_overrides.py b/src/aca_model/aca/regimes/_overrides.py index eb92ffe..23cbd77 100644 --- a/src/aca_model/aca/regimes/_overrides.py +++ b/src/aca_model/aca/regimes/_overrides.py @@ -8,6 +8,7 @@ from aca_model.aca import health_insurance as aca_hi from aca_model.aca.health_insurance import PolicyVariant +from aca_model.baseline import health_insurance as baseline_hi from aca_model.baseline.regimes._common import RegimeSpec from aca_model.environment import taxes @@ -55,6 +56,7 @@ def apply_aca_overrides( ) if has_medicaid_expansion: + functions["aca_magi"] = baseline_hi.aca_magi functions["is_medicaid_eligible"] = aca_hi.is_medicaid_eligible if has_subsidies and spec["his"] == "nongroup" and spec["mc"] == "nomc": @@ -64,8 +66,9 @@ def apply_aca_overrides( # dict, not a DAG function — no entry needed here. functions["plan_premium"] = aca_hi.community_rated_premium # The community-rated premium replaces the risk-rated one, so the - # risk-rated premium's zero-profit intercept has no consumer left. + # risk-rated inputs have no consumer left. functions.pop("private_premium_intercept", None) + functions.pop("predicted_hcc_insurer", None) functions["hic_premium_subsidy"] = aca_hi.premium_subsidy # Split at the bracket, which takes finitely many values, so the # out-of-pocket bill can be averaged per bracket. diff --git a/src/aca_model/baseline/health_insurance.py b/src/aca_model/baseline/health_insurance.py index d073287..ad76030 100644 --- a/src/aca_model/baseline/health_insurance.py +++ b/src/aca_model/baseline/health_insurance.py @@ -235,26 +235,20 @@ def private_premium_intercept( `[-50000, 10000]` finds the root. Without a sign change on the bracket the result is NaN, so an unpriceable slope `b` fails loudly downstream. """ - slope = premium_predicted_hcc * (1.0 + premium_markup) - minimum = premium_minimum[premium_sample_is_married] - target = (1.0 + premium_markup) * jnp.mean(premium_sample_insurer_cost) - - def excess_revenue(intercept: FloatND) -> FloatND: - premiums = jnp.maximum(minimum, intercept + slope * premium_sample_insurer_cost) - return jnp.mean(premiums) - target - - def halve( - _: jax.Array, bracket: tuple[FloatND, FloatND] - ) -> tuple[FloatND, FloatND]: - low, high = bracket - mid = 0.5 * (low + high) - too_high = excess_revenue(mid) > 0.0 - return jnp.where(too_high, low, mid), jnp.where(too_high, mid, high) - + sample = ( + premium_predicted_hcc * (1.0 + premium_markup), + premium_minimum[premium_sample_is_married], + premium_sample_insurer_cost, + (1.0 + premium_markup) * jnp.mean(premium_sample_insurer_cost), + ) low0 = jnp.asarray(_INTERCEPT_BRACKET[0]) high0 = jnp.asarray(_INTERCEPT_BRACKET[1]) - low, high = jax.lax.fori_loop(0, _N_INTERCEPT_BISECTIONS, halve, (low0, high0)) - bracketed = (excess_revenue(low0) <= 0.0) & (excess_revenue(high0) >= 0.0) + low, high, _ = jax.lax.fori_loop( + 0, _N_INTERCEPT_BISECTIONS, _halve, (low0, high0, sample) + ) + bracketed = (_excess_revenue(intercept=low0, sample=sample) <= 0.0) & ( + _excess_revenue(intercept=high0, sample=sample) >= 0.0 + ) return jnp.where(bracketed, 0.5 * (low + high), jnp.nan) @@ -600,3 +594,32 @@ def total_costs( + log_std[period, is_married, good_health] * (next_hcc_persistent * std_xsect_persistent + next_hcc_transitory * std_trans) ) + + +def _excess_revenue( + *, intercept: FloatND, sample: tuple[FloatND, FloatND, FloatND, FloatND] +) -> FloatND: + """Mean premium revenue at `intercept` less the zero-profit target. + + `sample` holds the premium slope on insurer cost, each sampled buyer's + premium floor, each buyer's expected insurer cost, and the required mean + revenue, in that order. + """ + slope, minimum, cost, target = sample + return jnp.mean(jnp.maximum(minimum, intercept + slope * cost)) - target + + +# keyword-only-exempt: library-callback=jax.lax.fori_loop +def _halve( + _: jax.Array, + carry: tuple[FloatND, FloatND, tuple[FloatND, FloatND, FloatND, FloatND]], +) -> tuple[FloatND, FloatND, tuple[FloatND, FloatND, FloatND, FloatND]]: + """Halve the bracket towards the zero-profit intercept. + + A module-level body with its operands in the carry lets every call reuse + one traced loop instead of tracing a fresh closure. + """ + low, high, sample = carry + mid = 0.5 * (low + high) + too_high = _excess_revenue(intercept=mid, sample=sample) > 0.0 + return jnp.where(too_high, low, mid), jnp.where(too_high, mid, high), sample diff --git a/src/aca_model/baseline/model.py b/src/aca_model/baseline/model.py index 1b1efe3..34d2278 100644 --- a/src/aca_model/baseline/model.py +++ b/src/aca_model/baseline/model.py @@ -1,124 +1,190 @@ -"""Baseline structural retirement model using pylcm. +"""Structural retirement model specification and construction using pylcm. -This is the main model specification, ported from struct-ret/. The baseline -represents pre-ACA rules (no individual mandate, no ACA subsidies). +The baseline represents pre-ACA rules (no individual mandate, no ACA +subsidies); an ACA `PolicyVariant` overlays its schedules on the baseline +regimes. Usage: - from aca_model.baseline.model import create_model - model = create_model(fixed_params=..., wage_params=..., ...) - params = get_default_params() - V = model.solve(params) + from aca_model.baseline.model import build_model_spec, create_model + spec = build_model_spec(grid_config=..., pia_aime_grid=..., ...) + model = create_model(spec=spec, fixed_params=...) """ from collections.abc import Mapping from typing import Any -from lcm import AgeGrid, DiscreteGrid, ExecutionConfig, InitialNodes, Model +from jax.typing import ArrayLike +from lcm import AgeGrid, DiscreteGrid, Model +from lcm.solvers import GridSearch from lcm.typing import UserParams +from aca_model.aca.health_insurance import PolicyVariant +from aca_model.aca.regimes import build_all_regimes as build_all_aca_regimes +from aca_model.agent.health import GoodHealth +from aca_model.agent.labor_market import IsMarried +from aca_model.baseline.health_insurance import HealthInsuranceState from aca_model.baseline.regimes import ( - INITIAL_NODES, RegimeId, SolverName, build_all_regimes, + build_entry_initial_nodes, build_model_slots, ) -from aca_model.config import MODEL_AGES, GridConfig -from aca_model.execution import execution_config_for_devices +from aca_model.config import MODEL_CONFIG, GridConfig, model_ages -def create_model( +def build_model_spec( *, - fixed_params: UserParams, - wage_params: Mapping[str, Any], - derived_categoricals: Mapping[str, DiscreteGrid], + policy: PolicyVariant | None = None, grid_config: GridConfig, + pia_aime_grid: ArrayLike, + wage_params: Mapping[str, Any], pref_type_grid: DiscreteGrid, solver: SolverName = "brute_force", consumption_dollars_points: tuple[float, ...] | None = None, - execution_config: ExecutionConfig | None = None, - initial_nodes: InitialNodes = INITIAL_NODES, -) -> Model: - """Create the baseline structural retirement model. + final_age: int = MODEL_CONFIG.end_age, + lottery_contraction: bool = False, +) -> dict[str, Any]: + """Return the domain keyword arguments of `lcm.Model` for the retirement model. + + The spec holds `regimes`, `ages`, `regime_id_class`, `description`, + `derived_categoricals`, the entry `initial_nodes`, `edges`, `functions`, + `constraints`, `states` and `state_transitions`. It holds no generic + `Model` option; pass those to `create_model`. Merge an override with `|`, + e.g. `spec | {"initial_nodes": build_restart_initial_nodes(ages=...)}`. Args: - fixed_params: Parameters to fix at model creation time. Fixed - params are partialled into compiled functions and removed - from the params template. Pass data-derived constants here; - only estimation parameters should go through - `model.simulate(params=...)`. - wage_params: Data-derived wage profile dict (`log_ft_wage_mean`, - `log_ft_wage_std`, `adj_wage_hours_*`) used only at grid-build - time to size the assets-floor to `-max_annual_labor_income`. - Not routed to the pylcm Model. - derived_categoricals: Categorical mappings for `pd.Series` - fixed_params index levels that aren't model state/action - grids — `target_his`, `his`, `good_health`, `is_married`, - `pref_type`. + policy: ACA policy whose schedules overlay the baseline regimes. None + builds the baseline (pre-ACA) model. grid_config: Continuous-grid point counts. Pass `GRID_CONFIG` for production values or `BENCHMARK_GRID_CONFIG` for the fast-but-structurally-faithful benchmark. + pia_aime_grid: PIA bend points in AIME, which break the AIME grid + into its segments. + wage_params: Data-derived wage profile dict (`log_ft_wage_mean`, + `log_ft_wage_std`, `adj_wage_hours_*`) used only at grid-build + time to size the assets-floor to `-max_annual_labor_income`. pref_type_grid: Pref-type `DiscreteGrid`. Pass `DiscreteGrid(PrefType)` for the production 3-type layout, or a compact variant (e.g. `DiscreteGrid(BenchmarkPrefType)`). - solver: `"brute_force"` (the default) or `"dcegm"`. DC-EGM swaps - the spec to its post-decision form: savings-form assets laws, + solver: `"brute_force"` (the default), `"dcegm"` or `"nbegm"`. DC-EGM + swaps the spec to its post-decision form: savings-form assets laws, broadcast `resources`/`savings`/`inverse_marginal_utility` - functions, no borrowing constraint, and a `DCEGM` solver - config on every living regime. + functions, and a `DCEGM` solver config on every living regime. consumption_dollars_points: Construction-time consumption action gridpoints. Required under DC-EGM (the kernel needs the continuous-action grid at model construction); `None` keeps the runtime-points grid completed per iteration via `inject_consumption_dollars_points`. - execution_config: Explicit hardware-local policy forwarded unchanged. - None uses the smallest selected accelerator allocator limit as the - device-memory budget; CPU construction remains unbudgeted. - initial_nodes: Admissible starting `(age, regime)` pairs. The default - admits the estimation sample's entry ages and regimes; pass - `build_restart_initial_nodes` to restart simulations mid-life. + final_age: First age at which everybody is dead; the model spans + `MODEL_CONFIG.start_age` through `final_age`. The default is the + full horizon. A shorter horizon reads a prefix of the age-indexed + data, and its fixed params must hold only what it reads (see + `select_horizon_params`). + lottery_contraction: Whether grid-search regimes take the expectation + over eligible draws once per kernel call; see `GridSearch`. Returns: - A pylcm Model with 19 regimes (18 non-terminal + dead) spanning - ages 51-96; 95 is the last age anyone is alive. Regime names follow - the `___` scheme. + Keyword arguments for `lcm.Model` describing 19 regimes (18 + non-terminal + dead) over ages 51 through `final_age`; `final_age - 1` + is the last age anyone is alive. Regime names follow the + `___` scheme. """ - ages = AgeGrid(exact_values=MODEL_AGES) _fail_if_dcegm_without_consumption_points( solver=solver, consumption_dollars_points=consumption_dollars_points ) - regimes = build_all_regimes( - grid_config=grid_config, - fixed_params=fixed_params, - wage_params=wage_params, - pref_type_grid=pref_type_grid, - solver=solver, - consumption_dollars_points=consumption_dollars_points, + ages = model_ages(final_age=final_age) + regimes = ( + build_all_regimes( + grid_config=grid_config, + pia_aime_grid=pia_aime_grid, + wage_params=wage_params, + pref_type_grid=pref_type_grid, + solver=solver, + consumption_dollars_points=consumption_dollars_points, + ) + if policy is None + else build_all_aca_regimes( + policy=policy, + grid_config=grid_config, + pia_aime_grid=pia_aime_grid, + wage_params=wage_params, + pref_type_grid=pref_type_grid, + solver=solver, + consumption_dollars_points=consumption_dollars_points, + ) ) + if lottery_contraction: + regimes = { + name: regime.replace(solver=GridSearch(lottery_contraction=True)) + if isinstance(regime.solver, GridSearch) + else regime + for name, regime in regimes.items() + } + # The ACA overlay swaps only regime-level functions; the broadcast slots + # are policy-invariant. model_slots = build_model_slots( grid_config=grid_config, - fixed_params=fixed_params, + pia_aime_grid=pia_aime_grid, wage_params=wage_params, pref_type_grid=pref_type_grid, + ages=ages, solver=solver, ) - - return Model( - regimes=regimes, - initial_nodes=initial_nodes, - ages=ages, - regime_id_class=RegimeId, - description="Baseline structural retirement model (pre-ACA)", - fixed_params=fixed_params, - derived_categoricals=derived_categoricals, - execution_config=( - execution_config_for_devices() - if execution_config is None - else execution_config + return { + "regimes": regimes, + "ages": AgeGrid(exact_values=ages), + "regime_id_class": RegimeId, + "description": ( + "Baseline structural retirement model (pre-ACA)" + if policy is None + else f"Structural retirement model ({policy.name})" + ), + "derived_categoricals": build_derived_categoricals( + pref_type_grid=pref_type_grid ), + "initial_nodes": build_entry_initial_nodes(ages=ages), **model_slots, - ) + } + + +def create_model( + *, spec: Mapping[str, Any], fixed_params: UserParams, **model_options: Any +) -> Model: + """Build the pylcm Model from `spec`, `fixed_params` and generic options. + + Args: + spec: Domain keyword arguments from `build_model_spec`. + fixed_params: Parameters to fix at model creation time. Fixed params + are partialled into compiled functions and removed from the params + template. They must hold exactly what the spec's horizon reads. + **model_options: Any other `lcm.Model` keyword argument, forwarded + unchanged, e.g. `execution_config`. A key the spec also holds, + such as `initial_nodes`, overrides the spec's value. + + Returns: + The pylcm Model. + + """ + return Model(**{**spec, **model_options}, fixed_params=fixed_params) + + +def build_derived_categoricals( + *, pref_type_grid: DiscreteGrid +) -> dict[str, DiscreteGrid]: + """Return the labels of params index levels that are not grids of every regime. + + `pd.Series` params are indexed by `target_his`, `his`, `good_health`, + `is_married` and `pref_type`. + """ + return { + "good_health": DiscreteGrid(GoodHealth), + "is_married": DiscreteGrid(IsMarried), + "his": DiscreteGrid(HealthInsuranceState), + "target_his": DiscreteGrid(HealthInsuranceState), + "pref_type": pref_type_grid, + } def _fail_if_dcegm_without_consumption_points( diff --git a/src/aca_model/baseline/regimes/__init__.py b/src/aca_model/baseline/regimes/__init__.py index 65b1f19..7034033 100644 --- a/src/aca_model/baseline/regimes/__init__.py +++ b/src/aca_model/baseline/regimes/__init__.py @@ -13,27 +13,29 @@ from collections.abc import Mapping from typing import Any +from jax.typing import ArrayLike from lcm import DiscreteGrid, Regime, Transition from lcm.solvers import DCEGM, NBEGM -from lcm.typing import UserParams from aca_model.baseline.regimes import _nongroup as nongroup from aca_model.baseline.regimes import _retiree as retiree from aca_model.baseline.regimes import _tied as tied from aca_model.baseline.regimes._common import ( ENTRY_REGIMES, - INITIAL_NODES, REGIME_SPECS, Grids, RegimeId, SolverName, build_dead_regime, + build_entry_initial_nodes, build_grids, build_model_constraints, build_model_functions, build_model_state_transitions, build_model_states, build_restart_initial_nodes, + reachable_regimes, + select_horizon_params, ) from aca_model.baseline.regimes._dcegm import build_dcegm_solver from aca_model.baseline.regimes._nbegm import build_nbegm_solver @@ -41,15 +43,17 @@ __all__ = [ "ENTRY_REGIMES", - "INITIAL_NODES", "REGIME_SPECS", "RegimeId", "build_all_regimes", + "build_entry_initial_nodes", "build_model_slots", "build_regime", "build_restart_initial_nodes", "nongroup", + "reachable_regimes", "retiree", + "select_horizon_params", "tied", ] @@ -90,7 +94,7 @@ def build_regime( def build_all_regimes( *, grid_config: GridConfig, - fixed_params: UserParams, + pia_aime_grid: ArrayLike, wage_params: Mapping[str, Any], pref_type_grid: DiscreteGrid, solver: SolverName = "brute_force", @@ -98,7 +102,7 @@ def build_all_regimes( ) -> dict[str, Regime]: """Build all 19 baseline regimes (18 non-terminal + dead). - `fixed_params` carries the PIA bends for the AIME piecewise grid; + `pia_aime_grid` holds the PIA bends for the AIME piecewise grid; `wage_params` sizes the assets-floor to `-max_annual_labor_income`; `pref_type_grid` selects the pref-type cardinality (production `DiscreteGrid(PrefType)` or the benchmark's 2-type variant); @@ -109,7 +113,7 @@ def build_all_regimes( """ grids = build_grids( grid_config=grid_config, - fixed_params=fixed_params, + pia_aime_grid=pia_aime_grid, wage_params=wage_params, pref_type_grid=pref_type_grid, consumption_dollars_points=consumption_dollars_points, @@ -131,28 +135,29 @@ def build_all_regimes( def build_model_slots( *, grid_config: GridConfig, - fixed_params: UserParams, + pia_aime_grid: ArrayLike, wage_params: Mapping[str, Any], pref_type_grid: DiscreteGrid, + ages: tuple[int, ...], solver: SolverName = "brute_force", ) -> dict[str, Any]: """Build the shared model topology and broadcast regime slots. Returns keyword arguments for `lcm.Model(...)`: the edges, functions, constraint, states, and laws of motion shared by all living regimes. - Both the baseline and the ACA `create_model` consume this — the ACA - overlay swaps only regime-level functions, so the broadcast slots are - policy-invariant. Under DC-EGM the solver-contract functions join the + The ACA overlay swaps only regime-level functions, so the broadcast slots + are policy-invariant. Under DC-EGM the solver-contract functions join the broadcast set; the borrowing constraint is declared under every solver. + `ages` is the model's age grid, which the edges' age schedules cover. """ grids = build_grids( grid_config=grid_config, - fixed_params=fixed_params, + pia_aime_grid=pia_aime_grid, wage_params=wage_params, pref_type_grid=pref_type_grid, ) return { - "edges": build_edges(), + "edges": build_edges(ages=ages), "functions": build_model_functions(solver=solver), "constraints": build_model_constraints(solver=solver), "states": build_model_states(grids), @@ -160,13 +165,13 @@ def build_model_slots( } -def build_edges() -> dict[str, Transition]: +def build_edges(*, ages: tuple[int, ...]) -> dict[str, Transition]: """Declare each living regime's outgoing edges by their law. The law's age schedule names each destination at the source ages that reach it. `dead` has no outgoing edges and is therefore terminal. """ return { - name: Transition(law=_HIS_LAWS[spec["his"]](name)) + name: Transition(law=_HIS_LAWS[spec["his"]](name, ages=ages)) for name, spec in REGIME_SPECS.items() } diff --git a/src/aca_model/baseline/regimes/_common.py b/src/aca_model/baseline/regimes/_common.py index 5dd4180..40a5c6c 100644 --- a/src/aca_model/baseline/regimes/_common.py +++ b/src/aca_model/baseline/regimes/_common.py @@ -13,6 +13,7 @@ import jax.numpy as jnp import numpy as np +from jax.typing import ArrayLike from lcm import ( AdditiveShockTransition, ByAge, @@ -43,7 +44,6 @@ Period, RegimeName, ScalarInt, - UserParams, ) from aca_model.agent import ( @@ -252,13 +252,6 @@ class Grids: """Grid sizes and numerical settings used to construct each solver.""" -# AIME piecewise grid: number of points per segment between the PIA -# bend points (0 → kink_0 → kink_1 → kink_2 → extension). The fourth -# segment covers the sparse delayed-retirement-credit region above the -# taxable max, so it carries fewer points than the dense lower segments. -_AIME_PIECE_N_POINTS: tuple[int, int, int, int] = (10, 11, 11, 6) - - # `pension_wealth` is a carried state (`Phased(solve=..., simulate=Grid)`): # imputed via a derived function in solve (never a solve grid axis) and # carried per subject in simulate. The grid is simulate-side metadata only — @@ -291,7 +284,7 @@ class Grids: def build_grids( *, grid_config: GridConfig, - fixed_params: UserParams, + pia_aime_grid: ArrayLike, wage_params: Mapping[str, Any], pref_type_grid: DiscreteGrid, consumption_dollars_points: tuple[float, ...] | None = None, @@ -299,7 +292,7 @@ def build_grids( """Build continuous-state/action grids from a `GridConfig`. The AIME grid is `PiecewiseLinSpacedGrid` breakpointed at the PIA - bends from `fixed_params["pia_aime_grid"]`. The assets grid + bends in `pia_aime_grid`. The assets grid (`build_assets_grid`) runs from `-max_annual_labor_income`, computed from `wage_params` (`log_ft_wage_mean`, `log_ft_wage_std`, `adj_wage_hours_*`), to the largest initial asset holding. @@ -326,7 +319,6 @@ def build_grids( gauss_hermite=True, mu=0.0, sigma=1.0, - fold=grid_config.fold_hcc_transitory, ) assets_start = -_compute_max_annual_labor_income( @@ -337,12 +329,15 @@ def build_grids( assets=build_assets_grid( floor=assets_start, n_points=grid_config.n_assets_gridpoints ), - aime=_build_aime_grid(fixed_params=fixed_params), + aime=_build_aime_grid( + pia_aime_grid=pia_aime_grid, + points_per_segment=grid_config.aime_points_per_segment, + ), pension_wealth=_PENSION_WEALTH_GRID, consumption_dollars=( IrregSpacedGrid(n_points=grid_config.n_consumption_dollars_gridpoints) if consumption_dollars_points is None - else IrregSpacedGrid(points=consumption_dollars_points) + else IrregSpacedGrid(points=np.asarray(consumption_dollars_points)) ), wage_res=wage_res, hcc_persistent=hcc_persistent, @@ -378,7 +373,7 @@ def build_assets_grid(*, floor: float, n_points: int) -> IrregSpacedGrid: ) negative[0] = floor positive[-1] = _ASSETS_TOP - return IrregSpacedGrid(points=np.concatenate([negative, positive]).tolist()) + return IrregSpacedGrid(points=np.concatenate([negative, positive])) def get_hcc_persistent_shock(*, grid_config: GridConfig) -> RouwenhorstAR1Process: @@ -402,17 +397,18 @@ def get_hcc_persistent_grid_points(*, grid_config: GridConfig) -> FloatND: return get_hcc_persistent_shock(grid_config=grid_config).to_jax() -def _build_aime_grid(*, fixed_params: UserParams) -> PiecewiseLinSpacedGrid: +def _build_aime_grid( + *, pia_aime_grid: ArrayLike, points_per_segment: tuple[int, int, int, int] +) -> PiecewiseLinSpacedGrid: """Return the AIME grid. The grid is piecewise-linspaced with breakpoints at the PIA bends - in `fixed_params["pia_aime_grid"]` and `_AIME_PIECE_N_POINTS` in + in `pia_aime_grid` and `points_per_segment` in each segment. The fifth bend point is the delayed-retirement-credit extension above the taxable max, so the grid carries four segments. - `n_aime_gridpoints` from `grid_config` is ignored on this path; the - total is fixed by the PIA structure (`sum(_AIME_PIECE_N_POINTS)`). + `n_aime_gridpoints` from `grid_config` is ignored on this path. """ - kinks = [float(k) for k in np.asarray(fixed_params["pia_aime_grid"])] + kinks = [float(k) for k in np.asarray(pia_aime_grid)] return PiecewiseLinSpacedGrid( start=kinks[0], stop=kinks[4], @@ -421,7 +417,7 @@ def _build_aime_grid(*, fixed_params: UserParams) -> PiecewiseLinSpacedGrid: GridBreakpoint(value=kinks[2]), GridBreakpoint(value=kinks[3]), ), - points_per_segment=_AIME_PIECE_N_POINTS, + points_per_segment=points_per_segment, ) @@ -460,30 +456,28 @@ def _compute_max_annual_labor_income( ) -# Structural stage data, shared by scheduled support and the numerical router. -# Each stage covers the half-open age interval `[start, stop)`. -_AGE_STAGES = ( - ( - (config.start_age, config.ss_early_age), - ("nomc_inelig", "dimc_inelig"), - ), - ( - (config.ss_early_age, config.medicare_age), - ("nomc_choose", "dimc_choose"), - ), - ( - (config.medicare_age, config.ss_forced_age), - ("forced_choose",) * 2, - ), - ( - (config.ss_forced_age, config.work_forced_out_age), - ("forced_forced",) * 2, - ), - ( - (config.work_forced_out_age, MODEL_AGES[-1]), - ("forcedout",) * 2, - ), -) +def age_stages( + *, final_age: int +) -> tuple[tuple[tuple[int, int], tuple[str, str]], ...]: + """Return the structural stages living through ages before `final_age`. + + Shared by scheduled support and the numerical router. Each stage covers the + half-open age interval `[start, stop)`, cut off at `final_age`, the first + age at which everybody is dead. A stage that starts at or after `final_age` + covers no age. + """ + stages = ( + ((config.start_age, config.ss_early_age), ("nomc_inelig", "dimc_inelig")), + ((config.ss_early_age, config.medicare_age), ("nomc_choose", "dimc_choose")), + ((config.medicare_age, config.ss_forced_age), ("forced_choose",) * 2), + ((config.ss_forced_age, config.work_forced_out_age), ("forced_forced",) * 2), + ((config.work_forced_out_age, config.end_age), ("forcedout",) * 2), + ) + return tuple( + ((start, min(stop, final_age)), branches) for (start, stop), branches in stages + ) + + # The living regimes a subject may start in: pre-claiming, pre-Medicare. ENTRY_REGIMES = ( "retiree_nomc_inelig_canwork", @@ -493,16 +487,22 @@ def _compute_max_annual_labor_income( "nongroup_dimc_inelig_canwork", ) -# Admissible starting (age, regime) pairs, shared by every model variant: the -# baseline estimation-sample ages. Later ages, and `dead` at any age, are reached only -# through transitions. -INITIAL_NODES = InitialNodes( - by_age={ - age: ENTRY_REGIMES - for age in MODEL_AGES - if config.start_age <= age <= config.last_start_age - } -) + +def build_entry_initial_nodes(*, ages: tuple[int, ...]) -> InitialNodes: + """Admit the entry regimes at the baseline estimation-sample ages. + + Shared by every model variant. Later ages, and `dead` at any age, are reached + only through transitions. Start ages stop before the final age, at which + everybody is dead. + """ + return InitialNodes( + by_age={ + age: ENTRY_REGIMES + for age in ages[:-1] + if config.start_age <= age <= config.last_start_age + } + ) + _STAGE_KEY = { ("nomc", "inelig", "canwork"): "nomc_inelig", @@ -513,19 +513,61 @@ def _compute_max_annual_labor_income( ("oamc", "forced", "canwork"): "forced_forced", ("oamc", "forced", "forcedout"): "forcedout", } -# Dynamic JAX period lookup and construction-time schedule use the same clock. -_NEXT_AGES = np.asarray([float(a) for a in MODEL_AGES[1:]]) -def transition_ages(spec: RegimeSpec) -> tuple[int, ...]: - """Exact source coordinates at which the template declares its law.""" +def transition_ages( + spec: RegimeSpec, *, ages: tuple[int, ...] = MODEL_AGES +) -> tuple[int, ...]: + """Exact source coordinates at which the template declares its law. + + Empty when the regime's stage starts at or after the final age of `ages`. + """ key = _STAGE_KEY.get((spec["mc"], spec["ss"], spec["canwork"])) - for (start, stop), branches in _AGE_STAGES: + for (start, stop), branches in age_stages(final_age=ages[-1]): if key in branches: - return tuple(age for age in MODEL_AGES if start <= age < stop) + return tuple(age for age in ages if start <= age < stop) raise ValueError(f"Unknown regime spec: {spec}") +# Model-level params that only the regimes able to claim Social Security read. +CLAIMING_PARAMS = frozenset( + { + "early_ret_adjustment", + "earnings_test_fraction", + "earnings_test_threshold", + "normal_retirement_age", + } +) + + +def reachable_regimes(*, ages: tuple[int, ...]) -> tuple[RegimeName, ...]: + """Return the living regimes a model over `ages` can reach. + + A regime is reachable when its stage covers a source age before the final + age, the same rule that gives it transition ages and edges. + """ + return tuple( + name for name, spec in REGIME_SPECS.items() if transition_ages(spec, ages=ages) + ) + + +def select_horizon_params[V]( + *, params: Mapping[str, V], ages: tuple[int, ...] +) -> dict[str, V]: + """Return the entries of `params` that a model over `ages` reads. + + `params` is written for the full horizon. The regime-level entries of + regimes `reachable_regimes` excludes are left out, and so are + `CLAIMING_PARAMS` when no reachable regime can claim Social Security. + Every entry is kept for the full horizon. + """ + reachable = reachable_regimes(ages=ages) + unreachable = set(REGIME_SPECS) - set(reachable) + if not any(REGIME_SPECS[name]["ss"] != "inelig" for name in reachable): + unreachable |= CLAIMING_PARAMS + return {key: value for key, value in params.items() if key not in unreachable} + + def build_restart_initial_nodes(*, ages: Iterable[int]) -> InitialNodes: """Admit every living regime active at each of `ages` as a start. @@ -544,21 +586,24 @@ def build_restart_initial_nodes(*, ages: Iterable[int]) -> InitialNodes: ) -def next_model_age(period: Period) -> FloatND: - """Advance by one grid position, never by an assumed number of years. +def next_model_age(period: Period, *, ages: tuple[int, ...]) -> FloatND: + """Advance by one position on `ages`, never by an assumed number of years. - Only covered nonterminal source periods call this function; no clipping - or extrapolation of invalid period indices is part of the contract. + Dynamic JAX period lookup and the construction-time schedule use the same + clock. Only covered nonterminal source periods call this function; no + clipping or extrapolation of invalid period indices is part of the contract. This does not by itself recalibrate ACA to a different period length. """ - return jnp.asarray(_NEXT_AGES)[period] + return jnp.asarray(np.asarray([float(age) for age in ages[1:]]))[period] -def _target_pair(next_age: int, group: dict[str, int]) -> tuple[int, int]: - if next_age == MODEL_AGES[-1]: +def _target_pair( + next_age: int, group: dict[str, int], *, final_age: int +) -> tuple[int, int]: + if next_age == final_age: dead = int(RegimeId.dead) return dead, dead - for (start, stop), branches in _AGE_STAGES: + for (start, stop), branches in age_stages(final_age=final_age): if start <= next_age < stop: return group[branches[0]], group[branches[1]] raise ValueError(f"Next age {next_age} is outside the declared stages") @@ -568,6 +613,7 @@ def build_regime_edges( *, spec: RegimeSpec, target_groups: tuple[dict[str, int], ...], + ages: tuple[int, ...], ) -> dict[RegimeName, tuple[int, ...]]: """Map each destination to the exact source ages that can reach it.""" # Both Medicare branches are reachable from every living regime: before 65 a @@ -576,10 +622,12 @@ def build_regime_edges( int(getattr(RegimeId, name)): name for name in (*REGIME_SPECS, "dead") } grouped: dict[RegimeName, list[int]] = {} - next_age_by_age = dict(itertools.pairwise(MODEL_AGES)) - for age in transition_ages(spec): + next_age_by_age = dict(itertools.pairwise(ages)) + for age in transition_ages(spec, ages=ages): next_age = next_age_by_age[age] - pairs = tuple(_target_pair(next_age, group) for group in target_groups) + pairs = tuple( + _target_pair(next_age, group, final_age=ages[-1]) for group in target_groups + ) supported_ids = {target for pair in pairs for target in pair} target_ids = tuple(sorted(supported_ids | {int(RegimeId.dead)})) for target_id in target_ids: @@ -587,10 +635,12 @@ def build_regime_edges( return {target: tuple(source_ages) for target, source_ages in grouped.items()} -def build_model_edges() -> dict[RegimeName, dict[RegimeName, tuple[int, ...]]]: +def build_model_edges( + *, ages: tuple[int, ...] = MODEL_AGES +) -> dict[RegimeName, dict[RegimeName, tuple[int, ...]]]: """Declare the policy-invariant topology of the living ACA regimes.""" return { - name: build_regime_edges(spec=spec, target_groups=make_targets(name)) + name: build_regime_edges(spec=spec, target_groups=make_targets(name), ages=ages) for name, spec in REGIME_SPECS.items() } @@ -600,21 +650,28 @@ def build_regime_transition( spec: RegimeSpec, transition_func: Callable[..., FloatND], target_groups: tuple[dict[str, int], ...], + ages: tuple[int, ...], ) -> ByAge: """Name each destination's probability cell at the source ages that reach it. One scalar probability cell per destination is shared by every source age; - the ages with the same destinations form one case. + the ages with the same destinations form one case. A regime whose stage + starts at or after the final age of `ages` is unreachable; its schedule + holds only the `dead` cell as a default that no period reads. """ - edges = build_regime_edges(spec=spec, target_groups=target_groups) + edges = build_regime_edges(spec=spec, target_groups=target_groups, ages=ages) cells = build_granular_regime_transition( transition_func=transition_func, target_ids=(int(getattr(RegimeId, target)) for target in edges), ) ages_by_targets: dict[tuple[RegimeName, ...], list[int]] = {} - for age in transition_ages(spec): - targets = tuple(target for target, ages in edges.items() if age in ages) + for age in transition_ages(spec, ages=ages): + targets = tuple( + target for target, source_ages in edges.items() if age in source_ages + ) ages_by_targets.setdefault(targets, []).append(age) + if not ages_by_targets: + return ByAge(cases={}, default=cells) return ByAge( cases={ tuple(ages): {target: cells[target] for target in targets} @@ -863,12 +920,10 @@ def build_model_functions(*, solver: SolverName = "brute_force") -> dict: # assets adjustment, both of which scale by the marginal income tax rate. functions["marginal_tax_rate"] = taxes.marginal_rate - # HIC premium - functions["predicted_hcc_insurer"] = health_insurance.hcc_insurer_predicted - # Transfers functions["consumption_dollars_floor"] = assets_and_income.consumption_dollars_floor - functions["transfers"] = assets_and_income.transfers + if solver == "brute_force": + functions["transfers"] = assets_and_income.transfers functions["consumption_equiv"] = preferences.consumption_equiv return functions @@ -1017,10 +1072,8 @@ def build_common_functions(spec: RegimeSpec, *, subtract_bill: bool = False) -> if spec["mc"] == "oamc" else health_insurance.is_disabled_from_health ) - # MAGI for the ACA Medicaid expansion track; pruned in the baseline DAG. - functions["aca_magi"] = health_insurance.aca_magi - # Swapped per policy variant by the ACA overlay, hence regime-level + functions["predicted_hcc_insurer"] = health_insurance.hcc_insurer_predicted functions["is_medicaid_eligible"] = health_insurance.is_medicaid_eligible functions["after_tax_income"] = taxes.after_tax_income if subtract_bill: @@ -1187,10 +1240,15 @@ def select_target_for_age( next_age: int | IntND | FloatND, mc_next: bool | BoolND, tgts: dict[str, int], + *, + final_age: int = config.end_age, ) -> IntND: - """Select with the same stage table that supplies the schedule's support.""" + """Select with the same stage table that supplies the schedule's support. + + A `next_age` at or after `final_age` selects `dead`. + """ result = jnp.asarray(RegimeId.dead) - for (start, stop), branches in reversed(_AGE_STAGES): + for (start, stop), branches in reversed(age_stages(final_age=final_age)): target = jnp.where(jnp.array(mc_next), tgts[branches[1]], tgts[branches[0]]) inside = (next_age >= start) & (next_age < stop) result = jnp.where(inside, target, result) diff --git a/src/aca_model/baseline/regimes/_dcegm.py b/src/aca_model/baseline/regimes/_dcegm.py index 54e3ab2..588cbae 100644 --- a/src/aca_model/baseline/regimes/_dcegm.py +++ b/src/aca_model/baseline/regimes/_dcegm.py @@ -11,6 +11,7 @@ the one piece that needs `lcm.solvers`. """ +import numpy as np from lcm import IrregSpacedGrid from lcm.solvers import DCEGM @@ -31,7 +32,9 @@ def build_dcegm_solver(grids: Grids) -> DCEGM: assets_points = grids.assets.to_jax() savings_stop = float(assets_points[-1]) - float(assets_points[0]) savings_grid = IrregSpacedGrid( - points=tuple(savings_stop * (i / (n_points - 1)) ** 3 for i in range(n_points)), + points=np.array( + [savings_stop * (i / (n_points - 1)) ** 3 for i in range(n_points)] + ), ) return DCEGM(savings_grid=savings_grid) diff --git a/src/aca_model/baseline/regimes/_nbegm.py b/src/aca_model/baseline/regimes/_nbegm.py index 23fb96a..1007ed0 100644 --- a/src/aca_model/baseline/regimes/_nbegm.py +++ b/src/aca_model/baseline/regimes/_nbegm.py @@ -4,6 +4,7 @@ Device placement and compiled program widths belong to the model execution policy. """ +import numpy as np from lcm import IrregSpacedGrid from lcm.solvers import NBEGM @@ -17,7 +18,9 @@ def build_nbegm_solver(grids: Grids) -> NBEGM: assets_points = grids.assets.to_jax() savings_stop = float(assets_points[-1]) - float(assets_points[0]) savings_grid = IrregSpacedGrid( - points=tuple(savings_stop * (i / (n_points - 1)) ** 3 for i in range(n_points)), + points=np.array( + [savings_stop * (i / (n_points - 1)) ** 3 for i in range(n_points)] + ), ) return NBEGM( savings_grid=savings_grid, diff --git a/src/aca_model/baseline/regimes/_nongroup.py b/src/aca_model/baseline/regimes/_nongroup.py index a346e0c..4bc48e7 100644 --- a/src/aca_model/baseline/regimes/_nongroup.py +++ b/src/aca_model/baseline/regimes/_nongroup.py @@ -41,6 +41,8 @@ def _make_transition_canwork( own: dict[str, int], + *, + ages: tuple[int, ...], ) -> Callable[..., FloatND]: """Create transition for canwork nongroup regimes. @@ -58,8 +60,12 @@ def transition( ) -> FloatND: del age # Keep the legacy signature; period owns the clock lookup. return build_regime_probs_with_di_medicare( - target_dimc=select_target_for_age(next_model_age(period), True, own), - target_nomc=select_target_for_age(next_model_age(period), False, own), + target_dimc=select_target_for_age( + next_model_age(period, ages=ages), True, own, final_age=ages[-1] + ), + target_nomc=select_target_for_age( + next_model_age(period, ages=ages), False, own, final_age=ages[-1] + ), prob_dimc=prob_di_medicare_next( labor_supply, prob_disabled_next[period, health] ), @@ -72,6 +78,8 @@ def transition( def _make_transition_forcedout( gets_medicare: bool, own: dict[str, int], + *, + ages: tuple[int, ...], ) -> Callable[..., FloatND]: """Create transition for forcedout nongroup regimes. @@ -86,7 +94,9 @@ def transition( survival_probs: FloatND, ) -> FloatND: del age # Keep the legacy signature; period owns the clock lookup. - target = select_target_for_age(next_model_age(period), gets_medicare, own) + target = select_target_for_age( + next_model_age(period, ages=ages), gets_medicare, own, final_age=ages[-1] + ) return build_regime_probs(target, survival_probs[period, health]) return transition @@ -137,17 +147,21 @@ def build_constraints(spec: RegimeSpec) -> dict: return {} -def build_law(name: str) -> ByAge: - """Build the nongroup regime's per-target transition probabilities by source age.""" +def build_law(name: str, *, ages: tuple[int, ...]) -> ByAge: + """Build the nongroup regime's per-target transition probabilities by source age. + + `ages` is the model's age grid; the final age is the first at which everybody + is dead. + """ spec = REGIME_SPECS[name] gets_mc = spec["mc"] != "nomc" own, _ng = make_targets(name) if spec["canwork"] == "canwork": - transition_func = _make_transition_canwork(own) + transition_func = _make_transition_canwork(own, ages=ages) else: - transition_func = _make_transition_forcedout(gets_mc, own) + transition_func = _make_transition_forcedout(gets_mc, own, ages=ages) return build_regime_transition( - spec=spec, transition_func=transition_func, target_groups=(own,) + spec=spec, transition_func=transition_func, target_groups=(own,), ages=ages ) diff --git a/src/aca_model/baseline/regimes/_retiree.py b/src/aca_model/baseline/regimes/_retiree.py index a0f304b..0789376 100644 --- a/src/aca_model/baseline/regimes/_retiree.py +++ b/src/aca_model/baseline/regimes/_retiree.py @@ -46,6 +46,8 @@ def _make_transition_canwork( own: dict[str, int], ng: dict[str, int], + *, + ages: tuple[int, ...], ) -> Callable[..., FloatND]: """Create transition for canwork retiree regimes. @@ -65,11 +67,13 @@ def transition( prob_disabled_next: FloatND, ) -> FloatND: del age # Keep the legacy signature; period owns the clock lookup. - next_age = next_model_age(period) + next_age = next_model_age(period, ages=ages) def target(mc_next: bool) -> IntND: - own_target = select_target_for_age(next_age, mc_next, own) - ng_target = select_target_for_age(next_age, mc_next, ng) + own_target = select_target_for_age( + next_age, mc_next, own, final_age=ages[-1] + ) + ng_target = select_target_for_age(next_age, mc_next, ng, final_age=ages[-1]) return jnp.where(is_ssi_eligible, ng_target, own_target) return build_regime_probs_with_di_medicare( @@ -88,6 +92,8 @@ def _make_transition_forcedout( gets_medicare: bool, own: dict[str, int], ng: dict[str, int], + *, + ages: tuple[int, ...], ) -> Callable[..., FloatND]: """Create transition for forcedout retiree regimes. @@ -104,9 +110,9 @@ def transition( ) -> FloatND: del age # Keep the legacy signature; period owns the clock lookup. sp = survival_probs[period, health] - next_age = next_model_age(period) - target = select_target_for_age(next_age, gets_medicare, own) - ng_ssi = select_target_for_age(next_age, gets_medicare, ng) + next_age = next_model_age(period, ages=ages) + target = select_target_for_age(next_age, gets_medicare, own, final_age=ages[-1]) + ng_ssi = select_target_for_age(next_age, gets_medicare, ng, final_age=ages[-1]) target = jnp.where(is_ssi_eligible, ng_ssi, target) return build_regime_probs(target, sp) @@ -133,17 +139,21 @@ def _build_functions(spec: RegimeSpec, *, subtract_bill: bool = False) -> dict: return functions -def build_law(name: str) -> ByAge: - """Build the retiree regime's per-target transition probabilities by source age.""" +def build_law(name: str, *, ages: tuple[int, ...]) -> ByAge: + """Build the retiree regime's per-target transition probabilities by source age. + + `ages` is the model's age grid; the final age is the first at which everybody + is dead. + """ spec = REGIME_SPECS[name] gets_mc = spec["mc"] != "nomc" own, ng = make_targets(name) if spec["canwork"] == "canwork": - transition_func = _make_transition_canwork(own, ng) + transition_func = _make_transition_canwork(own, ng, ages=ages) else: - transition_func = _make_transition_forcedout(gets_mc, own, ng) + transition_func = _make_transition_forcedout(gets_mc, own, ng, ages=ages) return build_regime_transition( - spec=spec, transition_func=transition_func, target_groups=(own, ng) + spec=spec, transition_func=transition_func, target_groups=(own, ng), ages=ages ) diff --git a/src/aca_model/baseline/regimes/_tied.py b/src/aca_model/baseline/regimes/_tied.py index 9a9c4b3..e627975 100644 --- a/src/aca_model/baseline/regimes/_tied.py +++ b/src/aca_model/baseline/regimes/_tied.py @@ -47,6 +47,8 @@ def _make_transition_canwork( own: dict[str, int], ng: dict[str, int], + *, + ages: tuple[int, ...], ) -> Callable[..., FloatND]: """Create transition for canwork tied regimes. @@ -66,12 +68,14 @@ def transition( prob_disabled_next: FloatND, ) -> FloatND: del age # Keep the legacy signature; period owns the clock lookup. - next_age = next_model_age(period) + next_age = next_model_age(period, ages=ages) to_nongroup = (labor_supply == LaborSupply.do_not_work) | is_ssi_eligible def target(mc_next: bool) -> IntND: - own_target = select_target_for_age(next_age, mc_next, own) - ng_target = select_target_for_age(next_age, mc_next, ng) + own_target = select_target_for_age( + next_age, mc_next, own, final_age=ages[-1] + ) + ng_target = select_target_for_age(next_age, mc_next, ng, final_age=ages[-1]) return jnp.where(to_nongroup, ng_target, own_target) return build_regime_probs_with_di_medicare( @@ -101,13 +105,17 @@ def _build_functions(spec: RegimeSpec, *, subtract_bill: bool = False) -> dict: return functions -def build_law(name: str) -> ByAge: - """Build the tied regime's per-target transition probabilities by source age.""" +def build_law(name: str, *, ages: tuple[int, ...]) -> ByAge: + """Build the tied regime's per-target transition probabilities by source age. + + `ages` is the model's age grid; the final age is the first at which everybody + is dead. + """ spec = REGIME_SPECS[name] own, ng = make_targets(name) - transition_func = _make_transition_canwork(own, ng) + transition_func = _make_transition_canwork(own, ng, ages=ages) return build_regime_transition( - spec=spec, transition_func=transition_func, target_groups=(own, ng) + spec=spec, transition_func=transition_func, target_groups=(own, ng), ages=ages ) diff --git a/src/aca_model/benchmark.py b/src/aca_model/benchmark.py index c3ca289..4ef0e9c 100644 --- a/src/aca_model/benchmark.py +++ b/src/aca_model/benchmark.py @@ -29,15 +29,17 @@ import jax.numpy as jnp import numpy as np from jax import Array -from lcm import DiscreteGrid, ExecutionConfig, InitialNodes, Model +from lcm import DiscreteGrid, Model -from aca_model.agent.health import GoodHealth -from aca_model.agent.labor_market import IsMarried from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.health_insurance import HealthInsuranceState -from aca_model.baseline.model import create_model -from aca_model.baseline.regimes import ENTRY_REGIMES, INITIAL_NODES -from aca_model.config import BENCHMARK_GRID_CONFIG, GridConfig +from aca_model.baseline.model import build_model_spec, create_model +from aca_model.baseline.regimes import ENTRY_REGIMES, select_horizon_params +from aca_model.config import ( + BENCHMARK_GRID_CONFIG, + MODEL_CONFIG, + GridConfig, + model_ages, +) from aca_model.consumption_dollars_grid import ( compute_consumption_dollars_points, inject_consumption_dollars_points, @@ -50,14 +52,6 @@ _N_BENCHMARK_PREF_TYPES = len(DiscreteGrid(BenchmarkPrefType).categories) -_DERIVED_CATEGORICALS = { - "good_health": DiscreteGrid(GoodHealth), - "is_married": DiscreteGrid(IsMarried), - "his": DiscreteGrid(HealthInsuranceState), - "target_his": DiscreteGrid(HealthInsuranceState), - "pref_type": DiscreteGrid(BenchmarkPrefType), -} - # The five entry regimes (inelig + canwork). All have # HealthWithDisability (3-state); four have lagged_labor_supply (tied # does not — it's implied by the regime). @@ -67,8 +61,9 @@ def create_benchmark_model( *, pref_type_grid: DiscreteGrid, grid_config: GridConfig = BENCHMARK_GRID_CONFIG, - execution_config: ExecutionConfig | None = None, - initial_nodes: InitialNodes = INITIAL_NODES, + final_age: int = MODEL_CONFIG.end_age, + lottery_contraction: bool = False, + **model_options: Any, ) -> Model: """Create the aca baseline with `BENCHMARK_GRID_CONFIG` and frozen fixed_params. @@ -77,27 +72,30 @@ def create_benchmark_model( Args: pref_type_grid: Pref-type grid; pass `DiscreteGrid(BenchmarkPrefType)`. - grid_config: Economic resolution and medical-shock folding declarations. - execution_config: Explicit hardware-local policy forwarded unchanged. - None uses the smallest selected accelerator allocator limit as the - device-memory budget; CPU construction remains unbudgeted. - initial_nodes: Admissible starting `(age, regime)` pairs, forwarded - to `create_model`. + grid_config: Economic resolution and numerical choices. + final_age: First age at which everybody is dead, forwarded to + `build_model_spec` and `get_benchmark_params`. The default is the + full horizon; the frozen age-indexed parameters cover it, and a + shorter horizon reads a prefix of them. + lottery_contraction: Forwarded to `build_model_spec`. + **model_options: Generic `lcm.Model` options forwarded to + `create_model`, e.g. `execution_config` or an `initial_nodes` + override. """ - fixed_params, wage_params, _ = get_benchmark_params(model=None) - return create_model( + fixed_params, wage_params, _ = get_benchmark_params(model=None, final_age=final_age) + spec = build_model_spec( grid_config=grid_config, - fixed_params=fixed_params, + pia_aime_grid=fixed_params["pia_aime_grid"], wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, pref_type_grid=pref_type_grid, - execution_config=execution_config, - initial_nodes=initial_nodes, + final_age=final_age, + lottery_contraction=lottery_contraction, ) + return create_model(spec=spec, fixed_params=fixed_params, **model_options) def get_benchmark_params( - *, model: Model | None + *, model: Model | None, final_age: int = MODEL_CONFIG.end_age ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: """Load the frozen `(fixed_params, wage_params, params)` snapshot. @@ -112,6 +110,9 @@ def get_benchmark_params( to skip injection (e.g. when constructing the model with `fixed_params`). + `fixed_params` and `params` hold only what a model ending at `final_age` + reads (`select_horizon_params`); pass the same `final_age` as the model's. + The regime-transition law arguments (`survival_probs`, `prob_disabled_next`) are returned under `fixed_params["edges"][source]`, where pylcm looks for the parameters of edge-declared callables. @@ -122,6 +123,8 @@ def get_benchmark_params( wage_params = data["wage_params"] params = data["params"] max_consumption_dollars = float(fixed_params.pop("max_consumption_dollars")) + ages = model_ages(final_age=final_age) + fixed_params = select_horizon_params(params=fixed_params, ages=ages) if model is not None: params = inject_consumption_dollars_points( params=params, @@ -129,7 +132,7 @@ def get_benchmark_params( max_consumption_dollars=max_consumption_dollars, ) params = inject_consumption_floor_schedule(params=params, model=model) - return fixed_params, wage_params, params + return fixed_params, wage_params, select_horizon_params(params=params, ages=ages) def get_benchmark_consumption_dollars_points(*, n_points: int) -> tuple[float, ...]: @@ -140,7 +143,7 @@ def get_benchmark_consumption_dollars_points(*, n_points: int) -> tuple[float, . snapshot's `consumption_equiv_floor` / `exponent` / `max_consumption_dollars`. DC-EGM builds need the continuous-action grid at model construction, so the points are passed to - `create_model(consumption_dollars_points=...)` instead of injected + `build_model_spec(consumption_dollars_points=...)` instead of injected into params. """ with _PARAMS_FILE.open("rb") as fh: @@ -188,7 +191,7 @@ def get_benchmark_initial_conditions( aime_lo, aime_hi = float(aime_pts.min()), float(aime_pts.max()) hcc_p_pts = np.asarray(grids["hcc_persistent"].to_jax()) # ty: ignore[unresolved-attribute] hcc_t_grid = grids.get("hcc_transitory") - # Preserve the random stream for shared states when the folded state is absent. + # Preserve the random stream for shared states; the transitory shock is no state. hcc_t_pts = ( np.asarray(hcc_t_grid.to_jax()) # ty: ignore[unresolved-attribute] if hcc_t_grid is not None diff --git a/src/aca_model/config.py b/src/aca_model/config.py index d95569b..a093ca5 100644 --- a/src/aca_model/config.py +++ b/src/aca_model/config.py @@ -30,18 +30,21 @@ class GridConfig: n_assets_gridpoints: int = 24 n_aime_gridpoints: int = 12 + # AIME piecewise grid: number of points per segment between the PIA bend + # points (0 → kink_0 → kink_1 → kink_2 → extension), at least 2 each. The + # fourth segment covers the sparse delayed-retirement-credit region above + # the taxable max, so it carries fewer points than the dense lower segments. + aime_points_per_segment: tuple[int, int, int, int] = (10, 11, 11, 6) n_consumption_dollars_gridpoints: int = 70 n_wage_res_gridpoints: int = 5 n_hcc_persistent_gridpoints: int = 3 n_hcc_transitory_gridpoints: int = 5 - # Fold the transitory medical-cost shock out of the state space. Nothing a - # period computes reads last year's transitory shock, so with the fold it is - # drawn on the transition only and no value carries its axis. - fold_hcc_transitory: bool = False # Declare the asset law toward living targets as resources minus the # out-of-pocket bill, so the solve averages each target's value over the # transitory shock once per period instead of at every source point. Needs - # `fold_hcc_transitory` and the brute-force asset law. + # the brute-force asset law. The transitory shock is read only as its draw + # `next_hcc_transitory`, so pylcm integrates it out and no value carries its + # axis, with or without this option. subtract_hcc_bill: bool = False # The post-decision savings grid is cubically clustered toward the borrowing # constraint. Its node count controls resolution under DC-EGM and NB-EGM. @@ -59,15 +62,40 @@ class GridConfig: MODEL_CONFIG = ModelConfig() + + +def model_ages(*, final_age: int) -> tuple[int, ...]: + """Return the model's ages, from `start_age` through `final_age`. + + `final_age` is the first age at which everybody is dead, so the model has + `final_age - start_age` nonterminal periods. The age-indexed data cover + `start_age` through `MODEL_CONFIG.end_age`; a shorter horizon reads a prefix + of them. + + Raises: + ValueError: If `final_age` leaves no nonterminal period or lies beyond + `MODEL_CONFIG.end_age`. + + """ + _fail_if_invalid_final_age(final_age) + return tuple(range(MODEL_CONFIG.start_age, final_age + 1)) + + +def _fail_if_invalid_final_age(final_age: int) -> None: + if not MODEL_CONFIG.start_age < final_age <= MODEL_CONFIG.end_age: + msg = ( + f"final_age must lie in ({MODEL_CONFIG.start_age}, " + f"{MODEL_CONFIG.end_age}], got {final_age}." + ) + raise ValueError(msg) + + # ACA is calibrated annually. Keep the exact clock on the host until Model build; # importing a task or regime builder must not initialize a JAX device allocator. -MODEL_AGES: tuple[int, ...] = tuple( - range(MODEL_CONFIG.start_age, MODEL_CONFIG.end_age + 1) -) +MODEL_AGES: tuple[int, ...] = model_ages(final_age=MODEL_CONFIG.end_age) GRID_CONFIG = GridConfig() BENCHMARK_GRID_CONFIG = GridConfig( - fold_hcc_transitory=True, subtract_hcc_bill=True, n_assets_gridpoints=3, n_aime_gridpoints=3, diff --git a/tests/conftest.py b/tests/conftest.py index 1da1dcf..49b62ae 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,46 @@ +"""Session-scoped models shared by every test that builds one with the same arguments. + +Under pytest-xdist each worker builds each model at most once. Tests read these +models and may solve or simulate them; none reassigns their attributes. +""" + +import functools import sys +from collections.abc import Callable from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) + +import pytest +from helpers.model import make_aca_model, make_baseline_model +from lcm import DiscreteGrid, Model + +from aca_model.aca.health_insurance import PolicyVariant +from aca_model.agent.preferences import BenchmarkPrefType +from aca_model.benchmark import create_benchmark_model + + +@pytest.fixture(scope="session") +def benchmark_model() -> Model: + """`create_benchmark_model` with the 2-type preference grid and its defaults. + + The same model as `make_baseline_model(grid_config=BENCHMARK_GRID_CONFIG)`. + """ + return create_benchmark_model(pref_type_grid=DiscreteGrid(BenchmarkPrefType)) + + +@pytest.fixture(scope="session") +def baseline_model() -> Model: + """`make_baseline_model()`: the benchmark snapshot on the plain asset law.""" + return make_baseline_model() + + +@pytest.fixture(scope="session") +def aca_model_for() -> Callable[[PolicyVariant], Model]: + """Return `make_aca_model` for a policy, built once per policy.""" + + @functools.cache + def build(policy: PolicyVariant) -> Model: + return make_aca_model(policy=policy) + + return build diff --git a/tests/helpers/model.py b/tests/helpers/model.py index 3645ab7..527739b 100644 --- a/tests/helpers/model.py +++ b/tests/helpers/model.py @@ -10,12 +10,8 @@ from lcm import DiscreteGrid, Model from aca_model.aca.health_insurance import PolicyVariant -from aca_model.aca.model import create_model as _create_aca_model -from aca_model.agent.health import GoodHealth -from aca_model.agent.labor_market import IsMarried from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.health_insurance import HealthInsuranceState -from aca_model.baseline.model import create_model as _create_baseline_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.baseline.regimes import REGIME_SPECS from aca_model.benchmark import get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG, GridConfig @@ -26,28 +22,20 @@ if spec["his"] == "nongroup" and spec["mc"] == "nomc" ) -_DERIVED_CATEGORICALS = { - "good_health": DiscreteGrid(GoodHealth), - "is_married": DiscreteGrid(IsMarried), - "his": DiscreteGrid(HealthInsuranceState), - "target_his": DiscreteGrid(HealthInsuranceState), - "pref_type": DiscreteGrid(BenchmarkPrefType), -} - -_UNFOLDED_GRID_CONFIG = replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False -) +_PLAIN_LAW_GRID_CONFIG = replace(BENCHMARK_GRID_CONFIG, subtract_hcc_bill=False) -def make_baseline_model(*, grid_config: GridConfig = _UNFOLDED_GRID_CONFIG) -> Model: +def make_baseline_model(*, grid_config: GridConfig = _PLAIN_LAW_GRID_CONFIG) -> Model: """Baseline model on `grid_config` with the benchmark snapshot params.""" fixed_params, wage_params, _ = get_benchmark_params(model=None) - return _create_baseline_model( + return create_model( + spec=build_model_spec( + pia_aime_grid=fixed_params["pia_aime_grid"], + wage_params=wage_params, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + ), fixed_params=fixed_params, - wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) @@ -72,15 +60,17 @@ def aca_fixed_params(*, fixed_params: dict, policy: PolicyVariant) -> dict: def make_aca_model( - *, policy: PolicyVariant, grid_config: GridConfig = _UNFOLDED_GRID_CONFIG + *, policy: PolicyVariant, grid_config: GridConfig = _PLAIN_LAW_GRID_CONFIG ) -> Model: """ACA model on `grid_config` with the benchmark snapshot params.""" fixed_params, wage_params, _ = get_benchmark_params(model=None) - return _create_aca_model( - policy=policy, + return create_model( + spec=build_model_spec( + pia_aime_grid=fixed_params["pia_aime_grid"], + policy=policy, + wage_params=wage_params, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + ), fixed_params=aca_fixed_params(fixed_params=fixed_params, policy=policy), - wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) diff --git a/tests/test_aca_employer_coverage.py b/tests/test_aca_employer_coverage.py index 53f6f6f..6b92443 100644 --- a/tests/test_aca_employer_coverage.py +++ b/tests/test_aca_employer_coverage.py @@ -21,7 +21,7 @@ _make_transition_canwork as retiree_canwork, ) from aca_model.baseline.regimes._tied import _make_transition_canwork as tied_canwork -from aca_model.config import MODEL_CONFIG +from aca_model.config import MODEL_AGES, MODEL_CONFIG N_PERIODS = MODEL_CONFIG.end_age - MODEL_CONFIG.start_age SURVIVAL = jnp.ones((N_PERIODS, 3)) * 0.99 @@ -81,7 +81,7 @@ def test_expansion_only_medicaid_keeps_employer_coverage( ) -> None: """An employer-covered household eligible only via the expansion keeps it.""" own, ng = make_targets(regime_name) - transition = make_transition(own=own, ng=ng) + transition = make_transition(own=own, ng=ng, ages=MODEL_AGES) result = _compose_with_aca_eligibility( "next_regime", transition, diff --git a/tests/test_aca_plan.py b/tests/test_aca_plan.py index c8b0e3c..8686faa 100644 --- a/tests/test_aca_plan.py +++ b/tests/test_aca_plan.py @@ -83,6 +83,21 @@ def test_aca_non_group_premium_is_community_rated( assert _aca_premium(policy, spousal_income) == pytest.approx(expected) +@pytest.mark.parametrize("policy", list(PolicyVariant)) +def test_aca_non_group_risk_prediction_is_registered_only_without_reform( + policy: PolicyVariant, +) -> None: + """The community-rated premium does not register a risk prediction node.""" + functions = {**build_model_functions(), **_build_functions(REGIME_SPECS[REGIME])} + apply_aca_overrides(functions, REGIME_SPECS[REGIME], policy) + expected = ( + health_insurance.hcc_insurer_predicted + if policy == PolicyVariant.ACA_ONLY_MEDICAID_EXPANSION + else None + ) + assert functions.get("predicted_hcc_insurer") is expected + + RISK_RATED_PREMIUM_PARAMS = frozenset( { "premium_markup", diff --git a/tests/test_additive_shock_medical_bill.py b/tests/test_additive_shock_medical_bill.py index 9fff9d0..0a2d0f4 100644 --- a/tests/test_additive_shock_medical_bill.py +++ b/tests/test_additive_shock_medical_bill.py @@ -10,28 +10,23 @@ """ from collections.abc import Mapping -from dataclasses import replace import jax.numpy as jnp import lcm import numpy as np import pytest -from helpers.model import make_baseline_model from aca_model.agent import assets_and_income from aca_model.baseline.health_insurance import negative_oop_costs from aca_model.benchmark import get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG -_FOLDED = replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=True, subtract_hcc_bill=False -) -_ADDITIVE = replace(_FOLDED, subtract_hcc_bill=True) - @pytest.fixture(scope="module") -def additive_model() -> lcm.Model: - return make_baseline_model(grid_config=_ADDITIVE) +def additive_model(benchmark_model: lcm.Model) -> lcm.Model: + """The benchmark grids subtract the medical bill as an additive shock.""" + assert BENCHMARK_GRID_CONFIG.subtract_hcc_bill + return benchmark_model def test_negative_oop_costs_is_the_negated_bill() -> None: @@ -55,15 +50,15 @@ def test_every_target_adds_the_negated_bill(additive_model: lcm.Model) -> None: @pytest.mark.long_running def test_additive_shock_value_equals_the_plain_law_value( - additive_model: lcm.Model, + additive_model: lcm.Model, baseline_model: lcm.Model ) -> None: """The two routes sum the same terms in a different order.""" - folded_model = make_baseline_model(grid_config=_FOLDED) - _, _, params = get_benchmark_params(model=folded_model) - folded_values = folded_model.solve(params=params, log_level="off").values + plain_model = baseline_model + _, _, params = get_benchmark_params(model=plain_model) + plain_values = plain_model.solve(params=params, log_level="off").values additive_values = additive_model.solve(params=params, log_level="off").values - assert set(additive_values) == set(folded_values) - for period, regimes in folded_values.items(): + assert set(additive_values) == set(plain_values) + for period, regimes in plain_values.items(): assert set(additive_values[period]) == set(regimes) for name, values in regimes.items(): np.testing.assert_array_equal( diff --git a/tests/test_aime_grid.py b/tests/test_aime_grid.py index d63da86..170d156 100644 --- a/tests/test_aime_grid.py +++ b/tests/test_aime_grid.py @@ -5,10 +5,10 @@ import jax.numpy as jnp import numpy as np -from aca_model.baseline.regimes._common import ( - _AIME_PIECE_N_POINTS, - _build_aime_grid, -) +from aca_model.baseline.regimes._common import _build_aime_grid +from aca_model.config import GridConfig + +_POINTS_PER_SEGMENT = GridConfig().aime_points_per_segment # Production SSA bend points plus the delayed-retirement-credit extension: # 0, kink_0, kink_1, taxable-max, and the extension point that carries the @@ -19,21 +19,27 @@ def test_build_aime_grid_owns_each_pia_breakpoint_on_the_right() -> None: """The AIME grid preserves four PIA pieces with right-owned interiors.""" - grid = _build_aime_grid(fixed_params=_FIXED_PARAMS) + grid = _build_aime_grid( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + points_per_segment=_POINTS_PER_SEGMENT, + ) np.testing.assert_allclose( [point.value for point in grid.breakpoints], _PIA_AIME_GRID[1:-1], ) assert tuple(point.owner for point in grid.breakpoints) == ("right",) * 3 - assert grid.points_per_segment == _AIME_PIECE_N_POINTS + assert grid.points_per_segment == _POINTS_PER_SEGMENT def test_build_aime_grid_top_point_is_extension_aime() -> None: """The grid reaches the delayed-credit extension AIME at its top.""" - grid = _build_aime_grid(fixed_params=_FIXED_PARAMS) + grid = _build_aime_grid( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + points_per_segment=_POINTS_PER_SEGMENT, + ) np.testing.assert_allclose(float(grid.to_jax().max()), 187954.752, rtol=1e-5) -def test_aime_piece_n_points_has_four_entries() -> None: - """One point-count per segment, including the sparse extension region.""" - assert len(_AIME_PIECE_N_POINTS) == 4 +def test_aime_points_per_segment_default_is_10_11_11_6() -> None: + """One point-count per segment; the extension region is the sparsest.""" + assert _POINTS_PER_SEGMENT == (10, 11, 11, 6) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 74b3af8..4bd1725 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -2,13 +2,16 @@ import numpy as np import pytest +from _lcm.simulation.additional_targets import _collect_all_available_targets from lcm import ( DiscreteGrid, GridBreakpoint, IrregSpacedGrid, + Model, PiecewiseLinSpacedGrid, RouwenhorstAR1Process, ) +from lcm.solvers import GridSearch from aca_model.agent.preferences import BenchmarkPrefType from aca_model.baseline.regimes import REGIME_SPECS @@ -19,11 +22,11 @@ ) -def test_benchmark_model_builds_with_the_current_pylcm_grid_api() -> None: +def test_benchmark_model_builds_with_the_current_pylcm_grid_api( + benchmark_model: Model, +) -> None: """The frozen benchmark preserves its state and action grid extents.""" - model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - ) + model = benchmark_model aime = model.user_regimes["retiree_nomc_inelig_canwork"].states["aime"] assert isinstance(aime, PiecewiseLinSpacedGrid) @@ -47,12 +50,18 @@ def test_benchmark_model_builds_with_the_current_pylcm_grid_api() -> None: assert consumption.n_points == 5 -@pytest.mark.long_running -def test_benchmark_model_simulates_end_to_end() -> None: - n_subjects = 20 +def test_benchmark_model_with_final_age_53_has_three_periods() -> None: + """Ages 51, 52 and 53 make three periods; everybody is dead at 53.""" model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), + pref_type_grid=DiscreteGrid(BenchmarkPrefType), final_age=53 ) + assert model.n_periods == 3 + + +@pytest.mark.long_running +def test_benchmark_model_simulates_end_to_end(benchmark_model: Model) -> None: + n_subjects = 20 + model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( model=model, n_subjects=n_subjects, seed=0 @@ -72,7 +81,9 @@ def test_benchmark_model_simulates_end_to_end() -> None: @pytest.mark.long_running -def test_benchmark_panel_exposes_hic_premium_and_wage_targets() -> None: +def test_benchmark_panel_exposes_hic_premium_and_wage_targets( + benchmark_model: Model, +) -> None: """`hic_premium` and `wage` are computable simulate targets. The MSM estimation matches `hic_private_premium_*` and `wage_growth_*` @@ -83,9 +94,7 @@ def test_benchmark_panel_exposes_hic_premium_and_wage_targets() -> None: target get NaN, alive/worker rows carry a finite value. """ n_subjects = 20 - model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - ) + model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( model=model, n_subjects=n_subjects, seed=0 @@ -112,8 +121,28 @@ def test_benchmark_panel_exposes_hic_premium_and_wage_targets() -> None: assert (defined_wage > 0).all() +def test_benchmark_model_offers_uncompensated_care_targets( + benchmark_model: Model, +) -> None: + """Transfers, the floor and the health-cost covariates can be added to the panel. + + Uncompensated care is the part of `transfers` above + `consumption_dollars_floor`. Total health costs depend on the next period's + shocks, so they are rebuilt from `is_married`, `good_health` and the shock + states rather than offered as a target. + """ + model = benchmark_model + available = _collect_all_available_targets(model._regimes) # noqa: SLF001 + assert { + "transfers", + "consumption_dollars_floor", + "is_married", + "good_health", + } <= available + + @pytest.mark.long_running -def test_benchmark_simulate_obeys_borrowing_constraint() -> None: +def test_benchmark_simulate_obeys_borrowing_constraint(benchmark_model: Model) -> None: """`consumption_dollars <= max(cash_on_hand, floor)` holds for every alive row. The simulator only ever picks feasible actions — the borrowing @@ -144,9 +173,7 @@ def test_benchmark_simulate_obeys_borrowing_constraint() -> None: consumption point, not the floor. """ n_subjects = 4 - model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - ) + model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( model=model, n_subjects=n_subjects, seed=0 @@ -170,9 +197,11 @@ def test_benchmark_simulate_obeys_borrowing_constraint() -> None: ) -def test_initial_conditions_choose_population_size_after_model_construction() -> None: +def test_initial_conditions_choose_population_size_after_model_construction( + benchmark_model: Model, +) -> None: """One model supports reproducible initial conditions with different row counts.""" - model = create_benchmark_model(pref_type_grid=DiscreteGrid(BenchmarkPrefType)) + model = benchmark_model small = get_benchmark_initial_conditions(model=model, n_subjects=2, seed=17) repeated = get_benchmark_initial_conditions(model=model, n_subjects=2, seed=17) large = get_benchmark_initial_conditions(model=model, n_subjects=5, seed=17) @@ -219,3 +248,18 @@ def test_benchmark_regimes_hold_no_law_args() -> None: if arg in fixed_params[name] ] assert leftovers == [] + + +@pytest.mark.parametrize("lottery_contraction", [False, True]) +def test_benchmark_regimes_search_grids_with_the_requested_lottery_contraction( + lottery_contraction: bool, +) -> None: + """Every benchmark regime solves by grid search with the requested contraction.""" + model = create_benchmark_model( + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + final_age=53, + lottery_contraction=lottery_contraction, + ) + assert {regime.solver for regime in model.user_regimes.values()} == { + GridSearch(lottery_contraction=lottery_contraction) + } diff --git a/tests/test_benchmark_folding.py b/tests/test_benchmark_folding.py index 71c096f..b538f05 100644 --- a/tests/test_benchmark_folding.py +++ b/tests/test_benchmark_folding.py @@ -1,21 +1,10 @@ -"""The ACA benchmark activates transitory-shock folding explicitly.""" +"""The ACA benchmark integrates the transitory medical bill out of every state.""" from collections.abc import Mapping -from dataclasses import replace import lcm -import numpy as np -import pytest -from lcm import DiscreteGrid -from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.benchmark import create_benchmark_model, get_benchmark_initial_conditions -from aca_model.config import BENCHMARK_GRID_CONFIG - - -@pytest.fixture(scope="module") -def benchmark_model() -> lcm.Model: - return create_benchmark_model(pref_type_grid=DiscreteGrid(BenchmarkPrefType)) +from aca_model.benchmark import get_benchmark_initial_conditions def test_benchmark_folds_the_transitory_medical_bill( @@ -37,28 +26,3 @@ def test_benchmark_folds_the_transitory_medical_bill( ) initial = get_benchmark_initial_conditions(model=model, n_subjects=8, seed=42) assert "hcc_transitory" not in initial - - -def test_unfolded_control_has_identical_shared_initial_conditions( - benchmark_model: lcm.Model, -) -> None: - control_grid = replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False - ) - control = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), grid_config=control_grid - ) - assert all( - "hcc_transitory" in control.state_names(regime_name=name) - for name in control.user_regimes - if name != "dead" - ) - folded_initial = get_benchmark_initial_conditions( - model=benchmark_model, n_subjects=8, seed=42 - ) - control_initial = get_benchmark_initial_conditions( - model=control, n_subjects=8, seed=42, grid_config=control_grid - ) - assert set(control_initial) == set(folded_initial) | {"hcc_transitory"} - for name, values in folded_initial.items(): - np.testing.assert_array_equal(values, control_initial[name]) diff --git a/tests/test_dag_coverage.py b/tests/test_dag_coverage.py index 16b6472..9eaa79d 100644 --- a/tests/test_dag_coverage.py +++ b/tests/test_dag_coverage.py @@ -3,7 +3,7 @@ import jax.numpy as jnp import pandas as pd import pytest -from helpers.model import make_baseline_model +from lcm import Model from lcm.exceptions import InvalidInitialConditionsError from aca_model.baseline.regimes import ENTRY_REGIMES, REGIME_SPECS @@ -14,8 +14,8 @@ @pytest.fixture(scope="module") -def model(): - return make_baseline_model() +def model(baseline_model: Model) -> Model: + return baseline_model def test_initial_nodes_are_the_age_51_to_60_entry_regimes(model): @@ -134,10 +134,13 @@ def test_select_admissible_starts_drops_starts_at_61_and_above(model): def test_medical_cost_draws_keep_living_states_without_choice_constraints(model): - """Living regimes carry medical shocks; bequests depend only on assets and type.""" + """Living regimes carry the persistent medical shock as a state; the transitory + one is read only as its next-period draw. Bequests depend only on assets and type. + """ for name, regime in model.user_regimes.items(): assert "medical_cost_shocks_carried" not in regime.constraints if name == "dead": assert set(regime.states) == {"assets", "pref_type"} else: - assert {"hcc_persistent", "hcc_transitory"} <= set(regime.states) + assert "hcc_persistent" in regime.states + assert "hcc_transitory" not in regime.states diff --git a/tests/test_dcegm_model_creation.py b/tests/test_dcegm_model_creation.py index fc7645f..4d02cac 100644 --- a/tests/test_dcegm_model_creation.py +++ b/tests/test_dcegm_model_creation.py @@ -11,14 +11,13 @@ import numpy as np import pytest -from helpers.model import _DERIVED_CATEGORICALS from lcm import DiscreteGrid, IrregSpacedGrid, Model, Regime from lcm.consumption_savings_regime import ConsumptionSavingsRegime from lcm.solvers import DCEGM from aca_model.agent import assets_and_income from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.model import create_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.baseline.regimes import ( REGIME_SPECS, SolverName, @@ -29,22 +28,19 @@ get_benchmark_consumption_dollars_points, get_benchmark_params, ) -from aca_model.config import BENCHMARK_GRID_CONFIG +from aca_model.config import BENCHMARK_GRID_CONFIG, MODEL_AGES _FIXED_PARAMS, _WAGE_PARAMS, _ = get_benchmark_params(model=None) -# pylcm folds a shock state only under grid search, and the EGM solvers take the -# savings-form asset law, so the transitory medical-cost shock stays a state and -# the bill stays inside `next_assets`. -_EGM_GRID_CONFIG = dataclasses.replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False -) +# The EGM solvers take the savings-form asset law, so the bill stays inside +# `next_assets`; the transitory medical-cost shock is read only as its draw. +_EGM_GRID_CONFIG = dataclasses.replace(BENCHMARK_GRID_CONFIG, subtract_hcc_bill=False) def _build_regimes(solver: SolverName) -> dict[str, Regime]: return build_all_regimes( grid_config=_EGM_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), solver=solver, @@ -53,12 +49,14 @@ def _build_regimes(solver: SolverName) -> dict[str, Regime]: def _build_model(solver: SolverName) -> Model: return create_model( + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + wage_params=_WAGE_PARAMS, + grid_config=_EGM_GRID_CONFIG, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver=solver, + ), fixed_params=_FIXED_PARAMS, - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=_EGM_GRID_CONFIG, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver=solver, ) @@ -100,9 +98,10 @@ def test_dcegm_model_slots_broadcast_contract_functions_and_constraint() -> None consumption grid and needs the explicit feasibility mask.""" slots = build_model_slots( grid_config=_EGM_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), + ages=MODEL_AGES, solver="dcegm", ) assert "borrowing_constraint" in slots["constraints"] @@ -130,12 +129,14 @@ def test_dcegm_requires_construction_time_consumption_points() -> None: at model construction, so the runtime-injection path cannot be used.""" with pytest.raises(ValueError, match="consumption_dollars_points"): create_model( + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + wage_params=_WAGE_PARAMS, + grid_config=_EGM_GRID_CONFIG, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver="dcegm", + ), fixed_params=_FIXED_PARAMS, - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=_EGM_GRID_CONFIG, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver="dcegm", ) @@ -153,15 +154,17 @@ def test_benchmark_consumption_points_pin_both_floors() -> None: def test_dcegm_benchmark_model_builds() -> None: """The benchmark model accepts `solver="dcegm"` end to end.""" model = create_model( - fixed_params=_FIXED_PARAMS, - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=_EGM_GRID_CONFIG, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver="dcegm", - consumption_dollars_points=get_benchmark_consumption_dollars_points( - n_points=_EGM_GRID_CONFIG.n_consumption_dollars_gridpoints + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + wage_params=_WAGE_PARAMS, + grid_config=_EGM_GRID_CONFIG, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver="dcegm", + consumption_dollars_points=get_benchmark_consumption_dollars_points( + n_points=_EGM_GRID_CONFIG.n_consumption_dollars_gridpoints + ), ), + fixed_params=_FIXED_PARAMS, ) assert isinstance(model.user_regimes["retiree_nomc_inelig_canwork"].solver, DCEGM) @@ -172,7 +175,7 @@ def test_savings_grid_length_follows_grid_config() -> None: grid_config = dataclasses.replace(_EGM_GRID_CONFIG, n_savings_gridpoints=70) regimes = build_all_regimes( grid_config=grid_config, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), solver="dcegm", @@ -189,7 +192,7 @@ def test_dcegm_savings_grid_rejects_too_few_points() -> None: with pytest.raises(ValueError, match="n_savings_gridpoints"): build_all_regimes( grid_config=grid_config, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), solver="dcegm", diff --git a/tests/test_dcegm_parity.py b/tests/test_dcegm_parity.py index 70bfe05..3bd86af 100644 --- a/tests/test_dcegm_parity.py +++ b/tests/test_dcegm_parity.py @@ -18,11 +18,8 @@ import pytest from lcm import DiscreteGrid, Model -from aca_model.agent.health import GoodHealth -from aca_model.agent.labor_market import IsMarried from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.health_insurance import HealthInsuranceState -from aca_model.baseline.model import SolverName, create_model +from aca_model.baseline.model import SolverName, build_model_spec, create_model from aca_model.benchmark import ( get_benchmark_consumption_dollars_points, get_benchmark_initial_conditions, @@ -78,14 +75,6 @@ def _recorded_noise_floor() -> tuple[float, float, float]: ) -_DERIVED_CATEGORICALS = { - "good_health": DiscreteGrid(GoodHealth), - "is_married": DiscreteGrid(IsMarried), - "his": DiscreteGrid(HealthInsuranceState), - "target_his": DiscreteGrid(HealthInsuranceState), - "pref_type": DiscreteGrid(BenchmarkPrefType), -} - _DISCRETE_COLUMNS = ("regime_name", "claim_ss", "labor_supply", "buy_private") _XFAIL_UNTIL_DCEGM_ADMITS_THE_ACA_BUDGET = pytest.mark.xfail( @@ -114,13 +103,15 @@ def _make_model(*, solver: SolverName, grid_config: GridConfig) -> Model: else None ) return create_model( + spec=build_model_spec( + pia_aime_grid=fixed_params["pia_aime_grid"], + wage_params=wage_params, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver=solver, + consumption_dollars_points=consumption_dollars_points, + ), fixed_params=fixed_params, - wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver=solver, - consumption_dollars_points=consumption_dollars_points, ) diff --git a/tests/test_di_medicare_transitions.py b/tests/test_di_medicare_transitions.py index 7c88074..8b128e7 100644 --- a/tests/test_di_medicare_transitions.py +++ b/tests/test_di_medicare_transitions.py @@ -27,7 +27,7 @@ _make_transition_canwork as retiree_canwork, ) from aca_model.baseline.regimes._tied import _make_transition_canwork as tied_canwork -from aca_model.config import MODEL_CONFIG +from aca_model.config import MODEL_AGES, MODEL_CONFIG N_PERIODS = MODEL_CONFIG.end_age - MODEL_CONFIG.start_age SURVIVAL = jnp.full((N_PERIODS, 3), 0.99) @@ -40,7 +40,7 @@ def _nongroup_probs(regime: str, health_state: int, labor: int) -> jnp.ndarray: own, _ = make_targets(regime) - return nongroup_canwork(own=own)( + return nongroup_canwork(own=own, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(health_state), @@ -112,7 +112,7 @@ def test_nongroup_transition_di_medicare_entry_and_exit( def test_retiree_transition_newly_disabled_non_worker_keeps_retiree_cover() -> None: """A retiree who stops working and becomes disabled holds EPHI-Medicare.""" own, ng = make_targets("retiree_nomc_inelig_canwork") - probs = retiree_canwork(own=own, ng=ng)( + probs = retiree_canwork(own=own, ng=ng, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(HealthWithDisability.good), @@ -129,7 +129,7 @@ def test_retiree_transition_newly_disabled_non_worker_keeps_retiree_cover() -> N def test_tied_transition_newly_disabled_non_worker_moves_to_nongroup_medicare() -> None: """A tied worker who stops and becomes disabled moves to non-group Medicare.""" own, ng = make_targets("tied_nomc_inelig_canwork") - probs = tied_canwork(own=own, ng=ng)( + probs = tied_canwork(own=own, ng=ng, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(HealthWithDisability.bad), diff --git a/tests/test_execution_config.py b/tests/test_execution_config.py index 79a47d6..743dfbc 100644 --- a/tests/test_execution_config.py +++ b/tests/test_execution_config.py @@ -1,26 +1,47 @@ -"""Model factories expose pylcm's execution policy without changing economic grids.""" +"""Model factories forward pylcm's generic options without changing economic grids.""" from functools import partial -from types import SimpleNamespace import jax import pytest from helpers.model import aca_fixed_params -from lcm import DiscreteGrid, ExecutionConfig +from lcm import DiscreteGrid, ExecutionConfig, InitialNodes from lcm.exceptions import ExecutionPlanningError -from aca_model.aca import model as aca_model_module from aca_model.aca.health_insurance import PolicyVariant -from aca_model.aca.model import create_model as create_aca_model -from aca_model.agent.health import GoodHealth -from aca_model.agent.labor_market import IsMarried from aca_model.agent.preferences import BenchmarkPrefType from aca_model.baseline import model as baseline_model_module -from aca_model.baseline.health_insurance import HealthInsuranceState -from aca_model.baseline.model import create_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.benchmark import create_benchmark_model, get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG +_DOMAIN_KEYS = frozenset( + { + "regimes", + "ages", + "regime_id_class", + "description", + "derived_categoricals", + "initial_nodes", + "edges", + "functions", + "constraints", + "states", + "state_transitions", + } +) + + +def _spec(*, policy: PolicyVariant | None = None) -> dict: + fixed_params, wage_params, _ = get_benchmark_params(model=None) + return build_model_spec( + policy=policy, + grid_config=BENCHMARK_GRID_CONFIG, + pia_aime_grid=fixed_params["pia_aime_grid"], + wage_params=wage_params, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + ) + def _factory(kind): if kind == "benchmark": @@ -28,27 +49,19 @@ def _factory(kind): create_benchmark_model, pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) - fixed_params, wage_params, _ = get_benchmark_params(model=None) - factory = create_model - if kind == "aca": - factory = partial(create_aca_model, policy=PolicyVariant.ACA) - fixed_params = aca_fixed_params( - fixed_params=fixed_params, policy=PolicyVariant.ACA - ) - return partial( - factory, - fixed_params=fixed_params, - wage_params=wage_params, - derived_categoricals={ - "good_health": DiscreteGrid(GoodHealth), - "is_married": DiscreteGrid(IsMarried), - "his": DiscreteGrid(HealthInsuranceState), - "target_his": DiscreteGrid(HealthInsuranceState), - "pref_type": DiscreteGrid(BenchmarkPrefType), - }, - grid_config=BENCHMARK_GRID_CONFIG, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - ) + fixed_params, _, _ = get_benchmark_params(model=None) + policy = PolicyVariant.ACA if kind == "aca" else None + if policy is not None: + fixed_params = aca_fixed_params(fixed_params=fixed_params, policy=policy) + return partial(create_model, spec=_spec(policy=policy), fixed_params=fixed_params) + + +@pytest.mark.parametrize("policy", [None, PolicyVariant.ACA]) +def test_build_model_spec_holds_exactly_the_domain_arguments( + policy: PolicyVariant | None, +) -> None: + """The spec carries the model's domain and no generic `Model` option.""" + assert set(_spec(policy=policy)) == _DOMAIN_KEYS @pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) @@ -73,48 +86,50 @@ def test_factory_preserves_axis_width_validation(kind): _factory(kind)(execution_config=config) -@pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) -@pytest.mark.parametrize( - ("requested_policy", "expected_budget"), - [ - (None, 800), - ( - ExecutionConfig( - devices=(0,), - device_memory_bytes=400, - sharded_states=("pref_type",), - axis_widths={"cell": 32}, - ), - 400, - ), - (ExecutionConfig(devices=(0,)), ExecutionConfig().device_memory_bytes), - ], -) -def test_factory_supplies_the_requested_or_measured_budget( - monkeypatch, kind, requested_policy, expected_budget -): - """Defaults use measured limits; explicit budgets and unbudgeted controls survive.""" - factory = _factory(kind) - device = SimpleNamespace( - id=0, platform="gpu", memory_stats=lambda: {"bytes_limit": 800} - ) - monkeypatch.setattr(jax, "devices", lambda: [device]) +class _ConstructionObservedError(Exception): + def __init__(self, kwargs: dict) -> None: + super().__init__() + self.kwargs = kwargs - class ConstructionObservedError(Exception): - pass +def _observe_model_kwargs(monkeypatch, factory, **options) -> dict: def observe_pylcm_constructor(**kwargs): - policy = kwargs["execution_config"] - assert policy.device_memory_bytes == expected_budget - assert policy.devices == (0,) - if requested_policy is not None: - assert policy == requested_policy - raise ConstructionObservedError + raise _ConstructionObservedError(kwargs) monkeypatch.setattr(baseline_model_module, "Model", observe_pylcm_constructor) - monkeypatch.setattr(aca_model_module, "Model", observe_pylcm_constructor) - with pytest.raises(ConstructionObservedError): - factory(execution_config=requested_policy) + with pytest.raises(_ConstructionObservedError) as observed: + factory(**options) + return observed.value.kwargs + + +@pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) +def test_factory_without_execution_config_leaves_pylcm_default(monkeypatch, kind): + """No execution policy reaches `Model`, so pylcm's device default applies.""" + kwargs = _observe_model_kwargs(monkeypatch, _factory(kind)) + assert "execution_config" not in kwargs + + +@pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) +def test_factory_forwards_an_explicit_execution_config_unchanged(monkeypatch, kind): + """An explicit policy reaches `Model` as the same object.""" + config = ExecutionConfig(devices=(0,), device_memory_bytes=400) + kwargs = _observe_model_kwargs(monkeypatch, _factory(kind), execution_config=config) + assert kwargs["execution_config"] is config + + +@pytest.mark.parametrize("kind", ["baseline", "benchmark"]) +def test_factory_forwards_any_model_option(monkeypatch, kind): + """A generic `Model` option the spec does not hold is passed through.""" + kwargs = _observe_model_kwargs(monkeypatch, _factory(kind), durable_identity=False) + assert kwargs["durable_identity"] is False + + +@pytest.mark.parametrize("kind", ["baseline", "benchmark"]) +def test_factory_initial_nodes_override_the_entry_default(monkeypatch, kind): + """`initial_nodes` passed as an option replaces the spec's entry starts.""" + nodes = InitialNodes(by_age={52: ("retiree_nomc_inelig_canwork",)}) + kwargs = _observe_model_kwargs(monkeypatch, _factory(kind), initial_nodes=nodes) + assert kwargs["initial_nodes"] is nodes @pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) diff --git a/tests/test_initial_conditions_extreme_assets.py b/tests/test_initial_conditions_extreme_assets.py index 6455bee..028928e 100644 --- a/tests/test_initial_conditions_extreme_assets.py +++ b/tests/test_initial_conditions_extreme_assets.py @@ -9,12 +9,10 @@ import jax.numpy as jnp from _lcm.simulation.initial_conditions import validate_initial_conditions -from lcm import DiscreteGrid +from lcm import Model from aca_model.agent.assets_and_income import borrowing_constraint -from aca_model.agent.preferences import BenchmarkPrefType from aca_model.benchmark import ( - create_benchmark_model, get_benchmark_initial_conditions, get_benchmark_params, ) @@ -92,7 +90,9 @@ def test_borrowing_constraint_admits_floor_at_million_dollar_negative_cash() -> assert admitted -def test_extreme_negative_assets_subject_passes_validation() -> None: +def test_extreme_negative_assets_subject_passes_validation( + benchmark_model: Model, +) -> None: """A subject placed at `assets = -1_000_000` clears initial-conditions validation. A large-but-reasonable negative value (very bad draws for both HCC shocks) @@ -100,9 +100,7 @@ def test_extreme_negative_assets_subject_passes_validation() -> None: transfer system absorbs them, with `c = c_floor` always feasible. """ n_subjects = 1 - model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - ) + model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( diff --git a/tests/test_medical_cost_timing.py b/tests/test_medical_cost_timing.py index 2ebbc8d..dcebb5b 100644 --- a/tests/test_medical_cost_timing.py +++ b/tests/test_medical_cost_timing.py @@ -14,7 +14,7 @@ import numpy as np import pandas as pd import pytest -from lcm import DiscreteGrid +from lcm import DiscreteGrid, Model from aca_model.agent.preferences import BenchmarkPrefType from aca_model.benchmark import ( @@ -24,19 +24,38 @@ ) from aca_model.config import BENCHMARK_GRID_CONFIG -_SHOCKS = ("hcc_persistent", "hcc_transitory") +_SHOCKS = ("hcc_persistent",) +# Period 0's choices look one year ahead, so ages 51-53 (two living periods and +# the age at which everybody is dead) carry the whole timing question. +_FINAL_AGE = 53 +# The twins differ in the lagged persistent shock at its grid ends, so only its +# grid keeps the benchmark resolution. +# Every other grid is at the smallest size the model accepts, except that +# consumption keeps an interior point above the two floors and below the cap, +# so the consumption comparison still allows a choice that cash would move: +# - assets: borrowing limit, zero and the top holding; +# - AIME: two points per PIA segment; +# - wage residual: two points. +_GRID_CONFIG = replace( + BENCHMARK_GRID_CONFIG, + subtract_hcc_bill=False, + n_assets_gridpoints=3, + aime_points_per_segment=(2, 2, 2, 2), + n_consumption_dollars_gridpoints=4, + n_wage_res_gridpoints=2, +) @pytest.fixture(scope="module") def period_0_by_shock() -> dict[tuple[str, str], pd.Series]: """Period-0 rows of twins that differ in one lagged shock, at its grid ends.""" - grid_config = replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False - ) + grid_config = _GRID_CONFIG model = create_benchmark_model( - pref_type_grid=DiscreteGrid(BenchmarkPrefType), grid_config=grid_config + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + grid_config=grid_config, + final_age=_FINAL_AGE, ) - _, _, params = get_benchmark_params(model=model) + _, _, params = get_benchmark_params(model=model, final_age=_FINAL_AGE) base = get_benchmark_initial_conditions( model=model, n_subjects=1, seed=0, grid_config=grid_config ) @@ -59,22 +78,14 @@ def period_0_by_shock() -> dict[tuple[str, str], pd.Series]: } -def test_value_does_not_depend_on_lagged_transitory_shock( - period_0_by_shock: dict[tuple[str, str], pd.Series], -) -> None: - """Twins differing only in last year's transitory shock have equal value.""" - low = period_0_by_shock["hcc_transitory", "low"]["value"] - high = period_0_by_shock["hcc_transitory", "high"]["value"] - assert low == high - - -def test_consumption_does_not_depend_on_lagged_transitory_shock( - period_0_by_shock: dict[tuple[str, str], pd.Series], +def test_no_regime_carries_a_lagged_transitory_shock( + benchmark_model: Model, ) -> None: - """Twins differing only in last year's transitory shock consume the same.""" - low = period_0_by_shock["hcc_transitory", "low"]["consumption_dollars"] - high = period_0_by_shock["hcc_transitory", "high"]["consumption_dollars"] - assert low == high + """Last year's transitory shock is read by nothing, so it is no state.""" + assert not any( + "hcc_transitory" in benchmark_model.state_names(regime_name=name) + for name in benchmark_model.user_regimes + ) def test_value_falls_with_lagged_persistent_shock( diff --git a/tests/test_model_creation.py b/tests/test_model_creation.py index 9940ffd..608db83 100644 --- a/tests/test_model_creation.py +++ b/tests/test_model_creation.py @@ -1,23 +1,23 @@ """Tests for baseline model creation and regime structure.""" import inspect -from collections.abc import Mapping +from collections.abc import Callable, Mapping import pytest -from helpers.model import ( - make_aca_model, - make_baseline_model, -) -from lcm import DiscreteGrid, Phased +from lcm import DiscreteGrid, Model, Phased from aca_model.aca import health_insurance as aca_hi from aca_model.aca.health_insurance import PolicyVariant from aca_model.aca.regimes import build_all_regimes as _build_aca_regimes +from aca_model.agent import assets_and_income from aca_model.agent.preferences import BenchmarkPrefType +from aca_model.baseline import health_insurance as baseline_hi from aca_model.baseline.regimes import REGIME_SPECS, RegimeId from aca_model.baseline.regimes import build_regime as _build_regime from aca_model.baseline.regimes._common import ( + SolverName, build_grids, + build_model_functions, build_model_state_transitions, build_model_states, ) @@ -32,7 +32,7 @@ def build_aca_regimes(policy: PolicyVariant) -> dict: return _build_aca_regimes( policy=policy, grid_config=BENCHMARK_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) @@ -40,7 +40,7 @@ def build_aca_regimes(policy: PolicyVariant) -> dict: _GRIDS = build_grids( grid_config=BENCHMARK_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) @@ -50,25 +50,25 @@ def build_regime(name: str): return _build_regime(name, _GRIDS) -def test_model_creates_successfully() -> None: - model = make_baseline_model() +def test_model_creates_successfully(baseline_model: Model) -> None: + model = baseline_model assert len(model.user_regimes) == 19 assert model.n_periods == 46 -def test_model_age_range() -> None: - model = make_baseline_model() +def test_model_age_range(baseline_model: Model) -> None: + model = baseline_model assert model.ages.values[0] == 51.0 assert model.ages.values[-1] == 96.0 -def test_dead_regime_is_terminal() -> None: - model = make_baseline_model() +def test_dead_regime_is_terminal(baseline_model: Model) -> None: + model = baseline_model assert model.graph.laws["dead"].terminal -def test_non_terminal_regimes_not_terminal() -> None: - model = make_baseline_model() +def test_non_terminal_regimes_not_terminal(baseline_model: Model) -> None: + model = baseline_model for name in REGIME_SPECS: assert not model.graph.laws[name].terminal @@ -222,7 +222,9 @@ def test_regime_specs_keys_match_regime_id() -> None: assert hasattr(RegimeId, name), f"RegimeId missing field for {name}" -def test_all_non_terminal_regimes_carry_pension_wealth_as_carried_state() -> None: +def test_all_non_terminal_regimes_carry_pension_wealth_as_carried_state( + baseline_model: Model, +) -> None: """`pension_wealth` is a carried state broadcast into every living regime. Imputed from AIME during solve (never a solve grid axis) yet seeded and @@ -237,7 +239,7 @@ def test_all_non_terminal_regimes_carry_pension_wealth_as_carried_state() -> Non build_model_state_transitions()["pension_wealth"] is pensions.wealth_next_before_adjustment ) - model = make_baseline_model() + model = baseline_model for name in REGIME_SPECS: assert isinstance(model.user_regimes[name].states["pension_wealth"], Phased), ( name @@ -284,12 +286,44 @@ def test_hcc_persistent_and_transitory_are_shock_grids() -> None: assert "hcc_transitory" not in regime.state_transitions -def test_aca_model_creates_successfully() -> None: - model = make_aca_model(policy=PolicyVariant.ACA) +def test_aca_model_creates_successfully( + aca_model_for: Callable[[PolicyVariant], Model], +) -> None: + model = aca_model_for(PolicyVariant.ACA) assert len(model.user_regimes) == 19 assert model.n_periods == 46 +@pytest.mark.parametrize("name", REGIME_SPECS) +def test_baseline_regime_omits_expansion_magi(name: str) -> None: + """Baseline eligibility does not register the ACA expansion income node.""" + assert "aca_magi" not in build_regime(name).functions + + +@pytest.mark.parametrize("policy", list(PolicyVariant)) +def test_aca_regime_registers_magi_only_for_expansion(policy: PolicyVariant) -> None: + """The expansion eligibility consumer owns its MAGI income node.""" + has_expansion = policy in ( + PolicyVariant.ACA, + PolicyVariant.ACA_NO_MANDATE, + PolicyVariant.ACA_ONLY_MEDICAID_EXPANSION, + ) + expected = baseline_hi.aca_magi if has_expansion else None + regimes = build_aca_regimes(policy) + assert { + name: regimes[name].functions.get("aca_magi") for name in REGIME_SPECS + } == dict.fromkeys(REGIME_SPECS, expected) + + +@pytest.mark.parametrize("solver", ["brute_force", "dcegm", "nbegm"]) +def test_model_registers_transfers_only_for_brute_asset_laws( + solver: SolverName, +) -> None: + """Savings-form asset laws already include transfers through resources.""" + expected = assets_and_income.transfers if solver == "brute_force" else None + assert build_model_functions(solver=solver).get("transfers") is expected + + def test_aca_nongroup_inelig_has_real_functions() -> None: """Nongroup+nomc regimes get real ACA functions under ACA policy.""" regimes = build_aca_regimes(PolicyVariant.ACA) @@ -328,9 +362,11 @@ def test_aca_other_regimes_have_no_aca_policy_keys() -> None: @pytest.mark.parametrize("policy", list(PolicyVariant)) -def test_all_policy_variants_create(policy: PolicyVariant) -> None: +def test_all_policy_variants_create( + policy: PolicyVariant, aca_model_for: Callable[[PolicyVariant], Model] +) -> None: """All policy variants create valid models.""" - model = make_aca_model(policy=policy) + model = aca_model_for(policy) assert len(model.user_regimes) == 19 @@ -368,35 +404,35 @@ def test_aca_only_medicaid_expansion() -> None: assert "cost_sharing_scale" not in nongroup.functions -def test_baseline_model_creates() -> None: +def test_baseline_model_creates(baseline_model: Model) -> None: """Baseline model creates successfully without PolicyVariant.""" - model = make_baseline_model() + model = baseline_model assert len(model.user_regimes) == 19 -def test_dead_regime_prunes_unused_broadcast_states() -> None: +def test_dead_regime_prunes_unused_broadcast_states(baseline_model: Model) -> None: """States every living regime shares are declared once at the model level; `dead` keeps what the bequest DAG reads (`assets`, `pref_type`). `pension_wealth` is masked (carried states are illegal in terminal regimes); the other unused broadcast states are pruned by reachability.""" - model = make_baseline_model() + model = baseline_model assert model.pruned_variables["dead"] == frozenset( {"aime", "spousal_income", "hcc_persistent", "hcc_transitory"} ) -def test_dead_regime_keeps_only_the_bequest_states() -> None: +def test_dead_regime_keeps_only_the_bequest_states(baseline_model: Model) -> None: """`dead` carries only assets and preference type for valuing bequests.""" - model = make_baseline_model() + model = baseline_model assert set(model.user_regimes["dead"].states) == { "assets", "pref_type", } -def test_living_regimes_keep_every_broadcast_state() -> None: +def test_living_regimes_keep_every_broadcast_state(baseline_model: Model) -> None: """Every model-level state is read by each living regime's DAG, so pruning removes nothing outside `dead`.""" - model = make_baseline_model() + model = baseline_model for name in REGIME_SPECS: assert model.pruned_variables[name] == frozenset() diff --git a/tests/test_mortality.py b/tests/test_mortality.py index 85bc6f5..1a8dc20 100644 --- a/tests/test_mortality.py +++ b/tests/test_mortality.py @@ -9,9 +9,12 @@ from aca_model.agent.labor_market import LaborSupply from aca_model.baseline.regimes._common import ( + ENTRY_REGIMES, REGIME_SPECS, RegimeId, make_targets, + reachable_regimes, + select_horizon_params, select_target_for_age, transition_ages, ) @@ -28,7 +31,7 @@ _make_transition_forcedout as retiree_forcedout, ) from aca_model.baseline.regimes._tied import _make_transition_canwork as tied_canwork -from aca_model.config import MODEL_AGES, MODEL_CONFIG +from aca_model.config import MODEL_AGES, MODEL_CONFIG, model_ages N_PERIODS = MODEL_CONFIG.end_age - MODEL_CONFIG.start_age # Survival by (period, health): distinct per health state. @@ -39,7 +42,7 @@ def _tied(health: int) -> jnp.ndarray: own, ng = make_targets("tied_nomc_inelig_canwork") - return tied_canwork(own=own, ng=ng)( + return tied_canwork(own=own, ng=ng, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(health), @@ -52,7 +55,7 @@ def _tied(health: int) -> jnp.ndarray: def _retiree(health: int) -> jnp.ndarray: own, ng = make_targets("retiree_nomc_inelig_canwork") - return retiree_canwork(own=own, ng=ng)( + return retiree_canwork(own=own, ng=ng, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(health), @@ -65,7 +68,7 @@ def _retiree(health: int) -> jnp.ndarray: def _retiree_forcedout(health: int) -> jnp.ndarray: own, ng = make_targets("retiree_oamc_forced_forcedout") - return retiree_forcedout(gets_medicare=True, own=own, ng=ng)( + return retiree_forcedout(gets_medicare=True, own=own, ng=ng, ages=MODEL_AGES)( age=jnp.int32(80), period=jnp.int32(29), health=jnp.int32(health), @@ -76,7 +79,7 @@ def _retiree_forcedout(health: int) -> jnp.ndarray: def _nongroup(health: int) -> jnp.ndarray: own, _ng = make_targets("nongroup_nomc_inelig_canwork") - return nongroup_canwork(own=own)( + return nongroup_canwork(own=own, ages=MODEL_AGES)( age=jnp.int32(55), period=jnp.int32(4), health=jnp.int32(health), @@ -88,7 +91,7 @@ def _nongroup(health: int) -> jnp.ndarray: def _nongroup_forcedout(health: int) -> jnp.ndarray: own, _ng = make_targets("nongroup_oamc_forced_forcedout") - return nongroup_forcedout(gets_medicare=True, own=own)( + return nongroup_forcedout(gets_medicare=True, own=own, ages=MODEL_AGES)( age=jnp.int32(80), period=jnp.int32(29), health=jnp.int32(health), @@ -131,6 +134,68 @@ def test_forcedout_regimes_are_active_at_95(regime: str) -> None: assert transition_ages(REGIME_SPECS[regime])[-1] == 95 +def test_everybody_is_dead_at_a_shorter_final_age() -> None: + """A survivor of age 52 in a model ending at 53 moves to `dead`.""" + own, _ng = make_targets("retiree_nomc_inelig_canwork") + target = select_target_for_age(53, True, own, final_age=53) + assert int(target) == int(RegimeId.dead) + + +def test_entry_regime_has_no_transition_at_a_shorter_final_age() -> None: + """With ages 51-53 the entry regimes transition at 51 and 52 only.""" + spec = REGIME_SPECS["retiree_nomc_inelig_canwork"] + assert transition_ages(spec, ages=model_ages(final_age=53)) == (51, 52) + + +def test_only_entry_regimes_are_reachable_at_final_age_53() -> None: + """Ages 51-53 reach only the five pre-claiming, pre-Medicare regimes.""" + assert set(reachable_regimes(ages=model_ages(final_age=53))) == set(ENTRY_REGIMES) + + +@pytest.mark.parametrize( + ("final_age", "expected"), + [ + (53, {"retiree_nomc_inelig_canwork", "medicare_age"}), + ( + 63, + { + "retiree_nomc_inelig_canwork", + "retiree_nomc_choose_canwork", + "medicare_age", + "normal_retirement_age", + }, + ), + ], +) +def test_select_horizon_params_keeps_what_the_horizon_reaches( + final_age: int, expected: set[str] +) -> None: + """Unreachable regimes' entries, and claiming params before 62, are left out.""" + params = { + "retiree_nomc_inelig_canwork": 1, + "retiree_nomc_choose_canwork": 2, + "retiree_oamc_forced_forcedout": 3, + "medicare_age": 4, + "normal_retirement_age": 5, + } + selected = select_horizon_params( + params=params, ages=model_ages(final_age=final_age) + ) + assert set(selected) == expected + + +def test_model_ages_end_at_final_age() -> None: + """A final age of 53 gives the ages 51, 52 and 53.""" + assert model_ages(final_age=53) == (51, 52, 53) + + +@pytest.mark.parametrize("final_age", [51, 97]) +def test_model_ages_rejects_final_age_outside_the_data(final_age: int) -> None: + """The final age must leave a living period and lie within the data.""" + with pytest.raises(ValueError, match=f"got {final_age}"): + model_ages(final_age=final_age) + + def test_model_ages_run_from_51_through_96() -> None: """The age grid spans 51 to 96; 96 is the age at which everybody is dead.""" assert (MODEL_AGES[0], MODEL_AGES[-1], len(MODEL_AGES)) == (51, 96, 46) diff --git a/tests/test_nbegm_labor_live_validation.py b/tests/test_nbegm_labor_live_validation.py index 62b4f9e..cbd07c9 100644 --- a/tests/test_nbegm_labor_live_validation.py +++ b/tests/test_nbegm_labor_live_validation.py @@ -16,11 +16,10 @@ import numpy as np import pytest -from helpers.model import _DERIVED_CATEGORICALS from lcm import DiscreteGrid, ExecutionConfig from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.model import create_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.baseline.regimes import SolverName from aca_model.benchmark import get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG @@ -38,12 +37,14 @@ def _solve_m1(solver: SolverName) -> tuple[dict[int, np.ndarray], int]: ) fixed_params, wage_params, _ = get_benchmark_params(model=None) model = create_model( + spec=build_model_spec( + pia_aime_grid=fixed_params["pia_aime_grid"], + wage_params=wage_params, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver=solver, + ), fixed_params=fixed_params, - wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver=solver, execution_config=ExecutionConfig( axis_widths={"cell": 32} if solver == "nbegm" else {} ), diff --git a/tests/test_nbegm_model_creation.py b/tests/test_nbegm_model_creation.py index 5394c25..a3ea65d 100644 --- a/tests/test_nbegm_model_creation.py +++ b/tests/test_nbegm_model_creation.py @@ -17,19 +17,18 @@ from typing import cast import pytest -from helpers.model import _DERIVED_CATEGORICALS, aca_fixed_params +from helpers.model import aca_fixed_params from lcm import DiscreteGrid, Model, Regime from lcm.consumption_savings_regime import ConsumptionSavingsRegime, LiquidMargin from lcm.exceptions import RegimeInitializationError from lcm.solvers import NBEGM from aca_model.aca import PolicyVariant -from aca_model.aca.model import create_model as create_aca_model from aca_model.aca.regimes import build_all_regimes as build_all_aca_regimes from aca_model.agent import assets_and_income from aca_model.agent.preferences import BenchmarkPrefType from aca_model.baseline import health_insurance -from aca_model.baseline.model import create_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.baseline.regimes import ( REGIME_SPECS, SolverName, @@ -40,14 +39,14 @@ from aca_model.benchmark import get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG, GridConfig +# NB-EGM is not a production solver; its wiring checks build the full model. +pytestmark = pytest.mark.long_running + _FIXED_PARAMS, _WAGE_PARAMS, _ = get_benchmark_params(model=None) -# pylcm folds a shock state only under grid search, and the EGM solvers take the -# savings-form asset law, so the transitory medical-cost shock stays a state and -# the bill stays inside `next_assets`. -_EGM_GRID_CONFIG = dataclasses.replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False -) +# The EGM solvers take the savings-form asset law, so the bill stays inside +# `next_assets`; the transitory medical-cost shock is read only as its draw. +_EGM_GRID_CONFIG = dataclasses.replace(BENCHMARK_GRID_CONFIG, subtract_hcc_bill=False) _M1_REGIME = "nongroup_nomc_inelig_canwork" _BRUTE_REGIME = "retiree_nomc_inelig_canwork" @@ -62,7 +61,7 @@ def _build_regimes(solver: SolverName) -> dict[str, Regime]: return build_all_regimes( grid_config=_EGM_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), solver=solver, @@ -71,12 +70,14 @@ def _build_regimes(solver: SolverName) -> dict[str, Regime]: def _build_model_with(solver: SolverName, grid_config: GridConfig) -> Model: return create_model( + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + wage_params=_WAGE_PARAMS, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver=solver, + ), fixed_params=_FIXED_PARAMS, - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver=solver, ) @@ -87,7 +88,7 @@ def _build_model(solver: SolverName) -> Model: def _grids() -> Grids: return build_grids( grid_config=_EGM_GRID_CONFIG, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) @@ -143,7 +144,7 @@ def test_build_nbegm_solver_forwards_the_jump_read_mode() -> None: grid_config = dataclasses.replace(_EGM_GRID_CONFIG, nbegm_jump_read="bridged") grids = build_grids( grid_config=grid_config, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), ) @@ -303,20 +304,22 @@ def test_nbegm_builds_every_aca_policy_variant(policy: PolicyVariant) -> None: the solver and both discrete choices live — the overlay's function swaps compose with the branch compiler's per-regime wiring.""" grid_config = _BRIDGED_GRID_CONFIG - model = create_aca_model( - policy=policy, + model = create_model( + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + policy=policy, + wage_params=_WAGE_PARAMS, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver="nbegm", + ), fixed_params=aca_fixed_params(fixed_params=_FIXED_PARAMS, policy=policy), - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver="nbegm", ) assert isinstance(model, Model) regimes = build_all_aca_regimes( policy=policy, grid_config=grid_config, - fixed_params=_FIXED_PARAMS, + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], wage_params=_WAGE_PARAMS, pref_type_grid=DiscreteGrid(BenchmarkPrefType), solver="nbegm", @@ -336,14 +339,16 @@ def test_nbegm_aca_variants_leave_no_free_buy_private_params( `*__buy_private` entry the pipeline cannot supply. """ grid_config = _BRIDGED_GRID_CONFIG - model = create_aca_model( - policy=policy, + model = create_model( + spec=build_model_spec( + pia_aime_grid=_FIXED_PARAMS["pia_aime_grid"], + policy=policy, + wage_params=_WAGE_PARAMS, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver="nbegm", + ), fixed_params=aca_fixed_params(fixed_params=_FIXED_PARAMS, policy=policy), - wage_params=_WAGE_PARAMS, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver="nbegm", ) template = model.get_params_template() offenders = [ diff --git a/tests/test_nbegm_solve_validation.py b/tests/test_nbegm_solve_validation.py index bbe2265..d37b624 100644 --- a/tests/test_nbegm_solve_validation.py +++ b/tests/test_nbegm_solve_validation.py @@ -19,11 +19,10 @@ import numpy as np import pytest -from helpers.model import _DERIVED_CATEGORICALS from lcm import DiscreteGrid from aca_model.agent.preferences import BenchmarkPrefType -from aca_model.baseline.model import create_model +from aca_model.baseline.model import build_model_spec, create_model from aca_model.baseline.regimes import SolverName from aca_model.benchmark import get_benchmark_params from aca_model.config import BENCHMARK_GRID_CONFIG @@ -35,12 +34,14 @@ def _solve_m1(solver: SolverName) -> dict[int, np.ndarray]: grid_config = dataclasses.replace(BENCHMARK_GRID_CONFIG, nbegm_jump_read="bridged") fixed_params, wage_params, _ = get_benchmark_params(model=None) model = create_model( + spec=build_model_spec( + pia_aime_grid=fixed_params["pia_aime_grid"], + wage_params=wage_params, + grid_config=grid_config, + pref_type_grid=DiscreteGrid(BenchmarkPrefType), + solver=solver, + ), fixed_params=fixed_params, - wage_params=wage_params, - derived_categoricals=_DERIVED_CATEGORICALS, - grid_config=grid_config, - pref_type_grid=DiscreteGrid(BenchmarkPrefType), - solver=solver, ) _, _, params = get_benchmark_params(model=model) solution = model.solve(params=params, log_level="off") diff --git a/tests/test_private_premium.py b/tests/test_private_premium.py index 40e8891..37d2932 100644 --- a/tests/test_private_premium.py +++ b/tests/test_private_premium.py @@ -1,8 +1,10 @@ """Private non-group premium: zero-profit intercept, pricing rule, and floor rule.""" +import jax import jax.numpy as jnp import numpy as np import pytest +from jax._src import monitoring from aca_model.aca import health_insurance as aca_health_insurance from aca_model.baseline import health_insurance @@ -234,3 +236,68 @@ def test_aca_primary_oop_doubles_couples_deductible_and_oop_max( oop_max=jnp.asarray(6500.0), ) np.testing.assert_allclose(result, expected, atol=1e-6) + + +def _closure_intercept( + *, coeff: float, minimum: jax.Array, cost: jax.Array, married: jax.Array +) -> jax.Array: + """Bisect the zero-profit condition with closures over the call's arrays.""" + slope = coeff * (1.0 + _MARKUP) + floor = minimum[married] + target = (1.0 + _MARKUP) * jnp.mean(cost) + + def excess_revenue(intercept: jax.Array) -> jax.Array: + return jnp.mean(jnp.maximum(floor, intercept + slope * cost)) - target + + def halve(_: jax.Array, bracket: tuple) -> tuple: + low, high = bracket + mid = 0.5 * (low + high) + too_high = excess_revenue(mid) > 0.0 + return jnp.where(too_high, low, mid), jnp.where(too_high, mid, high) + + low0, high0 = jnp.asarray(-50_000.0), jnp.asarray(10_000.0) + low, high = jax.lax.fori_loop(0, 100, halve, (low0, high0)) + bracketed = (excess_revenue(low0) <= 0.0) & (excess_revenue(high0) >= 0.0) + return jnp.where(bracketed, 0.5 * (low + high), jnp.nan) + + +def _intercept(*, coeff: float, cost: jax.Array) -> jax.Array: + return health_insurance.private_premium_intercept( + premium_predicted_hcc=jnp.asarray(coeff), + premium_markup=_MARKUP, + premium_minimum=_MINIMUM, + premium_sample_insurer_cost=cost, + premium_sample_is_married=_SAMPLE_MARRIED, + ) + + +def test_private_premium_intercept_reuses_its_trace_across_values() -> None: + """A second eager call with other values compiles no new program.""" + _intercept(coeff=0.5, cost=_SAMPLE_COST) + other_cost = (_SAMPLE_COST * 1.3).block_until_ready() + events: list[str] = [] + + # keyword-only-exempt: library-callback=jax.monitoring + def listener(event: str, duration_secs: float, **kwargs: str | int) -> None: + del duration_secs, kwargs + if event == "/jax/core/compile/backend_compile_duration": + events.append(event) + + monitoring.register_event_duration_secs_listener(listener) + try: + _intercept(coeff=0.8, cost=other_cost).block_until_ready() + finally: + monitoring.unregister_event_duration_listener(listener) + assert events == [] + + +@pytest.mark.parametrize("coeff", [0.5, 0.8, 1.5]) +def test_private_premium_intercept_equals_the_closure_bisection(coeff: float) -> None: + """The intercept is bitwise the closure-based bisection's.""" + cost = _SAMPLE_COST * 1.3 + np.testing.assert_array_equal( + _intercept(coeff=coeff, cost=cost), + _closure_intercept( + coeff=coeff, minimum=_MINIMUM, cost=cost, married=_SAMPLE_MARRIED + ), + ) diff --git a/tests/test_regime_transitions.py b/tests/test_regime_transitions.py index f7baf11..e2f3c21 100644 --- a/tests/test_regime_transitions.py +++ b/tests/test_regime_transitions.py @@ -22,7 +22,7 @@ _make_transition_forcedout as retiree_forcedout, ) from aca_model.baseline.regimes._tied import _make_transition_canwork as tied_canwork -from aca_model.config import MODEL_CONFIG +from aca_model.config import MODEL_AGES, MODEL_CONFIG N_REGIMES = 19 N_PERIODS = MODEL_CONFIG.end_age - MODEL_CONFIG.start_age @@ -47,7 +47,7 @@ def _target_from_probs(probs: jnp.ndarray) -> int: def test_tied_stop_working_becomes_nongroup() -> None: """Tied agent who stops working loses employer coverage → nongroup.""" own, ng = make_targets("tied_nomc_inelig_canwork") - transition = tied_canwork(own=own, ng=ng) + transition = tied_canwork(own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -66,7 +66,7 @@ def test_tied_stop_working_becomes_nongroup() -> None: def test_tied_keeps_working_stays_tied() -> None: """Tied agent who keeps working retains employer coverage.""" own, ng = make_targets("tied_nomc_inelig_canwork") - transition = tied_canwork(own=own, ng=ng) + transition = tied_canwork(own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -87,7 +87,7 @@ def test_tied_keeps_working_stays_tied() -> None: def test_retiree_medicaid_override_to_nongroup() -> None: """Medicaid-eligible retiree is overridden to nongroup.""" own, ng = make_targets("retiree_nomc_inelig_canwork") - transition = retiree_canwork(own=own, ng=ng) + transition = retiree_canwork(own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -105,7 +105,7 @@ def test_retiree_medicaid_override_to_nongroup() -> None: def test_retiree_not_medicaid_stays_retiree() -> None: """Non-Medicaid retiree stays retiree.""" own, ng = make_targets("retiree_nomc_inelig_canwork") - transition = retiree_canwork(own=own, ng=ng) + transition = retiree_canwork(own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -123,7 +123,7 @@ def test_retiree_not_medicaid_stays_retiree() -> None: def test_retiree_forcedout_medicaid_override() -> None: """Forcedout retiree with Medicaid → nongroup.""" own, ng = make_targets("retiree_oamc_forced_forcedout") - transition = retiree_forcedout(gets_medicare=True, own=own, ng=ng) + transition = retiree_forcedout(gets_medicare=True, own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(80), @@ -162,7 +162,7 @@ def test_retiree_age_bracket_transitions( # Use nomc+inelig as starting point — the transition function resolves # the target based on next_age, not current spec. own, ng = make_targets("retiree_nomc_inelig_canwork") - transition = retiree_canwork(own=own, ng=ng) + transition = retiree_canwork(own=own, ng=ng, ages=MODEL_AGES) period = jnp.int32(age - MODEL_CONFIG.start_age) probs = transition( @@ -184,7 +184,7 @@ def test_retiree_age_bracket_transitions( def test_nongroup_canwork_valid_probs() -> None: """Nongroup canwork produces valid probability vector.""" own, _ng = make_targets("nongroup_nomc_inelig_canwork") - transition = nongroup_canwork(own=own) + transition = nongroup_canwork(own=own, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -201,7 +201,7 @@ def test_nongroup_canwork_valid_probs() -> None: def test_nongroup_forcedout_valid_probs() -> None: """Nongroup forcedout produces valid probability vector.""" own, _ng = make_targets("nongroup_oamc_forced_forcedout") - transition = nongroup_forcedout(gets_medicare=True, own=own) + transition = nongroup_forcedout(gets_medicare=True, own=own, ages=MODEL_AGES) probs = transition( age=jnp.int32(80), @@ -219,7 +219,7 @@ def test_nongroup_forcedout_valid_probs() -> None: def test_tied_medicaid_override_to_nongroup() -> None: """Tied + Medicaid-eligible → nongroup (SSI override).""" own, ng = make_targets("tied_nomc_inelig_canwork") - transition = tied_canwork(own=own, ng=ng) + transition = tied_canwork(own=own, ng=ng, ages=MODEL_AGES) probs = transition( age=jnp.int32(55), @@ -237,7 +237,7 @@ def test_tied_medicaid_override_to_nongroup() -> None: def test_tied_at_medicare_age_with_medicaid() -> None: """Tied at age 64→65 (Medicare onset) + Medicaid → nongroup+oamc.""" own, ng = make_targets("tied_nomc_choose_canwork") - transition = tied_canwork(own=own, ng=ng) + transition = tied_canwork(own=own, ng=ng, ages=MODEL_AGES) period = jnp.int32(64 - MODEL_CONFIG.start_age) probs = transition( @@ -257,7 +257,7 @@ def test_tied_at_medicare_age_with_medicaid() -> None: def test_survival_prob_determines_death_weight() -> None: """Dead regime gets (1 - survival) probability weight.""" own, ng = make_targets("retiree_nomc_inelig_canwork") - transition = retiree_canwork(own=own, ng=ng) + transition = retiree_canwork(own=own, ng=ng, ages=MODEL_AGES) survival = jnp.ones((N_PERIODS, 3)) * 0.85 probs = transition( diff --git a/tests/test_transition_only_medical_shock.py b/tests/test_transition_only_medical_shock.py index a4a148f..e007f98 100644 --- a/tests/test_transition_only_medical_shock.py +++ b/tests/test_transition_only_medical_shock.py @@ -1,80 +1,31 @@ -"""Folding the transitory medical-cost shock takes it out of every state space. +"""The transitory medical-cost shock is in no state space. Nothing a period computes reads last year's transitory shock: this year's draw -enters the out-of-pocket bill inside the end-of-period asset law, and the draw is -IID. With `fold_hcc_transitory`, the shock is therefore drawn on the transition -only. Living regimes keep the lagged persistent shock, which prices the private -premium, and lose the transitory axis; values agree with the unfolded model on -every transitory slice. +enters the out-of-pocket bill inside the end-of-period asset law as +`next_hcc_transitory`, and the draw is IID. pylcm therefore draws it on the +transition only and integrates it in the continuation. Living regimes keep the +lagged persistent shock, which prices the private premium. """ -from dataclasses import replace - -import numpy as np import pytest -from helpers.model import make_baseline_model from lcm import Model -from aca_model.benchmark import get_benchmark_params -from aca_model.config import BENCHMARK_GRID_CONFIG - -_FOLDED = replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=True, subtract_hcc_bill=False -) - @pytest.fixture(scope="module") -def folded_model() -> Model: - return make_baseline_model(grid_config=_FOLDED) +def model(baseline_model: Model) -> Model: + return baseline_model -def test_living_regimes_carry_no_lagged_transitory_shock(folded_model: Model) -> None: +def test_living_regimes_carry_no_lagged_transitory_shock(model: Model) -> None: assert not any( - "hcc_transitory" in folded_model.state_names(regime_name=name) - for name in folded_model.user_regimes + "hcc_transitory" in model.state_names(regime_name=name) + for name in model.user_regimes ) -def test_living_regimes_keep_the_lagged_persistent_shock(folded_model: Model) -> None: +def test_living_regimes_keep_the_lagged_persistent_shock(model: Model) -> None: assert all( - "hcc_persistent" in folded_model.state_names(regime_name=name) - for name in folded_model.user_regimes + "hcc_persistent" in model.state_names(regime_name=name) + for name in model.user_regimes if name != "dead" ) - - -@pytest.mark.long_running -def test_folded_value_equals_every_transitory_slice_of_the_unfolded_value( - folded_model: Model, -) -> None: - """The two models' sums differ only in order, so they agree to rounding.""" - unfolded_model = make_baseline_model( - grid_config=replace( - BENCHMARK_GRID_CONFIG, fold_hcc_transitory=False, subtract_hcc_bill=False - ) - ) - _, _, params = get_benchmark_params(model=unfolded_model) - unfolded_values = unfolded_model.solve(params=params, log_level="off").values - folded_values = folded_model.solve(params=params, log_level="off").values - assert set(folded_values) == set(unfolded_values) - for period, regimes in unfolded_values.items(): - assert set(folded_values[period]) == set(regimes) - for name, values in regimes.items(): - unfolded = np.asarray(values) - folded = np.asarray(folded_values[period][name]) - states = unfolded_model.state_names(regime_name=name) - by_slice = ( - np.moveaxis(unfolded, states.index("hcc_transitory"), 0) - if "hcc_transitory" in states - else unfolded - ) - expected = np.broadcast_to(folded, by_slice.shape) - np.testing.assert_array_equal(np.isfinite(by_slice), np.isfinite(expected)) - np.testing.assert_allclose( - by_slice, - expected, - rtol=1e-6, - atol=0, - equal_nan=False, - err_msg=f"period={period}, regime={name}", - )