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 ...
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 . Me...
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...
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 . Me...
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 [ th...
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 ( EndOfP...
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 . E...
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 . m...
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 * s...
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 = ( ...
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...
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 ( ...
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 . LivP...
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_...
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 ) ) n...
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 = ShkPrbs...
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 )...
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...
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 ...
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 =...
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 . DeprFa...
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...
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...
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 ( ...
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 ...
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...
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...
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 . T...
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 . m...
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 ] ) sl...
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 ...
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 ] [ EventDra...
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 AggVa...
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 ( approxMean...
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 ( s...
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 ] ) Mr...
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 ( 'getKYratioD...
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_cente...
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 targ...
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...
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...
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 se...
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...
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 ) ) ,...
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 (...
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 ) ) *...
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 =...
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 ( EndOfPr...
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 th...
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 s...
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 ( 'pLvl...
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 ...
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 = cu...
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 )...
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 =...
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 = pNe...
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 ge...
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 ( aXtraMi...
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...
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 ,...
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 . IncomeD...
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 ) ) ) . transp...
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 ....
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 ( vNrm...
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 ...
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 yie...
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 >=...
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 . bNrmNo...
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' , 'Per...
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 ...
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" )...
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 ( " runnin...
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...
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 Capab...
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 : Colle...
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 ) , x...
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 ....
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 += 0xF...
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 .