code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Evaluates the interpolated function and its derivative at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. Returns ------- y : np.array or float The interpo...
def eval_with_derivative(self,x)
Evaluates the interpolated function and its derivative at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. Returns ------- y : np.array or float The interpolated function evalu...
3.023852
1.591909
1.899514
''' Evaluates the partial derivative of interpolated function with respect to x (the first argument) at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. y : np.array or float ...
def derivativeX(self,x,y)
Evaluates the partial derivative of interpolated function with respect to x (the first argument) at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. y : np.array or float Real values to...
3.916793
1.503959
2.604321
''' Evaluates the partial derivative of the interpolated function with respect to z (the third argument) at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. y : np.array or float ...
def derivativeZ(self,x,y,z)
Evaluates the partial derivative of the interpolated function with respect to z (the third argument) at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. y : np.array or float Real value...
2.81548
1.412124
1.993791
''' Evaluates the partial derivative with respect to w (the first argument) of the interpolated function at the given input. Parameters ---------- w : np.array or float Real values to be evaluated in the interpolated function. x : np.array or float ...
def derivativeW(self,w,x,y,z)
Evaluates the partial derivative with respect to w (the first argument) of the interpolated function at the given input. Parameters ---------- w : np.array or float Real values to be evaluated in the interpolated function. x : np.array or float Real value...
2.621141
1.334576
1.964025
''' Evaluates the partial derivative with respect to y (the third argument) of the interpolated function at the given input. Parameters ---------- w : np.array or float Real values to be evaluated in the interpolated function. x : np.array or float ...
def derivativeY(self,w,x,y,z)
Evaluates the partial derivative with respect to y (the third argument) of the interpolated function at the given input. Parameters ---------- w : np.array or float Real values to be evaluated in the interpolated function. x : np.array or float Real value...
2.584193
1.324509
1.951057
''' Returns the derivative of the function with respect to the first dimension. ''' if self.i_dim == 0: return np.ones_like(*args[0]) else: return np.zeros_like(*args[0])
def derivative(self,*args)
Returns the derivative of the function with respect to the first dimension.
4.641074
3.542747
1.310021
''' Returns the derivative of the function with respect to the X dimension. This is the first input whenever n_dims < 4 and the second input otherwise. ''' if self.n_dims >= 4: j = 1 else: j = 0 if self.i_dim == j: return np.one...
def derivativeX(self,*args)
Returns the derivative of the function with respect to the X dimension. This is the first input whenever n_dims < 4 and the second input otherwise.
5.234828
2.441041
2.144506
''' Returns the derivative of the function with respect to the W dimension. This should only exist when n_dims >= 4. ''' if self.n_dims >= 4: j = 0 else: assert False, "Derivative with respect to W can't be called when n_dims < 4!" if self....
def derivativeW(self,*args)
Returns the derivative of the function with respect to the W dimension. This should only exist when n_dims >= 4.
5.086683
3.087258
1.647638
''' Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros. ''' if len(args) > 0: if _isscalar(args[0]): return 0.0 ...
def _der(self,*args)
Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.
4.764169
1.825933
2.60917
''' Returns the level and/or first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc). Parameters ---------- x_list : scalar or np.array Set of points where we want to evlauate the interpolated func...
def _evalOrDer(self,x,_eval,_Der)
Returns the level and/or first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc). Parameters ---------- x_list : scalar or np.array Set of points where we want to evlauate the interpolated function and/or its deri...
2.749691
1.763249
1.559446
''' Returns the level of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.__call__ (etc). ''' return self._evalOrDer(x,True,False)[0]
def _evaluate(self,x,return_indices = False)
Returns the level of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.__call__ (etc).
16.143881
3.173795
5.086618
''' Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc). ''' y,dydx = self._evalOrDer(x,True,True) return y,dydx
def _evalAndDer(self,x)
Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc).
10.755098
2.721461
3.951958
''' Returns the first derivative of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.derivative (etc). ''' if _isscalar(x): pos = np.searchsorted(self.x_list,x) if pos == 0: dydx = self.coeffs[0,1] ...
def _der(self,x)
Returns the first derivative of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.derivative (etc).
2.128503
1.858144
1.145499
''' Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc). ''' if _isscalar(x): pos = np.searchsorted(self.x_list,x) if pos == 0: y = self.coeffs[0,0] + s...
def _evalAndDer(self,x)
Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der (etc).
1.706338
1.535133
1.111525
''' Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc). ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) y_pos = max(min(self.ySearchFunc(self....
def _evaluate(self,x,y)
Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc).
1.91729
1.57136
1.220147
''' Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX. ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) y_pos = max(min(se...
def _derX(self,x,y)
Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
2.057051
1.701095
1.209251
''' Returns the derivative with respect to y of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeY. ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) y_pos = max(min(se...
def _derY(self,x,y)
Returns the derivative with respect to y of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeY.
2.076699
1.702199
1.220009
''' Returns the derivative with respect to x of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.derivativeX. ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) y_pos = max(min(...
def _derX(self,x,y,z)
Returns the derivative with respect to x of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.derivativeX.
1.56294
1.393144
1.12188
''' Returns the level of the function at each value in x as the minimum among all of the functions. Only called internally by HARKinterpolator1D.__call__. ''' if _isscalar(x): y = np.nanmin([f(x) for f in self.functions]) else: m = len(x) ...
def _evaluate(self,x)
Returns the level of the function at each value in x as the minimum among all of the functions. Only called internally by HARKinterpolator1D.__call__.
4.506701
2.135925
2.109953
''' Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der. ''' m = len(x) fx = np.zeros((m,self.funcCount)) for j in range(self.funcCount): fx[:,j] = self.functions[j](x) ...
def _evalAndDer(self,x)
Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der.
3.019638
1.936842
1.559053
''' Returns the first derivative of the function with respect to X at each value in (x,y). Only called internally by HARKinterpolator2D._derX. ''' m = len(x) temp = np.zeros((m,self.funcCount)) for j in range(self.funcCount): temp[:,j] = self.function...
def _derX(self,x,y)
Returns the first derivative of the function with respect to X at each value in (x,y). Only called internally by HARKinterpolator2D._derX.
3.104772
2.012811
1.542505
''' Returns the first derivative of the function with respect to Y at each value in (x,y). Only called internally by HARKinterpolator2D._derY. ''' m = len(x) temp = np.zeros((m,self.funcCount)) for j in range(self.funcCount): temp[:,j] = self.function...
def _derY(self,x,y)
Returns the first derivative of the function with respect to Y at each value in (x,y). Only called internally by HARKinterpolator2D._derY.
3.117497
2.100857
1.483917
''' Returns the first derivative of the function with respect to Z at each value in (x,y,z). Only called internally by HARKinterpolator3D._derZ. ''' m = len(x) temp = np.zeros((m,self.funcCount)) for j in range(self.funcCount): temp[:,j] = self.functi...
def _derZ(self,x,y,z)
Returns the first derivative of the function with respect to Z at each value in (x,y,z). Only called internally by HARKinterpolator3D._derZ.
3.059489
2.064882
1.481678
''' Evaluate the first derivative with respect to x of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. Returns ...
def derivativeX(self,x,y)
Evaluate the first derivative with respect to x of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. Returns ------- ...
4.922544
1.831708
2.687406
''' Evaluate the first derivative with respect to y of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. Returns ...
def derivativeY(self,x,y)
Evaluate the first derivative with respect to y of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. Returns ------- ...
4.593507
2.061322
2.228427
''' Evaluate the first derivative with respect to z of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. z : np.array ...
def derivativeZ(self,x,y,z)
Evaluate the first derivative with respect to z of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape as x. z : np.array Third i...
4.003329
1.740095
2.300638
''' Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX. ''' if _isscalar(x): y_pos = max(min(np.searchsorted(self.y_list,y),self.y_n-1),1) alpha = (y - self.y...
def _derX(self,x,y)
Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
2.207258
1.803396
1.223946
''' Returns the level of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.__call__ (etc). ''' if _isscalar(x): y_pos = max(min(np.searchsorted(self.y_list,y),self.y_n-1),1) z_pos = max(min(np.searchsorted(self....
def _evaluate(self,x,y,z)
Returns the level of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.__call__ (etc).
1.565841
1.387925
1.128189
''' Returns the derivative with respect to y of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.derivativeY. ''' if _isscalar(x): z_pos = max(min(np.searchsorted(self.z_list,z),self.z_n-1),1) alpha = (z - self...
def _derY(self,x,y,z)
Returns the derivative with respect to y of the interpolated function at each value in x,y,z. Only called internally by HARKinterpolator3D.derivativeY.
2.093736
1.721008
1.216576
''' Fills in the polarity attribute of the interpolation, determining whether the "plus" (True) or "minus" (False) solution of the system of equations should be used for each sector. Needs to be called in __init__. Parameters ---------- none Returns ...
def updatePolarity(self)
Fills in the polarity attribute of the interpolation, determining whether the "plus" (True) or "minus" (False) solution of the system of equations should be used for each sector. Needs to be called in __init__. Parameters ---------- none Returns ------- ...
2.921455
2.276005
1.283589
''' Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc). ''' x_pos, y_pos = self.findSector(x,y) alpha, beta = self.findCoords(x,y,x_pos,y_pos) # Calculate the function at each point usi...
def _evaluate(self,x,y)
Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc).
3.395984
2.229809
1.522993
''' Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX. ''' x_pos, y_pos = self.findSector(x,y) alpha, beta = self.findCoords(x,y,x_pos,y_pos) # Get four corners dat...
def _derX(self,x,y)
Returns the derivative with respect to x of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
2.065974
1.817713
1.136578
''' Returns the derivative with respect to y of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX. ''' x_pos, y_pos = self.findSector(x,y) alpha, beta = self.findCoords(x,y,x_pos,y_pos) # Get four corners dat...
def _derY(self,x,y)
Returns the derivative with respect to y of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
2.134188
1.869737
1.141437
''' A "universal distance" metric that can be used as a default in many settings. Parameters ---------- thing_A : object A generic object. thing_B : object Another generic object. Returns: ------------ distance : float The "distance" between thing_A and thin...
def distanceMetric(thing_A,thing_B)
A "universal distance" metric that can be used as a default in many settings. Parameters ---------- thing_A : object A generic object. thing_B : object Another generic object. Returns: ------------ distance : float The "distance" between thing_A and thing_B.
2.939491
2.58688
1.136307
''' Solve the dynamic model for one agent type. This function iterates on "cycles" of an agent's model either a given number of times or until solution convergence if an infinite horizon model is used (with agent.cycles = 0). Parameters ---------- agent : AgentType The microeconomi...
def solveAgent(agent,verbose)
Solve the dynamic model for one agent type. This function iterates on "cycles" of an agent's model either a given number of times or until solution convergence if an infinite horizon model is used (with agent.cycles = 0). Parameters ---------- agent : AgentType The microeconomic AgentType ...
5.233984
3.38791
1.544901
''' Solve one "cycle" of the dynamic model for one agent type. This function iterates over the periods within an agent's cycle, updating the time-varying parameters and passing them to the single period solver(s). Parameters ---------- agent : AgentType The microeconomic AgentType ...
def solveOneCycle(agent,solution_last)
Solve one "cycle" of the dynamic model for one agent type. This function iterates over the periods within an agent's cycle, updating the time-varying parameters and passing them to the single period solver(s). Parameters ---------- agent : AgentType The microeconomic AgentType whose dynami...
4.478089
2.49528
1.794624
''' Helper function for copy_module_to_local(). Provides the actual copy functionality, with highly cautious safeguards against copying over important things. Parameters ---------- target_path : string String, file path to target location my_directory_full_path: string ...
def copy_module(target_path, my_directory_full_path, my_module)
Helper function for copy_module_to_local(). Provides the actual copy functionality, with highly cautious safeguards against copying over important things. Parameters ---------- target_path : string String, file path to target location my_directory_full_path: string String, full...
4.465725
2.878664
1.551319
''' A generic distance method, which requires the existence of an attribute called distance_criteria, giving a list of strings naming the attributes to be considered by the distance metric. Parameters ---------- other : object Another object to compar...
def distance(self,other)
A generic distance method, which requires the existence of an attribute called distance_criteria, giving a list of strings naming the attributes to be considered by the distance metric. Parameters ---------- other : object Another object to compare this instance to. ...
4.265144
1.953135
2.183743
''' Assign an arbitrary number of attributes to this agent. Parameters ---------- **kwds : keyword arguments Any number of keyword arguments of the form key=value. Each value will be assigned to the attribute named in self. Returns -----...
def assignParameters(self,**kwds)
Assign an arbitrary number of attributes to this agent. Parameters ---------- **kwds : keyword arguments Any number of keyword arguments of the form key=value. Each value will be assigned to the attribute named in self. Returns ------- none
4.913225
1.625431
3.022722
''' Calculates the average of an attribute of this instance. Returns NaN if no such attribute. Parameters ---------- varname : string The name of the attribute whose average is to be calculated. This attribute must be an np.array or other class compatib...
def getAvg(self,varname,**kwds)
Calculates the average of an attribute of this instance. Returns NaN if no such attribute. Parameters ---------- varname : string The name of the attribute whose average is to be calculated. This attribute must be an np.array or other class compatible with np.mean. ...
4.150791
1.425332
2.912156
''' Reverse the flow of time for this instance. Parameters ---------- none Returns ------- none ''' for name in self.time_vary: exec('self.' + name + '.reverse()') self.time_flow = not self.time_flow
def timeFlip(self)
Reverse the flow of time for this instance. Parameters ---------- none Returns ------- none
6.12271
3.484853
1.75695
''' Adds any number of parameters to time_vary for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_vary Returns ------- None ''' for param in params: ...
def addToTimeVary(self,*params)
Adds any number of parameters to time_vary for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_vary Returns ------- None
3.727321
1.692169
2.202688
''' Adds any number of parameters to time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_inv Returns ------- None ''' for param in params: i...
def addToTimeInv(self,*params)
Adds any number of parameters to time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be added to time_inv Returns ------- None
3.804107
1.692532
2.247583
''' Removes any number of parameters from time_vary for this instance. Parameters ---------- params : string Any number of strings naming attributes to be removed from time_vary Returns ------- None ''' for param in params: ...
def delFromTimeVary(self,*params)
Removes any number of parameters from time_vary for this instance. Parameters ---------- params : string Any number of strings naming attributes to be removed from time_vary Returns ------- None
4.143197
1.692425
2.448083
''' Removes any number of parameters from time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be removed from time_inv Returns ------- None ''' for param in params: ...
def delFromTimeInv(self,*params)
Removes any number of parameters from time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be removed from time_inv Returns ------- None
4.429072
1.739914
2.54557
''' Solve the model for this instance of an agent type by backward induction. Loops through the sequence of one period problems, passing the solution from period t+1 to the problem for period t. Parameters ---------- verbose : boolean If True, solutio...
def solve(self,verbose=False)
Solve the model for this instance of an agent type by backward induction. Loops through the sequence of one period problems, passing the solution from period t+1 to the problem for period t. Parameters ---------- verbose : boolean If True, solution progress is printe...
8.145717
4.598492
1.771389
for param in self.time_vary: assert type(getattr(self,param))==list,param + ' is not a list, but should be' + \ ' because it is in time_vary'
def checkElementsOfTimeVaryAreLists(self)
A method to check that elements of time_vary are lists.
7.254548
5.787442
1.253498
''' Prepares this AgentType for a new simulation. Resets the internal random number generator, makes initial states for all agents (using simBirth), clears histories of tracked variables. Parameters ---------- None Returns ------- None '...
def initializeSim(self)
Prepares this AgentType for a new simulation. Resets the internal random number generator, makes initial states for all agents (using simBirth), clears histories of tracked variables. Parameters ---------- None Returns ------- None
5.912399
3.182579
1.857738
''' Simulates one period for this type. Calls the methods getMortality(), getShocks() or readShocks, getStates(), getControls(), and getPostStates(). These should be defined for AgentType subclasses, except getMortality (define its components simDeath and simBirth instead) and ...
def simOnePeriod(self)
Simulates one period for this type. Calls the methods getMortality(), getShocks() or readShocks, getStates(), getControls(), and getPostStates(). These should be defined for AgentType subclasses, except getMortality (define its components simDeath and simBirth instead) and readShocks. ...
7.538643
3.513951
2.145347
''' Makes a pre-specified history of shocks for the simulation. Shock variables should be named in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset of the standard simulation loop by simulating only mortality and shocks; each variable named ...
def makeShockHistory(self)
Makes a pre-specified history of shocks for the simulation. Shock variables should be named in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset of the standard simulation loop by simulating only mortality and shocks; each variable named in shock_vars is s...
5.495009
2.587573
2.123615
''' Determines which agents in the current population "die" or should be replaced. Takes no inputs, returns a Boolean array of size self.AgentCount, which has True for agents who die and False for those that survive. Returns all False by default, must be overwritten by a subclas...
def simDeath(self)
Determines which agents in the current population "die" or should be replaced. Takes no inputs, returns a Boolean array of size self.AgentCount, which has True for agents who die and False for those that survive. Returns all False by default, must be overwritten by a subclass to have replacemen...
8.26802
1.811055
4.565306
''' Reads values of shock variables for the current period from history arrays. For each var- iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:]. This method is only ever called if self.read_shocks is True. This can be achieved by using ...
def readShocks(self)
Reads values of shock variables for the current period from history arrays. For each var- iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:]. This method is only ever called if self.read_shocks is True. This can be achieved by using the method makeSho...
7.734284
1.403207
5.511864
''' Simulates this agent type for a given number of periods (defaults to self.T_sim if no input). Records histories of attributes named in self.track_vars in attributes named varname_hist. Parameters ---------- None Returns ------- None '...
def simulate(self,sim_periods=None)
Simulates this agent type for a given number of periods (defaults to self.T_sim if no input). Records histories of attributes named in self.track_vars in attributes named varname_hist. Parameters ---------- None Returns ------- None
5.744282
3.566789
1.610491
''' Solves the microeconomic problem for all AgentTypes in this market. Parameters ---------- None Returns ------- None ''' #for this_type in self.agents: # this_type.solve() try: multiThreadCommands(self.ag...
def solveAgents(self)
Solves the microeconomic problem for all AgentTypes in this market. Parameters ---------- None Returns ------- None
7.422371
5.902869
1.257418
''' "Solves" the market by finding a "dynamic rule" that governs the aggregate market state such that when agents believe in these dynamics, their actions collectively generate the same dynamic rule. Parameters ---------- None Returns ------- ...
def solve(self)
"Solves" the market by finding a "dynamic rule" that governs the aggregate market state such that when agents believe in these dynamics, their actions collectively generate the same dynamic rule. Parameters ---------- None Returns ------- None
8.264059
4.911117
1.682725
''' Collects attributes named in reap_vars from each AgentType in the market, storing them in respectively named attributes of self. Parameters ---------- none Returns ------- none ''' for var_name in self.reap_vars: h...
def reap(self)
Collects attributes named in reap_vars from each AgentType in the market, storing them in respectively named attributes of self. Parameters ---------- none Returns ------- none
5.963048
2.085916
2.858719
''' Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none ''' for var_name in self.sow_vars: ...
def sow(self)
Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none
7.187641
2.198314
3.269615
''' Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. Parameters ---------- none Returns ------- none ''' # Make a dictionary of inputs for the millRule...
def mill(self)
Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. Parameters ---------- none Returns ------- none
4.414976
2.624123
1.682458
''' Reset the state of the market (attributes in sow_vars, etc) to some user-defined initial state, and erase the histories of tracked variables. Parameters ---------- none Returns ------- none ''' for var_name in self.track_vars:...
def reset(self)
Reset the state of the market (attributes in sow_vars, etc) to some user-defined initial state, and erase the histories of tracked variables. Parameters ---------- none Returns ------- none
6.455507
2.844719
2.269295
''' Record the current value of each variable X named in track_vars in an attribute named X_hist. Parameters ---------- none Returns ------- none ''' for var_name in self.track_vars: value_now = getattr(self,var_name) ...
def store(self)
Record the current value of each variable X named in track_vars in an attribute named X_hist. Parameters ---------- none Returns ------- none
6.247194
2.0619
3.029823
''' Runs a loop of sow-->cultivate-->reap-->mill act_T times, tracking the evolution of variables X named in track_vars in attributes named X_hist. Parameters ---------- none Returns ------- none ''' self.reset() # Initialize the ...
def makeHistory(self)
Runs a loop of sow-->cultivate-->reap-->mill act_T times, tracking the evolution of variables X named in track_vars in attributes named X_hist. Parameters ---------- none Returns ------- none
15.535761
3.682946
4.218297
''' Calculates a new "aggregate dynamic rule" using the history of variables named in track_vars, and distributes this rule to AgentTypes in agents. Parameters ---------- none Returns ------- dynamics : instance The new "aggregate dyn...
def updateDynamics(self)
Calculates a new "aggregate dynamic rule" using the history of variables named in track_vars, and distributes this rule to AgentTypes in agents. Parameters ---------- none Returns ------- dynamics : instance The new "aggregate dynamic rule" that agen...
6.426276
2.910115
2.208255
''' Returns a list of strings naming all of the arguments for the passed function. Parameters ---------- function : function A function whose argument names are wanted. Returns ------- argNames : [string] The names of the arguments of function. ''' argCount = fu...
def getArgNames(function)
Returns a list of strings naming all of the arguments for the passed function. Parameters ---------- function : function A function whose argument names are wanted. Returns ------- argNames : [string] The names of the arguments of function.
3.052374
1.701506
1.793925
''' Evaluates constant relative risk aversion (CRRA) utility of consumption c given risk aversion parameter gam. Parameters ---------- c : float Consumption value gam : float Risk aversion Returns ------- (unnamed) : float Utility Tests ----- ...
def CRRAutility(c, gam)
Evaluates constant relative risk aversion (CRRA) utility of consumption c given risk aversion parameter gam. Parameters ---------- c : float Consumption value gam : float Risk aversion Returns ------- (unnamed) : float Utility Tests ----- Test a val...
5.49182
1.649775
3.32883
''' Evaluates the inverse of the CRRA utility function (with risk aversion para- meter gam) at a given utility level u. Parameters ---------- u : float Utility value gam : float Risk aversion Returns ------- (unnamed) : float Consumption corresponding to...
def CRRAutility_inv(u, gam)
Evaluates the inverse of the CRRA utility function (with risk aversion para- meter gam) at a given utility level u. Parameters ---------- u : float Utility value gam : float Risk aversion Returns ------- (unnamed) : float Consumption corresponding to given utili...
5.801214
2.105465
2.755312
''' Evaluates the derivative of the inverse of the CRRA utility function (with risk aversion parameter gam) at a given utility level u. Parameters ---------- u : float Utility value gam : float Risk aversion Returns ------- (unnamed) : float Marginal con...
def CRRAutility_invP(u, gam)
Evaluates the derivative of the inverse of the CRRA utility function (with risk aversion parameter gam) at a given utility level u. Parameters ---------- u : float Utility value gam : float Risk aversion Returns ------- (unnamed) : float Marginal consumption cor...
5.044789
2.075878
2.430195
''' Calculate a discrete approximation to a mean one lognormal distribution. Based on function approxLognormal; see that function's documentation for further notes. Parameters ---------- N : int Size of discrete space vector to be returned. sigma : float standard deviati...
def approxMeanOneLognormal(N, sigma=1.0, **kwargs)
Calculate a discrete approximation to a mean one lognormal distribution. Based on function approxLognormal; see that function's documentation for further notes. Parameters ---------- N : int Size of discrete space vector to be returned. sigma : float standard deviation associate...
9.768511
1.565536
6.239721
''' Calculate a discrete approximation to the beta distribution. May be quite slow, as it uses a rudimentary numeric integration method to generate the discrete approximation. Parameters ---------- N : int Size of discrete space vector to be returned. a : float First sh...
def approxBeta(N,a=1.0,b=1.0)
Calculate a discrete approximation to the beta distribution. May be quite slow, as it uses a rudimentary numeric integration method to generate the discrete approximation. Parameters ---------- N : int Size of discrete space vector to be returned. a : float First shape paramete...
4.770117
2.050492
2.326329
''' Makes a discrete approximation to a uniform distribution, given its bottom and top limits and number of points. Parameters ---------- N : int The number of points in the discrete approximation bot : float The bottom of the uniform distribution top : float The...
def approxUniform(N,bot=0.0,top=1.0)
Makes a discrete approximation to a uniform distribution, given its bottom and top limits and number of points. Parameters ---------- N : int The number of points in the discrete approximation bot : float The bottom of the uniform distribution top : float The top of the ...
3.63045
2.064154
1.758808
''' Creates an approximation to a normal distribution with mean mu and standard deviation sigma, returning a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_gr...
def makeMarkovApproxToNormal(x_grid,mu,sigma,K=351,bound=3.5)
Creates an approximation to a normal distribution with mean mu and standard deviation sigma, returning a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_grid)). P...
3.701686
2.424789
1.526602
''' Creates an approximation to a normal distribution with mean mu and standard deviation sigma, by Monte Carlo. Returns a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = nump...
def makeMarkovApproxToNormalByMonteCarlo(x_grid,mu,sigma,N_draws = 10000)
Creates an approximation to a normal distribution with mean mu and standard deviation sigma, by Monte Carlo. Returns a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,...
3.167852
1.765979
1.793822
''' Function to return a discretized version of an AR1 process. See http://www.fperri.net/TEACHING/macrotheory08/numerical.pdf for details Parameters ---------- N: int Size of discretized grid sigma: float Standard deviation of the error term rho: float AR1 coeff...
def makeTauchenAR1(N, sigma=1.0, rho=0.9, bound=3.0)
Function to return a discretized version of an AR1 process. See http://www.fperri.net/TEACHING/macrotheory08/numerical.pdf for details Parameters ---------- N: int Size of discretized grid sigma: float Standard deviation of the error term rho: float AR1 coefficient b...
3.873024
1.572337
2.463228
''' Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes and overall mean. Parameters ---------- distribution : [np.array] Two element list containing a list of probabilities and a list of outcomes. ...
def addDiscreteOutcomeConstantMean(distribution, x, p, sort = False)
Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes and overall mean. Parameters ---------- distribution : [np.array] Two element list containing a list of probabilities and a list of outcomes. x : float ...
6.250928
1.673028
3.736296
''' Given n lists (or tuples) whose elements represent n independent, discrete probability spaces (probabilities and values), construct a joint pmf over all combinations of these independent points. Can take multivariate discrete distributions as inputs. Parameters ---------- distribut...
def combineIndepDstns(*distributions)
Given n lists (or tuples) whose elements represent n independent, discrete probability spaces (probabilities and values), construct a joint pmf over all combinations of these independent points. Can take multivariate discrete distributions as inputs. Parameters ---------- distributions : [np.a...
5.336797
2.672396
1.997008
''' Make a multi-exponentially spaced grid. Parameters ---------- ming : float Minimum value of the grid maxg : float Maximum value of the grid ng : int The number of grid points timestonest : int the number of times to nest the exponentiation Return...
def makeGridExpMult(ming, maxg, ng, timestonest=20)
Make a multi-exponentially spaced grid. Parameters ---------- ming : float Minimum value of the grid maxg : float Maximum value of the grid ng : int The number of grid points timestonest : int the number of times to nest the exponentiation Returns ------...
3.522731
1.587502
2.21904
''' Generates a weighted average of simulated data. The Nth row of data is averaged and then weighted by the Nth element of weights in an aggregate average. Parameters ---------- data : numpy.array An array of data with N rows of J floats weights : numpy.array A length N ar...
def calcWeightedAvg(data,weights)
Generates a weighted average of simulated data. The Nth row of data is averaged and then weighted by the Nth element of weights in an aggregate average. Parameters ---------- data : numpy.array An array of data with N rows of J floats weights : numpy.array A length N array of weigh...
4.941081
1.550931
3.18588
''' Calculates the requested percentiles of (weighted) data. Median by default. Parameters ---------- data : numpy.array A 1D array of float data. weights : np.array A weighting vector for the data. percentiles : [float] A list of percentiles to calculate for the da...
def getPercentiles(data,weights=None,percentiles=[0.5],presorted=False)
Calculates the requested percentiles of (weighted) data. Median by default. Parameters ---------- data : numpy.array A 1D array of float data. weights : np.array A weighting vector for the data. percentiles : [float] A list of percentiles to calculate for the data. Each el...
3.140573
2.028256
1.548411
''' Calculates the Lorenz curve at the requested percentiles of (weighted) data. Median by default. Parameters ---------- data : numpy.array A 1D array of float data. weights : numpy.array A weighting vector for the data. percentiles : [float] A list of percentil...
def getLorenzShares(data,weights=None,percentiles=[0.5],presorted=False)
Calculates the Lorenz curve at the requested percentiles of (weighted) data. Median by default. Parameters ---------- data : numpy.array A 1D array of float data. weights : numpy.array A weighting vector for the data. percentiles : [float] A list of percentiles to calcul...
3.378808
2.115694
1.597021
''' Calculates the average of (weighted) data between cutoff percentiles of a reference variable. Parameters ---------- data : numpy.array A 1D array of float data. reference : numpy.array A 1D array of float data of the same length as data. cutoffs : [(float,float)] ...
def calcSubpopAvg(data,reference,cutoffs,weights=None)
Calculates the average of (weighted) data between cutoff percentiles of a reference variable. Parameters ---------- data : numpy.array A 1D array of float data. reference : numpy.array A 1D array of float data of the same length as data. cutoffs : [(float,float)] A list ...
2.856473
1.751296
1.631062
''' Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth. Parameters ---------- x : np.array The independent variable in the kernel regression. y : np.array The dependent variable...
def kernelRegression(x,y,bot=None,top=None,N=500,h=None)
Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth. Parameters ---------- x : np.array The independent variable in the kernel regression. y : np.array The dependent variable in the kern...
3.438936
1.774519
1.937954
''' The Epanechnikov kernel. Parameters ---------- x : np.array Values at which to evaluate the kernel x_ref : float The reference point h : float Kernel bandwidth Returns ------- out : np.array Kernel values at each value of x ''' u ...
def epanechnikovKernel(x,ref_x,h=1.0)
The Epanechnikov kernel. Parameters ---------- x : np.array Values at which to evaluate the kernel x_ref : float The reference point h : float Kernel bandwidth Returns ------- out : np.array Kernel values at each value of x
3.816212
2.82501
1.350867
''' Plots 1D function(s) over a given range. Parameters ---------- functions : [function] or function A single function, or a list of functions, to be plotted. bottom : float The lower limit of the domain to be plotted. top : float The upper limit of the domain to be...
def plotFuncs(functions,bottom,top,N=1000,legend_kwds = None)
Plots 1D function(s) over a given range. Parameters ---------- functions : [function] or function A single function, or a list of functions, to be plotted. bottom : float The lower limit of the domain to be plotted. top : float The upper limit of the domain to be plotted. ...
2.287618
1.445017
1.583108
''' Plots the first derivative of 1D function(s) over a given range. Parameters ---------- function : function A function or list of functions, the derivatives of which are to be plotted. bottom : float The lower limit of the domain to be plotted. top : float The upp...
def plotFuncsDer(functions,bottom,top,N=1000,legend_kwds = None)
Plots the first derivative of 1D function(s) over a given range. Parameters ---------- function : function A function or list of functions, the derivatives of which are to be plotted. bottom : float The lower limit of the domain to be plotted. top : float The upper limit of ...
2.517834
1.490149
1.689652
''' Runs regressions for the main tables of the StickyC paper in Stata and produces a LaTeX table with results for one "panel". Running in Stata allows production of the KP-statistic, for which there is currently no command in statsmodels.api. Parameters ---------- infile_name : str ...
def runStickyEregressionsInStata(infile_name,interval_size,meas_err,sticky,all_specs,stata_exe)
Runs regressions for the main tables of the StickyC paper in Stata and produces a LaTeX table with results for one "panel". Running in Stata allows production of the KP-statistic, for which there is currently no command in statsmodels.api. Parameters ---------- infile_name : str Name of tab...
5.826763
1.99077
2.926889
''' Calculate expected value of being born in each Markov state using the realizations of consumption for a history of many consumers. The histories should already be trimmed of the "burn in" periods. Parameters ---------- cLvlHist : np.array TxN array of consumption level history ...
def calcValueAtBirth(cLvlHist,BirthBool,PlvlHist,MrkvHist,DiscFac,CRRA)
Calculate expected value of being born in each Markov state using the realizations of consumption for a history of many consumers. The histories should already be trimmed of the "burn in" periods. Parameters ---------- cLvlHist : np.array TxN array of consumption level history for many age...
4.886784
2.786276
1.753876
''' Make a discrete preference shock structure for each period in the cycle for this agent type, storing them as attributes of self for use in the solution (and other methods). Parameters ---------- none Returns ------- none ''' ...
def updatePrefShockProcess(self)
Make a discrete preference shock structure for each period in the cycle for this agent type, storing them as attributes of self for use in the solution (and other methods). Parameters ---------- none Returns ------- none
6.875285
3.851059
1.785297
''' Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Get permanent and transitory income shocks Pr...
def getShocks(self)
Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None
4.48037
3.556561
1.259748
''' Calculates consumption for each consumer of this type using the consumption functions. Parameters ---------- None Returns ------- None ''' cNrmNow = np.zeros(self.AgentCount) + np.nan for t in range(self.T_cycle): ...
def getControls(self)
Calculates consumption for each consumer of this type using the consumption functions. Parameters ---------- None Returns ------- None
5.453211
3.175424
1.717317
''' Find endogenous interpolation points for each asset point and each discrete preference shock. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-period asset values th...
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow)
Find endogenous interpolation points for each asset point and each discrete preference shock. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-period asset values that yield the margina...
3.314473
2.106835
1.5732
''' Make a basic solution object with a consumption function and marginal value function (unconditional on the preference shock). Parameters ---------- cNrm : np.array Consumption points for interpolation. mNrm : np.array Corresponding mar...
def usePointsForInterpolation(self,cNrm,mNrm,interpolator)
Make a basic solution object with a consumption function and marginal value function (unconditional on the preference shock). Parameters ---------- cNrm : np.array Consumption points for interpolation. mNrm : np.array Corresponding market resource points ...
4.2291
2.865478
1.475879
''' Make the beginning-of-period value function (unconditional on the shock). Parameters ---------- solution : ConsumerSolution The solution to this single period problem, which must include the consumption function. Returns ------- ...
def makevFunc(self,solution)
Make the beginning-of-period value function (unconditional on the shock). Parameters ---------- solution : ConsumerSolution The solution to this single period problem, which must include the consumption function. Returns ------- vFuncNow : ValueF...
3.391237
2.49447
1.359502
''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity. Parameters ---------- which_agents : np.array(Bool) Boolean array of size...
def simBirth(self,which_agents)
Makes new consumers for the given indices. Slightly extends base method by also setting pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount ind...
6.676734
1.623109
4.113547
''' Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. Parameters ---------- None Returns ------- None ''' how_many_update = int(round(self.Upda...
def getUpdaters(self)
Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. Parameters ---------- None Returns ------- None
6.680993
2.507555
2.664345
''' Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but only consumers who update their macroeconomic beliefs this period incorporate all pre- viously unnoticed aggregate permanent shocks. Agents correctly observe the level of all real variab...
def getShocks(self)
Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but only consumers who update their macroeconomic beliefs this period incorporate all pre- viously unnoticed aggregate permanent shocks. Agents correctly observe the level of all real variables (market resource...
9.402569
4.783357
1.965684
''' Gets simulated consumers pLvl and mNrm for this period, but with the alteration that these represent perceived rather than actual values. Also calculates mLvlTrue, the true level of market resources that the individual has on hand. Parameters ---------- None...
def getStates(self)
Gets simulated consumers pLvl and mNrm for this period, but with the alteration that these represent perceived rather than actual values. Also calculates mLvlTrue, the true level of market resources that the individual has on hand. Parameters ---------- None Returns ...
6.897961
3.844877
1.794065
''' Slightly extends the base version of this method by recalculating aLvlNow to account for the consumer's (potential) misperception about their productivity level. Parameters ---------- None Returns ------- None ''' AggShockCons...
def getPostStates(self)
Slightly extends the base version of this method by recalculating aLvlNow to account for the consumer's (potential) misperception about their productivity level. Parameters ---------- None Returns ------- None
8.597907
2.725035
3.155155
''' Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. This version also updates perceptions of the Markov state. Parameters ---------- None Returns ------- ...
def getUpdaters(self)
Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. This version also updates perceptions of the Markov state. Parameters ---------- None Returns ------- None
11.946505
3.808974
3.13641
''' Calculates and returns the misperception of this period's shocks. Updaters have no misperception this period, while those who don't update don't see the value of the aggregate permanent shock and thus base their belief about aggregate growth on the last Markov state that the...
def getpLvlError(self)
Calculates and returns the misperception of this period's shocks. Updaters have no misperception this period, while those who don't update don't see the value of the aggregate permanent shock and thus base their belief about aggregate growth on the last Markov state that they actually observed,...
14.081739
1.788323
7.874273
''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents s...
def simBirth(self,which_agents)
Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". ...
7.039732
2.159678
3.25962
''' Calculates updated values of normalized market resources and permanent income level. Makes both perceived and true values. The representative consumer will act on the basis of his *perceived* normalized market resources. Parameters ---------- None R...
def getStates(self)
Calculates updated values of normalized market resources and permanent income level. Makes both perceived and true values. The representative consumer will act on the basis of his *perceived* normalized market resources. Parameters ---------- None Returns -----...
4.720739
2.848484
1.657282