"""F5-conf-04: VFI vs closed form, optimal growth with log utility. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Reads only data/model.csv; deterministic (no randomness).""" 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, beta = float(p["alpha"]), float(p["beta"]) y_min, y_max, N = float(p["y_min"]), float(p["y_max"]), int(float(p["grid_points"])) tol = float(p["vfi_tolerance"]) assert str(p["grid_spacing"]).strip() == "log" evals = [float(p["eval_y_1"]), float(p["eval_y_2"]), float(p["eval_y_3"])] data_issues = [] # ---------- Closed form (guess-and-verify: V = A0 + B ln y) ---------- ab = alpha * beta B = 1.0 / (1.0 - ab) A0 = (np.log(1.0 - ab) + ab / (1.0 - ab) * np.log(ab)) / (1.0 - beta) c_closed = lambda y: (1.0 - ab) * np.asarray(y) V_closed = lambda y: A0 + B * np.log(np.asarray(y)) savings_rate = ab # (y - c)/y # ---------- VFI on the prescribed grid (discrete choice of next-period output on the grid) ---------- grid = np.exp(np.linspace(np.log(y_min), np.log(y_max), N)) k_needed = grid ** (1.0 / alpha) # capital required to reach each y' on the grid C = grid[:, None] - k_needed[None, :] # consumption for (y today, y' tomorrow) feas = C > 0 U = np.full(C.shape, -np.inf) U[feas] = np.log(C[feas]) V = np.zeros(N) n_iter, sup_change = 0, np.inf while sup_change >= tol: RHS = U + beta * V[None, :] V_new = RHS.max(axis=1) sup_change = float(np.max(np.abs(V_new - V))) V = V_new n_iter += 1 if n_iter > 100000: raise RuntimeError("VFI did not converge") pol_idx = (U + beta * V[None, :]).argmax(axis=1) c_pol = grid - k_needed[pol_idx] # Diagnostics: is the grid bound binding? (policy at the edge of the y' grid) edge_hits = int(np.sum((pol_idx == 0) | (pol_idx == N - 1))) yprime_closed = (ab * grid) ** alpha if yprime_closed.min() < y_min or yprime_closed.max() > y_max: data_issues.append({"issue": "closed-form next-period output leaves the prescribed grid", "handling": "reported; truncation may bias VFI near bounds"}) # Interpolation at evaluation points: c linear in y; V linear in ln y c_num = [float(np.interp(y, grid, c_pol)) for y in evals] cc = [float(c_closed(y)) for y in evals] on_node = [bool(np.any(np.isclose(grid, y, rtol=0, atol=1e-12))) for y in evals] V_num_1 = float(np.interp(np.log(1.0), np.log(grid), V)) # Theoretical bound on the remaining VFI error from the stopping rule vfi_err_bound = beta / (1 - beta) * sup_change results = { "task_id": "F5-conf-04", "c_closed_y05": cc[0], "c_closed_y1": cc[1], "c_closed_y2": cc[2], "c_num_y05": c_num[0], "c_num_y1": c_num[1], "c_num_y2": c_num[2], "max_abs_error_policy": float(max(abs(a - b) for a, b in zip(c_num, cc))), "value_closed_y1": float(V_closed(1.0)), "value_num_y1": V_num_1, "savings_rate_closed_form": float(savings_rate), "contraction_modulus": float(beta), "grid_points_used": int(N), "n_iterations": int(n_iter), "final_sup_change": float(sup_change), "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 "baseline_closed_form_B_coefficient": float(B), "diag_eval_points_on_grid_node": on_node, "diag_policy_edge_hits": edge_hits, "diag_closed_yprime_min": float(yprime_closed.min()), "diag_closed_yprime_max": float(yprime_closed.max()), "diag_grid_log_step": float(np.log(grid[1] / grid[0])), "diag_vfi_tolerance_error_bound": float(vfi_err_bound), "diag_value_abs_error_y1": float(abs(V_num_1 - float(V_closed(1.0)))), "diag_value_sup_error_grid": float(np.max(np.abs(V - V_closed(grid)))), "diag_policy_sup_error_grid": float(np.max(np.abs(c_pol - c_closed(grid)))), "diag_policy_max_rel_error_eval": float(max(abs(a - b) / b for a, b in zip(c_num, cc))), } os.makedirs(os.path.join(ROOT, "out"), exist_ok=True) with open(os.path.join(ROOT, "out", "results.json"), "w") as f: json.dump(results, f, indent=2) for k, v in results.items(): print(f"{k}: {v}")