def unconstrained_employment(self, v=None):
		"""
		Computes the (unconstrained) optimal level of employment
		in a market for every possible state of demand.  

		Parameters
		----------
		v : array_like(float, ndim=len(states))
			The value of the input function on different grid points
			for each of the possible states
		
		Returns
		-------
		n_hat: array_like(float, ndim=len(states))
			The number of employed workers for each state of demand

		"""
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)

		Av = [InterpolatedUnivariateSpline(self.grid, v[i], k=3) for i in xrange(self.states.size)]
		Avx = lambda y: np.asarray([function(y) for function in Av])
		
		#The zero in this function is the level of employment at which
		#workers are indifferent between leaving and staying.
		function = [lambda n, s=state: self.labour_demand(n, s) + 
					self.beta*np.dot(self.transition[j], Avx(n)) - 
					self.lamb for j, state in enumerate(self.states)] 
		
		n_hat = [int(fsolve(function[j], self.grid.max()/2)) for j in xrange(self.states.size)]
		return n_hat
	def plot(self):
		print self
		#w_guess = np.asarray([np.empty(len(self.grid))]*len(self.shocks))
		#w_guess = np.asarray([np.zeros(len(self.grid))]*len(self.shocks))
		w_guess = np.asarray([np.log(self.grid)]*len(self.shocks))
		#w_guess = np.asarray([self.grid]*len(self.shocks)) #Takes Longer.
		w_star = compute_fixed_point(self.bellman_operator, w_guess, max_iter=100000, verbose=0, error_tol=1e-3, print_skip=100)
		sigma_star = self.compute_greedy(w_star)

		fig, ax = plt.subplots(2, 1, figsize =(8,10))
		ax[0].set_xlabel("Cake Size")
		ax[1].set_xlabel("Cake Size")
		ax[0].set_ylabel("Value Function")
		ax[1].set_ylabel("Threshold shock")

		eating = [self.u(self.grid)*self.shocks[i] - .1  for i in xrange(len(self.shocks))] # Value function if always eating.
		                                                                           # Not labeled because they are ordered

		ax[0].set_color_cycle(['r', 'g', 'b', 'c', 'm', 'y'])
		labels = [r'Shock {0:.2g}'.format(self.shocks[k]) for k in xrange(len(self.shocks))] # Label "Shock 1", "Shock 2"
		for i in xrange(len(self.shocks)):
		    ax[0].plot(self.grid, w_star[i], lw = 2, alpha = .8, label= labels[i])
		    
		ax[1].plot(self.grid, sigma_star[0], 'k-', lw = 2, alpha = .8)
		ax[0].legend(loc = 'lower right')
		t = 'Discrete Choice - Cake Problem'
		fig.suptitle(t, fontsize=18)

		plt.show()
