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 interpolation. cLvl : np.array Consumption points for interpolation. Returns ------- cFuncUnc : LinearInterp The unconstrained consumption function for this period. ''' cFunc_by_pLvl_list = [] # list of consumption functions for each pLvl for j in range(pLvl.shape[0]): pLvl_j = pLvl[j,0] m_temp = mLvl[j,:] - self.BoroCnstNat(pLvl_j) c_temp = cLvl[j,:] # Make a linear consumption function for this pLvl if pLvl_j > 0: cFunc_by_pLvl_list.append(LinearInterp(m_temp,c_temp,lower_extrap=True,slope_limit=self.MPCminNow,intercept_limit=self.MPCminNow*self.hLvlNow(pLvl_j))) else: cFunc_by_pLvl_list.append(LinearInterp(m_temp,c_temp,lower_extrap=True)) pLvl_list = pLvl[:,0] cFuncUncBase = LinearInterpOnInterp1D(cFunc_by_pLvl_list,pLvl_list) # Combine all linear cFuncs cFuncUnc = VariableLowerBoundFunc2D(cFuncUncBase,self.BoroCnstNat) # Re-adjust for natural borrowing constraint (as lower bound) return cFuncUnc
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.array Consumption points for interpolation. Returns ------- cFuncUnc : LinearInterp The unconstrained consumption function for this period.
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. pLvl : np.array Persistent income level points for interpolation. cLvl : np.array Consumption points for interpolation. Returns ------- cFuncUnc : CubicInterp The unconstrained consumption function for this period. ''' # Calculate the MPC at each gridpoint EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*np.sum(self.vPPfuncNext(self.mLvlNext,self.pLvlNext)*self.ShkPrbs_temp,axis=0) dcda = EndOfPrdvPP/self.uPP(np.array(cLvl[1:,1:])) MPC = dcda/(dcda+1.) MPC = np.concatenate((np.reshape(MPC[:,0],(MPC.shape[0],1)),MPC),axis=1) # Stick an extra MPC value at bottom; MPCmax doesn't work MPC = np.concatenate((self.MPCminNow*np.ones((1,self.aXtraGrid.size+1)),MPC),axis=0) # Make cubic consumption function with respect to mLvl for each persistent income level cFunc_by_pLvl_list = [] # list of consumption functions for each pLvl for j in range(pLvl.shape[0]): pLvl_j = pLvl[j,0] m_temp = mLvl[j,:] - self.BoroCnstNat(pLvl_j) c_temp = cLvl[j,:] # Make a cubic consumption function for this pLvl MPC_temp = MPC[j,:] if pLvl_j > 0: cFunc_by_pLvl_list.append(CubicInterp(m_temp,c_temp,MPC_temp,lower_extrap=True,slope_limit=self.MPCminNow,intercept_limit=self.MPCminNow*self.hLvlNow(pLvl_j))) else: # When pLvl=0, cFunc is linear cFunc_by_pLvl_list.append(LinearInterp(m_temp,c_temp,lower_extrap=True)) pLvl_list = pLvl[:,0] cFuncUncBase = LinearInterpOnInterp1D(cFunc_by_pLvl_list,pLvl_list) # Combine all linear cFuncs cFuncUnc = VariableLowerBoundFunc2D(cFuncUncBase,self.BoroCnstNat) # Re-adjust for lower bound of natural borrowing constraint return cFuncUnc
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.array Persistent income level points for interpolation. cLvl : np.array Consumption points for interpolation. Returns ------- cFuncUnc : CubicInterp The unconstrained consumption function for this period.
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 solution to this period's consumption-saving problem, but now with human wealth and the bounding MPCs. ''' solution.hNrm = 0.0 # Can't have None or setAndUpdateValues breaks, should fix solution.hLvl = self.hLvlNow solution.mLvlMin= self.mLvlMinNow solution.MPCmin = self.MPCminNow solution.MPCmax = 0.0 # MPCmax is actually a function in this model return solution
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 period's consumption-saving problem, but now with human wealth and the bounding MPCs.
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 the consumption function. Returns ------- solution : ConsumerSolution The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc. ''' vPPfuncNow = MargMargValueFunc2D(solution.cFunc,self.CRRA) solution.vPPfunc = vPPfuncNow return solution
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 consumption function. Returns ------- solution : ConsumerSolution The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc.
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 problem, including a consumption function (defined over market resources and persistent income), a marginal value function, bounding MPCs, and human wealth as a func- tion of persistent income. Might also include a value function and marginal marginal value function, depending on options selected. ''' aLvl,pLvl = self.prepareToCalcEndOfPrdvP() EndOfPrdvP = self.calcEndOfPrdvP() if self.vFuncBool: self.makeEndOfPrdvFunc(EndOfPrdvP) if self.CubicBool: interpolator = self.makeCubiccFunc else: interpolator = self.makeLinearcFunc solution = self.makeBasicSolution(EndOfPrdvP,aLvl,pLvl,interpolator) solution = self.addMPCandHumanWealth(solution) if self.vFuncBool: solution.vFunc = self.makevFunc(solution) if self.CubicBool: solution = self.addvPPfunc(solution) return solution
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 a consumption function (defined over market resources and persistent income), a marginal value function, bounding MPCs, and human wealth as a func- tion of persistent income. Might also include a value function and marginal marginal value function, depending on options selected.
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_terminal_,self.CRRA) self.solution_terminal.vPfunc = MargValueFunc2D(self.cFunc_terminal_,self.CRRA) self.solution_terminal.vPPfunc = MargMargValueFunc2D(self.cFunc_terminal_,self.CRRA) self.solution_terminal.hNrm = 0.0 # Don't track normalized human wealth self.solution_terminal.hLvl = lambda p : np.zeros_like(p) # But do track absolute human wealth by persistent income self.solution_terminal.mLvlMin = lambda p : np.zeros_like(p)
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 ------- None ''' pLvlNextFuncBasic = LinearInterp(np.array([0.,1.]),np.array([0.,1.])) self.pLvlNextFunc = self.T_cycle*[pLvlNextFuncBasic] self.addToTimeVary('pLvlNextFunc')
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 method updatepLvlNextFunc, which ensures that time is flowing forward. Parameters ---------- None Returns ------- None ''' if (not hasattr(self,'pLvlNextFuncRet')) or self.T_retire == 0: return t = self.T_retire self.pLvlNextFunc[t] = self.pLvlNextFuncRet
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 updatepLvlNextFunc, which ensures that time is flowing forward. Parameters ---------- None Returns ------- None
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). Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' # Get and store states for newly born agents N = np.sum(which_agents) # Number of new consumers to make aNrmNow_new = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1)) self.pLvlNow[which_agents] = drawLognormal(N,mu=self.pLvlInitMean,sigma=self.pLvlInitStd,seed=self.RNG.randint(0,2**31-1)) self.aLvlNow[which_agents] = aNrmNow_new*self.pLvlNow[which_agents] self.t_age[which_agents] = 0 # How many periods since each agent was born self.t_cycle[which_agents] = 0
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 ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None
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 RfreeNow = self.getRfree() # Calculate new states: normalized market resources and persistent income level 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 # Updated persistent income level self.bLvlNow = RfreeNow*aLvlPrev # Bank balances before labor income self.mLvlNow = self.bLvlNow + self.TranShkNow*self.pLvlNow
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.nan for t in range(self.T_cycle): these = t == self.t_cycle cLvlNow[these] = self.solution[t].cFunc(self.mLvlNow[these],self.pLvlNow[these]) MPCnow[these] = self.solution[t].cFunc.derivativeX(self.mLvlNow[these],self.pLvlNow[these]) self.cLvlNow = cLvlNow self.MPCnow = MPCnow
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. Parameters ---------- None Returns ------- None ''' orig_time = self.time_flow self.timeFwd() pLvlNextFunc = [] for t in range(self.T_cycle): pLvlNextFunc.append(LinearInterp(np.array([0.,1.]),np.array([0.,self.PermGroFac[t]]))) self.pLvlNextFunc = pLvlNextFunc self.addToTimeVary('pLvlNextFunc') if not orig_time: self.timeRev()
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 ---------- None Returns ------- None
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 ---------- None Returns ------- None ''' orig_time = self.time_flow self.timeFwd() pLvlNextFunc = [] pLogMean = self.pLvlInitMean # Initial mean (log) persistent income for t in range(self.T_cycle): pLvlNextFunc.append(pLvlFuncAR1(pLogMean,self.PermGroFac[t],self.PrstIncCorr)) pLogMean += np.log(self.PermGroFac[t]) self.pLvlNextFunc = pLvlNextFunc self.addToTimeVary('pLvlNextFunc') if not orig_time: self.timeRev()
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 Returns ------- 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 lognormal with standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if isinstance(sigma,float): # Return a single array of length N mu = -0.5*sigma**2 draws = RNG.lognormal(mean=mu, sigma=sigma, size=N) else: # Set up empty list to populate, then loop and populate list with draws draws=[] for sig in sigma: mu = -0.5*(sig**2) draws.append(RNG.lognormal(mean=mu, sigma=sig, size=N)) return draws
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 lognormal with standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar).
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 lognormal with standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. mu : float or [float] One or more means. Number of elements T in mu determines number of rows of output. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if isinstance(sigma,float): # Return a single array of length N if sigma == 0: draws = np.exp(mu)*np.ones(N) else: draws = RNG.lognormal(mean=mu, sigma=sigma, size=N) else: # Set up empty list to populate, then loop and populate list with draws draws=[] for j in range(len(sigma)): if sigma[j] == 0: draws.append(np.exp(mu[j])*np.ones(N)) else: draws.append(RNG.lognormal(mean=mu[j], sigma=sigma[j], size=N)) return draws
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 lognormal with standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. mu : float or [float] One or more means. Number of elements T in mu determines number of rows of output. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar).
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 from the normal distribution with mean mu[t] and standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. mu : float or [float] One or more means. Number of elements T in mu determines number of rows of output. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of normal draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if isinstance(sigma,float): # Return a single array of length N draws = sigma*RNG.randn(N) + mu else: # Set up empty list to populate, then loop and populate list with draws draws=[] for t in range(len(sigma)): draws.append(sigma[t]*RNG.randn(N) + mu[t]) return draws
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 normal distribution with mean mu[t] and standard deviation sigma[t]. Parameters ---------- N : int Number of draws in each row. mu : float or [float] One or more means. Number of elements T in mu determines number of rows of output. sigma : float or [float] One or more standard deviations. Number of elements T in sigma determines number of rows of output. seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of normal draws each of size N, or a single array of size N (if sigma is a scalar).
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 the Weibull distribution with scale scale[t] and shape shape[t]. Note: When shape=1, the Weibull distribution is simply the exponential dist. Mean: scale*Gamma(1 + 1/shape) Parameters ---------- N : int Number of draws in each row. scale : float or [float] One or more scales. Number of elements T in scale determines number of rows of output. shape : float or [float] One or more shape parameters. Number of elements T in scale determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of Weibull draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if scale == 1: scale = float(scale) if isinstance(scale,float): # Return a single array of length N draws = scale*(-np.log(1.0-RNG.rand(N)))**(1.0/shape) else: # Set up empty list to populate, then loop and populate list with draws draws=[] for t in range(len(scale)): draws.append(scale[t]*(-np.log(1.0-RNG.rand(N)))**(1.0/shape[t])) return draws
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 Weibull distribution with scale scale[t] and shape shape[t]. Note: When shape=1, the Weibull distribution is simply the exponential dist. Mean: scale*Gamma(1 + 1/shape) Parameters ---------- N : int Number of draws in each row. scale : float or [float] One or more scales. Number of elements T in scale determines number of rows of output. shape : float or [float] One or more shape parameters. Number of elements T in scale determines number of rows of output. seed : int Seed for random number generator. Returns: ------------ draws : np.array or [np.array] T-length list of arrays of Weibull draws each of size N, or a single array of size N (if sigma is a scalar).
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 on [bot[t],top[t]]. Parameters ---------- N : int Number of draws in each row. bot : float or [float] One or more bottom values. Number of elements T in mu determines number of rows of output. top : float or [float] One or more top values. Number of elements T in top determines number of rows of output. seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of uniform draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if isinstance(bot,float) or isinstance(bot,int): # Return a single array of size N draws = bot + (top - bot)*RNG.rand(N) else: # Set up empty list to populate, then loop and populate list with draws draws=[] for t in range(len(bot)): draws.append(bot[t] + (top[t] - bot[t])*RNG.rand(N)) return draws
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[t],top[t]]. Parameters ---------- N : int Number of draws in each row. bot : float or [float] One or more bottom values. Number of elements T in mu determines number of rows of output. top : float or [float] One or more top values. Number of elements T in top determines number of rows of output. seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of uniform draws each of size N, or a single array of size N (if sigma is a scalar).
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 otherwise. Arguments --------- N : int Number of draws in each row. p : float or [float] Probability or probabilities of the event occurring (True). seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of Bernoulli draws each of size N, or a single array of size N (if sigma is a scalar). ''' # Set up the RNG RNG = np.random.RandomState(seed) if isinstance(p,float):# Return a single array of size N draws = RNG.uniform(size=N) < p else: # Set up empty list to populate, then loop and populate list with draws: draws=[] for t in range(len(p)): draws.append(RNG.uniform(size=N) < p[t]) return draws
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. Arguments --------- N : int Number of draws in each row. p : float or [float] Probability or probabilities of the event occurring (True). seed : int Seed for random number generator. Returns ------- draws : np.array or [np.array] T-length list of arrays of Bernoulli draws each of size N, or a single array of size N (if sigma is a scalar).
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 Whether the draws should "exactly" match the discrete distribution (as closely as possible given finite draws). When True, returned draws are a random permutation of the N-length list that best fits the discrete distribution. When False (default), each draw is independent from the others and the result could deviate from the input. seed : int Seed for random number generator. Returns ------- draws : np.array An array draws from the discrete distribution; each element is a value in X. ''' # Set up the RNG RNG = np.random.RandomState(seed) if exact_match: events = np.arange(P.size) # just a list of integers cutoffs = np.round(np.cumsum(P)*N).astype(int) # cutoff points between discrete outcomes top = 0 # Make a list of event indices that closely matches the discrete distribution event_list = [] for j in range(events.size): bot = top top = cutoffs[j] event_list += (top-bot)*[events[j]] # Randomly permute the event indices and store the corresponding results event_draws = RNG.permutation(event_list) draws = X[event_draws] else: # Generate a cumulative distribution base_draws = RNG.uniform(size=N) cum_dist = np.cumsum(P) # Convert the basic uniform draws into discrete draws indices = cum_dist.searchsorted(base_draws) draws = np.asarray(X)[indices] return draws
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 Whether the draws should "exactly" match the discrete distribution (as closely as possible given finite draws). When True, returned draws are a random permutation of the N-length list that best fits the discrete distribution. When False (default), each draw is independent from the others and the result could deviate from the input. seed : int Seed for random number generator. Returns ------- draws : np.array An array draws from the discrete distribution; each element is a value in X.
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 with the number of agents of each type in the market. Unused. ''' sNowX = np.asarray(sNow).flatten() pNow = np.mean(sNowX) return FashionMarketInfo(pNow)
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 number of agents of each type in the market. Unused.
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) : FashionEvoFunc A new rule for the evolution of the population punk proportion, based on the history in input pNow. ''' pNowX = np.array(pNow) T = pNowX.size p_t = pNowX[100:(T-1)] p_tp1 = pNowX[101:T] pNextSlope, pNextIntercept, trash1, trash2, trash3 = stats.linregress(p_t,p_tp1) pPopExp = pNextIntercept + pNextSlope*p_t pPopErrSq= (pPopExp - p_tp1)**2 pNextStd = np.sqrt(np.mean(pPopErrSq)) print(str(pNextIntercept) + ', ' + str(pNextSlope) + ', ' + str(pNextStd)) return FashionEvoFunc(pNextIntercept,pNextSlope,2*pNextStd)
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 A new rule for the evolution of the population punk proportion, based on the history in input pNow.
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, pNextSlope, pNextCount, pNextWidth, and pGrid, this method generates a new array for the attri- bute pEvolution, representing a discrete approximation of next period states for each current period state in pGrid. Parameters ---------- none Returns ------- none ''' self.pEvolution = np.zeros((self.pCount,self.pNextCount)) for j in range(self.pCount): pNow = self.pGrid[j] pNextMean = self.pNextIntercept + self.pNextSlope*pNow dist = approxUniform(N=self.pNextCount,bot=pNextMean-self.pNextWidth,top=pNextMean+self.pNextWidth)[1] self.pEvolution[j,:] = dist
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, pNextWidth, and pGrid, this method generates a new array for the attri- bute pEvolution, representing a discrete approximation of next period states for each current period state in pGrid. Parameters ---------- none Returns ------- none
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). Results are stored as attributes of self. Parameters ---------- none Returns ------- none ''' self.conformUtilityFunc = lambda x : stats.beta.pdf(x,self.uParamA,self.uParamB) self.pGrid = np.linspace(0.0001,0.9999,self.pCount) self.updateEvolution()
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 stored as attributes of self. Parameters ---------- none Returns ------- none
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_size) sNow[Shk < self.p_init] = 1 self.sNow = sNow
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].switchFuncJock self.VfuncPunk = self.solution[0].VfuncPunk self.VfuncJock = self.solution[0].VfuncJock
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 ------- none ''' pNow = self.pNow sPrev = self.sNow J2Pprob = self.switchFuncJock(pNow) P2Jprob = self.switchFuncPunk(pNow) Shks = self.RNG.rand(self.pop_size) J2P = np.logical_and(sPrev == 0,Shks < J2Pprob) P2J = np.logical_and(sPrev == 1,Shks < P2Jprob) sNow = copy(sPrev) sNow[J2P] = 1 sNow[P2J] = 0 self.sNow = sNow
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 # solutions from the inverted Euler equations that do not represent optimal # choices (the FOCs are only necessary in these models). # # `fall` is a vector of indeces that represent the first elements in all # of the falling segments (the curve can potentially fold several times) fall = np.empty(0, dtype=int) # initialize with empty and then add the last point below while-loop rise = np.array([0]) # Initialize such thatthe lowest point is the first grid point i = 1 # Initialize while i <= len(x) - 2: # Check if the next (`ip1` stands for i plus 1) grid point is below the # current one, such that the line is folding back. ip1_falls = x[i+1] < x[i] # true if grid decreases on index increment i_rose = x[i] > x[i-1] # true if grid decreases on index decrement val_fell = v[i] < v[i-1] # true if value rises on index decrement if (ip1_falls and i_rose) or (val_fell and i_rose): # we are in a region where the endogenous grid is decreasing or # the value function rises by stepping back in the grid. fall = np.append(fall, i) # add the index to the vector # We now iterate from the current index onwards until we find point # where resources rises again. Unfortunately, we need to check # each points, as there can be multiple spells of falling endogenous # grids, so we cannot use bisection or some other fast algorithm. k = i while x[k+1] < x[k]: k = k + 1 # k now holds either the next index the starts a new rising # region, or it holds the length of M, `m_len`. rise = np.append(rise, k) # Set the index to the point where resources again is rising i = k i = i + 1 # Add the last index for convenience (then all segments are complete, as # len(fall) == len(rise), and we can form them by range(rise[j], fall[j]+1). fall = np.append(fall, len(v)-1) return rise, fall
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 construct the upper envelope of potential solutions to the (necessary) first order conditions. Parameters ---------- x : np.ndarray array of points where `v` is evaluated v : np.ndarray array of values of some function of `x` Returns ------- rise : np.ndarray see description above fall : np.ndarray see description above
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 : float Survival probability; likelihood of being alive at the beginning of the succeeding period. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. Returns ------- solution : ConsumerSolution The solution to this period's problem. ''' solver = ConsPerfForesightSolver(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac) solution = solver.solve() return solution
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 Survival probability; likelihood of being alive at the beginning of the succeeding period. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. Returns ------- solution : ConsumerSolution The solution to this period's problem.
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 period. tax_rate : float A flat income tax rate to be applied to all employed income. T_retire : int The time index after which the agent retires. unemployed_indices : [int] Indices of transitory shocks that represent unemployment states (no tax). transitory_index : int The index of each element of IncomeDstn representing transitory shocks. Returns ------- IncomeDstn_new : [income distributions] The updated income distributions, after applying the tax. ''' IncomeDstn_new = deepcopy(IncomeDstn) i = transitory_index for t in range(len(IncomeDstn)): if t < T_retire: for j in range((IncomeDstn[t][i]).size): if j not in unemployed_indices: IncomeDstn_new[t][i][j] = IncomeDstn[t][i][j]*(1-tax_rate) return IncomeDstn_new
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. tax_rate : float A flat income tax rate to be applied to all employed income. T_retire : int The time index after which the agent retires. unemployed_indices : [int] Indices of transitory shocks that represent unemployment states (no tax). transitory_index : int The index of each element of IncomeDstn representing transitory shocks. Returns ------- IncomeDstn_new : [income distributions] The updated income distributions, after applying the tax.
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 ---------- aXtraMin: float Minimum value for the a-grid aXtraMax: float Maximum value for the a-grid aXtraCount: int Size of the a-grid aXtraExtra: [float] Extra values for the a-grid. exp_nest: int Level of nesting for the exponentially spaced grid Returns ------- aXtraGrid: np.ndarray Base array of values for the post-decision-state grid. ''' # Unpack the parameters aXtraMin = parameters.aXtraMin aXtraMax = parameters.aXtraMax aXtraCount = parameters.aXtraCount aXtraExtra = parameters.aXtraExtra grid_type = 'exp_mult' exp_nest = parameters.aXtraNestFac # Set up post decision state grid: aXtraGrid = None if grid_type == "linear": aXtraGrid = np.linspace(aXtraMin, aXtraMax, aXtraCount) elif grid_type == "exp_mult": aXtraGrid = makeGridExpMult(ming=aXtraMin, maxg=aXtraMax, ng=aXtraCount, timestonest=exp_nest) else: raise Exception("grid_type not recognized in __init__." + \ "Please ensure grid_type is 'linear' or 'exp_mult'") # Add in additional points for the grid: for a in aXtraExtra: if (a is not None): if a not in aXtraGrid: j = aXtraGrid.searchsorted(a) aXtraGrid = np.insert(aXtraGrid, j, a) return aXtraGrid
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: float Minimum value for the a-grid aXtraMax: float Maximum value for the a-grid aXtraCount: int Size of the a-grid aXtraExtra: [float] Extra values for the a-grid. exp_nest: int Level of nesting for the exponentially spaced grid Returns ------- aXtraGrid: np.ndarray Base array of values for the post-decision-state grid.
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 ---------- new_solution : ConsumerSolution The solution to a consumption-saving problem; each attribute is a list representing state-conditional values or functions. Returns ------- None ''' if type(self.cFunc)!=list: # Then we assume that self is an empty initialized solution instance. # Begin by checking this is so. assert NullFunc().distance(self.cFunc) == 0, 'appendSolution called incorrectly!' # We will need the attributes of the solution instance to be lists. Do that here. self.cFunc = [new_solution.cFunc] self.vFunc = [new_solution.vFunc] self.vPfunc = [new_solution.vPfunc] self.vPPfunc = [new_solution.vPPfunc] self.mNrmMin = [new_solution.mNrmMin] else: self.cFunc.append(new_solution.cFunc) self.vFunc.append(new_solution.vFunc) self.vPfunc.append(new_solution.vPfunc) self.vPPfunc.append(new_solution.vPPfunc) self.mNrmMin.append(new_solution.mNrmMin)
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_solution : ConsumerSolution The solution to a consumption-saving problem; each attribute is a list representing state-conditional values or functions. Returns ------- None
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 utility. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. Returns ------- none ''' self.solution_next = solution_next self.DiscFac = DiscFac self.LivPrb = LivPrb self.CRRA = CRRA self.Rfree = Rfree self.PermGroFac = PermGroFac
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 : float Survival probability; likelihood of being alive at the beginning of the succeeding period. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. Returns ------- none
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) # utility function self.uP = lambda c : utilityP(c,gam=self.CRRA) # marginal utility function self.uPP = lambda c : utilityPP(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.mNrmMin+1.0]),np.array([0.0, MPCnvrs])) self.vFunc = ValueFunc(vFuncNvrs,self.CRRA) self.vPfunc = MargValueFunc(self.cFunc,self.CRRA)
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.solution_next.hNrm + 1.0) self.mNrmMin = -self.hNrmNow # Calculate the (constant) marginal propensity to consume PatFac = ((self.Rfree*self.DiscFacEff)**(1.0/self.CRRA))/self.Rfree self.MPC = 1.0/(1.0 + PatFac/self.solution_next.MPCmin) # Construct the consumption function self.cFunc = LinearInterp([self.mNrmMin, self.mNrmMin+1.0],[0.0, self.MPC]) # Add two attributes to enable calculation of steady state market resources self.ExIncNext = 1.0 # Perfect foresight income of 1 self.mNrmMinNow = self.mNrmMin
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 ---------- solution : ConsumerSolution Solution to this period's problem, which must have attribute cFunc. Returns ------- solution : ConsumerSolution Same solution that was passed, but now with the attribute mNrmSS. ''' # Make a linear function of all combinations of c and m that yield mNext = mNow mZeroChangeFunc = lambda m : (1.0-self.PermGroFac/self.Rfree)*m + (self.PermGroFac/self.Rfree)*self.ExIncNext # Find the steady state level of market resources searchSSfunc = lambda m : solution.cFunc(m) - mZeroChangeFunc(m) # A zero of this is SS market resources m_init_guess = self.mNrmMinNow + self.ExIncNext # Minimum market resources plus next income is okay starting guess try: mNrmSS = newton(searchSSfunc,m_init_guess) except: mNrmSS = None # Add mNrmSS to the solution and return it solution.mNrmSS = mNrmSS return solution
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 : ConsumerSolution Solution to this period's problem, which must have attribute cFunc. Returns ------- solution : ConsumerSolution Same solution that was passed, but now with the attribute mNrmSS.
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.DiscFacEff = self.DiscFac*self.LivPrb self.makePFcFunc() self.defValueFuncs() solution = ConsumerSolution(cFunc=self.cFunc, vFunc=self.vFunc, vPfunc=self.vPfunc, mNrmMin=self.mNrmMin, hNrm=self.hNrmNow, MPCmin=self.MPC, MPCmax=self.MPC) #solution = self.addSSmNrm(solution) return solution
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, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. BoroCnstArt: float or None Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. aXtraGrid: np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. vFuncBool: boolean An indicator for whether the value function should be computed and included in the reported solution. CubicBool: boolean An indicator for whether the solver should use cubic or linear inter- polation. Returns ------- none ''' ConsPerfForesightSolver.assignParameters(self,solution_next,DiscFac,LivPrb, CRRA,Rfree,PermGroFac) self.BoroCnstArt = BoroCnstArt self.IncomeDstn = IncomeDstn self.aXtraGrid = aXtraGrid self.vFuncBool = vFuncBool self.CubicBool = CubicBool
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 discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroFac : float Expected permanent income growth factor at the end of this period. BoroCnstArt: float or None Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. aXtraGrid: np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. vFuncBool: boolean An indicator for whether the value function should be computed and included in the reported solution. CubicBool: boolean An indicator for whether the solver should use cubic or linear inter- polation. Returns ------- none
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 ''' ConsPerfForesightSolver.defUtilityFuncs(self) self.uPinv = lambda u : utilityP_inv(u,gam=self.CRRA) self.uPinvP = lambda u : utilityP_invP(u,gam=self.CRRA) self.uinvP = lambda u : utility_invP(u,gam=self.CRRA) if self.vFuncBool: self.uinv = lambda u : utility_inv(u,gam=self.CRRA)
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 period, the patience factor, human wealth, and the bounding MPCs. 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 discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None ''' self.DiscFacEff = DiscFac*LivPrb # "effective" discount factor self.ShkPrbsNext = IncomeDstn[0] self.PermShkValsNext = IncomeDstn[1] self.TranShkValsNext = IncomeDstn[2] self.PermShkMinNext = np.min(self.PermShkValsNext) self.TranShkMinNext = np.min(self.TranShkValsNext) self.vPfuncNext = solution_next.vPfunc self.WorstIncPrb = np.sum(self.ShkPrbsNext[ (self.PermShkValsNext*self.TranShkValsNext)== (self.PermShkMinNext*self.TranShkMinNext)]) if self.CubicBool: self.vPPfuncNext = solution_next.vPPfunc if self.vFuncBool: self.vFuncNext = solution_next.vFunc # Update the bounding MPCs and PDV of human wealth: self.PatFac = ((self.Rfree*self.DiscFacEff)**(1.0/self.CRRA))/self.Rfree self.MPCminNow = 1.0/(1.0 + self.PatFac/solution_next.MPCmin) self.ExIncNext = np.dot(self.ShkPrbsNext,self.TranShkValsNext*self.PermShkValsNext) self.hNrmNow = self.PermGroFac/self.Rfree*(self.ExIncNext + solution_next.hNrm) self.MPCmaxNow = 1.0/(1.0 + (self.WorstIncPrb**(1.0/self.CRRA))* self.PatFac/solution_next.MPCmax)
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 patience factor, human wealth, and the bounding MPCs. 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 discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None
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 assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. Returns ------- none ''' # Calculate the minimum allowable value of money resources in this period self.BoroCnstNat = (self.solution_next.mNrmMin - self.TranShkMinNext)*\ (self.PermGroFac*self.PermShkMinNext)/self.Rfree # Note: need to be sure to handle BoroCnstArt==None appropriately. # In Py2, this would evaluate to 5.0: np.max([None, 5.0]). # However in Py3, this raises a TypeError. Thus here we need to directly # address the situation in which BoroCnstArt == None: if BoroCnstArt is None: self.mNrmMinNow = self.BoroCnstNat else: self.mNrmMinNow = np.max([self.BoroCnstNat,BoroCnstArt]) if self.BoroCnstNat < self.mNrmMinNow: self.MPCmaxEff = 1.0 # If actually constrained, MPC near limit is 1 else: self.MPCmaxEff = self.MPCmaxNow # Define the borrowing constraint (limiting consumption function) self.cFuncNowCnst = LinearInterp(np.array([self.mNrmMinNow, self.mNrmMinNow+1]), np.array([0.0, 1.0]))
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 period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. Returns ------- none
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) self.defBoroCnst(self.BoroCnstArt)
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 ---------- none Returns ------- aNrmNow : np.array A 1D array of end-of-period assets; also stored as attribute of self. ''' # We define aNrmNow all the way from BoroCnstNat up to max(self.aXtraGrid) # even if BoroCnstNat < BoroCnstArt, so we can construct the consumption # function as the lower envelope of the (by the artificial borrowing con- # straint) uconstrained consumption function, and the artificially con- # strained consumption function. aNrmNow = np.asarray(self.aXtraGrid) + self.BoroCnstNat ShkCount = self.TranShkValsNext.size aNrm_temp = np.tile(aNrmNow,(ShkCount,1)) # Tile arrays of the income shocks and put them into useful shapes aNrmCount = aNrmNow.shape[0] PermShkVals_temp = (np.tile(self.PermShkValsNext,(aNrmCount,1))).transpose() TranShkVals_temp = (np.tile(self.TranShkValsNext,(aNrmCount,1))).transpose() ShkPrbs_temp = (np.tile(self.ShkPrbsNext,(aNrmCount,1))).transpose() # Get cash on hand next period mNrmNext = self.Rfree/(self.PermGroFac*PermShkVals_temp)*aNrm_temp + TranShkVals_temp # Store and report the results self.PermShkVals_temp = PermShkVals_temp self.ShkPrbs_temp = ShkPrbs_temp self.mNrmNext = mNrmNext self.aNrmNow = aNrmNow return aNrmNow
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 Returns ------- aNrmNow : np.array A 1D array of end-of-period assets; also stored as attribute of self.
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 ------- EndOfPrdvP : np.array A 1D array of end-of-period marginal value of assets ''' EndOfPrdvP = self.DiscFacEff*self.Rfree*self.PermGroFac**(-self.CRRA)*np.sum( self.PermShkVals_temp**(-self.CRRA)* self.vPfuncNext(self.mNrmNext)*self.ShkPrbs_temp,axis=0) return EndOfPrdvP
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 ------- EndOfPrdvP : np.array A 1D array of end-of-period marginal value of assets
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 in EndOfPrdvP. Returns ------- c_for_interpolation : np.array Consumption points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation. ''' cNrmNow = self.uPinv(EndOfPrdvP) mNrmNow = cNrmNow + aNrmNow # Limiting consumption is zero as m approaches mNrmMin c_for_interpolation = np.insert(cNrmNow,0,0.,axis=-1) m_for_interpolation = np.insert(mNrmNow,0,self.BoroCnstNat,axis=-1) # Store these for calcvFunc self.cNrmNow = cNrmNow self.mNrmNow = mNrmNow return c_for_interpolation,m_for_interpolation
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. Returns ------- c_for_interpolation : np.array Consumption points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation.
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) corresponding market resource points for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' # Construct the unconstrained consumption function cFuncNowUnc = interpolator(mNrm,cNrm) # Combine the constrained and unconstrained functions into the true consumption function cFuncNow = LowerEnvelope(cFuncNowUnc,self.cFuncNowCnst) # Make the marginal value function and the marginal marginal value function vPfuncNow = MargValueFunc(cFuncNow,self.CRRA) # Pack up the solution and return it solution_now = ConsumerSolution(cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=self.mNrmMinNow) return solution_now
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 resource points for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
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 values that yield the marginal values in EndOfPrdvP. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' cNrm,mNrm = self.getPointsForInterpolation(EndOfPrdvP,aNrm) solution_now = self.usePointsForInterpolation(cNrm,mNrm,interpolator) return solution_now
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 the marginal values in EndOfPrdvP. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
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 solution to this period's consumption-saving problem, but now with human wealth and the bounding MPCs. ''' solution.hNrm = self.hNrmNow solution.MPCmin = self.MPCminNow solution.MPCmax = self.MPCmaxEff return solution
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 period's consumption-saving problem, but now with human wealth and the bounding MPCs.
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. Returns ------- cFuncUnc : LinearInterp The unconstrained consumption function for this period. ''' cFuncUnc = LinearInterp(mNrm,cNrm,self.MPCminNow*self.hNrmNow,self.MPCminNow) return cFuncUnc
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 ------- cFuncUnc : LinearInterp The unconstrained consumption function for this period.
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() EndOfPrdvP = self.calcEndOfPrdvP() solution = self.makeBasicSolution(EndOfPrdvP,aNrm,self.makeLinearcFunc) solution = self.addMPCandHumanWealth(solution) return solution
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 interpolation. Returns ------- cFuncUnc : CubicInterp The unconstrained consumption function for this period. ''' EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*self.PermGroFac**(-self.CRRA-1.0)* \ np.sum(self.PermShkVals_temp**(-self.CRRA-1.0)* self.vPPfuncNext(self.mNrmNext)*self.ShkPrbs_temp,axis=0) dcda = EndOfPrdvPP/self.uPP(np.array(cNrm[1:])) MPC = dcda/(dcda+1.) MPC = np.insert(MPC,0,self.MPCmaxNow) cFuncNowUnc = CubicInterp(mNrm,cNrm,MPC,self.MPCminNow*self.hNrmNow,self.MPCminNow) return cFuncNowUnc
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. Returns ------- cFuncUnc : CubicInterp The unconstrained consumption function for this period.
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 values in self.aNrmNow. Returns ------- none ''' VLvlNext = (self.PermShkVals_temp**(1.0-self.CRRA)*\ self.PermGroFac**(1.0-self.CRRA))*self.vFuncNext(self.mNrmNext) EndOfPrdv = self.DiscFacEff*np.sum(VLvlNext*self.ShkPrbs_temp,axis=0) EndOfPrdvNvrs = self.uinv(EndOfPrdv) # value transformed through inverse utility EndOfPrdvNvrsP = EndOfPrdvP*self.uinvP(EndOfPrdv) EndOfPrdvNvrs = np.insert(EndOfPrdvNvrs,0,0.0) EndOfPrdvNvrsP = np.insert(EndOfPrdvNvrsP,0,EndOfPrdvNvrsP[0]) # This is a very good approximation, vNvrsPP = 0 at the asset minimum aNrm_temp = np.insert(self.aNrmNow,0,self.BoroCnstNat) EndOfPrdvNvrsFunc = CubicInterp(aNrm_temp,EndOfPrdvNvrs,EndOfPrdvNvrsP) self.EndOfPrdvFunc = ValueFunc(EndOfPrdvNvrsFunc,self.CRRA)
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. Returns ------- none
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. EndOfPrdvP : np.array Array of end-of-period marginal value of assets corresponding to the asset values in self.aNrmNow. Returns ------- solution : ConsumerSolution The single period solution passed as an input, but now with the value function (defined over market resources m) as an attribute. ''' self.makeEndOfPrdvFunc(EndOfPrdvP) solution.vFunc = self.makevFunc(solution) return solution
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 Array of end-of-period marginal value of assets corresponding to the asset values in self.aNrmNow. Returns ------- solution : ConsumerSolution The single period solution passed as an input, but now with the value function (defined over market resources m) as an attribute.
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 the consumption function. Returns ------- vFuncNow : ValueFunc A representation of the value function for this period, defined over normalized market resources m: v = vFuncNow(m). ''' # Compute expected value and marginal value on a grid of market resources 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) # Construct the beginning-of-period value function vNvrs = self.uinv(vNrmNow) # value transformed through inverse utility vNvrsP = vPnow*self.uinvP(vNrmNow) mNrm_temp = np.insert(mNrm_temp,0,self.mNrmMinNow) vNvrs = np.insert(vNvrs,0,0.0) vNvrsP = np.insert(vNvrsP,0,self.MPCmaxEff**(-self.CRRA/(1.0-self.CRRA))) MPCminNvrs = self.MPCminNow**(-self.CRRA/(1.0-self.CRRA)) vNvrsFuncNow = CubicInterp(mNrm_temp,vNvrs,vNvrsP,MPCminNvrs*self.hNrmNow,MPCminNvrs) vFuncNow = ValueFunc(vNvrsFuncNow,self.CRRA) return vFuncNow
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 consumption function. Returns ------- vFuncNow : ValueFunc A representation of the value function for this period, defined over normalized market resources m: v = vFuncNow(m).
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 the consumption function. Returns ------- solution : ConsumerSolution The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc. ''' vPPfuncNow = MargMargValueFunc(solution.cFunc,self.CRRA) solution.vPPfunc = vPPfuncNow return solution
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 consumption function. Returns ------- solution : ConsumerSolution The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc.
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 mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. Parameters ---------- none Returns ------- solution : ConsumerSolution The solution to the single period consumption-saving problem. ''' # Make arrays of end-of-period assets and end-of-period marginal value aNrm = self.prepareToCalcEndOfPrdvP() EndOfPrdvP = self.calcEndOfPrdvP() # Construct a basic solution for this period if self.CubicBool: solution = self.makeBasicSolution(EndOfPrdvP,aNrm,interpolator=self.makeCubiccFunc) else: solution = self.makeBasicSolution(EndOfPrdvP,aNrm,interpolator=self.makeLinearcFunc) solution = self.addMPCandHumanWealth(solution) # add a few things solution = self.addSSmNrm(solution) # find steady state m # Add the value function if requested, as well as the marginal marginal # value function if cubic splines were used (to prepare for next period) if self.vFuncBool: solution = self.addvFunc(solution,EndOfPrdvP) if self.CubicBool: solution = self.addvPPfunc(solution) return solution
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 human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. Parameters ---------- none Returns ------- solution : ConsumerSolution The solution to the single period consumption-saving problem.
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 because different savings choices yield different interest rates. Parameters ---------- none Returns ------- aNrmNow : np.array A 1D array of end-of-period assets; also stored as attribute of self. ''' KinkBool = self.Rboro > self.Rsave # Boolean indicating that there is actually a kink. # When Rboro == Rsave, this method acts just like it did in IndShock. # When Rboro < Rsave, the solver would have terminated when it was called. # Make a grid of end-of-period assets, including *two* copies of a=0 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 # Make tiled versions of the assets grid and income shocks ShkCount = self.TranShkValsNext.size aNrm_temp = np.tile(aNrmNow,(ShkCount,1)) PermShkVals_temp = (np.tile(self.PermShkValsNext,(aXtraCount,1))).transpose() TranShkVals_temp = (np.tile(self.TranShkValsNext,(aXtraCount,1))).transpose() ShkPrbs_temp = (np.tile(self.ShkPrbsNext,(aXtraCount,1))).transpose() # Make a 1D array of the interest factor at each asset gridpoint Rfree_vec = self.Rsave*np.ones(aXtraCount) if KinkBool: Rfree_vec[0:(np.sum(aNrmNow<=0)-1)] = self.Rboro self.Rfree = Rfree_vec Rfree_temp = np.tile(Rfree_vec,(ShkCount,1)) # Make an array of market resources that we could have next period, # considering the grid of assets and the income shocks that could occur mNrmNext = Rfree_temp/(self.PermGroFac*PermShkVals_temp)*aNrm_temp + TranShkVals_temp # Recalculate the minimum MPC and human wealth using the interest factor on saving. # This overwrites values from setAndUpdateValues, which were based on Rboro instead. if KinkBool: PatFacTop = ((self.Rsave*self.DiscFacEff)**(1.0/self.CRRA))/self.Rsave self.MPCminNow = 1.0/(1.0 + PatFacTop/self.solution_next.MPCmin) self.hNrmNow = self.PermGroFac/self.Rsave*(np.dot(self.ShkPrbsNext, self.TranShkValsNext*self.PermShkValsNext) + self.solution_next.hNrm) # Store some of the constructed arrays for later use and return the assets grid self.PermShkVals_temp = PermShkVals_temp self.ShkPrbs_temp = ShkPrbs_temp self.mNrmNext = mNrmNext self.aNrmNow = aNrmNow return aNrmNow
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 different savings choices yield different interest rates. Parameters ---------- none Returns ------- aNrmNow : np.array A 1D array of end-of-period assets; also stored as attribute of self.
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_terminal_,self.CRRA) self.solution_terminal.vPfunc = MargValueFunc(self.cFunc_terminal_,self.CRRA) self.solution_terminal.vPPfunc = MargMargValueFunc(self.cFunc_terminal_,self.CRRA)
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 list of consumption functions. Parameters ---------- none Returns ------- none ''' self.cFunc = [] for solution_t in self.solution: self.cFunc.append(solution_t.cFunc) self.addToTimeVary('cFunc')
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 functions. Parameters ---------- none Returns ------- none
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 ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' # Get and store states for newly born agents N = np.sum(which_agents) # Number of new consumers to make self.aNrmNow[which_agents] = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1)) pLvlInitMeanNow = self.pLvlInitMean + np.log(self.PlvlAggNow) # Account for newer cohorts having higher permanent income self.pLvlNow[which_agents] = drawLognormal(N,mu=pLvlInitMeanNow,sigma=self.pLvlInitStd,seed=self.RNG.randint(0,2**31-1)) self.t_age[which_agents] = 0 # How many periods since each agent was born self.t_cycle[which_agents] = 0 # Which period of the cycle each agent is currently in return None
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 ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None
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 of size AgentCount indicating which agents die. ''' # Determine who dies DiePrb_by_t_cycle = 1.0 - np.asarray(self.LivPrb) DiePrb = DiePrb_by_t_cycle[self.t_cycle-1] # Time has already advanced, so look back one DeathShks = drawUniform(N=self.AgentCount,seed=self.RNG.randint(0,2**31-1)) which_agents = DeathShks < DiePrb if self.T_age is not None: # Kill agents that have lived for too many periods too_old = self.t_age >= self.T_age which_agents = np.logical_or(which_agents,too_old) return which_agents
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 indicating which agents die.
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 ---------- None Returns ------- None ''' PermGroFac = np.array(self.PermGroFac) self.PermShkNow = PermGroFac[self.t_cycle-1] # cycle time has already been advanced self.TranShkNow = np.ones(self.AgentCount)
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 Returns ------- 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 aNrmPrev = self.aNrmNow RfreeNow = self.getRfree() # Calculate new states: normalized market resources and permanent income level self.pLvlNow = pLvlPrev*self.PermShkNow # Updated permanent income level self.PlvlAggNow = self.PlvlAggNow*self.PermShkAggNow # Updated aggregate permanent productivity level ReffNow = RfreeNow/self.PermShkNow # "Effective" interest factor on normalized assets self.bNrmNow = ReffNow*aNrmPrev # Bank balances before labor income self.mNrmNow = self.bNrmNow + self.TranShkNow # Market resources after income return None
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 to precalculate asset level return None
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 condition (FVAC). These are the conditions that are sufficient for nondegenerate solutions under infinite horizon with a 1 period cycle. Depending on the model at hand, a different combination of these conditions must be satisfied. To check which conditions are relevant to the model at hand, a reference to the relevant theoretical literature is made. Parameters ---------- verbose : boolean Specifies different levels of verbosity of feedback. When False, it only reports whether the instance's type fails to satisfy a particular condition. When True, it reports all results, i.e. the factor values for all conditions. Returns ------- None ''' if self.cycles!=0 or self.T_cycle > 1: if verbose == True: print('This method only checks for the conditions for infinite horizon models with a 1 period cycle') return violated = False #Evaluate and report on the return impatience condition RIF = (self.LivPrb[0]*(self.Rfree*self.DiscFac)**(1/self.CRRA))/self.Rfree if RIF<1: if public_call: print('The return impatience factor value for the supplied parameter values satisfies the return impatience condition.') else: violated = True print('The given type violates the Return Impatience Condition with the supplied parameter values; the factor is %1.5f ' % (RIF)) #Evaluate and report on the absolute impatience condition AIF = self.LivPrb[0]*(self.Rfree*self.DiscFac)**(1/self.CRRA) if AIF<1: if public_call: print('The absolute impatience factor value for the supplied parameter values satisfies the absolute impatience condition.') else: print('The given type violates the absolute impatience condition with the supplied parameter values; the AIF is %1.5f ' % (AIF)) if verbose: violated = True print(' Therefore, the absolute amount of consumption is expected to grow over time') #Evaluate and report on the finite human wealth condition FHWF = self.PermGroFac[0]/self.Rfree if FHWF<1: if public_call: print('The finite human wealth factor value for the supplied parameter values satisfies the finite human wealth condition.') else: print('The given type violates the finite human wealth condition; the finite human wealth factor value %2.5f ' % (FHWF)) violated = True if verbose and violated and verbose_reference: print('[!] For more information on the conditions, see Table 3 in "Theoretical Foundations of Buffer Stock Saving" at http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/') return violated
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). These are the conditions that are sufficient for nondegenerate solutions under infinite horizon with a 1 period cycle. Depending on the model at hand, a different combination of these conditions must be satisfied. To check which conditions are relevant to the model at hand, a reference to the relevant theoretical literature is made. Parameters ---------- verbose : boolean Specifies different levels of verbosity of feedback. When False, it only reports whether the instance's type fails to satisfy a particular condition. When True, it reports all results, i.e. the factor values for all conditions. Returns ------- None
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 = constructLognormalIncomeProcessUnemployment(self) self.IncomeDstn = IncomeDstn self.PermShkDstn = PermShkDstn self.TranShkDstn = TranShkDstn self.addToTimeVary('IncomeDstn','PermShkDstn','TranShkDstn') if not original_time: self.timeRev()
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.aXtraGrid = aXtraGrid self.addToTimeInv('aXtraGrid')
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, ignoring mort- ality. The maximum MPC is the limit of the MPC as m --> mNrmMin. The minimum MPC is the limit of the MPC as m --> infty. This version deals with the different interest rates on borrowing vs saving. Parameters ---------- None Returns ------- None ''' # Unpack the income distribution and get average and worst outcomes PermShkValsNext = self.IncomeDstn[0][1] TranShkValsNext = self.IncomeDstn[0][2] ShkPrbsNext = self.IncomeDstn[0][0] ExIncNext = np.dot(ShkPrbsNext,PermShkValsNext*TranShkValsNext) PermShkMinNext = np.min(PermShkValsNext) TranShkMinNext = np.min(TranShkValsNext) WorstIncNext = PermShkMinNext*TranShkMinNext WorstIncPrb = np.sum(ShkPrbsNext[(PermShkValsNext*TranShkValsNext)==WorstIncNext]) # Calculate human wealth and the infinite horizon natural borrowing constraint hNrm = (ExIncNext*self.PermGroFac[0]/self.Rsave)/(1.0-self.PermGroFac[0]/self.Rsave) temp = self.PermGroFac[0]*PermShkMinNext/self.Rboro BoroCnstNat = -TranShkMinNext*temp/(1.0-temp) PatFacTop = (self.DiscFac*self.LivPrb[0]*self.Rsave)**(1.0/self.CRRA)/self.Rsave PatFacBot = (self.DiscFac*self.LivPrb[0]*self.Rboro)**(1.0/self.CRRA)/self.Rboro if BoroCnstNat < self.BoroCnstArt: MPCmax = 1.0 # if natural borrowing constraint is overridden by artificial one, MPCmax is 1 else: MPCmax = 1.0 - WorstIncPrb**(1.0/self.CRRA)*PatFacBot MPCmin = 1.0 - PatFacTop # Store the results as attributes of self self.hNrm = hNrm self.MPCmin = MPCmin self.MPCmax = MPCmax
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- ality. The maximum MPC is the limit of the MPC as m --> mNrmMin. The minimum MPC is the limit of the MPC as m --> infty. This version deals with the different interest rates on borrowing vs saving. Parameters ---------- None Returns ------- None
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 interest rate for each agent. ''' RfreeNow = self.Rboro*np.ones(self.AgentCount) RfreeNow[self.aNrmNow > 0] = self.Rsave return RfreeNow
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 each agent.
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 = decode_packet(data) if not pkt: continue except Exception as err: if _debug: decode_file._debug(" - exception decoding packet %d: %r", i+1, err) continue # save the packet number (as viewed in Wireshark) and timestamp pkt._number = i + 1 pkt._timestamp = timestamp yield pkt
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 _debug: stop._debug(" - trigger") taskManager.trigger.set()
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.write(" deferredFns: %r\n" % (deferredFns,)) sys.stderr.write(" sleeptime: %r\n" % (sleeptime,)) sys.stderr.write("---------- stack\n") traceback.print_stack(frame) # make a list of interesting frames flist = [] f = frame while f.f_back: flist.append(f) f = f.f_back # reverse the list so it is in the same order as print_stack flist.reverse() for f in flist: sys.stderr.write("---------- frame: %s\n" % (f,)) for k, v in f.f_locals.items(): sys.stderr.write(" %s: %r\n" % (k, v)) sys.stderr.flush()
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 issubclass(cls, Capability): raise TypeError("%s is not a Capability subclass" % (cls,)) # start with everything the base has and add the new ones bases = (base,) + classes # build a new name name = base.__name__ for cls in classes: name += '+' + cls.__name__ # return a new type return type(name, bases, {})
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, Capability): raise TypeError("%s is not a Capability subclass" % (cls,)) base.__bases__ += classes for cls in classes: base.__name__ += '+' + cls.__name__
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) if _debug: Collector._debug(" - rslt: %r", rslt) return rslt
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: fns.append( (getattr(cls, '_zindex', None), xfn) ) # sort them by z-index fns.sort(key=lambda v: v[0]) if _debug: Collector._debug(" - fns: %r", fns) # now yield them in order for xindx, xfn in fns: if _debug: Collector._debug(" - yield xfn: %r", xfn) yield 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(cls) # morph into a new type newtype = type(self.__class__.__name__ + '+' + cls.__name__, bases, {}) self.__class__ = newtype # allow the new type to init if hasattr(cls, '__init__'): if _debug: Collector._debug(" - calling %r.__init__", cls) cls.__init__(self)
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 # encode the tag number part if (self.tagNumber < 15): data += (self.tagNumber << 4) else: data += 0xF0 # encode the length/value/type part if (self.tagLVT < 5): data += self.tagLVT else: data += 0x05 # save this and the extended tag value pdu.put( data ) if (self.tagNumber >= 15): pdu.put(self.tagNumber) # really short lengths are already done if (self.tagLVT >= 5): if (self.tagLVT <= 253): pdu.put( self.tagLVT ) elif (self.tagLVT <= 65535): pdu.put( 254 ) pdu.put_short( self.tagLVT ) else: pdu.put( 255 ) pdu.put_long( self.tagLVT ) # now put the data pdu.put_data(self.tagData)
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 return klass(self)
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 == Tag.contextTagClass: if tag.tagNumber == context: return tag # check for context encoded group elif tag.tagClass == Tag.openingTagClass: keeper = tag.tagNumber == context rslt = [] i += 1 lvl = 0 while i < len(self.tagList): tag = self.tagList[i] if tag.tagClass == Tag.openingTagClass: lvl += 1 elif tag.tagClass == Tag.closingTagClass: lvl -= 1 if lvl < 0: break rslt.append(tag) i += 1 # make sure everything balances if lvl >= 0: raise InvalidTag("mismatched open/close tags") # get everything we need? if keeper: return TagList(rslt) else: raise InvalidTag("unexpected tag") # try the next tag i += 1 # nothing found return None
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 return False
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 rslt
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: pass else: try: today = time.mktime( (year + 1900, month, day, 0, 0, 0, 0, 0, -1) ) day_of_week = time.gmtime(today)[6] + 1 except OverflowError: pass # put it back together self.value = (year, month, day, day_of_week)
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") # pack the components together return (objType, objInstance)
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] # get the existing cache record if it exists device_info = self.cache.get(device_instance, None) # maybe there is a record for this address if not device_info: device_info = self.cache.get(apdu.pduSource, None) # make a new one using the class provided if not device_info: device_info = self.device_info_class(device_instance, apdu.pduSource) # jam in the correct values device_info.deviceIdentifier = device_instance device_info.address = apdu.pduSource device_info.maxApduLengthAccepted = apdu.maxAPDULengthAccepted device_info.segmentationSupported = apdu.segmentationSupported device_info.vendorID = apdu.vendorID # tell the cache this is an updated record self.update_device_info(device_info)
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(device_info, '_cache_keys', (None, None)) if (cache_id is not None) and (device_info.deviceIdentifier != cache_id): if _debug: DeviceInfoCache._debug(" - device identifier updated") # remove the old reference, add the new one del self.cache[cache_id] self.cache[device_info.deviceIdentifier] = device_info if (cache_address is not None) and (device_info.address != cache_address): if _debug: DeviceInfoCache._debug(" - device address updated") # remove the old reference, add the new one del self.cache[cache_address] self.cache[device_info.address] = device_info # update the keys device_info._cache_keys = (device_info.deviceIdentifier, device_info.address)
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.localStationAddr, Address.remoteStationAddr): raise TypeError("address must be a local or remote station") else: device_info = self.cache.get(key, None) if device_info: if _debug: DeviceInfoCache._debug(" - reference bump") device_info._ref_count += 1 if _debug: DeviceInfoCache._debug(" - device_info: %r", device_info) return device_info
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: raise RuntimeError("object identifier required") # assuming the object identifier is well formed, check the instance number if (object_identifier[1] >= ObjectIdentifier.maximum_instance_number): raise RuntimeError("invalid object identifier") # make sure it hasn't already been defined if object_name in self.objectName: raise RuntimeError("already an object with name %r" % (object_name,)) if object_identifier in self.objectIdentifier: raise RuntimeError("already an object with identifier %r" % (object_identifier,)) # now put it in local dictionaries self.objectName[object_name] = obj self.objectIdentifier[object_identifier] = obj # append the new object's identifier to the local device's object list # if there is one and it has an object list property if self.localDevice and self.localDevice.objectList: self.localDevice.objectList.append(object_identifier) # let the object know which application stack it belongs to obj._app = self
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.objectIdentifier[object_identifier] # remove the object's identifier from the device's object list # if there is one and it has an object list property if self.localDevice and self.localDevice.objectList: indx = self.localDevice.objectList.index(object_identifier) del self.localDevice.objectList[indx] # make sure the object knows it's detached from an application obj._app = None
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.__name__ if hasattr(self, service_helper): service_supported = ConfirmedServiceChoice._xlate_table[service_choice] services_supported[service_supported] = 1 # look through the unconfirmed services for service_choice, service_request_class in unconfirmed_request_types.items(): service_helper = "do_" + service_request_class.__name__ if hasattr(self, service_helper): service_supported = UnconfirmedServiceChoice._xlate_table[service_choice] services_supported[service_supported] = 1 # return the bit list return services_supported
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: if v is not None: if hasattr(v, 'dict_contents'): v = v.dict_contents(as_class=as_class) use_dict.__setitem__(k, v) # return what we built/updated return use_dict
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