예제 #1
0
def test_eval_with_fortran_order():

    import numpy as np

    C_F = np.random.random((50, 50)).T
    C = C_F.copy()

    print(C.flags)
    print(C_F.flags)

    p = np.random.random((10, 2))

    p_F = p.T.copy().T

    from interpolation.splines import eval_linear

    out_F_C = eval_linear(((0.0, 1.0, 48), (0.0, 1.0, 48)), C_F, p)
    out_C_C = eval_linear(((0.0, 1.0, 48), (0.0, 1.0, 48)), C, p)

    out_F_F = eval_linear(((0.0, 1.0, 48), (0.0, 1.0, 48)), C_F, p_F)
    out_C_F = eval_linear(((0.0, 1.0, 48), (0.0, 1.0, 48)), C, p_F)

    assert np.array_equal(out_F_C, out_C_C)
    assert np.array_equal(out_F_C, out_F_F)
    assert np.array_equal(out_F_C, out_C_F)
예제 #2
0
    def objective_cap(c, rho, sigma, y):
        """
        The right hand side of the pricing operator
        """
        # First turn w into a function via interpolation
        #print(c)
        sigma_func = [lambda points: eval_linear(gridI, sigma[:,0].reshape(grid_size, grid_size),points),\
                         lambda points: eval_linear(gridI, sigma[:,1].reshape(grid_size, grid_size),points)]
        rho_func = [lambda points: eval_linear(gridI, rho[:,0].reshape(grid_size, grid_size), points),\
                     lambda points: eval_linear(gridI, rho[:,1].reshape(grid_size, grid_size), points)]

        x_prime = (1 - delta_storage) * (y[1] - p_inv(
            demand_shocks[int(y[2])], rho_func[int(y[2])](y[0:2]))) + shock * c
        I = c - (1 - delta_cap) * y[0]
        c_col = x_prime.copy()
        c_col.fill(c)
        prime_xc = np.column_stack((c_col, x_prime))
        I_prime = [(sigma_func[0](prime_xc) - (1 - delta_cap) * c),
                   (sigma_func[1](prime_xc) - (1 - delta_cap) * c)]

        #k_prime= x_prime.copy()
        #k_prime.fill(sigma_func[int(y[2])](y[0:2]))
        prime = np.column_stack((c_col, x_prime))

        integrand = demand_P[0]*(rho_func[0](prime)*shock\
                                +(1-delta_cap)*(2*phi_prime(I_prime[0]**2)*I_prime[0] +1))\
                    + demand_P[1]*(rho_func[1](prime)*shock\
                                +(1-delta_cap)*(2*phi_prime(I_prime[1]**2)*I_prime[1] +1))
        Eprof = beta * np.mean(integrand)
        #print(np.max([beta*Eprof, (2*phi_prime((-(1-delta_cap)*y[0])**2))*(-(1-delta_cap)*y[0])]) - 2*phi_prime(I**2)*I)
        return np.max([
            beta * Eprof, (2 * phi_prime(
                (-(1 - delta_cap) * y[0])**2)) * (-(1 - delta_cap) * y[0])
        ]) - 2 * phi_prime(I**2) * I
    def gen_VPi(points, Age, account_ind,\
       E_ind, alpha_ind,beta_ind,\
       pi_ushock, v_ushock,Xi_cov,Xi_copi):
        """ Genrates voluntary contribution 
			risk prob"""

        xi_V_vals = eval_linear(X_cont_W, Xi_cov[Age][account_ind,E_ind,alpha_ind,beta_ind,:],\
               points)

        xi_V_vals = xi_V_vals - max(xi_V_vals)

        prob_v = np.exp(xi_V_vals) / np.sum(np.exp(xi_V_vals))

        #pick a random draw for the voluntary contribution (index in the vol.cont grid)
        V_ind = np.arange(len(V))[np.searchsorted(np.cumsum(prob_v), v_ushock)]

        v = V[V_ind]

        #pull our probabiltiy of risk share matrix for this cont state
        xi_Pi_vals   = eval_linear(X_cont_W, Xi_copi[Age][account_ind,E_ind,alpha_ind,beta_ind,V_ind,:],\
                points)

        xi_Pi_vals = xi_Pi_vals - max(xi_Pi_vals)
        prob_Pi = np.exp(xi_Pi_vals) / np.sum(np.exp(xi_Pi_vals))

        Pi_ind = np.arange(len(Pi))[np.searchsorted(np.cumsum(prob_Pi),
                                                    pi_ushock)]

        pi = Pi[Pi_ind]

        return V_ind, v, Pi_ind, pi