Exemple #3
0
	def plot(self):
		print self
		#w_guess = np.asarray([np.empty(len(self.grid))]*len(self.shocks))
		#w_guess = np.asarray([np.zeros(len(self.grid))]*len(self.shocks))
		w_guess = np.asarray([np.log(self.grid)]*len(self.shocks))
		#w_guess = np.asarray([self.grid]*len(self.shocks)) #Takes Longer.
		w_star = compute_fixed_point(self.bellman_operator, w_guess, max_iter=100000, verbose=0, error_tol=1e-3, print_skip=100)
		sigma_star = self.compute_greedy(w_star)

		fig, ax = plt.subplots(2, 1, figsize =(8,10))
		ax[0].set_xlabel("Cake Size")
		ax[1].set_xlabel("Cake Size")
		ax[0].set_ylabel("Value Function")
		ax[1].set_ylabel("Threshold shock")

		eating = [self.u(self.grid)*self.shocks[i] - .01  for i in xrange(len(self.shocks))] # Value function if always eating.
		                                                                           # Not labeled because they are ordered

		ax[0].set_color_cycle(['r', 'g', 'b', 'c', 'm', 'y'])
		labels = [r'Shock {0:.2g}'.format(self.shocks[k]) for k in xrange(len(self.shocks))] # Label "Shock 1", "Shock 2"
		labels2 = ['']*(len(self.shocks)-1) + ['Always eating']
		for i in xrange(len(self.shocks)):
		    ax[0].plot(self.grid, w_star[i], lw = 2, alpha = .8, label= labels[i])
		    ax[0].plot(self.grid, eating[i], 'k--', lw = 2, alpha = .8, label= labels2[i])

		ax[1].plot(self.grid, sigma_star[0], 'k-', lw = 2, alpha = .8)
		ax[0].legend(loc = 'lower right')
		t = 'Discrete Choice - Cake Problem'
		fig.suptitle(t, fontsize=18)

		plt.show()
	def compute_employment(self, v=None):
		"""
		Computes the level of employment for every possible
		workforce and state of demand  

		Parameters
		----------
		v : array_like(float, ndim=len(states))
			The value of the input function on different grid points
			for each of the possible states
		
		Returns
		-------
		n_eq: array_like(float, ndim=len(states))
			The number of employed workers for each workforce and
			state of demand

		"""
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)

		n_hat = self.unconstrained_employment(v)
		n_eq = np.asarray([np.empty(self.grid.size)]*self.states.size)
				
		#Imposes the workforce constraint if it is binding
		for j in xrange(self.states.size):
			n_eq[j] = np.maximum(0,np.minimum(n_hat[j], self.grid))
					
		return n_eq
	def next_workforce(self, v=None):
		"""
		Computes the next period workforce given current workforce
		and state of demand
		
		Parameters
		----------
		v : array_like(float, ndim=len(states))
			The approximate value function. After applying the
			bellman operator until convergence
		
		Returns
		-------
		next_wf: array_like(float, ndim=len(states))
			The next period workforce for each current workforce 
			and state of demand

		"""
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)
		
		Av = [InterpolatedUnivariateSpline(self.grid, v[i], k=3) for i in xrange(self.states.size)]
		Avx = lambda y: np.asarray([function(y) for function in Av])
		
		n_eq = self.compute_employment(v)
		next_wf = np.asarray([np.empty(self.grid.size)]*self.states.size) 

		for j, state in enumerate(self.states):
			for i, y in enumerate(self.grid):
				if n_eq[j][i] == y: # This means we are in case B1 or B2
					e_value =[self.beta*np.dot(self.transition[j], Avx(y + a)) < self.lamb for a in xrange(100)]
					try:
						a_star = e_value.index(True) # This function gives the first a for which the function
					except ValueError:
						a_star = 0				 	 # self.beta*np.dot(self.transition[j], Avx(y + a)) - self.lamb
													 # becomes negative. Thus, it is the  number of workers 
													 # arriving in the next period. 
					next_wf[j][i] = y + a_star
				
				else: # This is case A 
					if i == 0:
						next_wf[j][i] = n_eq[j][i]
					else:
						next_wf[j][i] = next_wf[j][i-1] #As no more workers are being hired, 
													#next period workforce is the same as 
													#for a market with one less worker 	
									
		return next_wf
