Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/aca_model/baseline/regimes/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
32 changes: 16 additions & 16 deletions src/aca_model/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion src/aca_model/consumption_dollars_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/aca_model/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 12 additions & 12 deletions src/aca_model/simulation.py
Original file line number Diff line number Diff line change
@@ -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.
"""

Expand All @@ -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.

"""
Expand Down Expand Up @@ -84,23 +84,23 @@ 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.

Returns:
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()]})
20 changes: 10 additions & 10 deletions tests/test_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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()
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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():
Expand Down
5 changes: 3 additions & 2 deletions tests/test_benchmark_folding.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ 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"]
assert isinstance(laws, Mapping)
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
6 changes: 3 additions & 3 deletions tests/test_consumption_dollars_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions tests/test_dag_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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",
Expand All @@ -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",
Expand All @@ -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
Expand Down
20 changes: 10 additions & 10 deletions tests/test_dcegm_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -116,22 +116,22 @@ 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,
initial_conditions=initial_conditions,
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:

Expand All @@ -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`
Expand All @@ -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]
Expand Down
6 changes: 3 additions & 3 deletions tests/test_execution_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading