"""F5-conf-04: VFI vs closed-form policy, optimal growth with log utility. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Deterministic; no randomness used (random_seed = null).""" import json, os import numpy as np import pandas as pd ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) df = pd.read_csv(os.path.join(ROOT, "data", "model.csv")) p = dict(zip(df["parameter"], df["value"])) alpha = float(p["alpha"]); beta = float(p["beta"]) y_min = float(p["y_min"]); y_max = float(p["y_max"]); N = int(float(p["grid_points"])) spacing = str(p["grid_spacing"]).strip(); tol = float(p["vfi_tolerance"]) eval_y = [float(p["eval_y_1"]), float(p["eval_y_2"]), float(p["eval_y_3"])] assert spacing == "log" and 0 < alpha < 1 and 0 < beta < 1 and 0 < y_min < y_max and N > 1 data_issues = [] # ---- Closed form (guess-and-verify V = A + B ln y): B = 1/(1-ab), c = (1-ab) y ab = alpha * beta B = 1.0 / (1.0 - ab) A = (np.log(1.0 - ab) + ab / (1.0 - ab) * np.log(ab)) / (1.0 - beta) c_closed = lambda y: (1.0 - ab) * y V_closed = lambda y: A + B * np.log(y) savings_rate = ab # baseline quantity # ---- VFI on prescribed grid: state y_i, choice y'_j on the same grid, # consumption c_ij = y_i - (y'_j)^(1/alpha) (capital needed to produce y'_j); infeasible if c<=0. grid = np.exp(np.linspace(np.log(y_min), np.log(y_max), N)) k_needed = grid ** (1.0 / alpha) C = grid[:, None] - k_needed[None, :] U = np.where(C > 0, np.log(np.where(C > 0, C, 1.0)), -np.inf) V = np.zeros(N) n_it, sup = 0, np.inf while sup >= tol: Vn = np.max(U + beta * V[None, :], axis=1) sup = float(np.max(np.abs(Vn - V))) V = Vn; n_it += 1 if n_it > 100000: raise RuntimeError("VFI did not converge") jstar = np.argmax(U + beta * V[None, :], axis=1) c_pol = grid - k_needed[jstar] # check policy is interior w.r.t. grid bounds (no corner at the top/bottom of the choice grid) n_low = int(np.sum(jstar == 0)); n_high = int(np.sum(jstar == N - 1)) if n_low or n_high: data_issues.append({"issue": f"VFI choice hits grid bound at {n_low} (low) / {n_high} (high) states", "handling": "reported; policy near those states is truncated by the grid"}) lg = np.log(grid) interp = lambda f, y: float(np.interp(np.log(y), lg, f)) # linear in ln y between nodes for y in eval_y: if not np.any(np.isclose(grid, y, rtol=0, atol=1e-12)): pass # off-node: linear interpolation in ln y (allowed by the task) c_num = [interp(c_pol, y) for y in eval_y] c_cf = [float(c_closed(y)) for y in eval_y] max_err = float(max(abs(a - b) for a, b in zip(c_num, c_cf))) res = { "task_id": "F5-conf-04", "c_closed_y05": c_cf[0], "c_closed_y1": c_cf[1], "c_closed_y2": c_cf[2], "c_num_y05": c_num[0], "c_num_y1": c_num[1], "c_num_y2": c_num[2], "max_abs_error_policy": max_err, "value_closed_y1": float(V_closed(1.0)), "value_num_y1": interp(V, 1.0), "savings_rate_closed_form": float(savings_rate), "contraction_modulus": float(beta), "grid_points_used": int(N), "n_iterations": int(n_it), "final_sup_change": float(sup), "feasibility": "complete", "feasibility_reason": None, "data_issues": data_issues, "n_input_rows": {"model.csv": int(len(df))}, "n_analysed": int(N), "random_seed": None, # supplementary diagnostics (not required keys) "diag_eval_points_on_grid": [bool(np.any(np.isclose(grid, y, rtol=0, atol=1e-12))) for y in eval_y], "diag_grid_log_step": float(lg[1] - lg[0]), "diag_policy_max_abs_error_on_grid": float(np.max(np.abs(c_pol - c_closed(grid)))), "diag_value_max_abs_error_on_grid": float(np.max(np.abs(V - V_closed(grid)))), "diag_value_tolerance_bound": float(beta * tol / (1 - beta)), "diag_value_abs_error_y1": abs(interp(V, 1.0) - float(V_closed(1.0))), "diag_closed_form_A": float(A), "diag_closed_form_B": float(B), "diag_choice_at_lower_bound": n_low, "diag_choice_at_upper_bound": n_high, } os.makedirs(os.path.join(ROOT, "out"), exist_ok=True) with open(os.path.join(ROOT, "out", "results.json"), "w") as f: json.dump(res, f, indent=2) print(json.dumps(res, indent=2))