Exemple #6
0
def compute_asset_series(cp, T=500000):
    """
    Simulates a time series of length T for assets, given optimal savings
    behavior.  Parameter cp is an instance of consumerProblem
    """

    Pi, z_vals, R = cp.Pi, cp.z_vals, cp.R  # Simplify names
    v_init, c_init = initialize(cp)
    c = compute_fixed_point(coleman_operator, cp, c_init)
    cf = lambda a, i_z: interp(a, cp.asset_grid, c[:, i_z])
    a = np.zeros(T+1)
    z_seq = mc_tools.sample_path(Pi, sample_size=T)
    for t in range(T):
        i_z = z_seq[t]
        a[t+1] = R * a[t] + z_vals[i_z] - cf(a[t], i_z)
    return a
	def markov_transition(self, v=None):
		"""
		Creates the transition matrix for workforce sizes 
		and states of demand.
		"""
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)
		
		new_wf = self.next_workforce(v)
		pll, plh, phl, phh = self.transition.flatten()
		
		I = np.hstack((self.grid, self.grid, self.grid.size + self.grid, self.grid.size + self.grid))
		J = np.hstack((new_wf[0], self.grid.size + new_wf[0], new_wf[1], self.grid.size + new_wf[1]))
		V = np.hstack((pll*np.ones(self.grid.size), plh*np.ones(self.grid.size), 
						phl*np.ones(self.grid.size), phh*np.ones(self.grid.size)))
	
		A = coo_matrix((V,(I,J)),shape=(self.states.size*self.grid.size, self.states.size*self.grid.size))

		M = A.tocsr().transpose()

		return M
	def workforce_change(self, v=None, stochastic=False):
		"""
		Computes the change in workforce size given current
		workforce and state of demand
		
		Parameters
		----------
		v : array_like(float, ndim=len(states))
			The approximate value function. After applying the
			bellman operator until convergence
		
		Returns
		-------
		wf_change: array_like(float, ndim=len(states))
			The next period workforce for each current workforce 
			and state of demand

		"""
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)
		
		return self.next_workforce(v=v, stochastic=stochastic) - self.grid
import matplotlib.pyplot as plt
import numpy as np
from discrete_rv import discreteRV
from career import *
from compute_fp import compute_fixed_point

wp = workerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(bellman, wp, v_init)
optimal_policy = get_greedy(wp, v)
F = discreteRV(wp.F_probs)
G = discreteRV(wp.G_probs)

def gen_first_passage_time():
    t = 0
    i = j = 0  
    theta_index = []
    epsilon_index = []
    while 1:
        if optimal_policy[i, j] == 1:    # Stay put
            return t
        elif optimal_policy[i, j] == 2:  # New job
            j = int(G.draw())
        else:                            # New life
            i, j  = int(F.draw()), int(G.draw())
        t += 1

M = 25000 # Number of samples
samples = np.empty(M)
for i in range(M): 
    samples[i] = gen_first_passage_time()
	def markov_transition(self, v=None, stochastic=False):
		"""
		Creates the transition matrix for workforce sizes 
		and states of demand.
		"""
		
		if v == None:
			v = np.asarray([np.zeros(self.grid.size)]*self.states.size)
			v = compute_fixed_point(self.bellman_operator, v, verbose=0, max_iter=30)
		

		new_wf = self.next_workforce(v, stochastic=stochastic)
		pll, plh, phl, phh = self.transition.flatten()
		
		if stochastic:
			bottom = 0
			top = 2

			incoming = np.asarray([[(new_wf[state-1][y] - y)*(new_wf[state-1][y] > y) 
									for y in self.grid] for state in self.states], dtype=int)
									
			inc_index_0 = [[i for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[0]) if abs(y) >.1]
			inc_col_0 = [[i + y_1 for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[0]) if abs(y) >.1]
			inc_val_0 = [[1./(int(top*y+1)-int(bottom*y)) if y_1!=y else 1./(int(top*y+1)-int(bottom*y)) - 1 
									for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[0]) if abs(y) >.1]
									
			inc_index_1 = [[i for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[1]) if abs(y) >.1]
			inc_col_1 = [[i + y_1 for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[1]) if abs(y) >.1]
			inc_val_1 = [[1./(int(top*y+1)-int(bottom*y)) if y_1!=y else 1./(int(top*y+1)-int(bottom*y)) - 1 
									for y_1 in xrange(int(bottom*y), int(top*y + 1))] 
									for i, y in enumerate(incoming[1]) if abs(y) >.1]
			
			inc_index_0 = np.asarray(flatten(inc_index_0))
			inc_index_1 = np.asarray(flatten(inc_index_1))
			inc_val_0 = np.asarray(flatten(inc_val_0))
			inc_val_1 = np.asarray(flatten(inc_val_1))
			inc_col_0 = np.asarray(flatten(inc_col_0))
			inc_col_1 = np.asarray(flatten(inc_col_1))

			incoming_ind = np.hstack((inc_index_0, inc_index_0, self.grid.size + inc_index_1, self.grid.size + inc_index_1))
			incoming_col = np.hstack((inc_col_0, self.grid.size + inc_col_0, inc_col_1, self.grid.size + inc_col_1))
			incoming_val = np.hstack((pll*inc_val_0, plh*inc_val_0, phl*inc_val_1, phh*inc_val_1))
		 
			I = np.hstack((self.grid, self.grid, self.grid.size + self.grid, self.grid.size + self.grid, incoming_ind))
			J = np.hstack((new_wf[0], self.grid.size + new_wf[0], new_wf[1], self.grid.size + new_wf[1], incoming_col))
			V = np.hstack((pll*np.ones(self.grid.size), plh*np.ones(self.grid.size), phl*np.ones(self.grid.size), phh*np.ones(self.grid.size), incoming_val))

		else:
			I = np.hstack((self.grid, self.grid, self.grid.size + self.grid, self.grid.size + self.grid))
			J = np.hstack((new_wf[0], self.grid.size + new_wf[0], new_wf[1], self.grid.size + new_wf[1]))
			V = np.hstack((pll*np.ones(self.grid.size), plh*np.ones(self.grid.size), phl*np.ones(self.grid.size), phh*np.ones(self.grid.size)))
		

		A = coo_matrix((V,(I,J)),shape=(self.states.size*self.grid.size, self.states.size*self.grid.size))

		M = A.tocsr().transpose()

		return M
