repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | AggShockMarkovConsumerType.getShocks | def getShocks(self):
'''
Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for
each period in the cycle. This is a copy-paste from IndShockConsumerType, with the
addition of the Markov macroeconomic state. Unfortunately, the getShocks method for
MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector
with a value for each agent, not just a single int.
Parameters
----------
None
Returns
-------
None
'''
PermShkNow = np.zeros(self.AgentCount) # Initialize shock arrays
TranShkNow = np.zeros(self.AgentCount)
newborn = self.t_age == 0
for t in range(self.T_cycle):
these = t == self.t_cycle
N = np.sum(these)
if N > 0:
IncomeDstnNow = self.IncomeDstn[t-1][self.MrkvNow] # set current income distribution
PermGroFacNow = self.PermGroFac[t-1] # and permanent growth factor
Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers
# Get random draws of income shocks from the discrete distribution
EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=True,seed=self.RNG.randint(0,2**31-1))
PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth
TranShkNow[these] = IncomeDstnNow[2][EventDraws]
# That procedure used the *last* period in the sequence for newborns, but that's not right
# Redraw shocks for newborns, using the *first* period in the sequence. Approximation.
N = np.sum(newborn)
if N > 0:
these = newborn
IncomeDstnNow = self.IncomeDstn[0][self.MrkvNow] # set current income distribution
PermGroFacNow = self.PermGroFac[0] # and permanent growth factor
Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers
# Get random draws of income shocks from the discrete distribution
EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=False,seed=self.RNG.randint(0,2**31-1))
PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth
TranShkNow[these] = IncomeDstnNow[2][EventDraws]
# PermShkNow[newborn] = 1.0
# TranShkNow[newborn] = 1.0
# Store the shocks in self
self.EmpNow = np.ones(self.AgentCount,dtype=bool)
self.EmpNow[TranShkNow == self.IncUnemp] = False
self.TranShkNow = TranShkNow*self.TranShkAggNow*self.wRteNow
self.PermShkNow = PermShkNow*self.PermShkAggNow | python | def getShocks(self):
'''
Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for
each period in the cycle. This is a copy-paste from IndShockConsumerType, with the
addition of the Markov macroeconomic state. Unfortunately, the getShocks method for
MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector
with a value for each agent, not just a single int.
Parameters
----------
None
Returns
-------
None
'''
PermShkNow = np.zeros(self.AgentCount) # Initialize shock arrays
TranShkNow = np.zeros(self.AgentCount)
newborn = self.t_age == 0
for t in range(self.T_cycle):
these = t == self.t_cycle
N = np.sum(these)
if N > 0:
IncomeDstnNow = self.IncomeDstn[t-1][self.MrkvNow] # set current income distribution
PermGroFacNow = self.PermGroFac[t-1] # and permanent growth factor
Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers
# Get random draws of income shocks from the discrete distribution
EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=True,seed=self.RNG.randint(0,2**31-1))
PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth
TranShkNow[these] = IncomeDstnNow[2][EventDraws]
# That procedure used the *last* period in the sequence for newborns, but that's not right
# Redraw shocks for newborns, using the *first* period in the sequence. Approximation.
N = np.sum(newborn)
if N > 0:
these = newborn
IncomeDstnNow = self.IncomeDstn[0][self.MrkvNow] # set current income distribution
PermGroFacNow = self.PermGroFac[0] # and permanent growth factor
Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers
# Get random draws of income shocks from the discrete distribution
EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=False,seed=self.RNG.randint(0,2**31-1))
PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth
TranShkNow[these] = IncomeDstnNow[2][EventDraws]
# PermShkNow[newborn] = 1.0
# TranShkNow[newborn] = 1.0
# Store the shocks in self
self.EmpNow = np.ones(self.AgentCount,dtype=bool)
self.EmpNow[TranShkNow == self.IncUnemp] = False
self.TranShkNow = TranShkNow*self.TranShkAggNow*self.wRteNow
self.PermShkNow = PermShkNow*self.PermShkAggNow | [
"def",
"getShocks",
"(",
"self",
")",
":",
"PermShkNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize shock arrays",
"TranShkNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"newborn",
"=",
"self",
".",
"... | Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for
each period in the cycle. This is a copy-paste from IndShockConsumerType, with the
addition of the Markov macroeconomic state. Unfortunately, the getShocks method for
MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector
with a value for each agent, not just a single int.
Parameters
----------
None
Returns
-------
None | [
"Gets",
"permanent",
"and",
"transitory",
"income",
"shocks",
"for",
"this",
"period",
".",
"Samples",
"from",
"IncomeDstn",
"for",
"each",
"period",
"in",
"the",
"cycle",
".",
"This",
"is",
"a",
"copy",
"-",
"paste",
"from",
"IndShockConsumerType",
"with",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L417-L467 | train | 201,800 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | AggShockMarkovConsumerType.getControls | def getControls(self):
'''
Calculates consumption for each consumer of this type using the consumption functions.
For this AgentType class, MrkvNow is the same for all consumers. However, in an
extension with "macroeconomic inattention", consumers might misperceive the state
and thus act as if they are in different states.
Parameters
----------
None
Returns
-------
None
'''
cNrmNow = np.zeros(self.AgentCount) + np.nan
MPCnow = np.zeros(self.AgentCount) + np.nan
MaggNow = self.getMaggNow()
MrkvNow = self.getMrkvNow()
StateCount = self.MrkvArray.shape[0]
MrkvBoolArray = np.zeros((StateCount,self.AgentCount),dtype=bool)
for i in range(StateCount):
MrkvBoolArray[i,:] = i == MrkvNow
for t in range(self.T_cycle):
these = t == self.t_cycle
for i in range(StateCount):
those = np.logical_and(these,MrkvBoolArray[i,:])
cNrmNow[those] = self.solution[t].cFunc[i](self.mNrmNow[those],MaggNow[those])
MPCnow[those] = self.solution[t].cFunc[i].derivativeX(self.mNrmNow[those],MaggNow[those]) # Marginal propensity to consume
self.cNrmNow = cNrmNow
self.MPCnow = MPCnow
return None | python | def getControls(self):
'''
Calculates consumption for each consumer of this type using the consumption functions.
For this AgentType class, MrkvNow is the same for all consumers. However, in an
extension with "macroeconomic inattention", consumers might misperceive the state
and thus act as if they are in different states.
Parameters
----------
None
Returns
-------
None
'''
cNrmNow = np.zeros(self.AgentCount) + np.nan
MPCnow = np.zeros(self.AgentCount) + np.nan
MaggNow = self.getMaggNow()
MrkvNow = self.getMrkvNow()
StateCount = self.MrkvArray.shape[0]
MrkvBoolArray = np.zeros((StateCount,self.AgentCount),dtype=bool)
for i in range(StateCount):
MrkvBoolArray[i,:] = i == MrkvNow
for t in range(self.T_cycle):
these = t == self.t_cycle
for i in range(StateCount):
those = np.logical_and(these,MrkvBoolArray[i,:])
cNrmNow[those] = self.solution[t].cFunc[i](self.mNrmNow[those],MaggNow[those])
MPCnow[those] = self.solution[t].cFunc[i].derivativeX(self.mNrmNow[those],MaggNow[those]) # Marginal propensity to consume
self.cNrmNow = cNrmNow
self.MPCnow = MPCnow
return None | [
"def",
"getControls",
"(",
"self",
")",
":",
"cNrmNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"+",
"np",
".",
"nan",
"MPCnow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"+",
"np",
".",
"nan",
"MaggNow",
... | Calculates consumption for each consumer of this type using the consumption functions.
For this AgentType class, MrkvNow is the same for all consumers. However, in an
extension with "macroeconomic inattention", consumers might misperceive the state
and thus act as if they are in different states.
Parameters
----------
None
Returns
-------
None | [
"Calculates",
"consumption",
"for",
"each",
"consumer",
"of",
"this",
"type",
"using",
"the",
"consumption",
"functions",
".",
"For",
"this",
"AgentType",
"class",
"MrkvNow",
"is",
"the",
"same",
"for",
"all",
"consumers",
".",
"However",
"in",
"an",
"extensio... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L470-L503 | train | 201,801 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasEconomy.makeAggShkDstn | def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
Parameters
----------
None
Returns
-------
None
'''
self.TranShkAggDstn = approxMeanOneLognormal(sigma=self.TranShkAggStd,N=self.TranShkAggCount)
self.PermShkAggDstn = approxMeanOneLognormal(sigma=self.PermShkAggStd,N=self.PermShkAggCount)
self.AggShkDstn = combineIndepDstns(self.PermShkAggDstn,self.TranShkAggDstn) | python | def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
Parameters
----------
None
Returns
-------
None
'''
self.TranShkAggDstn = approxMeanOneLognormal(sigma=self.TranShkAggStd,N=self.TranShkAggCount)
self.PermShkAggDstn = approxMeanOneLognormal(sigma=self.PermShkAggStd,N=self.PermShkAggCount)
self.AggShkDstn = combineIndepDstns(self.PermShkAggDstn,self.TranShkAggDstn) | [
"def",
"makeAggShkDstn",
"(",
"self",
")",
":",
"self",
".",
"TranShkAggDstn",
"=",
"approxMeanOneLognormal",
"(",
"sigma",
"=",
"self",
".",
"TranShkAggStd",
",",
"N",
"=",
"self",
".",
"TranShkAggCount",
")",
"self",
".",
"PermShkAggDstn",
"=",
"approxMeanOn... | Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
Parameters
----------
None
Returns
-------
None | [
"Creates",
"the",
"attributes",
"TranShkAggDstn",
"PermShkAggDstn",
"and",
"AggShkDstn",
".",
"Draws",
"on",
"attributes",
"TranShkAggStd",
"PermShkAddStd",
"TranShkAggCount",
"PermShkAggCount",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L988-L1003 | train | 201,802 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasEconomy.calcRandW | def calcRandW(self,aLvlNow,pLvlNow):
'''
Calculates the interest factor and wage rate this period using each agent's
capital stock to get the aggregate capital ratio.
Parameters
----------
aLvlNow : [np.array]
Agents' current end-of-period assets. Elements of the list correspond
to types in the economy, entries within arrays to agents of that type.
Returns
-------
AggVarsNow : CobbDouglasAggVars
An object containing the aggregate variables for the upcoming period:
capital-to-labor ratio, interest factor, (normalized) wage rate,
aggregate permanent and transitory shocks.
'''
# Calculate aggregate savings
AaggPrev = np.mean(np.array(aLvlNow))/np.mean(pLvlNow) # End-of-period savings from last period
# Calculate aggregate capital this period
AggregateK = np.mean(np.array(aLvlNow)) # ...becomes capital today
# This version uses end-of-period assets and
# permanent income to calculate aggregate capital, unlike the Mathematica
# version, which first applies the idiosyncratic permanent income shocks
# and then aggregates. Obviously this is mathematically equivalent.
# Get this period's aggregate shocks
PermShkAggNow = self.PermShkAggHist[self.Shk_idx]
TranShkAggNow = self.TranShkAggHist[self.Shk_idx]
self.Shk_idx += 1
AggregateL = np.mean(pLvlNow)*PermShkAggNow
# Calculate the interest factor and wage rate this period
KtoLnow = AggregateK/AggregateL
self.KtoYnow = KtoLnow**(1.0-self.CapShare)
RfreeNow = self.Rfunc(KtoLnow/TranShkAggNow)
wRteNow = self.wFunc(KtoLnow/TranShkAggNow)
MaggNow = KtoLnow*RfreeNow + wRteNow*TranShkAggNow
self.KtoLnow = KtoLnow # Need to store this as it is a sow variable
# Package the results into an object and return it
AggVarsNow = CobbDouglasAggVars(MaggNow,AaggPrev,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow)
return AggVarsNow | python | def calcRandW(self,aLvlNow,pLvlNow):
'''
Calculates the interest factor and wage rate this period using each agent's
capital stock to get the aggregate capital ratio.
Parameters
----------
aLvlNow : [np.array]
Agents' current end-of-period assets. Elements of the list correspond
to types in the economy, entries within arrays to agents of that type.
Returns
-------
AggVarsNow : CobbDouglasAggVars
An object containing the aggregate variables for the upcoming period:
capital-to-labor ratio, interest factor, (normalized) wage rate,
aggregate permanent and transitory shocks.
'''
# Calculate aggregate savings
AaggPrev = np.mean(np.array(aLvlNow))/np.mean(pLvlNow) # End-of-period savings from last period
# Calculate aggregate capital this period
AggregateK = np.mean(np.array(aLvlNow)) # ...becomes capital today
# This version uses end-of-period assets and
# permanent income to calculate aggregate capital, unlike the Mathematica
# version, which first applies the idiosyncratic permanent income shocks
# and then aggregates. Obviously this is mathematically equivalent.
# Get this period's aggregate shocks
PermShkAggNow = self.PermShkAggHist[self.Shk_idx]
TranShkAggNow = self.TranShkAggHist[self.Shk_idx]
self.Shk_idx += 1
AggregateL = np.mean(pLvlNow)*PermShkAggNow
# Calculate the interest factor and wage rate this period
KtoLnow = AggregateK/AggregateL
self.KtoYnow = KtoLnow**(1.0-self.CapShare)
RfreeNow = self.Rfunc(KtoLnow/TranShkAggNow)
wRteNow = self.wFunc(KtoLnow/TranShkAggNow)
MaggNow = KtoLnow*RfreeNow + wRteNow*TranShkAggNow
self.KtoLnow = KtoLnow # Need to store this as it is a sow variable
# Package the results into an object and return it
AggVarsNow = CobbDouglasAggVars(MaggNow,AaggPrev,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow)
return AggVarsNow | [
"def",
"calcRandW",
"(",
"self",
",",
"aLvlNow",
",",
"pLvlNow",
")",
":",
"# Calculate aggregate savings",
"AaggPrev",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"aLvlNow",
")",
")",
"/",
"np",
".",
"mean",
"(",
"pLvlNow",
")",
"# End-of-peri... | Calculates the interest factor and wage rate this period using each agent's
capital stock to get the aggregate capital ratio.
Parameters
----------
aLvlNow : [np.array]
Agents' current end-of-period assets. Elements of the list correspond
to types in the economy, entries within arrays to agents of that type.
Returns
-------
AggVarsNow : CobbDouglasAggVars
An object containing the aggregate variables for the upcoming period:
capital-to-labor ratio, interest factor, (normalized) wage rate,
aggregate permanent and transitory shocks. | [
"Calculates",
"the",
"interest",
"factor",
"and",
"wage",
"rate",
"this",
"period",
"using",
"each",
"agent",
"s",
"capital",
"stock",
"to",
"get",
"the",
"aggregate",
"capital",
"ratio",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1045-L1089 | train | 201,803 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasEconomy.calcAFunc | def calcAFunc(self,MaggNow,AaggNow):
'''
Calculate a new aggregate savings rule based on the history
of the aggregate savings and aggregate market resources from a simulation.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing a new savings rule
'''
verbose = self.verbose
discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS
update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters
total_periods = len(MaggNow)
# Regress the log savings against log market resources
logAagg = np.log(AaggNow[discard_periods:total_periods])
logMagg = np.log(MaggNow[discard_periods-1:total_periods-1])
slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg,logAagg)
# Make a new aggregate savings rule by combining the new regression parameters
# with the previous guess
intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev
slope = update_weight*slope + (1.0-update_weight)*self.slope_prev
AFunc = AggregateSavingRule(intercept,slope) # Make a new next-period capital function
# Save the new values as "previous" values for the next iteration
self.intercept_prev = intercept
self.slope_prev = slope
# Plot aggregate resources vs aggregate savings for this run and print the new parameters
if verbose:
print('intercept=' + str(intercept) + ', slope=' + str(slope) + ', r-sq=' + str(r_value**2))
#plot_start = discard_periods
#plt.plot(logMagg[plot_start:],logAagg[plot_start:],'.k')
#plt.show()
return AggShocksDynamicRule(AFunc) | python | def calcAFunc(self,MaggNow,AaggNow):
'''
Calculate a new aggregate savings rule based on the history
of the aggregate savings and aggregate market resources from a simulation.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing a new savings rule
'''
verbose = self.verbose
discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS
update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters
total_periods = len(MaggNow)
# Regress the log savings against log market resources
logAagg = np.log(AaggNow[discard_periods:total_periods])
logMagg = np.log(MaggNow[discard_periods-1:total_periods-1])
slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg,logAagg)
# Make a new aggregate savings rule by combining the new regression parameters
# with the previous guess
intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev
slope = update_weight*slope + (1.0-update_weight)*self.slope_prev
AFunc = AggregateSavingRule(intercept,slope) # Make a new next-period capital function
# Save the new values as "previous" values for the next iteration
self.intercept_prev = intercept
self.slope_prev = slope
# Plot aggregate resources vs aggregate savings for this run and print the new parameters
if verbose:
print('intercept=' + str(intercept) + ', slope=' + str(slope) + ', r-sq=' + str(r_value**2))
#plot_start = discard_periods
#plt.plot(logMagg[plot_start:],logAagg[plot_start:],'.k')
#plt.show()
return AggShocksDynamicRule(AFunc) | [
"def",
"calcAFunc",
"(",
"self",
",",
"MaggNow",
",",
"AaggNow",
")",
":",
"verbose",
"=",
"self",
".",
"verbose",
"discard_periods",
"=",
"self",
".",
"T_discard",
"# Throw out the first T periods to allow the simulation to approach the SS",
"update_weight",
"=",
"1.",... | Calculate a new aggregate savings rule based on the history
of the aggregate savings and aggregate market resources from a simulation.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing a new savings rule | [
"Calculate",
"a",
"new",
"aggregate",
"savings",
"rule",
"based",
"on",
"the",
"history",
"of",
"the",
"aggregate",
"savings",
"and",
"aggregate",
"market",
"resources",
"from",
"a",
"simulation",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1091-L1135 | train | 201,804 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | SmallOpenEconomy.update | def update(self):
'''
Use primitive parameters to set basic objects. This is an extremely stripped-down version
of update for CobbDouglasEconomy.
Parameters
----------
none
Returns
-------
none
'''
self.kSS = 1.0
self.MSS = 1.0
self.KtoLnow_init = self.kSS
self.Rfunc = ConstantFunction(self.Rfree)
self.wFunc = ConstantFunction(self.wRte)
self.RfreeNow_init = self.Rfunc(self.kSS)
self.wRteNow_init = self.wFunc(self.kSS)
self.MaggNow_init = self.kSS
self.AaggNow_init = self.kSS
self.PermShkAggNow_init = 1.0
self.TranShkAggNow_init = 1.0
self.makeAggShkDstn()
self.AFunc = ConstantFunction(1.0) | python | def update(self):
'''
Use primitive parameters to set basic objects. This is an extremely stripped-down version
of update for CobbDouglasEconomy.
Parameters
----------
none
Returns
-------
none
'''
self.kSS = 1.0
self.MSS = 1.0
self.KtoLnow_init = self.kSS
self.Rfunc = ConstantFunction(self.Rfree)
self.wFunc = ConstantFunction(self.wRte)
self.RfreeNow_init = self.Rfunc(self.kSS)
self.wRteNow_init = self.wFunc(self.kSS)
self.MaggNow_init = self.kSS
self.AaggNow_init = self.kSS
self.PermShkAggNow_init = 1.0
self.TranShkAggNow_init = 1.0
self.makeAggShkDstn()
self.AFunc = ConstantFunction(1.0) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"kSS",
"=",
"1.0",
"self",
".",
"MSS",
"=",
"1.0",
"self",
".",
"KtoLnow_init",
"=",
"self",
".",
"kSS",
"self",
".",
"Rfunc",
"=",
"ConstantFunction",
"(",
"self",
".",
"Rfree",
")",
"self",
"."... | Use primitive parameters to set basic objects. This is an extremely stripped-down version
of update for CobbDouglasEconomy.
Parameters
----------
none
Returns
-------
none | [
"Use",
"primitive",
"parameters",
"to",
"set",
"basic",
"objects",
".",
"This",
"is",
"an",
"extremely",
"stripped",
"-",
"down",
"version",
"of",
"update",
"for",
"CobbDouglasEconomy",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1173-L1198 | train | 201,805 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | SmallOpenEconomy.makeAggShkHist | def makeAggShkHist(self):
'''
Make simulated histories of aggregate transitory and permanent shocks. Histories are of
length self.act_T, for use in the general equilibrium simulation. This replicates the same
method for CobbDouglasEconomy; future version should create parent class.
Parameters
----------
None
Returns
-------
None
'''
sim_periods = self.act_T
Events = np.arange(self.AggShkDstn[0].size) # just a list of integers
EventDraws = drawDiscrete(N=sim_periods,P=self.AggShkDstn[0],X=Events,seed=0)
PermShkAggHist = self.AggShkDstn[1][EventDraws]
TranShkAggHist = self.AggShkDstn[2][EventDraws]
# Store the histories
self.PermShkAggHist = PermShkAggHist
self.TranShkAggHist = TranShkAggHist | python | def makeAggShkHist(self):
'''
Make simulated histories of aggregate transitory and permanent shocks. Histories are of
length self.act_T, for use in the general equilibrium simulation. This replicates the same
method for CobbDouglasEconomy; future version should create parent class.
Parameters
----------
None
Returns
-------
None
'''
sim_periods = self.act_T
Events = np.arange(self.AggShkDstn[0].size) # just a list of integers
EventDraws = drawDiscrete(N=sim_periods,P=self.AggShkDstn[0],X=Events,seed=0)
PermShkAggHist = self.AggShkDstn[1][EventDraws]
TranShkAggHist = self.AggShkDstn[2][EventDraws]
# Store the histories
self.PermShkAggHist = PermShkAggHist
self.TranShkAggHist = TranShkAggHist | [
"def",
"makeAggShkHist",
"(",
"self",
")",
":",
"sim_periods",
"=",
"self",
".",
"act_T",
"Events",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"AggShkDstn",
"[",
"0",
"]",
".",
"size",
")",
"# just a list of integers",
"EventDraws",
"=",
"drawDiscrete",
"... | Make simulated histories of aggregate transitory and permanent shocks. Histories are of
length self.act_T, for use in the general equilibrium simulation. This replicates the same
method for CobbDouglasEconomy; future version should create parent class.
Parameters
----------
None
Returns
-------
None | [
"Make",
"simulated",
"histories",
"of",
"aggregate",
"transitory",
"and",
"permanent",
"shocks",
".",
"Histories",
"are",
"of",
"length",
"self",
".",
"act_T",
"for",
"use",
"in",
"the",
"general",
"equilibrium",
"simulation",
".",
"This",
"replicates",
"the",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1250-L1272 | train | 201,806 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | SmallOpenEconomy.getAggShocks | def getAggShocks(self):
'''
Returns aggregate state variables and shocks for this period. The capital-to-labor ratio
is irrelevant and thus treated as constant, and the wage and interest rates are also
constant. However, aggregate shocks are assigned from a prespecified history.
Parameters
----------
None
Returns
-------
AggVarsNow : CobbDouglasAggVars
Aggregate state and shock variables for this period.
'''
# Get this period's aggregate shocks
PermShkAggNow = self.PermShkAggHist[self.Shk_idx]
TranShkAggNow = self.TranShkAggHist[self.Shk_idx]
self.Shk_idx += 1
# Factor prices are constant
RfreeNow = self.Rfunc(1.0/PermShkAggNow)
wRteNow = self.wFunc(1.0/PermShkAggNow)
# Aggregates are irrelavent
AaggNow = 1.0
MaggNow = 1.0
KtoLnow = 1.0/PermShkAggNow
# Package the results into an object and return it
AggVarsNow = CobbDouglasAggVars(MaggNow,AaggNow,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow)
return AggVarsNow | python | def getAggShocks(self):
'''
Returns aggregate state variables and shocks for this period. The capital-to-labor ratio
is irrelevant and thus treated as constant, and the wage and interest rates are also
constant. However, aggregate shocks are assigned from a prespecified history.
Parameters
----------
None
Returns
-------
AggVarsNow : CobbDouglasAggVars
Aggregate state and shock variables for this period.
'''
# Get this period's aggregate shocks
PermShkAggNow = self.PermShkAggHist[self.Shk_idx]
TranShkAggNow = self.TranShkAggHist[self.Shk_idx]
self.Shk_idx += 1
# Factor prices are constant
RfreeNow = self.Rfunc(1.0/PermShkAggNow)
wRteNow = self.wFunc(1.0/PermShkAggNow)
# Aggregates are irrelavent
AaggNow = 1.0
MaggNow = 1.0
KtoLnow = 1.0/PermShkAggNow
# Package the results into an object and return it
AggVarsNow = CobbDouglasAggVars(MaggNow,AaggNow,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow)
return AggVarsNow | [
"def",
"getAggShocks",
"(",
"self",
")",
":",
"# Get this period's aggregate shocks",
"PermShkAggNow",
"=",
"self",
".",
"PermShkAggHist",
"[",
"self",
".",
"Shk_idx",
"]",
"TranShkAggNow",
"=",
"self",
".",
"TranShkAggHist",
"[",
"self",
".",
"Shk_idx",
"]",
"s... | Returns aggregate state variables and shocks for this period. The capital-to-labor ratio
is irrelevant and thus treated as constant, and the wage and interest rates are also
constant. However, aggregate shocks are assigned from a prespecified history.
Parameters
----------
None
Returns
-------
AggVarsNow : CobbDouglasAggVars
Aggregate state and shock variables for this period. | [
"Returns",
"aggregate",
"state",
"variables",
"and",
"shocks",
"for",
"this",
"period",
".",
"The",
"capital",
"-",
"to",
"-",
"labor",
"ratio",
"is",
"irrelevant",
"and",
"thus",
"treated",
"as",
"constant",
"and",
"the",
"wage",
"and",
"interest",
"rates",... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1274-L1305 | train | 201,807 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasMarkovEconomy.makeAggShkDstn | def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
This version accounts for the Markov macroeconomic state.
Parameters
----------
None
Returns
-------
None
'''
TranShkAggDstn = []
PermShkAggDstn = []
AggShkDstn = []
StateCount = self.MrkvArray.shape[0]
for i in range(StateCount):
TranShkAggDstn.append(approxMeanOneLognormal(sigma=self.TranShkAggStd[i],N=self.TranShkAggCount))
PermShkAggDstn.append(approxMeanOneLognormal(sigma=self.PermShkAggStd[i],N=self.PermShkAggCount))
AggShkDstn.append(combineIndepDstns(PermShkAggDstn[-1],TranShkAggDstn[-1]))
self.TranShkAggDstn = TranShkAggDstn
self.PermShkAggDstn = PermShkAggDstn
self.AggShkDstn = AggShkDstn | python | def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
This version accounts for the Markov macroeconomic state.
Parameters
----------
None
Returns
-------
None
'''
TranShkAggDstn = []
PermShkAggDstn = []
AggShkDstn = []
StateCount = self.MrkvArray.shape[0]
for i in range(StateCount):
TranShkAggDstn.append(approxMeanOneLognormal(sigma=self.TranShkAggStd[i],N=self.TranShkAggCount))
PermShkAggDstn.append(approxMeanOneLognormal(sigma=self.PermShkAggStd[i],N=self.PermShkAggCount))
AggShkDstn.append(combineIndepDstns(PermShkAggDstn[-1],TranShkAggDstn[-1]))
self.TranShkAggDstn = TranShkAggDstn
self.PermShkAggDstn = PermShkAggDstn
self.AggShkDstn = AggShkDstn | [
"def",
"makeAggShkDstn",
"(",
"self",
")",
":",
"TranShkAggDstn",
"=",
"[",
"]",
"PermShkAggDstn",
"=",
"[",
"]",
"AggShkDstn",
"=",
"[",
"]",
"StateCount",
"=",
"self",
".",
"MrkvArray",
".",
"shape",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"... | Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
This version accounts for the Markov macroeconomic state.
Parameters
----------
None
Returns
-------
None | [
"Creates",
"the",
"attributes",
"TranShkAggDstn",
"PermShkAggDstn",
"and",
"AggShkDstn",
".",
"Draws",
"on",
"attributes",
"TranShkAggStd",
"PermShkAddStd",
"TranShkAggCount",
"PermShkAggCount",
".",
"This",
"version",
"accounts",
"for",
"the",
"Markov",
"macroeconomic",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1391-L1417 | train | 201,808 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasMarkovEconomy.makeMrkvHist | def makeMrkvHist(self):
'''
Makes a history of macroeconomic Markov states, stored in the attribute
MrkvNow_hist. This version ensures that each state is reached a sufficient
number of times to have a valid sample for calcDynamics to produce a good
dynamic rule. It will sometimes cause act_T to be increased beyond its
initially specified level.
Parameters
----------
None
Returns
-------
None
'''
if hasattr(self,'loops_max'):
loops_max = self.loops_max
else: # Maximum number of loops; final act_T never exceeds act_T*loops_max
loops_max = 10
state_T_min = 50 # Choose minimum number of periods in each state for a valid Markov sequence
logit_scale = 0.2 # Scaling factor on logit choice shocks when jumping to a new state
# Values close to zero make the most underrepresented states very likely to visit, while
# large values of logit_scale make any state very likely to be jumped to.
# Reset act_T to the level actually specified by the user
if hasattr(self,'act_T_orig'):
act_T = self.act_T_orig
else: # Or store it for the first time
self.act_T_orig = self.act_T
act_T = self.act_T
# Find the long run distribution of Markov states
w, v = np.linalg.eig(np.transpose(self.MrkvArray))
idx = (np.abs(w-1.0)).argmin()
x = v[:,idx].astype(float)
LR_dstn = (x/np.sum(x))
# Initialize the Markov history and set up transitions
MrkvNow_hist = np.zeros(self.act_T_orig,dtype=int)
cutoffs = np.cumsum(self.MrkvArray,axis=1)
loops = 0
go = True
MrkvNow = self.MrkvNow_init
t = 0
StateCount = self.MrkvArray.shape[0]
# Add histories until each state has been visited at least state_T_min times
while go:
draws = drawUniform(N=self.act_T_orig,seed=loops)
for s in range(draws.size): # Add act_T_orig more periods
MrkvNow_hist[t] = MrkvNow
MrkvNow = np.searchsorted(cutoffs[MrkvNow,:],draws[s])
t += 1
# Calculate the empirical distribution
state_T = np.zeros(StateCount)
for i in range(StateCount):
state_T[i] = np.sum(MrkvNow_hist==i)
# Check whether each state has been visited state_T_min times
if np.all(state_T >= state_T_min):
go = False # If so, terminate the loop
continue
# Choose an underrepresented state to "jump" to
if np.any(state_T == 0): # If any states have *never* been visited, randomly choose one of those
never_visited = np.where(np.array(state_T == 0))[0]
MrkvNow = np.random.choice(never_visited)
else: # Otherwise, use logit choice probabilities to visit an underrepresented state
emp_dstn = state_T/act_T
ratios = LR_dstn/emp_dstn
ratios_adj = ratios - np.max(ratios)
ratios_exp = np.exp(ratios_adj/logit_scale)
ratios_sum = np.sum(ratios_exp)
jump_probs = ratios_exp/ratios_sum
cum_probs = np.cumsum(jump_probs)
MrkvNow = np.searchsorted(cum_probs,draws[-1])
loops += 1
# Make the Markov state history longer by act_T_orig periods
if loops >= loops_max:
go = False
print('makeMrkvHist reached maximum number of loops without generating a valid sequence!')
else:
MrkvNow_new = np.zeros(self.act_T_orig,dtype=int)
MrkvNow_hist = np.concatenate((MrkvNow_hist,MrkvNow_new))
act_T += self.act_T_orig
# Store the results as attributes of self
self.MrkvNow_hist = MrkvNow_hist
self.act_T = act_T | python | def makeMrkvHist(self):
'''
Makes a history of macroeconomic Markov states, stored in the attribute
MrkvNow_hist. This version ensures that each state is reached a sufficient
number of times to have a valid sample for calcDynamics to produce a good
dynamic rule. It will sometimes cause act_T to be increased beyond its
initially specified level.
Parameters
----------
None
Returns
-------
None
'''
if hasattr(self,'loops_max'):
loops_max = self.loops_max
else: # Maximum number of loops; final act_T never exceeds act_T*loops_max
loops_max = 10
state_T_min = 50 # Choose minimum number of periods in each state for a valid Markov sequence
logit_scale = 0.2 # Scaling factor on logit choice shocks when jumping to a new state
# Values close to zero make the most underrepresented states very likely to visit, while
# large values of logit_scale make any state very likely to be jumped to.
# Reset act_T to the level actually specified by the user
if hasattr(self,'act_T_orig'):
act_T = self.act_T_orig
else: # Or store it for the first time
self.act_T_orig = self.act_T
act_T = self.act_T
# Find the long run distribution of Markov states
w, v = np.linalg.eig(np.transpose(self.MrkvArray))
idx = (np.abs(w-1.0)).argmin()
x = v[:,idx].astype(float)
LR_dstn = (x/np.sum(x))
# Initialize the Markov history and set up transitions
MrkvNow_hist = np.zeros(self.act_T_orig,dtype=int)
cutoffs = np.cumsum(self.MrkvArray,axis=1)
loops = 0
go = True
MrkvNow = self.MrkvNow_init
t = 0
StateCount = self.MrkvArray.shape[0]
# Add histories until each state has been visited at least state_T_min times
while go:
draws = drawUniform(N=self.act_T_orig,seed=loops)
for s in range(draws.size): # Add act_T_orig more periods
MrkvNow_hist[t] = MrkvNow
MrkvNow = np.searchsorted(cutoffs[MrkvNow,:],draws[s])
t += 1
# Calculate the empirical distribution
state_T = np.zeros(StateCount)
for i in range(StateCount):
state_T[i] = np.sum(MrkvNow_hist==i)
# Check whether each state has been visited state_T_min times
if np.all(state_T >= state_T_min):
go = False # If so, terminate the loop
continue
# Choose an underrepresented state to "jump" to
if np.any(state_T == 0): # If any states have *never* been visited, randomly choose one of those
never_visited = np.where(np.array(state_T == 0))[0]
MrkvNow = np.random.choice(never_visited)
else: # Otherwise, use logit choice probabilities to visit an underrepresented state
emp_dstn = state_T/act_T
ratios = LR_dstn/emp_dstn
ratios_adj = ratios - np.max(ratios)
ratios_exp = np.exp(ratios_adj/logit_scale)
ratios_sum = np.sum(ratios_exp)
jump_probs = ratios_exp/ratios_sum
cum_probs = np.cumsum(jump_probs)
MrkvNow = np.searchsorted(cum_probs,draws[-1])
loops += 1
# Make the Markov state history longer by act_T_orig periods
if loops >= loops_max:
go = False
print('makeMrkvHist reached maximum number of loops without generating a valid sequence!')
else:
MrkvNow_new = np.zeros(self.act_T_orig,dtype=int)
MrkvNow_hist = np.concatenate((MrkvNow_hist,MrkvNow_new))
act_T += self.act_T_orig
# Store the results as attributes of self
self.MrkvNow_hist = MrkvNow_hist
self.act_T = act_T | [
"def",
"makeMrkvHist",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'loops_max'",
")",
":",
"loops_max",
"=",
"self",
".",
"loops_max",
"else",
":",
"# Maximum number of loops; final act_T never exceeds act_T*loops_max",
"loops_max",
"=",
"10",
"state_... | Makes a history of macroeconomic Markov states, stored in the attribute
MrkvNow_hist. This version ensures that each state is reached a sufficient
number of times to have a valid sample for calcDynamics to produce a good
dynamic rule. It will sometimes cause act_T to be increased beyond its
initially specified level.
Parameters
----------
None
Returns
-------
None | [
"Makes",
"a",
"history",
"of",
"macroeconomic",
"Markov",
"states",
"stored",
"in",
"the",
"attribute",
"MrkvNow_hist",
".",
"This",
"version",
"ensures",
"that",
"each",
"state",
"is",
"reached",
"a",
"sufficient",
"number",
"of",
"times",
"to",
"have",
"a",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1463-L1555 | train | 201,809 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | CobbDouglasMarkovEconomy.calcAFunc | def calcAFunc(self,MaggNow,AaggNow):
'''
Calculate a new aggregate savings rule based on the history of the
aggregate savings and aggregate market resources from a simulation.
Calculates an aggregate saving rule for each macroeconomic Markov state.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing new saving rules for each Markov state.
'''
verbose = self.verbose
discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS
update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters
total_periods = len(MaggNow)
# Trim the histories of M_t and A_t and convert them to logs
logAagg = np.log(AaggNow[discard_periods:total_periods])
logMagg = np.log(MaggNow[discard_periods-1:total_periods-1])
MrkvHist = self.MrkvNow_hist[discard_periods-1:total_periods-1]
# For each Markov state, regress A_t on M_t and update the saving rule
AFunc_list = []
rSq_list = []
for i in range(self.MrkvArray.shape[0]):
these = i == MrkvHist
slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg[these],logAagg[these])
#if verbose:
# plt.plot(logMagg[these],logAagg[these],'.')
# Make a new aggregate savings rule by combining the new regression parameters
# with the previous guess
intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev[i]
slope = update_weight*slope + (1.0-update_weight)*self.slope_prev[i]
AFunc_list.append(AggregateSavingRule(intercept,slope)) # Make a new next-period capital function
rSq_list.append(r_value**2)
# Save the new values as "previous" values for the next iteration
self.intercept_prev[i] = intercept
self.slope_prev[i] = slope
# Plot aggregate resources vs aggregate savings for this run and print the new parameters
if verbose:
print('intercept=' + str(self.intercept_prev) + ', slope=' + str(self.slope_prev) + ', r-sq=' + str(rSq_list))
#plt.show()
return AggShocksDynamicRule(AFunc_list) | python | def calcAFunc(self,MaggNow,AaggNow):
'''
Calculate a new aggregate savings rule based on the history of the
aggregate savings and aggregate market resources from a simulation.
Calculates an aggregate saving rule for each macroeconomic Markov state.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing new saving rules for each Markov state.
'''
verbose = self.verbose
discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS
update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters
total_periods = len(MaggNow)
# Trim the histories of M_t and A_t and convert them to logs
logAagg = np.log(AaggNow[discard_periods:total_periods])
logMagg = np.log(MaggNow[discard_periods-1:total_periods-1])
MrkvHist = self.MrkvNow_hist[discard_periods-1:total_periods-1]
# For each Markov state, regress A_t on M_t and update the saving rule
AFunc_list = []
rSq_list = []
for i in range(self.MrkvArray.shape[0]):
these = i == MrkvHist
slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg[these],logAagg[these])
#if verbose:
# plt.plot(logMagg[these],logAagg[these],'.')
# Make a new aggregate savings rule by combining the new regression parameters
# with the previous guess
intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev[i]
slope = update_weight*slope + (1.0-update_weight)*self.slope_prev[i]
AFunc_list.append(AggregateSavingRule(intercept,slope)) # Make a new next-period capital function
rSq_list.append(r_value**2)
# Save the new values as "previous" values for the next iteration
self.intercept_prev[i] = intercept
self.slope_prev[i] = slope
# Plot aggregate resources vs aggregate savings for this run and print the new parameters
if verbose:
print('intercept=' + str(self.intercept_prev) + ', slope=' + str(self.slope_prev) + ', r-sq=' + str(rSq_list))
#plt.show()
return AggShocksDynamicRule(AFunc_list) | [
"def",
"calcAFunc",
"(",
"self",
",",
"MaggNow",
",",
"AaggNow",
")",
":",
"verbose",
"=",
"self",
".",
"verbose",
"discard_periods",
"=",
"self",
".",
"T_discard",
"# Throw out the first T periods to allow the simulation to approach the SS",
"update_weight",
"=",
"1.",... | Calculate a new aggregate savings rule based on the history of the
aggregate savings and aggregate market resources from a simulation.
Calculates an aggregate saving rule for each macroeconomic Markov state.
Parameters
----------
MaggNow : [float]
List of the history of the simulated aggregate market resources for an economy.
AaggNow : [float]
List of the history of the simulated aggregate savings for an economy.
Returns
-------
(unnamed) : CapDynamicRule
Object containing new saving rules for each Markov state. | [
"Calculate",
"a",
"new",
"aggregate",
"savings",
"rule",
"based",
"on",
"the",
"history",
"of",
"the",
"aggregate",
"savings",
"and",
"aggregate",
"market",
"resources",
"from",
"a",
"simulation",
".",
"Calculates",
"an",
"aggregate",
"saving",
"rule",
"for",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L1572-L1625 | train | 201,810 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | getKYratioDifference | def getKYratioDifference(Economy,param_name,param_count,center,spread,dist_type):
'''
Finds the difference between simulated and target capital to income ratio in an economy when
a given parameter has heterogeneity according to some distribution.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center : float
A measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
diff : float
Difference between simulated and target capital to income ratio for this economy.
'''
Economy(LorenzBool = False, ManyStatsBool = False) # Make sure we're not wasting time calculating stuff
Economy.distributeParams(param_name,param_count,center,spread,dist_type) # Distribute parameters
Economy.solve()
diff = Economy.calcKYratioDifference()
print('getKYratioDifference tried center = ' + str(center) + ' and got ' + str(diff))
return diff | python | def getKYratioDifference(Economy,param_name,param_count,center,spread,dist_type):
'''
Finds the difference between simulated and target capital to income ratio in an economy when
a given parameter has heterogeneity according to some distribution.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center : float
A measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
diff : float
Difference between simulated and target capital to income ratio for this economy.
'''
Economy(LorenzBool = False, ManyStatsBool = False) # Make sure we're not wasting time calculating stuff
Economy.distributeParams(param_name,param_count,center,spread,dist_type) # Distribute parameters
Economy.solve()
diff = Economy.calcKYratioDifference()
print('getKYratioDifference tried center = ' + str(center) + ' and got ' + str(diff))
return diff | [
"def",
"getKYratioDifference",
"(",
"Economy",
",",
"param_name",
",",
"param_count",
",",
"center",
",",
"spread",
",",
"dist_type",
")",
":",
"Economy",
"(",
"LorenzBool",
"=",
"False",
",",
"ManyStatsBool",
"=",
"False",
")",
"# Make sure we're not wasting time... | Finds the difference between simulated and target capital to income ratio in an economy when
a given parameter has heterogeneity according to some distribution.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center : float
A measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
diff : float
Difference between simulated and target capital to income ratio for this economy. | [
"Finds",
"the",
"difference",
"between",
"simulated",
"and",
"target",
"capital",
"to",
"income",
"ratio",
"in",
"an",
"economy",
"when",
"a",
"given",
"parameter",
"has",
"heterogeneity",
"according",
"to",
"some",
"distribution",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L386-L416 | train | 201,811 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | findLorenzDistanceAtTargetKY | def findLorenzDistanceAtTargetKY(Economy,param_name,param_count,center_range,spread,dist_type):
'''
Finds the sum of squared distances between simulated and target Lorenz points in an economy when
a given parameter has heterogeneity according to some distribution. The class of distribution
and a measure of spread are given as inputs, but the measure of centrality such that the capital
to income ratio matches the target ratio must be found.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center_range : [float,float]
Bounding values for a measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points for this economy (sqrt).
'''
# Define the function to search for the correct value of center, then find its zero
intermediateObjective = lambda center : getKYratioDifference(Economy = Economy,
param_name = param_name,
param_count = param_count,
center = center,
spread = spread,
dist_type = dist_type)
optimal_center = brentq(intermediateObjective,center_range[0],center_range[1],xtol=10**(-6))
Economy.center_save = optimal_center
# Get the sum of squared Lorenz distances given the correct distribution of the parameter
Economy(LorenzBool = True) # Make sure we actually calculate simulated Lorenz points
Economy.distributeParams(param_name,param_count,optimal_center,spread,dist_type) # Distribute parameters
Economy.solveAgents()
Economy.makeHistory()
dist = Economy.calcLorenzDistance()
Economy(LorenzBool = False)
print ('findLorenzDistanceAtTargetKY tried spread = ' + str(spread) + ' and got ' + str(dist))
return dist | python | def findLorenzDistanceAtTargetKY(Economy,param_name,param_count,center_range,spread,dist_type):
'''
Finds the sum of squared distances between simulated and target Lorenz points in an economy when
a given parameter has heterogeneity according to some distribution. The class of distribution
and a measure of spread are given as inputs, but the measure of centrality such that the capital
to income ratio matches the target ratio must be found.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center_range : [float,float]
Bounding values for a measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points for this economy (sqrt).
'''
# Define the function to search for the correct value of center, then find its zero
intermediateObjective = lambda center : getKYratioDifference(Economy = Economy,
param_name = param_name,
param_count = param_count,
center = center,
spread = spread,
dist_type = dist_type)
optimal_center = brentq(intermediateObjective,center_range[0],center_range[1],xtol=10**(-6))
Economy.center_save = optimal_center
# Get the sum of squared Lorenz distances given the correct distribution of the parameter
Economy(LorenzBool = True) # Make sure we actually calculate simulated Lorenz points
Economy.distributeParams(param_name,param_count,optimal_center,spread,dist_type) # Distribute parameters
Economy.solveAgents()
Economy.makeHistory()
dist = Economy.calcLorenzDistance()
Economy(LorenzBool = False)
print ('findLorenzDistanceAtTargetKY tried spread = ' + str(spread) + ' and got ' + str(dist))
return dist | [
"def",
"findLorenzDistanceAtTargetKY",
"(",
"Economy",
",",
"param_name",
",",
"param_count",
",",
"center_range",
",",
"spread",
",",
"dist_type",
")",
":",
"# Define the function to search for the correct value of center, then find its zero",
"intermediateObjective",
"=",
"la... | Finds the sum of squared distances between simulated and target Lorenz points in an economy when
a given parameter has heterogeneity according to some distribution. The class of distribution
and a measure of spread are given as inputs, but the measure of centrality such that the capital
to income ratio matches the target ratio must be found.
Parameters
----------
Economy : cstwMPCmarket
An object representing the entire economy, containing the various AgentTypes as an attribute.
param_name : string
The name of the parameter of interest that varies across the population.
param_count : int
The number of different values the parameter of interest will take on.
center_range : [float,float]
Bounding values for a measure of centrality for the distribution of the parameter of interest.
spread : float
A measure of spread or diffusion for the distribution of the parameter of interest.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points for this economy (sqrt). | [
"Finds",
"the",
"sum",
"of",
"squared",
"distances",
"between",
"simulated",
"and",
"target",
"Lorenz",
"points",
"in",
"an",
"economy",
"when",
"a",
"given",
"parameter",
"has",
"heterogeneity",
"according",
"to",
"some",
"distribution",
".",
"The",
"class",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L419-L464 | train | 201,812 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | calcStationaryAgeDstn | def calcStationaryAgeDstn(LivPrb,terminal_period):
'''
Calculates the steady state proportions of each age given survival probability sequence LivPrb.
Assumes that agents who die are replaced by a newborn agent with t_age=0.
Parameters
----------
LivPrb : [float]
Sequence of survival probabilities in ordinary chronological order. Has length T_cycle.
terminal_period : bool
Indicator for whether a terminal period follows the last period in the cycle (with LivPrb=0).
Returns
-------
AgeDstn : np.array
Stationary distribution of age. Stochastic vector with frequencies of each age.
'''
T = len(LivPrb)
if terminal_period:
MrkvArray = np.zeros((T+1,T+1))
top = T
else:
MrkvArray = np.zeros((T,T))
top = T-1
for t in range(top):
MrkvArray[t,0] = 1.0 - LivPrb[t]
MrkvArray[t,t+1] = LivPrb[t]
MrkvArray[t+1,0] = 1.0
w, v = np.linalg.eig(np.transpose(MrkvArray))
idx = (np.abs(w-1.0)).argmin()
x = v[:,idx].astype(float)
AgeDstn = (x/np.sum(x))
return AgeDstn | python | def calcStationaryAgeDstn(LivPrb,terminal_period):
'''
Calculates the steady state proportions of each age given survival probability sequence LivPrb.
Assumes that agents who die are replaced by a newborn agent with t_age=0.
Parameters
----------
LivPrb : [float]
Sequence of survival probabilities in ordinary chronological order. Has length T_cycle.
terminal_period : bool
Indicator for whether a terminal period follows the last period in the cycle (with LivPrb=0).
Returns
-------
AgeDstn : np.array
Stationary distribution of age. Stochastic vector with frequencies of each age.
'''
T = len(LivPrb)
if terminal_period:
MrkvArray = np.zeros((T+1,T+1))
top = T
else:
MrkvArray = np.zeros((T,T))
top = T-1
for t in range(top):
MrkvArray[t,0] = 1.0 - LivPrb[t]
MrkvArray[t,t+1] = LivPrb[t]
MrkvArray[t+1,0] = 1.0
w, v = np.linalg.eig(np.transpose(MrkvArray))
idx = (np.abs(w-1.0)).argmin()
x = v[:,idx].astype(float)
AgeDstn = (x/np.sum(x))
return AgeDstn | [
"def",
"calcStationaryAgeDstn",
"(",
"LivPrb",
",",
"terminal_period",
")",
":",
"T",
"=",
"len",
"(",
"LivPrb",
")",
"if",
"terminal_period",
":",
"MrkvArray",
"=",
"np",
".",
"zeros",
"(",
"(",
"T",
"+",
"1",
",",
"T",
"+",
"1",
")",
")",
"top",
... | Calculates the steady state proportions of each age given survival probability sequence LivPrb.
Assumes that agents who die are replaced by a newborn agent with t_age=0.
Parameters
----------
LivPrb : [float]
Sequence of survival probabilities in ordinary chronological order. Has length T_cycle.
terminal_period : bool
Indicator for whether a terminal period follows the last period in the cycle (with LivPrb=0).
Returns
-------
AgeDstn : np.array
Stationary distribution of age. Stochastic vector with frequencies of each age. | [
"Calculates",
"the",
"steady",
"state",
"proportions",
"of",
"each",
"age",
"given",
"survival",
"probability",
"sequence",
"LivPrb",
".",
"Assumes",
"that",
"agents",
"who",
"die",
"are",
"replaced",
"by",
"a",
"newborn",
"agent",
"with",
"t_age",
"=",
"0",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L466-L500 | train | 201,813 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCagent.updateIncomeProcess | def updateIncomeProcess(self):
'''
An alternative method for constructing the income process in the infinite horizon model.
Parameters
----------
none
Returns
-------
none
'''
if self.cycles == 0:
tax_rate = (self.IncUnemp*self.UnempPrb)/((1.0-self.UnempPrb)*self.IndL)
TranShkDstn = deepcopy(approxMeanOneLognormal(self.TranShkCount,sigma=self.TranShkStd[0],tail_N=0))
TranShkDstn[0] = np.insert(TranShkDstn[0]*(1.0-self.UnempPrb),0,self.UnempPrb)
TranShkDstn[1] = np.insert(TranShkDstn[1]*(1.0-tax_rate)*self.IndL,0,self.IncUnemp)
PermShkDstn = approxMeanOneLognormal(self.PermShkCount,sigma=self.PermShkStd[0],tail_N=0)
self.IncomeDstn = [combineIndepDstns(PermShkDstn,TranShkDstn)]
self.TranShkDstn = TranShkDstn
self.PermShkDstn = PermShkDstn
self.addToTimeVary('IncomeDstn')
else: # Do the usual method if this is the lifecycle model
EstimationAgentClass.updateIncomeProcess(self) | python | def updateIncomeProcess(self):
'''
An alternative method for constructing the income process in the infinite horizon model.
Parameters
----------
none
Returns
-------
none
'''
if self.cycles == 0:
tax_rate = (self.IncUnemp*self.UnempPrb)/((1.0-self.UnempPrb)*self.IndL)
TranShkDstn = deepcopy(approxMeanOneLognormal(self.TranShkCount,sigma=self.TranShkStd[0],tail_N=0))
TranShkDstn[0] = np.insert(TranShkDstn[0]*(1.0-self.UnempPrb),0,self.UnempPrb)
TranShkDstn[1] = np.insert(TranShkDstn[1]*(1.0-tax_rate)*self.IndL,0,self.IncUnemp)
PermShkDstn = approxMeanOneLognormal(self.PermShkCount,sigma=self.PermShkStd[0],tail_N=0)
self.IncomeDstn = [combineIndepDstns(PermShkDstn,TranShkDstn)]
self.TranShkDstn = TranShkDstn
self.PermShkDstn = PermShkDstn
self.addToTimeVary('IncomeDstn')
else: # Do the usual method if this is the lifecycle model
EstimationAgentClass.updateIncomeProcess(self) | [
"def",
"updateIncomeProcess",
"(",
"self",
")",
":",
"if",
"self",
".",
"cycles",
"==",
"0",
":",
"tax_rate",
"=",
"(",
"self",
".",
"IncUnemp",
"*",
"self",
".",
"UnempPrb",
")",
"/",
"(",
"(",
"1.0",
"-",
"self",
".",
"UnempPrb",
")",
"*",
"self"... | An alternative method for constructing the income process in the infinite horizon model.
Parameters
----------
none
Returns
-------
none | [
"An",
"alternative",
"method",
"for",
"constructing",
"the",
"income",
"process",
"in",
"the",
"infinite",
"horizon",
"model",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L52-L75 | train | 201,814 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCmarket.solve | def solve(self):
'''
Solves the cstwMPCmarket.
'''
if self.AggShockBool:
for agent in self.agents:
agent.getEconomyData(self)
Market.solve(self)
else:
self.solveAgents()
self.makeHistory() | python | def solve(self):
'''
Solves the cstwMPCmarket.
'''
if self.AggShockBool:
for agent in self.agents:
agent.getEconomyData(self)
Market.solve(self)
else:
self.solveAgents()
self.makeHistory() | [
"def",
"solve",
"(",
"self",
")",
":",
"if",
"self",
".",
"AggShockBool",
":",
"for",
"agent",
"in",
"self",
".",
"agents",
":",
"agent",
".",
"getEconomyData",
"(",
"self",
")",
"Market",
".",
"solve",
"(",
"self",
")",
"else",
":",
"self",
".",
"... | Solves the cstwMPCmarket. | [
"Solves",
"the",
"cstwMPCmarket",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L101-L111 | train | 201,815 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCmarket.millRule | def millRule(self,aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool):
'''
The millRule for this class simply calls the method calcStats.
'''
self.calcStats(aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool)
if self.AggShockBool:
return self.calcRandW(aLvlNow,pLvlNow)
else: # These variables are tracked but not created in no-agg-shocks specifications
self.MaggNow = 0.0
self.AaggNow = 0.0 | python | def millRule(self,aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool):
'''
The millRule for this class simply calls the method calcStats.
'''
self.calcStats(aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool)
if self.AggShockBool:
return self.calcRandW(aLvlNow,pLvlNow)
else: # These variables are tracked but not created in no-agg-shocks specifications
self.MaggNow = 0.0
self.AaggNow = 0.0 | [
"def",
"millRule",
"(",
"self",
",",
"aLvlNow",
",",
"pLvlNow",
",",
"MPCnow",
",",
"TranShkNow",
",",
"EmpNow",
",",
"t_age",
",",
"LorenzBool",
",",
"ManyStatsBool",
")",
":",
"self",
".",
"calcStats",
"(",
"aLvlNow",
",",
"pLvlNow",
",",
"MPCnow",
","... | The millRule for this class simply calls the method calcStats. | [
"The",
"millRule",
"for",
"this",
"class",
"simply",
"calls",
"the",
"method",
"calcStats",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L113-L122 | train | 201,816 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCmarket.distributeParams | def distributeParams(self,param_name,param_count,center,spread,dist_type):
'''
Distributes heterogeneous values of one parameter to the AgentTypes in self.agents.
Parameters
----------
param_name : string
Name of the parameter to be assigned.
param_count : int
Number of different values the parameter will take on.
center : float
A measure of centrality for the distribution of the parameter.
spread : float
A measure of spread or diffusion for the distribution of the parameter.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
None
'''
# Get a list of discrete values for the parameter
if dist_type == 'uniform':
# If uniform, center is middle of distribution, spread is distance to either edge
param_dist = approxUniform(N=param_count,bot=center-spread,top=center+spread)
elif dist_type == 'lognormal':
# If lognormal, center is the mean and spread is the standard deviation (in log)
tail_N = 3
param_dist = approxLognormal(N=param_count-tail_N,mu=np.log(center)-0.5*spread**2,sigma=spread,tail_N=tail_N,tail_bound=[0.0,0.9], tail_order=np.e)
# Distribute the parameters to the various types, assigning consecutive types the same
# value if there are more types than values
replication_factor = len(self.agents) // param_count
# Note: the double division is intenger division in Python 3 and 2.7, this makes it explicit
j = 0
b = 0
while j < len(self.agents):
for n in range(replication_factor):
self.agents[j](AgentCount = int(self.Population*param_dist[0][b]*self.TypeWeight[n]))
exec('self.agents[j](' + param_name + '= param_dist[1][b])')
j += 1
b += 1 | python | def distributeParams(self,param_name,param_count,center,spread,dist_type):
'''
Distributes heterogeneous values of one parameter to the AgentTypes in self.agents.
Parameters
----------
param_name : string
Name of the parameter to be assigned.
param_count : int
Number of different values the parameter will take on.
center : float
A measure of centrality for the distribution of the parameter.
spread : float
A measure of spread or diffusion for the distribution of the parameter.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
None
'''
# Get a list of discrete values for the parameter
if dist_type == 'uniform':
# If uniform, center is middle of distribution, spread is distance to either edge
param_dist = approxUniform(N=param_count,bot=center-spread,top=center+spread)
elif dist_type == 'lognormal':
# If lognormal, center is the mean and spread is the standard deviation (in log)
tail_N = 3
param_dist = approxLognormal(N=param_count-tail_N,mu=np.log(center)-0.5*spread**2,sigma=spread,tail_N=tail_N,tail_bound=[0.0,0.9], tail_order=np.e)
# Distribute the parameters to the various types, assigning consecutive types the same
# value if there are more types than values
replication_factor = len(self.agents) // param_count
# Note: the double division is intenger division in Python 3 and 2.7, this makes it explicit
j = 0
b = 0
while j < len(self.agents):
for n in range(replication_factor):
self.agents[j](AgentCount = int(self.Population*param_dist[0][b]*self.TypeWeight[n]))
exec('self.agents[j](' + param_name + '= param_dist[1][b])')
j += 1
b += 1 | [
"def",
"distributeParams",
"(",
"self",
",",
"param_name",
",",
"param_count",
",",
"center",
",",
"spread",
",",
"dist_type",
")",
":",
"# Get a list of discrete values for the parameter",
"if",
"dist_type",
"==",
"'uniform'",
":",
"# If uniform, center is middle of dist... | Distributes heterogeneous values of one parameter to the AgentTypes in self.agents.
Parameters
----------
param_name : string
Name of the parameter to be assigned.
param_count : int
Number of different values the parameter will take on.
center : float
A measure of centrality for the distribution of the parameter.
spread : float
A measure of spread or diffusion for the distribution of the parameter.
dist_type : string
The type of distribution to be used. Can be "lognormal" or "uniform" (can expand).
Returns
-------
None | [
"Distributes",
"heterogeneous",
"values",
"of",
"one",
"parameter",
"to",
"the",
"AgentTypes",
"in",
"self",
".",
"agents",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L238-L279 | train | 201,817 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCmarket.calcKYratioDifference | def calcKYratioDifference(self):
'''
Returns the difference between the simulated capital to income ratio and the target ratio.
Can only be run after solving all AgentTypes and running makeHistory.
Parameters
----------
None
Returns
-------
diff : float
Difference between simulated and target capital to income ratio.
'''
# Ignore the first X periods to allow economy to stabilize from initial conditions
KYratioSim = np.mean(np.array(self.KtoYnow_hist)[self.ignore_periods:])
diff = KYratioSim - self.KYratioTarget
return diff | python | def calcKYratioDifference(self):
'''
Returns the difference between the simulated capital to income ratio and the target ratio.
Can only be run after solving all AgentTypes and running makeHistory.
Parameters
----------
None
Returns
-------
diff : float
Difference between simulated and target capital to income ratio.
'''
# Ignore the first X periods to allow economy to stabilize from initial conditions
KYratioSim = np.mean(np.array(self.KtoYnow_hist)[self.ignore_periods:])
diff = KYratioSim - self.KYratioTarget
return diff | [
"def",
"calcKYratioDifference",
"(",
"self",
")",
":",
"# Ignore the first X periods to allow economy to stabilize from initial conditions",
"KYratioSim",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"self",
".",
"KtoYnow_hist",
")",
"[",
"self",
".",
"ignore... | Returns the difference between the simulated capital to income ratio and the target ratio.
Can only be run after solving all AgentTypes and running makeHistory.
Parameters
----------
None
Returns
-------
diff : float
Difference between simulated and target capital to income ratio. | [
"Returns",
"the",
"difference",
"between",
"the",
"simulated",
"capital",
"to",
"income",
"ratio",
"and",
"the",
"target",
"ratio",
".",
"Can",
"only",
"be",
"run",
"after",
"solving",
"all",
"AgentTypes",
"and",
"running",
"makeHistory",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L281-L298 | train | 201,818 |
econ-ark/HARK | HARK/cstwMPC/cstwMPC.py | cstwMPCmarket.calcLorenzDistance | def calcLorenzDistance(self):
'''
Returns the sum of squared differences between simulated and target Lorenz points.
Parameters
----------
None
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points (sqrt)
'''
LorenzSim = np.mean(np.array(self.Lorenz_hist)[self.ignore_periods:,:],axis=0)
dist = np.sqrt(np.sum((100*(LorenzSim - self.LorenzTarget))**2))
self.LorenzDistance = dist
return dist | python | def calcLorenzDistance(self):
'''
Returns the sum of squared differences between simulated and target Lorenz points.
Parameters
----------
None
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points (sqrt)
'''
LorenzSim = np.mean(np.array(self.Lorenz_hist)[self.ignore_periods:,:],axis=0)
dist = np.sqrt(np.sum((100*(LorenzSim - self.LorenzTarget))**2))
self.LorenzDistance = dist
return dist | [
"def",
"calcLorenzDistance",
"(",
"self",
")",
":",
"LorenzSim",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"array",
"(",
"self",
".",
"Lorenz_hist",
")",
"[",
"self",
".",
"ignore_periods",
":",
",",
":",
"]",
",",
"axis",
"=",
"0",
")",
"dist",
"=",... | Returns the sum of squared differences between simulated and target Lorenz points.
Parameters
----------
None
Returns
-------
dist : float
Sum of squared distances between simulated and target Lorenz points (sqrt) | [
"Returns",
"the",
"sum",
"of",
"squared",
"differences",
"between",
"simulated",
"and",
"target",
"Lorenz",
"points",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cstwMPC/cstwMPC.py#L300-L316 | train | 201,819 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | MargValueFunc2D.derivativeX | def derivativeX(self,m,p):
'''
Evaluate the first derivative with respect to market resources of the
marginal value function at given levels of market resources m and per-
manent income p.
Parameters
----------
m : float or np.array
Market resources whose value is to be calcuated.
p : float or np.array
Persistent income levels whose value is to be calculated.
Returns
-------
vPP : float or np.array
Marginal marginal value of market resources when beginning this period
with market resources m and persistent income p; has same size as inputs
m and p.
'''
c = self.cFunc(m,p)
MPC = self.cFunc.derivativeX(m,p)
return MPC*utilityPP(c,gam=self.CRRA) | python | def derivativeX(self,m,p):
'''
Evaluate the first derivative with respect to market resources of the
marginal value function at given levels of market resources m and per-
manent income p.
Parameters
----------
m : float or np.array
Market resources whose value is to be calcuated.
p : float or np.array
Persistent income levels whose value is to be calculated.
Returns
-------
vPP : float or np.array
Marginal marginal value of market resources when beginning this period
with market resources m and persistent income p; has same size as inputs
m and p.
'''
c = self.cFunc(m,p)
MPC = self.cFunc.derivativeX(m,p)
return MPC*utilityPP(c,gam=self.CRRA) | [
"def",
"derivativeX",
"(",
"self",
",",
"m",
",",
"p",
")",
":",
"c",
"=",
"self",
".",
"cFunc",
"(",
"m",
",",
"p",
")",
"MPC",
"=",
"self",
".",
"cFunc",
".",
"derivativeX",
"(",
"m",
",",
"p",
")",
"return",
"MPC",
"*",
"utilityPP",
"(",
"... | Evaluate the first derivative with respect to market resources of the
marginal value function at given levels of market resources m and per-
manent income p.
Parameters
----------
m : float or np.array
Market resources whose value is to be calcuated.
p : float or np.array
Persistent income levels whose value is to be calculated.
Returns
-------
vPP : float or np.array
Marginal marginal value of market resources when beginning this period
with market resources m and persistent income p; has same size as inputs
m and p. | [
"Evaluate",
"the",
"first",
"derivative",
"with",
"respect",
"to",
"market",
"resources",
"of",
"the",
"marginal",
"value",
"function",
"at",
"given",
"levels",
"of",
"market",
"resources",
"m",
"and",
"per",
"-",
"manent",
"income",
"p",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L131-L153 | train | 201,820 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | ConsGenIncProcessSolver.defBoroCnst | def defBoroCnst(self,BoroCnstArt):
'''
Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self.
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
'''
# Make temporary grids of income shocks and next period income values
ShkCount = self.TranShkValsNext.size
pLvlCount = self.pLvlGrid.size
PermShkVals_temp = np.tile(np.reshape(self.PermShkValsNext,(1,ShkCount)),(pLvlCount,1))
TranShkVals_temp = np.tile(np.reshape(self.TranShkValsNext,(1,ShkCount)),(pLvlCount,1))
pLvlNext_temp = np.tile(np.reshape(self.pLvlNextFunc(self.pLvlGrid),(pLvlCount,1)),(1,ShkCount))*PermShkVals_temp
# Find the natural borrowing constraint for each persistent income level
aLvlMin_candidates = (self.mLvlMinNext(pLvlNext_temp) - TranShkVals_temp*pLvlNext_temp)/self.Rfree
aLvlMinNow = np.max(aLvlMin_candidates,axis=1)
self.BoroCnstNat = LinearInterp(np.insert(self.pLvlGrid,0,0.0),np.insert(aLvlMinNow,0,0.0))
# Define the minimum allowable mLvl by pLvl as the greater of the natural and artificial borrowing constraints
if self.BoroCnstArt is not None:
self.BoroCnstArt = LinearInterp(np.array([0.0,1.0]),np.array([0.0,self.BoroCnstArt]))
self.mLvlMinNow = UpperEnvelope(self.BoroCnstArt,self.BoroCnstNat)
else:
self.mLvlMinNow = self.BoroCnstNat
# Define the constrained consumption function as "consume all" shifted by mLvlMin
cFuncNowCnstBase = BilinearInterp(np.array([[0.,0.],[1.,1.]]),np.array([0.0,1.0]),np.array([0.0,1.0]))
self.cFuncNowCnst = VariableLowerBoundFunc2D(cFuncNowCnstBase,self.mLvlMinNow) | python | def defBoroCnst(self,BoroCnstArt):
'''
Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self.
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
'''
# Make temporary grids of income shocks and next period income values
ShkCount = self.TranShkValsNext.size
pLvlCount = self.pLvlGrid.size
PermShkVals_temp = np.tile(np.reshape(self.PermShkValsNext,(1,ShkCount)),(pLvlCount,1))
TranShkVals_temp = np.tile(np.reshape(self.TranShkValsNext,(1,ShkCount)),(pLvlCount,1))
pLvlNext_temp = np.tile(np.reshape(self.pLvlNextFunc(self.pLvlGrid),(pLvlCount,1)),(1,ShkCount))*PermShkVals_temp
# Find the natural borrowing constraint for each persistent income level
aLvlMin_candidates = (self.mLvlMinNext(pLvlNext_temp) - TranShkVals_temp*pLvlNext_temp)/self.Rfree
aLvlMinNow = np.max(aLvlMin_candidates,axis=1)
self.BoroCnstNat = LinearInterp(np.insert(self.pLvlGrid,0,0.0),np.insert(aLvlMinNow,0,0.0))
# Define the minimum allowable mLvl by pLvl as the greater of the natural and artificial borrowing constraints
if self.BoroCnstArt is not None:
self.BoroCnstArt = LinearInterp(np.array([0.0,1.0]),np.array([0.0,self.BoroCnstArt]))
self.mLvlMinNow = UpperEnvelope(self.BoroCnstArt,self.BoroCnstNat)
else:
self.mLvlMinNow = self.BoroCnstNat
# Define the constrained consumption function as "consume all" shifted by mLvlMin
cFuncNowCnstBase = BilinearInterp(np.array([[0.,0.],[1.,1.]]),np.array([0.0,1.0]),np.array([0.0,1.0]))
self.cFuncNowCnst = VariableLowerBoundFunc2D(cFuncNowCnstBase,self.mLvlMinNow) | [
"def",
"defBoroCnst",
"(",
"self",
",",
"BoroCnstArt",
")",
":",
"# Make temporary grids of income shocks and next period income values",
"ShkCount",
"=",
"self",
".",
"TranShkValsNext",
".",
"size",
"pLvlCount",
"=",
"self",
".",
"pLvlGrid",
".",
"size",
"PermShkVals_t... | Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self.
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 | [
"Defines",
"the",
"constrained",
"portion",
"of",
"the",
"consumption",
"function",
"as",
"cFuncNowCnst",
"an",
"attribute",
"of",
"self",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L400-L438 | train | 201,821 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | ConsGenIncProcessSolver.prepareToCalcEndOfPrdvP | 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 normalized assets, the grid of persistent income
levels, and the distribution of shocks he might experience next period.
Parameters
----------
None
Returns
-------
aLvlNow : np.array
2D array of end-of-period assets; also stored as attribute of self.
pLvlNow : np.array
2D array of persistent income levels this period.
'''
ShkCount = self.TranShkValsNext.size
pLvlCount = self.pLvlGrid.size
aNrmCount = self.aXtraGrid.size
pLvlNow = np.tile(self.pLvlGrid,(aNrmCount,1)).transpose()
aLvlNow = np.tile(self.aXtraGrid,(pLvlCount,1))*pLvlNow + self.BoroCnstNat(pLvlNow)
pLvlNow_tiled = np.tile(pLvlNow,(ShkCount,1,1))
aLvlNow_tiled = np.tile(aLvlNow,(ShkCount,1,1)) # shape = (ShkCount,pLvlCount,aNrmCount)
if self.pLvlGrid[0] == 0.0: # aLvl turns out badly if pLvl is 0 at bottom
aLvlNow[0,:] = self.aXtraGrid
aLvlNow_tiled[:,0,:] = np.tile(self.aXtraGrid,(ShkCount,1))
# Tile arrays of the income shocks and put them into useful shapes
PermShkVals_tiled = np.transpose(np.tile(self.PermShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
TranShkVals_tiled = np.transpose(np.tile(self.TranShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
ShkPrbs_tiled = np.transpose(np.tile(self.ShkPrbsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
# Get cash on hand next period
pLvlNext = self.pLvlNextFunc(pLvlNow_tiled)*PermShkVals_tiled
mLvlNext = self.Rfree*aLvlNow_tiled + pLvlNext*TranShkVals_tiled
# Store and report the results
self.ShkPrbs_temp = ShkPrbs_tiled
self.pLvlNext = pLvlNext
self.mLvlNext = mLvlNext
self.aLvlNow = aLvlNow
return aLvlNow, pLvlNow | python | 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 normalized assets, the grid of persistent income
levels, and the distribution of shocks he might experience next period.
Parameters
----------
None
Returns
-------
aLvlNow : np.array
2D array of end-of-period assets; also stored as attribute of self.
pLvlNow : np.array
2D array of persistent income levels this period.
'''
ShkCount = self.TranShkValsNext.size
pLvlCount = self.pLvlGrid.size
aNrmCount = self.aXtraGrid.size
pLvlNow = np.tile(self.pLvlGrid,(aNrmCount,1)).transpose()
aLvlNow = np.tile(self.aXtraGrid,(pLvlCount,1))*pLvlNow + self.BoroCnstNat(pLvlNow)
pLvlNow_tiled = np.tile(pLvlNow,(ShkCount,1,1))
aLvlNow_tiled = np.tile(aLvlNow,(ShkCount,1,1)) # shape = (ShkCount,pLvlCount,aNrmCount)
if self.pLvlGrid[0] == 0.0: # aLvl turns out badly if pLvl is 0 at bottom
aLvlNow[0,:] = self.aXtraGrid
aLvlNow_tiled[:,0,:] = np.tile(self.aXtraGrid,(ShkCount,1))
# Tile arrays of the income shocks and put them into useful shapes
PermShkVals_tiled = np.transpose(np.tile(self.PermShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
TranShkVals_tiled = np.transpose(np.tile(self.TranShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
ShkPrbs_tiled = np.transpose(np.tile(self.ShkPrbsNext,(aNrmCount,pLvlCount,1)),(2,1,0))
# Get cash on hand next period
pLvlNext = self.pLvlNextFunc(pLvlNow_tiled)*PermShkVals_tiled
mLvlNext = self.Rfree*aLvlNow_tiled + pLvlNext*TranShkVals_tiled
# Store and report the results
self.ShkPrbs_temp = ShkPrbs_tiled
self.pLvlNext = pLvlNext
self.mLvlNext = mLvlNext
self.aLvlNow = aLvlNow
return aLvlNow, pLvlNow | [
"def",
"prepareToCalcEndOfPrdvP",
"(",
"self",
")",
":",
"ShkCount",
"=",
"self",
".",
"TranShkValsNext",
".",
"size",
"pLvlCount",
"=",
"self",
".",
"pLvlGrid",
".",
"size",
"aNrmCount",
"=",
"self",
".",
"aXtraGrid",
".",
"size",
"pLvlNow",
"=",
"np",
".... | Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period normalized assets, the grid of persistent income
levels, and the distribution of shocks he might experience next period.
Parameters
----------
None
Returns
-------
aLvlNow : np.array
2D array of end-of-period assets; also stored as attribute of self.
pLvlNow : np.array
2D array of persistent income levels this period. | [
"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... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L441-L484 | train | 201,822 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | ConsGenIncProcessSolver.makevFunc | def makevFunc(self,solution):
'''
Creates the value function for this period, defined over market resources
m and persistent income p. self must have the attribute EndOfPrdvFunc in
order to execute.
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
market resources m and persistent income p: v = vFuncNow(m,p).
'''
mSize = self.aXtraGrid.size
pSize = self.pLvlGrid.size
# Compute expected value and marginal value on a grid of market resources
pLvl_temp = np.tile(self.pLvlGrid,(mSize,1)) # Tile pLvl across m values
mLvl_temp = np.tile(self.mLvlMinNow(self.pLvlGrid),(mSize,1)) + np.tile(np.reshape(self.aXtraGrid,(mSize,1)),(1,pSize))*pLvl_temp
cLvlNow = solution.cFunc(mLvl_temp,pLvl_temp)
aLvlNow = mLvl_temp - cLvlNow
vNow = self.u(cLvlNow) + self.EndOfPrdvFunc(aLvlNow,pLvl_temp)
vPnow = self.uP(cLvlNow)
# Calculate pseudo-inverse value and its first derivative (wrt mLvl)
vNvrs = self.uinv(vNow) # value transformed through inverse utility
vNvrsP = vPnow*self.uinvP(vNow)
# Add data at the lower bound of m
mLvl_temp = np.concatenate((np.reshape(self.mLvlMinNow(self.pLvlGrid),(1,pSize)),mLvl_temp),axis=0)
vNvrs = np.concatenate((np.zeros((1,pSize)),vNvrs),axis=0)
vNvrsP = np.concatenate((np.reshape(vNvrsP[0,:],(1,vNvrsP.shape[1])),vNvrsP),axis=0)
# Add data at the lower bound of p
MPCminNvrs = self.MPCminNow**(-self.CRRA/(1.0-self.CRRA))
m_temp = np.reshape(mLvl_temp[:,0],(mSize+1,1))
mLvl_temp = np.concatenate((m_temp,mLvl_temp),axis=1)
vNvrs = np.concatenate((MPCminNvrs*m_temp,vNvrs),axis=1)
vNvrsP = np.concatenate((MPCminNvrs*np.ones((mSize+1,1)),vNvrsP),axis=1)
# Construct the pseudo-inverse value function
vNvrsFunc_list = []
for j in range(pSize+1):
pLvl = np.insert(self.pLvlGrid,0,0.0)[j]
vNvrsFunc_list.append(CubicInterp(mLvl_temp[:,j]-self.mLvlMinNow(pLvl),vNvrs[:,j],vNvrsP[:,j],MPCminNvrs*self.hLvlNow(pLvl),MPCminNvrs))
vNvrsFuncBase = LinearInterpOnInterp1D(vNvrsFunc_list,np.insert(self.pLvlGrid,0,0.0)) # Value function "shifted"
vNvrsFuncNow = VariableLowerBoundFunc2D(vNvrsFuncBase,self.mLvlMinNow)
# "Re-curve" the pseudo-inverse value function into the value function
vFuncNow = ValueFunc2D(vNvrsFuncNow,self.CRRA)
return vFuncNow | python | def makevFunc(self,solution):
'''
Creates the value function for this period, defined over market resources
m and persistent income p. self must have the attribute EndOfPrdvFunc in
order to execute.
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
market resources m and persistent income p: v = vFuncNow(m,p).
'''
mSize = self.aXtraGrid.size
pSize = self.pLvlGrid.size
# Compute expected value and marginal value on a grid of market resources
pLvl_temp = np.tile(self.pLvlGrid,(mSize,1)) # Tile pLvl across m values
mLvl_temp = np.tile(self.mLvlMinNow(self.pLvlGrid),(mSize,1)) + np.tile(np.reshape(self.aXtraGrid,(mSize,1)),(1,pSize))*pLvl_temp
cLvlNow = solution.cFunc(mLvl_temp,pLvl_temp)
aLvlNow = mLvl_temp - cLvlNow
vNow = self.u(cLvlNow) + self.EndOfPrdvFunc(aLvlNow,pLvl_temp)
vPnow = self.uP(cLvlNow)
# Calculate pseudo-inverse value and its first derivative (wrt mLvl)
vNvrs = self.uinv(vNow) # value transformed through inverse utility
vNvrsP = vPnow*self.uinvP(vNow)
# Add data at the lower bound of m
mLvl_temp = np.concatenate((np.reshape(self.mLvlMinNow(self.pLvlGrid),(1,pSize)),mLvl_temp),axis=0)
vNvrs = np.concatenate((np.zeros((1,pSize)),vNvrs),axis=0)
vNvrsP = np.concatenate((np.reshape(vNvrsP[0,:],(1,vNvrsP.shape[1])),vNvrsP),axis=0)
# Add data at the lower bound of p
MPCminNvrs = self.MPCminNow**(-self.CRRA/(1.0-self.CRRA))
m_temp = np.reshape(mLvl_temp[:,0],(mSize+1,1))
mLvl_temp = np.concatenate((m_temp,mLvl_temp),axis=1)
vNvrs = np.concatenate((MPCminNvrs*m_temp,vNvrs),axis=1)
vNvrsP = np.concatenate((MPCminNvrs*np.ones((mSize+1,1)),vNvrsP),axis=1)
# Construct the pseudo-inverse value function
vNvrsFunc_list = []
for j in range(pSize+1):
pLvl = np.insert(self.pLvlGrid,0,0.0)[j]
vNvrsFunc_list.append(CubicInterp(mLvl_temp[:,j]-self.mLvlMinNow(pLvl),vNvrs[:,j],vNvrsP[:,j],MPCminNvrs*self.hLvlNow(pLvl),MPCminNvrs))
vNvrsFuncBase = LinearInterpOnInterp1D(vNvrsFunc_list,np.insert(self.pLvlGrid,0,0.0)) # Value function "shifted"
vNvrsFuncNow = VariableLowerBoundFunc2D(vNvrsFuncBase,self.mLvlMinNow)
# "Re-curve" the pseudo-inverse value function into the value function
vFuncNow = ValueFunc2D(vNvrsFuncNow,self.CRRA)
return vFuncNow | [
"def",
"makevFunc",
"(",
"self",
",",
"solution",
")",
":",
"mSize",
"=",
"self",
".",
"aXtraGrid",
".",
"size",
"pSize",
"=",
"self",
".",
"pLvlGrid",
".",
"size",
"# Compute expected value and marginal value on a grid of market resources",
"pLvl_temp",
"=",
"np",
... | Creates the value function for this period, defined over market resources
m and persistent income p. self must have the attribute EndOfPrdvFunc in
order to execute.
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
market resources m and persistent income p: v = vFuncNow(m,p). | [
"Creates",
"the",
"value",
"function",
"for",
"this",
"period",
"defined",
"over",
"market",
"resources",
"m",
"and",
"persistent",
"income",
"p",
".",
"self",
"must",
"have",
"the",
"attribute",
"EndOfPrdvFunc",
"in",
"order",
"to",
"execute",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L629-L684 | train | 201,823 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | ConsGenIncProcessSolver.makeCubiccFunc | 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.
'''
# 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 | python | 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.
'''
# 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",
")",
":",
"# Calculate the MPC at each gridpoint",
"EndOfPrdvPP",
"=",
"self",
".",
"DiscFacEff",
"*",
"self",
".",
"Rfree",
"*",
"self",
".",
"Rfree",
"*",
"np",
".",
"sum",
"(",... | 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. | [
"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",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L750-L791 | train | 201,824 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | ConsGenIncProcessSolver.solve | 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.
'''
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 | python | 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.
'''
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",
")",
":",
"aLvl",
",",
"pLvl",
"=",
"self",
".",
"prepareToCalcEndOfPrdvP",
"(",
")",
"EndOfPrdvP",
"=",
"self",
".",
"calcEndOfPrdvP",
"(",
")",
"if",
"self",
".",
"vFuncBool",
":",
"self",
".",
"makeEndOfPrdvFunc",
"(",
"En... | 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. | [
"Solves",
"a",
"one",
"period",
"consumption",
"saving",
"problem",
"with",
"risky",
"income",
"with",
"persistent",
"income",
"explicitly",
"tracked",
"as",
"a",
"state",
"variable",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L836-L868 | train | 201,825 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | GenIncProcessConsumerType.installRetirementFunc | 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
'''
if (not hasattr(self,'pLvlNextFuncRet')) or self.T_retire == 0:
return
t = self.T_retire
self.pLvlNextFunc[t] = self.pLvlNextFuncRet | python | 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
'''
if (not hasattr(self,'pLvlNextFuncRet')) or self.T_retire == 0:
return
t = self.T_retire
self.pLvlNextFunc[t] = self.pLvlNextFuncRet | [
"def",
"installRetirementFunc",
"(",
"self",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"self",
",",
"'pLvlNextFuncRet'",
")",
")",
"or",
"self",
".",
"T_retire",
"==",
"0",
":",
"return",
"t",
"=",
"self",
".",
"T_retire",
"self",
".",
"pLvlNextFunc",
... | 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 | [
"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",
"o... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1020-L1039 | train | 201,826 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | GenIncProcessConsumerType.getStates | 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
'''
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 | python | 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
'''
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",
")",
":",
"aLvlPrev",
"=",
"self",
".",
"aLvlNow",
"RfreeNow",
"=",
"self",
".",
"getRfree",
"(",
")",
"# Calculate new states: normalized market resources and persistent income level",
"pLvlNow",
"=",
"np",
".",
"zeros_like",
"(",
"... | Calculates updated values of normalized market resources and persistent income level for each
agent. Uses pLvlNow, aLvlNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None | [
"Calculates",
"updated",
"values",
"of",
"normalized",
"market",
"resources",
"and",
"persistent",
"income",
"level",
"for",
"each",
"agent",
".",
"Uses",
"pLvlNow",
"aLvlNow",
"PermShkNow",
"TranShkNow",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1133-L1156 | train | 201,827 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | IndShockExplicitPermIncConsumerType.updatepLvlNextFunc | 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
'''
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() | python | 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
'''
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",
")",
":",
"orig_time",
"=",
"self",
".",
"time_flow",
"self",
".",
"timeFwd",
"(",
")",
"pLvlNextFunc",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"T_cycle",
")",
":",
"pLvlNextFunc",
".",
"app... | 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 | [
"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",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1209-L1234 | train | 201,828 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | PersistentShockConsumerType.updatepLvlNextFunc | 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
'''
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() | python | 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
'''
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",
")",
":",
"orig_time",
"=",
"self",
".",
"time_flow",
"self",
".",
"timeFwd",
"(",
")",
"pLvlNextFunc",
"=",
"[",
"]",
"pLogMean",
"=",
"self",
".",
"pLvlInitMean",
"# Initial mean (log) persistent income",
"for",
"t",
... | 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 | [
"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",... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1248-L1276 | train | 201,829 |
econ-ark/HARK | HARK/simulation.py | drawDiscrete | 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.
'''
# 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 | python | 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.
'''
# 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",
")",
":",
"# Set up the RNG",
"RNG",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"see... | 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. | [
"Simulates",
"N",
"draws",
"from",
"a",
"discrete",
"distribution",
"with",
"probabilities",
"P",
"and",
"outcomes",
"X",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/simulation.py#L244-L294 | train | 201,830 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | solveFashion | def solveFashion(solution_next,DiscFac,conformUtilityFunc,punk_utility,jock_utility,switchcost_J2P,switchcost_P2J,pGrid,pEvolution,pref_shock_mag):
'''
Solves a single period of the fashion victim model.
Parameters
----------
solution_next: FashionSolution
A representation of the solution to the subsequent period's problem.
DiscFac: float
The intertemporal discount factor.
conformUtilityFunc: function
Utility as a function of the proportion of the population who wears the
same style as the agent.
punk_utility: float
Direct utility from wearing the punk style this period.
jock_utility: float
Direct utility from wearing the jock style this period.
switchcost_J2P: float
Utility cost of switching from jock to punk this period.
switchcost_P2J: float
Utility cost of switching from punk to jock this period.
pGrid: np.array
1D array of "proportion of punks" states spanning [0,1], representing
the fraction of agents *currently* wearing punk style.
pEvolution: np.array
2D array representing the distribution of next period's "proportion of
punks". The pEvolution[i,:] contains equiprobable values of p for next
period if p = pGrid[i] today.
pref_shock_mag: float
Standard deviation of T1EV preference shocks over style.
Returns
-------
solution_now: FashionSolution
A representation of the solution to this period's problem.
'''
# Unpack next period's solution
VfuncPunkNext = solution_next.VfuncPunk
VfuncJockNext = solution_next.VfuncJock
# Calculate end-of-period expected value for each style at points on the pGrid
EndOfPrdVpunk = DiscFac*np.mean(VfuncPunkNext(pEvolution),axis=1)
EndOfPrdVjock = DiscFac*np.mean(VfuncJockNext(pEvolution),axis=1)
# Get current period utility flow from each style (without switching cost)
Upunk = punk_utility + conformUtilityFunc(pGrid)
Ujock = jock_utility + conformUtilityFunc(1.0 - pGrid)
# Calculate choice-conditional value for each combination of current and next styles (at each)
V_J2J = Ujock + EndOfPrdVjock
V_J2P = Upunk - switchcost_J2P + EndOfPrdVpunk
V_P2J = Ujock - switchcost_P2J + EndOfPrdVjock
V_P2P = Upunk + EndOfPrdVpunk
# Calculate the beginning-of-period expected value of each p-state when punk
Vboth_P = np.vstack((V_P2J,V_P2P))
Vbest_P = np.max(Vboth_P,axis=0)
Vnorm_P = Vboth_P - np.tile(np.reshape(Vbest_P,(1,pGrid.size)),(2,1))
ExpVnorm_P = np.exp(Vnorm_P/pref_shock_mag)
SumExpVnorm_P = np.sum(ExpVnorm_P,axis=0)
V_P = np.log(SumExpVnorm_P)*pref_shock_mag + Vbest_P
switch_P = ExpVnorm_P[0,:]/SumExpVnorm_P
# Calculate the beginning-of-period expected value of each p-state when jock
Vboth_J = np.vstack((V_J2J,V_J2P))
Vbest_J = np.max(Vboth_J,axis=0)
Vnorm_J = Vboth_J - np.tile(np.reshape(Vbest_J,(1,pGrid.size)),(2,1))
ExpVnorm_J = np.exp(Vnorm_J/pref_shock_mag)
SumExpVnorm_J = np.sum(ExpVnorm_J,axis=0)
V_J = np.log(SumExpVnorm_J)*pref_shock_mag + Vbest_J
switch_J = ExpVnorm_J[1,:]/SumExpVnorm_J
# Make value and policy functions for each style
VfuncPunkNow = LinearInterp(pGrid,V_P)
VfuncJockNow = LinearInterp(pGrid,V_J)
switchFuncPunkNow = LinearInterp(pGrid,switch_P)
switchFuncJockNow = LinearInterp(pGrid,switch_J)
# Make and return this period's solution
solution_now = FashionSolution(VfuncJock=VfuncJockNow,
VfuncPunk=VfuncPunkNow,
switchFuncJock=switchFuncJockNow,
switchFuncPunk=switchFuncPunkNow)
return solution_now | python | def solveFashion(solution_next,DiscFac,conformUtilityFunc,punk_utility,jock_utility,switchcost_J2P,switchcost_P2J,pGrid,pEvolution,pref_shock_mag):
'''
Solves a single period of the fashion victim model.
Parameters
----------
solution_next: FashionSolution
A representation of the solution to the subsequent period's problem.
DiscFac: float
The intertemporal discount factor.
conformUtilityFunc: function
Utility as a function of the proportion of the population who wears the
same style as the agent.
punk_utility: float
Direct utility from wearing the punk style this period.
jock_utility: float
Direct utility from wearing the jock style this period.
switchcost_J2P: float
Utility cost of switching from jock to punk this period.
switchcost_P2J: float
Utility cost of switching from punk to jock this period.
pGrid: np.array
1D array of "proportion of punks" states spanning [0,1], representing
the fraction of agents *currently* wearing punk style.
pEvolution: np.array
2D array representing the distribution of next period's "proportion of
punks". The pEvolution[i,:] contains equiprobable values of p for next
period if p = pGrid[i] today.
pref_shock_mag: float
Standard deviation of T1EV preference shocks over style.
Returns
-------
solution_now: FashionSolution
A representation of the solution to this period's problem.
'''
# Unpack next period's solution
VfuncPunkNext = solution_next.VfuncPunk
VfuncJockNext = solution_next.VfuncJock
# Calculate end-of-period expected value for each style at points on the pGrid
EndOfPrdVpunk = DiscFac*np.mean(VfuncPunkNext(pEvolution),axis=1)
EndOfPrdVjock = DiscFac*np.mean(VfuncJockNext(pEvolution),axis=1)
# Get current period utility flow from each style (without switching cost)
Upunk = punk_utility + conformUtilityFunc(pGrid)
Ujock = jock_utility + conformUtilityFunc(1.0 - pGrid)
# Calculate choice-conditional value for each combination of current and next styles (at each)
V_J2J = Ujock + EndOfPrdVjock
V_J2P = Upunk - switchcost_J2P + EndOfPrdVpunk
V_P2J = Ujock - switchcost_P2J + EndOfPrdVjock
V_P2P = Upunk + EndOfPrdVpunk
# Calculate the beginning-of-period expected value of each p-state when punk
Vboth_P = np.vstack((V_P2J,V_P2P))
Vbest_P = np.max(Vboth_P,axis=0)
Vnorm_P = Vboth_P - np.tile(np.reshape(Vbest_P,(1,pGrid.size)),(2,1))
ExpVnorm_P = np.exp(Vnorm_P/pref_shock_mag)
SumExpVnorm_P = np.sum(ExpVnorm_P,axis=0)
V_P = np.log(SumExpVnorm_P)*pref_shock_mag + Vbest_P
switch_P = ExpVnorm_P[0,:]/SumExpVnorm_P
# Calculate the beginning-of-period expected value of each p-state when jock
Vboth_J = np.vstack((V_J2J,V_J2P))
Vbest_J = np.max(Vboth_J,axis=0)
Vnorm_J = Vboth_J - np.tile(np.reshape(Vbest_J,(1,pGrid.size)),(2,1))
ExpVnorm_J = np.exp(Vnorm_J/pref_shock_mag)
SumExpVnorm_J = np.sum(ExpVnorm_J,axis=0)
V_J = np.log(SumExpVnorm_J)*pref_shock_mag + Vbest_J
switch_J = ExpVnorm_J[1,:]/SumExpVnorm_J
# Make value and policy functions for each style
VfuncPunkNow = LinearInterp(pGrid,V_P)
VfuncJockNow = LinearInterp(pGrid,V_J)
switchFuncPunkNow = LinearInterp(pGrid,switch_P)
switchFuncJockNow = LinearInterp(pGrid,switch_J)
# Make and return this period's solution
solution_now = FashionSolution(VfuncJock=VfuncJockNow,
VfuncPunk=VfuncPunkNow,
switchFuncJock=switchFuncJockNow,
switchFuncPunk=switchFuncPunkNow)
return solution_now | [
"def",
"solveFashion",
"(",
"solution_next",
",",
"DiscFac",
",",
"conformUtilityFunc",
",",
"punk_utility",
",",
"jock_utility",
",",
"switchcost_J2P",
",",
"switchcost_P2J",
",",
"pGrid",
",",
"pEvolution",
",",
"pref_shock_mag",
")",
":",
"# Unpack next period's so... | Solves a single period of the fashion victim model.
Parameters
----------
solution_next: FashionSolution
A representation of the solution to the subsequent period's problem.
DiscFac: float
The intertemporal discount factor.
conformUtilityFunc: function
Utility as a function of the proportion of the population who wears the
same style as the agent.
punk_utility: float
Direct utility from wearing the punk style this period.
jock_utility: float
Direct utility from wearing the jock style this period.
switchcost_J2P: float
Utility cost of switching from jock to punk this period.
switchcost_P2J: float
Utility cost of switching from punk to jock this period.
pGrid: np.array
1D array of "proportion of punks" states spanning [0,1], representing
the fraction of agents *currently* wearing punk style.
pEvolution: np.array
2D array representing the distribution of next period's "proportion of
punks". The pEvolution[i,:] contains equiprobable values of p for next
period if p = pGrid[i] today.
pref_shock_mag: float
Standard deviation of T1EV preference shocks over style.
Returns
-------
solution_now: FashionSolution
A representation of the solution to this period's problem. | [
"Solves",
"a",
"single",
"period",
"of",
"the",
"fashion",
"victim",
"model",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L281-L364 | train | 201,831 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | calcPunkProp | 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.
'''
sNowX = np.asarray(sNow).flatten()
pNow = np.mean(sNowX)
return FashionMarketInfo(pNow) | python | 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.
'''
sNowX = np.asarray(sNow).flatten()
pNow = np.mean(sNowX)
return FashionMarketInfo(pNow) | [
"def",
"calcPunkProp",
"(",
"sNow",
")",
":",
"sNowX",
"=",
"np",
".",
"asarray",
"(",
"sNow",
")",
".",
"flatten",
"(",
")",
"pNow",
"=",
"np",
".",
"mean",
"(",
"sNowX",
")",
"return",
"FashionMarketInfo",
"(",
"pNow",
")"
] | Calculates the proportion of punks in the population, given data from each type.
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. | [
"Calculates",
"the",
"proportion",
"of",
"punks",
"in",
"the",
"population",
"given",
"data",
"from",
"each",
"type",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L367-L381 | train | 201,832 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | calcFashionEvoFunc | 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.
'''
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) | python | 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.
'''
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",
")",
":",
"pNowX",
"=",
"np",
".",
"array",
"(",
"pNow",
")",
"T",
"=",
"pNowX",
".",
"size",
"p_t",
"=",
"pNowX",
"[",
"100",
":",
"(",
"T",
"-",
"1",
")",
"]",
"p_tp1",
"=",
"pNowX",
"[",
"101",
":",
... | 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. | [
"Calculates",
"a",
"new",
"approximate",
"dynamic",
"rule",
"for",
"the",
"evolution",
"of",
"the",
"proportion",
"of",
"punks",
"as",
"a",
"linear",
"function",
"and",
"a",
"shock",
"width",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L384-L409 | train | 201,833 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | FashionVictimType.updateEvolution | 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
'''
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 | python | 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
'''
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",
")",
":",
"self",
".",
"pEvolution",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"pCount",
",",
"self",
".",
"pNextCount",
")",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"pCount",
")",
":",
"pNow",... | 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 | [
"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",
... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L148-L171 | train | 201,834 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | FashionVictimType.reset | 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.
'''
self.resetRNG()
sNow = np.zeros(self.pop_size)
Shk = self.RNG.rand(self.pop_size)
sNow[Shk < self.p_init] = 1
self.sNow = sNow | python | 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.
'''
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",
")",
":",
"self",
".",
"resetRNG",
"(",
")",
"sNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"pop_size",
")",
"Shk",
"=",
"self",
".",
"RNG",
".",
"rand",
"(",
"self",
".",
"pop_size",
")",
"sNow",
"[",
"Shk",
"<... | 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. | [
"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"... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L193-L203 | train | 201,835 |
econ-ark/HARK | HARK/FashionVictim/FashionVictimModel.py | FashionVictimType.postSolve | def postSolve(self):
'''
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 | python | def postSolve(self):
'''
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",
")",
":",
"self",
".",
"switchFuncPunk",
"=",
"self",
".",
"solution",
"[",
"0",
"]",
".",
"switchFuncPunk",
"self",
".",
"switchFuncJock",
"=",
"self",
".",
"solution",
"[",
"0",
"]",
".",
"switchFuncJock",
"self",
".",
... | Unpack the behavioral and value functions for more parsimonious access.
Parameters
----------
none
Returns
-------
none | [
"Unpack",
"the",
"behavioral",
"and",
"value",
"functions",
"for",
"more",
"parsimonious",
"access",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L222-L237 | train | 201,836 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | solvePerfForesight | 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.
'''
solver = ConsPerfForesightSolver(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac)
solution = solver.solve()
return solution | python | 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.
'''
solver = ConsPerfForesightSolver(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac)
solution = solver.solve()
return solution | [
"def",
"solvePerfForesight",
"(",
"solution_next",
",",
"DiscFac",
",",
"LivPrb",
",",
"CRRA",
",",
"Rfree",
",",
"PermGroFac",
")",
":",
"solver",
"=",
"ConsPerfForesightSolver",
"(",
"solution_next",
",",
"DiscFac",
",",
"LivPrb",
",",
"CRRA",
",",
"Rfree",
... | 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. | [
"Solves",
"a",
"single",
"period",
"consumption",
"-",
"saving",
"problem",
"for",
"a",
"consumer",
"with",
"perfect",
"foresight",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L495-L522 | train | 201,837 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | constructAssetsGrid | 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.
'''
# 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 | python | 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.
'''
# 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",
")",
":",
"# Unpack the parameters",
"aXtraMin",
"=",
"parameters",
".",
"aXtraMin",
"aXtraMax",
"=",
"parameters",
".",
"aXtraMax",
"aXtraCount",
"=",
"parameters",
".",
"aXtraCount",
"aXtraExtra",
"=",
"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. | [
"Constructs",
"the",
"base",
"grid",
"of",
"post",
"-",
"decision",
"states",
"representing",
"end",
"-",
"of",
"-",
"period",
"assets",
"above",
"the",
"absolute",
"minimum",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L2378-L2429 | train | 201,838 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsPerfForesightSolver.assignParameters | 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
'''
self.solution_next = solution_next
self.DiscFac = DiscFac
self.LivPrb = LivPrb
self.CRRA = CRRA
self.Rfree = Rfree
self.PermGroFac = PermGroFac | python | 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
'''
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",
")",
":",
"self",
".",
"solution_next",
"=",
"solution_next",
"self",
".",
"DiscFac",
"=",
"DiscFac",
"self",
".",
"L... | 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 | [
"Saves",
"necessary",
"parameters",
"as",
"attributes",
"of",
"self",
"for",
"use",
"by",
"other",
"methods",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L351-L380 | train | 201,839 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsPerfForesightSolver.defValueFuncs | def defValueFuncs(self):
'''
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) | python | def defValueFuncs(self):
'''
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",
")",
":",
"MPCnvrs",
"=",
"self",
".",
"MPC",
"**",
"(",
"-",
"self",
".",
"CRRA",
"/",
"(",
"1.0",
"-",
"self",
".",
"CRRA",
")",
")",
"vFuncNvrs",
"=",
"LinearInterp",
"(",
"np",
".",
"array",
"(",
"[",
"sel... | Defines the value and marginal value function for this period.
Parameters
----------
none
Returns
-------
none | [
"Defines",
"the",
"value",
"and",
"marginal",
"value",
"function",
"for",
"this",
"period",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L399-L414 | train | 201,840 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsPerfForesightSolver.solve | def solve(self):
'''
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 | python | def solve(self):
'''
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",
")",
":",
"self",
".",
"defUtilityFuncs",
"(",
")",
"self",
".",
"DiscFacEff",
"=",
"self",
".",
"DiscFac",
"*",
"self",
".",
"LivPrb",
"self",
".",
"makePFcFunc",
"(",
")",
"self",
".",
"defValueFuncs",
"(",
")",
"solution... | Solves the one period perfect foresight consumption-saving problem.
Parameters
----------
none
Returns
-------
solution : ConsumerSolution
The solution to this period's problem. | [
"Solves",
"the",
"one",
"period",
"perfect",
"foresight",
"consumption",
"-",
"saving",
"problem",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L471-L492 | train | 201,841 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSetup.assignParameters | 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
'''
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 | python | 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
'''
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",
")",
":",
"ConsPerfForesight... | 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 | [
"Assigns",
"period",
"parameters",
"as",
"attributes",
"of",
"self",
"for",
"use",
"by",
"other",
"methods"
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L582-L632 | train | 201,842 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSetup.prepareToSolve | def prepareToSolve(self):
'''
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) | python | def prepareToSolve(self):
'''
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",
")",
":",
"self",
".",
"setAndUpdateValues",
"(",
"self",
".",
"solution_next",
",",
"self",
".",
"IncomeDstn",
",",
"self",
".",
"LivPrb",
",",
"self",
".",
"DiscFac",
")",
"self",
".",
"defBoroCnst",
"(",
"self",
"... | Perform preparatory work before calculating the unconstrained consumption
function.
Parameters
----------
none
Returns
-------
none | [
"Perform",
"preparatory",
"work",
"before",
"calculating",
"the",
"unconstrained",
"consumption",
"function",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L749-L763 | train | 201,843 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSolverBasic.prepareToCalcEndOfPrdvP | 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.
'''
# 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 | python | 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.
'''
# 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",
")",
":",
"# 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... | 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. | [
"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... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L780-L820 | train | 201,844 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSolverBasic.solve | 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.
'''
aNrm = self.prepareToCalcEndOfPrdvP()
EndOfPrdvP = self.calcEndOfPrdvP()
solution = self.makeBasicSolution(EndOfPrdvP,aNrm,self.makeLinearcFunc)
solution = self.addMPCandHumanWealth(solution)
return solution | python | 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.
'''
aNrm = self.prepareToCalcEndOfPrdvP()
EndOfPrdvP = self.calcEndOfPrdvP()
solution = self.makeBasicSolution(EndOfPrdvP,aNrm,self.makeLinearcFunc)
solution = self.addMPCandHumanWealth(solution)
return solution | [
"def",
"solve",
"(",
"self",
")",
":",
"aNrm",
"=",
"self",
".",
"prepareToCalcEndOfPrdvP",
"(",
")",
"EndOfPrdvP",
"=",
"self",
".",
"calcEndOfPrdvP",
"(",
")",
"solution",
"=",
"self",
".",
"makeBasicSolution",
"(",
"EndOfPrdvP",
",",
"aNrm",
",",
"self"... | Solves a one period consumption saving problem with risky income.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem. | [
"Solves",
"a",
"one",
"period",
"consumption",
"saving",
"problem",
"with",
"risky",
"income",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L977-L994 | train | 201,845 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSolver.makeCubiccFunc | 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.
'''
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 | python | 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.
'''
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",
")",
":",
"EndOfPrdvPP",
"=",
"self",
".",
"DiscFacEff",
"*",
"self",
".",
"Rfree",
"*",
"self",
".",
"Rfree",
"*",
"self",
".",
"PermGroFac",
"**",
"(",
"-",
"self",
".",
"CRRA",
"-",
... | 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. | [
"Makes",
"a",
"cubic",
"spline",
"interpolation",
"of",
"the",
"unconstrained",
"consumption",
"function",
"for",
"this",
"period",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1007-L1032 | train | 201,846 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSolver.addvFunc | 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.
'''
self.makeEndOfPrdvFunc(EndOfPrdvP)
solution.vFunc = self.makevFunc(solution)
return solution | python | 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.
'''
self.makeEndOfPrdvFunc(EndOfPrdvP)
solution.vFunc = self.makevFunc(solution)
return solution | [
"def",
"addvFunc",
"(",
"self",
",",
"solution",
",",
"EndOfPrdvP",
")",
":",
"self",
".",
"makeEndOfPrdvFunc",
"(",
"EndOfPrdvP",
")",
"solution",
".",
"vFunc",
"=",
"self",
".",
"makevFunc",
"(",
"solution",
")",
"return",
"solution"
] | Creates the value function for this period and adds it to the solution.
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. | [
"Creates",
"the",
"value",
"function",
"for",
"this",
"period",
"and",
"adds",
"it",
"to",
"the",
"solution",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1062-L1083 | train | 201,847 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsIndShockSolver.makevFunc | 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).
'''
# 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 | python | 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).
'''
# 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",
")",
":",
"# Compute expected value and marginal value on a grid of market resources",
"mNrm_temp",
"=",
"self",
".",
"mNrmMinNow",
"+",
"self",
".",
"aXtraGrid",
"cNrmNow",
"=",
"solution",
".",
"cFunc",
"(",
"mNrm_te... | 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). | [
"Creates",
"the",
"value",
"function",
"for",
"this",
"period",
"defined",
"over",
"market",
"resources",
"m",
".",
"self",
"must",
"have",
"the",
"attribute",
"EndOfPrdvFunc",
"in",
"order",
"to",
"execute",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1086-L1119 | train | 201,848 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | ConsKinkedRsolver.prepareToCalcEndOfPrdvP | 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.
'''
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 | python | 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.
'''
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",
")",
":",
"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 solv... | 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. | [
"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... | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1320-L1380 | train | 201,849 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | PerfForesightConsumerType.simDeath | 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.
'''
# 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 | python | 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.
'''
# 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",
")",
":",
"# 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... | 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. | [
"Determines",
"which",
"agents",
"die",
"this",
"period",
"and",
"must",
"be",
"replaced",
".",
"Uses",
"the",
"sequence",
"in",
"LivPrb",
"to",
"determine",
"survival",
"probabilities",
"for",
"each",
"agent",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1569-L1591 | train | 201,850 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | PerfForesightConsumerType.getStates | 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
'''
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 | python | 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
'''
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",
")",
":",
"pLvlPrev",
"=",
"self",
".",
"pLvlNow",
"aNrmPrev",
"=",
"self",
".",
"aNrmNow",
"RfreeNow",
"=",
"self",
".",
"getRfree",
"(",
")",
"# Calculate new states: normalized market resources and permanent income level",
"self",
... | Calculates updated values of normalized market resources and permanent income level for each
agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.
Parameters
----------
None
Returns
-------
None | [
"Calculates",
"updated",
"values",
"of",
"normalized",
"market",
"resources",
"and",
"permanent",
"income",
"level",
"for",
"each",
"agent",
".",
"Uses",
"pLvlNow",
"aNrmNow",
"PermShkNow",
"TranShkNow",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1627-L1650 | train | 201,851 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | IndShockConsumerType.updateIncomeProcess | def updateIncomeProcess(self):
'''
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() | python | def updateIncomeProcess(self):
'''
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",
")",
":",
"original_time",
"=",
"self",
".",
"time_flow",
"self",
".",
"timeFwd",
"(",
")",
"IncomeDstn",
",",
"PermShkDstn",
",",
"TranShkDstn",
"=",
"constructLognormalIncomeProcessUnemployment",
"(",
"self",
")",
"self... | Updates this agent's income process based on his own attributes.
Parameters
----------
none
Returns:
-----------
none | [
"Updates",
"this",
"agent",
"s",
"income",
"process",
"based",
"on",
"his",
"own",
"attributes",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1791-L1811 | train | 201,852 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | IndShockConsumerType.updateAssetsGrid | 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
'''
aXtraGrid = constructAssetsGrid(self)
self.aXtraGrid = aXtraGrid
self.addToTimeInv('aXtraGrid') | python | 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
'''
aXtraGrid = constructAssetsGrid(self)
self.aXtraGrid = aXtraGrid
self.addToTimeInv('aXtraGrid') | [
"def",
"updateAssetsGrid",
"(",
"self",
")",
":",
"aXtraGrid",
"=",
"constructAssetsGrid",
"(",
"self",
")",
"self",
".",
"aXtraGrid",
"=",
"aXtraGrid",
"self",
".",
"addToTimeInv",
"(",
"'aXtraGrid'",
")"
] | Updates this agent's end-of-period assets grid by constructing a multi-
exponentially spaced grid of aXtra values.
Parameters
----------
none
Returns
-------
none | [
"Updates",
"this",
"agent",
"s",
"end",
"-",
"of",
"-",
"period",
"assets",
"grid",
"by",
"constructing",
"a",
"multi",
"-",
"exponentially",
"spaced",
"grid",
"of",
"aXtra",
"values",
"."
] | 3d184153a189e618a87c9540df1cd12044039cc5 | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1813-L1828 | train | 201,853 |
JoelBender/bacpypes | py34/bacpypes/analysis.py | decode_file | def decode_file(fname):
"""Given the name of a pcap file, open it, decode the contents and yield each packet."""
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 | python | def decode_file(fname):
"""Given the name of a pcap file, open it, decode the contents and yield each packet."""
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",
")",
":",
"if",
"_debug",
":",
"decode_file",
".",
"_debug",
"(",
"\"decode_file %r\"",
",",
"fname",
")",
"if",
"not",
"pcap",
":",
"raise",
"RuntimeError",
"(",
"\"failed to import pcap\"",
")",
"# create a pcap object, readin... | Given the name of a pcap file, open it, decode the contents and yield each packet. | [
"Given",
"the",
"name",
"of",
"a",
"pcap",
"file",
"open",
"it",
"decode",
"the",
"contents",
"and",
"yield",
"each",
"packet",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/analysis.py#L355-L379 | train | 201,854 |
JoelBender/bacpypes | py25/bacpypes/core.py | stop | def stop(*args):
"""Call to stop running, may be called with a signum and frame
parameter if called as a signal handler."""
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() | python | def stop(*args):
"""Call to stop running, may be called with a signum and frame
parameter if called as a signal handler."""
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",
")",
":",
"if",
"_debug",
":",
"stop",
".",
"_debug",
"(",
"\"stop\"",
")",
"global",
"running",
",",
"taskManager",
"if",
"args",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"===== TERM Signal, %s\\n\"",
"%",
"time",... | Call to stop running, may be called with a signum and frame
parameter if called as a signal handler. | [
"Call",
"to",
"stop",
"running",
"may",
"be",
"called",
"with",
"a",
"signum",
"and",
"frame",
"parameter",
"if",
"called",
"as",
"a",
"signal",
"handler",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/core.py#L32-L47 | train | 201,855 |
JoelBender/bacpypes | py25/bacpypes/core.py | print_stack | def print_stack(sig, frame):
"""Signal handler to print a stack trace and some interesting values."""
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() | python | def print_stack(sig, frame):
"""Signal handler to print a stack trace and some interesting values."""
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",
")",
":",
"if",
"_debug",
":",
"print_stack",
".",
"_debug",
"(",
"\"print_stack %r %r\"",
",",
"sig",
",",
"frame",
")",
"global",
"running",
",",
"deferredFns",
",",
"sleeptime",
"sys",
".",
"stderr",
".",
... | Signal handler to print a stack trace and some interesting values. | [
"Signal",
"handler",
"to",
"print",
"a",
"stack",
"trace",
"and",
"some",
"interesting",
"values",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/core.py#L66-L95 | train | 201,856 |
JoelBender/bacpypes | py25/bacpypes/capability.py | compose_capability | def compose_capability(base, *classes):
"""Create a new class starting with the base and adding capabilities."""
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, {}) | python | def compose_capability(base, *classes):
"""Create a new class starting with the base and adding capabilities."""
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",
")",
":",
"if",
"_debug",
":",
"compose_capability",
".",
"_debug",
"(",
"\"compose_capability %r %r\"",
",",
"base",
",",
"classes",
")",
"# make sure the base is a Collector",
"if",
"not",
"issubclass"... | Create a new class starting with the base and adding capabilities. | [
"Create",
"a",
"new",
"class",
"starting",
"with",
"the",
"base",
"and",
"adding",
"capabilities",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L107-L129 | train | 201,857 |
JoelBender/bacpypes | py25/bacpypes/capability.py | add_capability | 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!"""
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__ | python | 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!"""
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",
")",
":",
"if",
"_debug",
":",
"add_capability",
".",
"_debug",
"(",
"\"add_capability %r %r\"",
",",
"base",
",",
"classes",
")",
"# start out with a collector",
"if",
"not",
"issubclass",
"(",
"base",
... | Add capabilites to an existing base, all objects get the additional
functionality, but don't get inited. Use with great care! | [
"Add",
"capabilites",
"to",
"an",
"existing",
"base",
"all",
"objects",
"get",
"the",
"additional",
"functionality",
"but",
"don",
"t",
"get",
"inited",
".",
"Use",
"with",
"great",
"care!"
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L137-L153 | train | 201,858 |
JoelBender/bacpypes | py25/bacpypes/capability.py | Collector._search_capability | def _search_capability(self, base):
"""Given a class, return a list of all of the derived classes that
are themselves derived from Capability."""
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 | python | def _search_capability(self, base):
"""Given a class, return a list of all of the derived classes that
are themselves derived from Capability."""
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",
")",
":",
"if",
"_debug",
":",
"Collector",
".",
"_debug",
"(",
"\"_search_capability %r\"",
",",
"base",
")",
"rslt",
"=",
"[",
"]",
"for",
"cls",
"in",
"base",
".",
"__bases__",
":",
"if",
"issubcl... | Given a class, return a list of all of the derived classes that
are themselves derived from Capability. | [
"Given",
"a",
"class",
"return",
"a",
"list",
"of",
"all",
"of",
"the",
"derived",
"classes",
"that",
"are",
"themselves",
"derived",
"from",
"Capability",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L44-L57 | train | 201,859 |
JoelBender/bacpypes | py25/bacpypes/capability.py | Collector.capability_functions | def capability_functions(self, fn):
"""This generator yields functions that match the
requested capability sorted by z-index."""
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 | python | def capability_functions(self, fn):
"""This generator yields functions that match the
requested capability sorted by z-index."""
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",
")",
":",
"if",
"_debug",
":",
"Collector",
".",
"_debug",
"(",
"\"capability_functions %r\"",
",",
"fn",
")",
"# build a list of functions to call",
"fns",
"=",
"[",
"]",
"for",
"cls",
"in",
"self",
".",
... | This generator yields functions that match the
requested capability sorted by z-index. | [
"This",
"generator",
"yields",
"functions",
"that",
"match",
"the",
"requested",
"capability",
"sorted",
"by",
"z",
"-",
"index",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L59-L79 | train | 201,860 |
JoelBender/bacpypes | py25/bacpypes/capability.py | Collector.add_capability | def add_capability(self, cls):
"""Add a capability to this object."""
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) | python | def add_capability(self, cls):
"""Add a capability to this object."""
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",
")",
":",
"if",
"_debug",
":",
"Collector",
".",
"_debug",
"(",
"\"add_capability %r\"",
",",
"cls",
")",
"# the new type has everything the current one has plus this new one",
"bases",
"=",
"(",
"self",
".",
"__clas... | Add a capability to this object. | [
"Add",
"a",
"capability",
"to",
"this",
"object",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/capability.py#L81-L99 | train | 201,861 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | _merge | def _merge(*args):
"""Create a composite pattern and compile it."""
return re.compile(r'^' + r'[/-]'.join(args) + r'(?:\s+' + _dow + ')?$') | python | def _merge(*args):
"""Create a composite pattern and compile it."""
return re.compile(r'^' + r'[/-]'.join(args) + r'(?:\s+' + _dow + ')?$') | [
"def",
"_merge",
"(",
"*",
"args",
")",
":",
"return",
"re",
".",
"compile",
"(",
"r'^'",
"+",
"r'[/-]'",
".",
"join",
"(",
"args",
")",
"+",
"r'(?:\\s+'",
"+",
"_dow",
"+",
"')?$'",
")"
] | Create a composite pattern and compile it. | [
"Create",
"a",
"composite",
"pattern",
"and",
"compile",
"it",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L1256-L1258 | train | 201,862 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Tag.encode | def encode(self, pdu):
"""Encode a tag on the end of the PDU."""
# 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) | python | def encode(self, pdu):
"""Encode a tag on the end of the PDU."""
# 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",
")",
":",
"# check for special encoding",
"if",
"(",
"self",
".",
"tagClass",
"==",
"Tag",
".",
"contextTagClass",
")",
":",
"data",
"=",
"0x08",
"elif",
"(",
"self",
".",
"tagClass",
"==",
"Tag",
".",
"openingTa... | Encode a tag on the end of the PDU. | [
"Encode",
"a",
"tag",
"on",
"the",
"end",
"of",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L98-L139 | train | 201,863 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Tag.app_to_object | def app_to_object(self):
"""Return the application object encoded by the tag."""
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) | python | def app_to_object(self):
"""Return the application object encoded by the tag."""
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",
")",
":",
"if",
"self",
".",
"tagClass",
"!=",
"Tag",
".",
"applicationTagClass",
":",
"raise",
"ValueError",
"(",
"\"application tag required\"",
")",
"# get the class to build",
"klass",
"=",
"self",
".",
"_app_tag_class",
"[... | Return the application object encoded by the tag. | [
"Return",
"the",
"application",
"object",
"encoded",
"by",
"the",
"tag",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L201-L212 | train | 201,864 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | TagList.Pop | def Pop(self):
"""Remove the tag from the front of the list and return it."""
if self.tagList:
tag = self.tagList[0]
del self.tagList[0]
else:
tag = None
return tag | python | def Pop(self):
"""Remove the tag from the front of the list and return it."""
if self.tagList:
tag = self.tagList[0]
del self.tagList[0]
else:
tag = None
return tag | [
"def",
"Pop",
"(",
"self",
")",
":",
"if",
"self",
".",
"tagList",
":",
"tag",
"=",
"self",
".",
"tagList",
"[",
"0",
"]",
"del",
"self",
".",
"tagList",
"[",
"0",
"]",
"else",
":",
"tag",
"=",
"None",
"return",
"tag"
] | Remove the tag from the front of the list and return it. | [
"Remove",
"the",
"tag",
"from",
"the",
"front",
"of",
"the",
"list",
"and",
"return",
"it",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L377-L385 | train | 201,865 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | TagList.get_context | def get_context(self, context):
"""Return a tag or a list of tags context encoded."""
# 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 | python | def get_context(self, context):
"""Return a tag or a list of tags context encoded."""
# 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",
")",
":",
"# forward pass",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"self",
".",
"tagList",
")",
":",
"tag",
"=",
"self",
".",
"tagList",
"[",
"i",
"]",
"# skip application stuff",
"if",
"tag",
... | Return a tag or a list of tags context encoded. | [
"Return",
"a",
"tag",
"or",
"a",
"list",
"of",
"tags",
"context",
"encoded",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L387-L434 | train | 201,866 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | TagList.decode | def decode(self, pdu):
"""decode the tags from a PDU."""
while pdu.pduData:
self.tagList.append( Tag(pdu) ) | python | def decode(self, pdu):
"""decode the tags from a PDU."""
while pdu.pduData:
self.tagList.append( Tag(pdu) ) | [
"def",
"decode",
"(",
"self",
",",
"pdu",
")",
":",
"while",
"pdu",
".",
"pduData",
":",
"self",
".",
"tagList",
".",
"append",
"(",
"Tag",
"(",
"pdu",
")",
")"
] | decode the tags from a PDU. | [
"decode",
"the",
"tags",
"from",
"a",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L441-L444 | train | 201,867 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Atomic.coerce | def coerce(cls, arg):
"""Given an arg, return the appropriate value given the class."""
try:
return cls(arg).value
except (ValueError, TypeError):
raise InvalidParameterDatatype("%s coerce error" % (cls.__name__,)) | python | def coerce(cls, arg):
"""Given an arg, return the appropriate value given the class."""
try:
return cls(arg).value
except (ValueError, TypeError):
raise InvalidParameterDatatype("%s coerce error" % (cls.__name__,)) | [
"def",
"coerce",
"(",
"cls",
",",
"arg",
")",
":",
"try",
":",
"return",
"cls",
"(",
"arg",
")",
".",
"value",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"InvalidParameterDatatype",
"(",
"\"%s coerce error\"",
"%",
"(",
"cls",
".",... | Given an arg, return the appropriate value given the class. | [
"Given",
"an",
"arg",
"return",
"the",
"appropriate",
"value",
"given",
"the",
"class",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L494-L499 | train | 201,868 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Enumerated.keylist | def keylist(self):
"""Return a list of names in order by value."""
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 | python | def keylist(self):
"""Return a list of names in order by value."""
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",
")",
":",
"items",
"=",
"self",
".",
"enumerations",
".",
"items",
"(",
")",
"items",
".",
"sort",
"(",
"lambda",
"a",
",",
"b",
":",
"self",
".",
"cmp",
"(",
"a",
"[",
"1",
"]",
",",
"b",
"[",
"1",
"]",
")",
... | Return a list of names in order by value. | [
"Return",
"a",
"list",
"of",
"names",
"in",
"order",
"by",
"value",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L1135-L1148 | train | 201,869 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Date.CalcDayOfWeek | def CalcDayOfWeek(self):
"""Calculate the correct day of the week."""
# 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) | python | def CalcDayOfWeek(self):
"""Calculate the correct day of the week."""
# 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",
")",
":",
"# 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",
":"... | Calculate the correct day of the week. | [
"Calculate",
"the",
"correct",
"day",
"of",
"the",
"week",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L1382-L1405 | train | 201,870 |
JoelBender/bacpypes | py34/bacpypes/primitivedata.py | Date.now | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"if",
"when",
"is",
"None",
":",
"when",
"=",
"_TaskManager",
"(",
")",
".",
"get_time",
"(",
")",
"tup",
"=",
"time",
".",
"localtime",
"(",
"when",
")",
"self",
".",
"value",
"=",
... | 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. | [
"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",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L1407-L1418 | train | 201,871 |
JoelBender/bacpypes | py25/bacpypes/app.py | DeviceInfoCache.has_device_info | def has_device_info(self, key):
"""Return true iff cache has information about the device."""
if _debug: DeviceInfoCache._debug("has_device_info %r", key)
return key in self.cache | python | def has_device_info(self, key):
"""Return true iff cache has information about the device."""
if _debug: DeviceInfoCache._debug("has_device_info %r", key)
return key in self.cache | [
"def",
"has_device_info",
"(",
"self",
",",
"key",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"has_device_info %r\"",
",",
"key",
")",
"return",
"key",
"in",
"self",
".",
"cache"
] | Return true iff cache has information about the device. | [
"Return",
"true",
"iff",
"cache",
"has",
"information",
"about",
"the",
"device",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L89-L93 | train | 201,872 |
JoelBender/bacpypes | py25/bacpypes/app.py | DeviceInfoCache.iam_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."""
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) | python | def iam_device_info(self, apdu):
"""Create a device information record based on the contents of an
IAmRequest and put it in the cache."""
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",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"iam_device_info %r\"",
",",
"apdu",
")",
"# make sure the apdu is an I-Am",
"if",
"not",
"isinstance",
"(",
"apdu",
",",
"IAmRequest",
")... | Create a device information record based on the contents of an
IAmRequest and put it in the cache. | [
"Create",
"a",
"device",
"information",
"record",
"based",
"on",
"the",
"contents",
"of",
"an",
"IAmRequest",
"and",
"put",
"it",
"in",
"the",
"cache",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L95-L126 | train | 201,873 |
JoelBender/bacpypes | py25/bacpypes/app.py | DeviceInfoCache.update_device_info | 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."""
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) | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"update_device_info %r\"",
",",
"device_info",
")",
"# give this a reference count if it doesn't have one",
"if",
"not",
"hasattr",
"(",... | 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. | [
"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",
"versio... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L137-L166 | train | 201,874 |
JoelBender/bacpypes | py25/bacpypes/app.py | DeviceInfoCache.acquire | def acquire(self, key):
"""Return the known information about the device and mark the record
as being used by a segmenation state machine."""
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 | python | def acquire(self, key):
"""Return the known information about the device and mark the record
as being used by a segmenation state machine."""
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",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"acquire %r\"",
",",
"key",
")",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"device_info",
"=",
"self",
".",
"cache",
".",
"... | Return the known information about the device and mark the record
as being used by a segmenation state machine. | [
"Return",
"the",
"known",
"information",
"about",
"the",
"device",
"and",
"mark",
"the",
"record",
"as",
"being",
"used",
"by",
"a",
"segmenation",
"state",
"machine",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L168-L191 | train | 201,875 |
JoelBender/bacpypes | py25/bacpypes/app.py | DeviceInfoCache.release | def release(self, device_info):
"""This function is called by the segmentation state machine when it
has finished with the device information."""
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 | python | def release(self, device_info):
"""This function is called by the segmentation state machine when it
has finished with the device information."""
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",
")",
":",
"if",
"_debug",
":",
"DeviceInfoCache",
".",
"_debug",
"(",
"\"release %r\"",
",",
"device_info",
")",
"# this information record might be used by more than one SSM",
"if",
"device_info",
".",
"_ref_count",
... | This function is called by the segmentation state machine when it
has finished with the device information. | [
"This",
"function",
"is",
"called",
"by",
"the",
"segmentation",
"state",
"machine",
"when",
"it",
"has",
"finished",
"with",
"the",
"device",
"information",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L193-L203 | train | 201,876 |
JoelBender/bacpypes | py25/bacpypes/app.py | Application.get_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."""
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 | python | def get_services_supported(self):
"""Return a ServicesSupported bit string based in introspection, look
for helper methods that match confirmed and unconfirmed services."""
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",
")",
":",
"if",
"_debug",
":",
"Application",
".",
"_debug",
"(",
"\"get_services_supported\"",
")",
"services_supported",
"=",
"ServicesSupported",
"(",
")",
"# look through the confirmed services",
"for",
"service_choice",
... | Return a ServicesSupported bit string based in introspection, look
for helper methods that match confirmed and unconfirmed services. | [
"Return",
"a",
"ServicesSupported",
"bit",
"string",
"based",
"in",
"introspection",
"look",
"for",
"helper",
"methods",
"that",
"match",
"confirmed",
"and",
"unconfirmed",
"services",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/app.py#L321-L343 | train | 201,877 |
JoelBender/bacpypes | py34/bacpypes/task.py | TaskManager.get_next_task | def get_next_task(self):
"""get the next task if there's one that should be processed,
and return how long it will be until the next one should be
processed."""
if _debug: TaskManager._debug("get_next_task")
# get the time
now = _time()
task = None
delta = None
if self.tasks:
# look at the first task
when, n, nxttask = self.tasks[0]
if when <= now:
# pull it off the list and mark that it's no longer scheduled
heappop(self.tasks)
task = nxttask
task.isScheduled = False
if self.tasks:
when, n, nxttask = self.tasks[0]
# peek at the next task, return how long to wait
delta = max(when - now, 0.0)
else:
delta = when - now
# return the task to run and how long to wait for the next one
return (task, delta) | python | def get_next_task(self):
"""get the next task if there's one that should be processed,
and return how long it will be until the next one should be
processed."""
if _debug: TaskManager._debug("get_next_task")
# get the time
now = _time()
task = None
delta = None
if self.tasks:
# look at the first task
when, n, nxttask = self.tasks[0]
if when <= now:
# pull it off the list and mark that it's no longer scheduled
heappop(self.tasks)
task = nxttask
task.isScheduled = False
if self.tasks:
when, n, nxttask = self.tasks[0]
# peek at the next task, return how long to wait
delta = max(when - now, 0.0)
else:
delta = when - now
# return the task to run and how long to wait for the next one
return (task, delta) | [
"def",
"get_next_task",
"(",
"self",
")",
":",
"if",
"_debug",
":",
"TaskManager",
".",
"_debug",
"(",
"\"get_next_task\"",
")",
"# get the time",
"now",
"=",
"_time",
"(",
")",
"task",
"=",
"None",
"delta",
"=",
"None",
"if",
"self",
".",
"tasks",
":",
... | get the next task if there's one that should be processed,
and return how long it will be until the next one should be
processed. | [
"get",
"the",
"next",
"task",
"if",
"there",
"s",
"one",
"that",
"should",
"be",
"processed",
"and",
"return",
"how",
"long",
"it",
"will",
"be",
"until",
"the",
"next",
"one",
"should",
"be",
"processed",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/task.py#L341-L370 | train | 201,878 |
JoelBender/bacpypes | py25/bacpypes/local/schedule.py | match_date | def match_date(date, date_pattern):
"""
Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values.
"""
# unpack the date and pattern
year, month, day, day_of_week = date
year_p, month_p, day_p, day_of_week_p = date_pattern
# check the year
if year_p == 255:
# any year
pass
elif year != year_p:
# specific year
return False
# check the month
if month_p == 255:
# any month
pass
elif month_p == 13:
# odd months
if (month % 2) == 0:
return False
elif month_p == 14:
# even months
if (month % 2) == 1:
return False
elif month != month_p:
# specific month
return False
# check the day
if day_p == 255:
# any day
pass
elif day_p == 32:
# last day of the month
last_day = calendar.monthrange(year + 1900, month)[1]
if day != last_day:
return False
elif day_p == 33:
# odd days of the month
if (day % 2) == 0:
return False
elif day_p == 34:
# even days of the month
if (day % 2) == 1:
return False
elif day != day_p:
# specific day
return False
# check the day of week
if day_of_week_p == 255:
# any day of the week
pass
elif day_of_week != day_of_week_p:
# specific day of the week
return False
# all tests pass
return True | python | def match_date(date, date_pattern):
"""
Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values.
"""
# unpack the date and pattern
year, month, day, day_of_week = date
year_p, month_p, day_p, day_of_week_p = date_pattern
# check the year
if year_p == 255:
# any year
pass
elif year != year_p:
# specific year
return False
# check the month
if month_p == 255:
# any month
pass
elif month_p == 13:
# odd months
if (month % 2) == 0:
return False
elif month_p == 14:
# even months
if (month % 2) == 1:
return False
elif month != month_p:
# specific month
return False
# check the day
if day_p == 255:
# any day
pass
elif day_p == 32:
# last day of the month
last_day = calendar.monthrange(year + 1900, month)[1]
if day != last_day:
return False
elif day_p == 33:
# odd days of the month
if (day % 2) == 0:
return False
elif day_p == 34:
# even days of the month
if (day % 2) == 1:
return False
elif day != day_p:
# specific day
return False
# check the day of week
if day_of_week_p == 255:
# any day of the week
pass
elif day_of_week != day_of_week_p:
# specific day of the week
return False
# all tests pass
return True | [
"def",
"match_date",
"(",
"date",
",",
"date_pattern",
")",
":",
"# unpack the date and pattern",
"year",
",",
"month",
",",
"day",
",",
"day_of_week",
"=",
"date",
"year_p",
",",
"month_p",
",",
"day_p",
",",
"day_of_week_p",
"=",
"date_pattern",
"# check the y... | Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values. | [
"Match",
"a",
"specific",
"date",
"a",
"four",
"-",
"tuple",
"with",
"no",
"special",
"values",
"with",
"a",
"date",
"pattern",
"four",
"-",
"tuple",
"possibly",
"having",
"special",
"values",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/local/schedule.py#L30-L93 | train | 201,879 |
JoelBender/bacpypes | py25/bacpypes/local/schedule.py | datetime_to_time | def datetime_to_time(date, time):
"""Take the date and time 4-tuples and return the time in seconds since
the epoch as a floating point number."""
if (255 in date) or (255 in time):
raise RuntimeError("specific date and time required")
time_tuple = (
date[0]+1900, date[1], date[2],
time[0], time[1], time[2],
0, 0, -1,
)
return _mktime(time_tuple) | python | def datetime_to_time(date, time):
"""Take the date and time 4-tuples and return the time in seconds since
the epoch as a floating point number."""
if (255 in date) or (255 in time):
raise RuntimeError("specific date and time required")
time_tuple = (
date[0]+1900, date[1], date[2],
time[0], time[1], time[2],
0, 0, -1,
)
return _mktime(time_tuple) | [
"def",
"datetime_to_time",
"(",
"date",
",",
"time",
")",
":",
"if",
"(",
"255",
"in",
"date",
")",
"or",
"(",
"255",
"in",
"time",
")",
":",
"raise",
"RuntimeError",
"(",
"\"specific date and time required\"",
")",
"time_tuple",
"=",
"(",
"date",
"[",
"... | Take the date and time 4-tuples and return the time in seconds since
the epoch as a floating point number. | [
"Take",
"the",
"date",
"and",
"time",
"4",
"-",
"tuples",
"and",
"return",
"the",
"time",
"in",
"seconds",
"since",
"the",
"epoch",
"as",
"a",
"floating",
"point",
"number",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/local/schedule.py#L218-L229 | train | 201,880 |
JoelBender/bacpypes | py25/bacpypes/local/schedule.py | LocalScheduleObject._check_reliability | def _check_reliability(self, old_value=None, new_value=None):
"""This function is called when the object is created and after
one of its configuration properties has changed. The new and old value
parameters are ignored, this is called after the property has been
changed and this is only concerned with the current value."""
if _debug: LocalScheduleObject._debug("_check_reliability %r %r", old_value, new_value)
try:
schedule_default = self.scheduleDefault
if schedule_default is None:
raise ValueError("scheduleDefault expected")
if not isinstance(schedule_default, Atomic):
raise TypeError("scheduleDefault must be an instance of an atomic type")
schedule_datatype = schedule_default.__class__
if _debug: LocalScheduleObject._debug(" - schedule_datatype: %r", schedule_datatype)
if (self.weeklySchedule is None) and (self.exceptionSchedule is None):
raise ValueError("schedule required")
# check the weekly schedule values
if self.weeklySchedule:
for daily_schedule in self.weeklySchedule:
for time_value in daily_schedule.daySchedule:
if _debug: LocalScheduleObject._debug(" - daily time_value: %r", time_value)
if time_value is None:
pass
elif not isinstance(time_value.value, (Null, schedule_datatype)):
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
schedule_datatype,
time_value.__class__,
)
raise TypeError("wrong type")
elif 255 in time_value.time:
if _debug: LocalScheduleObject._debug(" - wildcard in time")
raise ValueError("must be a specific time")
# check the exception schedule values
if self.exceptionSchedule:
for special_event in self.exceptionSchedule:
for time_value in special_event.listOfTimeValues:
if _debug: LocalScheduleObject._debug(" - special event time_value: %r", time_value)
if time_value is None:
pass
elif not isinstance(time_value.value, (Null, schedule_datatype)):
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
schedule_datatype,
time_value.__class__,
)
raise TypeError("wrong type")
# check list of object property references
obj_prop_refs = self.listOfObjectPropertyReferences
if obj_prop_refs:
for obj_prop_ref in obj_prop_refs:
if obj_prop_ref.deviceIdentifier:
raise RuntimeError("no external references")
# get the datatype of the property to be written
obj_type = obj_prop_ref.objectIdentifier[0]
datatype = get_datatype(obj_type, obj_prop_ref.propertyIdentifier)
if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype)
if issubclass(datatype, Array) and (obj_prop_ref.propertyArrayIndex is not None):
if obj_prop_ref.propertyArrayIndex == 0:
datatype = Unsigned
else:
datatype = datatype.subtype
if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype)
if datatype is not schedule_datatype:
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
datatype,
schedule_datatype,
)
raise TypeError("wrong type")
# all good
self.reliability = 'noFaultDetected'
if _debug: LocalScheduleObject._debug(" - no fault detected")
except Exception as err:
if _debug: LocalScheduleObject._debug(" - exception: %r", err)
self.reliability = 'configurationError' | python | def _check_reliability(self, old_value=None, new_value=None):
"""This function is called when the object is created and after
one of its configuration properties has changed. The new and old value
parameters are ignored, this is called after the property has been
changed and this is only concerned with the current value."""
if _debug: LocalScheduleObject._debug("_check_reliability %r %r", old_value, new_value)
try:
schedule_default = self.scheduleDefault
if schedule_default is None:
raise ValueError("scheduleDefault expected")
if not isinstance(schedule_default, Atomic):
raise TypeError("scheduleDefault must be an instance of an atomic type")
schedule_datatype = schedule_default.__class__
if _debug: LocalScheduleObject._debug(" - schedule_datatype: %r", schedule_datatype)
if (self.weeklySchedule is None) and (self.exceptionSchedule is None):
raise ValueError("schedule required")
# check the weekly schedule values
if self.weeklySchedule:
for daily_schedule in self.weeklySchedule:
for time_value in daily_schedule.daySchedule:
if _debug: LocalScheduleObject._debug(" - daily time_value: %r", time_value)
if time_value is None:
pass
elif not isinstance(time_value.value, (Null, schedule_datatype)):
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
schedule_datatype,
time_value.__class__,
)
raise TypeError("wrong type")
elif 255 in time_value.time:
if _debug: LocalScheduleObject._debug(" - wildcard in time")
raise ValueError("must be a specific time")
# check the exception schedule values
if self.exceptionSchedule:
for special_event in self.exceptionSchedule:
for time_value in special_event.listOfTimeValues:
if _debug: LocalScheduleObject._debug(" - special event time_value: %r", time_value)
if time_value is None:
pass
elif not isinstance(time_value.value, (Null, schedule_datatype)):
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
schedule_datatype,
time_value.__class__,
)
raise TypeError("wrong type")
# check list of object property references
obj_prop_refs = self.listOfObjectPropertyReferences
if obj_prop_refs:
for obj_prop_ref in obj_prop_refs:
if obj_prop_ref.deviceIdentifier:
raise RuntimeError("no external references")
# get the datatype of the property to be written
obj_type = obj_prop_ref.objectIdentifier[0]
datatype = get_datatype(obj_type, obj_prop_ref.propertyIdentifier)
if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype)
if issubclass(datatype, Array) and (obj_prop_ref.propertyArrayIndex is not None):
if obj_prop_ref.propertyArrayIndex == 0:
datatype = Unsigned
else:
datatype = datatype.subtype
if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype)
if datatype is not schedule_datatype:
if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r",
datatype,
schedule_datatype,
)
raise TypeError("wrong type")
# all good
self.reliability = 'noFaultDetected'
if _debug: LocalScheduleObject._debug(" - no fault detected")
except Exception as err:
if _debug: LocalScheduleObject._debug(" - exception: %r", err)
self.reliability = 'configurationError' | [
"def",
"_check_reliability",
"(",
"self",
",",
"old_value",
"=",
"None",
",",
"new_value",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"LocalScheduleObject",
".",
"_debug",
"(",
"\"_check_reliability %r %r\"",
",",
"old_value",
",",
"new_value",
")",
"try",
":... | This function is called when the object is created and after
one of its configuration properties has changed. The new and old value
parameters are ignored, this is called after the property has been
changed and this is only concerned with the current value. | [
"This",
"function",
"is",
"called",
"when",
"the",
"object",
"is",
"created",
"and",
"after",
"one",
"of",
"its",
"configuration",
"properties",
"has",
"changed",
".",
"The",
"new",
"and",
"old",
"value",
"parameters",
"are",
"ignored",
"this",
"is",
"called... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/local/schedule.py#L259-L343 | train | 201,881 |
JoelBender/bacpypes | py25/bacpypes/local/schedule.py | LocalScheduleInterpreter.present_value_changed | def present_value_changed(self, old_value, new_value):
"""This function is called when the presentValue of the local schedule
object has changed, both internally by this interpreter, or externally
by some client using WriteProperty."""
if _debug: LocalScheduleInterpreter._debug("present_value_changed %s %s", old_value, new_value)
# if this hasn't been added to an application, there's nothing to do
if not self.sched_obj._app:
if _debug: LocalScheduleInterpreter._debug(" - no application")
return
# process the list of [device] object property [array index] references
obj_prop_refs = self.sched_obj.listOfObjectPropertyReferences
if not obj_prop_refs:
if _debug: LocalScheduleInterpreter._debug(" - no writes defined")
return
# primitive values just set the value part
new_value = new_value.value
# loop through the writes
for obj_prop_ref in obj_prop_refs:
if obj_prop_ref.deviceIdentifier:
if _debug: LocalScheduleInterpreter._debug(" - no externals")
continue
# get the object from the application
obj = self.sched_obj._app.get_object_id(obj_prop_ref.objectIdentifier)
if not obj:
if _debug: LocalScheduleInterpreter._debug(" - no object")
continue
# try to change the value
try:
obj.WriteProperty(
obj_prop_ref.propertyIdentifier,
new_value,
arrayIndex=obj_prop_ref.propertyArrayIndex,
priority=self.sched_obj.priorityForWriting,
)
if _debug: LocalScheduleInterpreter._debug(" - success")
except Exception as err:
if _debug: LocalScheduleInterpreter._debug(" - error: %r", err) | python | def present_value_changed(self, old_value, new_value):
"""This function is called when the presentValue of the local schedule
object has changed, both internally by this interpreter, or externally
by some client using WriteProperty."""
if _debug: LocalScheduleInterpreter._debug("present_value_changed %s %s", old_value, new_value)
# if this hasn't been added to an application, there's nothing to do
if not self.sched_obj._app:
if _debug: LocalScheduleInterpreter._debug(" - no application")
return
# process the list of [device] object property [array index] references
obj_prop_refs = self.sched_obj.listOfObjectPropertyReferences
if not obj_prop_refs:
if _debug: LocalScheduleInterpreter._debug(" - no writes defined")
return
# primitive values just set the value part
new_value = new_value.value
# loop through the writes
for obj_prop_ref in obj_prop_refs:
if obj_prop_ref.deviceIdentifier:
if _debug: LocalScheduleInterpreter._debug(" - no externals")
continue
# get the object from the application
obj = self.sched_obj._app.get_object_id(obj_prop_ref.objectIdentifier)
if not obj:
if _debug: LocalScheduleInterpreter._debug(" - no object")
continue
# try to change the value
try:
obj.WriteProperty(
obj_prop_ref.propertyIdentifier,
new_value,
arrayIndex=obj_prop_ref.propertyArrayIndex,
priority=self.sched_obj.priorityForWriting,
)
if _debug: LocalScheduleInterpreter._debug(" - success")
except Exception as err:
if _debug: LocalScheduleInterpreter._debug(" - error: %r", err) | [
"def",
"present_value_changed",
"(",
"self",
",",
"old_value",
",",
"new_value",
")",
":",
"if",
"_debug",
":",
"LocalScheduleInterpreter",
".",
"_debug",
"(",
"\"present_value_changed %s %s\"",
",",
"old_value",
",",
"new_value",
")",
"# if this hasn't been added to an... | This function is called when the presentValue of the local schedule
object has changed, both internally by this interpreter, or externally
by some client using WriteProperty. | [
"This",
"function",
"is",
"called",
"when",
"the",
"presentValue",
"of",
"the",
"local",
"schedule",
"object",
"has",
"changed",
"both",
"internally",
"by",
"this",
"interpreter",
"or",
"externally",
"by",
"some",
"client",
"using",
"WriteProperty",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/local/schedule.py#L366-L408 | train | 201,882 |
JoelBender/bacpypes | py25/bacpypes/consolecmd.py | ConsoleCmd.do_gc | def do_gc(self, args):
"""gc - print out garbage collection information"""
### humm...
instance_type = getattr(types, 'InstanceType', object)
# snapshot of counts
type2count = {}
type2all = {}
for o in gc.get_objects():
if type(o) == instance_type:
type2count[o.__class__] = type2count.get(o.__class__,0) + 1
type2all[o.__class__] = type2all.get(o.__class__,0) + sys.getrefcount(o)
# count the things that have changed
ct = [ ( t.__module__
, t.__name__
, type2count[t]
, type2count[t] - self.type2count.get(t,0)
, type2all[t] - self.type2all.get(t,0)
) for t in type2count.iterkeys()
]
# ready for the next time
self.type2count = type2count
self.type2all = type2all
fmt = "%-30s %-30s %6s %6s %6s\n"
self.stdout.write(fmt % ("Module", "Type", "Count", "dCount", "dRef"))
# sorted by count
ct.sort(lambda x, y: cmp(y[2], x[2]))
for i in range(min(10,len(ct))):
m, n, c, delta1, delta2 = ct[i]
self.stdout.write(fmt % (m, n, c, delta1, delta2))
self.stdout.write("\n")
self.stdout.write(fmt % ("Module", "Type", "Count", "dCount", "dRef"))
# sorted by module and class
ct.sort()
for m, n, c, delta1, delta2 in ct:
if delta1 or delta2:
self.stdout.write(fmt % (m, n, c, delta1, delta2))
self.stdout.write("\n") | python | def do_gc(self, args):
"""gc - print out garbage collection information"""
### humm...
instance_type = getattr(types, 'InstanceType', object)
# snapshot of counts
type2count = {}
type2all = {}
for o in gc.get_objects():
if type(o) == instance_type:
type2count[o.__class__] = type2count.get(o.__class__,0) + 1
type2all[o.__class__] = type2all.get(o.__class__,0) + sys.getrefcount(o)
# count the things that have changed
ct = [ ( t.__module__
, t.__name__
, type2count[t]
, type2count[t] - self.type2count.get(t,0)
, type2all[t] - self.type2all.get(t,0)
) for t in type2count.iterkeys()
]
# ready for the next time
self.type2count = type2count
self.type2all = type2all
fmt = "%-30s %-30s %6s %6s %6s\n"
self.stdout.write(fmt % ("Module", "Type", "Count", "dCount", "dRef"))
# sorted by count
ct.sort(lambda x, y: cmp(y[2], x[2]))
for i in range(min(10,len(ct))):
m, n, c, delta1, delta2 = ct[i]
self.stdout.write(fmt % (m, n, c, delta1, delta2))
self.stdout.write("\n")
self.stdout.write(fmt % ("Module", "Type", "Count", "dCount", "dRef"))
# sorted by module and class
ct.sort()
for m, n, c, delta1, delta2 in ct:
if delta1 or delta2:
self.stdout.write(fmt % (m, n, c, delta1, delta2))
self.stdout.write("\n") | [
"def",
"do_gc",
"(",
"self",
",",
"args",
")",
":",
"### humm...",
"instance_type",
"=",
"getattr",
"(",
"types",
",",
"'InstanceType'",
",",
"object",
")",
"# snapshot of counts",
"type2count",
"=",
"{",
"}",
"type2all",
"=",
"{",
"}",
"for",
"o",
"in",
... | gc - print out garbage collection information | [
"gc",
"-",
"print",
"out",
"garbage",
"collection",
"information"
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/consolecmd.py#L103-L147 | train | 201,883 |
JoelBender/bacpypes | py25/bacpypes/consolecmd.py | ConsoleCmd.do_buggers | def do_buggers(self, args):
"""buggers - list the console logging handlers"""
args = args.split()
if _debug: ConsoleCmd._debug("do_buggers %r", args)
if not self.handlers:
self.stdout.write("no handlers\n")
else:
self.stdout.write("handlers: ")
self.stdout.write(', '.join(loggerName or '__root__' for loggerName in self.handlers))
self.stdout.write("\n")
loggers = logging.Logger.manager.loggerDict.keys()
for loggerName in sorted(loggers):
if args and (not args[0] in loggerName):
continue
if loggerName in self.handlers:
self.stdout.write("* %s\n" % loggerName)
else:
self.stdout.write(" %s\n" % loggerName)
self.stdout.write("\n") | python | def do_buggers(self, args):
"""buggers - list the console logging handlers"""
args = args.split()
if _debug: ConsoleCmd._debug("do_buggers %r", args)
if not self.handlers:
self.stdout.write("no handlers\n")
else:
self.stdout.write("handlers: ")
self.stdout.write(', '.join(loggerName or '__root__' for loggerName in self.handlers))
self.stdout.write("\n")
loggers = logging.Logger.manager.loggerDict.keys()
for loggerName in sorted(loggers):
if args and (not args[0] in loggerName):
continue
if loggerName in self.handlers:
self.stdout.write("* %s\n" % loggerName)
else:
self.stdout.write(" %s\n" % loggerName)
self.stdout.write("\n") | [
"def",
"do_buggers",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"_debug",
":",
"ConsoleCmd",
".",
"_debug",
"(",
"\"do_buggers %r\"",
",",
"args",
")",
"if",
"not",
"self",
".",
"handlers",
":",
"self",
"."... | buggers - list the console logging handlers | [
"buggers",
"-",
"list",
"the",
"console",
"logging",
"handlers"
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/consolecmd.py#L212-L233 | train | 201,884 |
JoelBender/bacpypes | py25/bacpypes/consolecmd.py | ConsoleCmd.do_EOF | def do_EOF(self, args):
"""Exit on system end of file character"""
if _debug: ConsoleCmd._debug("do_EOF %r", args)
return self.do_exit(args) | python | def do_EOF(self, args):
"""Exit on system end of file character"""
if _debug: ConsoleCmd._debug("do_EOF %r", args)
return self.do_exit(args) | [
"def",
"do_EOF",
"(",
"self",
",",
"args",
")",
":",
"if",
"_debug",
":",
"ConsoleCmd",
".",
"_debug",
"(",
"\"do_EOF %r\"",
",",
"args",
")",
"return",
"self",
".",
"do_exit",
"(",
"args",
")"
] | Exit on system end of file character | [
"Exit",
"on",
"system",
"end",
"of",
"file",
"character"
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/consolecmd.py#L243-L246 | train | 201,885 |
JoelBender/bacpypes | py25/bacpypes/consolecmd.py | ConsoleCmd.do_shell | def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
if _debug: ConsoleCmd._debug("do_shell %r", args)
os.system(args) | python | def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
if _debug: ConsoleCmd._debug("do_shell %r", args)
os.system(args) | [
"def",
"do_shell",
"(",
"self",
",",
"args",
")",
":",
"if",
"_debug",
":",
"ConsoleCmd",
".",
"_debug",
"(",
"\"do_shell %r\"",
",",
"args",
")",
"os",
".",
"system",
"(",
"args",
")"
] | Pass command to a system shell when line begins with '! | [
"Pass",
"command",
"to",
"a",
"system",
"shell",
"when",
"line",
"begins",
"with",
"!"
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/consolecmd.py#L248-L252 | train | 201,886 |
JoelBender/bacpypes | py25/bacpypes/netservice.py | NetworkAdapter.confirmation | def confirmation(self, pdu):
"""Decode upstream PDUs and pass them up to the service access point."""
if _debug: NetworkAdapter._debug("confirmation %r (net=%r)", pdu, self.adapterNet)
npdu = NPDU(user_data=pdu.pduUserData)
npdu.decode(pdu)
self.adapterSAP.process_npdu(self, npdu) | python | def confirmation(self, pdu):
"""Decode upstream PDUs and pass them up to the service access point."""
if _debug: NetworkAdapter._debug("confirmation %r (net=%r)", pdu, self.adapterNet)
npdu = NPDU(user_data=pdu.pduUserData)
npdu.decode(pdu)
self.adapterSAP.process_npdu(self, npdu) | [
"def",
"confirmation",
"(",
"self",
",",
"pdu",
")",
":",
"if",
"_debug",
":",
"NetworkAdapter",
".",
"_debug",
"(",
"\"confirmation %r (net=%r)\"",
",",
"pdu",
",",
"self",
".",
"adapterNet",
")",
"npdu",
"=",
"NPDU",
"(",
"user_data",
"=",
"pdu",
".",
... | Decode upstream PDUs and pass them up to the service access point. | [
"Decode",
"upstream",
"PDUs",
"and",
"pass",
"them",
"up",
"to",
"the",
"service",
"access",
"point",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/netservice.py#L182-L188 | train | 201,887 |
JoelBender/bacpypes | py25/bacpypes/netservice.py | NetworkAdapter.process_npdu | def process_npdu(self, npdu):
"""Encode NPDUs from the service access point and send them downstream."""
if _debug: NetworkAdapter._debug("process_npdu %r (net=%r)", npdu, self.adapterNet)
pdu = PDU(user_data=npdu.pduUserData)
npdu.encode(pdu)
self.request(pdu) | python | def process_npdu(self, npdu):
"""Encode NPDUs from the service access point and send them downstream."""
if _debug: NetworkAdapter._debug("process_npdu %r (net=%r)", npdu, self.adapterNet)
pdu = PDU(user_data=npdu.pduUserData)
npdu.encode(pdu)
self.request(pdu) | [
"def",
"process_npdu",
"(",
"self",
",",
"npdu",
")",
":",
"if",
"_debug",
":",
"NetworkAdapter",
".",
"_debug",
"(",
"\"process_npdu %r (net=%r)\"",
",",
"npdu",
",",
"self",
".",
"adapterNet",
")",
"pdu",
"=",
"PDU",
"(",
"user_data",
"=",
"npdu",
".",
... | Encode NPDUs from the service access point and send them downstream. | [
"Encode",
"NPDUs",
"from",
"the",
"service",
"access",
"point",
"and",
"send",
"them",
"downstream",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/netservice.py#L190-L196 | train | 201,888 |
JoelBender/bacpypes | py25/bacpypes/netservice.py | NetworkServiceAccessPoint.bind | def bind(self, server, net=None, address=None):
"""Create a network adapter object and bind."""
if _debug: NetworkServiceAccessPoint._debug("bind %r net=%r address=%r", server, net, address)
# make sure this hasn't already been called with this network
if net in self.adapters:
raise RuntimeError("already bound")
# create an adapter object, add it to our map
adapter = NetworkAdapter(self, net)
self.adapters[net] = adapter
if _debug: NetworkServiceAccessPoint._debug(" - adapters[%r]: %r", net, adapter)
# if the address was given, make it the "local" one
if address and not self.local_address:
self.local_adapter = adapter
self.local_address = address
# bind to the server
bind(adapter, server) | python | def bind(self, server, net=None, address=None):
"""Create a network adapter object and bind."""
if _debug: NetworkServiceAccessPoint._debug("bind %r net=%r address=%r", server, net, address)
# make sure this hasn't already been called with this network
if net in self.adapters:
raise RuntimeError("already bound")
# create an adapter object, add it to our map
adapter = NetworkAdapter(self, net)
self.adapters[net] = adapter
if _debug: NetworkServiceAccessPoint._debug(" - adapters[%r]: %r", net, adapter)
# if the address was given, make it the "local" one
if address and not self.local_address:
self.local_adapter = adapter
self.local_address = address
# bind to the server
bind(adapter, server) | [
"def",
"bind",
"(",
"self",
",",
"server",
",",
"net",
"=",
"None",
",",
"address",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"NetworkServiceAccessPoint",
".",
"_debug",
"(",
"\"bind %r net=%r address=%r\"",
",",
"server",
",",
"net",
",",
"address",
")"... | Create a network adapter object and bind. | [
"Create",
"a",
"network",
"adapter",
"object",
"and",
"bind",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/netservice.py#L234-L253 | train | 201,889 |
JoelBender/bacpypes | py34/bacpypes/pdu.py | unpack_ip_addr | def unpack_ip_addr(addr):
"""Given a six-octet BACnet address, return an IP address tuple."""
if isinstance(addr, bytearray):
addr = bytes(addr)
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0]) | python | def unpack_ip_addr(addr):
"""Given a six-octet BACnet address, return an IP address tuple."""
if isinstance(addr, bytearray):
addr = bytes(addr)
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0]) | [
"def",
"unpack_ip_addr",
"(",
"addr",
")",
":",
"if",
"isinstance",
"(",
"addr",
",",
"bytearray",
")",
":",
"addr",
"=",
"bytes",
"(",
"addr",
")",
"return",
"(",
"socket",
".",
"inet_ntoa",
"(",
"addr",
"[",
"0",
":",
"4",
"]",
")",
",",
"struct"... | Given a six-octet BACnet address, return an IP address tuple. | [
"Given",
"a",
"six",
"-",
"octet",
"BACnet",
"address",
"return",
"an",
"IP",
"address",
"tuple",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/pdu.py#L391-L395 | train | 201,890 |
JoelBender/bacpypes | py25/bacpypes/debugging.py | ModuleLogger | def ModuleLogger(globs):
"""Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
All of the calls within functions or class methods within the module should
first check to see if _debug is set to prevent calls to formatter objects
that aren't necessary.
"""
# make sure that _debug is defined
if not globs.has_key('_debug'):
raise RuntimeError("define _debug before creating a module logger")
# logger name is the module name
logger_name = globs['__name__']
# create a logger to be assigned to _log
logger = logging.getLogger(logger_name)
# put in a reference to the module globals
logger.globs = globs
# if this is a "root" logger add a default handler for warnings and up
if '.' not in logger_name:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.WARNING)
hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
logger.addHandler(hdlr)
return logger | python | def ModuleLogger(globs):
"""Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
All of the calls within functions or class methods within the module should
first check to see if _debug is set to prevent calls to formatter objects
that aren't necessary.
"""
# make sure that _debug is defined
if not globs.has_key('_debug'):
raise RuntimeError("define _debug before creating a module logger")
# logger name is the module name
logger_name = globs['__name__']
# create a logger to be assigned to _log
logger = logging.getLogger(logger_name)
# put in a reference to the module globals
logger.globs = globs
# if this is a "root" logger add a default handler for warnings and up
if '.' not in logger_name:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.WARNING)
hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
logger.addHandler(hdlr)
return logger | [
"def",
"ModuleLogger",
"(",
"globs",
")",
":",
"# make sure that _debug is defined",
"if",
"not",
"globs",
".",
"has_key",
"(",
"'_debug'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"define _debug before creating a module logger\"",
")",
"# logger name is the module name",
... | Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
All of the calls within functions or class methods within the module should
first check to see if _debug is set to prevent calls to formatter objects
that aren't necessary. | [
"Create",
"a",
"module",
"level",
"logger",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/debugging.py#L43-L75 | train | 201,891 |
JoelBender/bacpypes | py25/bacpypes/debugging.py | bacpypes_debugging | def bacpypes_debugging(obj):
"""Function for attaching a debugging logger to a class or function."""
# create a logger for this object
logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)
# make it available to instances
obj._logger = logger
obj._debug = logger.debug
obj._info = logger.info
obj._warning = logger.warning
obj._error = logger.error
obj._exception = logger.exception
obj._fatal = logger.fatal
return obj | python | def bacpypes_debugging(obj):
"""Function for attaching a debugging logger to a class or function."""
# create a logger for this object
logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)
# make it available to instances
obj._logger = logger
obj._debug = logger.debug
obj._info = logger.info
obj._warning = logger.warning
obj._error = logger.error
obj._exception = logger.exception
obj._fatal = logger.fatal
return obj | [
"def",
"bacpypes_debugging",
"(",
"obj",
")",
":",
"# create a logger for this object",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"obj",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__name__",
")",
"# make it available to instances",
"obj",
".",
"_logge... | Function for attaching a debugging logger to a class or function. | [
"Function",
"for",
"attaching",
"a",
"debugging",
"logger",
"to",
"a",
"class",
"or",
"function",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/debugging.py#L269-L283 | train | 201,892 |
JoelBender/bacpypes | py25/bacpypes/vlan.py | Network.add_node | def add_node(self, node):
""" Add a node to this network, let the node know which network it's on. """
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
# update the node name
if not node.name:
node.name = '%s:%s' % (self.name, node.address) | python | def add_node(self, node):
""" Add a node to this network, let the node know which network it's on. """
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
# update the node name
if not node.name:
node.name = '%s:%s' % (self.name, node.address) | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"_debug",
":",
"Network",
".",
"_debug",
"(",
"\"add_node %r\"",
",",
"node",
")",
"self",
".",
"nodes",
".",
"append",
"(",
"node",
")",
"node",
".",
"lan",
"=",
"self",
"# update the node n... | Add a node to this network, let the node know which network it's on. | [
"Add",
"a",
"node",
"to",
"this",
"network",
"let",
"the",
"node",
"know",
"which",
"network",
"it",
"s",
"on",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/vlan.py#L40-L49 | train | 201,893 |
JoelBender/bacpypes | py25/bacpypes/vlan.py | Network.remove_node | def remove_node(self, node):
""" Remove a node from this network. """
if _debug: Network._debug("remove_node %r", node)
self.nodes.remove(node)
node.lan = None | python | def remove_node(self, node):
""" Remove a node from this network. """
if _debug: Network._debug("remove_node %r", node)
self.nodes.remove(node)
node.lan = None | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"_debug",
":",
"Network",
".",
"_debug",
"(",
"\"remove_node %r\"",
",",
"node",
")",
"self",
".",
"nodes",
".",
"remove",
"(",
"node",
")",
"node",
".",
"lan",
"=",
"None"
] | Remove a node from this network. | [
"Remove",
"a",
"node",
"from",
"this",
"network",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/vlan.py#L51-L56 | train | 201,894 |
JoelBender/bacpypes | py25/bacpypes/vlan.py | Network.process_pdu | def process_pdu(self, pdu):
""" Process a PDU by sending a copy to each node as dictated by the
addressing and if a node is promiscuous.
"""
if _debug: Network._debug("process_pdu(%s) %r", self.name, pdu)
# if there is a traffic log, call it with the network name and pdu
if self.traffic_log:
self.traffic_log(self.name, pdu)
# randomly drop a packet
if self.drop_percent != 0.0:
if (random.random() * 100.0) < self.drop_percent:
if _debug: Network._debug(" - packet dropped")
return
if pdu.pduDestination == self.broadcast_address:
if _debug: Network._debug(" - broadcast")
for node in self.nodes:
if (pdu.pduSource != node.address):
if _debug: Network._debug(" - match: %r", node)
node.response(deepcopy(pdu))
else:
if _debug: Network._debug(" - unicast")
for node in self.nodes:
if node.promiscuous or (pdu.pduDestination == node.address):
if _debug: Network._debug(" - match: %r", node)
node.response(deepcopy(pdu)) | python | def process_pdu(self, pdu):
""" Process a PDU by sending a copy to each node as dictated by the
addressing and if a node is promiscuous.
"""
if _debug: Network._debug("process_pdu(%s) %r", self.name, pdu)
# if there is a traffic log, call it with the network name and pdu
if self.traffic_log:
self.traffic_log(self.name, pdu)
# randomly drop a packet
if self.drop_percent != 0.0:
if (random.random() * 100.0) < self.drop_percent:
if _debug: Network._debug(" - packet dropped")
return
if pdu.pduDestination == self.broadcast_address:
if _debug: Network._debug(" - broadcast")
for node in self.nodes:
if (pdu.pduSource != node.address):
if _debug: Network._debug(" - match: %r", node)
node.response(deepcopy(pdu))
else:
if _debug: Network._debug(" - unicast")
for node in self.nodes:
if node.promiscuous or (pdu.pduDestination == node.address):
if _debug: Network._debug(" - match: %r", node)
node.response(deepcopy(pdu)) | [
"def",
"process_pdu",
"(",
"self",
",",
"pdu",
")",
":",
"if",
"_debug",
":",
"Network",
".",
"_debug",
"(",
"\"process_pdu(%s) %r\"",
",",
"self",
".",
"name",
",",
"pdu",
")",
"# if there is a traffic log, call it with the network name and pdu",
"if",
"self",
".... | Process a PDU by sending a copy to each node as dictated by the
addressing and if a node is promiscuous. | [
"Process",
"a",
"PDU",
"by",
"sending",
"a",
"copy",
"to",
"each",
"node",
"as",
"dictated",
"by",
"the",
"addressing",
"and",
"if",
"a",
"node",
"is",
"promiscuous",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/vlan.py#L58-L85 | train | 201,895 |
JoelBender/bacpypes | py25/bacpypes/vlan.py | Node.bind | def bind(self, lan):
"""bind to a LAN."""
if _debug: Node._debug("bind %r", lan)
lan.add_node(self) | python | def bind(self, lan):
"""bind to a LAN."""
if _debug: Node._debug("bind %r", lan)
lan.add_node(self) | [
"def",
"bind",
"(",
"self",
",",
"lan",
")",
":",
"if",
"_debug",
":",
"Node",
".",
"_debug",
"(",
"\"bind %r\"",
",",
"lan",
")",
"lan",
".",
"add_node",
"(",
"self",
")"
] | bind to a LAN. | [
"bind",
"to",
"a",
"LAN",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/vlan.py#L118-L122 | train | 201,896 |
JoelBender/bacpypes | pcap_tools/COVNotificationSummaryFilter.py | Match | def Match(addr1, addr2):
"""Return true iff addr1 matches addr2."""
if _debug: Match._debug("Match %r %r", addr1, addr2)
if (addr2.addrType == Address.localBroadcastAddr):
# match any local station
return (addr1.addrType == Address.localStationAddr) or (addr1.addrType == Address.localBroadcastAddr)
elif (addr2.addrType == Address.localStationAddr):
# match a specific local station
return (addr1.addrType == Address.localStationAddr) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.remoteBroadcastAddr):
# match any remote station or remote broadcast on a matching network
return ((addr1.addrType == Address.remoteStationAddr) or (addr1.addrType == Address.remoteBroadcastAddr)) \
and (addr1.addrNet == addr2.addrNet)
elif (addr2.addrType == Address.remoteStationAddr):
# match a specific remote station
return (addr1.addrType == Address.remoteStationAddr) and \
(addr1.addrNet == addr2.addrNet) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.globalBroadcastAddr):
# match a global broadcast address
return (addr1.addrType == Address.globalBroadcastAddr)
else:
raise RuntimeError, "invalid match combination" | python | def Match(addr1, addr2):
"""Return true iff addr1 matches addr2."""
if _debug: Match._debug("Match %r %r", addr1, addr2)
if (addr2.addrType == Address.localBroadcastAddr):
# match any local station
return (addr1.addrType == Address.localStationAddr) or (addr1.addrType == Address.localBroadcastAddr)
elif (addr2.addrType == Address.localStationAddr):
# match a specific local station
return (addr1.addrType == Address.localStationAddr) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.remoteBroadcastAddr):
# match any remote station or remote broadcast on a matching network
return ((addr1.addrType == Address.remoteStationAddr) or (addr1.addrType == Address.remoteBroadcastAddr)) \
and (addr1.addrNet == addr2.addrNet)
elif (addr2.addrType == Address.remoteStationAddr):
# match a specific remote station
return (addr1.addrType == Address.remoteStationAddr) and \
(addr1.addrNet == addr2.addrNet) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.globalBroadcastAddr):
# match a global broadcast address
return (addr1.addrType == Address.globalBroadcastAddr)
else:
raise RuntimeError, "invalid match combination" | [
"def",
"Match",
"(",
"addr1",
",",
"addr2",
")",
":",
"if",
"_debug",
":",
"Match",
".",
"_debug",
"(",
"\"Match %r %r\"",
",",
"addr1",
",",
"addr2",
")",
"if",
"(",
"addr2",
".",
"addrType",
"==",
"Address",
".",
"localBroadcastAddr",
")",
":",
"# ma... | Return true iff addr1 matches addr2. | [
"Return",
"true",
"iff",
"addr1",
"matches",
"addr2",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/pcap_tools/COVNotificationSummaryFilter.py#L33-L55 | train | 201,897 |
JoelBender/bacpypes | py25/bacpypes/service/device.py | WhoIsIAmServices.do_WhoIsRequest | def do_WhoIsRequest(self, apdu):
"""Respond to a Who-Is request."""
if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu)
# ignore this if there's no local device
if not self.localDevice:
if _debug: WhoIsIAmServices._debug(" - no local device")
return
# extract the parameters
low_limit = apdu.deviceInstanceRangeLowLimit
high_limit = apdu.deviceInstanceRangeHighLimit
# check for consistent parameters
if (low_limit is not None):
if (high_limit is None):
raise MissingRequiredParameter("deviceInstanceRangeHighLimit required")
if (low_limit < 0) or (low_limit > 4194303):
raise ParameterOutOfRange("deviceInstanceRangeLowLimit out of range")
if (high_limit is not None):
if (low_limit is None):
raise MissingRequiredParameter("deviceInstanceRangeLowLimit required")
if (high_limit < 0) or (high_limit > 4194303):
raise ParameterOutOfRange("deviceInstanceRangeHighLimit out of range")
# see we should respond
if (low_limit is not None):
if (self.localDevice.objectIdentifier[1] < low_limit):
return
if (high_limit is not None):
if (self.localDevice.objectIdentifier[1] > high_limit):
return
# generate an I-Am
self.i_am(address=apdu.pduSource) | python | def do_WhoIsRequest(self, apdu):
"""Respond to a Who-Is request."""
if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu)
# ignore this if there's no local device
if not self.localDevice:
if _debug: WhoIsIAmServices._debug(" - no local device")
return
# extract the parameters
low_limit = apdu.deviceInstanceRangeLowLimit
high_limit = apdu.deviceInstanceRangeHighLimit
# check for consistent parameters
if (low_limit is not None):
if (high_limit is None):
raise MissingRequiredParameter("deviceInstanceRangeHighLimit required")
if (low_limit < 0) or (low_limit > 4194303):
raise ParameterOutOfRange("deviceInstanceRangeLowLimit out of range")
if (high_limit is not None):
if (low_limit is None):
raise MissingRequiredParameter("deviceInstanceRangeLowLimit required")
if (high_limit < 0) or (high_limit > 4194303):
raise ParameterOutOfRange("deviceInstanceRangeHighLimit out of range")
# see we should respond
if (low_limit is not None):
if (self.localDevice.objectIdentifier[1] < low_limit):
return
if (high_limit is not None):
if (self.localDevice.objectIdentifier[1] > high_limit):
return
# generate an I-Am
self.i_am(address=apdu.pduSource) | [
"def",
"do_WhoIsRequest",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"WhoIsIAmServices",
".",
"_debug",
"(",
"\"do_WhoIsRequest %r\"",
",",
"apdu",
")",
"# ignore this if there's no local device",
"if",
"not",
"self",
".",
"localDevice",
":",
"if",
... | Respond to a Who-Is request. | [
"Respond",
"to",
"a",
"Who",
"-",
"Is",
"request",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/device.py#L67-L101 | train | 201,898 |
JoelBender/bacpypes | py25/bacpypes/service/device.py | WhoIsIAmServices.do_IAmRequest | def do_IAmRequest(self, apdu):
"""Respond to an I-Am request."""
if _debug: WhoIsIAmServices._debug("do_IAmRequest %r", apdu)
# check for required parameters
if apdu.iAmDeviceIdentifier is None:
raise MissingRequiredParameter("iAmDeviceIdentifier required")
if apdu.maxAPDULengthAccepted is None:
raise MissingRequiredParameter("maxAPDULengthAccepted required")
if apdu.segmentationSupported is None:
raise MissingRequiredParameter("segmentationSupported required")
if apdu.vendorID is None:
raise MissingRequiredParameter("vendorID required")
# extract the device instance number
device_instance = apdu.iAmDeviceIdentifier[1]
if _debug: WhoIsIAmServices._debug(" - device_instance: %r", device_instance)
# extract the source address
device_address = apdu.pduSource
if _debug: WhoIsIAmServices._debug(" - device_address: %r", device_address) | python | def do_IAmRequest(self, apdu):
"""Respond to an I-Am request."""
if _debug: WhoIsIAmServices._debug("do_IAmRequest %r", apdu)
# check for required parameters
if apdu.iAmDeviceIdentifier is None:
raise MissingRequiredParameter("iAmDeviceIdentifier required")
if apdu.maxAPDULengthAccepted is None:
raise MissingRequiredParameter("maxAPDULengthAccepted required")
if apdu.segmentationSupported is None:
raise MissingRequiredParameter("segmentationSupported required")
if apdu.vendorID is None:
raise MissingRequiredParameter("vendorID required")
# extract the device instance number
device_instance = apdu.iAmDeviceIdentifier[1]
if _debug: WhoIsIAmServices._debug(" - device_instance: %r", device_instance)
# extract the source address
device_address = apdu.pduSource
if _debug: WhoIsIAmServices._debug(" - device_address: %r", device_address) | [
"def",
"do_IAmRequest",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"WhoIsIAmServices",
".",
"_debug",
"(",
"\"do_IAmRequest %r\"",
",",
"apdu",
")",
"# check for required parameters",
"if",
"apdu",
".",
"iAmDeviceIdentifier",
"is",
"None",
":",
"ra... | Respond to an I-Am request. | [
"Respond",
"to",
"an",
"I",
"-",
"Am",
"request",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/device.py#L128-L148 | train | 201,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.