예제 #4
0
    def objective_price(c, rho, sigma, y):
        """
        The right hand side of the pricing operator
        """
        # First turn w into a function via interpolation
        sigma_func = lambda x, z: eval_linear(
            gridI, sigma[:, int(y[2])].reshape(grid_size, grid_size),
            np.array([x, z]))
        rho_func = [lambda points: eval_linear(gridI, rho[:,0].reshape(grid_size, grid_size), points), \
                    lambda points: eval_linear(gridI, rho[:,1].reshape(grid_size, grid_size), points)]

        x_prime = (1 - delta_storage) * (y[1] - p_inv(
            demand_shocks[int(int(y[2]))], c)) + shock * sigma_func(
                y[0], y[1])
        k_prime = x_prime.copy()
        k_prime.fill(sigma_func(y[0], y[1]))
        prime = np.column_stack((k_prime, x_prime))
        integrand = demand_P[0]*rho_func[0](prime)\
                +demand_P[1]*rho_func[1](prime)
        Eprice = np.mean(integrand)

        if S_bar_flag == 1:
            return np.min([
                np.max([beta * Eprice,
                        p(demand_shocks[int(y[2])], y[1])]),
                p(demand_shocks[int(y[2])], y[1] - S_bar)
            ]) - c
        elif S_bar_flag == 0:
            return np.max([beta * Eprice,
                           p(demand_shocks[int(y[2])], y[1])]) - c
예제 #5
0
    def interpolate(self, spin, bands, kpoints):
        v = np.concatenate([np.asarray(bands)[:, None], np.asarray(kpoints)], axis=1)

        if interpolation:
            from interpolation.splines import eval_linear
            from interpolation.splines import extrap_options as xto

            grid, data = self.interpolators[spin]
            if np.iscomplexobj(data):
                # only allows interpolating floats, so have to separate real and imag
                interp_data = np.empty((len(v),) + self.data_shape, dtype=np.complex)
                interp_data.real = eval_linear(grid, data.real, v, xto.LINEAR).reshape(
                    -1, *self.data_shape
                )
                interp_data.imag = eval_linear(grid, data.imag, v, xto.LINEAR).reshape(
                    -1, *self.data_shape
                )
            else:
                interp_data = eval_linear(grid, data, v, xto.LINEAR).reshape(
                    -1, *self.data_shape
                )
        else:
            interp_data = self.interpolators[spin](v)

        return interp_data
예제 #6
0
def _get_overlap_ncl(grid, data, points, n_coeffs):
    initial = np.zeros((n_coeffs, 2), dtype=np.complex64)
    initial.real[:] = eval_linear(grid, data.real, points[0],
                                  xto.LINEAR).reshape((n_coeffs, 2))
    initial.imag[:] = eval_linear(grid, data.imag, points[0],
                                  xto.LINEAR).reshape((n_coeffs, 2))
    initial /= np.linalg.norm(initial)
    initial[:] = np.conj(initial)

    res = np.zeros(points.shape[0] - 1)
    final = np.zeros((n_coeffs, 2), dtype=np.complex64)
    for i in range(1, points.shape[0]):
        final.real[:] = eval_linear(grid, data.real, points[i],
                                    xto.LINEAR).reshape((n_coeffs, 2))
        final.imag[:] = eval_linear(grid, data.imag, points[i],
                                    xto.LINEAR).reshape((n_coeffs, 2))
        final /= np.linalg.norm(final)

        sum_ = 0j
        for j in range(final.shape[0]):
            sum_ += initial[j, 0] * final[j, 0] + initial[j, 1] * final[j, 1]

        res[i - 1] = abs(sum_)**2

    return res
예제 #7
0
파일: overlap.py 프로젝트: kcbhamu/amset
    def get_overlap(self, spin, band_a, kpoint_a, band_b, kpoint_b):
        # k-points should be in fractional
        kpoint_a = np.asarray(kpoint_a)
        kpoint_b = np.asarray(kpoint_b)
        v1 = np.array([[band_a] + kpoint_a.tolist()])

        single_overlap = False
        if isinstance(band_b, numeric_types):
            # only one band index given

            if len(kpoint_b.shape) > 1:
                # multiple k-point indices given
                band_b = np.array([band_b] * len(kpoint_b))

            else:
                band_b = np.array([band_b])
                kpoint_b = [kpoint_b]
                single_overlap = True

        else:
            band_b = np.asarray(band_b)

        # v2 now has shape of (nkpoints_b, 4)
        v2 = np.concatenate([band_b[:, None], kpoint_b], axis=1)

        # get a big array of all the k-points to interpolate
        all_v = np.vstack([v1, v2])

        # get the interpolate projections for the k-points; p1 is the projections for
        # kpoint_a, p2 is a list of projections for the kpoint_b
        if eval_linear:
            grid, coeffs = self.interpolators[spin]

            # only allows interpolating floats, so have to separate real and imag parts
            p1_real, *p2_real = eval_linear(grid, coeffs.real, all_v,
                                            xto.LINEAR)
            p1_imag, *p2_imag = eval_linear(grid, coeffs.imag, all_v,
                                            xto.LINEAR)
            p1 = p1_real + 1j * np.asarray(p1_imag)
            p2 = p2_real + 1j * np.asarray(p2_imag)
        else:
            p1, *p2 = self.interpolators[spin](all_v)

        p1 = np.asarray(p1) / np.linalg.norm(p1)
        p2 = np.asarray(p2) / np.linalg.norm(p2, axis=-1)[:, None]

        braket = np.abs(np.dot(np.conj(p1), p2.T))
        overlap = braket**2

        if single_overlap:
            return overlap[0]
        else:
            return overlap
