HARK.core¶
High-level functions and classes for solving a wide variety of economic models. The “core” of HARK is a framework for “microeconomic” and “macroeconomic” models. A micro model concerns the dynamic optimization problem for some type of agents, where agents take the inputs to their problem as exogenous. A macro model adds an additional layer, endogenizing some of the inputs to the micro problem by finding a general equilibrium dynamic rule.
Functions
copy_module (target_path, …) |
Helper function for copy_module_to_local(). |
copy_module_to_local (full_module_name) |
This function contains simple code to copy a submodule to a location on your hard drive, as specified by you. |
distanceMetric (thing_A, thing_B) |
A “universal distance” metric that can be used as a default in many settings. |
main () |
|
print_helper () |
|
solveAgent (agent, verbose) |
Solve the dynamic model for one agent type. |
solveOneCycle (agent, solution_last) |
Solve one “cycle” of the dynamic model for one agent type. |
Classes
AgentType ([solution_terminal, cycles, …]) |
A superclass for economic agents in the HARK framework. |
HARKobject |
A superclass for object classes in HARK. |
Market ([agents, sow_vars, reap_vars, …]) |
A superclass to represent a central clearinghouse of information. |
Solution |
A superclass for representing the “solution” to a single period problem in a dynamic microeconomic model. |
-
class
HARK.core.
AgentType
(solution_terminal=None, cycles=1, time_flow=False, pseudo_terminal=True, tolerance=1e-06, seed=0, **kwds)¶ A superclass for economic agents in the HARK framework. Each model should specify its own subclass of AgentType, inheriting its methods and overwriting as necessary. Critically, every subclass of AgentType should define class- specific static values of the attributes time_vary and time_inv as lists of strings. Each element of time_vary is the name of a field in AgentSubType that varies over time in the model. Each element of time_inv is the name of a field in AgentSubType that is constant over time in the model. The string ‘solveOnePeriod’ should appear in exactly one of these lists, depending on whether the same solution method is used in all periods of the model.
Methods
__call__
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent, as a convenience. addToTimeInv
(self, \*params)Adds any number of parameters to time_inv for this instance. addToTimeVary
(self, \*params)Adds any number of parameters to time_vary for this instance. assignParameters
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent. checkElementsOfTimeVaryAreLists
(self)A method to check that elements of time_vary are lists. checkRestrictions
(self)A method to check that various restrictions are met for the model class. clearHistory
(self)Clears the histories of the attributes named in self.track_vars. delFromTimeInv
(self, \*params)Removes any number of parameters from time_inv for this instance. delFromTimeVary
(self, \*params)Removes any number of parameters from time_vary for this instance. 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. getAvg
(self, varname, \*\*kwds)Calculates the average of an attribute of this instance. getControls
(self)Gets values of control variables for the current period, probably by using current states. getMortality
(self)Simulates mortality or agent turnover according to some model-specific rules named simDeath and simBirth (methods of an AgentType subclass). getPostStates
(self)Gets values of post-decision state variables for the current period, probably by current states and controls and maybe market-level events or shock variables. getShocks
(self)Gets values of shock variables for the current period. getStates
(self)Gets values of state variables for the current period, probably by using post-decision states from last period, current period shocks, and maybe market-level events. initializeSim
(self)Prepares this AgentType for a new simulation. makeShockHistory
(self)Makes a pre-specified history of shocks for the simulation. postSolve
(self)A method that is run immediately after the model is solved, to finalize the solution in some way. preSolve
(self)A method that is run immediately before the model is solved, to check inputs or to prepare the terminal solution, perhaps. readShocks
(self)Reads values of shock variables for the current period from history arrays. resetRNG
(self)Reset the random number generator for this type. simBirth
(self, which_agents)Makes new agents for the simulation. simDeath
(self)Determines which agents in the current population “die” or should be replaced. simOnePeriod
(self)Simulates one period for this type. simulate
(self[, sim_periods])Simulates this agent type for a given number of periods (defaults to self.T_sim if no input). solve
(self[, verbose])Solve the model for this instance of an agent type by backward induction. timeFlip
(self)Reverse the flow of time for this instance. timeFwd
(self)Make time flow forward for this instance. timeReport
(self)Report to the user the direction that time is currently “flowing” for this instance. timeRev
(self)Make time flow backward for this instance. -
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
-
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
-
checkElementsOfTimeVaryAreLists
(self)¶ A method to check that elements of time_vary are lists.
-
checkRestrictions
(self)¶ A method to check that various restrictions are met for the model class.
-
clearHistory
(self)¶ Clears the histories of the attributes named in self.track_vars.
Parameters: - None
Returns: - None
-
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
-
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
-
getControls
(self)¶ Gets values of control variables for the current period, probably by using current states. Does nothing by default, but can be overwritten by subclasses of AgentType.
Parameters: - None
Returns: - None
-
getMortality
(self)¶ Simulates mortality or agent turnover according to some model-specific rules named simDeath and simBirth (methods of an AgentType subclass). simDeath takes no arguments and returns a Boolean array of size AgentCount, indicating which agents of this type have “died” and must be replaced. simBirth takes such a Boolean array as an argument and generates initial post-decision states for those agent indices.
Parameters: - None
Returns: - None
-
getPostStates
(self)¶ Gets values of post-decision state variables for the current period, probably by current states and controls and maybe market-level events or shock variables. Does nothing by default, but can be overwritten by subclasses of AgentType.
Parameters: - None
Returns: - None
-
getShocks
(self)¶ Gets values of shock variables for the current period. Does nothing by default, but can be overwritten by subclasses of AgentType.
Parameters: - None
Returns: - None
-
getStates
(self)¶ Gets values of state variables for the current period, probably by using post-decision states from last period, current period shocks, and maybe market-level events. Does nothing by default, but can be overwritten by subclasses of AgentType.
Parameters: - None
Returns: - None
-
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
-
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 stored in a T_sim x AgentCount array in an attribute of self named X_hist. Automatically sets self.read_shocks to True so that these pre-specified shocks are used for all subsequent calls to simulate().
Parameters: - None
Returns: - None
-
postSolve
(self)¶ A method that is run immediately after the model is solved, to finalize the solution in some way. Does nothing here.
Parameters: - none
Returns: - none
-
preSolve
(self)¶ A method that is run immediately before the model is solved, to check inputs or to prepare the terminal solution, perhaps.
Parameters: - none
Returns: - none
-
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 makeShockHistory() (or manually after storing a “handcrafted” shock history).
Parameters: - None
Returns: - None
-
resetRNG
(self)¶ Reset the random number generator for this type.
Parameters: - none
Returns: - none
-
simBirth
(self, which_agents)¶ Makes new agents for the simulation. Takes a boolean array as an input, indicating which agent indices are to be “born”. Does nothing by default, must be overwritten by a subclass.
Parameters: - which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns: - None
-
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 replacement events.
Parameters: - None
Returns: - who_dies : np.array
Boolean array of size self.AgentCount indicating which agents die and are replaced.
-
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.
Parameters: - None
Returns: - None
-
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
-
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 printed to screen.
Returns: - none
-
timeFlip
(self)¶ Reverse the flow of time for this instance.
Parameters: - none
Returns: - none
-
timeFwd
(self)¶ Make time flow forward for this instance.
Parameters: - none
Returns: - none
-
timeReport
(self)¶ Report to the user the direction that time is currently “flowing” for this instance. Only exists as a reminder of how time_flow works.
Parameters: - none
Returns: - none
-
timeRev
(self)¶ Make time flow backward for this instance.
Parameters: - none
Returns: - none
-
-
class
HARK.core.
HARKobject
¶ A superclass for object classes in HARK. Comes with two useful methods: a generic/universal distance method and an attribute assignment method.
Methods
__call__
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent, as a convenience. assignParameters
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent. 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. getAvg
(self, varname, \*\*kwds)Calculates the average of an attribute of this instance. -
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
-
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.
Returns: - (unnamed) : float
The distance between this object and another, using the “universal distance” metric.
-
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.
Returns: - avg : float or np.array
The average of this attribute. Might be an array if the axis keyword is passed.
-
-
class
HARK.core.
Market
(agents=[], sow_vars=[], reap_vars=[], const_vars=[], track_vars=[], dyn_vars=[], millRule=None, calcDynamics=None, act_T=1000, tolerance=1e-06)¶ A superclass to represent a central clearinghouse of information. Used for dynamic general equilibrium models to solve the “macroeconomic” model as a layer on top of the “microeconomic” models of one or more AgentTypes.
Methods
__call__
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent, as a convenience. assignParameters
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent. cultivate
(self)Has each AgentType in agents perform their marketAction method, using variables sown from the market (and maybe also “private” variables). 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. getAvg
(self, varname, \*\*kwds)Calculates the average of an attribute of this instance. 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. mill
(self)Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. reap
(self)Collects attributes named in reap_vars from each AgentType in the market, storing them in respectively named attributes of self. 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. 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. solveAgents
(self)Solves the microeconomic problem for all AgentTypes in this market. sow
(self)Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. store
(self)Record the current value of each variable X named in track_vars in an attribute named X_hist. 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. -
cultivate
(self)¶ Has each AgentType in agents perform their marketAction method, using variables sown from the market (and maybe also “private” variables). The marketAction method should store new results in attributes named in reap_vars to be reaped later.
Parameters: - none
Returns: - none
-
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
-
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
-
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
-
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
-
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
-
solveAgents
(self)¶ Solves the microeconomic problem for all AgentTypes in this market.
Parameters: - None
Returns: - None
-
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
-
store
(self)¶ Record the current value of each variable X named in track_vars in an attribute named X_hist.
Parameters: - none
Returns: - none
-
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 agents believe in and act on. Should have attributes named in dyn_vars.
-
-
class
HARK.core.
Solution
¶ A superclass for representing the “solution” to a single period problem in a dynamic microeconomic model.
NOTE: This can be deprecated now that HARKobject exists, but this requires replacing each instance of Solution with HARKobject in the other modules.
Methods
__call__
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent, as a convenience. assignParameters
(self, \*\*kwds)Assign an arbitrary number of attributes to this agent. 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. getAvg
(self, varname, \*\*kwds)Calculates the average of an attribute of this instance.
-
HARK.core.
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 pathname to this file’s directory
- my_module : string
String, name of the module to copy
Returns: - none
-
HARK.core.
copy_module_to_local
(full_module_name)¶ This function contains simple code to copy a submodule to a location on your hard drive, as specified by you. The purpose of this code is to provide users with a simple way to access a copy of code that usually sits deep in the Econ-ARK package structure, for purposes of tinkering and experimenting directly. This is meant to be a simple way to explore HARK code. To interact with the codebase under active development, please refer to the documentation under github.com/econ-ark/HARK/
To execute, do the following on the Python command line:
from HARK.core import copy_module_to_local copy_module_to_local(“FULL-HARK-MODULE-NAME-HERE”)For example, if you want SolvingMicroDSOPs you would enter
from HARK.core import copy_module_to_local copy_module_to_local(“HARK.SolvingMicroDSOPs”)
-
HARK.core.
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.
-
HARK.core.
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 whose dynamic problem is to be solved.
- verbose : boolean
If True, solution progress is printed to screen (when cycles != 1).
Returns: - solution : [Solution]
A list of solutions to the one period problems that the agent will encounter in his “lifetime”. Returns in reverse chronological order.
-
HARK.core.
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 dynamic problem is to be solved.
- solution_last : Solution
A representation of the solution of the period that comes after the end of the sequence of one period problems. This might be the term- inal period solution, a “pseudo terminal” solution, or simply the solution to the earliest period from the succeeding cycle.
Returns: - solution_cycle : [Solution]
A list of one period solutions for one “cycle” of the AgentType’s microeconomic model. Returns in reverse chronological order.