S = BasisSpline(n, a, b, f=ff) L = BasisSpline(n, a, b, k=1, f=ff) # Compute actual and fitted values on grid y = ff(x) # actual yc = C(x) # Chebychev approximant ys = S(x) # cubic spline approximant yl = L(x) # linear spline approximant # Plot function approximations plt.figure() ymin = np.floor(y.min()) ymax = np.ceil(y.max()) xlim = [a, b] ylim = [-0.2, 1.2] if ifunc == 2 else [ymin, ymax] subfig(1, x, y, xlim, ylim, 'Function') subfig(2, x, yc, xlim, ylim, 'Chebyshev') subfig(3, x, ys, xlim, ylim, 'Cubic Spline') subfig(4, x, yl, xlim, ylim, 'Linear Spline') # Plot function approximation error plt.figure() plt.plot(x, np.c_[yc - y, ys - y], linewidth=3) plt.xlabel('x') plt.ylabel('Approximation Error') plt.legend(['Chebychev Polynomial', 'Cubic Spline']) # pltlegend('boxoff') plt.show()
# Simulate Model T = 20 nrep = 50000 sinit = np.full((1, nrep), smin) data = growth.simulate(T, sinit) # Plot Simulated State Path subdata = data[data['_rep'] < 3][['time', 'wealth', '_rep']] subdata.pivot(index='time', columns='_rep', values='wealth').plot(legend=False, lw=1) data.groupby('time')['wealth'].mean().plot(color='k', linestyle='--') plt.title('Simulated and Expected Wealth') plt.xlabel('Period') plt.ylabel('Wealth') # Plot Simulated Policy Path subdata = data[data['_rep'] < 3][['time', 'investment', '_rep']] subdata.pivot(index='time', columns='_rep', values='investment').plot(legend=False, lw=1) plt.plot(data.groupby('time')['investment'].mean(), 'k-') plt.title('Simulated and Expected Investment') plt.xlabel('Period') plt.ylabel('Investment') # Print Steady-State and Ergodic Moments ff = '\t%15s = %5.2f' D = data[data['time'] == T][['wealth', 'investment']]
plt.figure(figsize=[12, 6]) demo.subplot(1, 2, 1, 'Chebychev Collocation Residual\nand Approximation Error', 'Wealth', 'Residual/Error') plt.plot(Wealth, np.c_[S.resid, v - vtrue], Wealth, np.zeros_like(Wealth), 'k--') plt.legend(['Residual','Error'], loc='lower right') # Plot Linear-Quadratic Approximation Error demo.subplot(1, 2, 2, 'Linear-Quadratic Approximation Error', 'Wealth', 'Error') plt.plot(Wealth, vlq - vtrue) # Plot State and Policy Paths opts = dict(spec='r*', offset=(-5, -5), fs=11, ha='right') data[['Wealth', 'Investment']].plot() plt.title('State and Policy Paths') demo.annotate(T, sstar, 'steady-state wealth\n = %.2f' % sstar, **opts) demo.annotate(T, kstar, 'steady-state investment\n = %.2f' % kstar, **opts) plt.xlabel('Period') plt.ylabel('Wealth/Investment') plt.xlim([0, T + 0.5]) # Print Steady-State print('\n\nSteady-State') print(' Wealth = %5.4f' % sstar) print(' Investment = %5.4f' % kstar) plt.show()
## SIMULATION # Simulate Model T = 30 nrep = 100000 sinit = np.full((1, nrep), smin) data = model.simulate(T, sinit, seed=945) # Plot Simulated State Path D = data[data['_rep'] < 3][['time', 'reservoir', '_rep']] D.pivot(index='time', columns='_rep', values='reservoir').plot(legend=False, lw=1) data.groupby('time')['reservoir'].mean().plot(color='k', linestyle='--') plt.title('Simulated and Expected Reservoir Level') plt.xlabel('Year') plt.ylabel('Reservoir Level') # Plot Simulated Policy Path D = data[data['_rep'] < 3][['time', 'released', '_rep']] D.pivot('time', '_rep', 'released').plot(legend=False, lw=1) data.groupby('time')['released'].mean().plot(color='k', linestyle='--') plt.title('Simulated and Expected Irrigation') plt.xlabel('Year') plt.ylabel('Irrigation') # Print Steady-State and Ergodic Moments ff = '\t%15s = %5.2f' D = data[data['time'] == T]
F.c = np.reshape(c, (2, n)) nplot = 501 t = np.linspace(0, T, nplot) (p, s), (dp, ds) = F(t, [[0, 1]]) res_p = dp - r * p - k res_s = ds + p ** -eta plt.figure() plt.subplot(2, 1, 1) plt.plot(t, res_p) plt.title('Residuals') plt.ylabel('d(price) residual') plt.subplot(2, 1, 2) plt.plot(t, res_s) plt.xlabel('time') plt.ylabel('d(storage) residual') plt.figure() plt.subplot(2, 1, 1) plt.plot(t, p) plt.title('Solution') plt.ylabel('Price') plt.subplot(2, 1, 2) plt.plot(t, s) plt.xlabel('time') plt.ylabel('Stock')
if abs(i - j) > 1: AA[i,j] = 0 n = np.hstack((np.arange(50, 250, 50), np.arange(300, 1100, 100))) ratio = np.empty(n.size) for k in range(n.size): A = AA[:n[k], :n[k]] b = bb[:n[k]] tt = tic() for i in range(100): x = solve(A, b) toc1 = toc(tt) S = csc_matrix(A) tt = tic() for i in range(100): x = spsolve(S, b) toc2 = toc(tt) ratio[k] = toc2 / toc1 # Plot effort ratio plt.figure(figsize=[6, 6]) plt.plot(n, ratio) plt.xlabel('n') plt.ylabel('Ratio') plt.title('Ratio of Sparse Solve Time to Full Solve Time') plt.show()
a, b = 0, 2 f = lambda x: x**3 + x**2 + 1 g = lambda x: x**3 + 2 p1, p2 = 1, 2 q1 = quad(lambda x: np.abs(f(x)-g(x)) ** p1, a, b)[0] ** (1 / p1) q2 = quad(lambda x: np.abs(f(x)-g(x)) ** p2, a, b)[0] ** (1 / p2) print('\nCompute function metrics') print('\tnorm 1 = {:6.4f}, norm 2 = {:6.4f}'.format(q1, q2)) # Illustrate function metrics x = np.linspace(a, b, 200) plt.figure(figsize=[12, 4]) plt.subplot(1, 2, 1) plt.plot([0, 2], [0, 0], 'k:', linewidth=4) plt.plot(x, f(x) - g(x), 'b', linewidth=4, label='f - g') plt.xlabel('x') plt.ylabel('y') plt.xticks([0, 1, 2]) plt.yticks([-1, 0, 1, 2, 3]) plt.title('f - g') plt.subplot(1, 2, 2) plt.plot(x, np.abs(f(x) - g(x)), 'b', linewidth=4, label='f - g') plt.xlabel('x') plt.ylabel('y') plt.xticks([0, 1, 2]) plt.yticks([0, 1, 2, 3]) plt.title('|f - g|') plt.show()
c = storage.broyden(print=True) F.c = np.reshape(c, (2, n)) nplot = 501 t = np.linspace(0, T, nplot) (p, s), (dp, ds) = F(t, [[0, 1]]) res_p = dp - r * p - k res_s = ds + p**-eta plt.figure() plt.subplot(2, 1, 1) plt.plot(t, res_p) plt.title('Residuals') plt.ylabel('d(price) residual') plt.subplot(2, 1, 2) plt.plot(t, res_s) plt.xlabel('time') plt.ylabel('d(storage) residual') plt.figure() plt.subplot(2, 1, 1) plt.plot(t, p) plt.title('Solution') plt.ylabel('Price') plt.subplot(2, 1, 2) plt.plot(t, s) plt.xlabel('time') plt.ylabel('Stock') plt.show()