예제 #8
0
def pfi_raw(func,
            xfromv,
            pars,
            args,
            grid_shape,
            grid,
            gp,
            eps_max,
            it_max,
            init_pfunc,
            x0=None,
            use_x0=True,
            verbose=False):

    ndim = len(grid)
    eps = 1e9
    it_cnt = 0

    xe = xfromv(
        eval_linear(grid, init_pfunc, init_pfunc.reshape(-1, ndim),
                    xto.LINEAR))
    values = func(pars, gp, xe, args=args)[0]
    svalues = values.reshape(grid_shape)

    if use_x0:
        z_old = eval_linear(grid, svalues, x0, xto.LINEAR)[0]

    while eps > eps_max or eps_max < 0:

        it_cnt += 1
        values_old = values.copy()
        values = svalues.reshape(-1, 3)
        xe = xfromv(eval_linear(grid, svalues, values, xto.LINEAR))
        values = func(pars, gp, xe, args=args)[0]
        # values = np.maximum(values, -1e2)
        # values = np.minimum(values, 1e2)
        svalues = values.reshape(grid_shape)

        if use_x0:
            z = eval_linear(grid, svalues, x0, xto.LINEAR)[0]
            eps = np.abs(z - z_old)
            z_old = z
        else:
            eps = np.linalg.norm(values - values_old)

        if verbose:
            print(it_cnt, '- eps:', eps)

        if it_cnt == it_max:
            break

    return values.reshape(grid_shape), it_cnt, eps
예제 #9
0
def _get_overlap(grid, data, points, n_coeffs):
    initial = np.zeros(n_coeffs, dtype=np.complex64)
    initial.real[:] = eval_linear(grid, data.real, points[0], xto.LINEAR)
    initial.imag[:] = eval_linear(grid, data.imag, points[0], xto.LINEAR)
    initial /= np.linalg.norm(initial)
    initial[:] = np.conj(initial)

    res = np.zeros(points.shape[0] - 1)
    final = np.zeros(n_coeffs, dtype=np.complex64)
    for i in range(1, points.shape[0]):
        final.real[:] = eval_linear(grid, data.real, points[i], xto.LINEAR)
        final.imag[:] = eval_linear(grid, data.imag, points[i], xto.LINEAR)
        final /= np.linalg.norm(final)
        res[i - 1] = np.abs(np.dot(final, initial))**2
    return res
예제 #10
0
def eval_s(itp: object, exo_grid: EmptyGrid, endo_grid: CartesianGrid,
           interp_type: Linear, s: object):
    from interpolation.splines import eval_linear
    assert (s.ndim == 2)
    coeffs = itp.coefficients
    gg = endo_grid.__numba_repr__()
    return eval_linear(gg, coeffs, s)
예제 #11
0
파일: overlap.py 프로젝트: kcbhamu/amset
    def get_coefficients(self, spin, bands, kpoints):
        v = np.concatenate([np.asarray(bands)[:, None],
                            np.asarray(kpoints)],
                           axis=1)

        if eval_linear:
            grid, coeffs = self.interpolators[spin]

            # only allows interpolating floats, so have to separate real and imag parts
            real_part = eval_linear(grid, coeffs.real, v, xto.LINEAR)
            imag_part = eval_linear(grid, coeffs.imag, v, xto.LINEAR)

            interp_coeffs = real_part + 1j * imag_part
        else:
            interp_coeffs = self.interpolators[spin](v)

        # need to renormalize coefficients
        return interp_coeffs / np.linalg.norm(interp_coeffs, axis=-1)[:, None]
예제 #12
0
 def drfut(i, ss):
     if iid_process:
         i = 0
     m = dp.node(i)
     l_ = lb(m, ss, p)
     u_ = ub(m, ss, p)
     x = eval_linear((sa0[i, :, 0], ), xa0[i, :, 0], ss)[:, None]
     x = np.minimum(x, u_)
     x = np.maximum(x, l_)
     return x
예제 #13
0
def eval_is(itp, exo_grid: UnstructuredGrid, endo_grid: CartesianGrid, interp_type: Linear, i, s):

    from interpolation.splines import eval_linear
    assert(s.ndim==2)

    grid = endo_grid # one single CartesianGrid
    coeffs = itp.coefficients[i]
    d = len(grid.n)
    gg = tuple( [(grid.min[i], grid.max[i], grid.n[i]) for i in range(d)] )

    return eval_linear(gg, coeffs, s)