from compute_fp import compute_fixed_point
from matplotlib import pyplot as plt
from ifp import *

# === solve for optimal consumption === #
m = consumerProblem(r=0.03, grid_max=4)
v_init, c_init = initialize(m)
c = compute_fixed_point(coleman_operator, m, c_init)
a = m.asset_grid
R, z_vals = m.R, m.z_vals

# === generate savings plot === #
fig, ax = plt.subplots()
ax.plot(a, R * a + z_vals[0] - c[:, 0], label='low income')
ax.plot(a, R * a + z_vals[1] - c[:, 1], label='high income')
ax.plot(a, a, 'k--')
ax.set_xlabel('current assets')
ax.set_ylabel('next period assets')
ax.legend(loc='upper left')
fig.show()
Exemple #12
0
"""
Tests jv.py with a particular parameterization.

"""
import matplotlib.pyplot as plt
from jv import workerProblem, bellman_operator
from compute_fp import compute_fixed_point

# === solve for optimal policy === #
wp = workerProblem(grid_size=25)
v_init = wp.x_grid * 0.5
V = compute_fixed_point(bellman_operator, wp, v_init, max_iter=40)
s_policy, phi_policy = bellman_operator(wp, V, return_policies=True)

# === plot policies === #
fig, ax = plt.subplots()
ax.set_xlim(0, max(wp.x_grid))
ax.set_ylim(-0.1, 1.1)
ax.plot(wp.x_grid, phi_policy, 'b-', label='phi')
ax.plot(wp.x_grid, s_policy, 'g-', label='s')
ax.legend()
plt.show()

Exemple #13
0
"""
Origin: QE by John Stachurski and Thomas J. Sargent
Filename: ifp_savings_plots.py
Authors: John Stachurski, Thomas J. Sargent
LastModified: 11/08/2013

"""
from compute_fp import compute_fixed_point
from matplotlib import pyplot as plt
from ifp import *

# === solve for optimal consumption === #
m = consumerProblem(r=0.03, grid_max=4)
v_init, c_init = initialize(m)
c = compute_fixed_point(coleman_operator, m, c_init)
a = m.asset_grid
R, z_vals = m.R, m.z_vals

