"""F5-conf-04: VFI vs closed form for optimal growth with log utility. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py""" import json, os import numpy as np import pandas as pd df = pd.read_csv("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"])) tol = float(p["vfi_tolerance"]) evals = [float(p["eval_y_1"]), float(p["eval_y_2"]), float(p["eval_y_3"])] assert str(p["grid_spacing"]).strip().lower() == "log" # ---- closed form (guess V = A + B ln y, verified in report) ---- 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) * np.asarray(y) V_closed = lambda y: A + B * np.log(y) # ---- VFI on log-spaced grid, choice = next-period output y' on the same grid ---- y = np.exp(np.linspace(np.log(y_min), np.log(y_max), n)) k_needed = y ** (1.0 / alpha) # capital needed to reach y' : k = y'^(1/alpha) C = y[:, None] - k_needed[None, :] # consumption for (y, y') feasible = C > 0 U = np.full_like(C, -np.inf) U[feasible] = np.log(C[feasible]) V = np.zeros(n) it = 0; sup = np.inf while sup >= tol: V_new = np.max(U + beta * V[None, :], axis=1) sup = float(np.max(np.abs(V_new - V))) V = V_new; it += 1 if it > 100000: raise RuntimeError("VFI did not converge") idx = np.argmax(U + beta * V[None, :], axis=1) c_grid = y - k_needed[idx] at_upper = int(np.sum(idx == n - 1)); at_lower = int(np.sum(idx == 0)) # interpolate (linear in ln y) to evaluation points ly = np.log(y) c_num = [float(np.interp(np.log(e), ly, c_grid)) for e in evals] c_cf = [float(c_closed(e)) for e in evals] V_num_1 = float(np.interp(0.0, ly, V)) on_grid = [bool(np.any(np.isclose(y, e, rtol=1e-12))) for e in evals] # diagnostics over the whole grid max_err_grid = float(np.max(np.abs(c_grid - c_closed(y)))) max_V_err_grid = float(np.max(np.abs(V - V_closed(y)))) issues = [] if not all(on_grid): issues.append({"issue": "Evaluation points " + ", ".join(str(e) for e, g in zip(evals, on_grid) if not g) + " are not grid nodes of the prescribed log grid.", "handling": "VFI policy and value linearly interpolated in ln y between adjacent grid nodes, as TASK.md allows."}) issues.append({"issue": "TASK does not prescribe the choice set for VFI.", "handling": "Discrete choice of next-period output y' on the same 400-point grid (c = y - y'^(1/alpha)); no off-grid optimisation. Initial guess V0 = 0."}) 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": float(max(abs(a - b) for a, b in zip(c_num, c_cf))), "value_closed_y1": float(V_closed(1.0)), "value_num_y1": V_num_1, "savings_rate_closed_form": float(ab), "contraction_modulus": beta, "grid_points_used": n, "n_iterations": it, "final_sup_change": sup, "feasibility": "complete", "feasibility_reason": None, "data_issues": issues, "n_input_rows": {"model.csv": int(len(df))}, "n_analysed": n, "random_seed": None, "diagnostics": { "max_abs_policy_error_on_grid": max_err_grid, "max_abs_value_error_on_grid": max_V_err_grid, "value_error_y1": V_num_1 - float(V_closed(1.0)), "error_bound_from_stopping_rule": beta * sup / (1 - beta), "grid_log_step": float(ly[1] - ly[0]), "n_grid_points_choosing_upper_bound": at_upper, "n_grid_points_choosing_lower_bound": at_lower, "closed_form_A": float(A), "closed_form_B": float(B), }, } os.makedirs("out", exist_ok=True) with open("out/results.json", "w") as f: json.dump(res, f, indent=2) print(json.dumps(res, indent=2))