code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Makes a quasi-bilinear interpolation to represent the (unconstrained)
consumption function.
Parameters
----------
mLvl : np.array
Market resource points for interpolation.
pLvl : np.array
Persistent income level points for interpolatio... | def makeLinearcFunc(self,mLvl,pLvl,cLvl) | Makes a quasi-bilinear interpolation to represent the (unconstrained)
consumption function.
Parameters
----------
mLvl : np.array
Market resource points for interpolation.
pLvl : np.array
Persistent income level points for interpolation.
cLvl : np... | 3.659449 | 2.615953 | 1.398897 |
'''
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.
Parameters
----------
mLvl : np.array
Market resource points for interpolation... | def makeCubiccFunc(self,mLvl,pLvl,cLvl) | 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.
Parameters
----------
mLvl : np.array
Market resource points for interpolation.
pLvl : np.... | 4.073285 | 3.144272 | 1.295462 |
'''
Take a solution and add human wealth and the bounding MPCs to it.
Parameters
----------
solution : ConsumerSolution
The solution to this period's consumption-saving problem.
Returns:
----------
solution : ConsumerSolution
The ... | def addMPCandHumanWealth(self,solution) | Take a solution and add human wealth and the bounding MPCs to it.
Parameters
----------
solution : ConsumerSolution
The solution to this period's consumption-saving problem.
Returns:
----------
solution : ConsumerSolution
The solution to this per... | 6.246112 | 3.547044 | 1.760935 |
'''
Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include ... | def addvPPfunc(self,solution) | Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include the
cons... | 6.948669 | 1.915051 | 3.628452 |
'''
Solves a one period consumption saving problem with risky income, with
persistent income explicitly tracked as a state variable.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period... | def solve(self) | Solves a one period consumption saving problem with risky income, with
persistent income explicitly tracked as a state variable.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem, including ... | 5.912169 | 2.349797 | 2.516034 |
'''
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None
'''
self.solution_terminal.vFunc = ValueFunc2D(self.cFunc_te... | def updateSolutionTerminal(self) | Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None | 4.55188 | 3.131093 | 1.453767 |
'''
A dummy method that creates a trivial pLvlNextFunc attribute that has
no persistent income dynamics. This method should be overwritten by
subclasses in order to make (e.g.) an AR1 income process.
Parameters
----------
None
Returns
-------
... | def updatepLvlNextFunc(self) | A dummy method that creates a trivial pLvlNextFunc attribute that has
no persistent income dynamics. This method should be overwritten by
subclasses in order to make (e.g.) an AR1 income process.
Parameters
----------
None
Returns
-------
None | 6.956605 | 2.416557 | 2.878726 |
'''
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... | def installRetirementFunc(self) | 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 upda... | 6.291246 | 1.497308 | 4.201704 |
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameter... | def simBirth(self,which_agents) | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------... | 3.887403 | 1.840313 | 2.112359 |
'''
Calculates updated values of normalized market resources and persistent income level for each
agent. Uses pLvlNow, aLvlNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None
'''
aLvlPrev = self.aLvlNow
... | def getStates(self) | Calculates updated values of normalized market resources and persistent income level for each
agent. Uses pLvlNow, aLvlNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None | 4.768418 | 2.718127 | 1.754303 |
'''
Calculates consumption for each consumer of this type using the consumption functions.
Parameters
----------
None
Returns
-------
None
'''
cLvlNow = np.zeros(self.AgentCount) + np.nan
MPCnow = np.zeros(self.AgentCount) + np.na... | def getControls(self) | Calculates consumption for each consumer of this type using the consumption functions.
Parameters
----------
None
Returns
-------
None | 3.639828 | 2.575837 | 1.413066 |
'''
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.
Par... | def updatepLvlNextFunc(self) | 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.
Parameters
----... | 6.519608 | 2.412169 | 2.7028 |
'''
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.
Parameters
---... | def updatepLvlNextFunc(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.
Parameters
----------
None... | 6.205222 | 2.739169 | 2.265367 |
'''
Generate arrays of mean one lognormal draws. The sigma input can be a number
or list-like. If a number, output is a length N array of draws from the
lognormal distribution with standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array of draws from the
... | def drawMeanOneLognormal(N, sigma=1.0, seed=0) | Generate arrays of mean one lognormal draws. The sigma input can be a number
or list-like. If a number, output is a length N array of draws from the
lognormal distribution with standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array of draws from the
lognorma... | 3.617318 | 1.689505 | 2.141053 |
'''
Generate arrays of mean one lognormal draws. The sigma input can be a number
or list-like. If a number, output is a length N array of draws from the
lognormal distribution with standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array of draws from the
... | def drawLognormal(N,mu=0.0,sigma=1.0,seed=0) | Generate arrays of mean one lognormal draws. The sigma input can be a number
or list-like. If a number, output is a length N array of draws from the
lognormal distribution with standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array of draws from the
lognorma... | 3.216934 | 1.564845 | 2.055753 |
'''
Generate arrays of normal draws. The mu and sigma inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the normal
distribution with mean mu and standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array with draws f... | def drawNormal(N, mu=0.0, sigma=1.0, seed=0) | Generate arrays of normal draws. The mu and sigma inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the normal
distribution with mean mu and standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array with draws from the
... | 3.318584 | 1.591875 | 2.084701 |
'''
Generate arrays of Weibull draws. The scale and shape inputs can be
numbers or list-likes. If a number, output is a length N array of draws from
the Weibull distribution with the given scale and shape. If a list, output
is a length T list whose t-th entry is a length N array with draws from th... | def drawWeibull(N, scale=1.0, shape=1.0, seed=0) | Generate arrays of Weibull draws. The scale and shape inputs can be
numbers or list-likes. If a number, output is a length N array of draws from
the Weibull distribution with the given scale and shape. If a list, output
is a length T list whose t-th entry is a length N array with draws from the
Weibul... | 3.798846 | 1.586549 | 2.394408 |
'''
Generate arrays of uniform draws. The bot and top inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the
uniform distribution on [bot,top]. If a list, output is a length T list
whose t-th entry is a length N array with draws from the uniform distribution... | def drawUniform(N, bot=0.0, top=1.0, seed=0) | Generate arrays of uniform draws. The bot and top inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the
uniform distribution on [bot,top]. If a list, output is a length T list
whose t-th entry is a length N array with draws from the uniform distribution
on [bot... | 3.5444 | 1.59175 | 2.226731 |
'''
Generates arrays of booleans drawn from a simple Bernoulli distribution.
The input p can be a float or a list-like of floats; its length T determines
the number of entries in the output. The t-th entry of the output is an
array of N booleans which are True with probability p[t] and False otherw... | def drawBernoulli(N,p=0.5,seed=0) | Generates arrays of booleans drawn from a simple Bernoulli distribution.
The input p can be a float or a list-like of floats; its length T determines
the number of entries in the output. The t-th entry of the output is an
array of N booleans which are True with probability p[t] and False otherwise.
Ar... | 4.445632 | 1.720216 | 2.584345 |
'''
Simulates N draws from a discrete distribution with probabilities P and outcomes X.
Parameters
----------
P : np.array
A list of probabilities of outcomes.
X : np.array
A list of discrete outcomes.
N : int
Number of draws to simulate.
exact_match : boolean
... | def drawDiscrete(N,P=[1.0],X=[0.0],exact_match=False,seed=0) | Simulates N draws from a discrete distribution with probabilities P and outcomes X.
Parameters
----------
P : np.array
A list of probabilities of outcomes.
X : np.array
A list of discrete outcomes.
N : int
Number of draws to simulate.
exact_match : boolean
Whethe... | 4.295944 | 2.343927 | 1.832798 |
'''
Calculates the proportion of punks in the population, given data from each type.
Parameters
----------
pNow : [np.array]
List of arrays of binary data, representing the fashion choice of each
agent in each type of this market (0=jock, 1=punk).
pop_size : [int]
List w... | def calcPunkProp(sNow) | Calculates the proportion of punks in the population, given data from each type.
Parameters
----------
pNow : [np.array]
List of arrays of binary data, representing the fashion choice of each
agent in each type of this market (0=jock, 1=punk).
pop_size : [int]
List with the numb... | 10.457702 | 2.319917 | 4.507791 |
'''
Calculates a new approximate dynamic rule for the evolution of the proportion
of punks as a linear function and a "shock width".
Parameters
----------
pNow : [float]
List describing the history of the proportion of punks in the population.
Returns
-------
(unnamed) : Fa... | def calcFashionEvoFunc(pNow) | Calculates a new approximate dynamic rule for the evolution of the proportion
of punks as a linear function and a "shock width".
Parameters
----------
pNow : [float]
List describing the history of the proportion of punks in the population.
Returns
-------
(unnamed) : FashionEvoFunc... | 5.435077 | 2.491565 | 2.18139 |
'''
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, pNextSlop... | def updateEvolution(self) | 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,
... | 9.733462 | 1.814819 | 5.363323 |
'''
Updates the non-primitive objects needed for solution, using primitive
attributes. This includes defining a "utility from conformity" function
conformUtilityFunc, a grid of population punk proportions, and an array
of future punk proportions (for each value in the grid). Re... | def update(self) | Updates the non-primitive objects needed for solution, using primitive
attributes. This includes defining a "utility from conformity" function
conformUtilityFunc, a grid of population punk proportions, and an array
of future punk proportions (for each value in the grid). Results are
st... | 11.52964 | 2.149267 | 5.364452 |
'''
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.
'''
self.resetRNG()
sNow = np.zeros(self.pop_size)
Shk = self.RNG.rand(self.pop_... | def reset(self) | 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. | 8.37489 | 3.58226 | 2.337879 |
'''
Unpack the behavioral and value functions for more parsimonious access.
Parameters
----------
none
Returns
-------
none
'''
self.switchFuncPunk = self.solution[0].switchFuncPunk
self.switchFuncJock = self.solution[0].switchFun... | def postSolve(self) | Unpack the behavioral and value functions for more parsimonious access.
Parameters
----------
none
Returns
-------
none | 5.750748 | 3.179577 | 1.808652 |
'''
Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
none
Returns
-------
n... | def simOnePrd(self) | Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
none
Returns
-------
none | 6.273422 | 2.892198 | 2.169084 |
# NOTE: assumes that the first segment is in fact increasing (forced in EGM
# by augmentation with the constrained segment).
# elements in common grid g
# Identify index intervals of falling and rising regions
# We need these to construct the upper envelope because we need to discard
# sol... | def calcSegments(x, v) | Find index vectors `rise` and `fall` such that `rise` holds the indeces `i`
such that x[i+1]>x[i] and `fall` holds indeces `j` such that either
- x[j+1] < x[j] or,
- x[j]>x[j-1] and v[j]<v[j-1].
The vectors are essential to the DCEGM algorithm, as they definite the
relevant intervals to be used to ... | 10.151403 | 9.274071 | 1.094601 |
'''
Solves a single period consumption-saving problem for a consumer with perfect foresight.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
DiscFac : float
Intertemporal discount factor for future utility.
LivPrb : fl... | def solvePerfForesight(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac) | Solves a single period consumption-saving problem for a consumer with perfect foresight.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
DiscFac : float
Intertemporal discount factor for future utility.
LivPrb : float
... | 1.91132 | 1.304692 | 1.464959 |
'''
Applies a flat income tax rate to all employed income states during the working
period of life (those before T_retire). Time runs forward in this function.
Parameters
----------
IncomeDstn : [income distributions]
The discrete approximation to the income distribution in each time p... | def applyFlatIncomeTax(IncomeDstn,tax_rate,T_retire,unemployed_indices=[],transitory_index=2) | Applies a flat income tax rate to all employed income states during the working
period of life (those before T_retire). Time runs forward in this function.
Parameters
----------
IncomeDstn : [income distributions]
The discrete approximation to the income distribution in each time period.
t... | 3.324032 | 1.373449 | 2.420207 |
'''
Constructs the base grid of post-decision states, representing end-of-period
assets above the absolute minimum.
All parameters are passed as attributes of the single input parameters. The
input can be an instance of a ConsumerType, or a custom Parameters class.
Parameters
----------
... | def constructAssetsGrid(parameters) | Constructs the base grid of post-decision states, representing end-of-period
assets above the absolute minimum.
All parameters are passed as attributes of the single input parameters. The
input can be an instance of a ConsumerType, or a custom Parameters class.
Parameters
----------
aXtraMin:... | 4.254084 | 2.053037 | 2.072093 |
'''
Appends one solution to another to create a ConsumerSolution whose
attributes are lists. Used in ConsMarkovModel, where we append solutions
*conditional* on a particular value of a Markov state to each other in
order to get the entire solution.
Parameters
--... | def appendSolution(self,new_solution) | Appends one solution to another to create a ConsumerSolution whose
attributes are lists. Used in ConsMarkovModel, where we append solutions
*conditional* on a particular value of a Markov state to each other in
order to get the entire solution.
Parameters
----------
new... | 4.822947 | 2.297775 | 2.098964 |
'''
Saves necessary parameters as attributes of self for use by other methods.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
DiscFac : float
Intertemporal discount factor for future utilit... | def assignParameters(self,solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac) | Saves necessary parameters as attributes of self for use by other methods.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
DiscFac : float
Intertemporal discount factor for future utility.
LivPrb : ... | 1.773016 | 1.275997 | 1.389515 |
'''
Defines CRRA utility function for this period (and its derivatives),
saving them as attributes of self for other methods to use.
Parameters
----------
none
Returns
-------
none
'''
self.u = lambda c : utility(c,gam=self.CRRA... | def defUtilityFuncs(self) | Defines CRRA utility function for this period (and its derivatives),
saving them as attributes of self for other methods to use.
Parameters
----------
none
Returns
-------
none | 5.128199 | 2.452647 | 2.090884 |
'''
Defines the value and marginal value function for this period.
Parameters
----------
none
Returns
-------
none
'''
MPCnvrs = self.MPC**(-self.CRRA/(1.0-self.CRRA))
vFuncNvrs = LinearInterp(np.array([self.mNrmMin, self.... | def defValueFuncs(self) | Defines the value and marginal value function for this period.
Parameters
----------
none
Returns
-------
none | 5.631768 | 3.783353 | 1.488565 |
'''
Makes the (linear) consumption function for this period.
Parameters
----------
none
Returns
-------
none
'''
# Calculate human wealth this period (and lower bound of m)
self.hNrmNow = (self.PermGroFac/self.Rfree)*(self.solutio... | def makePFcFunc(self) | Makes the (linear) consumption function for this period.
Parameters
----------
none
Returns
-------
none | 5.9626 | 5.188555 | 1.149183 |
'''
Finds steady state (normalized) market resources and adds it to the
solution. This is the level of market resources such that the expectation
of market resources in the next period is unchanged. This value doesn't
necessarily exist.
Parameters
----------
... | def addSSmNrm(self,solution) | Finds steady state (normalized) market resources and adds it to the
solution. This is the level of market resources such that the expectation
of market resources in the next period is unchanged. This value doesn't
necessarily exist.
Parameters
----------
solution : Con... | 6.99545 | 3.62823 | 1.928061 |
'''
Solves the one period perfect foresight consumption-saving problem.
Parameters
----------
none
Returns
-------
solution : ConsumerSolution
The solution to this period's problem.
'''
self.defUtilityFuncs()
self.Disc... | def solve(self) | Solves the one period perfect foresight consumption-saving problem.
Parameters
----------
none
Returns
-------
solution : ConsumerSolution
The solution to this period's problem. | 5.513844 | 3.623473 | 1.521702 |
'''
Assigns period parameters as attributes of self for use by other methods
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncomeDstn : [np.array]
A list containing three arrays of floats,... | def assignParameters(self,solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,
PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool) | Assigns period parameters as attributes of self for use by other methods
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncomeDstn : [np.array]
A list containing three arrays of floats, representing a disc... | 1.715214 | 1.252936 | 1.368956 |
'''
Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use.
Parameters
----------
none
Returns
-------
none
'''
ConsPerfForesight... | def defUtilityFuncs(self) | Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use.
Parameters
----------
none
Returns
-------
none | 4.969833 | 2.760157 | 1.800562 |
'''
Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function
(etc), the probability of getting the worst income shock next... | def setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac) | Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function
(etc), the probability of getting the worst income shock next period,
the... | 2.797965 | 1.941064 | 1.44146 |
'''
Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self. Uses the artificial and natural borrowing constraints.
Parameters
----------
BoroCnstArt : float or None
Borrowing constraint for the minimum allowable ass... | def defBoroCnst(self,BoroCnstArt) | Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self. Uses the artificial and natural borrowing constraints.
Parameters
----------
BoroCnstArt : float or None
Borrowing constraint for the minimum allowable assets to end the
... | 4.633626 | 3.059321 | 1.514593 |
'''
Perform preparatory work before calculating the unconstrained consumption
function.
Parameters
----------
none
Returns
-------
none
'''
self.setAndUpdateValues(self.solution_next,self.IncomeDstn,self.LivPrb,self.DiscFac)
... | def prepareToSolve(self) | Perform preparatory work before calculating the unconstrained consumption
function.
Parameters
----------
none
Returns
-------
none | 9.133774 | 4.472661 | 2.042134 |
'''
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.
Parameters
---------... | def prepareToCalcEndOfPrdvP(self) | 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.
Parameters
----------
none
... | 4.585052 | 3.122085 | 1.468587 |
'''
Calculate end-of-period marginal value of assets at each point in aNrmNow.
Does so by taking a weighted sum of next period marginal values across
income shocks (in a preconstructed grid self.mNrmNext).
Parameters
----------
none
Returns
-----... | def calcEndOfPrdvP(self) | Calculate end-of-period marginal value of assets at each point in aNrmNow.
Does so by taking a weighted sum of next period marginal values across
income shocks (in a preconstructed grid self.mNrmNext).
Parameters
----------
none
Returns
-------
EndOfPrdv... | 5.935201 | 2.237464 | 2.652647 |
'''
Finds interpolation points (c,m) for the consumption function.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrmNow : np.array
Array of end-of-period asset values that yield the marginal values
... | def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow) | Finds interpolation points (c,m) for the consumption function.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrmNow : np.array
Array of end-of-period asset values that yield the marginal values
in EndOfPrdvP.
... | 3.480919 | 2.206166 | 1.577814 |
'''
Constructs a basic solution for this period, including the consumption
function and marginal value function.
Parameters
----------
cNrm : np.array
(Normalized) consumption points for interpolation.
mNrm : np.array
(Normalized) correspo... | def usePointsForInterpolation(self,cNrm,mNrm,interpolator) | Constructs a basic solution for this period, including the consumption
function and marginal value function.
Parameters
----------
cNrm : np.array
(Normalized) consumption points for interpolation.
mNrm : np.array
(Normalized) corresponding market resourc... | 4.321769 | 2.110949 | 2.047311 |
'''
Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrm : np.array
Array of end-of-period asset... | def makeBasicSolution(self,EndOfPrdvP,aNrm,interpolator) | Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrm : np.array
Array of end-of-period asset values that yield t... | 4.120577 | 1.645229 | 2.504562 |
'''
Take a solution and add human wealth and the bounding MPCs to it.
Parameters
----------
solution : ConsumerSolution
The solution to this period's consumption-saving problem.
Returns:
----------
solution : ConsumerSolution
The ... | def addMPCandHumanWealth(self,solution) | Take a solution and add human wealth and the bounding MPCs to it.
Parameters
----------
solution : ConsumerSolution
The solution to this period's consumption-saving problem.
Returns:
----------
solution : ConsumerSolution
The solution to this per... | 4.003003 | 1.824566 | 2.193947 |
'''
Makes a linear interpolation to represent the (unconstrained) consumption function.
Parameters
----------
mNrm : np.array
Corresponding market resource points for interpolation.
cNrm : np.array
Consumption points for interpolation.
Re... | def makeLinearcFunc(self,mNrm,cNrm) | Makes a linear interpolation to represent the (unconstrained) consumption function.
Parameters
----------
mNrm : np.array
Corresponding market resource points for interpolation.
cNrm : np.array
Consumption points for interpolation.
Returns
------... | 4.811033 | 2.018859 | 2.383045 |
'''
Solves a one period consumption saving problem with risky income.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem.
'''
aNrm = self.prepareToCalcEndOfPrdvP... | def solve(self) | Solves a one period consumption saving problem with risky income.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem. | 8.126563 | 4.458921 | 1.82254 |
'''
Makes a cubic spline interpolation of the unconstrained consumption
function for this period.
Parameters
----------
mNrm : np.array
Corresponding market resource points for interpolation.
cNrm : np.array
Consumption points for interpol... | def makeCubiccFunc(self,mNrm,cNrm) | Makes a cubic spline interpolation of the unconstrained consumption
function for this period.
Parameters
----------
mNrm : np.array
Corresponding market resource points for interpolation.
cNrm : np.array
Consumption points for interpolation.
Retu... | 4.977262 | 3.480633 | 1.429988 |
'''
Construct the end-of-period value function for this period, storing it
as an attribute of self for use by other methods.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal value of assets corresponding to the
asset val... | def makeEndOfPrdvFunc(self,EndOfPrdvP) | Construct the end-of-period value function for this period, storing it
as an attribute of self for use by other methods.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal value of assets corresponding to the
asset values in self.aNrmNow.... | 4.130639 | 3.223075 | 1.281583 |
'''
Creates the value function for this period and adds it to the solution.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, likely including the
consumption function, marginal value function, etc.
EndO... | def addvFunc(self,solution,EndOfPrdvP) | Creates the value function for this period and adds it to the solution.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, likely including the
consumption function, marginal value function, etc.
EndOfPrdvP : np.array
... | 6.249227 | 1.480083 | 4.222214 |
'''
Creates the value function for this period, defined over market resources m.
self must have the attribute EndOfPrdvFunc in order to execute.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include t... | def makevFunc(self,solution) | Creates the value function for this period, defined over market resources m.
self must have the attribute EndOfPrdvFunc in order to execute.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include the
consu... | 4.06629 | 2.52261 | 1.611938 |
'''
Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include ... | def addvPPfunc(self,solution) | Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include the
cons... | 6.764294 | 1.820139 | 3.71636 |
'''
Solves the single period consumption-saving problem using the method of
endogenous gridpoints. Solution includes a consumption function cFunc
(using cubic or linear splines), a marginal value function vPfunc, a min-
imum acceptable level of normalized market resources mNrmMi... | def solve(self) | Solves the single period consumption-saving problem using the method of
endogenous gridpoints. Solution includes a consumption function cFunc
(using cubic or linear splines), a marginal value function vPfunc, a min-
imum acceptable level of normalized market resources mNrmMin, normalized
... | 5.914674 | 2.792468 | 2.118081 |
'''
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 ... | def prepareToCalcEndOfPrdvP(self) | 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
diff... | 4.433738 | 3.318778 | 1.335955 |
'''
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
none
Returns
-------
none
'''
self.solution_terminal.vFunc = ValueFunc(self.cFunc_te... | def updateSolutionTerminal(self) | Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
none
Returns
-------
none | 4.439115 | 2.357926 | 1.882635 |
'''
"Unpacks" the consumption functions into their own field for easier access.
After the model has been solved, the consumption functions reside in the
attribute cFunc of each element of ConsumerType.solution. This method
creates a (time varying) attribute cFunc that contains a... | def unpackcFunc(self) | "Unpacks" the consumption functions into their own field for easier access.
After the model has been solved, the consumption functions reside in the
attribute cFunc of each element of ConsumerType.solution. This method
creates a (time varying) attribute cFunc that contains a list of consumption... | 8.837524 | 1.88099 | 4.698336 |
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and permanent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters... | def simBirth(self,which_agents) | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and permanent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
... | 4.289337 | 2.140144 | 2.004228 |
'''
Determines which agents die this period and must be replaced. Uses the sequence in LivPrb
to determine survival probabilities for each agent.
Parameters
----------
None
Returns
-------
which_agents : np.array(bool)
Boolean array ... | def simDeath(self) | Determines which agents die this period and must be replaced. Uses the sequence in LivPrb
to determine survival probabilities for each agent.
Parameters
----------
None
Returns
-------
which_agents : np.array(bool)
Boolean array of size AgentCount i... | 6.245626 | 3.338663 | 1.870697 |
'''
Finds permanent and transitory income "shocks" for each agent this period. As this is a
perfect foresight model, there are no stochastic shocks: PermShkNow = PermGroFac for each
agent (according to their t_cycle) and TranShkNow = 1.0 for all agents.
Parameters
-----... | def getShocks(self) | Finds permanent and transitory income "shocks" for each agent this period. As this is a
perfect foresight model, there are no stochastic shocks: PermShkNow = PermGroFac for each
agent (according to their t_cycle) and TranShkNow = 1.0 for all agents.
Parameters
----------
None
... | 5.643047 | 1.843069 | 3.061766 |
'''
Calculates updated values of normalized market resources and permanent income level for each
agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None
'''
pLvlPrev = self.pLvlNow
... | def getStates(self) | Calculates updated values of normalized market resources and permanent income level for each
agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None | 5.318743 | 3.113591 | 1.708234 |
'''
Calculates end-of-period assets for each consumer of this type.
Parameters
----------
None
Returns
-------
None
'''
self.aNrmNow = self.mNrmNow - self.cNrmNow
self.aLvlNow = self.aNrmNow*self.pLvlNow # Useful in some cases t... | def getPostStates(self) | Calculates end-of-period assets for each consumer of this type.
Parameters
----------
None
Returns
-------
None | 8.736976 | 4.388789 | 1.990749 |
'''
This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human wealth condition (FHWC) and finite value of
autarky co... | def checkConditions(self,verbose=False,verbose_reference=False,public_call=False) | This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human wealth condition (FHWC) and finite value of
autarky condition (FVAC). Thes... | 4.855731 | 2.448414 | 1.983214 |
'''
Updates this agent's income process based on his own attributes.
Parameters
----------
none
Returns:
-----------
none
'''
original_time = self.time_flow
self.timeFwd()
IncomeDstn, PermShkDstn, TranShkDstn = constructLo... | def updateIncomeProcess(self) | Updates this agent's income process based on his own attributes.
Parameters
----------
none
Returns:
-----------
none | 4.987944 | 3.625193 | 1.375911 |
'''
Updates this agent's end-of-period assets grid by constructing a multi-
exponentially spaced grid of aXtra values.
Parameters
----------
none
Returns
-------
none
'''
aXtraGrid = constructAssetsGrid(self)
self.aXtraGri... | def updateAssetsGrid(self) | Updates this agent's end-of-period assets grid by constructing a multi-
exponentially spaced grid of aXtra values.
Parameters
----------
none
Returns
-------
none | 10.420244 | 2.756361 | 3.780436 |
'''
Calculate human wealth plus minimum and maximum MPC in an infinite
horizon model with only one period repeated indefinitely. Store results
as attributes of self. Human wealth is the present discounted value of
expected future income after receiving income this period, ignor... | def calcBoundingValues(self) | Calculate human wealth plus minimum and maximum MPC in an infinite
horizon model with only one period repeated indefinitely. Store results
as attributes of self. Human wealth is the present discounted value of
expected future income after receiving income this period, ignoring mort-
al... | 3.864788 | 2.307534 | 1.674856 |
'''
Returns an array of size self.AgentCount with self.Rboro or self.Rsave in each entry, based
on whether self.aNrmNow >< 0.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free... | def getRfree(self) | Returns an array of size self.AgentCount with self.Rboro or self.Rsave in each entry, based
on whether self.aNrmNow >< 0.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free interest rate for e... | 6.088835 | 1.488515 | 4.090542 |
if _debug: decode_file._debug("decode_file %r", fname)
if not pcap:
raise RuntimeError("failed to import pcap")
# create a pcap object, reading from the file
p = pcap.pcap(fname)
# loop through the packets
for i, (timestamp, data) in enumerate(p):
try:
pkt = d... | def decode_file(fname) | Given the name of a pcap file, open it, decode the contents and yield each packet. | 3.357666 | 3.158957 | 1.062904 |
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
# trigger the task manager event
if taskManager and taskManager.trigger:
if _deb... | def stop(*args) | Call to stop running, may be called with a signum and frame
parameter if called as a signal handler. | 5.790973 | 5.644131 | 1.026017 |
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.writ... | def print_stack(sig, frame) | Signal handler to print a stack trace and some interesting values. | 2.734658 | 2.645175 | 1.033829 |
if _debug: compose_capability._debug("compose_capability %r %r", base, classes)
# make sure the base is a Collector
if not issubclass(base, Collector):
raise TypeError("base must be a subclass of Collector")
# make sure you only add capabilities
for cls in classes:
if not issu... | def compose_capability(base, *classes) | Create a new class starting with the base and adding capabilities. | 3.036524 | 2.834877 | 1.071131 |
if _debug: add_capability._debug("add_capability %r %r", base, classes)
# start out with a collector
if not issubclass(base, Collector):
raise TypeError("base must be a subclass of Collector")
# make sure you only add capabilities
for cls in classes:
if not issubclass(cls, Cap... | def add_capability(base, *classes) | Add capabilites to an existing base, all objects get the additional
functionality, but don't get inited. Use with great care! | 3.4211 | 3.440614 | 0.994328 |
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)
... | def _search_capability(self, base) | Given a class, return a list of all of the derived classes that
are themselves derived from Capability. | 2.949752 | 2.758575 | 1.069303 |
if _debug: Collector._debug("capability_functions %r", fn)
# build a list of functions to call
fns = []
for cls in self.capabilities:
xfn = getattr(cls, fn, None)
if _debug: Collector._debug(" - cls, xfn: %r, %r", cls, xfn)
if xfn:
... | def capability_functions(self, fn) | This generator yields functions that match the
requested capability sorted by z-index. | 2.565918 | 2.294594 | 1.118245 |
if _debug: Collector._debug("add_capability %r", cls)
# the new type has everything the current one has plus this new one
bases = (self.__class__, cls)
if _debug: Collector._debug(" - bases: %r", bases)
# save this additional class
self.capabilities.append(c... | def add_capability(self, cls) | Add a capability to this object. | 4.006429 | 3.817822 | 1.049402 |
return re.compile(r'^' + r'[/-]'.join(args) + r'(?:\s+' + _dow + ')?$') | def _merge(*args) | Create a composite pattern and compile it. | 14.515125 | 11.318236 | 1.282455 |
if isinstance(tdata, bytearray):
tdata = bytes(tdata)
elif not isinstance(tdata, bytes):
raise TypeError("tag data must be bytes or bytearray")
self.tagClass = tclass
self.tagNumber = tnum
self.tagLVT = tlvt
self.tagData = tdata | def set(self, tclass, tnum, tlvt=0, tdata=b'') | set the values of the tag. | 2.430676 | 2.246866 | 1.081807 |
# check for special encoding
if (self.tagClass == Tag.contextTagClass):
data = 0x08
elif (self.tagClass == Tag.openingTagClass):
data = 0x0E
elif (self.tagClass == Tag.closingTagClass):
data = 0x0F
else:
data = 0x00
... | def encode(self, pdu) | Encode a tag on the end of the PDU. | 2.806519 | 2.7616 | 1.016266 |
if self.tagClass != Tag.applicationTagClass:
raise ValueError("application tag required")
# get the class to build
klass = self._app_tag_class[self.tagNumber]
if not klass:
return None
# build an object, tell it to decode this tag, and return it... | def app_to_object(self) | Return the application object encoded by the tag. | 7.151375 | 5.722186 | 1.249763 |
if self.tagList:
tag = self.tagList[0]
del self.tagList[0]
else:
tag = None
return tag | def Pop(self) | Remove the tag from the front of the list and return it. | 3.878966 | 2.735831 | 1.417839 |
# forward pass
i = 0
while i < len(self.tagList):
tag = self.tagList[i]
# skip application stuff
if tag.tagClass == Tag.applicationTagClass:
pass
# check for context encoded atomic value
elif tag.tagClass == T... | def get_context(self, context) | Return a tag or a list of tags context encoded. | 3.868897 | 3.64959 | 1.060091 |
while pdu.pduData:
self.tagList.append( Tag(pdu) ) | def decode(self, pdu) | decode the tags from a PDU. | 11.729192 | 8.493212 | 1.381008 |
try:
return cls(arg).value
except (ValueError, TypeError):
raise InvalidParameterDatatype("%s coerce error" % (cls.__name__,)) | def coerce(cls, arg) | Given an arg, return the appropriate value given the class. | 7.038397 | 6.733037 | 1.045352 |
if isinstance(arg, list):
allInts = allStrings = True
for elem in arg:
allInts = allInts and ((elem == 0) or (elem == 1))
allStrings = allStrings and elem in cls.bitNames
if allInts or allStrings:
return True
r... | def is_valid(cls, arg) | Return True if arg is valid value for the class. | 4.235445 | 4.159275 | 1.018313 |
items = self.enumerations.items()
items.sort(lambda a, b: self.cmp(a[1], b[1]))
# last item has highest value
rslt = [None] * (items[-1][1] + 1)
# map the values
for key, value in items:
rslt[value] = key
# return the result
return ... | def keylist(self) | Return a list of names in order by value. | 4.392348 | 3.709709 | 1.184014 |
# rip apart the value
year, month, day, day_of_week = self.value
# assume the worst
day_of_week = 255
# check for special values
if year == 255:
pass
elif month in _special_mon_inv:
pass
elif day in _special_day_inv:
... | def CalcDayOfWeek(self) | Calculate the correct day of the week. | 3.296285 | 3.275299 | 1.006407 |
if when is None:
when = _TaskManager().get_time()
tup = time.localtime(when)
self.value = (tup[0]-1900, tup[1], tup[2], tup[6] + 1)
return self | def now(self, when=None) | Set the current value to the correct tuple based on the seconds
since the epoch. If 'when' is not provided, get the current time
from the task manager. | 5.908013 | 4.37834 | 1.349373 |
objType, objInstance = self.value
if isinstance(objType, int):
pass
elif isinstance(objType, str):
# turn it back into an integer
objType = self.objectTypeClass()[objType]
else:
raise TypeError("invalid datatype for objType")
... | def get_tuple(self) | Return the unsigned integer tuple of the identifier. | 7.000529 | 6.096509 | 1.148285 |
if _debug: DeviceInfoCache._debug("has_device_info %r", key)
return key in self.cache | def has_device_info(self, key) | Return true iff cache has information about the device. | 4.819504 | 3.824573 | 1.260142 |
if _debug: DeviceInfoCache._debug("iam_device_info %r", apdu)
# make sure the apdu is an I-Am
if not isinstance(apdu, IAmRequest):
raise ValueError("not an IAmRequest: %r" % (apdu,))
# get the device instance
device_instance = apdu.iAmDeviceIdentifier[1]
... | def iam_device_info(self, apdu) | Create a device information record based on the contents of an
IAmRequest and put it in the cache. | 3.054041 | 2.909078 | 1.049831 |
if _debug: DeviceInfoCache._debug("update_device_info %r", device_info)
# give this a reference count if it doesn't have one
if not hasattr(device_info, '_ref_count'):
device_info._ref_count = 0
# get the current keys
cache_id, cache_address = getattr(devic... | def update_device_info(self, device_info) | The application has updated one or more fields in the device
information record and the cache needs to be updated to reflect the
changes. If this is a cached version of a persistent record then this
is the opportunity to update the database. | 2.187359 | 2.20856 | 0.9904 |
if _debug: DeviceInfoCache._debug("acquire %r", key)
if isinstance(key, int):
device_info = self.cache.get(key, None)
elif not isinstance(key, Address):
raise TypeError("key must be integer or an address")
elif key.addrType not in (Address.localStation... | def acquire(self, key) | Return the known information about the device and mark the record
as being used by a segmenation state machine. | 2.7833 | 2.724188 | 1.021699 |
if _debug: DeviceInfoCache._debug("release %r", device_info)
# this information record might be used by more than one SSM
if device_info._ref_count == 0:
raise RuntimeError("reference count")
# decrement the reference count
device_info._ref_count -= 1 | def release(self, device_info) | This function is called by the segmentation state machine when it
has finished with the device information. | 6.763111 | 6.522406 | 1.036904 |
if _debug: Application._debug("add_object %r", obj)
# extract the object name and identifier
object_name = obj.objectName
if not object_name:
raise RuntimeError("object name required")
object_identifier = obj.objectIdentifier
if not object_identifier... | def add_object(self, obj) | Add an object to the local collection. | 3.514243 | 3.447599 | 1.01933 |
if _debug: Application._debug("delete_object %r", obj)
# extract the object name and identifier
object_name = obj.objectName
object_identifier = obj.objectIdentifier
# delete it from the application
del self.objectName[object_name]
del self.objectIdenti... | def delete_object(self, obj) | Add an object to the local collection. | 4.002824 | 3.964888 | 1.009568 |
if _debug: Application._debug("get_services_supported")
services_supported = ServicesSupported()
# look through the confirmed services
for service_choice, service_request_class in confirmed_request_types.items():
service_helper = "do_" + service_request_class.__nam... | def get_services_supported(self) | Return a ServicesSupported bit string based in introspection, look
for helper methods that match confirmed and unconfirmed services. | 2.963286 | 2.558034 | 1.158423 |
if _debug: key_value_contents._debug("key_value_contents use_dict=%r as_class=%r key_values=%r", use_dict, as_class, key_values)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# loop through the values and save them
for k, v in key_values:
i... | def key_value_contents(use_dict=None, as_class=dict, key_values=()) | Return the contents of an object as a dict. | 2.524005 | 2.405915 | 1.049084 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.