idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
12,900
def simDeath ( self ) : which_agents = np . zeros ( self . AgentCount , dtype = bool ) return which_agents
Trivial function that returns boolean array of all False as there is no death .
12,901
def getShocks ( self ) : employed = self . eStateNow == 1.0 N = int ( np . sum ( employed ) ) newly_unemployed = drawBernoulli ( N , p = self . UnempPrb , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) self . eStateNow [ employed ] = 1.0 - newly_unemployed
Determine which agents switch from employment to unemployment . All unemployed agents remain unemployed until death .
12,902
def getStates ( self ) : self . bLvlNow = self . Rfree * self . aLvlNow self . mLvlNow = self . bLvlNow + self . eStateNow
Calculate market resources for all agents this period .
12,903
def getControls ( self ) : employed = self . eStateNow == 1.0 unemployed = np . logical_not ( employed ) cLvlNow = np . zeros ( self . AgentCount ) cLvlNow [ employed ] = self . solution [ 0 ] . cFunc ( self . mLvlNow [ employed ] ) cLvlNow [ unemployed ] = self . solution [ 0 ] . cFunc_U ( self . mLvlNow [ unemployed ] ) self . cLvlNow = cLvlNow
Calculate consumption for each agent this period .
12,904
def derivativeX ( self , mLvl , pLvl , MedShk ) : xLvl = self . xFunc ( mLvl , pLvl , MedShk ) dxdm = self . xFunc . derivativeX ( mLvl , pLvl , MedShk ) dcdx = self . cFunc . derivativeX ( xLvl , MedShk ) dcdm = dxdm * dcdx dMeddm = ( dxdm - dcdm ) / self . MedPrice return dcdm , dMeddm
Evaluate the derivative of consumption and medical care with respect to market resources at given levels of market resources permanent income and medical need shocks .
12,905
def derivativeY ( self , mLvl , pLvl , MedShk ) : xLvl = self . xFunc ( mLvl , pLvl , MedShk ) dxdp = self . xFunc . derivativeY ( mLvl , pLvl , MedShk ) dcdx = self . cFunc . derivativeX ( xLvl , MedShk ) dcdp = dxdp * dcdx dMeddp = ( dxdp - dcdp ) / self . MedPrice return dcdp , dMeddp
Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources permanent income and medical need shocks .
12,906
def derivativeZ ( self , mLvl , pLvl , MedShk ) : xLvl = self . xFunc ( mLvl , pLvl , MedShk ) dxdShk = self . xFunc . derivativeZ ( mLvl , pLvl , MedShk ) dcdx = self . cFunc . derivativeX ( xLvl , MedShk ) dcdShk = dxdShk * dcdx + self . cFunc . derivativeY ( xLvl , MedShk ) dMeddShk = ( dxdShk - dcdShk ) / self . MedPrice return dcdShk , dMeddShk
Evaluate the derivative of consumption and medical care with respect to medical need shock at given levels of market resources permanent income and medical need shocks .
12,907
def update ( self ) : self . updateIncomeProcess ( ) self . updateAssetsGrid ( ) self . updatepLvlNextFunc ( ) self . updatepLvlGrid ( ) self . updateMedShockProcess ( ) self . updateSolutionTerminal ( )
Update the income process the assets grid the permanent income grid the medical shock distribution and the terminal solution .
12,908
def updateMedShockProcess ( self ) : MedShkDstn = [ ] for t in range ( self . T_cycle ) : MedShkAvgNow = self . MedShkAvg [ t ] MedShkStdNow = self . MedShkStd [ t ] MedShkDstnNow = approxLognormal ( mu = np . log ( MedShkAvgNow ) - 0.5 * MedShkStdNow ** 2 , sigma = MedShkStdNow , N = self . MedShkCount , tail_N = self . MedShkCountTail , tail_bound = [ 0 , 0.9 ] ) MedShkDstnNow = addDiscreteOutcomeConstantMean ( MedShkDstnNow , 0.0 , 0.0 , sort = True ) MedShkDstn . append ( MedShkDstnNow ) self . MedShkDstn = MedShkDstn self . addToTimeVary ( 'MedShkDstn' )
Constructs discrete distributions of medical preference shocks for each period in the cycle . Distributions are saved as attribute MedShkDstn which is added to time_vary .
12,909
def getShocks ( self ) : PersistentShockConsumerType . getShocks ( self ) MedShkNow = np . zeros ( self . AgentCount ) MedPriceNow = np . zeros ( self . AgentCount ) for t in range ( self . T_cycle ) : these = t == self . t_cycle N = np . sum ( these ) if N > 0 : MedShkAvg = self . MedShkAvg [ t ] MedShkStd = self . MedShkStd [ t ] MedPrice = self . MedPrice [ t ] MedShkNow [ these ] = self . RNG . permutation ( approxLognormal ( N , mu = np . log ( MedShkAvg ) - 0.5 * MedShkStd ** 2 , sigma = MedShkStd ) [ 1 ] ) MedPriceNow [ these ] = MedPrice self . MedShkNow = MedShkNow self . MedPriceNow = MedPriceNow
Gets permanent and transitory income shocks for this period as well as medical need shocks and the price of medical care .
12,910
def getControls ( self ) : cLvlNow = np . zeros ( self . AgentCount ) + np . nan MedNow = np . zeros ( self . AgentCount ) + np . nan for t in range ( self . T_cycle ) : these = t == self . t_cycle cLvlNow [ these ] , MedNow [ these ] = self . solution [ t ] . policyFunc ( self . mLvlNow [ these ] , self . pLvlNow [ these ] , self . MedShkNow [ these ] ) self . cLvlNow = cLvlNow self . MedNow = MedNow return None
Calculates consumption and medical care for each consumer of this type using the consumption and medical care functions .
12,911
def solve ( self ) : aLvl , trash = self . prepareToCalcEndOfPrdvP ( ) EndOfPrdvP = self . calcEndOfPrdvP ( ) if self . vFuncBool : self . makeEndOfPrdvFunc ( EndOfPrdvP ) if self . CubicBool : interpolator = self . makeCubicxFunc else : interpolator = self . makeLinearxFunc solution = self . makeBasicSolution ( EndOfPrdvP , aLvl , interpolator ) solution = self . addMPCandHumanWealth ( solution ) if self . CubicBool : solution = self . addvPPfunc ( solution ) return solution
Solves a one period consumption saving problem with risky income and shocks to medical need .
12,912
def solve ( self ) : self . defBoundary ( ) self . EndOfPrdvFunc_list = [ ] self . EndOfPrdvPfunc_list = [ ] self . ExIncNextAll = np . zeros ( self . StateCount ) + np . nan self . WorstIncPrbAll = np . zeros ( self . StateCount ) + np . nan for j in range ( self . StateCount ) : self . conditionOnState ( j ) self . ExIncNextAll [ j ] = np . dot ( self . ShkPrbsNext , self . PermShkValsNext * self . TranShkValsNext ) self . WorstIncPrbAll [ j ] = self . WorstIncPrb EndOfPrdvPfunc_cond = self . makeEndOfPrdvPfuncCond ( ) self . EndOfPrdvPfunc_list . append ( EndOfPrdvPfunc_cond ) if self . vFuncBool : EndOfPrdvFunc_cond = self . makeEndOfPrdvFuncCond ( ) self . EndOfPrdvFunc_list . append ( EndOfPrdvFunc_cond ) self . calcEndOfPrdvP ( ) self . calcHumWealthAndBoundingMPCs ( ) aNrm = np . asarray ( self . aXtraGrid ) [ np . newaxis , : ] + np . array ( self . BoroCnstNat_list ) [ : , np . newaxis ] self . getPointsForInterpolation ( self . EndOfPrdvP , aNrm ) cNrm = np . hstack ( ( np . zeros ( ( self . StateCount , 1 ) ) , self . cNrmNow ) ) mNrm = np . hstack ( ( np . reshape ( self . mNrmMin_list , ( self . StateCount , 1 ) ) , self . mNrmNow ) ) self . BoroCnstNat = self . BoroCnstNat_list solution = self . makeSolution ( cNrm , mNrm ) return solution
Solve the one period problem of the consumption - saving model with a Markov state .
12,913
def defBoundary ( self ) : self . BoroCnstNatAll = np . zeros ( self . StateCount ) + np . nan for j in range ( self . StateCount ) : PermShkMinNext = np . min ( self . IncomeDstn_list [ j ] [ 1 ] ) TranShkMinNext = np . min ( self . IncomeDstn_list [ j ] [ 2 ] ) self . BoroCnstNatAll [ j ] = ( self . solution_next . mNrmMin [ j ] - TranShkMinNext ) * ( self . PermGroFac_list [ j ] * PermShkMinNext ) / self . Rfree_list [ j ] self . BoroCnstNat_list = np . zeros ( self . StateCount ) + np . nan self . mNrmMin_list = np . zeros ( self . StateCount ) + np . nan self . BoroCnstDependency = np . zeros ( ( self . StateCount , self . StateCount ) ) + np . nan for i in range ( self . StateCount ) : possible_next_states = self . MrkvArray [ i , : ] > 0 self . BoroCnstNat_list [ i ] = np . max ( self . BoroCnstNatAll [ possible_next_states ] ) if self . BoroCnstArt is None : self . mNrmMin_list [ i ] = self . BoroCnstNat_list [ i ] else : self . mNrmMin_list [ i ] = np . max ( [ self . BoroCnstNat_list [ i ] , self . BoroCnstArt ] ) self . BoroCnstDependency [ i , : ] = self . BoroCnstNat_list [ i ] == self . BoroCnstNatAll
Find the borrowing constraint for each current state and save it as an attribute of self for use by other methods .
12,914
def calcEndOfPrdvPP ( self ) : EndOfPrdvPP = self . DiscFacEff * self . Rfree * self . Rfree * self . PermGroFac ** ( - self . CRRA - 1.0 ) * np . sum ( self . PermShkVals_temp ** ( - self . CRRA - 1.0 ) * self . vPPfuncNext ( self . mNrmNext ) * self . ShkPrbs_temp , axis = 0 ) return EndOfPrdvPP
Calculates end - of - period marginal marginal value using a pre - defined array of next period market resources in self . mNrmNext .
12,915
def makeEndOfPrdvPfuncCond ( self ) : self . aNrm_cond = self . prepareToCalcEndOfPrdvP ( ) self . EndOfPrdvP_cond = self . calcEndOfPrdvPcond ( ) EndOfPrdvPnvrs_cond = self . uPinv ( self . EndOfPrdvP_cond ) if self . CubicBool : EndOfPrdvPP_cond = self . calcEndOfPrdvPP ( ) EndOfPrdvPnvrsP_cond = EndOfPrdvPP_cond * self . uPinvP ( self . EndOfPrdvP_cond ) if self . CubicBool : EndOfPrdvPnvrsFunc_cond = CubicInterp ( self . aNrm_cond , EndOfPrdvPnvrs_cond , EndOfPrdvPnvrsP_cond , lower_extrap = True ) else : EndOfPrdvPnvrsFunc_cond = LinearInterp ( self . aNrm_cond , EndOfPrdvPnvrs_cond , lower_extrap = True ) EndofPrdvPfunc_cond = MargValueFunc ( EndOfPrdvPnvrsFunc_cond , self . CRRA ) return EndofPrdvPfunc_cond
Construct the end - of - period marginal value function conditional on next period s state .
12,916
def calcHumWealthAndBoundingMPCs ( self ) : WorstIncPrb_array = self . BoroCnstDependency * np . tile ( np . reshape ( self . WorstIncPrbAll , ( 1 , self . StateCount ) ) , ( self . StateCount , 1 ) ) temp_array = self . MrkvArray * WorstIncPrb_array WorstIncPrbNow = np . sum ( temp_array , axis = 1 ) ExMPCmaxNext = ( np . dot ( temp_array , self . Rfree_list ** ( 1.0 - self . CRRA ) * self . solution_next . MPCmax ** ( - self . CRRA ) ) / WorstIncPrbNow ) ** ( - 1.0 / self . CRRA ) DiscFacEff_temp = self . DiscFac * self . LivPrb self . MPCmaxNow = 1.0 / ( 1.0 + ( ( DiscFacEff_temp * WorstIncPrbNow ) ** ( 1.0 / self . CRRA ) ) / ExMPCmaxNext ) self . MPCmaxEff = self . MPCmaxNow self . MPCmaxEff [ self . BoroCnstNat_list < self . mNrmMin_list ] = 1.0 hNrmPlusIncNext = self . ExIncNextAll + self . solution_next . hNrm self . hNrmNow = np . dot ( self . MrkvArray , ( self . PermGroFac_list / self . Rfree_list ) * hNrmPlusIncNext ) temp = ( DiscFacEff_temp * np . dot ( self . MrkvArray , self . solution_next . MPCmin ** ( - self . CRRA ) * self . Rfree_list ** ( 1.0 - self . CRRA ) ) ) ** ( 1.0 / self . CRRA ) self . MPCminNow = 1.0 / ( 1.0 + temp )
Calculates human wealth and the maximum and minimum MPC for each current period state then stores them as attributes of self for use by other methods .
12,917
def makeSolution ( self , cNrm , mNrm ) : solution = ConsumerSolution ( ) if self . CubicBool : dcda = self . EndOfPrdvPP / self . uPP ( np . array ( self . cNrmNow ) ) MPC = dcda / ( dcda + 1.0 ) self . MPC_temp = np . hstack ( ( np . reshape ( self . MPCmaxNow , ( self . StateCount , 1 ) ) , MPC ) ) interpfunc = self . makeCubiccFunc else : interpfunc = self . makeLinearcFunc for i in range ( self . StateCount ) : self . hNrmNow_j = self . hNrmNow [ i ] self . MPCminNow_j = self . MPCminNow [ i ] if self . CubicBool : self . MPC_temp_j = self . MPC_temp [ i , : ] self . cFuncNowCnst = LinearInterp ( [ self . mNrmMin_list [ i ] , self . mNrmMin_list [ i ] + 1.0 ] , [ 0.0 , 1.0 ] ) cFuncNowUnc = interpfunc ( mNrm [ i , : ] , cNrm [ i , : ] ) cFuncNow = LowerEnvelope ( cFuncNowUnc , self . cFuncNowCnst ) vPfuncNow = MargValueFunc ( cFuncNow , self . CRRA ) solution_cond = ConsumerSolution ( cFunc = cFuncNow , vPfunc = vPfuncNow , mNrmMin = self . mNrmMinNow ) if self . CubicBool : solution_cond = self . addvPPfunc ( solution_cond ) solution . appendSolution ( solution_cond ) solution . mNrmMin = self . mNrmMin_list solution = self . addMPCandHumanWealth ( solution ) if self . vFuncBool : vFuncNow = self . makevFunc ( solution ) solution . vFunc = vFuncNow return solution
Construct an object representing the solution to this period s problem .
12,918
def makevFunc ( self , solution ) : vFuncNow = [ ] for i in range ( self . StateCount ) : mNrmMin = self . mNrmMin_list [ i ] mGrid = mNrmMin + self . aXtraGrid cGrid = solution . cFunc [ i ] ( mGrid ) aGrid = mGrid - cGrid EndOfPrdv_all = np . zeros ( ( self . StateCount , self . aXtraGrid . size ) ) for j in range ( self . StateCount ) : if self . possible_transitions [ i , j ] : EndOfPrdv_all [ j , : ] = self . EndOfPrdvFunc_list [ j ] ( aGrid ) EndOfPrdv = np . dot ( self . MrkvArray [ i , : ] , EndOfPrdv_all ) vNrmNow = self . u ( cGrid ) + EndOfPrdv vPnow = self . uP ( cGrid ) vNvrs = self . uinv ( vNrmNow ) vNvrsP = vPnow * self . uinvP ( vNrmNow ) mNrm_temp = np . insert ( mGrid , 0 , mNrmMin ) vNvrs = np . insert ( vNvrs , 0 , 0.0 ) vNvrsP = np . insert ( vNvrsP , 0 , self . MPCmaxEff [ i ] ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) ) MPCminNvrs = self . MPCminNow [ i ] ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) vNvrsFunc_i = CubicInterp ( mNrm_temp , vNvrs , vNvrsP , MPCminNvrs * self . hNrmNow [ i ] , MPCminNvrs ) vFunc_i = ValueFunc ( vNvrsFunc_i , self . CRRA ) vFuncNow . append ( vFunc_i ) return vFuncNow
Construct the value function for each current state .
12,919
def checkMarkovInputs ( self ) : StateCount = self . MrkvArray [ 0 ] . shape [ 0 ] assert self . Rfree . shape == ( StateCount , ) , 'Rfree not the right shape!' for MrkvArray_t in self . MrkvArray : assert MrkvArray_t . shape == ( StateCount , StateCount ) , 'MrkvArray not the right shape!' for LivPrb_t in self . LivPrb : assert LivPrb_t . shape == ( StateCount , ) , 'Array in LivPrb is not the right shape!' for PermGroFac_t in self . LivPrb : assert PermGroFac_t . shape == ( StateCount , ) , 'Array in PermGroFac is not the right shape!' for IncomeDstn_t in self . IncomeDstn : assert len ( IncomeDstn_t ) == StateCount , 'List in IncomeDstn is not the right length!'
Many parameters used by MarkovConsumerType are arrays . Make sure those arrays are the right shape .
12,920
def simBirth ( self , which_agents ) : IndShockConsumerType . simBirth ( self , which_agents ) if not self . global_markov : N = np . sum ( which_agents ) base_draws = drawUniform ( N , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) Cutoffs = np . cumsum ( np . array ( self . MrkvPrbsInit ) ) self . MrkvNow [ which_agents ] = np . searchsorted ( Cutoffs , base_draws ) . astype ( int )
Makes new Markov consumer by drawing initial normalized assets permanent income levels and discrete states . Calls IndShockConsumerType . simBirth then draws from initial Markov distribution .
12,921
def getShocks ( self ) : if self . global_markov : base_draws = np . ones ( self . AgentCount ) * drawUniform ( 1 , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) else : base_draws = self . RNG . permutation ( np . arange ( self . AgentCount , dtype = float ) / self . AgentCount + 1.0 / ( 2 * self . AgentCount ) ) newborn = self . t_age == 0 MrkvPrev = self . MrkvNow MrkvNow = np . zeros ( self . AgentCount , dtype = int ) for t in range ( self . T_cycle ) : Cutoffs = np . cumsum ( self . MrkvArray [ t ] , axis = 1 ) for j in range ( self . MrkvArray [ t ] . shape [ 0 ] ) : these = np . logical_and ( self . t_cycle == t , MrkvPrev == j ) MrkvNow [ these ] = np . searchsorted ( Cutoffs [ j , : ] , base_draws [ these ] ) . astype ( int ) if not self . global_markov : MrkvNow [ newborn ] = MrkvPrev [ newborn ] self . MrkvNow = MrkvNow . astype ( int ) PermShkNow = np . zeros ( self . AgentCount ) TranShkNow = np . zeros ( self . AgentCount ) for t in range ( self . T_cycle ) : for j in range ( self . MrkvArray [ t ] . shape [ 0 ] ) : these = np . logical_and ( t == self . t_cycle , j == MrkvNow ) N = np . sum ( these ) if N > 0 : IncomeDstnNow = self . IncomeDstn [ t - 1 ] [ j ] PermGroFacNow = self . PermGroFac [ t - 1 ] [ j ] Indices = np . arange ( IncomeDstnNow [ 0 ] . size ) EventDraws = drawDiscrete ( N , X = Indices , P = IncomeDstnNow [ 0 ] , exact_match = False , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) PermShkNow [ these ] = IncomeDstnNow [ 1 ] [ EventDraws ] * PermGroFacNow TranShkNow [ these ] = IncomeDstnNow [ 2 ] [ EventDraws ] newborn = self . t_age == 0 PermShkNow [ newborn ] = 1.0 TranShkNow [ newborn ] = 1.0 self . PermShkNow = PermShkNow self . TranShkNow = TranShkNow
Gets new Markov states and permanent and transitory income shocks for this period . Samples from IncomeDstn for each period - state in the cycle .
12,922
def readShocks ( self ) : IndShockConsumerType . readShocks ( self ) self . MrkvNow = self . MrkvNow . astype ( int )
A slight modification of AgentType . readShocks that makes sure that MrkvNow is int not float .
12,923
def solveConsRepAgent ( solution_next , DiscFac , CRRA , IncomeDstn , CapShare , DeprFac , PermGroFac , aXtraGrid ) : vPfuncNext = solution_next . vPfunc ShkPrbsNext = IncomeDstn [ 0 ] PermShkValsNext = IncomeDstn [ 1 ] TranShkValsNext = IncomeDstn [ 2 ] aNrmNow = aXtraGrid aNrmCount = aNrmNow . size ShkCount = ShkPrbsNext . size aNrm_tiled = np . tile ( np . reshape ( aNrmNow , ( aNrmCount , 1 ) ) , ( 1 , ShkCount ) ) PermShkVals_tiled = np . tile ( np . reshape ( PermShkValsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) TranShkVals_tiled = np . tile ( np . reshape ( TranShkValsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) ShkPrbs_tiled = np . tile ( np . reshape ( ShkPrbsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) kNrmNext = aNrm_tiled / ( PermGroFac * PermShkVals_tiled ) KtoLnext = kNrmNext / TranShkVals_tiled RfreeNext = 1. - DeprFac + CapShare * KtoLnext ** ( CapShare - 1. ) wRteNext = ( 1. - CapShare ) * KtoLnext ** CapShare mNrmNext = RfreeNext * kNrmNext + wRteNext * TranShkVals_tiled vPnext = vPfuncNext ( mNrmNext ) EndOfPrdvP = DiscFac * np . sum ( RfreeNext * ( PermGroFac * PermShkVals_tiled ) ** ( - CRRA ) * vPnext * ShkPrbs_tiled , axis = 1 ) cNrmNow = EndOfPrdvP ** ( - 1. / CRRA ) mNrmNow = aNrmNow + cNrmNow cFuncNow = LinearInterp ( np . insert ( mNrmNow , 0 , 0.0 ) , np . insert ( cNrmNow , 0 , 0.0 ) ) vPfuncNow = MargValueFunc ( cFuncNow , CRRA ) solution_now = ConsumerSolution ( cFunc = cFuncNow , vPfunc = vPfuncNow ) return solution_now
Solve one period of the simple representative agent consumption - saving model .
12,924
def solveConsRepAgentMarkov ( solution_next , MrkvArray , DiscFac , CRRA , IncomeDstn , CapShare , DeprFac , PermGroFac , aXtraGrid ) : StateCount = MrkvArray . shape [ 0 ] aNrmNow = aXtraGrid aNrmCount = aNrmNow . size EndOfPrdvP_cond = np . zeros ( ( StateCount , aNrmCount ) ) + np . nan for j in range ( StateCount ) : vPfuncNext = solution_next . vPfunc [ j ] ShkPrbsNext = IncomeDstn [ j ] [ 0 ] PermShkValsNext = IncomeDstn [ j ] [ 1 ] TranShkValsNext = IncomeDstn [ j ] [ 2 ] ShkCount = ShkPrbsNext . size aNrm_tiled = np . tile ( np . reshape ( aNrmNow , ( aNrmCount , 1 ) ) , ( 1 , ShkCount ) ) PermShkVals_tiled = np . tile ( np . reshape ( PermShkValsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) TranShkVals_tiled = np . tile ( np . reshape ( TranShkValsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) ShkPrbs_tiled = np . tile ( np . reshape ( ShkPrbsNext , ( 1 , ShkCount ) ) , ( aNrmCount , 1 ) ) kNrmNext = aNrm_tiled / ( PermGroFac [ j ] * PermShkVals_tiled ) KtoLnext = kNrmNext / TranShkVals_tiled RfreeNext = 1. - DeprFac + CapShare * KtoLnext ** ( CapShare - 1. ) wRteNext = ( 1. - CapShare ) * KtoLnext ** CapShare mNrmNext = RfreeNext * kNrmNext + wRteNext * TranShkVals_tiled vPnext = vPfuncNext ( mNrmNext ) EndOfPrdvP_cond [ j , : ] = DiscFac * np . sum ( RfreeNext * ( PermGroFac [ j ] * PermShkVals_tiled ) ** ( - CRRA ) * vPnext * ShkPrbs_tiled , axis = 1 ) EndOfPrdvP = np . dot ( MrkvArray , EndOfPrdvP_cond ) cFuncNow_list = [ ] vPfuncNow_list = [ ] for i in range ( StateCount ) : cNrmNow = EndOfPrdvP [ i , : ] ** ( - 1. / CRRA ) mNrmNow = aNrmNow + cNrmNow cFuncNow_list . append ( LinearInterp ( np . insert ( mNrmNow , 0 , 0.0 ) , np . insert ( cNrmNow , 0 , 0.0 ) ) ) vPfuncNow_list . append ( MargValueFunc ( cFuncNow_list [ - 1 ] , CRRA ) ) solution_now = ConsumerSolution ( cFunc = cFuncNow_list , vPfunc = vPfuncNow_list ) return solution_now
Solve one period of the simple representative agent consumption - saving model . This version supports a discrete Markov process .
12,925
def getStates ( self ) : pLvlPrev = self . pLvlNow aNrmPrev = self . aNrmNow self . pLvlNow = pLvlPrev * self . PermShkNow self . kNrmNow = aNrmPrev / self . PermShkNow self . yNrmNow = self . kNrmNow ** self . CapShare * self . TranShkNow ** ( 1. - self . CapShare ) self . Rfree = 1. + self . CapShare * self . kNrmNow ** ( self . CapShare - 1. ) * self . TranShkNow ** ( 1. - self . CapShare ) - self . DeprFac self . wRte = ( 1. - self . CapShare ) * self . kNrmNow ** self . CapShare * self . TranShkNow ** ( - self . CapShare ) self . mNrmNow = self . Rfree * self . kNrmNow + self . wRte * self . TranShkNow
Calculates updated values of normalized market resources and permanent income level . Uses pLvlNow aNrmNow PermShkNow TranShkNow .
12,926
def getShocks ( self ) : cutoffs = np . cumsum ( self . MrkvArray [ self . MrkvNow , : ] ) MrkvDraw = drawUniform ( N = 1 , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) self . MrkvNow = np . searchsorted ( cutoffs , MrkvDraw ) t = self . t_cycle [ 0 ] i = self . MrkvNow [ 0 ] IncomeDstnNow = self . IncomeDstn [ t - 1 ] [ i ] PermGroFacNow = self . PermGroFac [ t - 1 ] [ i ] Indices = np . arange ( IncomeDstnNow [ 0 ] . size ) EventDraw = drawDiscrete ( N = 1 , X = Indices , P = IncomeDstnNow [ 0 ] , exact_match = False , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) PermShkNow = IncomeDstnNow [ 1 ] [ EventDraw ] * PermGroFacNow TranShkNow = IncomeDstnNow [ 2 ] [ EventDraw ] self . PermShkNow = np . array ( PermShkNow ) self . TranShkNow = np . array ( TranShkNow )
Draws a new Markov state and income shocks for the representative agent .
12,927
def getControls ( self ) : t = self . t_cycle [ 0 ] i = self . MrkvNow [ 0 ] self . cNrmNow = self . solution [ t ] . cFunc [ i ] ( self . mNrmNow )
Calculates consumption for the representative agent using the consumption functions .
12,928
def updateSolutionTerminal ( self ) : cFunc_terminal = BilinearInterp ( np . array ( [ [ 0.0 , 0.0 ] , [ 1.0 , 1.0 ] ] ) , np . array ( [ 0.0 , 1.0 ] ) , np . array ( [ 0.0 , 1.0 ] ) ) vPfunc_terminal = MargValueFunc2D ( cFunc_terminal , self . CRRA ) mNrmMin_terminal = ConstantFunction ( 0 ) self . solution_terminal = ConsumerSolution ( cFunc = cFunc_terminal , vPfunc = vPfunc_terminal , mNrmMin = mNrmMin_terminal )
Updates the terminal period solution for an aggregate shock consumer . Only fills in the consumption function and marginal value function .
12,929
def getEconomyData ( self , Economy ) : self . T_sim = Economy . act_T self . kInit = Economy . kSS self . aNrmInitMean = np . log ( 0.00000001 ) self . Mgrid = Economy . MSS * self . MgridBase self . AFunc = Economy . AFunc self . Rfunc = Economy . Rfunc self . wFunc = Economy . wFunc self . DeprFac = Economy . DeprFac self . PermGroFacAgg = Economy . PermGroFacAgg self . addAggShkDstn ( Economy . AggShkDstn ) self . addToTimeInv ( 'Mgrid' , 'AFunc' , 'Rfunc' , 'wFunc' , 'DeprFac' , 'PermGroFacAgg' )
Imports economy - determined objects into self from a Market . Instances of AggShockConsumerType live in some macroeconomy that has attributes relevant to their microeconomic model like the relationship between the capital - to - labor ratio and the interest and wage rates ; this method imports those attributes from an economy object and makes them attributes of the ConsumerType .
12,930
def addAggShkDstn ( self , AggShkDstn ) : if len ( self . IncomeDstn [ 0 ] ) > 3 : self . IncomeDstn = self . IncomeDstnWithoutAggShocks else : self . IncomeDstnWithoutAggShocks = self . IncomeDstn self . IncomeDstn = [ combineIndepDstns ( self . IncomeDstn [ t ] , AggShkDstn ) for t in range ( self . T_cycle ) ]
Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks .
12,931
def simDeath ( self ) : how_many_die = int ( round ( self . AgentCount * ( 1.0 - self . LivPrb [ 0 ] ) ) ) base_bool = np . zeros ( self . AgentCount , dtype = bool ) base_bool [ 0 : how_many_die ] = True who_dies = self . RNG . permutation ( base_bool ) if self . T_age is not None : who_dies [ self . t_age >= self . T_age ] = True who_lives = np . logical_not ( who_dies ) wealth_living = np . sum ( self . aLvlNow [ who_lives ] ) wealth_dead = np . sum ( self . aLvlNow [ who_dies ] ) Ractuarial = 1.0 + wealth_dead / wealth_living self . aNrmNow [ who_lives ] = self . aNrmNow [ who_lives ] * Ractuarial self . aLvlNow [ who_lives ] = self . aLvlNow [ who_lives ] * Ractuarial return who_dies
Randomly determine which consumers die and distribute their wealth among the survivors . This method only works if there is only one period in the cycle .
12,932
def getRfree ( self ) : RfreeNow = self . RfreeNow * np . ones ( self . AgentCount ) return RfreeNow
Returns an array of size self . AgentCount with self . RfreeNow in every entry .
12,933
def getShocks ( self ) : IndShockConsumerType . getShocks ( self ) self . TranShkNow = self . TranShkNow * self . TranShkAggNow * self . wRteNow self . PermShkNow = self . PermShkNow * self . PermShkAggNow
Finds the effective permanent and transitory shocks this period by combining the aggregate and idiosyncratic shocks of each type .
12,934
def addAggShkDstn ( self , AggShkDstn ) : if len ( self . IncomeDstn [ 0 ] [ 0 ] ) > 3 : self . IncomeDstn = self . IncomeDstnWithoutAggShocks else : self . IncomeDstnWithoutAggShocks = self . IncomeDstn IncomeDstnOut = [ ] N = self . MrkvArray . shape [ 0 ] for t in range ( self . T_cycle ) : IncomeDstnOut . append ( [ combineIndepDstns ( self . IncomeDstn [ t ] [ n ] , AggShkDstn [ n ] ) for n in range ( N ) ] ) self . IncomeDstn = IncomeDstnOut
Variation on AggShockConsumerType . addAggShkDstn that handles the Markov state . AggShkDstn is a list of aggregate productivity shock distributions for each Markov state .
12,935
def getShocks ( self ) : PermShkNow = np . zeros ( self . AgentCount ) TranShkNow = np . zeros ( self . AgentCount ) newborn = self . t_age == 0 for t in range ( self . T_cycle ) : these = t == self . t_cycle N = np . sum ( these ) if N > 0 : IncomeDstnNow = self . IncomeDstn [ t - 1 ] [ self . MrkvNow ] PermGroFacNow = self . PermGroFac [ t - 1 ] Indices = np . arange ( IncomeDstnNow [ 0 ] . size ) EventDraws = drawDiscrete ( N , X = Indices , P = IncomeDstnNow [ 0 ] , exact_match = True , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) PermShkNow [ these ] = IncomeDstnNow [ 1 ] [ EventDraws ] * PermGroFacNow TranShkNow [ these ] = IncomeDstnNow [ 2 ] [ EventDraws ] N = np . sum ( newborn ) if N > 0 : these = newborn IncomeDstnNow = self . IncomeDstn [ 0 ] [ self . MrkvNow ] PermGroFacNow = self . PermGroFac [ 0 ] Indices = np . arange ( IncomeDstnNow [ 0 ] . size ) EventDraws = drawDiscrete ( N , X = Indices , P = IncomeDstnNow [ 0 ] , exact_match = False , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) PermShkNow [ these ] = IncomeDstnNow [ 1 ] [ EventDraws ] * PermGroFacNow TranShkNow [ these ] = IncomeDstnNow [ 2 ] [ EventDraws ] self . EmpNow = np . ones ( self . AgentCount , dtype = bool ) self . EmpNow [ TranShkNow == self . IncUnemp ] = False self . TranShkNow = TranShkNow * self . TranShkAggNow * self . wRteNow self . PermShkNow = PermShkNow * self . PermShkAggNow
Gets permanent and transitory income shocks for this period . Samples from IncomeDstn for each period in the cycle . This is a copy - paste from IndShockConsumerType with the addition of the Markov macroeconomic state . Unfortunately the getShocks method for MarkovConsumerType cannot be used as that method assumes that MrkvNow is a vector with a value for each agent not just a single int .
12,936
def getControls ( self ) : cNrmNow = np . zeros ( self . AgentCount ) + np . nan MPCnow = np . zeros ( self . AgentCount ) + np . nan MaggNow = self . getMaggNow ( ) MrkvNow = self . getMrkvNow ( ) StateCount = self . MrkvArray . shape [ 0 ] MrkvBoolArray = np . zeros ( ( StateCount , self . AgentCount ) , dtype = bool ) for i in range ( StateCount ) : MrkvBoolArray [ i , : ] = i == MrkvNow for t in range ( self . T_cycle ) : these = t == self . t_cycle for i in range ( StateCount ) : those = np . logical_and ( these , MrkvBoolArray [ i , : ] ) cNrmNow [ those ] = self . solution [ t ] . cFunc [ i ] ( self . mNrmNow [ those ] , MaggNow [ those ] ) MPCnow [ those ] = self . solution [ t ] . cFunc [ i ] . derivativeX ( self . mNrmNow [ those ] , MaggNow [ those ] ) self . cNrmNow = cNrmNow self . MPCnow = MPCnow return None
Calculates consumption for each consumer of this type using the consumption functions . For this AgentType class MrkvNow is the same for all consumers . However in an extension with macroeconomic inattention consumers might misperceive the state and thus act as if they are in different states .
12,937
def makeAggShkDstn ( self ) : self . TranShkAggDstn = approxMeanOneLognormal ( sigma = self . TranShkAggStd , N = self . TranShkAggCount ) self . PermShkAggDstn = approxMeanOneLognormal ( sigma = self . PermShkAggStd , N = self . PermShkAggCount ) self . AggShkDstn = combineIndepDstns ( self . PermShkAggDstn , self . TranShkAggDstn )
Creates the attributes TranShkAggDstn PermShkAggDstn and AggShkDstn . Draws on attributes TranShkAggStd PermShkAddStd TranShkAggCount PermShkAggCount .
12,938
def calcRandW ( self , aLvlNow , pLvlNow ) : AaggPrev = np . mean ( np . array ( aLvlNow ) ) / np . mean ( pLvlNow ) AggregateK = np . mean ( np . array ( aLvlNow ) ) PermShkAggNow = self . PermShkAggHist [ self . Shk_idx ] TranShkAggNow = self . TranShkAggHist [ self . Shk_idx ] self . Shk_idx += 1 AggregateL = np . mean ( pLvlNow ) * PermShkAggNow KtoLnow = AggregateK / AggregateL self . KtoYnow = KtoLnow ** ( 1.0 - self . CapShare ) RfreeNow = self . Rfunc ( KtoLnow / TranShkAggNow ) wRteNow = self . wFunc ( KtoLnow / TranShkAggNow ) MaggNow = KtoLnow * RfreeNow + wRteNow * TranShkAggNow self . KtoLnow = KtoLnow AggVarsNow = CobbDouglasAggVars ( MaggNow , AaggPrev , KtoLnow , RfreeNow , wRteNow , PermShkAggNow , TranShkAggNow ) return AggVarsNow
Calculates the interest factor and wage rate this period using each agent s capital stock to get the aggregate capital ratio .
12,939
def calcAFunc ( self , MaggNow , AaggNow ) : verbose = self . verbose discard_periods = self . T_discard update_weight = 1. - self . DampingFac total_periods = len ( MaggNow ) logAagg = np . log ( AaggNow [ discard_periods : total_periods ] ) logMagg = np . log ( MaggNow [ discard_periods - 1 : total_periods - 1 ] ) slope , intercept , r_value , p_value , std_err = stats . linregress ( logMagg , logAagg ) intercept = update_weight * intercept + ( 1.0 - update_weight ) * self . intercept_prev slope = update_weight * slope + ( 1.0 - update_weight ) * self . slope_prev AFunc = AggregateSavingRule ( intercept , slope ) self . intercept_prev = intercept self . slope_prev = slope if verbose : print ( 'intercept=' + str ( intercept ) + ', slope=' + str ( slope ) + ', r-sq=' + str ( r_value ** 2 ) ) return AggShocksDynamicRule ( AFunc )
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation .
12,940
def update ( self ) : self . kSS = 1.0 self . MSS = 1.0 self . KtoLnow_init = self . kSS self . Rfunc = ConstantFunction ( self . Rfree ) self . wFunc = ConstantFunction ( self . wRte ) self . RfreeNow_init = self . Rfunc ( self . kSS ) self . wRteNow_init = self . wFunc ( self . kSS ) self . MaggNow_init = self . kSS self . AaggNow_init = self . kSS self . PermShkAggNow_init = 1.0 self . TranShkAggNow_init = 1.0 self . makeAggShkDstn ( ) self . AFunc = ConstantFunction ( 1.0 )
Use primitive parameters to set basic objects . This is an extremely stripped - down version of update for CobbDouglasEconomy .
12,941
def makeAggShkHist ( self ) : sim_periods = self . act_T Events = np . arange ( self . AggShkDstn [ 0 ] . size ) EventDraws = drawDiscrete ( N = sim_periods , P = self . AggShkDstn [ 0 ] , X = Events , seed = 0 ) PermShkAggHist = self . AggShkDstn [ 1 ] [ EventDraws ] TranShkAggHist = self . AggShkDstn [ 2 ] [ EventDraws ] self . PermShkAggHist = PermShkAggHist self . TranShkAggHist = TranShkAggHist
Make simulated histories of aggregate transitory and permanent shocks . Histories are of length self . act_T for use in the general equilibrium simulation . This replicates the same method for CobbDouglasEconomy ; future version should create parent class .
12,942
def getAggShocks ( self ) : PermShkAggNow = self . PermShkAggHist [ self . Shk_idx ] TranShkAggNow = self . TranShkAggHist [ self . Shk_idx ] self . Shk_idx += 1 RfreeNow = self . Rfunc ( 1.0 / PermShkAggNow ) wRteNow = self . wFunc ( 1.0 / PermShkAggNow ) AaggNow = 1.0 MaggNow = 1.0 KtoLnow = 1.0 / PermShkAggNow AggVarsNow = CobbDouglasAggVars ( MaggNow , AaggNow , KtoLnow , RfreeNow , wRteNow , PermShkAggNow , TranShkAggNow ) return AggVarsNow
Returns aggregate state variables and shocks for this period . The capital - to - labor ratio is irrelevant and thus treated as constant and the wage and interest rates are also constant . However aggregate shocks are assigned from a prespecified history .
12,943
def makeAggShkDstn ( self ) : TranShkAggDstn = [ ] PermShkAggDstn = [ ] AggShkDstn = [ ] StateCount = self . MrkvArray . shape [ 0 ] for i in range ( StateCount ) : TranShkAggDstn . append ( approxMeanOneLognormal ( sigma = self . TranShkAggStd [ i ] , N = self . TranShkAggCount ) ) PermShkAggDstn . append ( approxMeanOneLognormal ( sigma = self . PermShkAggStd [ i ] , N = self . PermShkAggCount ) ) AggShkDstn . append ( combineIndepDstns ( PermShkAggDstn [ - 1 ] , TranShkAggDstn [ - 1 ] ) ) self . TranShkAggDstn = TranShkAggDstn self . PermShkAggDstn = PermShkAggDstn self . AggShkDstn = AggShkDstn
Creates the attributes TranShkAggDstn PermShkAggDstn and AggShkDstn . Draws on attributes TranShkAggStd PermShkAddStd TranShkAggCount PermShkAggCount . This version accounts for the Markov macroeconomic state .
12,944
def makeMrkvHist ( self ) : if hasattr ( self , 'loops_max' ) : loops_max = self . loops_max else : loops_max = 10 state_T_min = 50 logit_scale = 0.2 if hasattr ( self , 'act_T_orig' ) : act_T = self . act_T_orig else : self . act_T_orig = self . act_T act_T = self . act_T w , v = np . linalg . eig ( np . transpose ( self . MrkvArray ) ) idx = ( np . abs ( w - 1.0 ) ) . argmin ( ) x = v [ : , idx ] . astype ( float ) LR_dstn = ( x / np . sum ( x ) ) MrkvNow_hist = np . zeros ( self . act_T_orig , dtype = int ) cutoffs = np . cumsum ( self . MrkvArray , axis = 1 ) loops = 0 go = True MrkvNow = self . MrkvNow_init t = 0 StateCount = self . MrkvArray . shape [ 0 ] while go : draws = drawUniform ( N = self . act_T_orig , seed = loops ) for s in range ( draws . size ) : MrkvNow_hist [ t ] = MrkvNow MrkvNow = np . searchsorted ( cutoffs [ MrkvNow , : ] , draws [ s ] ) t += 1 state_T = np . zeros ( StateCount ) for i in range ( StateCount ) : state_T [ i ] = np . sum ( MrkvNow_hist == i ) if np . all ( state_T >= state_T_min ) : go = False continue if np . any ( state_T == 0 ) : never_visited = np . where ( np . array ( state_T == 0 ) ) [ 0 ] MrkvNow = np . random . choice ( never_visited ) else : emp_dstn = state_T / act_T ratios = LR_dstn / emp_dstn ratios_adj = ratios - np . max ( ratios ) ratios_exp = np . exp ( ratios_adj / logit_scale ) ratios_sum = np . sum ( ratios_exp ) jump_probs = ratios_exp / ratios_sum cum_probs = np . cumsum ( jump_probs ) MrkvNow = np . searchsorted ( cum_probs , draws [ - 1 ] ) loops += 1 if loops >= loops_max : go = False print ( 'makeMrkvHist reached maximum number of loops without generating a valid sequence!' ) else : MrkvNow_new = np . zeros ( self . act_T_orig , dtype = int ) MrkvNow_hist = np . concatenate ( ( MrkvNow_hist , MrkvNow_new ) ) act_T += self . act_T_orig self . MrkvNow_hist = MrkvNow_hist self . act_T = act_T
Makes a history of macroeconomic Markov states stored in the attribute MrkvNow_hist . This version ensures that each state is reached a sufficient number of times to have a valid sample for calcDynamics to produce a good dynamic rule . It will sometimes cause act_T to be increased beyond its initially specified level .
12,945
def calcAFunc ( self , MaggNow , AaggNow ) : verbose = self . verbose discard_periods = self . T_discard update_weight = 1. - self . DampingFac total_periods = len ( MaggNow ) logAagg = np . log ( AaggNow [ discard_periods : total_periods ] ) logMagg = np . log ( MaggNow [ discard_periods - 1 : total_periods - 1 ] ) MrkvHist = self . MrkvNow_hist [ discard_periods - 1 : total_periods - 1 ] AFunc_list = [ ] rSq_list = [ ] for i in range ( self . MrkvArray . shape [ 0 ] ) : these = i == MrkvHist slope , intercept , r_value , p_value , std_err = stats . linregress ( logMagg [ these ] , logAagg [ these ] ) intercept = update_weight * intercept + ( 1.0 - update_weight ) * self . intercept_prev [ i ] slope = update_weight * slope + ( 1.0 - update_weight ) * self . slope_prev [ i ] AFunc_list . append ( AggregateSavingRule ( intercept , slope ) ) rSq_list . append ( r_value ** 2 ) self . intercept_prev [ i ] = intercept self . slope_prev [ i ] = slope if verbose : print ( 'intercept=' + str ( self . intercept_prev ) + ', slope=' + str ( self . slope_prev ) + ', r-sq=' + str ( rSq_list ) ) return AggShocksDynamicRule ( AFunc_list )
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation . Calculates an aggregate saving rule for each macroeconomic Markov state .
12,946
def getKYratioDifference ( Economy , param_name , param_count , center , spread , dist_type ) : Economy ( LorenzBool = False , ManyStatsBool = False ) Economy . distributeParams ( param_name , param_count , center , spread , dist_type ) Economy . solve ( ) diff = Economy . calcKYratioDifference ( ) print ( 'getKYratioDifference tried center = ' + str ( center ) + ' and got ' + str ( diff ) ) return diff
Finds the difference between simulated and target capital to income ratio in an economy when a given parameter has heterogeneity according to some distribution .
12,947
def findLorenzDistanceAtTargetKY ( Economy , param_name , param_count , center_range , spread , dist_type ) : intermediateObjective = lambda center : getKYratioDifference ( Economy = Economy , param_name = param_name , param_count = param_count , center = center , spread = spread , dist_type = dist_type ) optimal_center = brentq ( intermediateObjective , center_range [ 0 ] , center_range [ 1 ] , xtol = 10 ** ( - 6 ) ) Economy . center_save = optimal_center Economy ( LorenzBool = True ) Economy . distributeParams ( param_name , param_count , optimal_center , spread , dist_type ) Economy . solveAgents ( ) Economy . makeHistory ( ) dist = Economy . calcLorenzDistance ( ) Economy ( LorenzBool = False ) print ( 'findLorenzDistanceAtTargetKY tried spread = ' + str ( spread ) + ' and got ' + str ( dist ) ) return dist
Finds the sum of squared distances between simulated and target Lorenz points in an economy when a given parameter has heterogeneity according to some distribution . The class of distribution and a measure of spread are given as inputs but the measure of centrality such that the capital to income ratio matches the target ratio must be found .
12,948
def calcStationaryAgeDstn ( LivPrb , terminal_period ) : T = len ( LivPrb ) if terminal_period : MrkvArray = np . zeros ( ( T + 1 , T + 1 ) ) top = T else : MrkvArray = np . zeros ( ( T , T ) ) top = T - 1 for t in range ( top ) : MrkvArray [ t , 0 ] = 1.0 - LivPrb [ t ] MrkvArray [ t , t + 1 ] = LivPrb [ t ] MrkvArray [ t + 1 , 0 ] = 1.0 w , v = np . linalg . eig ( np . transpose ( MrkvArray ) ) idx = ( np . abs ( w - 1.0 ) ) . argmin ( ) x = v [ : , idx ] . astype ( float ) AgeDstn = ( x / np . sum ( x ) ) return AgeDstn
Calculates the steady state proportions of each age given survival probability sequence LivPrb . Assumes that agents who die are replaced by a newborn agent with t_age = 0 .
12,949
def updateIncomeProcess ( self ) : if self . cycles == 0 : tax_rate = ( self . IncUnemp * self . UnempPrb ) / ( ( 1.0 - self . UnempPrb ) * self . IndL ) TranShkDstn = deepcopy ( approxMeanOneLognormal ( self . TranShkCount , sigma = self . TranShkStd [ 0 ] , tail_N = 0 ) ) TranShkDstn [ 0 ] = np . insert ( TranShkDstn [ 0 ] * ( 1.0 - self . UnempPrb ) , 0 , self . UnempPrb ) TranShkDstn [ 1 ] = np . insert ( TranShkDstn [ 1 ] * ( 1.0 - tax_rate ) * self . IndL , 0 , self . IncUnemp ) PermShkDstn = approxMeanOneLognormal ( self . PermShkCount , sigma = self . PermShkStd [ 0 ] , tail_N = 0 ) self . IncomeDstn = [ combineIndepDstns ( PermShkDstn , TranShkDstn ) ] self . TranShkDstn = TranShkDstn self . PermShkDstn = PermShkDstn self . addToTimeVary ( 'IncomeDstn' ) else : EstimationAgentClass . updateIncomeProcess ( self )
An alternative method for constructing the income process in the infinite horizon model .
12,950
def solve ( self ) : if self . AggShockBool : for agent in self . agents : agent . getEconomyData ( self ) Market . solve ( self ) else : self . solveAgents ( ) self . makeHistory ( )
Solves the cstwMPCmarket .
12,951
def millRule ( self , aLvlNow , pLvlNow , MPCnow , TranShkNow , EmpNow , t_age , LorenzBool , ManyStatsBool ) : self . calcStats ( aLvlNow , pLvlNow , MPCnow , TranShkNow , EmpNow , t_age , LorenzBool , ManyStatsBool ) if self . AggShockBool : return self . calcRandW ( aLvlNow , pLvlNow ) else : self . MaggNow = 0.0 self . AaggNow = 0.0
The millRule for this class simply calls the method calcStats .
12,952
def distributeParams ( self , param_name , param_count , center , spread , dist_type ) : if dist_type == 'uniform' : param_dist = approxUniform ( N = param_count , bot = center - spread , top = center + spread ) elif dist_type == 'lognormal' : tail_N = 3 param_dist = approxLognormal ( N = param_count - tail_N , mu = np . log ( center ) - 0.5 * spread ** 2 , sigma = spread , tail_N = tail_N , tail_bound = [ 0.0 , 0.9 ] , tail_order = np . e ) replication_factor = len ( self . agents ) // param_count j = 0 b = 0 while j < len ( self . agents ) : for n in range ( replication_factor ) : self . agents [ j ] ( AgentCount = int ( self . Population * param_dist [ 0 ] [ b ] * self . TypeWeight [ n ] ) ) exec ( 'self.agents[j](' + param_name + '= param_dist[1][b])' ) j += 1 b += 1
Distributes heterogeneous values of one parameter to the AgentTypes in self . agents .
12,953
def calcKYratioDifference ( self ) : KYratioSim = np . mean ( np . array ( self . KtoYnow_hist ) [ self . ignore_periods : ] ) diff = KYratioSim - self . KYratioTarget return diff
Returns the difference between the simulated capital to income ratio and the target ratio . Can only be run after solving all AgentTypes and running makeHistory .
12,954
def calcLorenzDistance ( self ) : LorenzSim = np . mean ( np . array ( self . Lorenz_hist ) [ self . ignore_periods : , : ] , axis = 0 ) dist = np . sqrt ( np . sum ( ( 100 * ( LorenzSim - self . LorenzTarget ) ) ** 2 ) ) self . LorenzDistance = dist return dist
Returns the sum of squared differences between simulated and target Lorenz points .
12,955
def derivativeX ( self , m , p ) : c = self . cFunc ( m , p ) MPC = self . cFunc . derivativeX ( m , p ) return MPC * utilityPP ( c , gam = self . CRRA )
Evaluate the first derivative with respect to market resources of the marginal value function at given levels of market resources m and per - manent income p .
12,956
def defBoroCnst ( self , BoroCnstArt ) : ShkCount = self . TranShkValsNext . size pLvlCount = self . pLvlGrid . size PermShkVals_temp = np . tile ( np . reshape ( self . PermShkValsNext , ( 1 , ShkCount ) ) , ( pLvlCount , 1 ) ) TranShkVals_temp = np . tile ( np . reshape ( self . TranShkValsNext , ( 1 , ShkCount ) ) , ( pLvlCount , 1 ) ) pLvlNext_temp = np . tile ( np . reshape ( self . pLvlNextFunc ( self . pLvlGrid ) , ( pLvlCount , 1 ) ) , ( 1 , ShkCount ) ) * PermShkVals_temp aLvlMin_candidates = ( self . mLvlMinNext ( pLvlNext_temp ) - TranShkVals_temp * pLvlNext_temp ) / self . Rfree aLvlMinNow = np . max ( aLvlMin_candidates , axis = 1 ) self . BoroCnstNat = LinearInterp ( np . insert ( self . pLvlGrid , 0 , 0.0 ) , np . insert ( aLvlMinNow , 0 , 0.0 ) ) if self . BoroCnstArt is not None : self . BoroCnstArt = LinearInterp ( np . array ( [ 0.0 , 1.0 ] ) , np . array ( [ 0.0 , self . BoroCnstArt ] ) ) self . mLvlMinNow = UpperEnvelope ( self . BoroCnstArt , self . BoroCnstNat ) else : self . mLvlMinNow = self . BoroCnstNat cFuncNowCnstBase = BilinearInterp ( np . array ( [ [ 0. , 0. ] , [ 1. , 1. ] ] ) , np . array ( [ 0.0 , 1.0 ] ) , np . array ( [ 0.0 , 1.0 ] ) ) self . cFuncNowCnst = VariableLowerBoundFunc2D ( cFuncNowCnstBase , self . mLvlMinNow )
Defines the constrained portion of the consumption function as cFuncNowCnst an attribute of self .
12,957
def prepareToCalcEndOfPrdvP ( self ) : ShkCount = self . TranShkValsNext . size pLvlCount = self . pLvlGrid . size aNrmCount = self . aXtraGrid . size pLvlNow = np . tile ( self . pLvlGrid , ( aNrmCount , 1 ) ) . transpose ( ) aLvlNow = np . tile ( self . aXtraGrid , ( pLvlCount , 1 ) ) * pLvlNow + self . BoroCnstNat ( pLvlNow ) pLvlNow_tiled = np . tile ( pLvlNow , ( ShkCount , 1 , 1 ) ) aLvlNow_tiled = np . tile ( aLvlNow , ( ShkCount , 1 , 1 ) ) if self . pLvlGrid [ 0 ] == 0.0 : aLvlNow [ 0 , : ] = self . aXtraGrid aLvlNow_tiled [ : , 0 , : ] = np . tile ( self . aXtraGrid , ( ShkCount , 1 ) ) PermShkVals_tiled = np . transpose ( np . tile ( self . PermShkValsNext , ( aNrmCount , pLvlCount , 1 ) ) , ( 2 , 1 , 0 ) ) TranShkVals_tiled = np . transpose ( np . tile ( self . TranShkValsNext , ( aNrmCount , pLvlCount , 1 ) ) , ( 2 , 1 , 0 ) ) ShkPrbs_tiled = np . transpose ( np . tile ( self . ShkPrbsNext , ( aNrmCount , pLvlCount , 1 ) ) , ( 2 , 1 , 0 ) ) pLvlNext = self . pLvlNextFunc ( pLvlNow_tiled ) * PermShkVals_tiled mLvlNext = self . Rfree * aLvlNow_tiled + pLvlNext * TranShkVals_tiled self . ShkPrbs_temp = ShkPrbs_tiled self . pLvlNext = pLvlNext self . mLvlNext = mLvlNext self . aLvlNow = aLvlNow return aLvlNow , pLvlNow
Prepare to calculate end - of - period marginal value by creating an array of market resources that the agent could have next period considering the grid of end - of - period normalized assets the grid of persistent income levels and the distribution of shocks he might experience next period .
12,958
def makevFunc ( self , solution ) : mSize = self . aXtraGrid . size pSize = self . pLvlGrid . size pLvl_temp = np . tile ( self . pLvlGrid , ( mSize , 1 ) ) mLvl_temp = np . tile ( self . mLvlMinNow ( self . pLvlGrid ) , ( mSize , 1 ) ) + np . tile ( np . reshape ( self . aXtraGrid , ( mSize , 1 ) ) , ( 1 , pSize ) ) * pLvl_temp cLvlNow = solution . cFunc ( mLvl_temp , pLvl_temp ) aLvlNow = mLvl_temp - cLvlNow vNow = self . u ( cLvlNow ) + self . EndOfPrdvFunc ( aLvlNow , pLvl_temp ) vPnow = self . uP ( cLvlNow ) vNvrs = self . uinv ( vNow ) vNvrsP = vPnow * self . uinvP ( vNow ) mLvl_temp = np . concatenate ( ( np . reshape ( self . mLvlMinNow ( self . pLvlGrid ) , ( 1 , pSize ) ) , mLvl_temp ) , axis = 0 ) vNvrs = np . concatenate ( ( np . zeros ( ( 1 , pSize ) ) , vNvrs ) , axis = 0 ) vNvrsP = np . concatenate ( ( np . reshape ( vNvrsP [ 0 , : ] , ( 1 , vNvrsP . shape [ 1 ] ) ) , vNvrsP ) , axis = 0 ) MPCminNvrs = self . MPCminNow ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) m_temp = np . reshape ( mLvl_temp [ : , 0 ] , ( mSize + 1 , 1 ) ) mLvl_temp = np . concatenate ( ( m_temp , mLvl_temp ) , axis = 1 ) vNvrs = np . concatenate ( ( MPCminNvrs * m_temp , vNvrs ) , axis = 1 ) vNvrsP = np . concatenate ( ( MPCminNvrs * np . ones ( ( mSize + 1 , 1 ) ) , vNvrsP ) , axis = 1 ) vNvrsFunc_list = [ ] for j in range ( pSize + 1 ) : pLvl = np . insert ( self . pLvlGrid , 0 , 0.0 ) [ j ] vNvrsFunc_list . append ( CubicInterp ( mLvl_temp [ : , j ] - self . mLvlMinNow ( pLvl ) , vNvrs [ : , j ] , vNvrsP [ : , j ] , MPCminNvrs * self . hLvlNow ( pLvl ) , MPCminNvrs ) ) vNvrsFuncBase = LinearInterpOnInterp1D ( vNvrsFunc_list , np . insert ( self . pLvlGrid , 0 , 0.0 ) ) vNvrsFuncNow = VariableLowerBoundFunc2D ( vNvrsFuncBase , self . mLvlMinNow ) vFuncNow = ValueFunc2D ( vNvrsFuncNow , self . CRRA ) return vFuncNow
Creates the value function for this period defined over market resources m and persistent income p . self must have the attribute EndOfPrdvFunc in order to execute .
12,959
def makeCubiccFunc ( self , mLvl , pLvl , cLvl ) : EndOfPrdvPP = self . DiscFacEff * self . Rfree * self . Rfree * np . sum ( self . vPPfuncNext ( self . mLvlNext , self . pLvlNext ) * self . ShkPrbs_temp , axis = 0 ) dcda = EndOfPrdvPP / self . uPP ( np . array ( cLvl [ 1 : , 1 : ] ) ) MPC = dcda / ( dcda + 1. ) MPC = np . concatenate ( ( np . reshape ( MPC [ : , 0 ] , ( MPC . shape [ 0 ] , 1 ) ) , MPC ) , axis = 1 ) MPC = np . concatenate ( ( self . MPCminNow * np . ones ( ( 1 , self . aXtraGrid . size + 1 ) ) , MPC ) , axis = 0 ) cFunc_by_pLvl_list = [ ] for j in range ( pLvl . shape [ 0 ] ) : pLvl_j = pLvl [ j , 0 ] m_temp = mLvl [ j , : ] - self . BoroCnstNat ( pLvl_j ) c_temp = cLvl [ j , : ] MPC_temp = MPC [ j , : ] if pLvl_j > 0 : cFunc_by_pLvl_list . append ( CubicInterp ( m_temp , c_temp , MPC_temp , lower_extrap = True , slope_limit = self . MPCminNow , intercept_limit = self . MPCminNow * self . hLvlNow ( pLvl_j ) ) ) else : cFunc_by_pLvl_list . append ( LinearInterp ( m_temp , c_temp , lower_extrap = True ) ) pLvl_list = pLvl [ : , 0 ] cFuncUncBase = LinearInterpOnInterp1D ( cFunc_by_pLvl_list , pLvl_list ) cFuncUnc = VariableLowerBoundFunc2D ( cFuncUncBase , self . BoroCnstNat ) return cFuncUnc
Makes a quasi - cubic spline interpolation of the unconstrained consumption function for this period . Function is cubic splines with respect to mLvl but linear in pLvl .
12,960
def solve ( self ) : aLvl , pLvl = self . prepareToCalcEndOfPrdvP ( ) EndOfPrdvP = self . calcEndOfPrdvP ( ) if self . vFuncBool : self . makeEndOfPrdvFunc ( EndOfPrdvP ) if self . CubicBool : interpolator = self . makeCubiccFunc else : interpolator = self . makeLinearcFunc solution = self . makeBasicSolution ( EndOfPrdvP , aLvl , pLvl , interpolator ) solution = self . addMPCandHumanWealth ( solution ) if self . vFuncBool : solution . vFunc = self . makevFunc ( solution ) if self . CubicBool : solution = self . addvPPfunc ( solution ) return solution
Solves a one period consumption saving problem with risky income with persistent income explicitly tracked as a state variable .
12,961
def installRetirementFunc ( self ) : if ( not hasattr ( self , 'pLvlNextFuncRet' ) ) or self . T_retire == 0 : return t = self . T_retire self . pLvlNextFunc [ t ] = self . pLvlNextFuncRet
Installs a special pLvlNextFunc representing retirement in the correct element of self . pLvlNextFunc . Draws on the attributes T_retire and pLvlNextFuncRet . If T_retire is zero or pLvlNextFuncRet does not exist this method does nothing . Should only be called from within the method updatepLvlNextFunc which ensures that time is flowing forward .
12,962
def getStates ( self ) : aLvlPrev = self . aLvlNow RfreeNow = self . getRfree ( ) pLvlNow = np . zeros_like ( aLvlPrev ) for t in range ( self . T_cycle ) : these = t == self . t_cycle pLvlNow [ these ] = self . pLvlNextFunc [ t - 1 ] ( self . pLvlNow [ these ] ) * self . PermShkNow [ these ] self . pLvlNow = pLvlNow self . bLvlNow = RfreeNow * aLvlPrev self . mLvlNow = self . bLvlNow + self . TranShkNow * self . pLvlNow
Calculates updated values of normalized market resources and persistent income level for each agent . Uses pLvlNow aLvlNow PermShkNow TranShkNow .
12,963
def updatepLvlNextFunc ( self ) : orig_time = self . time_flow self . timeFwd ( ) pLvlNextFunc = [ ] for t in range ( self . T_cycle ) : pLvlNextFunc . append ( LinearInterp ( np . array ( [ 0. , 1. ] ) , np . array ( [ 0. , self . PermGroFac [ t ] ] ) ) ) self . pLvlNextFunc = pLvlNextFunc self . addToTimeVary ( 'pLvlNextFunc' ) if not orig_time : self . timeRev ( )
A method that creates the pLvlNextFunc attribute as a sequence of linear functions indicating constant expected permanent income growth across permanent income levels . Draws on the attribute PermGroFac and installs a special retirement function when it exists .
12,964
def updatepLvlNextFunc ( self ) : orig_time = self . time_flow self . timeFwd ( ) pLvlNextFunc = [ ] pLogMean = self . pLvlInitMean for t in range ( self . T_cycle ) : pLvlNextFunc . append ( pLvlFuncAR1 ( pLogMean , self . PermGroFac [ t ] , self . PrstIncCorr ) ) pLogMean += np . log ( self . PermGroFac [ t ] ) self . pLvlNextFunc = pLvlNextFunc self . addToTimeVary ( 'pLvlNextFunc' ) if not orig_time : self . timeRev ( )
A method that creates the pLvlNextFunc attribute as a sequence of AR1 - style functions . Draws on the attributes PermGroFac and PrstIncCorr . If cycles = 0 the product of PermGroFac across all periods must be 1 . 0 otherwise this method is invalid .
12,965
def drawDiscrete ( N , P = [ 1.0 ] , X = [ 0.0 ] , exact_match = False , seed = 0 ) : RNG = np . random . RandomState ( seed ) if exact_match : events = np . arange ( P . size ) cutoffs = np . round ( np . cumsum ( P ) * N ) . astype ( int ) top = 0 event_list = [ ] for j in range ( events . size ) : bot = top top = cutoffs [ j ] event_list += ( top - bot ) * [ events [ j ] ] event_draws = RNG . permutation ( event_list ) draws = X [ event_draws ] else : base_draws = RNG . uniform ( size = N ) cum_dist = np . cumsum ( P ) indices = cum_dist . searchsorted ( base_draws ) draws = np . asarray ( X ) [ indices ] return draws
Simulates N draws from a discrete distribution with probabilities P and outcomes X .
12,966
def solveFashion ( solution_next , DiscFac , conformUtilityFunc , punk_utility , jock_utility , switchcost_J2P , switchcost_P2J , pGrid , pEvolution , pref_shock_mag ) : VfuncPunkNext = solution_next . VfuncPunk VfuncJockNext = solution_next . VfuncJock EndOfPrdVpunk = DiscFac * np . mean ( VfuncPunkNext ( pEvolution ) , axis = 1 ) EndOfPrdVjock = DiscFac * np . mean ( VfuncJockNext ( pEvolution ) , axis = 1 ) Upunk = punk_utility + conformUtilityFunc ( pGrid ) Ujock = jock_utility + conformUtilityFunc ( 1.0 - pGrid ) V_J2J = Ujock + EndOfPrdVjock V_J2P = Upunk - switchcost_J2P + EndOfPrdVpunk V_P2J = Ujock - switchcost_P2J + EndOfPrdVjock V_P2P = Upunk + EndOfPrdVpunk Vboth_P = np . vstack ( ( V_P2J , V_P2P ) ) Vbest_P = np . max ( Vboth_P , axis = 0 ) Vnorm_P = Vboth_P - np . tile ( np . reshape ( Vbest_P , ( 1 , pGrid . size ) ) , ( 2 , 1 ) ) ExpVnorm_P = np . exp ( Vnorm_P / pref_shock_mag ) SumExpVnorm_P = np . sum ( ExpVnorm_P , axis = 0 ) V_P = np . log ( SumExpVnorm_P ) * pref_shock_mag + Vbest_P switch_P = ExpVnorm_P [ 0 , : ] / SumExpVnorm_P Vboth_J = np . vstack ( ( V_J2J , V_J2P ) ) Vbest_J = np . max ( Vboth_J , axis = 0 ) Vnorm_J = Vboth_J - np . tile ( np . reshape ( Vbest_J , ( 1 , pGrid . size ) ) , ( 2 , 1 ) ) ExpVnorm_J = np . exp ( Vnorm_J / pref_shock_mag ) SumExpVnorm_J = np . sum ( ExpVnorm_J , axis = 0 ) V_J = np . log ( SumExpVnorm_J ) * pref_shock_mag + Vbest_J switch_J = ExpVnorm_J [ 1 , : ] / SumExpVnorm_J VfuncPunkNow = LinearInterp ( pGrid , V_P ) VfuncJockNow = LinearInterp ( pGrid , V_J ) switchFuncPunkNow = LinearInterp ( pGrid , switch_P ) switchFuncJockNow = LinearInterp ( pGrid , switch_J ) solution_now = FashionSolution ( VfuncJock = VfuncJockNow , VfuncPunk = VfuncPunkNow , switchFuncJock = switchFuncJockNow , switchFuncPunk = switchFuncPunkNow ) return solution_now
Solves a single period of the fashion victim model .
12,967
def calcPunkProp ( sNow ) : sNowX = np . asarray ( sNow ) . flatten ( ) pNow = np . mean ( sNowX ) return FashionMarketInfo ( pNow )
Calculates the proportion of punks in the population given data from each type .
12,968
def calcFashionEvoFunc ( pNow ) : pNowX = np . array ( pNow ) T = pNowX . size p_t = pNowX [ 100 : ( T - 1 ) ] p_tp1 = pNowX [ 101 : T ] pNextSlope , pNextIntercept , trash1 , trash2 , trash3 = stats . linregress ( p_t , p_tp1 ) pPopExp = pNextIntercept + pNextSlope * p_t pPopErrSq = ( pPopExp - p_tp1 ) ** 2 pNextStd = np . sqrt ( np . mean ( pPopErrSq ) ) print ( str ( pNextIntercept ) + ', ' + str ( pNextSlope ) + ', ' + str ( pNextStd ) ) return FashionEvoFunc ( pNextIntercept , pNextSlope , 2 * pNextStd )
Calculates a new approximate dynamic rule for the evolution of the proportion of punks as a linear function and a shock width .
12,969
def updateEvolution ( self ) : self . pEvolution = np . zeros ( ( self . pCount , self . pNextCount ) ) for j in range ( self . pCount ) : pNow = self . pGrid [ j ] pNextMean = self . pNextIntercept + self . pNextSlope * pNow dist = approxUniform ( N = self . pNextCount , bot = pNextMean - self . pNextWidth , top = pNextMean + self . pNextWidth ) [ 1 ] self . pEvolution [ j , : ] = dist
Updates the population punk proportion evolution array . Fasion victims believe that the proportion of punks in the subsequent period is a linear function of the proportion of punks this period subject to a uniform shock . Given attributes of self pNextIntercept pNextSlope pNextCount pNextWidth and pGrid this method generates a new array for the attri - bute pEvolution representing a discrete approximation of next period states for each current period state in pGrid .
12,970
def reset ( self ) : self . resetRNG ( ) sNow = np . zeros ( self . pop_size ) Shk = self . RNG . rand ( self . pop_size ) sNow [ Shk < self . p_init ] = 1 self . sNow = sNow
Resets this agent type to prepare it for a new simulation run . This includes resetting the random number generator and initializing the style of each agent of this type .
12,971
def postSolve ( self ) : self . switchFuncPunk = self . solution [ 0 ] . switchFuncPunk self . switchFuncJock = self . solution [ 0 ] . switchFuncJock self . VfuncPunk = self . solution [ 0 ] . VfuncPunk self . VfuncJock = self . solution [ 0 ] . VfuncJock
Unpack the behavioral and value functions for more parsimonious access .
12,972
def solvePerfForesight ( solution_next , DiscFac , LivPrb , CRRA , Rfree , PermGroFac ) : solver = ConsPerfForesightSolver ( solution_next , DiscFac , LivPrb , CRRA , Rfree , PermGroFac ) solution = solver . solve ( ) return solution
Solves a single period consumption - saving problem for a consumer with perfect foresight .
12,973
def constructAssetsGrid ( parameters ) : aXtraMin = parameters . aXtraMin aXtraMax = parameters . aXtraMax aXtraCount = parameters . aXtraCount aXtraExtra = parameters . aXtraExtra grid_type = 'exp_mult' exp_nest = parameters . aXtraNestFac aXtraGrid = None if grid_type == "linear" : aXtraGrid = np . linspace ( aXtraMin , aXtraMax , aXtraCount ) elif grid_type == "exp_mult" : aXtraGrid = makeGridExpMult ( ming = aXtraMin , maxg = aXtraMax , ng = aXtraCount , timestonest = exp_nest ) else : raise Exception ( "grid_type not recognized in __init__." + "Please ensure grid_type is 'linear' or 'exp_mult'" ) for a in aXtraExtra : if ( a is not None ) : if a not in aXtraGrid : j = aXtraGrid . searchsorted ( a ) aXtraGrid = np . insert ( aXtraGrid , j , a ) return aXtraGrid
Constructs the base grid of post - decision states representing end - of - period assets above the absolute minimum .
12,974
def assignParameters ( self , solution_next , DiscFac , LivPrb , CRRA , Rfree , PermGroFac ) : self . solution_next = solution_next self . DiscFac = DiscFac self . LivPrb = LivPrb self . CRRA = CRRA self . Rfree = Rfree self . PermGroFac = PermGroFac
Saves necessary parameters as attributes of self for use by other methods .
12,975
def defValueFuncs ( self ) : MPCnvrs = self . MPC ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) vFuncNvrs = LinearInterp ( np . array ( [ self . mNrmMin , self . mNrmMin + 1.0 ] ) , np . array ( [ 0.0 , MPCnvrs ] ) ) self . vFunc = ValueFunc ( vFuncNvrs , self . CRRA ) self . vPfunc = MargValueFunc ( self . cFunc , self . CRRA )
Defines the value and marginal value function for this period .
12,976
def solve ( self ) : self . defUtilityFuncs ( ) self . DiscFacEff = self . DiscFac * self . LivPrb self . makePFcFunc ( ) self . defValueFuncs ( ) solution = ConsumerSolution ( cFunc = self . cFunc , vFunc = self . vFunc , vPfunc = self . vPfunc , mNrmMin = self . mNrmMin , hNrm = self . hNrmNow , MPCmin = self . MPC , MPCmax = self . MPC ) return solution
Solves the one period perfect foresight consumption - saving problem .
12,977
def assignParameters ( self , solution_next , IncomeDstn , LivPrb , DiscFac , CRRA , Rfree , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) : ConsPerfForesightSolver . assignParameters ( self , solution_next , DiscFac , LivPrb , CRRA , Rfree , PermGroFac ) self . BoroCnstArt = BoroCnstArt self . IncomeDstn = IncomeDstn self . aXtraGrid = aXtraGrid self . vFuncBool = vFuncBool self . CubicBool = CubicBool
Assigns period parameters as attributes of self for use by other methods
12,978
def prepareToSolve ( self ) : self . setAndUpdateValues ( self . solution_next , self . IncomeDstn , self . LivPrb , self . DiscFac ) self . defBoroCnst ( self . BoroCnstArt )
Perform preparatory work before calculating the unconstrained consumption function .
12,979
def prepareToCalcEndOfPrdvP ( self ) : aNrmNow = np . asarray ( self . aXtraGrid ) + self . BoroCnstNat ShkCount = self . TranShkValsNext . size aNrm_temp = np . tile ( aNrmNow , ( ShkCount , 1 ) ) aNrmCount = aNrmNow . shape [ 0 ] PermShkVals_temp = ( np . tile ( self . PermShkValsNext , ( aNrmCount , 1 ) ) ) . transpose ( ) TranShkVals_temp = ( np . tile ( self . TranShkValsNext , ( aNrmCount , 1 ) ) ) . transpose ( ) ShkPrbs_temp = ( np . tile ( self . ShkPrbsNext , ( aNrmCount , 1 ) ) ) . transpose ( ) mNrmNext = self . Rfree / ( self . PermGroFac * PermShkVals_temp ) * aNrm_temp + TranShkVals_temp self . PermShkVals_temp = PermShkVals_temp self . ShkPrbs_temp = ShkPrbs_temp self . mNrmNext = mNrmNext self . aNrmNow = aNrmNow return aNrmNow
Prepare to calculate end - of - period marginal value by creating an array of market resources that the agent could have next period considering the grid of end - of - period assets and the distribution of shocks he might experience next period .
12,980
def solve ( self ) : aNrm = self . prepareToCalcEndOfPrdvP ( ) EndOfPrdvP = self . calcEndOfPrdvP ( ) solution = self . makeBasicSolution ( EndOfPrdvP , aNrm , self . makeLinearcFunc ) solution = self . addMPCandHumanWealth ( solution ) return solution
Solves a one period consumption saving problem with risky income .
12,981
def makeCubiccFunc ( self , mNrm , cNrm ) : EndOfPrdvPP = self . DiscFacEff * self . Rfree * self . Rfree * self . PermGroFac ** ( - self . CRRA - 1.0 ) * np . sum ( self . PermShkVals_temp ** ( - self . CRRA - 1.0 ) * self . vPPfuncNext ( self . mNrmNext ) * self . ShkPrbs_temp , axis = 0 ) dcda = EndOfPrdvPP / self . uPP ( np . array ( cNrm [ 1 : ] ) ) MPC = dcda / ( dcda + 1. ) MPC = np . insert ( MPC , 0 , self . MPCmaxNow ) cFuncNowUnc = CubicInterp ( mNrm , cNrm , MPC , self . MPCminNow * self . hNrmNow , self . MPCminNow ) return cFuncNowUnc
Makes a cubic spline interpolation of the unconstrained consumption function for this period .
12,982
def addvFunc ( self , solution , EndOfPrdvP ) : self . makeEndOfPrdvFunc ( EndOfPrdvP ) solution . vFunc = self . makevFunc ( solution ) return solution
Creates the value function for this period and adds it to the solution .
12,983
def makevFunc ( self , solution ) : mNrm_temp = self . mNrmMinNow + self . aXtraGrid cNrmNow = solution . cFunc ( mNrm_temp ) aNrmNow = mNrm_temp - cNrmNow vNrmNow = self . u ( cNrmNow ) + self . EndOfPrdvFunc ( aNrmNow ) vPnow = self . uP ( cNrmNow ) vNvrs = self . uinv ( vNrmNow ) vNvrsP = vPnow * self . uinvP ( vNrmNow ) mNrm_temp = np . insert ( mNrm_temp , 0 , self . mNrmMinNow ) vNvrs = np . insert ( vNvrs , 0 , 0.0 ) vNvrsP = np . insert ( vNvrsP , 0 , self . MPCmaxEff ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) ) MPCminNvrs = self . MPCminNow ** ( - self . CRRA / ( 1.0 - self . CRRA ) ) vNvrsFuncNow = CubicInterp ( mNrm_temp , vNvrs , vNvrsP , MPCminNvrs * self . hNrmNow , MPCminNvrs ) vFuncNow = ValueFunc ( vNvrsFuncNow , self . CRRA ) return vFuncNow
Creates the value function for this period defined over market resources m . self must have the attribute EndOfPrdvFunc in order to execute .
12,984
def prepareToCalcEndOfPrdvP ( self ) : KinkBool = self . Rboro > self . Rsave if KinkBool : aNrmNow = np . sort ( np . hstack ( ( np . asarray ( self . aXtraGrid ) + self . mNrmMinNow , np . array ( [ 0.0 , 0.0 ] ) ) ) ) else : aNrmNow = np . asarray ( self . aXtraGrid ) + self . mNrmMinNow aXtraCount = aNrmNow . size ShkCount = self . TranShkValsNext . size aNrm_temp = np . tile ( aNrmNow , ( ShkCount , 1 ) ) PermShkVals_temp = ( np . tile ( self . PermShkValsNext , ( aXtraCount , 1 ) ) ) . transpose ( ) TranShkVals_temp = ( np . tile ( self . TranShkValsNext , ( aXtraCount , 1 ) ) ) . transpose ( ) ShkPrbs_temp = ( np . tile ( self . ShkPrbsNext , ( aXtraCount , 1 ) ) ) . transpose ( ) Rfree_vec = self . Rsave * np . ones ( aXtraCount ) if KinkBool : Rfree_vec [ 0 : ( np . sum ( aNrmNow <= 0 ) - 1 ) ] = self . Rboro self . Rfree = Rfree_vec Rfree_temp = np . tile ( Rfree_vec , ( ShkCount , 1 ) ) mNrmNext = Rfree_temp / ( self . PermGroFac * PermShkVals_temp ) * aNrm_temp + TranShkVals_temp if KinkBool : PatFacTop = ( ( self . Rsave * self . DiscFacEff ) ** ( 1.0 / self . CRRA ) ) / self . Rsave self . MPCminNow = 1.0 / ( 1.0 + PatFacTop / self . solution_next . MPCmin ) self . hNrmNow = self . PermGroFac / self . Rsave * ( np . dot ( self . ShkPrbsNext , self . TranShkValsNext * self . PermShkValsNext ) + self . solution_next . hNrm ) self . PermShkVals_temp = PermShkVals_temp self . ShkPrbs_temp = ShkPrbs_temp self . mNrmNext = mNrmNext self . aNrmNow = aNrmNow return aNrmNow
Prepare to calculate end - of - period marginal value by creating an array of market resources that the agent could have next period considering the grid of end - of - period assets and the distribution of shocks he might experience next period . This differs from the baseline case because different savings choices yield different interest rates .
12,985
def simDeath ( self ) : DiePrb_by_t_cycle = 1.0 - np . asarray ( self . LivPrb ) DiePrb = DiePrb_by_t_cycle [ self . t_cycle - 1 ] DeathShks = drawUniform ( N = self . AgentCount , seed = self . RNG . randint ( 0 , 2 ** 31 - 1 ) ) which_agents = DeathShks < DiePrb if self . T_age is not None : too_old = self . t_age >= self . T_age which_agents = np . logical_or ( which_agents , too_old ) return which_agents
Determines which agents die this period and must be replaced . Uses the sequence in LivPrb to determine survival probabilities for each agent .
12,986
def getStates ( self ) : pLvlPrev = self . pLvlNow aNrmPrev = self . aNrmNow RfreeNow = self . getRfree ( ) self . pLvlNow = pLvlPrev * self . PermShkNow self . PlvlAggNow = self . PlvlAggNow * self . PermShkAggNow ReffNow = RfreeNow / self . PermShkNow self . bNrmNow = ReffNow * aNrmPrev self . mNrmNow = self . bNrmNow + self . TranShkNow return None
Calculates updated values of normalized market resources and permanent income level for each agent . Uses pLvlNow aNrmNow PermShkNow TranShkNow .
12,987
def updateIncomeProcess ( self ) : original_time = self . time_flow self . timeFwd ( ) IncomeDstn , PermShkDstn , TranShkDstn = constructLognormalIncomeProcessUnemployment ( self ) self . IncomeDstn = IncomeDstn self . PermShkDstn = PermShkDstn self . TranShkDstn = TranShkDstn self . addToTimeVary ( 'IncomeDstn' , 'PermShkDstn' , 'TranShkDstn' ) if not original_time : self . timeRev ( )
Updates this agent s income process based on his own attributes .
12,988
def updateAssetsGrid ( self ) : aXtraGrid = constructAssetsGrid ( self ) self . aXtraGrid = aXtraGrid self . addToTimeInv ( 'aXtraGrid' )
Updates this agent s end - of - period assets grid by constructing a multi - exponentially spaced grid of aXtra values .
12,989
def decode_file ( fname ) : if _debug : decode_file . _debug ( "decode_file %r" , fname ) if not pcap : raise RuntimeError ( "failed to import pcap" ) p = pcap . pcap ( fname ) for i , ( timestamp , data ) in enumerate ( p ) : try : pkt = decode_packet ( data ) if not pkt : continue except Exception as err : if _debug : decode_file . _debug ( " - exception decoding packet %d: %r" , i + 1 , err ) continue pkt . _number = i + 1 pkt . _timestamp = timestamp yield pkt
Given the name of a pcap file open it decode the contents and yield each packet .
12,990
def stop ( * args ) : if _debug : stop . _debug ( "stop" ) global running , taskManager if args : sys . stderr . write ( "===== TERM Signal, %s\n" % time . strftime ( "%d-%b-%Y %H:%M:%S" ) ) sys . stderr . flush ( ) running = False if taskManager and taskManager . trigger : if _debug : stop . _debug ( " - trigger" ) taskManager . trigger . set ( )
Call to stop running may be called with a signum and frame parameter if called as a signal handler .
12,991
def print_stack ( sig , frame ) : if _debug : print_stack . _debug ( "print_stack %r %r" , sig , frame ) global running , deferredFns , sleeptime sys . stderr . write ( "==== USR1 Signal, %s\n" % time . strftime ( "%d-%b-%Y %H:%M:%S" ) ) sys . stderr . write ( "---------- globals\n" ) sys . stderr . write ( " running: %r\n" % ( running , ) ) sys . stderr . write ( " deferredFns: %r\n" % ( deferredFns , ) ) sys . stderr . write ( " sleeptime: %r\n" % ( sleeptime , ) ) sys . stderr . write ( "---------- stack\n" ) traceback . print_stack ( frame ) flist = [ ] f = frame while f . f_back : flist . append ( f ) f = f . f_back flist . reverse ( ) for f in flist : sys . stderr . write ( "---------- frame: %s\n" % ( f , ) ) for k , v in f . f_locals . items ( ) : sys . stderr . write ( " %s: %r\n" % ( k , v ) ) sys . stderr . flush ( )
Signal handler to print a stack trace and some interesting values .
12,992
def compose_capability ( base , * classes ) : if _debug : compose_capability . _debug ( "compose_capability %r %r" , base , classes ) if not issubclass ( base , Collector ) : raise TypeError ( "base must be a subclass of Collector" ) for cls in classes : if not issubclass ( cls , Capability ) : raise TypeError ( "%s is not a Capability subclass" % ( cls , ) ) bases = ( base , ) + classes name = base . __name__ for cls in classes : name += '+' + cls . __name__ return type ( name , bases , { } )
Create a new class starting with the base and adding capabilities .
12,993
def add_capability ( base , * classes ) : if _debug : add_capability . _debug ( "add_capability %r %r" , base , classes ) if not issubclass ( base , Collector ) : raise TypeError ( "base must be a subclass of Collector" ) for cls in classes : if not issubclass ( cls , Capability ) : raise TypeError ( "%s is not a Capability subclass" % ( cls , ) ) base . __bases__ += classes for cls in classes : base . __name__ += '+' + cls . __name__
Add capabilites to an existing base all objects get the additional functionality but don t get inited . Use with great care!
12,994
def _search_capability ( self , base ) : if _debug : Collector . _debug ( "_search_capability %r" , base ) rslt = [ ] for cls in base . __bases__ : if issubclass ( cls , Collector ) : map ( rslt . append , self . _search_capability ( cls ) ) elif issubclass ( cls , Capability ) : rslt . append ( cls ) if _debug : Collector . _debug ( " - rslt: %r" , rslt ) return rslt
Given a class return a list of all of the derived classes that are themselves derived from Capability .
12,995
def capability_functions ( self , fn ) : if _debug : Collector . _debug ( "capability_functions %r" , fn ) fns = [ ] for cls in self . capabilities : xfn = getattr ( cls , fn , None ) if _debug : Collector . _debug ( " - cls, xfn: %r, %r" , cls , xfn ) if xfn : fns . append ( ( getattr ( cls , '_zindex' , None ) , xfn ) ) fns . sort ( key = lambda v : v [ 0 ] ) if _debug : Collector . _debug ( " - fns: %r" , fns ) for xindx , xfn in fns : if _debug : Collector . _debug ( " - yield xfn: %r" , xfn ) yield xfn
This generator yields functions that match the requested capability sorted by z - index .
12,996
def add_capability ( self , cls ) : if _debug : Collector . _debug ( "add_capability %r" , cls ) bases = ( self . __class__ , cls ) if _debug : Collector . _debug ( " - bases: %r" , bases ) self . capabilities . append ( cls ) newtype = type ( self . __class__ . __name__ + '+' + cls . __name__ , bases , { } ) self . __class__ = newtype if hasattr ( cls , '__init__' ) : if _debug : Collector . _debug ( " - calling %r.__init__" , cls ) cls . __init__ ( self )
Add a capability to this object .
12,997
def _merge ( * args ) : return re . compile ( r'^' + r'[/-]' . join ( args ) + r'(?:\s+' + _dow + ')?$' )
Create a composite pattern and compile it .
12,998
def encode ( self , pdu ) : if ( self . tagClass == Tag . contextTagClass ) : data = 0x08 elif ( self . tagClass == Tag . openingTagClass ) : data = 0x0E elif ( self . tagClass == Tag . closingTagClass ) : data = 0x0F else : data = 0x00 if ( self . tagNumber < 15 ) : data += ( self . tagNumber << 4 ) else : data += 0xF0 if ( self . tagLVT < 5 ) : data += self . tagLVT else : data += 0x05 pdu . put ( data ) if ( self . tagNumber >= 15 ) : pdu . put ( self . tagNumber ) if ( self . tagLVT >= 5 ) : if ( self . tagLVT <= 253 ) : pdu . put ( self . tagLVT ) elif ( self . tagLVT <= 65535 ) : pdu . put ( 254 ) pdu . put_short ( self . tagLVT ) else : pdu . put ( 255 ) pdu . put_long ( self . tagLVT ) pdu . put_data ( self . tagData )
Encode a tag on the end of the PDU .
12,999
def app_to_object ( self ) : if self . tagClass != Tag . applicationTagClass : raise ValueError ( "application tag required" ) klass = self . _app_tag_class [ self . tagNumber ] if not klass : return None return klass ( self )
Return the application object encoded by the tag .