# === generate savings plot === #
fig, ax = plt.subplots()
ax.plot(a, R * a + z_vals[0] - c[:, 0], label='low income')
ax.plot(a, R * a + z_vals[1] - c[:, 1], label='high income')
ax.plot(a, a, 'k--')
ax.set_xlabel('current assets')
ax.set_ylabel('next period assets')
ax.legend(loc='upper left')
plt.show()
Exemple #14
0
def fp(x,alpha,Omega, *args): 
	y = np.zeros(len(x))
	S = Omega(x,*args)

	f2 = np.zeros(len(x))
	f_2 = np.zeros(len(x))
	
	for i in range(len(x)):
		f_2[i] = (1-alpha)*(x[i]**alpha)*S[i]**(-alpha)
	f2 = Omega(f_2,*args)
	for i in range(len(x)):
		y[i] = (alpha*x[i]**(alpha-1))*S[i]**(1-alpha) + f2[i]
	return y


x = np.ones(grid_size)
x = x*M

geo = geog(f,fp,alpha, beta, delta, theta, Omega, ker, grid_size,M)

fig, ax = plt.subplots(figsize=(5, 5))
ax.set_xlabel("location",fontsize = 14)
ax.set_ylabel("capital",fontsize = 12)

v_star = compute_fixed_point(geo.proj_dec, x, maxiter=1000)
g_star, lamb = geo.growth(v_star)

ax.plot(grid,v_star, '-', lw=1)

plt.savefig('geo.eps')
Exemple #15
0
    beta, c, f, g, q = sp.beta, sp.c, sp.f, sp.g, sp.q  # Simplify names
    phi_f = lambda p: interp(p, sp.pi_grid, phi)  # Turn phi into a function
    new_phi = np.empty(len(phi))
    for i, pi in enumerate(sp.pi_grid):

        def integrand(x):
            "Integral expression on right-hand side of operator"
            return npmax(x, phi_f(q(x, pi))) * (pi * f(x) + (1 - pi) * g(x))

        integral, error = fixed_quad(integrand, 0, sp.w_max)
        new_phi[i] = (1 - beta) * c + beta * integral
    return new_phi


if __name__ == '__main__':  # If module is run rather than imported

    sp = searchProblem(pi_grid_size=50)
    phi_init = np.ones(len(sp.pi_grid))
    w_bar = compute_fixed_point(res_wage_operator, sp, phi_init)

    fig, ax = plt.subplots()
    ax.plot(sp.pi_grid, w_bar, linewidth=2, color='black')
    ax.set_ylim(0, 2)
    ax.grid(axis='x', linewidth=0.25, linestyle='--', color='0.25')
    ax.grid(axis='y', linewidth=0.25, linestyle='--', color='0.25')
    ax.fill_between(sp.pi_grid, 0, w_bar, color='blue', alpha=0.15)
    ax.fill_between(sp.pi_grid, w_bar, 2, color='green', alpha=0.15)
    ax.text(0.42, 1.2, 'reject')
    ax.text(0.7, 1.8, 'accept')
    plt.show()
Exemple #16
0
import matplotlib.pyplot as plt
from matplotlib import cm
from career import *
from compute_fp import compute_fixed_point

wp = workerProblem()
v_init = np.ones((wp.N, wp.N)) * 100
v = compute_fixed_point(bellman, wp, v_init)
optimal_policy = get_greedy(wp, v)

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
tg, eg = np.meshgrid(wp.theta, wp.epsilon)
lvls = (0.5, 1.5, 2.5, 3.5)
ax.contourf(tg, eg, optimal_policy.T, levels=lvls, cmap=cm.winter, alpha=0.5)
ax.contour(tg, eg, optimal_policy.T, colors='k', levels=lvls, linewidths=2)
ax.set_xlabel('theta', fontsize=14)
ax.set_ylabel('epsilon', fontsize=14)
ax.text(1.8, 2.5, 'new life', fontsize=14)
ax.text(4.5, 2.5, 'new job', fontsize=14, rotation='vertical')
ax.text(4.0, 4.5, 'stay put', fontsize=14)
plt.show()
Exemple #17
0
"""
Origin: QE by John Stachurski and Thomas J. Sargent
Filename: jv_test.py
Authors: John Stachurski and Thomas Sargent
LastModified: 11/08/2013

Tests jv.py with a particular parameterization.

"""
import matplotlib.pyplot as plt
from jv import workerProblem, bellman_operator
from compute_fp import compute_fixed_point

