def newPlot(title, Y, k): ax = fig.add_subplot(1, 3, k, projection='3d') ax.plot_surface(x1, x2, Y, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_zlabel('$y$') plt.title(title)
nrep = 10000 sinit = np.full(nrep, pbar) iinit = 0 data = model.simulate(T,sinit,iinit, seed=945) # Print Ergodic Moments frm = '\t{:<10s} = {:5.2f}' print('\nErgodic Means') print(frm.format('Price', data['unit profit'].mean())) print(frm.format('Age', data.i.mean())) print('\nErgodic Standard Deviations') print(frm.format('Price', data['unit profit'].std())) print(frm.format('Age', data.i.std())) # Plot Simulated and Expected Continuous State Path print(demo.qplot('time', 'unit profit', '_rep', data=data[data['_rep'] < 3], geom='line', main='Simulated and Expected Price', ylab='Net Unit Profit', xlab='Period')) # Plot Expected Discrete State Path data[['time', 'i']].groupby('time').mean().plot(legend=False) plt.title('Expected Machine Age') plt.xlabel('Period') plt.ylabel('Age') plt.show()
def subfig(k, x, y, xlim, ylim, title): plt.subplot(2, 2, k) plt.plot(x, y) plt.xlim(xlim) plt.ylim(ylim) plt.title(title)
plt.hlines(0, smin, smax, 'k', '--') ## 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]
plt.plot(s, q.T) # Plot Value Function demo.figure('Value Function', 'Ore Stock', 'Value') plt.plot(s, v.T) # Plot Shadow Price Function demo.figure('Shadow Price Function', 'Ore Stock', 'Shadow Price') plt.plot(s, model.Value(s, 1)) # Plot Residual demo.figure('Bellman Equation Residual', 'Ore Stock', 'Residual') plt.plot(s, resid.T) plt.hlines(0, 0, smax, 'k', '--') ## SIMULATION # Simulate Model T = 20 data = model.simulate(T, smax) # Plot State and Policy Paths data[['stock', 'extracted']].plot() plt.title('State and Policy Paths') plt.legend(['Stock', 'Extraction']) plt.hlines(sstar, 0, T, 'k', '--') plt.xlabel('Period') plt.ylabel('Stock / Extraction') plt.show()
# Plot Chebychev Collocation Residual and Approximation Error 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()
# Print Ergodic Moments ff = '\t{:12s} = {:5.2f}' print('\nErgodic Means') print(ff.format('Wage', data['wage'].mean())) print(ff.format('Employment', (data['i'] == 'employed').mean())) print('\nErgodic Standard Deviations') print(ff.format('Wage', data['wage'].std())) print(ff.format('Employment', (data['i'] == 'employed').std())) # Plot Expected Discrete State Path subdata = data[['time', 'i']] subdata['i'] = subdata['i'] == 'employed' subdata.groupby('time').mean().plot(legend=False) plt.title('Probability of Employment') plt.xlabel('Period') plt.ylabel('Probability') # Plot Simulated and Expected Continuous State Path subdata = data[data['_rep'] < 3][['time', 'wage', '_rep']] subdata.pivot(index='time', columns='_rep', values='wage').plot(legend=False, lw=1) plt.hlines(data['wage'].mean(), 0, T) plt.title('Simulated and Expected Wage') plt.xlabel('Period') plt.ylabel('Wage') plt.show()
X2.shape = nplot fig = plt.figure(figsize=[15, 6]) ax = fig.add_subplot(1, 2, 1, projection='3d') ax.plot_surface(X1, X2, error, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_zlabel('error') plt.title('Chebychev Approximation Error') # The plot indicates that an order 11 by 11 Chebychev approximation scheme # produces approximation errors no bigger in magnitude than 1x10^-10. # Let us repeat the approximation exercise, this time constructing an order # 21 by 21 cubic spline approximation scheme: n = [21, 21] # order of approximation S = BasisSpline(n, a, b, f=f) yapp = S(X) # approximant values at grid nodes error = (yapp - yact).reshape(nplot) ax = fig.add_subplot(1, 2, 2, projection='3d') ax.plot_surface(X1, X2, error, rstride=1,
yc = C(x) # values dc = C(x, 1) # first derivative sc = C(x, 2) # second derivative # Construct and evaluate cubic spline interpolant S = BasisSpline(n, a, b, f=f) # chose basis functions ys = S(x) # values ds = S(x, 1) # first derivative ss = S(x, 2) # second derivative # Plot function approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, y - yc[0]) plt.ylabel('Chebychev') plt.title('Function Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, y - ys[0]) plt.ylabel('Cubic Spline') plt.xlabel('x') # Plot first derivative approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, d - dc[0]) plt.ylabel('Chebychev') plt.title('First Derivative Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, d - ds[0], 'm')
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()
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() # Demonstrate Pythagorean Theorem a, b = -1, 1 f = lambda x: 2 * x**2 - 1 g = lambda x: 4 * x**3 -3*x
# 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
return np.r_[d.flatten(), s_0 - s0, s_T] storage = NLP(resid, F.c.flatten(), tnodes, T, n, F, r, k, eta, s0) 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)
dc = C(x, 1) # first derivative sc = C(x, 2) # second derivative # Construct and evaluate cubic spline interpolant S = BasisSpline(n, a, b, f=f) # chose basis functions ys = S(x) # values ds = S(x, 1) # first derivative ss = S(x, 2) # second derivative # Plot function approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, y - yc[0]) plt.ylabel('Chebychev') plt.title('Function Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, y - ys[0]) plt.ylabel('Cubic Spline') plt.xlabel('x') # Plot first derivative approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, d - dc[0]) plt.ylabel('Chebychev') plt.title('First Derivative Approximation Error') plt.subplot(2, 1, 2)
return np.r_[d.flatten(), s_0 - s0, s_T] storage = NLP(resid, F.c.flatten(), tnodes, T, n, F, r, k, eta, s0) 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)
## SIMULATION # 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'