예제 #14
0
def eval_ms(itp, exo_grid: CartesianGrid, endo_grid: CartesianGrid, interp_type: Linear, m, s):

    assert(m.ndim==s.ndim==2)

    grid = cat_grids(exo_grid, endo_grid) # one single CartesianGrid
    coeffs = itp.coefficients
    d = len(grid.n)
    gg = tuple( [(grid.min[i], grid.max[i], grid.n[i]) for i in range(d)] )
    from interpolation.splines import eval_linear

    x = np.concatenate([m, s], axis=1)

    return eval_linear(gg, coeffs, x)
예제 #15
0
def eval_ms(itp: object, exo_grid: CartesianGrid, endo_grid: CartesianGrid, interp_type: Linear, m: object, s: object):

    assert(m.ndim==s.ndim==2)

    grid = exo_grid + endo_grid # one single CartesianGrid

    coeffs = itp.coefficients

    gg = grid.__numba_repr__()
    from interpolation.splines import eval_linear

    x = np.concatenate([m, s], axis=1)

    return eval_linear(gg, coeffs, x)
예제 #16
0
def eval_is(
    itp: object,
    exo_grid: UnstructuredGrid,
    endo_grid: CartesianGrid,
    interp_type: Linear,
    i: object,
    s: object,
):

    from interpolation.splines import eval_linear

    assert s.ndim == 2
    coeffs = itp.coefficients[i]
    gg = endo_grid.__numba_repr__()

    return eval_linear(gg, coeffs, s)
예제 #17
0
파일: UTL.py 프로젝트: clatfd/PolarReg
def topolar(car_img, rsamples=0, thsamples=180, intmethod='linear'):
    #BUG in cubic
    if rsamples == 0:
        rsamples = car_img.shape[0] // 2
    if len(car_img.shape) == 2:
        cimg = car_img[:, :, None]
    elif len(car_img.shape) == 3:
        cimg = car_img
    else:
        print('channel not 2/3')
        return

    SUBTH = 360 / thsamples
    height, width, channel = cimg.shape

    grid = UCGrid((0, cimg.shape[1] - 1, cimg.shape[1]),
                  (0, cimg.shape[0] - 1, cimg.shape[0]))

    # filter values
    if intmethod == 'cubic':
        coeffs = filter_cubic(grid, cimg)

    rth = np.zeros((thsamples, rsamples, channel))
    for th in range(thsamples):
        for r in range(rsamples):
            inty = cimg.shape[0] // 2 + r * math.sin(
                th * SUBTH / 180 * math.pi)
            intx = cimg.shape[1] // 2 + r * math.cos(
                th * SUBTH / 180 * math.pi)
            if intx >= cimg.shape[1] - 1 or inty >= cimg.shape[0] - 1:
                rth[th, r] = 0
            elif intx < 0 or inty < 0:
                rth[th, r] = 0
            else:
                if intmethod == 'cubic':
                    rth[th, r] = eval_cubic(grid, coeffs,
                                            np.array([inty, intx]))
                elif intmethod == 'linear':
                    rth[th, r] = eval_linear(grid, cimg, np.array([inty,
                                                                   intx]))

    if len(car_img.shape) == 2:
        return rth[:, :, 0]
    else:
        return rth
예제 #18
0
파일: UTL.py 프로젝트: clatfd/PolarReg
def tocart(polar_img, rheight=0, rwidth=0, intmethod='linear'):
    if rheight == 0 or rwidth == 0:
        rheight = polar_img.shape[1] * 2
        rwidth = polar_img.shape[1] * 2
    #transfer to cartesian based
    if len(polar_img.shape) == 2:
        cimg = polar_img[:, :, None]
    elif len(polar_img.shape) == 3:
        cimg = polar_img
    else:
        print('channel not 2/3')
        return
    rth, rr, rchannel = cimg.shape
    SUBTH = 360 / rth

    grid = UCGrid((0, cimg.shape[0] - 1, cimg.shape[0]),
                  (0, cimg.shape[1] - 1, cimg.shape[1]))

    test_out_c = np.zeros((rheight, rwidth, rchannel))
    for h in range(rheight):
        for w in range(rwidth):
            hy = h - rheight // 2
            wx = w - rwidth // 2
            intradius = int(np.sqrt(hy * hy + wx * wx))
            cth = math.atan2(hy, wx) / np.pi * 180
            if cth < 0:
                intth = (360 + cth)
            else:
                intth = (cth)

            intth /= SUBTH
            if intth > cimg.shape[0] - 1:
                intth = cimg.shape[0] - 1
            #print(intradius,intth)
            if intradius >= cimg.shape[1]:
                test_out_c[h, w] = 0
            else:
                test_out_c[h, w] = eval_linear(grid, cimg,
                                               np.array([intth, intradius]))
    if len(polar_img.shape) == 2:
        return test_out_c[:, :, 0]
    else:
        return test_out_c
