|
| 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