# === solve for optimal policy === #
wp = workerProblem(grid_size=25)
v_init = wp.x_grid * 0.5
V = compute_fixed_point(bellman_operator, wp, v_init, max_iter=40)
s_policy, phi_policy = bellman_operator(wp, V, return_policies=True)

# === plot policies === #
fig, ax = plt.subplots()
ax.set_xlim(0, max(wp.x_grid))
ax.set_ylim(-0.1, 1.1)
ax.plot(wp.x_grid, phi_policy, 'b-', label='phi')
ax.plot(wp.x_grid, s_policy, 'g-', label='s')
ax.legend()
plt.show()

Exemple #18
0
from scipy import interp
import numpy as np
import matplotlib.pyplot as plt
from odu_vfi import searchProblem
from solution_odu_ex1 import res_wage_operator
from compute_fp import compute_fixed_point

# Set up model and compute the function w_bar
sp = searchProblem(pi_grid_size=50, F_a=1, F_b=1)
pi_grid, f, g, F, G = sp.pi_grid, sp.f, sp.g, sp.F, sp.G
phi_init = np.ones(len(sp.pi_grid)) 
w_bar_vals = compute_fixed_point(res_wage_operator, sp, phi_init)
w_bar = lambda x: interp(x, pi_grid, w_bar_vals)


class Agent:
    """
    Holds the employment state and beliefs of an individual agent.
    """

    def __init__(self, pi=1e-3):
        self.pi = pi
        self.employed = 1

    def update(self, H):
        "Update self by drawing wage offer from distribution H."
        if self.employed == 0:
            w = H.rvs()
            if w >= w_bar(self.pi):
                self.employed = 1
            else:
Exemple #19
0
from compute_fp import compute_fixed_point

gm = growthModel() 
w = 5 * gm.u(gm.grid) - 25  # To be used as an initial condition
discount_factors = (0.9, 0.94, 0.98)
series_length = 25

fig, ax = plt.subplots()
ax.set_xlabel("time")
ax.set_ylabel("capital")

for beta in discount_factors:

    # Compute the optimal policy given the discount factor
    gm.beta = beta
    v_star = compute_fixed_point(bellman_operator, gm, w, max_iter=20)
    sigma = compute_greedy(gm, v_star)

    # Compute the corresponding time series for capital
    k = np.empty(series_length)
    k[0] = 0.1
    sigma_function = lambda x: interp(x, gm.grid, sigma)
    for t in range(1, series_length):
        k[t] = gm.f(k[t-1]) - sigma_function(k[t-1])
    ax.plot(k, 'o-', lw=2, alpha=0.75, label=r'$\beta = {}$'.format(beta))

ax.legend(loc='lower right')
plt.show()


from compute_fp import compute_fixed_point

alpha, beta = 0.65, 0.95
gm = growthModel()
true_sigma = (1 - alpha * beta) * gm.grid**alpha
w = 5 * gm.u(gm.grid) - 25  # Initial condition

fig, ax = plt.subplots(3, 1, figsize=(8, 10))

for i, n in enumerate((2, 4, 6)):
    ax[i].set_ylim(0, 1)
    ax[i].set_xlim(0, 2)
    ax[i].set_yticks((0, 1))
    ax[i].set_xticks((0, 2))

    v_star = compute_fixed_point(bellman_operator, gm, w, max_iter=n)
    sigma = compute_greedy(gm, v_star)

    ax[i].plot(gm.grid,
               sigma,
               'b-',
               lw=2,
               alpha=0.8,
               label='approximate optimal policy')
    ax[i].plot(gm.grid,
               true_sigma,
               'k-',
               lw=2,
               alpha=0.8,
               label='true optimal policy')
    ax[i].legend(loc='upper left')