diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c0a8585..a243d64 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -42,7 +42,7 @@ jobs: # install; keep it compatible with the model's graph declarations. run: >- pip install "pylcm @ - git+https://github.com/OpenSourceEconomics/pylcm.git@318324f6bce1487178714b047211ce1245d170a8" + git+https://github.com/OpenSourceEconomics/pylcm.git@5660c4f30efa5b753bbd3698a5a78bdb08a8824e" - name: Install aca-model with test deps run: pip install -e . pytest pytest-xdist pdbp - name: Run pytest diff --git a/src/aca_model/baseline/regimes/_common.py b/src/aca_model/baseline/regimes/_common.py index 2553b21..e461400 100644 --- a/src/aca_model/baseline/regimes/_common.py +++ b/src/aca_model/baseline/regimes/_common.py @@ -254,7 +254,7 @@ class Grids: # `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 — +# carried per agent in simulate. The grid is simulate-side metadata only — # it fixes the state's continuous kind and float dtype. Seeds are taken # verbatim from the initial conditions without bound-clamping, and the state # is never an interpolation axis, so neither the bounds nor the point count @@ -478,7 +478,7 @@ def age_stages( ) -# The living regimes a subject may start in: pre-claiming, pre-Medicare. +# The living regimes an agent may start in: pre-claiming, pre-Medicare. ENTRY_REGIMES = ( "retiree_nomc_inelig_canwork", "tied_nomc_inelig_canwork", diff --git a/src/aca_model/benchmark.py b/src/aca_model/benchmark.py index a5bcf30..8bd9376 100644 --- a/src/aca_model/benchmark.py +++ b/src/aca_model/benchmark.py @@ -162,20 +162,20 @@ def get_benchmark_consumption_dollars_points(*, n_points: int) -> tuple[float, . def get_benchmark_initial_conditions( *, model: Model, - n_subjects: int, + n_agents: int, seed: int, grid_config: GridConfig = BENCHMARK_GRID_CONFIG, ) -> dict[str, Array]: """Draw random feasible initial conditions across five age-51 regimes. - Every subject gets a random regime from `ENTRY_REGIMES`; continuous + Every agent gets a random regime from `ENTRY_REGIMES`; continuous states are drawn uniformly over the regime's grid range, discrete states - uniformly over categories. States absent from a subject's regime are + uniformly over categories. States absent from an agent's regime are filled with 0 (pylcm ignores them for that regime). """ rng = np.random.default_rng(seed) regime_ids = tuple(model.regime_names_to_ids[n] for n in ENTRY_REGIMES) - regime = rng.choice(regime_ids, size=n_subjects).astype(np.int32) + regime = rng.choice(regime_ids, size=n_agents).astype(np.int32) # Grid ranges come from any of the five regimes (shared structure). # Use to_jax() so the helper handles both LinSpacedGrid and @@ -202,30 +202,30 @@ def get_benchmark_initial_conditions( # For lagged_labor_supply: 0 for tied rows (regime lacks the state), # random 0/1 for the others. tied_id = model.regime_names_to_ids["tied_nomc_inelig_canwork"] - lls = np.where(regime == tied_id, 0, rng.integers(0, 2, size=n_subjects)).astype( + lls = np.where(regime == tied_id, 0, rng.integers(0, 2, size=n_agents)).astype( np.int32 ) initial = { "regime_id": jnp.asarray(regime), - "age": jnp.full(n_subjects, 51.0), - "assets": jnp.asarray(rng.uniform(assets_lo, assets_hi, n_subjects)), - "aime": jnp.asarray(rng.uniform(aime_lo, aime_hi, n_subjects)), + "age": jnp.full(n_agents, 51.0), + "assets": jnp.asarray(rng.uniform(assets_lo, assets_hi, n_agents)), + "aime": jnp.asarray(rng.uniform(aime_lo, aime_hi, n_agents)), # pension_wealth is a carried state seeded as the agent's true # pension wealth; the synthetic benchmark draws a modest positive stock. - "pension_wealth": jnp.asarray(rng.uniform(0.0, 200_000.0, n_subjects)), - "health": jnp.asarray(rng.integers(0, 3, n_subjects).astype(np.int32)), - "lagged_hcc_persistent": jnp.asarray(rng.choice(hcc_p_pts, n_subjects)), - "lagged_hcc_transitory": jnp.asarray(rng.choice(hcc_t_pts, n_subjects)), - "spousal_income": jnp.asarray(rng.integers(0, 3, n_subjects).astype(np.int32)), + "pension_wealth": jnp.asarray(rng.uniform(0.0, 200_000.0, n_agents)), + "health": jnp.asarray(rng.integers(0, 3, n_agents).astype(np.int32)), + "lagged_hcc_persistent": jnp.asarray(rng.choice(hcc_p_pts, n_agents)), + "lagged_hcc_transitory": jnp.asarray(rng.choice(hcc_t_pts, n_agents)), + "spousal_income": jnp.asarray(rng.integers(0, 3, n_agents).astype(np.int32)), "pref_type": jnp.asarray( - rng.integers(0, _N_BENCHMARK_PREF_TYPES, n_subjects).astype(np.int32) + rng.integers(0, _N_BENCHMARK_PREF_TYPES, n_agents).astype(np.int32) ), - "log_ft_wage_res": jnp.asarray(rng.choice(wage_res_pts, n_subjects)), + "log_ft_wage_res": jnp.asarray(rng.choice(wage_res_pts, n_agents)), "lagged_labor_supply": jnp.asarray(lls), # claimed_ss is required by non-initial regimes (ss="choose"); # everyone starts as not-yet-claimed. - "claimed_ss": jnp.zeros(n_subjects, dtype=jnp.int32), + "claimed_ss": jnp.zeros(n_agents, dtype=jnp.int32), } if "lagged_hcc_transitory" not in model.state_names(regime_name=ENTRY_REGIMES[0]): initial.pop("lagged_hcc_transitory") diff --git a/src/aca_model/consumption_dollars_grid.py b/src/aca_model/consumption_dollars_grid.py index abb2dfb..083a325 100644 --- a/src/aca_model/consumption_dollars_grid.py +++ b/src/aca_model/consumption_dollars_grid.py @@ -176,7 +176,7 @@ def compute_consumption_dollars_points( respectively). Both must land exactly on the action grid so the borrowing constraint's `max(cash_on_hand, floor)` kink boundary is a feasible action; otherwise sub-ULP drift can flip the `<=` - comparison for subjects with very negative cash. The geomspace + comparison for agents with very negative cash. The geomspace tail starts at the married floor and runs to `max_consumption_dollars` so the two pinned points stay strictly increasing. diff --git a/src/aca_model/results.py b/src/aca_model/results.py index 7ee8504..04758de 100644 --- a/src/aca_model/results.py +++ b/src/aca_model/results.py @@ -6,8 +6,8 @@ def add_his_from_regime_name(panel: pd.DataFrame) -> pd.DataFrame: """Return `panel` with a `his` column derived from `regime_name`. - The current health-insurance state is not a per-subject model output — it is - the regime a subject occupies. Regime names follow the + The current health-insurance state is not a per-agent model output — it is + the regime an agent occupies. Regime names follow the `{his}_{mc}_{ss}_{canwork}` convention (see `aca_model.baseline.regimes.REGIME_SPECS`), so `his` is the leading underscore-delimited token of `regime_name`. The terminal `dead` regime has diff --git a/src/aca_model/simulation.py b/src/aca_model/simulation.py index 743394a..e78b547 100644 --- a/src/aca_model/simulation.py +++ b/src/aca_model/simulation.py @@ -1,13 +1,13 @@ """Helpers for driving pylcm's simulate across a non-positional id index. -pylcm assigns each simulated subject a positional `subject_id` (`0..n-1`) and, +pylcm assigns each simulated agent a positional `agent_id` (`0..n-1`) and, when given a DataFrame of initial conditions, scatters each regime group's state values into the result arrays *by the group's index labels*. A seed indexed by anything other than a dense `[0, n)` range — e.g. HRS person ids — therefore indexes out of bounds, and the original id never reaches the output. These helpers wrap that boundary: reset the seed to a dense range just before -simulating, and map the positional `subject_id` back to the caller's ids just +simulating, and map the positional `agent_id` back to the caller's ids just after. """ @@ -24,19 +24,19 @@ def simulate_with_dense_index( initial_conditions: pd.DataFrame, **simulate_kwargs: Any, ) -> tuple[Any, NDArray[Any]]: - """Simulate `model` with a dense subject index, preserving the caller's ids. + """Simulate `model` with a dense agent index, preserving the caller's ids. Args: model: A pylcm `Model`. - initial_conditions: Seed DataFrame indexed by the caller's subject ids + initial_conditions: Seed DataFrame indexed by the caller's agent ids (any index — typically the HRS person id). **simulate_kwargs: Forwarded to `model.simulate` (e.g. `params`, - `period_to_regime_to_V_arr`, `log_level`). + `solution`, `log_level`). Returns: Tuple of the `SimulationResult` and the original id array aligned to - `subject_id` — position `i` holds the id of the subject pylcm labels - `subject_id == i`. Pass it to `restore_subject_ids` to recover the ids + `agent_id` — position `i` holds the id of the agent pylcm labels + `agent_id == i`. Pass it to `restore_agent_ids` to recover the ids on the result panel. """ @@ -84,18 +84,18 @@ def _fail_if_starts_not_admitted(*, refused: set[tuple[float, str]]) -> None: raise ValueError(msg) -def restore_subject_ids( +def restore_agent_ids( panel: pd.DataFrame, original_ids: NDArray[Any], *, id_col: str = "id", ) -> pd.DataFrame: - """Map a result panel's positional `subject_id` back to the caller's ids. + """Map a result panel's positional `agent_id` back to the caller's ids. Args: - panel: Simulation result DataFrame carrying a positional `subject_id` + panel: Simulation result DataFrame carrying a positional `agent_id` column (`0..n-1`). - original_ids: Original ids aligned to `subject_id`, as returned by + original_ids: Original ids aligned to `agent_id`, as returned by `simulate_with_dense_index`. id_col: Name of the column to add with the restored ids. @@ -103,4 +103,4 @@ def restore_subject_ids( A copy of `panel` with the restored id column added. """ - return panel.assign(**{id_col: original_ids[panel["subject_id"].to_numpy()]}) + return panel.assign(**{id_col: original_ids[panel["agent_id"].to_numpy()]}) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 4bd1725..f8d382d 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -60,11 +60,11 @@ def test_benchmark_model_with_final_age_53_has_three_periods() -> None: @pytest.mark.long_running def test_benchmark_model_simulates_end_to_end(benchmark_model: Model) -> None: - n_subjects = 20 + n_agents = 20 model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( - model=model, n_subjects=n_subjects, seed=0 + model=model, n_agents=n_agents, seed=0 ) result = model.simulate( @@ -74,7 +74,7 @@ def test_benchmark_model_simulates_end_to_end(benchmark_model: Model) -> None: ) df = result.to_dataframe(terminal_rows="all") - assert len(df) == n_subjects * model.n_periods + assert len(df) == n_agents * model.n_periods # Period 0 rows reflect initial conditions — no NaN in continuous states. period_0 = df.loc[df["period"] == 0] assert not period_0[["assets", "aime", "value"]].isna().any().any() @@ -93,11 +93,11 @@ def test_benchmark_panel_exposes_hic_premium_and_wage_targets( `to_dataframe(additional_targets=...)`; dead/forced-out rows that lack a target get NaN, alive/worker rows carry a finite value. """ - n_subjects = 20 + n_agents = 20 model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( - model=model, n_subjects=n_subjects, seed=0 + model=model, n_agents=n_agents, seed=0 ) result = model.simulate( @@ -172,11 +172,11 @@ def test_benchmark_simulate_obeys_borrowing_constraint(benchmark_model: Model) - `max(cash_on_hand, floor) = cash_on_hand`) and pick an interior consumption point, not the floor. """ - n_subjects = 4 + n_agents = 4 model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( - model=model, n_subjects=n_subjects, seed=0 + model=model, n_agents=n_agents, seed=0 ) result = model.simulate( @@ -202,9 +202,9 @@ def test_initial_conditions_choose_population_size_after_model_construction( ) -> None: """One model supports reproducible initial conditions with different row counts.""" 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) + small = get_benchmark_initial_conditions(model=model, n_agents=2, seed=17) + repeated = get_benchmark_initial_conditions(model=model, n_agents=2, seed=17) + large = get_benchmark_initial_conditions(model=model, n_agents=5, seed=17) assert small.keys() == repeated.keys() == large.keys() for name, values in small.items(): diff --git a/tests/test_benchmark_folding.py b/tests/test_benchmark_folding.py index 695a03b..41262ec 100644 --- a/tests/test_benchmark_folding.py +++ b/tests/test_benchmark_folding.py @@ -16,7 +16,8 @@ def test_benchmark_folds_the_transitory_medical_bill( } assert living assert all( - "lagged_hcc_transitory" not in model.state_names(regime_name=name) for name in living + "lagged_hcc_transitory" not in model.state_names(regime_name=name) + for name in living ) for regime in living.values(): laws = regime.state_transitions["assets"] @@ -24,5 +25,5 @@ def test_benchmark_folds_the_transitory_medical_bill( assert all( isinstance(law, lcm.AdditiveShockTransition) for law in laws.values() ) - initial = get_benchmark_initial_conditions(model=model, n_subjects=8, seed=42) + initial = get_benchmark_initial_conditions(model=model, n_agents=8, seed=42) assert "lagged_hcc_transitory" not in initial diff --git a/tests/test_consumption_dollars_grid.py b/tests/test_consumption_dollars_grid.py index cfab891..8fbc21c 100644 --- a/tests/test_consumption_dollars_grid.py +++ b/tests/test_consumption_dollars_grid.py @@ -2,8 +2,8 @@ The borrowing constraint in `agent.assets_and_income.borrowing_constraint` compares the lowest consumption_dollars action against -`max(cash_on_hand, consumption_dollars_floor)`. For subjects with cash -below the floor (large-negative-asset subjects, moderate-negative-asset +`max(cash_on_hand, consumption_dollars_floor)`. For agents with cash +below the floor (large-negative-asset agents, moderate-negative-asset retirees, etc.) this RHS collapses to exactly `consumption_dollars_floor`. The constraint is feasible iff the relevant household-floor gridpoint is `<= consumption_dollars_floor`. @@ -19,7 +19,7 @@ point equals `start`, but XLA backends can drift by sub-ULP for some `(start, stop, n)` combinations (observed: CUDA, n=70, drift +2.27e-13). A positive drift above the floor flips the kink-boundary `<=` and -rejects every action for the affected subjects. +rejects every action for the affected agents. `compute_consumption_dollars_points` therefore prepends the singles' floor as `pts[0]`, runs `geomspace` from the married floor up to the diff --git a/tests/test_dag_coverage.py b/tests/test_dag_coverage.py index 5d509db..ceba97a 100644 --- a/tests/test_dag_coverage.py +++ b/tests/test_dag_coverage.py @@ -61,7 +61,7 @@ def test_regimes_carry_no_active_attribute(model): ) def test_simulate_rejects_starts_outside_the_entry_contract(model, age, regime): _, _, params = get_benchmark_params(model=model) - ic = get_benchmark_initial_conditions(model=model, n_subjects=2, seed=0) + ic = get_benchmark_initial_conditions(model=model, n_agents=2, seed=0) ic = { **ic, "age": jnp.full(2, age), @@ -73,7 +73,7 @@ def test_simulate_rejects_starts_outside_the_entry_contract(model, age, regime): def test_boundary_targets_change_with_source_age(model): assert set( - model.graph.solution.targets(period=9, source="retiree_nomc_inelig_canwork") + model.graph.solution.targets(step=9, source="retiree_nomc_inelig_canwork") ) == { "retiree_nomc_inelig_canwork", "retiree_dimc_inelig_canwork", @@ -82,7 +82,7 @@ def test_boundary_targets_change_with_source_age(model): "dead", } assert set( - model.graph.solution.targets(period=10, source="retiree_nomc_inelig_canwork") + model.graph.solution.targets(step=10, source="retiree_nomc_inelig_canwork") ) == { "retiree_nomc_choose_canwork", "retiree_dimc_choose_canwork", @@ -108,7 +108,7 @@ def test_each_regime_law_reaches_exactly_its_declared_targets(model, regime): def test_bequest_continuation_is_not_removed(model): regime = model.user_regimes["retiree_oamc_forced_forcedout"] assert model.graph.solution.targets( - period=44, source="retiree_oamc_forced_forcedout" + step=44, source="retiree_oamc_forced_forcedout" ) == ("dead",) assert "consumption_dollars" in regime.actions assert (95, "retiree_oamc_forced_forcedout") in model.graph.nodes diff --git a/tests/test_dcegm_parity.py b/tests/test_dcegm_parity.py index 3bd86af..a63442e 100644 --- a/tests/test_dcegm_parity.py +++ b/tests/test_dcegm_parity.py @@ -47,12 +47,12 @@ n_hcc_transitory_gridpoints=3, ) -N_SUBJECTS = 200 +N_AGENTS = 200 SEED = 0 # Pre-registered tolerances, recorded from the noise-floor derivation # (brute at PARITY_GRID_CONFIG vs brute at REFERENCE_GRID_CONFIG, seed 0, -# 200 subjects). A DC-EGM deviation within these bounds is indistinguishable +# 200 agents). A DC-EGM deviation within these bounds is indistinguishable # from brute-force resolution noise; bounds are not adjusted after seeing # DC-EGM results. `None` means not yet recorded — the floor tests skip. NOISE_FLOOR_ACTION_AGREEMENT: float | None = None # RECORDED-FROM-DERIVATION @@ -116,10 +116,10 @@ def _make_model(*, solver: SolverName, grid_config: GridConfig) -> Model: def _seeded_panel(model: Model) -> pd.DataFrame: - """Solve + simulate the fixed seeded panel and return it in subject order.""" + """Solve + simulate the fixed seeded panel and return it in agent order.""" _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( - model=model, n_subjects=N_SUBJECTS, seed=SEED + model=model, n_agents=N_AGENTS, seed=SEED ) result = model.simulate( params=params, @@ -127,11 +127,11 @@ def _seeded_panel(model: Model) -> pd.DataFrame: log_level="off", ) df = result.to_dataframe() - return df.sort_values(["subject_id", "period"]).reset_index(drop=True) + return df.sort_values(["agent_id", "period"]).reset_index(drop=True) def panel_distance(panel_a: pd.DataFrame, panel_b: pd.DataFrame) -> dict[str, float]: - """Distance between two seeded panels of the same subjects. + """Distance between two seeded panels of the same agents. Returns: @@ -140,8 +140,8 @@ def panel_distance(panel_a: pd.DataFrame, panel_b: pd.DataFrame) -> dict[str, fl (NaN) in the regimes where it does not apply counts as agreeing when both panels mask it — identical masking is identical behavior, not a disagreement. - - `prefix_share`: share of rows inside each subject's agreeing prefix — - after a subject's first discrete disagreement, the paths legitimately + - `prefix_share`: share of rows inside each agent's agreeing prefix — + after an agent's first discrete disagreement, the paths legitimately diverge, so continuous comparisons stop there. - `value_rdiff` / `consumption_rdiff`: max relative deviation of the recorded value and consumption inside the agreeing prefixes (`0.0` @@ -157,9 +157,9 @@ def panel_distance(panel_a: pd.DataFrame, panel_b: pd.DataFrame) -> dict[str, fl agree_row &= equal | both_masked frame = pd.DataFrame( - {"subject_id": panel_a["subject_id"].to_numpy(), "agree": agree_row} + {"agent_id": panel_a["agent_id"].to_numpy(), "agree": agree_row} ) - prefix = frame.groupby("subject_id")["agree"].cummin().to_numpy() + prefix = frame.groupby("agent_id")["agree"].cummin().to_numpy() def _max_rdiff(series_a: pd.Series, series_b: pd.Series) -> float: left = series_a.to_numpy()[prefix] diff --git a/tests/test_execution_config.py b/tests/test_execution_config.py index 743dfbc..592fa2a 100644 --- a/tests/test_execution_config.py +++ b/tests/test_execution_config.py @@ -133,7 +133,7 @@ def test_factory_initial_nodes_override_the_entry_default(monkeypatch, kind): @pytest.mark.parametrize("kind", ["baseline", "aca", "benchmark"]) -def test_factory_rejects_construction_subject_count(kind): +def test_factory_rejects_construction_agent_count(kind): """Population size is supplied by initial conditions, not model construction.""" - with pytest.raises(TypeError, match="n_subjects"): - _factory(kind)(n_subjects=1) + with pytest.raises(TypeError, match="n_agents"): + _factory(kind)(n_agents=1) diff --git a/tests/test_initial_conditions_extreme_assets.py b/tests/test_initial_conditions_extreme_assets.py index 028928e..ac925a8 100644 --- a/tests/test_initial_conditions_extreme_assets.py +++ b/tests/test_initial_conditions_extreme_assets.py @@ -1,4 +1,4 @@ -"""Subjects at extreme negative assets must clear `validate_initial_conditions`. +"""Agents at extreme negative assets must clear `validate_initial_conditions`. The transfer system (`agent.assets_and_income.transfers`) tops cash-on-hand to the household-$ consumption floor at any starting state, so the lowest @@ -90,21 +90,21 @@ def test_borrowing_constraint_admits_floor_at_million_dollar_negative_cash() -> assert admitted -def test_extreme_negative_assets_subject_passes_validation( +def test_extreme_negative_assets_agent_passes_validation( benchmark_model: Model, ) -> None: - """A subject placed at `assets = -1_000_000` clears initial-conditions validation. + """An agent placed at `assets = -1_000_000` clears initial-conditions validation. A large-but-reasonable negative value (very bad draws for both HCC shocks) should remain in the simulated population: the consumption floor / transfer system absorbs them, with `c = c_floor` always feasible. """ - n_subjects = 1 + n_agents = 1 model = benchmark_model _, _, params = get_benchmark_params(model=model) initial_conditions = get_benchmark_initial_conditions( - model=model, n_subjects=n_subjects, seed=0 + model=model, n_agents=n_agents, seed=0 ) initial_conditions = { **initial_conditions, diff --git a/tests/test_medical_cost_timing.py b/tests/test_medical_cost_timing.py index 78960ed..a78f6cc 100644 --- a/tests/test_medical_cost_timing.py +++ b/tests/test_medical_cost_timing.py @@ -57,7 +57,7 @@ def period_0_by_shock() -> dict[tuple[str, str], pd.Series]: ) _, _, 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 + model=model, n_agents=1, seed=0, grid_config=grid_config ) grids = model.user_regimes["retiree_nomc_inelig_canwork"].states initial_conditions = {name: jnp.tile(values, 4) for name, values in base.items()} @@ -70,7 +70,7 @@ def period_0_by_shock() -> dict[tuple[str, str], pd.Series]: params=params, initial_conditions=initial_conditions, log_level="off" ) df = result.to_dataframe(terminal_rows="all") - period_0 = df.loc[df["period"] == 0].sort_values("subject_id") + period_0 = df.loc[df["period"] == 0].sort_values("agent_id") return { (shock, end): period_0.iloc[2 * row + i] for row, shock in enumerate(_SHOCKS) diff --git a/tests/test_nbegm_model_creation.py b/tests/test_nbegm_model_creation.py index a3ea65d..09b334c 100644 --- a/tests/test_nbegm_model_creation.py +++ b/tests/test_nbegm_model_creation.py @@ -238,7 +238,7 @@ def test_nbegm_m1_regime_keeps_the_borrowing_constraint() -> None: The EGM solve enforces the borrowing limit through the savings grid's lower bound, but forward simulation re-decides consumption by an argmax over the consumption grid — without the explicit `consumption <= resources` - feasibility mask, floor-region subjects (negative cash-on-hand rescued by + feasibility mask, floor-region agents (negative cash-on-hand rescued by the consumption floor) would pick the consumption grid's top value. """ model = _build_model("nbegm") diff --git a/tests/test_simulation.py b/tests/test_simulation.py index 5abf531..c7cd8c8 100644 --- a/tests/test_simulation.py +++ b/tests/test_simulation.py @@ -7,7 +7,7 @@ import pytest from lcm import InitialNodes -from aca_model.simulation import restore_subject_ids, simulate_with_dense_index +from aca_model.simulation import restore_agent_ids, simulate_with_dense_index class _StubModel: @@ -29,7 +29,7 @@ def test_simulate_with_dense_index_hands_pylcm_a_dense_range() -> None: """The simulator receives a dense 0..n-1 index regardless of the caller's ids. pylcm indexes the initial conditions by their index labels and assigns - `subject_id` positionally, so a sparse id index would index out of bounds. + `agent_id` positionally, so a sparse id index would index out of bounds. """ ic = pd.DataFrame( {"regime_name": ["a", "b", "c"], "age": [51, 51, 51]}, @@ -40,8 +40,8 @@ def test_simulate_with_dense_index_hands_pylcm_a_dense_range() -> None: assert model.seen_index == [0, 1, 2] -def test_simulate_with_dense_index_returns_ids_aligned_to_subject() -> None: - """Returned ids align to subject_id: position i is the id of subject i.""" +def test_simulate_with_dense_index_returns_ids_aligned_to_agent() -> None: + """Returned ids align to agent_id: position i is the id of agent i.""" ic = pd.DataFrame( {"regime_name": ["a", "b"], "age": [51, 51]}, index=pd.Index([3010, 959_738_010], name="id"), @@ -52,11 +52,11 @@ def test_simulate_with_dense_index_returns_ids_aligned_to_subject() -> None: np.testing.assert_array_equal(ids, [3010, 959_738_010]) -def test_restore_subject_ids_maps_positional_subject_back_to_original() -> None: - """`restore_subject_ids` recovers the caller's id from the positional subject_id.""" +def test_restore_agent_ids_maps_positional_agent_back_to_original() -> None: + """`restore_agent_ids` recovers the caller's id from the positional agent_id.""" original_ids = np.array([3010, 959_738_010]) - panel = pd.DataFrame({"subject_id": [0, 1, 0, 1], "period": [0, 0, 1, 1]}) - out = restore_subject_ids(panel, original_ids) + panel = pd.DataFrame({"agent_id": [0, 1, 0, 1], "period": [0, 0, 1, 1]}) + out = restore_agent_ids(panel, original_ids) np.testing.assert_array_equal( out["id"].to_numpy(), [3010, 959_738_010, 3010, 959_738_010] )