"""F5-conf-04: VFI vs closed form for the Brock-Mirman optimal growth model (log utility). Run from workspace root: ~/wp29/venv/bin/python out/analysis.py """ import json, os import numpy as np import pandas as pd HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) 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"]) evals = [float(p["eval_y_1"]), float(p["eval_y_2"]), float(p["eval_y_3"])] data_issues = [{"issue": "Evaluation points y=0.5, 1.0, 2.0 (and y=1 for V) are not nodes of the prescribed 400-point log grid.", "handling": "VFI policy and value are linearly interpolated in ln y between adjacent grid nodes (as allowed by TASK.md); grid itself unchanged."}, {"issue": "VFI implemented as discrete choice of next-period output y' restricted to the same grid (consumption c = y - y'^(1/alpha)); infeasible choices (c<=0) excluded.", "handling": "Design choice, not a deviation from prescribed parameters; it introduces a discretisation error in the policy reported as max_abs_error_policy."}] assert spacing == "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 - ab) + (ab / (1 - ab)) * np.log(ab)) / (1 - beta) c_closed = lambda y: (1 - ab) * np.asarray(y) V_closed = lambda y: a + b * np.log(np.asarray(y)) # ---- VFI: discrete choice of next-period output y' on the same grid ---- grid = np.exp(np.linspace(np.log(y_min), np.log(y_max), N)) k_needed = grid ** (1.0 / alpha) # savings needed to reach y' C = grid[:, None] - k_needed[None, :] # consumption for (y, y') feasible = C > 0 U = np.where(feasible, np.log(np.where(feasible, C, 1.0)), -np.inf) V = np.zeros(N) n_iter = 0 while True: RHS = U + beta * V[None, :] V_new = RHS.max(axis=1) n_iter += 1 diff = np.max(np.abs(V_new - V)) V = V_new if diff < tol: break if n_iter > 100000: raise RuntimeError("VFI did not converge") pol_idx = (U + beta * V[None, :]).argmax(axis=1) c_grid = grid - k_needed[pol_idx] # check that the optimal choice is not at a grid boundary (truncation) n_at_lower = int(np.sum(pol_idx == 0)); n_at_upper = int(np.sum(pol_idx == N - 1)) lg = np.log(grid) interp = lambda f, y: float(np.interp(np.log(y), lg, f)) # linear in ln y on_node = [bool(np.any(np.isclose(grid, y, rtol=1e-12, atol=0))) for y in evals] c_num = [interp(c_grid, y) for y in evals] c_cf = [float(c_closed(y)) for y in evals] max_err = float(max(abs(x - z) for x, z in zip(c_num, c_cf))) v_num_1 = interp(V, 1.0) v_cf_1 = float(V_closed(1.0)) # diagnostics (not required keys) diag = { "eval_points_are_grid_nodes": on_node, "policy_at_lower_bound_count": n_at_lower, "policy_at_upper_bound_count": n_at_upper, "max_abs_policy_error_over_grid": float(np.max(np.abs(c_grid - c_closed(grid)))), "max_abs_value_error_over_grid": float(np.max(np.abs(V - V_closed(grid)))), "grid_log_step": float(lg[1] - lg[0]), "closed_form_a": float(a), "closed_form_b": float(b), } 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": v_cf_1, "value_num_y1": v_num_1, "savings_rate_closed_form": float(ab), "contraction_modulus": float(beta), "grid_points_used": int(N), "n_iterations": int(n_iter), "final_sup_change": float(diff), "feasibility": "complete", "feasibility_reason": None, "data_issues": data_issues, "n_input_rows": {"model.csv": int(len(df))}, "n_analysed": int(N), "random_seed": None, "diagnostics": diag, } with open(os.path.join(HERE, "results.json"), "w") as f: json.dump(res, f, indent=2) print(json.dumps(res, indent=2))