Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
140 commits
Select commit Hold shift + click to select a range
5e5d529
Let the NBEGM regime declare every choice its structure affords
hmgaudecker Aug 14, 2026
3b2a0b1
Consume pylcm's multi-action discrete envelope
hmgaudecker Aug 15, 2026
9a5fe8a
Solve every living regime with NB-EGM
hmgaudecker Aug 15, 2026
ace111b
Let pylcm's NBEGM probes check the ACA budget
hmgaudecker Aug 16, 2026
4f25818
Declare the liquid Euler margin on the EGM regimes
hmgaudecker Aug 19, 2026
221bf4f
Describe the borrowing constraint's actual solver coverage
hmgaudecker Aug 19, 2026
8466aac
Name the DC-EGM blocker that actually fires
hmgaudecker Aug 19, 2026
a2ad958
FIX Declare the ACA borrowing limit structurally
hmgaudecker Aug 20, 2026
328e371
Migrate ACA benchmark to breakpoint grids
hmgaudecker Aug 21, 2026
f61cff9
ENH Forward NB-EGM workspace controls
hmgaudecker Aug 30, 2026
5d1d479
ENH Allow explicit fp32 ACA runs
hmgaudecker Sep 1, 2026
94977a3
FIX Gate the experimental NB-EGM planner
hmgaudecker Sep 2, 2026
3af83d0
MAINT Migrate the tests to pylcm's SolutionResult solve API
hmgaudecker Sep 3, 2026
b941507
ENH Move ACA execution controls to Model policy
hmgaudecker Sep 8, 2026
735a250
API Remove constructor population hints from model factories
hmgaudecker Sep 12, 2026
4ec7ce0
TST Pin float32 felicity at the leisure floor against a 60-digit refe…
hmgaudecker Sep 25, 2026
4f37ec2
ENH Bend leisure onto a positive floor with a smooth max
hmgaudecker Sep 25, 2026
05c4a43
CI Install pylcm at the commit aca-dev pins
hmgaudecker Sep 25, 2026
3bc89f7
Floor leisure at a small positive value so float32 utility stays fini…
hmgaudecker Sep 26, 2026
fd30823
Declare regime transitions by age with `regime_transitions`
hmgaudecker Sep 28, 2026
bf4c654
Test against pylcm without Regime.active
hmgaudecker Sep 28, 2026
8f6ea5d
Declare the 51-61 entry regimes as the model's starting pairs
hmgaudecker Sep 28, 2026
ad38653
Narrow the admissible starting ages to 51-60
hmgaudecker Sep 28, 2026
57eda22
Test the per-type transformed bequest weight in the dead regime
hmgaudecker Oct 1, 2026
a13aeca
TST Expect the ACA Medicaid expansion to reach the disabled under 65
hmgaudecker Oct 1, 2026
b69fe0c
Extend the ACA Medicaid expansion to the disabled under 65
hmgaudecker Oct 1, 2026
28e4d72
TST Expect employer coverage to survive expansion-only Medicaid eligi…
hmgaudecker Oct 1, 2026
b0b5ed1
Keep employer coverage for households eligible only through the ACA e…
hmgaudecker Oct 1, 2026
3bbcc5a
TST Pin budget, Social Security and pension rules at production values
hmgaudecker Oct 1, 2026
7fd408c
Test health-dependent mortality, terminal age 95 and the sinh asset grid
hmgaudecker Oct 1, 2026
1de2466
Derive the per-type bequest weight from the bequest MPC in the dead r…
hmgaudecker Oct 1, 2026
e7925ad
TST Expect Medicaid to replace non-group cover and pay Medicare premia
hmgaudecker Oct 1, 2026
b9358a6
TEST Pin private premium pricing, couples' cost sharing, DI Medicare …
hmgaudecker Oct 1, 2026
5a5806f
Let Medicaid replace non-group cover and pay Medicare premia
hmgaudecker Oct 1, 2026
b3e852f
FIX Read spousal income by age and own health
hmgaudecker Oct 1, 2026
e9436fc
FIX Credit back only benefits the earnings test withholds
hmgaudecker Oct 1, 2026
1975cea
FIX Cap AIME at the taxable maximum after labor accrual
hmgaudecker Oct 1, 2026
1c06b65
FIX Stop pension accrual at the pension claiming age 71
hmgaudecker Oct 1, 2026
83f2015
Name the non-group premium after Medicaid `medicaid_adjusted_premium`
hmgaudecker Oct 1, 2026
5b56aac
FIX Index and accrue a disabled agent's AIME before the DI continuity…
hmgaudecker Oct 1, 2026
a4eccf2
FIX Freeze AIME once claiming is forced
hmgaudecker Oct 1, 2026
3ae5518
TST Expect a community-rated ACA non-group premium
hmgaudecker Oct 1, 2026
14b312e
FIX Require consumption at or above the household's own floor
hmgaudecker Oct 1, 2026
c84e56b
FIX Add the ACA surtaxes on unearned income and earnings
hmgaudecker Oct 1, 2026
e76ee7a
Community-rate the ACA private non-group premium
hmgaudecker Oct 1, 2026
fb842c5
DOC Describe the ACA plan premium and Medicaid in the non-group regimes
hmgaudecker Oct 1, 2026
117b7bf
FIX Price private cover per the draft; double couples' cost sharing; …
hmgaudecker Oct 1, 2026
0c73bf1
FIX Carry the pension-corrected PIA across a claim-age adjustment in …
hmgaudecker Oct 1, 2026
d9e4fe1
CI Install pylcm at the main commit that aca-dev pins
hmgaudecker Oct 1, 2026
0d4c0af
Merge remote-tracking branch 'origin/fix/smooth-max-leisure-floor' in…
hmgaudecker Oct 1, 2026
6dd9f4f
Merge remote-tracking branch 'origin/fix/smooth-max-leisure-floor' in…
hmgaudecker Oct 1, 2026
93bf0a1
Merge remote-tracking branch 'origin/fix/smooth-max-leisure-floor' in…
hmgaudecker Oct 1, 2026
6252bc6
FIX Drop the withheld fraction from the forced regimes' benchmark params
hmgaudecker Oct 1, 2026
dee781b
Merge remote-tracking branch 'origin/fix/smooth-max-leisure-floor' in…
hmgaudecker Oct 1, 2026
562b8e1
Make mortality depend on health, keep people alive through 95, use a …
hmgaudecker Oct 1, 2026
2c28d15
Merge origin/fix/smooth-max-leisure-floor into fix/draft-processes
hmgaudecker Oct 1, 2026
7b0ac93
TST Build ACA test models without the risk-rated premium parameters
hmgaudecker Oct 1, 2026
3c1c2d8
Merge remote-tracking branch 'origin/fix/draft-budget' into fix/draft…
hmgaudecker Oct 1, 2026
cbcf28d
TST Expect the ACA overlay to charge the ACA surtaxes
hmgaudecker Oct 1, 2026
1bd0a20
Merge origin/fix/draft-prefs into fix/draft-model
hmgaudecker Oct 1, 2026
69923ee
Charge the ACA surtaxes under every ACA variant
hmgaudecker Oct 1, 2026
38c8aee
Merge origin/fix/draft-budget into fix/draft-model
hmgaudecker Oct 1, 2026
c05e03e
MAINT Regenerate the benchmark snapshot from the merged branches
hmgaudecker Oct 1, 2026
78a46ce
FIX Read the disability probability from a dedicated (age, health) pa…
hmgaudecker Oct 1, 2026
2b410bd
TST Share the ACA fixed-params helper with the NBEGM ACA tests
hmgaudecker Oct 1, 2026
eb9a2f7
Merge origin/fix/draft-processes into fix/draft-model
hmgaudecker Oct 1, 2026
77c5c43
TEST Pension wealth stays undivided where nobody survives
hmgaudecker Oct 1, 2026
3155f63
FIX Leave pension wealth undivided where nobody survives
hmgaudecker Oct 1, 2026
50bc566
MAINT Regenerate the benchmark snapshot after the processes merge
hmgaudecker Oct 1, 2026
41bc2f6
Merge remote-tracking branch 'origin/fix/draft-processes' into fix/dr…
hmgaudecker Oct 1, 2026
cf3fe2c
TST Pass categorical Medicaid eligibility to the transitions in the m…
hmgaudecker Oct 1, 2026
8f72005
Merge origin/fix/draft-aca into fix/draft-model
hmgaudecker Oct 1, 2026
e821fa8
MAINT Regenerate the benchmark snapshot after all merges
hmgaudecker Oct 1, 2026
e265120
Merge remote-tracking branch 'origin/fix/draft-aca' into fix/draft-pr…
hmgaudecker Oct 1, 2026
6d26b22
TEST Pin couples' doubled deductible and OOP maximum under the ACA plan
hmgaudecker Oct 1, 2026
b87ac7c
FIX Double couples' deductible and OOP maximum under the ACA plan
hmgaudecker Oct 1, 2026
922b545
MAINT Carry the private-premium and disability inputs in the benchmar…
hmgaudecker Oct 1, 2026
7312f19
Merge origin/fix/draft-premiums into fix/draft-model
hmgaudecker Oct 1, 2026
ecca1c4
MAINT Regenerate the benchmark snapshot after the premiums merge
hmgaudecker Oct 1, 2026
5bda643
TEST Build the ACA execution-config model from ACA-fit params
hmgaudecker Oct 1, 2026
82ac671
MAINT Regenerate the benchmark snapshot with the 950-row premium sample
hmgaudecker Oct 1, 2026
86fa18b
Merge the age-scheduled regime transitions into the draft model
hmgaudecker Oct 2, 2026
db17dcf
TST Read the scheduled disability-Medicare targets through the resolv…
hmgaudecker Oct 2, 2026
aa12061
Type the age stages and starting regimes for the checker
hmgaudecker Oct 2, 2026
aa70e92
MAINT Regenerate the benchmark snapshot with the age-64 disability row
hmgaudecker Oct 2, 2026
c88da0b
FIX Realise medical costs after the period's choices
hmgaudecker Oct 2, 2026
f3f0fb5
TEST Follow the medical-cost shock states into dead and the EGM refusals
hmgaudecker Oct 2, 2026
ce84697
Merge fix/draft-timing into fix/draft-model
hmgaudecker Oct 2, 2026
d8973c4
Port ACA models to explicit graphs and retain medical shock draws
hmgaudecker Oct 2, 2026
a2a16ee
Pin standalone CI to the pylcm draw-state test follow-up
hmgaudecker Oct 2, 2026
196a56a
Pin standalone CI to latest pylcm draw-state branch
hmgaudecker Oct 2, 2026
938c733
Declare regime transitions on Model.edges
hmgaudecker Oct 6, 2026
0a5ea10
TEST Expect the benchmark law arguments under params["edges"]
hmgaudecker Oct 7, 2026
721d774
ENH Route the benchmark law arguments to params["edges"]
hmgaudecker Oct 7, 2026
280e1e7
MAINT Pin CI pylcm to the edges-params API
hmgaudecker Oct 7, 2026
b9915a2
MAINT Read the benchmark law arguments from the snapshot's edges layout
hmgaudecker Oct 7, 2026
2400c0a
MAINT Pin CI pylcm to the fixed edges-params head
hmgaudecker Oct 7, 2026
591da5c
REF Schedule each regime's transition cells by source age
hmgaudecker Oct 8, 2026
5761c52
MAINT Pin CI pylcm to the strict transition-targets head
hmgaudecker Oct 8, 2026
621c150
FIX Drop the risk-rated premium intercept where the ACA plan is commu…
hmgaudecker Oct 8, 2026
e2b17fb
FIX Declare the admissible starts as InitialNodes and read their pair…
hmgaudecker Oct 9, 2026
98ebb47
Test ACA against the precise pylcm API
hmgaudecker Oct 10, 2026
a5e6950
ENH Add a grid flag that folds the transitory medical-cost shock
hmgaudecker Oct 9, 2026
649bed9
ENH Declare the asset law as resources minus the medical bill
hmgaudecker Oct 9, 2026
622ba00
ENH Declare the asset law as lcm.AdditiveShockTransition
hmgaudecker Oct 10, 2026
5b75bee
Enable medical-shock folding in the ACA benchmark
hmgaudecker Oct 11, 2026
ee48d9b
Preserve unfolded controls in legacy model test fixtures
hmgaudecker Oct 11, 2026
b962ebd
Check folded values across every solved model cell
hmgaudecker Oct 11, 2026
89d26dd
State exact ACA cost-sharing parity with a numeric assertion
hmgaudecker Oct 11, 2026
54397e8
Use the unfolded control for lagged medical-shock twins
hmgaudecker Oct 11, 2026
5e69b66
Keep the transition-only fold witness separate from additive folding
hmgaudecker Oct 11, 2026
03a8143
Pass grid points to IrregSpacedGrid as arrays
hmgaudecker Oct 20, 2026
4862f6f
Merge aca-model main into the array-grids compat branch
hmgaudecker Oct 22, 2026
3c237f9
Let simulations restart mid-life from any living regime
hmgaudecker Oct 22, 2026
bfcbbc3
Register policy and solver helpers only where consumed
hmgaudecker Oct 22, 2026
407c737
Merge remote-tracking branch 'origin/feat/restart-initial-nodes' into…
hmgaudecker Oct 23, 2026
ffb2f37
Test against pylcm #604 and offer uncompensated-care targets
hmgaudecker Oct 23, 2026
d0d2ea6
Test the health-cost covariates instead of total health costs as targets
hmgaudecker Oct 23, 2026
7938e6e
Make the model horizon a constructor argument and shorten slow tests
hmgaudecker Oct 23, 2026
7449c01
Merge remote-tracking branch 'origin/feat/did-2014-pylcm604' into fea…
hmgaudecker Oct 23, 2026
0d258a6
Pass a short-horizon model only the params it reads
hmgaudecker Oct 23, 2026
9d8ace9
Share the standard test models per session
hmgaudecker Oct 23, 2026
5de722d
Shrink the medical-cost timing test to the smallest grids
hmgaudecker Oct 23, 2026
b3fb325
Write short-horizon params by the reachability rule
hmgaudecker Oct 23, 2026
8f3c5f2
Split the model factories into a domain spec and a thin create_model
hmgaudecker Oct 23, 2026
e511da0
Keep each test module on one xdist worker in CI
hmgaudecker Oct 23, 2026
5c0c26a
Merge feat/model-horizon into feat/model-spec
hmgaudecker Oct 23, 2026
10b5532
Integrate the transitory medical shock by read timing
hmgaudecker Oct 30, 2026
2b9f127
Expect no transitory medical-shock state in the DAG coverage test
hmgaudecker Oct 30, 2026
75b9f05
Merge feat/hcc-transitory-read-timing
hmgaudecker Nov 1, 2026
cafb160
Test against pylcm #630
hmgaudecker Nov 1, 2026
2eae3b5
Test against pylcm #630 with the off-grid continuation fix
hmgaudecker Nov 1, 2026
9c3a8a1
Reuse one traced bisection for the private premium intercept
hmgaudecker Nov 2, 2026
664ddad
Carry the premium bisection operands as a plain tuple
hmgaudecker Nov 2, 2026
1067f2a
Merge main into the benchmark lottery-contraction branch
hmgaudecker Nov 19, 2026
c65eb94
Let the benchmark model search grids with lottery contraction
hmgaudecker Nov 19, 2026
3503af8
Keep CI on the jax 0.12.0 series pylcm locks
hmgaudecker Nov 19, 2026
87dee06
Merge the model-horizon and model-spec branches
hmgaudecker Nov 19, 2026
425b8e0
Reuse the shared benchmark model and a short horizon in two tests
hmgaudecker Nov 19, 2026
513b2fc
Test against the pylcm lottery-contraction head and shard the timing …
hmgaudecker Nov 19, 2026
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
15 changes: 11 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 }}
45 changes: 25 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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`,
Expand Down
4 changes: 2 additions & 2 deletions docs/dag-migration.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand Down
110 changes: 0 additions & 110 deletions src/aca_model/aca/model.py

This file was deleted.

6 changes: 3 additions & 3 deletions src/aca_model/aca/regimes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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",
Expand All @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion src/aca_model/aca/regimes/_overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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":
Expand All @@ -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.
Expand Down
59 changes: 41 additions & 18 deletions src/aca_model/baseline/health_insurance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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
Loading