Source code for ogcore.household

"""
------------------------------------------------------------------------
Household functions.
------------------------------------------------------------------------
"""

# Packages
import numpy as np
from ogcore import tax, utils, pensions
import logging

logger = logging.getLogger(__name__)

"""
------------------------------------------------------------------------
    Functions
------------------------------------------------------------------------
"""


def _get_e_long(p):
    """Return ``p.e`` extended for the TPI transition window.

    ``e_long`` is a pure function of ``p.e`` / ``p.S`` / ``p.J`` -- none of
    which change during a solve -- so it is built once and cached on the
    parameters object. ``FOC_savings`` and ``FOC_labor`` previously rebuilt
    this array on every call, which profiling identified as the single most
    expensive operation in a TPI run.
    """
    e_long = getattr(p, "_e_long_cache", None)
    if e_long is None:
        e_long = np.concatenate(
            (p.e, np.tile(p.e[-1, :, :].reshape(1, p.S, p.J), (p.S, 1, 1))),
            axis=0,
        )
        p._e_long_cache = e_long
    return e_long


[docs] def marg_ut_cons(c, sigma): r""" Compute the marginal utility of consumption. .. math:: MU_{c} = c^{-\sigma} Args: c (array_like): household consumption sigma (scalar): coefficient of relative risk aversion Returns: output (array_like): marginal utility of consumption """ if np.ndim(c) == 0: c = np.array([c]) epsilon = 0.003 cvec_cnstr = c < epsilon MU_c = np.zeros(c.shape) MU_c[~cvec_cnstr] = c[~cvec_cnstr] ** (-sigma) b2 = (-sigma * (epsilon ** (-sigma - 1))) / 2 b1 = (epsilon ** (-sigma)) - 2 * b2 * epsilon MU_c[cvec_cnstr] = 2 * b2 * c[cvec_cnstr] + b1 output = MU_c output = np.squeeze(output) return output
[docs] def marg_ut_labor(n, chi_n, p): r""" Compute the marginal disutility of labor. .. math:: MDU_{l} = \chi^n_{s}\biggl(\frac{b}{\tilde{l}}\biggr) \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^{\upsilon-1} \Biggl[1-\biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^\upsilon \Biggr]^{\frac{1-\upsilon}{\upsilon}} Args: n (array_like): household labor supply chi_n (array_like): utility weights on disutility of labor p (OG-Core Specifications object): model parameters Returns: output (array_like): marginal disutility of labor supply """ nvec = n if np.ndim(nvec) == 0: nvec = np.array([nvec]) eps_low = 0.000001 eps_high = p.ltilde - 0.000001 nvec_low = nvec < eps_low nvec_high = nvec > eps_high nvec_uncstr = np.logical_and(~nvec_low, ~nvec_high) MDU_n = np.zeros(nvec.shape) MDU_n[nvec_uncstr] = ( (p.b_ellipse / p.ltilde) * ((nvec[nvec_uncstr] / p.ltilde) ** (p.upsilon - 1)) * ( (1 - ((nvec[nvec_uncstr] / p.ltilde) ** p.upsilon)) ** ((1 - p.upsilon) / p.upsilon) ) ) b2 = ( 0.5 * p.b_ellipse * (p.ltilde ** (-p.upsilon)) * (p.upsilon - 1) * (eps_low ** (p.upsilon - 2)) * ( (1 - ((eps_low / p.ltilde) ** p.upsilon)) ** ((1 - p.upsilon) / p.upsilon) ) * ( 1 + ((eps_low / p.ltilde) ** p.upsilon) * ((1 - ((eps_low / p.ltilde) ** p.upsilon)) ** (-1)) ) ) b1 = (p.b_ellipse / p.ltilde) * ( (eps_low / p.ltilde) ** (p.upsilon - 1) ) * ( (1 - ((eps_low / p.ltilde) ** p.upsilon)) ** ((1 - p.upsilon) / p.upsilon) ) - (2 * b2 * eps_low) MDU_n[nvec_low] = 2 * b2 * nvec[nvec_low] + b1 d2 = ( 0.5 * p.b_ellipse * (p.ltilde ** (-p.upsilon)) * (p.upsilon - 1) * (eps_high ** (p.upsilon - 2)) * ( (1 - ((eps_high / p.ltilde) ** p.upsilon)) ** ((1 - p.upsilon) / p.upsilon) ) * ( 1 + ((eps_high / p.ltilde) ** p.upsilon) * ((1 - ((eps_high / p.ltilde) ** p.upsilon)) ** (-1)) ) ) d1 = (p.b_ellipse / p.ltilde) * ( (eps_high / p.ltilde) ** (p.upsilon - 1) ) * ( (1 - ((eps_high / p.ltilde) ** p.upsilon)) ** ((1 - p.upsilon) / p.upsilon) ) - (2 * d2 * eps_high) MDU_n[nvec_high] = 2 * d2 * nvec[nvec_high] + d1 output = MDU_n * np.squeeze(chi_n) output = np.squeeze(output) return output
[docs] def get_bq(BQ, j, p, method): r""" Calculate bequests to each household. .. math:: \hat{bq}_{j,s,t} = \zeta_{j,s} \frac{\hat{BQ}_{t}}{\lambda_{j}\hat{\omega}_{s,t}} \quad\forall j,s,t Args: BQ (array_like): aggregate bequests j (int): index of lifetime ability group p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' Returns: bq (array_like): bequests received by each household """ if p.use_zeta: if j is not None: if method == "SS": bq = (p.zeta[:, j] * BQ) / p.omega_SS[:, j] else: len_T = BQ.shape[0] bq = ( np.reshape(p.zeta[:, j], (1, p.S)) * BQ.reshape((len_T, 1)) ) / p.omega[:len_T, :, j] else: if method == "SS": bq = (p.zeta * BQ) / p.omega_SS else: len_T = BQ.shape[0] bq = ( np.reshape(p.zeta, (1, p.S, p.J)) * utils.to_timepath_shape(BQ) ) / p.omega[:len_T, :, :] else: # Divide each group's bequest pool by its actual population share # rather than its birth share (lambdas): with demographic gradients # across income groups (PR #1165), survivorship differs by group and # the two are no longer equal. With common demographics they # coincide, so results are unchanged in that case. if j is not None: if method == "SS": pop_j = p.omega_SS[:, j].sum() bq = np.tile(BQ[j], p.S) / pop_j if method == "TPI": len_T = BQ.shape[0] pop_j = p.omega[:len_T, :, j].sum(axis=1) bq = np.tile( np.reshape(BQ[:, j] / pop_j, (len_T, 1)), (1, p.S) ) else: if method == "SS": pop = p.omega_SS.sum(axis=0) BQ_per = BQ / pop bq = np.tile(np.reshape(BQ_per, (1, p.J)), (p.S, 1)) if method == "TPI": len_T = BQ.shape[0] pop = p.omega[:len_T, :, :].sum(axis=1) BQ_per = BQ / pop bq = np.tile(np.reshape(BQ_per, (len_T, 1, p.J)), (1, p.S, 1)) return bq
[docs] def get_tr(TR, j, p, method): r""" Calculate transfers to each household. .. math:: \hat{tr}_{j,s,t} = \zeta_{j,s} \frac{\hat{TR}_{t}}{\lambda_{j}\hat{\omega}_{s,t}} \quad\forall j,s,t Args: TR (array_like): aggregate transfers j (int): index of lifetime ability group p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' Returns: tr (array_like): transfers received by household """ if j is not None: if method == "SS": tr = (p.eta[-1, :, j] * TR) / p.omega_SS[:, j] else: len_T = TR.shape[0] tr = (p.eta[:len_T, :, j] * TR.reshape((len_T, 1))) / ( p.omega[:len_T, :, j] ) else: if method == "SS": tr = (p.eta[-1, :, :] * TR) / p.omega_SS else: len_T = TR.shape[0] tr = (p.eta[:len_T, :, :] * utils.to_timepath_shape(TR)) / ( p.omega[:len_T, :, :] ) return tr
[docs] def get_rm(RM, j, p, method): r""" Calculate remittances to each household. .. math:: \hat{rm}_{j,s,t} = \eta_{RM,j,s,t} \frac{\hat{RM}_{t}}{\lambda_{j}\hat{\omega}_{s,t}} \quad\forall j,s,t Args: RM (array_like): aggregate remittances j (int): index of lifetime ability group p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' Returns: rm (array_like): remittances received by household """ if j is not None: if method == "SS": rm = (p.eta_RM[-1, :, j] * RM) / p.omega_SS[:, j] else: len_T = RM.shape[0] rm = (p.eta_RM[:len_T, :, j] * RM.reshape((len_T, 1))) / ( p.omega[:len_T, :, j] ) else: if method == "SS": rm = (p.eta_RM[-1, :, :] * RM) / p.omega_SS else: len_T = RM.shape[0] rm = (p.eta_RM[:len_T, :, :] * utils.to_timepath_shape(RM)) / ( p.omega[:len_T, :, :] ) return rm
[docs] def get_cons( r_p, w, p_tilde, p_i, b, b_splus1, n, bq, rm, net_tax, e, tau_c, p, method="SS", ): r""" Calculate household composite consumption. .. math:: \hat{c}_{j,s,t} &= \biggl[(1 + r_{p,t})\hat{b}_{j,s,t} + \hat{w}_t e_{j,s}n_{j,s,t} + \hat{bq}_{j,s,t} + \hat{rm}_{j,s,t} + \hat{tr}_{j,s,t} + \hat{ubi}_{j,s,t} + \hat{pension}_{j,s,t} - \hat{tax}_{j,s,t} \\ &\qquad - \sum_{i=1}^I\left(1 + \tau^c_{i,t}\right) p_{i,t}\hat{c}_{min,i} - e^{g_y}\hat{b}_{j,s+1,t+1}\biggr] / p_t \\ &\qquad\qquad\forall j,t \quad\text{and}\quad E+1\leq s\leq E+S \quad\text{where}\quad \hat{b}_{j,E+1,t}=0 Args: r_p (array_like): the real interest rate w (array_like): the real wage rate p_tilde (array_like): the ratio of real GDP to nominal GDP p_i (Numpy array): prices for consumption good i b (Numpy array): household savings b_splus1 (Numpy array): household savings one period ahead n (Numpy array): household labor supply bq (Numpy array): household bequests received rm (Numpy array): household remittances received net_tax (Numpy array): household net taxes paid e (Numpy array): effective labor units tau_c (Numpy array): consumption tax rates p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' Returns: cons (Numpy array): household consumption """ if method == "SS": min_cons_expenditure = np.sum((1 + tau_c) * p_i * p.c_min) elif method == "TPI_scalar": min_cons_expenditure = np.sum((1 + tau_c) * p_i * p.c_min) else: # TPI case min_cons_expenditure = np.sum( (1 + tau_c) * p_i * p.c_min.reshape((1, p.I)), axis=1 ) length = r_p.shape[0] # reshape if needed for broadcasting n_dims = np.ndim(bq) if n_dims == 1: min_cons_expenditure = min_cons_expenditure.reshape((length,)) elif n_dims == 2: min_cons_expenditure = min_cons_expenditure.reshape((length, 1)) else: min_cons_expenditure = min_cons_expenditure.reshape((length, 1, 1)) cons = ( (1 + r_p) * b + w * e * n + bq + rm - net_tax - b_splus1 * np.exp(p.g_y) - min_cons_expenditure ) / p_tilde return cons
[docs] def get_ci(c_s, p_i, p_tilde, tau_c, alpha_c, c_min, method="SS"): r""" Compute consumption of good i given amount of composite consumption and prices. .. math:: c_{i,j,s,t} = \frac{c_{s,j,t}}{\alpha_{i,j}p_{i,j}} Args: c_s (array_like): composite consumption p_i (array_like): prices for consumption good i p_tilde (array_like): composite good price tau_c (array_like): consumption tax rate alpha_c (array_like): consumption share parameters c_min (array_like): minimum consumption levels for each good i method (str): adjusts calculation dimensions based on 'SS' or 'TPI' Returns: c_si (array_like): consumption of good i """ if method == "SS": I = alpha_c.shape[0] # noqa: E741 S = c_s.shape[0] J = c_s.shape[1] tau_c = tau_c.reshape(I, 1, 1) alpha_c = alpha_c.reshape(I, 1, 1) c_min = c_min.reshape(I, 1, 1) p_tilde.reshape(1, 1, 1) p_i = p_i.reshape(I, 1, 1) c_s = c_s.reshape(1, S, J) c_si = alpha_c * (((1 + tau_c) * p_i) / p_tilde) ** (-1) * c_s + c_min else: # Time path case I = alpha_c.shape[0] # noqa: E741 T = p_i.shape[0] S = c_s.shape[1] J = c_s.shape[2] tau_c = tau_c.reshape(T, I, 1, 1) alpha_c = alpha_c.reshape(1, I, 1, 1) c_min = c_min.reshape(1, I, 1, 1) p_tilde = p_tilde.reshape(T, 1, 1, 1) p_i = p_i.reshape(T, I, 1, 1) c_s = c_s.reshape(T, 1, S, J) c_si = alpha_c * (((1 + tau_c) * p_i) / p_tilde) ** (-1) * c_s + c_min return c_si
[docs] def fdc_active(p): """ Whether the funded defined contribution (FDC) pillar is on, that is, whether any cohort pays a positive contribution rate ``fdc_tau``. Args: p (OG-Core Specifications object): model parameters Returns: bool: True if any element of ``fdc_tau`` is positive """ # Specifications objects pickled before fdc_tau existed have none return bool(np.any(np.asarray(getattr(p, "fdc_tau", 0.0)) > 0))
[docs] def get_fdc(r_p, w, n, e, j, p, method, t=None): """ Funded defined contribution accounts of the households whose labor supply is ``n``, or None when the FDC pillar is off. In the steady state, ``n`` covers a whole lifetime (length S, or S x J for all income groups). On the time path ('TPI' or 'TPI_scalar'), ``n`` covers the remaining lifetime of one cohort of income group j that is age S - len(n) in period t, and ``r_p`` and ``w`` are the paths over those periods. A cohort alive before the time path begins starts from the FDC claims of its age in ``p.fdc_claims_preTP`` (set by ``TPI.get_initial_SS_values``), credited with the period-0 FDC return r_fdc = r_p - r_fdc_wedge. Args: r_p (scalar or Numpy array): return on the household investment portfolio; the accounts earn this less ``r_fdc_wedge`` w (scalar or Numpy array): real wage rate n (Numpy array): labor supply e (Numpy array): effective labor units, shaped like ``n`` j (int): index of lifetime income group, None if all groups (steady state only) p (OG-Core Specifications object): model parameters method (str): 'SS', 'TPI', or 'TPI_scalar' t (int): on the time path, the model period of the first element of ``n`` (None means period 0) Returns: fdc (pensions.FDCLifetime or None): the accounts by age for the ages in ``n`` (the field R is the cohort's retirement age) """ if not fdc_active(p): return None if method == "SS": r_p = float(np.squeeze(r_p)) w = float(np.squeeze(w)) if j is not None: return pensions.fdc_lifetime(w, e, n, r_p, None, j, p) return pensions.fdc_ss(r_p, w, e, n, p) if j is None or np.ndim(n) > 1: raise NotImplementedError( "On the time path, FDC accounts are computed one cohort of " "one income group at a time" ) S = p.S n = np.atleast_1d(np.asarray(n, dtype=float)).ravel() L = n.shape[0] a0 = S - L t = 0 if t is None else int(t) e = np.atleast_1d(np.asarray(e, dtype=float)).ravel()[-L:] r_p = np.atleast_1d(np.asarray(r_p, dtype=float)).ravel()[:L] w = np.atleast_1d(np.asarray(w, dtype=float)).ravel()[:L] def pad(x): full = np.full(S, x[0]) full[a0:] = x return full n_full = np.zeros(S) n_full[a0:] = n e_full = np.zeros(S) e_full[a0:] = e A0 = 0.0 if a0 > 0: claims0 = getattr(p, "fdc_claims_preTP", None) if claims0 is not None: # balances carried in earn the FDC return of age a0 in # period t, r_fdc = r_p - r_fdc_wedge, as in pensions.fdc_tpi wedge_arr = pensions.fdc_wedge_path(p) wedge0 = wedge_arr[min(t, wedge_arr.shape[0] - 1), a0] A0 = (1.0 + r_p[0] - wedge0) * claims0[a0 - 1, j] acct = pensions.fdc_lifetime( pad(w), e_full, n_full, pad(r_p), t - a0, j, p, a0=a0, A0=A0, by_age=True, ) return pensions.FDCLifetime(*[x[a0:] for x in acct[:-1]], acct.R)
[docs] def fdc_net_flow(fdc): r""" Net payment of households into their funded defined contribution accounts, the contribution less the annuity benefit, $C_{j,s,t} - P_{j,s,t}$. It enters the budget constraint alongside net taxes but is neither government revenue nor a government outlay. Args: fdc (pensions.FDCLifetime or None): the accounts, None when the pillar is off Returns: net (Numpy array or scalar): contribution less benefit, or 0.0 when the pillar is off """ if fdc is None: return 0.0 return fdc.contrib - fdc.benefit
[docs] def fdc_labor_wedge(cons, p_tilde, fdc, rho, beta, p): r""" Terms the funded defined contribution (FDC) pillar adds to the first order condition for labor supply. An extra unit of labor at working age s raises the contribution by $\partial C_s / \partial n_s$, which lowers consumption at s, and raises the annuity at every age u from the retirement age R on by $\partial C_s / \partial n_s \, m_s e^{-g_y(u - R)}$, where $m_s$ is the benefit at R bought by a unit contributed at s. The second effect is valued with the household's own discounting of future marginal utility: .. math:: -\frac{u'(c_s)}{\tilde{p}_s}\frac{\partial C_s}{\partial n_s} + \frac{\partial C_s}{\partial n_s}m_s\sum_{u=R}^{S-1} \beta^{u-s}\prod_{i=s}^{u-1}(1 - \rho_i)e^{(1-\sigma)g_y(u-s)} \frac{u'(c_u)}{\tilde{p}_u}e^{-g_y(u-R)} The factor $e^{(1-\sigma)g_y}$ per period is the weight of detrended utility in the lifetime objective. (The savings Euler equation shows $e^{-\sigma g_y}$ instead because next period's savings enter this period's budget multiplied by $e^{g_y}$.) The second (accrual) term is included only when ``p.pension_FOC_linkage`` is true; otherwise households choose labor as if the annuity did not depend on their contributions. The first term is always included. Contributions of households that die before R go to bequests, which the household does not value here (its bequest motive is over private savings only). The arrays may cover the whole life (ages 0 to S - 1) or, on the time path, the remaining ages S - L to S - 1 of a cohort alive when the path begins. Args: cons (Numpy array): consumption by age, length S or S x J p_tilde (scalar or Numpy array): composite good price fdc (pensions.FDCLifetime): the accounts, shaped like ``cons`` rho (Numpy array): mortality rates, shaped like ``cons`` beta (scalar or Numpy array): discount factor (length J when ``cons`` is S x J) p (OG-Core Specifications object): model parameters Returns: wedge (Numpy array): term to add to the labor FOC error at each age, shaped like ``cons`` """ mu = marg_ut_cons(cons, p.sigma) / p_tilde wedge = -mu * fdc.dcontrib_dn # the arrays may cover only the remaining ages a0, ..., S - 1 of a # cohort alive when the time path begins L = np.shape(cons)[0] a0 = p.S - L R = fdc.R - a0 # Specifications objects pickled before pension_FOC_linkage existed # have none; they were solved with the accrual term linkage = getattr(p, "pension_FOC_linkage", True) if not linkage or fdc.R >= p.S or not np.any(fdc.benefit_per_contrib): return wedge rho = np.asarray(rho, dtype=float).reshape(np.shape(cons)) ages = np.arange(L).reshape((L,) + (1,) * (rho.ndim - 1)) surv = np.concatenate( (np.ones((1,) + rho.shape[1:]), np.cumprod(1.0 - rho[:-1], axis=0)), axis=0, ) # discount from age 0 to age u, so the discount from s to u is # Q[u] / Q[s] Q = ( np.asarray(beta, dtype=float) ** ages * surv * np.exp((1.0 - p.sigma) * p.g_y * ages) ) pay = np.exp(-p.g_y * (ages[R:] - R)) value_at_0 = (Q[R:] * mu[R:] * pay).sum(axis=0) accrual = fdc.dcontrib_dn * fdc.benefit_per_contrib * value_at_0 / Q return wedge + accrual
[docs] def FOC_savings( r, w, p_tilde, p_i, b, b_splus1, n, bq, rm, factor, tr, ubi, theta, rho, etr_params, mtry_params, t, j, p, method, ndc_rates=None, net_tax=None, ): r""" Computes Euler errors for the FOC for savings in the steady state. This function is usually looped through over J, so it does one lifetime income group at a time. .. math:: \frac{c_{j,s,t}^{-\sigma}}{\tilde{p}_{t}} = e^{-\sigma g_y} \biggl[\chi^b_j\rho_s(b_{j,s+1,t+1})^{-\sigma} + \beta_j\bigl(1 - \rho_s\bigr)\Bigl(\frac{1 + r_{t+1} \bigl[1 - \tau^{mtry}_{s+1,t+1}\bigr]}{\tilde{p}_{t+1}}\Bigr) (c_{j,s+1,t+1})^{-\sigma}\biggr] Args: r (array_like): the real interest rate w (array_like): the real wage rate p_tilde (array_like): composite good price p_i (Numpy array): prices for consumption good i b (Numpy array): household savings b_splus1 (Numpy array): household savings one period ahead b_splus2 (Numpy array): household savings two periods ahead n (Numpy array): household labor supply bq (Numpy array): household bequests received rm (Numpy array): household remittances received factor (scalar): scaling factor converting model units to dollars tr (Numpy array): government transfers to household ubi (Numpy array): universal basic income payment theta (Numpy array): social security replacement rate for each lifetime income group rho (Numpy array): mortality rates etr_params (list): parameters of the effective tax rate functions mtry_params (list): parameters of the marginal tax rate on capital income functions t (int): model period j (int): index of ability type p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' ndc_rates (NDCRates): calendar paths of the NDC credited and discount rates (``pensions.ndc_rates_path``); None for the steady-state rates net_tax (Numpy array or None): household net taxes, if the caller has already computed them for these arguments (as ``tax.net_taxes`` would); None to compute them here Returns: euler (Numpy array): Euler error from FOC for savings """ if j is not None: chi_b = p.chi_b[j] beta = p.beta[j] if method == "SS": tax_noncompliance = p.capital_income_tax_noncompliance_rate[-1, j] income_tax_filer = p.income_tax_filer[-1, j] wealth_tax_filer = p.wealth_tax_filer[-1, j] e = np.squeeze(p.e[-1, :, j]) elif method == "TPI_scalar": tax_noncompliance = p.capital_income_tax_noncompliance_rate[0, j] income_tax_filer = p.income_tax_filer[0, j] wealth_tax_filer = p.wealth_tax_filer[0, j] e = np.squeeze(p.e[0, :, j]) else: length = r.shape[0] tax_noncompliance = p.capital_income_tax_noncompliance_rate[ t : t + length, j ] income_tax_filer = p.income_tax_filer[t : t + length, j] wealth_tax_filer = p.wealth_tax_filer[t : t + length, j] e_long = _get_e_long(p) e = np.diag(e_long[t : t + p.S, :, j], max(p.S - length, 0)) else: chi_b = p.chi_b beta = p.beta if method == "SS": tax_noncompliance = p.capital_income_tax_noncompliance_rate[-1, :] income_tax_filer = p.income_tax_filer[-1, :] wealth_tax_filer = p.wealth_tax_filer[-1, :] e = np.squeeze(p.e[-1, :, :]) elif method == "TPI_scalar": tax_noncompliance = p.capital_income_tax_noncompliance_rate[0, :] income_tax_filer = p.income_tax_filer[0, :] wealth_tax_filer = p.wealth_tax_filer[0, :] e = np.squeeze(p.e[0, :, :]) else: length = r.shape[0] tax_noncompliance = p.capital_income_tax_noncompliance_rate[ t : t + length, : ] income_tax_filer = p.income_tax_filer[t : t + length, :] wealth_tax_filer = p.wealth_tax_filer[t : t + length, :] e_long = _get_e_long(p) e = np.diag(e_long[t : t + p.S, :, :], max(p.S - length, 0)) e = np.squeeze(e) if method == "SS": h_wealth = p.h_wealth[-1] m_wealth = p.m_wealth[-1] p_wealth = p.p_wealth[-1] p_tilde = np.ones_like(rho) * p_tilde tau_c = p.tau_c[-1, :] elif method == "TPI_scalar": h_wealth = p.h_wealth[0] m_wealth = p.m_wealth[0] p_wealth = p.p_wealth[0] tau_c = p.tau_c[0, :] else: h_wealth = p.h_wealth[t : t + length] m_wealth = p.m_wealth[t : t + length] p_wealth = p.p_wealth[t : t + length] tau_c = p.tau_c[t : t + length, :] if net_tax is None: taxes = tax.net_taxes( r, w, b, n, bq, factor, tr, ubi, theta, t, j, False, method, e, etr_params, p, ndc_rates, ) else: taxes = net_tax fdc = get_fdc(r, w, n, e, j, p, method, t) cons = get_cons( r, w, p_tilde, p_i, b, b_splus1, n, bq, rm, taxes + fdc_net_flow(fdc), e, tau_c, p, method, ) deriv = ( (1 + r) - ( r * tax.MTR_income( r, w, b, n, factor, True, e, etr_params, mtry_params, tax_noncompliance, income_tax_filer, p, ) ) - tax.MTR_wealth(b, h_wealth, m_wealth, p_wealth, wealth_tax_filer) ) savings_ut = ( rho * np.exp(-p.sigma * p.g_y) * chi_b * b_splus1 ** (-p.sigma) ) euler_error = np.zeros_like(n) if n.shape[0] > 1: euler_error[:-1] = ( marg_ut_cons(cons[:-1], p.sigma) * (1 / p_tilde[:-1]) - beta * (1 - rho[:-1]) * deriv[1:] * marg_ut_cons(cons[1:], p.sigma) * (1 / p_tilde[1:]) * np.exp(-p.sigma * p.g_y) - savings_ut[:-1] ) euler_error[-1] = ( marg_ut_cons(cons[-1], p.sigma) * (1 / p_tilde[-1]) - savings_ut[-1] ) else: euler_error[-1] = ( marg_ut_cons(cons[-1], p.sigma) * (1 / p_tilde[-1]) - savings_ut[-1] ) return euler_error
[docs] def FOC_labor( r, w, p_tilde, p_i, b, b_splus1, n, bq, rm, factor, tr, ubi, theta, chi_n, etr_params, mtrx_params, t, j, p, method, ndc_rates=None, net_tax=None, ): r""" Computes errors for the FOC for labor supply in the steady state. This function is usually looped through over J, so it does one lifetime income group at a time. .. math:: w_t e_{j,s}\bigl(1 - \tau^{mtrx}_{s,t}\bigr) \frac{(c_{j,s,t})^{-\sigma}}{ \tilde{p}_{t}} = \chi^n_{s} \biggl(\frac{b}{\tilde{l}}\biggr)\biggl(\frac{n_{j,s,t}} {\tilde{l}}\biggr)^{\upsilon-1}\Biggl[1 - \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^\upsilon\Biggr] ^{\frac{1-\upsilon}{\upsilon}} Args: r (array_like): the real interest rate w (array_like): the real wage rate p_tilde (array_like): composite good price p_i (Numpy array): prices for consumption good i b (Numpy array): household savings b_splus1 (Numpy array): household savings one period ahead n (Numpy array): household labor supply bq (Numpy array): household bequests received rm (Numpy array): household bequests received factor (scalar): scaling factor converting model units to dollars tr (Numpy array): government transfers to household ubi (Numpy array): universal basic income payment theta (Numpy array): social security replacement rate for each lifetime income group chi_n (Numpy array): utility weight on the disutility of labor supply e (Numpy array): effective labor units etr_params (list): parameters of the effective tax rate functions mtrx_params (list): parameters of the marginal tax rate on labor income functions t (int): model period j (int): index of ability type p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' ndc_rates (NDCRates): calendar paths of the NDC credited and discount rates (``pensions.ndc_rates_path``); None for the steady-state rates net_tax (Numpy array or None): household net taxes, if the caller has already computed them for these arguments (as ``tax.net_taxes`` would); None to compute them here Returns: FOC_error (Numpy array): error from FOC for labor supply """ if method == "SS": tau_c = p.tau_c[-1, :] elif method == "TPI_scalar": # for 1st donut ring only tau_c = p.tau_c[0, :] else: length = r.shape[0] tau_c = p.tau_c[t : t + length, :] if j is not None: if method == "SS": tax_noncompliance = p.labor_income_tax_noncompliance_rate[-1, j] income_tax_filer = p.income_tax_filer[-1, j] tau_payroll = p.tau_payroll[-1, j] e = np.squeeze(p.e[-1, :, j]) elif method == "TPI_scalar": tax_noncompliance = p.labor_income_tax_noncompliance_rate[0, j] income_tax_filer = p.income_tax_filer[0, j] tau_payroll = p.tau_payroll[0, j] e = np.squeeze(p.e[0, -1, j]) else: tax_noncompliance = p.labor_income_tax_noncompliance_rate[ t : t + length, j ] income_tax_filer = p.income_tax_filer[t : t + length, j] tau_payroll = p.tau_payroll[t : t + length, j] e_long = _get_e_long(p) e = np.diag(e_long[t : t + p.S, :, j], max(p.S - length, 0)) else: if method == "SS": tax_noncompliance = p.labor_income_tax_noncompliance_rate[-1, :] income_tax_filer = p.income_tax_filer[-1, :] tau_payroll = p.tau_payroll[-1, :] e = np.squeeze(p.e[-1, :, :]) elif method == "TPI_scalar": tax_noncompliance = p.labor_income_tax_noncompliance_rate[0, :] income_tax_filer = p.income_tax_filer[0, :] tau_payroll = p.tau_payroll[0, :] e = np.squeeze(p.e[0, -1, :]) else: tax_noncompliance = p.labor_income_tax_noncompliance_rate[ t : t + length, : ] income_tax_filer = p.income_tax_filer[t : t + length, :] tau_payroll = p.tau_payroll[t : t + length, :] e_long = _get_e_long(p) e = np.diag(e_long[t : t + p.S, :, j], max(p.S - length, 0)) if method == "TPI": if b.ndim == 2: r = r.reshape(r.shape[0], 1) w = w.reshape(w.shape[0], 1) tau_payroll = tau_payroll.reshape(tau_payroll.shape[0], 1) if net_tax is None: taxes = tax.net_taxes( r, w, b, n, bq, factor, tr, ubi, theta, t, j, False, method, e, etr_params, p, ndc_rates, ) else: taxes = net_tax fdc = get_fdc(r, w, n, e, j, p, method, t) cons = get_cons( r, w, p_tilde, p_i, b, b_splus1, n, bq, rm, taxes + fdc_net_flow(fdc), e, tau_c, p, method, ) deriv = ( 1 - tau_payroll - tax.MTR_income( r, w, b, n, factor, False, e, etr_params, mtrx_params, tax_noncompliance, income_tax_filer, p, ) ) FOC_error = marg_ut_cons(cons, p.sigma) * ( 1 / p_tilde ) * w * deriv * e - marg_ut_labor(n, chi_n, p) if fdc is not None: # mortality along the household's own lifetime if method == "SS": if j is not None: rho, beta = p.rho[-1, :, j], p.beta[j] else: rho, beta = p.rho[-1, :, :], p.beta elif method == "TPI_scalar": rho, beta = np.array([p.rho[0, -1, j]]), p.beta[j] else: L = np.size(cons) rho = np.diag(p.rho[t : t + p.S, :, j], max(p.S - L, 0)) beta = p.beta[j] cons_w = cons if method == "SS" else np.ravel(cons) FOC_error = FOC_error + fdc_labor_wedge( cons_w, p_tilde, fdc, rho, beta, p ) return FOC_error
[docs] def get_y(r_p, w, b_s, n, p, method): r""" Compute household income before taxes. .. math:: y_{j,s,t} = r_{p,t}b_{j,s,t} + w_{t}e_{j,s}n_{j,s,t} Args: r_p (array_like): real interest rate on the household portfolio w (array_like): real wage rate b_s (Numpy array): household savings coming into the period n (Numpy array): household labor supply p (OG-Core Specifications object): model parameters method (str): adjusts calculation dimensions based on 'SS' or 'TPI' """ if method == "SS": # NOTE: do not np.squeeze here -- for J=1 it collapses p.e[-1, :, :] # from (S, 1) to (S,), which then broadcasts against the (S, 1) b_s/n # into an (S, S) outer product, giving wrong before-tax income. The # array is already (S, J). e = p.e[-1, :, :] elif method == "TPI": e = p.e y = r_p * b_s + w * e * n return y
[docs] def constraint_checker_SS(bssmat, nssmat, cssmat, ltilde): """ Checks constraints on consumption, savings, and labor supply in the steady state. Args: bssmat (Numpy array): steady state distribution of capital nssmat (Numpy array): steady state distribution of labor cssmat (Numpy array): steady state distribution of consumption ltilde (scalar): upper bound of household labor supply Returns: None Raises: Warnings: if constraints are violated, warnings printed """ logger.info("Checking constraints on capital, labor, and consumption.") if (bssmat < 0).any(): logger.info("WARNING: There is negative capital stock") flag2 = False if (nssmat < 0).any(): logger.info( "WARNING: Labor supply violates nonnegativity constraints." ) flag2 = True if (nssmat > ltilde).any(): logger.info("WARNING: Labor supply violates the ltilde constraint.") flag2 = True if flag2 is False: logger.info( "There were no violations of the constraints on labor supply.", ) if (cssmat < 0).any(): logger.info("WARNING: Consumption violates nonnegativity constraints.") else: logger.info( "There were no violations of the constraints on consumption." )
[docs] def constraint_checker_TPI(b_dist, n_dist, c_dist, t, ltilde): """ Checks constraints on consumption, savings, and labor supply along the transition path. Does this for each period t separately. Args: b_dist (Numpy array): distribution of capital at time t n_dist (Numpy array): distribution of labor at time t c_dist (Numpy array): distribution of consumption at time t t (int): time period ltilde (scalar): upper bound of household labor supply Returns: None Raises: Warnings: if constraints are violated, warnings printed """ if (b_dist <= 0).any(): logger.info( "WARNING: Aggregate capital is less than or equal to" f" zero in period {t}." ) if (n_dist < 0).any(): logger.info( "WARNING: Labor supply violates nonnegativity" f" constraints in period {t}." ) if (n_dist > ltilde).any(): logger.info( "\tWARNING: Labor suppy violates the ltilde constraint" f" in period {t}." ) if (c_dist < 0).any(): logger.info( "\tWARNING: Consumption violates nonnegativity" f" constraints in period {t}." )