예제 #19
0
파일: mrta.py 프로젝트: kcbhamu/amset
    def get_mrta_factor(self, spin, band_a, kpoint_a, band_b, kpoint_b):
        # k-points should be in fractional
        kpoint_a = np.asarray(kpoint_a)
        kpoint_b = np.asarray(kpoint_b)
        v1 = np.array([[band_a] + kpoint_a.tolist()])

        single_factor = False
        if isinstance(band_b, numeric_types):
            # only one band index given

            if len(kpoint_b.shape) > 1:
                # multiple k-point indices given
                band_b = np.array([band_b] * len(kpoint_b))

            else:
                band_b = np.array([band_b])
                kpoint_b = [kpoint_b]
                single_factor = True

        else:
            band_b = np.asarray(band_b)

        # v2 now has shape of (nkpoints_b, 4)
        v2 = np.concatenate([band_b[:, None], kpoint_b], axis=1)

        # get a big array of all the k-points to interpolate
        all_v = np.vstack([v1, v2])

        # get the interpolate projections for the k-points; p1 is the projections for
        # kpoint_a, p2 is a list of projections for the kpoint_b

        if eval_linear:
            p1, *p2 = eval_linear(*self.interpolators[spin], all_v, xto.LINEAR)
        else:
            p1, *p2 = self.interpolators[spin](all_v)

        factor = 1 - np.dot(p1, np.asarray(p2).T) / np.linalg.norm(p1) ** 2

        if single_factor:
            return factor[0]
        else:
            return factor
