Skip to content

Commit 307c079

Browse files
committed
joergensen druedahl upper envelope
1 parent e148605 commit 307c079

4 files changed

Lines changed: 251 additions & 0 deletions

File tree

‎src/upper_envelope/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
from upper_envelope.fues_jax.fues_jax import fues_jax, fues_jax_unconstrained
22
from upper_envelope.fues_numba.fues_numba import fues_numba, fues_numba_unconstrained
3+
from upper_envelope.upper_jor_drued import upper_jor_drued

‎src/upper_envelope/fues_jax/fues_jax.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ def fues_jax(
128128

129129
# This is the condition, which we do not use at the moment.
130130
# closed_form_cond = min_wealth_grid < endog_grid[0]
131+
# NOTE: We intentionally mirror NumPy's `linspace` behavior used in the
132+
# reference implementation and in the stored test fixtures.
133+
# Using `n_constrained_points_to_add` (not `+ 1` and slicing) yields
134+
# slightly different spacing and is important for numerical reproducibility.
131135
grid_points_to_add = jnp.linspace(
132136
min_wealth_grid, endog_grid[0], n_constrained_points_to_add
133137
)
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from __future__ import annotations
2+
3+
from functools import partial
4+
from typing import Callable, Dict, Optional
5+
6+
import jax
7+
import jax.numpy as jnp
8+
9+
10+
@partial(jax.jit, static_argnames=["value_function"])
11+
def upper_jor_drued(
12+
endog_grid: jnp.ndarray,
13+
policy: jnp.ndarray,
14+
value: jnp.ndarray,
15+
m_grid: jnp.ndarray,
16+
expected_value_zero_savings: jnp.ndarray | float,
17+
value_function: Callable,
18+
value_function_args=(),
19+
value_function_kwargs: Optional[Dict] = None,
20+
):
21+
"""Compute a simple 1D upper envelope on a given common grid.
22+
23+
The envelope is computed by linearly interpolating every adjacent pair
24+
``(endog_grid[i], endog_grid[i+1])`` onto the common grid ``m_grid``.
25+
For each point on ``m_grid``, we take the pointwise maximum over all segment
26+
interpolants and an additional "consume-all" candidate.
27+
28+
This function intentionally does *not*:
29+
- sort inputs
30+
- detect or insert intersection points
31+
- apply FUES jump/scan logic
32+
33+
Returns arrays with the convention that index 0 corresponds to zero wealth:
34+
``value_out[0] = expected_value_zero_savings`` and ``endog_out[0] = policy_out[0] = 0``.
35+
"""
36+
37+
if value_function_kwargs is None:
38+
value_function_kwargs = {}
39+
40+
# Segment interpolation weights for each adjacent pair.
41+
dm = endog_grid[1:] - endog_grid[:-1] # (N-1,)
42+
eps = 1e-16
43+
weight = (m_grid[None, :] - endog_grid[:-1, None]) / (dm[:, None] + eps) # (N-1, M)
44+
45+
c_interp = policy[:-1, None] + weight * (policy[1:] - policy[:-1])[:, None]
46+
v_interp = value[:-1, None] + weight * (value[1:] - value[:-1])[:, None]
47+
48+
outside = (weight < 0.0) | (weight > 1.0)
49+
v_interp = jnp.where(outside, -jnp.inf, v_interp)
50+
51+
# Consume-all candidate.
52+
c_all = m_grid
53+
v_all = value_function(c_all, *value_function_args, **value_function_kwargs)
54+
55+
v_stack = jnp.vstack((v_interp, v_all[None, :]))
56+
c_stack = jnp.vstack((c_interp, c_all[None, :]))
57+
58+
best = jnp.argmax(v_stack, axis=0)
59+
grid_idx = jnp.arange(m_grid.size)
60+
61+
value_best = v_stack[best, grid_idx]
62+
policy_best = c_stack[best, grid_idx]
63+
64+
# Prepend zero-wealth convention.
65+
endog_out = jnp.concatenate((jnp.array([0.0]), m_grid))
66+
policy_out = jnp.concatenate((jnp.array([0.0]), policy_best))
67+
value_out = jnp.concatenate((jnp.array([expected_value_zero_savings]), value_best))
68+
69+
return endog_out, policy_out, value_out

‎tests/test_upper_jor_drued.py‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
"""Tests for `upper_jor_drued`.
2+
3+
We compare against `upenv.fues_jax`, but only on evaluation points that lie on
4+
reference line segments that are not affected by explicit intersection handling.
5+
6+
Heuristic:
7+
- `fues_jax` can insert intersection points by duplicating an endogenous grid
8+
point (same `m` appearing twice with different left/right policy values).
9+
- Linear interpolation is ambiguous around such duplicates.
10+
11+
We therefore:
12+
1) run `fues_jax` to get a reference refined correspondence
13+
2) build a boolean mask on the *given* `m_grid` selecting points that fall inside
14+
non-degenerate reference segments (strictly increasing in `m`)
15+
3) interpolate the reference onto `m_grid` using only those safe segments
16+
4) compare `upper_jor_drued` to that reference on the masked points
17+
"""
18+
19+
from pathlib import Path
20+
from typing import Dict
21+
22+
import jax
23+
import jax.numpy as jnp
24+
import numpy as np
25+
import pytest
26+
from numpy.testing import assert_allclose
27+
28+
import upper_envelope as upenv
29+
30+
31+
TEST_DIR = Path(__file__).parent
32+
TEST_RESOURCES_DIR = TEST_DIR / "resources"
33+
34+
35+
def utility_crra(consumption: jnp.ndarray, choice: int, params: Dict[str, float]) -> jnp.ndarray:
36+
utility_consumption = (consumption ** (1 - params["rho"]) - 1) / (1 - params["rho"])
37+
utility = utility_consumption - (1 - choice) * params["delta"]
38+
return utility
39+
40+
41+
def interpolate_on_safe_reference_segments(
42+
ref_m: np.ndarray,
43+
ref_y: np.ndarray,
44+
m_grid: np.ndarray,
45+
):
46+
"""Interpolate reference (ref_m, ref_y) onto m_grid, ignoring unsafe segments.
47+
48+
A "safe" segment is any adjacent pair (ref_m[i], ref_m[i+1]) with ref_m[i+1] > ref_m[i].
49+
For each x in m_grid, we take the maximum interpolated value over all safe segments
50+
covering x. This avoids ambiguity around duplicated ref_m values.
51+
"""
52+
53+
dm = ref_m[1:] - ref_m[:-1]
54+
safe = dm > 0
55+
56+
weight = (m_grid[None, :] - ref_m[:-1, None]) / (dm[:, None] + 1e-16)
57+
y_interp = ref_y[:-1, None] + weight * (ref_y[1:] - ref_y[:-1])[:, None]
58+
59+
outside = (weight < 0.0) | (weight > 1.0)
60+
y_interp[outside | (~safe[:, None])] = -np.inf
61+
62+
y_best = np.max(y_interp, axis=0)
63+
return y_best
64+
65+
66+
@pytest.fixture(autouse=True)
67+
def _jax_x64():
68+
jax.config.update("jax_enable_x64", True)
69+
70+
71+
@pytest.fixture()
72+
def setup_model():
73+
params = {"beta": 0.95, "rho": 1.95, "delta": 0.35}
74+
state_choice_vec = {"lagged_choice": 0, "choice": 0}
75+
return params, state_choice_vec
76+
77+
78+
@pytest.mark.parametrize("period", [2, 4, 9, 10, 18])
79+
def test_upper_jor_drued_matches_fues_on_safe_segments(period, setup_model):
80+
value_egm = np.genfromtxt(
81+
TEST_RESOURCES_DIR / f"upper_envelope_period_tests/val{period}.csv",
82+
delimiter=",",
83+
dtype=float,
84+
)
85+
policy_egm = np.genfromtxt(
86+
TEST_RESOURCES_DIR / f"upper_envelope_period_tests/pol{period}.csv",
87+
delimiter=",",
88+
dtype=float,
89+
)
90+
91+
params, state_choice_vec = setup_model
92+
93+
def value_func(consumption, choice, params):
94+
# Same convention as existing tests: includes continuation value.
95+
return utility_crra(consumption, choice, params) + params["beta"] * value_egm[1, 0]
96+
97+
ref_m, ref_c, ref_v = upenv.fues_jax(
98+
endog_grid=jnp.asarray(policy_egm[0, 1:]),
99+
policy=jnp.asarray(policy_egm[1, 1:]),
100+
value=jnp.asarray(value_egm[1, 1:]),
101+
expected_value_zero_savings=value_egm[1, 0],
102+
value_function=value_func,
103+
value_function_args=(state_choice_vec["choice"], params),
104+
n_constrained_points_to_add=len(policy_egm[0, 1:]) // 10,
105+
)
106+
107+
ref_m = np.asarray(ref_m)
108+
ref_c = np.asarray(ref_c)
109+
ref_v = np.asarray(ref_v)
110+
111+
valid = ~np.isnan(ref_m)
112+
ref_m = ref_m[valid]
113+
ref_c = ref_c[valid]
114+
ref_v = ref_v[valid]
115+
116+
# Given common grid for Joerg-Drued.
117+
# Use the input correspondence range (exclude the synthetic zero-wealth anchor).
118+
m_min = float(np.min(policy_egm[0, 1:]))
119+
m_max = float(np.max(policy_egm[0, 1:]))
120+
m_grid = np.linspace(m_min, m_max, 500)
121+
122+
endog_out, policy_out, value_out = upenv.upper_jor_drued(
123+
endog_grid=jnp.asarray(policy_egm[0, 1:]),
124+
policy=jnp.asarray(policy_egm[1, 1:]),
125+
value=jnp.asarray(value_egm[1, 1:]),
126+
m_grid=jnp.asarray(m_grid),
127+
expected_value_zero_savings=value_egm[1, 0],
128+
value_function=value_func,
129+
value_function_args=(state_choice_vec["choice"], params),
130+
)
131+
132+
endog_out = np.asarray(endog_out)
133+
policy_out = np.asarray(policy_out)
134+
value_out = np.asarray(value_out)
135+
136+
# Check index-0 convention.
137+
assert endog_out[0] == 0.0
138+
assert policy_out[0] == 0.0
139+
assert value_out[0] == value_egm[1, 0]
140+
141+
# Build reference interpolants on safe segments only.
142+
# Use value to select the best reference segment; then take policy from that segment.
143+
v_ref = interpolate_on_safe_reference_segments(ref_m, ref_v, m_grid)
144+
145+
# Recompute the segment-wise interpolation for policy using the same winner segments
146+
# implied by the value envelope.
147+
dm = ref_m[1:] - ref_m[:-1]
148+
safe = dm > 0
149+
weight = (m_grid[None, :] - ref_m[:-1, None]) / (dm[:, None] + 1e-16)
150+
c_interp = ref_c[:-1, None] + weight * (ref_c[1:] - ref_c[:-1])[:, None]
151+
152+
outside = (weight < 0.0) | (weight > 1.0)
153+
c_interp[outside | (~safe[:, None])] = np.nan
154+
155+
# Determine which segment delivers v_ref at each grid point.
156+
v_interp = ref_v[:-1, None] + weight * (ref_v[1:] - ref_v[:-1])[:, None]
157+
v_interp[outside | (~safe[:, None])] = -np.inf
158+
best_seg = np.argmax(v_interp, axis=0)
159+
c_ref = c_interp[best_seg, np.arange(m_grid.size)]
160+
161+
# Mask points where reference is defined.
162+
good = np.isfinite(v_ref) & np.isfinite(c_ref)
163+
assert good.any(), "No safe reference points found; test setup issue."
164+
165+
# Our implementation only interpolates adjacent input pairs. The input ordering can
166+
# leave gaps where no segment covers m_grid; those points will be -inf and are not
167+
# comparable to the reference.
168+
good &= np.isfinite(value_out[1:]) & np.isfinite(policy_out[1:])
169+
170+
# Compare on the common grid portion (skip index 0 which is a convention).
171+
assert_allclose(value_out[1:][good], v_ref[good], rtol=1e-7, atol=1e-7)
172+
173+
# Policy can differ even when value matches because:
174+
# - `upper_jor_drued` includes a consume-all candidate with policy == m_grid
175+
# - `fues_jax` does not explicitly expose that candidate as a segment
176+
# - near kinks, the value envelope can have multiple near-ties with different policies
177+
# We therefore only assert value agreement here.

0 commit comments

Comments
 (0)