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()
## 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] print('\nDeterministic Steady-State')
## 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] print('\nDeterministic Steady-State')
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()
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)
C = BasisChebyshev(n, a, b, f=f) # chose basis functions 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)
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()
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() # Demonstrate Pythagorean Theorem
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()
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) plt.xlabel('time')
# 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()
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')
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()
plt.plot(s, v.T) # Plot Shadow Price Function demo.figure('Shadow Price Function', 'Stock', 'Shadow Price') plt.plot(s, model.Value(s, 1).T) # Plot Residual demo.figure('Bellman Equation Residual', 'Stock', 'Residual') plt.plot(s, resid.T) plt.hlines(0, smin, smax, 'k', '--') ## SIMULATION # Simulate Model T = 15 data = model.simulate(T, smin) print(data) # Plot State and Policy Paths opts = dict(spec='r*', offset=(0, -5), fs=11, ha='right') data[['available', 'harvest']].plot() demo.annotate(T, sstar, 'steady-state stock = %.2f' % sstar, **opts) demo.annotate(T, qstar, 'steady-state harvest = %.2f' % qstar, **opts) plt.xlim([0, T + 0.25]) plt.title('State and Policy Paths') plt.xlabel('Period') plt.ylabel('Stock / Harvest') plt.legend(['Stock', 'Harvest'], loc='right') plt.show()
scrit = np.interp(0.0, vr[1] - vr[0], sr) vcrit = np.interp(scrit, sr, vr[0]) demo.annotate(scrit, vcrit, '$s^* = {:.2f}$'.format(scrit), 'wo', (-5, 5), fs=12) print('Optimal Biomass Harvesting Level = {:5.2f}'.format(scrit)) # Plot Residual demo.figure('Bellman Equation Residual', 'Biomass', 'Percent Residual') plt.plot(sr, 100 * resid.T / vr.max(0).T) ## SIMULATION # Simulate Model T = 50 # Number of periods simulated sinit = 0.0 # Initial value of continuous state data = model.simulate(T, sinit) # Compute Optimal Rotation Cycle print('Optimal Rotation Cycle = ', np.min(data.time[data.j == 'clear cut'])) # Plot State Path data.plot('time', 'stand biomass', legend=False, title='Rotation cycle') plt.ylabel('Biomass') plt.show()
# Plot Shadow Price Function demo.figure('Shadow Price Function', 'Stock', 'Shadow Price') plt.plot(s, model.Value(s, 1).T) # Plot Residual demo.figure('Bellman Equation Residual','Stock', 'Residual') plt.plot(s, resid.T) plt.hlines(0, smin, smax, 'k', '--') ## SIMULATION # Simulate Model T = 15 data = model.simulate(T, smin) print(data) # Plot State and Policy Paths opts = dict(spec='r*', offset=(0,-5), fs=11, ha='right') data[['available', 'harvest']].plot() demo.annotate(T, sstar, 'steady-state stock = %.2f' % sstar, **opts) demo.annotate(T, qstar, 'steady-state harvest = %.2f' % qstar, **opts) plt.xlim([0, T + 0.25]) plt.title('State and Policy Paths') plt.xlabel('Period') plt.ylabel('Stock / Harvest') plt.legend(['Stock','Harvest'], loc='right') 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']]
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()