예제 #20
0
def pfi_determinisic(func, xfromv, pars, args, grid_shape, grid, gp, eps_max,
                     it_max):

    ndim = len(grid)
    eps = 1e9
    it_cnt = 0

    values = func(pars, gp, 0., args=args)[0]

    while eps > eps_max:

        it_cnt += 1
        values_old = values.copy()
        svalues = values.reshape(grid_shape)
        xe = xfromv(eval_linear(grid, svalues, values, xto.LINEAR))
        values = func(pars, gp, xe, args=args)[0]
        eps = np.linalg.norm(values - values_old)

        if it_cnt == it_max:
            break

    return values.reshape(grid_shape), it_cnt, eps
    def seriesgen(age,wave_length, W, beta_hat_ts, alpha_hat_ts,V_ushock_ts, Pi_ushock_ts,DBshock,\
        a_noadj, etas_noadj, H_adj, a_adj, c_adj, Xi_cov,Xi_copi,policy_VF):
        """ Returns a time series of one agent to age 
			in baseline year and age in baseline year + wave_len
		"""

        length = int(age + wave_length + 2)

        # generate sequences of shocks for this agent i
        # remeber start year is tzero.
        # we generate shocks such that TS_j[t] gives the value of
        # the shock at t

        TS_A, TS_A_1 = 0, 0
        TS_H, TS_H_1 = 0, 0
        TS_DC, TS_DC_1 = 0, 0
        TS_C, TS_C_1 = 0, 0
        TS_V, TS_V_1 = 0, 0
        TS_PI, TS_PI_1 = 0, 0
        TS_wage, TS_wage_1 = 0, 0
        TS_hinv, TS_hinv_1 = 0, 0
        adj_V, adj_V_1 = 0, 0
        adj_pi, adj_pi_1 = 0, 0
        P_h = np.zeros(length + 1)

        # generate sequence of house prices

        P_h[tzero] = 1 / ((1 + r_H)**(age - tzero))

        for t in np.arange(tzero, len(P_h) - 1):
            P_h[t + 1] = (1 + r_H) * P_h[t]

        # initialize continuous points

        TS_A = 1e-5
        TS_H = 1e-5
        TS_DC = 1e-5

        wave_data_14 = np.zeros(17)
        wave_data_10 = np.zeros(17)

        # generate time series of wage shocks, beta_hat and alpha_hat draws for this guy

        #DC_H= 	np.exp(r_h + lnrh_mc.simulate(ts_length = length)) # these need to be made deterministic
        #DC_L = 	np.exp(r_l + lnrl_mc.simulate(ts_length = length)) # these need to be made deterministic

        # get the initial value of the series and draw from account type

        #sigma_plan =.03
        #disc_exog_ind = int(np.where((np.where(W[int(tzero)]== E)[0] \
        #						== X_disc_exog[:,0]) \
        #					&   (X_disc_exog[:,1] == np.where(alpha_hat \
        #						 == alpha_hat_ts[int(tzero)])[0]) \
        #					& 	(X_disc_exog[:,2] == np.where(beta_hat\
        #						 == beta_hat_ts[int(tzero)])[0]))[0])

        E_ind = int(W[tzero])
        beta_ind = int(beta_hat_ts[tzero])
        alpha_ind = int(alpha_hat_ts[tzero])


        V_DC   =  eval_linear(X_cont_W, \
             policy_VF[1,E_ind,alpha_ind,beta_ind,:], \
             np.array([TS_A,TS_DC,TS_H, P_h[tzero]]))



        V_DB   =  eval_linear(X_cont_W, \
             policy_VF[0,E_ind,alpha_ind,beta_ind,:], \
             np.array([TS_A,TS_DC,TS_H, P_h[tzero]]))

        V_DC_scaled = ((V_DC - adj_p(tzero)) / sigma_plan) - max(
            ((V_DC - adj_p(tzero)) / sigma_plan), ((V_DB / sigma_plan)))
        V_DB_scaled = ((V_DB / sigma_plan)) - max(
            ((V_DC - adj_p(tzero)) / sigma_plan), ((V_DB / sigma_plan)))


        Prob_DC  = np.exp(V_DC_scaled)/(
            np.exp(V_DB_scaled) \
           +   np.exp(V_DC_scaled ) )

        account_ind = int(
            np.searchsorted(np.cumsum(np.array([1 - Prob_DC, Prob_DC])),
                            DBshock))

        for t in range(int(tzero), int(length) + 1):
            if t < R:
                #get the index for the labour shock
                E_ind = int(W[t])
                beta_ind = int(beta_hat_ts[t])
                alpha_ind = int(alpha_hat_ts[t])

                E_val = E[int(W[t])]
                beta_val = beta_hat[int(beta_hat_ts[t])]
                alpha_val = alpha_hat[int(alpha_hat_ts[t])]

                #get continuous state index
                points = np.array([TS_A,TS_DC\
                     ,TS_H, P_h[t]])

                #pull out the probability of voluntary contribution probability matrix for this cont state

                pi_ushock = Pi_ushock_ts[t]
                v_ushock = V_ushock_ts[t]
                args = (account_ind, E_ind, alpha_ind, beta_ind, pi_ushock,
                        v_ushock, Xi_cov, Xi_copi)

                V_ind, v, Pi_ind, pi = gen_VPi(points, t - tzero, *args)

                #calculate wage for agent
                TS_wage = y(t, E[E_ind])

                # total liquid wealth for non-adjuster
                wealth_no_adj       = TS_A*(1+r)\
                      + (1-v -v_S -v_E)*TS_wage

                # next period DC assets (before returns)
                # (recall domain of policy functions from def of eval_policy_W)
                # DC_prime is DC assets at the end of t, before returns into t+1

                DC_prime = TS_DC + (v + (v_S + v_E) * account_ind) * TS_wage

                h = TS_H * (1 - delta_housing)
                q = P_h[t]

                TS_DC_1    = (1+(1-pi)*r_l\
                      + pi*r_h )*DC_prime

                wealth_adj = wealth_no_adj + P_h[t] * h

                eta_func            =  etas_noadj[t-tzero][account_ind,\
                         E_ind,\
                         alpha_ind,\
                         beta_ind,\
                         Pi_ind,:]

                eta                 = eval_linear(X_cont_W,eta_func,\
                          np.array([wealth_no_adj,\
                          DC_prime,h,P_h[t]]),\
                          xto.NEAREST)

                if np.abs(eta) < 1:
                    a_noadjust_func     =  a_noadj[t-tzero][account_ind,\
                            E_ind,\
                            alpha_ind,\
                            beta_ind,\
                            Pi_ind,:]
                    h_prime = h
                    TS_A_1     = eval_linear(X_cont_W,a_noadjust_func,\
                           np.array([wealth_no_adj,DC_prime,h,q]),\
                           xto.NEAREST)
                    TS_C          = max(1e-10,wealth_no_adj\
                           - TS_A_1)
                    TS_H_1 = h

                else:
                    a_prime_adj_func = a_adj[t-tzero][account_ind,\
                            E_ind,\
                            alpha_ind,\
                            beta_ind,\
                            Pi_ind,:]
                    c_prime_adj_func = c_adj[t-tzero][account_ind,\
                            E_ind,\
                            alpha_ind,\
                            beta_ind,\
                            Pi_ind,:]

                    H_adj_func = H_adj[t-tzero][account_ind,\
                            E_ind,\
                            alpha_ind,\
                            beta_ind,\
                            Pi_ind,:]


                    TS_C           = max(eval_linear(X_QH_W,\
                           c_prime_adj_func,\
                           np.array([DC_prime,q,\
                           wealth_adj]),xto.NEAREST), 1E-20)

                    TS_H_1          = max(1e-20, eval_linear(X_QH_W,\
                            H_adj_func,\
                            np.array([DC_prime,q,\
                            wealth_adj]), xto.NEAREST))

                    TS_A_1          = max(1e-20, eval_linear(X_QH_W,\
                            a_prime_adj_func,\
                            np.array([DC_prime,q,\
                            wealth_adj]), xto.NEAREST))
                TS_hinv = TS_H_1 - TS_H
                TS_PI = pi
                TS_V = v

                # if t not terminal, iterate forward
                if t == age:
                    wave_data_10    =  np.array([account_ind,age, TS_A*norm,\
                          TS_H*norm, TS_DC*norm, TS_C*norm, \
                          TS_wage*norm, TS_V, TS_V*TS_wage*norm, TS_PI, \
                          int(TS_hinv>0), int(TS_PI>.7), int(TS_V>0), \
                          alpha_hat_ts[age], beta_hat_ts[age],adj_V, adj_pi])

                if t == age + wave_length:
                    # we denote the age at wave_14 by thier age at 10 so they go in 2010 bucket
                    age_wave_10 = age
                    age14 = age + wave_length
                    wave_data_14    = np.array([account_ind,age_wave_10, TS_A*norm,\
                           TS_H*norm, TS_DC*norm, TS_C*norm, \
                           TS_wage*norm, TS_V,TS_V*TS_wage*norm, TS_PI, \
                           int(TS_hinv>0), int(TS_PI>.7), int(TS_V>0), \
                           alpha_hat_ts[age14], beta_hat_ts[age14],adj_V, adj_pi])

                TS_A = TS_A_1
                TS_H = TS_H_1
                TS_DC = TS_DC_1

        return wave_data_10, wave_data_14
예제 #22
0
파일: v11.py 프로젝트: dylanmoonhou/LCM
def core(i, t, coords, policy_C, policy_D, policy_S, policy_V):
    # translate state var and set up choice var
    X0, K0, H0, Ph0, Ps0, N0, A0 = grid_X[coords[0]], grid_K[
        coords[1]], grid_H[coords[2]], grid_P[coords[3]], grid_P[
            coords[4]], grid_N[coords[5]], grid_A[coords[6]]
    if (X0 == grid_X[0]) | (
        (t >= 15) &
        (A0 == 0)):  # after 2035, there will be sure SSB adjustment
        return (1, 1, 1, utility(X0, N0))
    K0 = X0 * K0  # K from % to $
    Ph0 = Ph0 * ((1 - (eta * eta)**t) / (1 - eta * eta))**0.5
    Ps0 = Ps0 * ((1 - (eta * eta)**t) / (1 - eta * eta))**0.5
    if (t >= T - 3) | (t == 71 - 65):
        if K0 == 0:
            grid_D = np.array([0])
        else:
            grid_D = np.arange(21) / 20
            grid_D = np.extract(grid_D >= rmd_pct[t], grid_D)
        grid_C = np.arange(1, 20) / 20
        grid_S = np.arange(21) / 20
    else:
        C_guess = policy_C[coords]
        D_guess = policy_D[coords]
        S_guess = policy_S[coords]
        grid_C = np.arange(max(.01, C_guess - .05), min(C_guess + .05, .99),
                           .01)
        if K0 == 0:
            grid_D = np.array([0])
        else:
            grid_D = np.arange(max(rmd_pct[t], D_guess - .05),
                               min(D_guess + .05, 1.0),
                               .01)  # not optimal to withdraw less than RMD
        grid_S = np.arange(max(0, S_guess - .05), min(S_guess + .05, 1.0), .01)
    # SHOCKS
    re, perm_h, tran_h, perm_s, tran_s, ft = grid_re, grid_perm, grid_tran, grid_perm, grid_tran, grid_ft[
        t]
    wgt_re, wgt_perm, wgt_tran = GQ_wgt, GQ_wgt, GQ_wgt
    wgt_ft = [1 - p_ft[t], p_ft[t]]
    if N0 == 1:
        sp, wgt_sp = np.array([0]), [1]
    elif N0 == 2:
        sp, wgt_sp = np.array([0, 1]), [1 - p_s[t], p_s[t]]
    if A0 == 0:
        adj, wgt_adj = np.array([0, 1]), [1 - p_SSadj[t], p_SSadj[t]]
    elif A0 == 1:
        adj, wgt_adj = np.array([1]), [1]
    # evaluate at mesh grid for shocks
    mesh_C, mesh_D, mesh_S, mesh_re, mesh_perm_h, mesh_tran_h, mesh_perm_s, mesh_tran_s, mesh_ft, mesh_sp, mesh_adj = np.meshgrid(
        grid_C,
        grid_D,
        grid_S,
        re,
        perm_h,
        tran_h,
        perm_s,
        tran_s,
        ft,
        sp,
        adj,
        indexing='ij')
    mesh_shape = [
        grid_C.shape[0], grid_D.shape[0], grid_S.shape[0], re.shape[0],
        perm_h.shape[0], tran_h.shape[0], perm_s.shape[0], tran_s.shape[0],
        ft.shape[0], sp.shape[0], adj.shape[0]
    ]
    mesh_Ph1 = Ph0 * eta + mesh_perm_h
    mesh_Ps1 = Ps0 * eta + mesh_perm_s
    mesh_me_h = np.exp(me_mu_h[t] + me_sigma_h[t] * (mesh_Ph1 + mesh_tran_h))
    mesh_me_s = np.exp(me_mu_s[t] + me_sigma_s[t] * (mesh_Ps1 + mesh_tran_s))
    mesh_L0 = X0 - K0 + (K0 * mesh_D) * (
        1 - tax
    )  # comprehensive tax rule of SSB later (tax up to 50% or 85% of SSB based on combo inc)
    mesh_C = mesh_L0 * mesh_C
    mesh_L1 = mesh_L0 - mesh_C
    mesh_L1 *= (1 + (mesh_S * mesh_re + (1 - mesh_S) * rf - 1) * (1 - tax))
    mesh_L1 += (-H_price[t + 1] * rent * (1 - H0) - mesh_me_h -
                mesh_me_s * N0 - mesh_ft + (Y_h + Y_s * mesh_sp) *
                (1 - mesh_adj * SSadj))
    mesh_K1 = K0 * (1 - mesh_D) * (K_share[t] * mesh_re +
                                   (1 - K_share[t]) * rf)
    # if L1 < L_min (medicaid limit), withdraw K to fill; if not enough and own home, sell home; if still not enough, claim medicaid
    mesh_DD = np.clip(L_min - mesh_L1, 0, mesh_K1)
    mesh_K1 = mesh_K1 - mesh_DD
    mesh_L1 = mesh_L1 + mesh_DD
    mesh_H1 = np.ones_like(mesh_L1) * H0
    if H0 == 1:
        mesh_sellhome = mesh_L1 < L_min
        mesh_sellhome = mesh_sellhome.astype(int)
        mesh_L1 += H_price[t + 1] * mesh_sellhome * (1 - tax)
        mesh_H1 = mesh_H1 - mesh_sellhome
    # new state var grid at next period
    mesh_X1 = mesh_L1 + mesh_K1
    mesh_X1 = np.clip(mesh_X1, grid_X[0], grid_X[-1])
    mesh_K1 = np.clip(mesh_K1 / mesh_X1, grid_K[0], grid_K[-1])
    grid_P1 = grid_P * ((1 - (eta * eta)**(t + 1)) / (1 - eta * eta))**0.5
    mesh_Ph1 = np.clip(mesh_Ph1, grid_P1[0], grid_P1[-1])
    mesh_Ps1 = np.clip(mesh_Ps1, grid_P1[0], grid_P1[-1])
    mesh_N1 = mesh_sp + 1
    mesh_A1 = mesh_adj

    grid = CGrid(grid_X, grid_K, grid_H, grid_P1, grid_P1, grid_N, grid_A)
    values = policy_V
    points = np.stack([
        mesh_X1.ravel(),
        mesh_K1.ravel(),
        mesh_H1.ravel(),
        mesh_Ph1.ravel(),
        mesh_Ps1.ravel(),
        mesh_N1.ravel(),
        mesh_A1.ravel()
    ],
                      axis=-1)
    mesh_EV1 = eval_linear(grid, values, points).reshape(mesh_shape)

    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_adj)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_sp)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_ft)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_tran)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_perm)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_tran)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_perm)
    mesh_EV1 = np.average(mesh_EV1, axis=(-1), weights=wgt_re)
    mesh_C = mesh_C[:, :, :, 0, 0, 0, 0, 0, 0, 0, 0]
    mesh_V0 = utility(mesh_C, N0)
    mesh_V = mesh_V0 + beta * p_h[t] * mesh_EV1
    coord_C, coord_D, coord_S = np.unravel_index(np.nanargmax(mesh_V),
                                                 mesh_V.shape)
    [C_max, D_max, S_max] = grid_C[coord_C], grid_D[coord_D], grid_S[coord_S]
    V_max = mesh_V[coord_C, coord_D, coord_S]
    return (i, C_max, D_max, S_max, V_max)
예제 #23
0
    def evaluate(self, v):

        return eval_linear(self._grid, self._values, v)
예제 #24
0
 def wrapper(xs, values, points, out):
     """Calls eval_linear()."""
     eval_linear((xs, ), values, points, out)
예제 #25
0
    def pfi_t_func_wrap(state):

        newstate = eval_linear(grid, pfunc, state, xto.LINEAR)

        return newstate
예제 #26
0
        def __call__(self, v):

            return eval_linear(self._grid, self._values, v)