From 09195b13bae501b715b271d7decf2c5bb7c59f60 Mon Sep 17 00:00:00 2001 From: Mridul Seth Date: Sat, 9 Mar 2024 19:01:47 +0100 Subject: [PATCH 1/3] update pre-commit --- .pre-commit-config.yaml | 44 ++++++----------------------------------- ruff.toml | 3 +-- 2 files changed, 7 insertions(+), 40 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 30117c837..d2360c4e3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,49 +2,17 @@ exclude: Documentation/example_notebooks/ repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.1.4 + rev: v0.3.2 hooks: - id: ruff - types_or: [jupyter] + types_or: [ python, pyi, jupyter ] + args: + - --fix - id: ruff-format - args: [--check] - types_or: [jupyter] - - - repo: https://github.com/psf/black - rev: 23.7.0 - hooks: - - id: black - exclude: ^examples/ - - - repo: https://github.com/asottile/pyupgrade - rev: v3.10.1 - hooks: - - id: pyupgrade - args: ["--py38-plus"] - exclude: ^examples/ - - - repo: https://github.com/asottile/blacken-docs - rev: 1.15.0 - hooks: - - id: blacken-docs - exclude: ^examples/ - - - repo: https://github.com/pycqa/isort - rev: 5.12.0 - hooks: - - id: isort - name: isort (python) - args: ["--profile", "black", "--filter-files", "--skip", "__init__.py"] - exclude: ^examples/ - - - repo: https://github.com/pre-commit/mirrors-prettier - rev: v3.0.1 - hooks: - - id: prettier - exclude: ^examples/ + types_or: [ python, pyi, jupyter ] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace diff --git a/ruff.toml b/ruff.toml index 84d7322cf..cc569fbce 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,3 +1,2 @@ include = ["*.ipynb"] -# ignore F401 for now: https://github.com/astral-sh/ruff/issues/8354 -ignore = ["E731", "E721", "E402", "F841", "F821", "F405", "F403", "F401"] +lint.ignore = ["E731", "E721", "E402", "F841", "F821", "F405", "F403", "E722", "E741", "F811"] From 1bdfca2ac4929f13c4703c95fc533b19d2a9aa3d Mon Sep 17 00:00:00 2001 From: Mridul Seth Date: Sat, 9 Mar 2024 19:02:13 +0100 Subject: [PATCH 2/3] run linter --- HARK/ConsumptionSaving/ConsAggShockModel.py | 1 + .../ConsGenIncProcessModel.py | 1 + HARK/ConsumptionSaving/ConsIndShockModel.py | 9 +- HARK/ConsumptionSaving/ConsLabeledModel.py | 4 +- HARK/ConsumptionSaving/ConsLaborModel.py | 20 +- HARK/ConsumptionSaving/ConsMarkovModel.py | 8 +- HARK/ConsumptionSaving/ConsMedModel.py | 1 + .../ConsPortfolioFrameModel.py | 2 +- HARK/ConsumptionSaving/ConsPortfolioModel.py | 1 + HARK/ConsumptionSaving/ConsPrefShockModel.py | 1 + HARK/ConsumptionSaving/ConsRepAgentModel.py | 3 +- HARK/ConsumptionSaving/ConsRiskyAssetModel.py | 1 + .../ConsRiskyContribModel.py | 9 +- .../TractableBufferStockModel.py | 7 +- .../tests/test_ConsAggShockModel.py | 5 +- .../tests/test_ConsMarkovModel.py | 6 +- .../tests/test_IndShockConsumerType.py | 10 +- .../tests/test_IndShockConsumerTypeFast.py | 6 +- .../tests/test_SmallOpenEconomy.py | 6 +- .../tests/test_modelInits.py | 8 +- .../tests/test_modelcomparisons.py | 2 +- HARK/core.py | 39 +-- HARK/dcegm.py | 1 + HARK/distribution.py | 4 +- HARK/estimation.py | 1 + HARK/frame.py | 15 +- HARK/interpolation.py | 1 + HARK/models/fisher.py | 1 - HARK/parallel.py | 2 +- HARK/simulation/monte_carlo.py | 6 +- HARK/simulation/test_monte_carlo.py | 1 + HARK/tests/OpenCLtest.py | 6 +- HARK/tests/test_HARKutilities.py | 1 + HARK/tests/test_core.py | 1 + HARK/tests/test_dcegm.py | 1 + HARK/tests/test_discrete.py | 1 + HARK/tests/test_frame.py | 1 + HARK/tests/test_interpolation.py | 1 + HARK/tests/test_simulation.py | 3 - HARK/utilities.py | 10 +- HARK/validators.py | 1 + .../example_ConsMarkovModel.ipynb | 12 +- examples/Journeys/JourneyPhDparam.py | 264 ++++++++++-------- examples/LifecycleModel/LifecycleModel.ipynb | 36 +-- ...eneric Monte Carlo Perfect Foresight.ipynb | 1 - 45 files changed, 275 insertions(+), 246 deletions(-) diff --git a/HARK/ConsumptionSaving/ConsAggShockModel.py b/HARK/ConsumptionSaving/ConsAggShockModel.py index 2d14f81c7..5827a26b9 100644 --- a/HARK/ConsumptionSaving/ConsAggShockModel.py +++ b/HARK/ConsumptionSaving/ConsAggShockModel.py @@ -4,6 +4,7 @@ basic solver. Also includes a subclass of Market called CobbDouglas economy, used for solving "macroeconomic" models with aggregate shocks. """ + from copy import deepcopy import numpy as np diff --git a/HARK/ConsumptionSaving/ConsGenIncProcessModel.py b/HARK/ConsumptionSaving/ConsGenIncProcessModel.py index b586299ff..31083d011 100644 --- a/HARK/ConsumptionSaving/ConsGenIncProcessModel.py +++ b/HARK/ConsumptionSaving/ConsGenIncProcessModel.py @@ -4,6 +4,7 @@ ConsIndShockModel by explicitly tracking persistent income as a state variable, and allows (log) persistent income to follow an AR1 process rather than random walk. """ + import numpy as np from HARK import AgentType, make_one_period_oo_solver diff --git a/HARK/ConsumptionSaving/ConsIndShockModel.py b/HARK/ConsumptionSaving/ConsIndShockModel.py index a41724c7e..b1f1e015f 100644 --- a/HARK/ConsumptionSaving/ConsIndShockModel.py +++ b/HARK/ConsumptionSaving/ConsIndShockModel.py @@ -46,7 +46,6 @@ ) from HARK.interpolation import CubicHermiteInterp as CubicInterp from HARK.interpolation import ( - CubicInterp, LinearInterp, LowerEnvelope, MargMargValueFuncCRRA, @@ -2569,9 +2568,7 @@ def calc_transition_matrix(self, shk_dstn=None): if not hasattr(shk_dstn, "pmv"): shk_dstn = self.IncShkDstn - self.cPol_Grid = ( - [] - ) # List of consumption policy grids for each period in T_cycle + self.cPol_Grid = [] # List of consumption policy grids for each period in T_cycle self.aPol_Grid = [] # List of asset policy grids for each period in T_cycle self.tran_matrix = [] # List of transition matrices @@ -2952,9 +2949,7 @@ def J_from_F(F): else: peturbed_list = [getattr(self, shk_param) + dx] + ( params["T_cycle"] - 1 - ) * [ - getattr(self, shk_param) - ] # Sequence of interest rates the agent + ) * [getattr(self, shk_param)] # Sequence of interest rates the agent setattr(ZerothColAgent, shk_param, peturbed_list) # Set attribute to agent diff --git a/HARK/ConsumptionSaving/ConsLabeledModel.py b/HARK/ConsumptionSaving/ConsLabeledModel.py index 585389b0e..ca49deea6 100644 --- a/HARK/ConsumptionSaving/ConsLabeledModel.py +++ b/HARK/ConsumptionSaving/ConsLabeledModel.py @@ -897,7 +897,9 @@ class ConsRiskyAssetLabeledSolver(ConsIndShockLabeledSolver): """ solution_next: ConsumerSolutionLabeled # solution to next period's problem - ShockDstn: DiscreteDistributionLabeled # distribution of shocks to income and returns + ShockDstn: ( + DiscreteDistributionLabeled # distribution of shocks to income and returns + ) LivPrb: float # survival probability DiscFac: float # intertemporal discount factor CRRA: float # coefficient of relative risk aversion diff --git a/HARK/ConsumptionSaving/ConsLaborModel.py b/HARK/ConsumptionSaving/ConsLaborModel.py index 3a47115f4..7ffbde762 100644 --- a/HARK/ConsumptionSaving/ConsLaborModel.py +++ b/HARK/ConsumptionSaving/ConsLaborModel.py @@ -8,6 +8,7 @@ productivity shocks. Agents choose their quantities of labor and consumption after observing both of these shocks, so the transitory shock is a state variable. """ + import sys from copy import copy @@ -343,7 +344,6 @@ def uPinv(X): class LaborIntMargConsumerType(IndShockConsumerType): - """ A class representing agents who make a decision each period about how much to consume vs save and how much labor to supply (as a fraction of their time). @@ -737,13 +737,13 @@ def plot_LbrFunc(self, t, bMin=None, bMax=None, ShkSet=None): init_labor_intensive["LbrCostCoeffs"] = [-1.0] init_labor_intensive["WageRte"] = [1.0] init_labor_intensive["IncUnemp"] = 0.0 -init_labor_intensive[ - "TranShkCount" -] = 15 # Crank up permanent shock count - Number of points in discrete approximation to transitory income shocks +init_labor_intensive["TranShkCount"] = ( + 15 # Crank up permanent shock count - Number of points in discrete approximation to transitory income shocks +) init_labor_intensive["PermShkCount"] = 16 # Crank up permanent shock count -init_labor_intensive[ - "aXtraCount" -] = 200 # May be important to have a larger number of gridpoints (than 48 initially) +init_labor_intensive["aXtraCount"] = ( + 200 # May be important to have a larger number of gridpoints (than 48 initially) +) init_labor_intensive["aXtraMax"] = 80.0 init_labor_intensive["BoroCnstArt"] = None @@ -791,6 +791,6 @@ def plot_LbrFunc(self, t, bMin=None, bMax=None, ShkSet=None): init_labor_lifecycle["LbrCostCoeffs"] = np.array([-2.0, 0.4]) init_labor_lifecycle["T_cycle"] = 10 # init_labor_lifecycle['T_retire'] = 7 # IndexError at line 774 in interpolation.py. -init_labor_lifecycle[ - "T_age" -] = 11 # Make sure that old people die at terminal age and don't turn into newborns! +init_labor_lifecycle["T_age"] = ( + 11 # Make sure that old people die at terminal age and don't turn into newborns! +) diff --git a/HARK/ConsumptionSaving/ConsMarkovModel.py b/HARK/ConsumptionSaving/ConsMarkovModel.py index 958220fdf..2b096fb0b 100644 --- a/HARK/ConsumptionSaving/ConsMarkovModel.py +++ b/HARK/ConsumptionSaving/ConsMarkovModel.py @@ -470,9 +470,7 @@ def calc_EndOfPrdvP(self): np.logical_and(self.possible_transitions[:, j], which_states) ): # only consider a future state if one of the relevant states could transition to it EndOfPrdvP_all[j, :] = self.EndOfPrdvPfunc_list[j](aGrid) - if ( - self.CubicBool - ): # Add conditional end-of-period (marginal) marginal value to the arrays + if self.CubicBool: # Add conditional end-of-period (marginal) marginal value to the arrays EndOfPrdvPP_all[j, :] = self.EndOfPrdvPfunc_list[j].derivativeX( aGrid ) @@ -606,9 +604,7 @@ def make_solution(self, cNrm, mNrm): solution_cond = ConsumerSolution( cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=self.mNrmMinNow ) - if ( - self.CubicBool - ): # Add the state-conditional marginal marginal value function (if desired) + if self.CubicBool: # Add the state-conditional marginal marginal value function (if desired) solution_cond = self.add_vPPfunc(solution_cond) # Add the current-state-conditional solution to the overall period solution diff --git a/HARK/ConsumptionSaving/ConsMedModel.py b/HARK/ConsumptionSaving/ConsMedModel.py index 0c3fb8912..c32c00bd8 100644 --- a/HARK/ConsumptionSaving/ConsMedModel.py +++ b/HARK/ConsumptionSaving/ConsMedModel.py @@ -1,6 +1,7 @@ """ Consumption-saving models that also include medical spending. """ + from copy import deepcopy import numpy as np diff --git a/HARK/ConsumptionSaving/ConsPortfolioFrameModel.py b/HARK/ConsumptionSaving/ConsPortfolioFrameModel.py index 249462fcc..7fa32d95e 100644 --- a/HARK/ConsumptionSaving/ConsPortfolioFrameModel.py +++ b/HARK/ConsumptionSaving/ConsPortfolioFrameModel.py @@ -161,7 +161,7 @@ def birth_pLvlNow(self, N): { "mean": init_portfolio["RiskyAvg"], "std": init_portfolio["RiskyStd"], - } + }, # seed=self.RNG.integers(0, 2 ** 31 - 1) : TODO: Seed logic ).discretize(init_portfolio["RiskyCount"], method="equiprobable"), aggregate=True, diff --git a/HARK/ConsumptionSaving/ConsPortfolioModel.py b/HARK/ConsumptionSaving/ConsPortfolioModel.py index 731f603de..9778d0f99 100644 --- a/HARK/ConsumptionSaving/ConsPortfolioModel.py +++ b/HARK/ConsumptionSaving/ConsPortfolioModel.py @@ -3,6 +3,7 @@ agents who must allocate their resources among consumption, saving in a risk-free asset (with a low return), and saving in a risky asset (with higher average return). """ + from copy import deepcopy import numpy as np diff --git a/HARK/ConsumptionSaving/ConsPrefShockModel.py b/HARK/ConsumptionSaving/ConsPrefShockModel.py index 4dcb61992..fcedbe2f3 100644 --- a/HARK/ConsumptionSaving/ConsPrefShockModel.py +++ b/HARK/ConsumptionSaving/ConsPrefShockModel.py @@ -6,6 +6,7 @@ 2) A combination of (1) and ConsKinkedR, demonstrating how to construct a new model by inheriting from multiple classes. """ + import numpy as np from HARK import make_one_period_oo_solver diff --git a/HARK/ConsumptionSaving/ConsRepAgentModel.py b/HARK/ConsumptionSaving/ConsRepAgentModel.py index e0c9f8ca9..c365b7c6e 100644 --- a/HARK/ConsumptionSaving/ConsRepAgentModel.py +++ b/HARK/ConsumptionSaving/ConsRepAgentModel.py @@ -4,6 +4,7 @@ take a heterogeneous agents approach. In RA models, all attributes are either time invariant or exist on a short cycle; models must be infinite horizon. """ + import numpy as np from HARK.ConsumptionSaving.ConsIndShockModel import ( @@ -12,7 +13,7 @@ init_idiosyncratic_shocks, ) from HARK.ConsumptionSaving.ConsMarkovModel import MarkovConsumerType -from HARK.distribution import MarkovProcess, Uniform +from HARK.distribution import MarkovProcess from HARK.interpolation import LinearInterp, MargValueFuncCRRA __all__ = ["RepAgentConsumerType", "RepAgentMarkovConsumerType"] diff --git a/HARK/ConsumptionSaving/ConsRiskyAssetModel.py b/HARK/ConsumptionSaving/ConsRiskyAssetModel.py index a18fce177..e02a8b0fc 100644 --- a/HARK/ConsumptionSaving/ConsRiskyAssetModel.py +++ b/HARK/ConsumptionSaving/ConsRiskyAssetModel.py @@ -5,6 +5,7 @@ simulation methods. It is meant as a container of methods for dealing with risky assets that will be useful to models what will inherit from it. """ + from dataclasses import dataclass import numpy as np diff --git a/HARK/ConsumptionSaving/ConsRiskyContribModel.py b/HARK/ConsumptionSaving/ConsRiskyContribModel.py index 368aea69d..0baa243bb 100644 --- a/HARK/ConsumptionSaving/ConsRiskyContribModel.py +++ b/HARK/ConsumptionSaving/ConsRiskyContribModel.py @@ -23,6 +23,7 @@ } """ + from copy import deepcopy import numpy as np @@ -425,9 +426,9 @@ def sim_one_period(self): # Advance time for all agents self.t_age = self.t_age + 1 # Age all consumers by one period self.t_cycle = self.t_cycle + 1 # Age all consumers within their cycle - self.t_cycle[ - self.t_cycle == self.T_cycle - ] = 0 # Resetting to zero for those who have reached the end + self.t_cycle[self.t_cycle == self.T_cycle] = ( + 0 # Resetting to zero for those who have reached the end + ) def get_states_Reb(self): """ @@ -513,7 +514,7 @@ def get_states_Sha(self): # Post-states are assets after rebalancing - if not "tau" in self.time_vary: + if "tau" not in self.time_vary: mNrmTilde, nNrmTilde = rebalance_assets( self.controls["dfrac"], self.state_now["mNrm"], diff --git a/HARK/ConsumptionSaving/TractableBufferStockModel.py b/HARK/ConsumptionSaving/TractableBufferStockModel.py index f1e563beb..94846dc70 100644 --- a/HARK/ConsumptionSaving/TractableBufferStockModel.py +++ b/HARK/ConsumptionSaving/TractableBufferStockModel.py @@ -20,6 +20,7 @@ Despite the non-standard solution method, the iterative process can be embedded in the HARK framework, as shown below. """ + from copy import copy import numpy as np @@ -621,9 +622,9 @@ def sim_birth(self, which_agents): self.shocks["eStateNow"][which_agents] = 1.0 # How many periods since each agent was born self.t_age[which_agents] = 0 - self.t_cycle[ - which_agents - ] = 0 # Which period of the cycle each agent is currently in + self.t_cycle[which_agents] = ( + 0 # Which period of the cycle each agent is currently in + ) return None def sim_death(self): diff --git a/HARK/ConsumptionSaving/tests/test_ConsAggShockModel.py b/HARK/ConsumptionSaving/tests/test_ConsAggShockModel.py index 0bce3ffbc..31d44393e 100644 --- a/HARK/ConsumptionSaving/tests/test_ConsAggShockModel.py +++ b/HARK/ConsumptionSaving/tests/test_ConsAggShockModel.py @@ -23,7 +23,10 @@ def setUp(self): # Make agents heterogeneous in their discount factor self.agents = distribute_params( - agent, "DiscFac", 3, Uniform(bot=0.90, top=0.94) # Impatient agents + agent, + "DiscFac", + 3, + Uniform(bot=0.90, top=0.94), # Impatient agents ) # Make an economy with those agents living in it diff --git a/HARK/ConsumptionSaving/tests/test_ConsMarkovModel.py b/HARK/ConsumptionSaving/tests/test_ConsMarkovModel.py index b557f81ae..ce435bccb 100644 --- a/HARK/ConsumptionSaving/tests/test_ConsMarkovModel.py +++ b/HARK/ConsumptionSaving/tests/test_ConsMarkovModel.py @@ -56,9 +56,9 @@ def setUp(self): init_serial_unemployment = copy(init_idiosyncratic_shocks) init_serial_unemployment["MrkvArray"] = [MrkvArray] - init_serial_unemployment[ - "UnempPrb" - ] = 0.0 # to make income distribution when employed + init_serial_unemployment["UnempPrb"] = ( + 0.0 # to make income distribution when employed + ) init_serial_unemployment["global_markov"] = False self.model = MarkovConsumerType(**init_serial_unemployment) self.model.cycles = 0 diff --git a/HARK/ConsumptionSaving/tests/test_IndShockConsumerType.py b/HARK/ConsumptionSaving/tests/test_IndShockConsumerType.py index 45a202259..f7f0caaa1 100644 --- a/HARK/ConsumptionSaving/tests/test_IndShockConsumerType.py +++ b/HARK/ConsumptionSaving/tests/test_IndShockConsumerType.py @@ -169,9 +169,9 @@ def test_GICRawFails(self): GICRaw_fail_dictionary = dict(self.base_params) GICRaw_fail_dictionary["Rfree"] = 1.08 GICRaw_fail_dictionary["PermGroFac"] = [1.00] - GICRaw_fail_dictionary[ - "cycles" - ] = 0 # cycles=0 makes this an infinite horizon consumer + GICRaw_fail_dictionary["cycles"] = ( + 0 # cycles=0 makes this an infinite horizon consumer + ) GICRawFailExample = IndShockConsumerType(**GICRaw_fail_dictionary) @@ -896,9 +896,7 @@ def test_calc_tran_matrix(self): asset = example1.aPol_Grid # Normalized Asset Policy Grid example1.calc_ergodic_dist() - vecDstn = ( - example1.vec_erg_dstn - ) # Distribution of market resources and permanent income as a vector (m*p)x1 vector where + vecDstn = example1.vec_erg_dstn # Distribution of market resources and permanent income as a vector (m*p)x1 vector where # Compute Aggregate Consumption and Aggregate Assets gridc = np.zeros((len(c), len(p))) diff --git a/HARK/ConsumptionSaving/tests/test_IndShockConsumerTypeFast.py b/HARK/ConsumptionSaving/tests/test_IndShockConsumerTypeFast.py index 5bebe1ba7..130cf2177 100644 --- a/HARK/ConsumptionSaving/tests/test_IndShockConsumerTypeFast.py +++ b/HARK/ConsumptionSaving/tests/test_IndShockConsumerTypeFast.py @@ -127,9 +127,9 @@ def test_GICRawFails(self): GICRaw_fail_dictionary = dict(self.base_params) GICRaw_fail_dictionary["Rfree"] = 1.08 GICRaw_fail_dictionary["PermGroFac"] = [1.00] - GICRaw_fail_dictionary[ - "cycles" - ] = 0 # cycles=0 makes this an infinite horizon consumer + GICRaw_fail_dictionary["cycles"] = ( + 0 # cycles=0 makes this an infinite horizon consumer + ) GICRawFailExample = IndShockConsumerTypeFast(**GICRaw_fail_dictionary) diff --git a/HARK/ConsumptionSaving/tests/test_SmallOpenEconomy.py b/HARK/ConsumptionSaving/tests/test_SmallOpenEconomy.py index aee2d3860..9aeea94a0 100644 --- a/HARK/ConsumptionSaving/tests/test_SmallOpenEconomy.py +++ b/HARK/ConsumptionSaving/tests/test_SmallOpenEconomy.py @@ -1,7 +1,6 @@ import copy import unittest -import numpy as np from HARK import distribute_params from HARK.ConsumptionSaving.ConsAggShockModel import ( @@ -20,7 +19,10 @@ def test_small_open(self): # Make agents heterogeneous in their discount factor agents = distribute_params( - agent, "DiscFac", 3, Uniform(bot=0.90, top=0.94) # Impatient agents + agent, + "DiscFac", + 3, + Uniform(bot=0.90, top=0.94), # Impatient agents ) # Make an economy with those agents living in it diff --git a/HARK/ConsumptionSaving/tests/test_modelInits.py b/HARK/ConsumptionSaving/tests/test_modelInits.py index 032f40da5..616e789ec 100644 --- a/HARK/ConsumptionSaving/tests/test_modelInits.py +++ b/HARK/ConsumptionSaving/tests/test_modelInits.py @@ -2,7 +2,6 @@ This file tests whether HARK's models are initialized correctly. """ - # Bring in modules we need import unittest from copy import copy @@ -18,7 +17,6 @@ init_lifecycle, ) from HARK.ConsumptionSaving.ConsMarkovModel import MarkovConsumerType -from HARK.utilities import plot_funcs, plot_funcs_der class testInitialization(unittest.TestCase): @@ -92,9 +90,9 @@ def test_MarkovConsumerType(self): # Make a consumer with serially correlated unemployment, subject to boom and bust cycles init_serial_unemployment = copy(init_idiosyncratic_shocks) init_serial_unemployment["MrkvArray"] = [MrkvArray] - init_serial_unemployment[ - "UnempPrb" - ] = 0.0 # to make income distribution when employed + init_serial_unemployment["UnempPrb"] = ( + 0.0 # to make income distribution when employed + ) init_serial_unemployment["global_markov"] = False SerialUnemploymentExample = MarkovConsumerType(**init_serial_unemployment) except: diff --git a/HARK/ConsumptionSaving/tests/test_modelcomparisons.py b/HARK/ConsumptionSaving/tests/test_modelcomparisons.py index 8c8dba980..b1a1cb78a 100644 --- a/HARK/ConsumptionSaving/tests/test_modelcomparisons.py +++ b/HARK/ConsumptionSaving/tests/test_modelcomparisons.py @@ -19,7 +19,7 @@ ) from HARK.ConsumptionSaving.ConsMarkovModel import MarkovConsumerType from HARK.ConsumptionSaving.TractableBufferStockModel import TractableConsumerType -from HARK.distribution import DiscreteDistribution, DiscreteDistributionLabeled +from HARK.distribution import DiscreteDistributionLabeled class Compare_PerfectForesight_and_Infinite(unittest.TestCase): diff --git a/HARK/core.py b/HARK/core.py index bae538f1a..2f292a870 100644 --- a/HARK/core.py +++ b/HARK/core.py @@ -6,15 +6,16 @@ model adds an additional layer, endogenizing some of the inputs to the micro problem by finding a general equilibrium dynamic rule. """ + # Set logging and define basic functions # Set logging and define basic functions import logging import sys -from collections import defaultdict, namedtuple +from collections import namedtuple from copy import copy, deepcopy from dataclasses import dataclass, field from time import time -from typing import Any, Dict, List, NewType, Optional, Union +from typing import Any, Dict, List, Optional, Union from warnings import warn import numpy as np @@ -707,9 +708,9 @@ def sim_one_period(self): # Advance time for all agents self.t_age = self.t_age + 1 # Age all consumers by one period self.t_cycle = self.t_cycle + 1 # Age all consumers within their cycle - self.t_cycle[ - self.t_cycle == self.T_cycle - ] = 0 # Resetting to zero for those who have reached the end + self.t_cycle[self.t_cycle == self.T_cycle] = ( + 0 # Resetting to zero for those who have reached the end + ) def make_shock_history(self): """ @@ -779,13 +780,13 @@ def make_shock_history(self): and len(self.state_now[var_name]) == self.AgentCount ) if idio: - self.newborn_init_history[var_name][ - t, self.who_dies - ] = self.state_now[var_name][self.who_dies] + self.newborn_init_history[var_name][t, self.who_dies] = ( + self.state_now[var_name][self.who_dies] + ) else: - self.newborn_init_history[var_name][ - t, self.who_dies - ] = self.state_now[var_name] + self.newborn_init_history[var_name][t, self.who_dies] = ( + self.state_now[var_name] + ) # Other Shocks self.get_shocks() @@ -795,9 +796,9 @@ def make_shock_history(self): self.t_sim += 1 self.t_age = self.t_age + 1 # Age all consumers by one period self.t_cycle = self.t_cycle + 1 # Age all consumers within their cycle - self.t_cycle[ - self.t_cycle == self.T_cycle - ] = 0 # Resetting to zero for those who have reached the end + self.t_cycle[self.t_cycle == self.T_cycle] = ( + 0 # Resetting to zero for those who have reached the end + ) # Flag that shocks can be read rather than simulated self.read_shocks = True @@ -831,11 +832,11 @@ def get_mortality(self): and len(self.state_now[var_name]) == self.AgentCount ) if idio: - self.state_now[var_name][ - who_dies - ] = self.newborn_init_history[var_name][ - self.t_sim, who_dies - ] + self.state_now[var_name][who_dies] = ( + self.newborn_init_history[ + var_name + ][self.t_sim, who_dies] + ) else: warn( diff --git a/HARK/dcegm.py b/HARK/dcegm.py index 131f96c35..ba0d7c060 100644 --- a/HARK/dcegm.py +++ b/HARK/dcegm.py @@ -6,6 +6,7 @@ Example can be found in https://github.com/econ-ark/DemARK/blob/master/notebooks/DCEGM-Upper-Envelope.ipynb """ + import numpy as np from interpolation import interp from numba import njit diff --git a/HARK/distribution.py b/HARK/distribution.py index 3b5ac0463..8a1be8882 100644 --- a/HARK/distribution.py +++ b/HARK/distribution.py @@ -407,9 +407,7 @@ def _approx_equiprobable( lower_CDF_vals = [0.0] if lo_cut > 0.0: for x in range(tail_N - 1, -1, -1): - lower_CDF_vals.append( - lower_CDF_vals[-1] + lo_cut * scale**x / mag - ) + lower_CDF_vals.append(lower_CDF_vals[-1] + lo_cut * scale**x / mag) upper_CDF_vals = [hi_cut] if hi_cut < 1.0: for x in range(tail_N): diff --git a/HARK/estimation.py b/HARK/estimation.py index dd58fc342..4b4c84a42 100644 --- a/HARK/estimation.py +++ b/HARK/estimation.py @@ -2,6 +2,7 @@ Functions for estimating structural models, including optimization methods and bootstrapping tools. """ + import csv import multiprocessing import warnings diff --git a/HARK/frame.py b/HARK/frame.py index 143e96ca2..968df180e 100644 --- a/HARK/frame.py +++ b/HARK/frame.py @@ -1,14 +1,13 @@ import copy import itertools from collections import OrderedDict -from sre_constants import SRE_FLAG_ASCII import matplotlib.pyplot as plt import networkx as nx import numpy as np from HARK import AgentType, Model -from HARK.distribution import Distribution, TimeVaryingDiscreteDistribution +from HARK.distribution import Distribution class Frame: @@ -537,9 +536,9 @@ def sim_one_period(self): # Advance time for all agents self.t_age = self.t_age + 1 # Age all consumers by one period self.t_cycle = self.t_cycle + 1 # Age all consumers within their cycle - self.t_cycle[ - self.t_cycle == self.T_cycle - ] = 0 # Resetting to zero for those who have reached the end + self.t_cycle[self.t_cycle == self.T_cycle] = ( + 0 # Resetting to zero for those who have reached the end + ) def sim_birth(self, which_agents): """ @@ -584,9 +583,9 @@ def sim_birth(self, which_agents): # from ConsIndShockModel. Needed??? self.t_age[which_agents] = 0 # How many periods since each agent was born - self.t_cycle[ - which_agents - ] = 0 # Which period of the cycle each agent is currently in + self.t_cycle[which_agents] = ( + 0 # Which period of the cycle each agent is currently in + ) ## simplest version of this. diff --git a/HARK/interpolation.py b/HARK/interpolation.py index 4ba7021aa..62b08b0e2 100644 --- a/HARK/interpolation.py +++ b/HARK/interpolation.py @@ -6,6 +6,7 @@ convergence. The interpolator classes currently in this module inherit their distance method from MetricObject. """ + import warnings from copy import deepcopy diff --git a/HARK/models/fisher.py b/HARK/models/fisher.py index bc5aa83fd..b676963b7 100644 --- a/HARK/models/fisher.py +++ b/HARK/models/fisher.py @@ -2,7 +2,6 @@ A model file for a Fisher 2-period consumption problem. """ -from HARK.distribution import Bernoulli from HARK.model import Control # This way of distributing parameters across the scope is clunky diff --git a/HARK/parallel.py b/HARK/parallel.py index 61df0d596..0bde05d08 100644 --- a/HARK/parallel.py +++ b/HARK/parallel.py @@ -1,5 +1,5 @@ import multiprocessing -from typing import Any, List, Type +from typing import Any, List from joblib import Parallel, delayed diff --git a/HARK/simulation/monte_carlo.py b/HARK/simulation/monte_carlo.py index 13a3e34af..ecfd986ba 100644 --- a/HARK/simulation/monte_carlo.py +++ b/HARK/simulation/monte_carlo.py @@ -386,9 +386,9 @@ def sim_birth(self, which_agents): if np.sum(which_agents) > 0: for varn in initial_vals: self.vars_now[varn][which_agents] = initial_vals[varn] - self.newborn_init_history[varn][ - self.t_sim, which_agents - ] = initial_vals[varn] + self.newborn_init_history[varn][self.t_sim, which_agents] = ( + initial_vals[varn] + ) self.t_age[which_agents] = 0 self.t_cycle[which_agents] = 0 diff --git a/HARK/simulation/test_monte_carlo.py b/HARK/simulation/test_monte_carlo.py index bb1620c3c..ec0a183db 100644 --- a/HARK/simulation/test_monte_carlo.py +++ b/HARK/simulation/test_monte_carlo.py @@ -1,6 +1,7 @@ """ This file implements unit tests for the Monte Carlo simulation module """ + import unittest from HARK.distribution import Bernoulli, IndexDistribution, MeanOneLogNormal diff --git a/HARK/tests/OpenCLtest.py b/HARK/tests/OpenCLtest.py index 665d508b3..78fccd458 100644 --- a/HARK/tests/OpenCLtest.py +++ b/HARK/tests/OpenCLtest.py @@ -7,9 +7,9 @@ import numpy as np import opencl4py as cl -os.environ[ - "PYOPENCL_CTX" -] = "0:0" # This is where you set which devices are in the context +os.environ["PYOPENCL_CTX"] = ( + "0:0" # This is where you set which devices are in the context +) # EVERY machine will have a device 0:0 from time import time diff --git a/HARK/tests/test_HARKutilities.py b/HARK/tests/test_HARKutilities.py index a21ed3712..37873faf1 100644 --- a/HARK/tests/test_HARKutilities.py +++ b/HARK/tests/test_HARKutilities.py @@ -1,6 +1,7 @@ """ This file implements unit tests to check HARK/utilities.py """ + # Bring in modules we need import unittest from types import SimpleNamespace diff --git a/HARK/tests/test_core.py b/HARK/tests/test_core.py index 8dacf071b..c105648ab 100644 --- a/HARK/tests/test_core.py +++ b/HARK/tests/test_core.py @@ -1,6 +1,7 @@ """ This file implements unit tests for core HARK functionality. """ + import unittest import numpy as np diff --git a/HARK/tests/test_dcegm.py b/HARK/tests/test_dcegm.py index 7632c4fae..9b93d7262 100644 --- a/HARK/tests/test_dcegm.py +++ b/HARK/tests/test_dcegm.py @@ -1,6 +1,7 @@ """ This file implements unit tests to check discrete choice functions """ + # Bring in modules we need import unittest diff --git a/HARK/tests/test_discrete.py b/HARK/tests/test_discrete.py index 8ee9afec7..eb987177d 100644 --- a/HARK/tests/test_discrete.py +++ b/HARK/tests/test_discrete.py @@ -1,6 +1,7 @@ """ This file implements unit tests to check discrete choice functions """ + # Bring in modules we need import unittest diff --git a/HARK/tests/test_frame.py b/HARK/tests/test_frame.py index fbe5169b5..50110759c 100644 --- a/HARK/tests/test_frame.py +++ b/HARK/tests/test_frame.py @@ -1,6 +1,7 @@ """ This file implements unit tests for the frame.py module. """ + import unittest from HARK.frame import BackwardFrameReference, ForwardFrameReference, Frame, FrameModel diff --git a/HARK/tests/test_interpolation.py b/HARK/tests/test_interpolation.py index ad0008330..200b49d0e 100644 --- a/HARK/tests/test_interpolation.py +++ b/HARK/tests/test_interpolation.py @@ -1,6 +1,7 @@ """ This file implements unit tests for interpolation methods """ + import unittest import numpy as np diff --git a/HARK/tests/test_simulation.py b/HARK/tests/test_simulation.py index fc321956b..e69de29bb 100644 --- a/HARK/tests/test_simulation.py +++ b/HARK/tests/test_simulation.py @@ -1,3 +0,0 @@ -import unittest - -import HARK.simulation as simulation diff --git a/HARK/utilities.py b/HARK/utilities.py index 96181fbb9..f44aede12 100644 --- a/HARK/utilities.py +++ b/HARK/utilities.py @@ -3,6 +3,7 @@ continuous distributions with discrete ones, utility functions (and their derivatives), manipulation of discrete distributions, and basic plotting tools. """ + import cProfile import functools import os @@ -574,9 +575,7 @@ def jump_to_grid_2D(m_vals, perm_vals, probs, dist_mGrid, dist_pGrid): # For instance, if mval lies between dist_mGrid[4] and dist_mGrid[5] it is in bin 4 (would be 5 if 1 was not subtracted in the previous line). mIndex[ m_vals <= dist_mGrid[0] - ] = ( - -1 - ) # if the value is less than the smallest value on dist_mGrid assign it an index of -1 + ] = -1 # if the value is less than the smallest value on dist_mGrid assign it an index of -1 mIndex[m_vals >= dist_mGrid[-1]] = ( len(dist_mGrid) - 1 ) # if value if greater than largest value on dist_mGrid assign it an index of the length of the grid minus 1 @@ -606,8 +605,9 @@ def jump_to_grid_2D(m_vals, perm_vals, probs, dist_mGrid, dist_pGrid): mlowerIndex = mIndex[i] mupperIndex = mIndex[i] + 1 # Assign weight to the indices that bound the m_vals point. Intuitively, an mval perfectly between two points on the mgrid will assign a weight of .5 to the gridpoint above and below - mlowerWeight = (dist_mGrid[mupperIndex] - m_vals[i]) / ( - dist_mGrid[mupperIndex] - dist_mGrid[mlowerIndex] + mlowerWeight = ( + (dist_mGrid[mupperIndex] - m_vals[i]) + / (dist_mGrid[mupperIndex] - dist_mGrid[mlowerIndex]) ) # Metric to determine weight of gridpoint/index below. Intuitively, mvals that are close to gridpoint/index above are assigned a smaller mlowerweight. mupperWeight = 1.0 - mlowerWeight # weight of gridpoint/ index above diff --git a/HARK/validators.py b/HARK/validators.py index 792832abc..c3acbe87c 100644 --- a/HARK/validators.py +++ b/HARK/validators.py @@ -1,6 +1,7 @@ """ Decorators which can be used for validating arguments passed into decorated functions """ + from functools import wraps from inspect import signature diff --git a/examples/ConsumptionSaving/example_ConsMarkovModel.ipynb b/examples/ConsumptionSaving/example_ConsMarkovModel.ipynb index f48d7948d..d991e9f20 100644 --- a/examples/ConsumptionSaving/example_ConsMarkovModel.ipynb +++ b/examples/ConsumptionSaving/example_ConsMarkovModel.ipynb @@ -320,13 +320,13 @@ "MrkvArray[0, 0] = (\n", " 1.0 - ImmunityPrb\n", ") # Probability of not becoming immune in ordinary state: stay in ordinary state\n", - "MrkvArray[\n", - " 0, ImmunityT\n", - "] = ImmunityPrb # Probability of becoming immune in ordinary state: begin immunity periods\n", + "MrkvArray[0, ImmunityT] = (\n", + " ImmunityPrb # Probability of becoming immune in ordinary state: begin immunity periods\n", + ")\n", "for j in range(ImmunityT):\n", - " MrkvArray[\n", - " j + 1, j\n", - " ] = 1.0 # When immune, have 100% chance of transition to state with one fewer immunity periods remaining" + " MrkvArray[j + 1, j] = (\n", + " 1.0 # When immune, have 100% chance of transition to state with one fewer immunity periods remaining\n", + " )" ] }, { diff --git a/examples/Journeys/JourneyPhDparam.py b/examples/Journeys/JourneyPhDparam.py index d03e3e3dd..d095f5100 100644 --- a/examples/Journeys/JourneyPhDparam.py +++ b/examples/Journeys/JourneyPhDparam.py @@ -1,6 +1,7 @@ -''' +""" Set if parameters for the first journey -''' +""" + from copy import copy import numpy as np @@ -8,150 +9,171 @@ # --- Define all of the parameters for the perfect foresight model ------------ # ----------------------------------------------------------------------------- -CRRA = 2.0 # Coefficient of relative risk aversion -Rfree = 1.03 # Interest factor on assets -DiscFac = 0.96 # Intertemporal discount factor -LivPrb = [1.0] # Survival probability -PermGroFac = [1.0] # Permanent income growth factor -AgentCount = 10000 # Number of agents of this type (only matters for simulation) -aNrmInitMean = 0.0 # Mean of log initial assets (only matters for simulation) -aNrmInitStd = 1.0 # Standard deviation of log initial assets (only for simulation) -pLvlInitMean = 0.0 # Mean of log initial permanent income (only matters for simulation) -pLvlInitStd = 0.0 # Standard deviation of log initial permanent income (only matters for simulation) -PermGroFacAgg = 1.0 # Aggregate permanent income growth factor (only matters for simulation) -T_age = None # Age after which simulated agents are automatically killed -T_cycle = 1 # Number of periods in the cycle for this agent type +CRRA = 2.0 # Coefficient of relative risk aversion +Rfree = 1.03 # Interest factor on assets +DiscFac = 0.96 # Intertemporal discount factor +LivPrb = [1.0] # Survival probability +PermGroFac = [1.0] # Permanent income growth factor +AgentCount = 10000 # Number of agents of this type (only matters for simulation) +aNrmInitMean = 0.0 # Mean of log initial assets (only matters for simulation) +aNrmInitStd = 1.0 # Standard deviation of log initial assets (only for simulation) +pLvlInitMean = 0.0 # Mean of log initial permanent income (only matters for simulation) +pLvlInitStd = 0.0 # Standard deviation of log initial permanent income (only matters for simulation) +PermGroFacAgg = ( + 1.0 # Aggregate permanent income growth factor (only matters for simulation) +) +T_age = None # Age after which simulated agents are automatically killed +T_cycle = 1 # Number of periods in the cycle for this agent type # Make a dictionary to specify a perfect foresight consumer type -init_perfect_foresight = { 'CRRA': CRRA, - 'Rfree': Rfree, - 'DiscFac': DiscFac, - 'LivPrb': LivPrb, - 'PermGroFac': PermGroFac, - 'AgentCount': AgentCount, - 'aNrmInitMean' : aNrmInitMean, - 'aNrmInitStd' : aNrmInitStd, - 'pLvlInitMean' : pLvlInitMean, - 'pLvlInitStd' : pLvlInitStd, - 'PermGroFacAgg' : PermGroFacAgg, - 'T_age' : T_age, - 'T_cycle' : T_cycle - } +init_perfect_foresight = { + "CRRA": CRRA, + "Rfree": Rfree, + "DiscFac": DiscFac, + "LivPrb": LivPrb, + "PermGroFac": PermGroFac, + "AgentCount": AgentCount, + "aNrmInitMean": aNrmInitMean, + "aNrmInitStd": aNrmInitStd, + "pLvlInitMean": pLvlInitMean, + "pLvlInitStd": pLvlInitStd, + "PermGroFacAgg": PermGroFacAgg, + "T_age": T_age, + "T_cycle": T_cycle, +} # ----------------------------------------------------------------------------- # --- Define additional parameters for the idiosyncratic shocks model --------- # ----------------------------------------------------------------------------- # Parameters for constructing the "assets above minimum" grid -aXtraMin = 0.001 # Minimum end-of-period "assets above minimum" value -aXtraMax = 20 # Maximum end-of-period "assets above minimum" value -#aXtraExtra = [None] # Some other value of "assets above minimum" to add to the grid, not used -aXtraNestFac = 3 # Exponential nesting factor when constructing "assets above minimum" grid -aXtraCount = 48 # Number of points in the grid of "assets above minimum" +aXtraMin = 0.001 # Minimum end-of-period "assets above minimum" value +aXtraMax = 20 # Maximum end-of-period "assets above minimum" value +# aXtraExtra = [None] # Some other value of "assets above minimum" to add to the grid, not used +aXtraNestFac = ( + 3 # Exponential nesting factor when constructing "assets above minimum" grid +) +aXtraCount = 48 # Number of points in the grid of "assets above minimum" # Parameters describing the income process -PermShkCount = 7 # Number of points in discrete approximation to permanent income shocks -TranShkCount = 7 # Number of points in discrete approximation to transitory income shocks -PermShkStd = [0.1] # Standard deviation of log permanent income shocks -TranShkStd = [0.2] # Standard deviation of log transitory income shocks -UnempPrb = 0.005 # Probability of unemployment while working -UnempPrbRet = 0.005 # Probability of "unemployment" while retired -IncUnemp = 0.3 # Unemployment benefits replacement rate -IncUnempRet = 0.0 # "Unemployment" benefits when retired -tax_rate = 0.0 # Flat income tax rate -T_retire = 0 # Period of retirement (0 --> no retirement) +PermShkCount = ( + 7 # Number of points in discrete approximation to permanent income shocks +) +TranShkCount = ( + 7 # Number of points in discrete approximation to transitory income shocks +) +PermShkStd = [0.1] # Standard deviation of log permanent income shocks +TranShkStd = [0.2] # Standard deviation of log transitory income shocks +UnempPrb = 0.005 # Probability of unemployment while working +UnempPrbRet = 0.005 # Probability of "unemployment" while retired +IncUnemp = 0.3 # Unemployment benefits replacement rate +IncUnempRet = 0.0 # "Unemployment" benefits when retired +tax_rate = 0.0 # Flat income tax rate +T_retire = 0 # Period of retirement (0 --> no retirement) # A few other parameters -BoroCnstArt = 0.0 # Artificial borrowing constraint; imposed minimum level of end-of period assets -CubicBool = True # Use cubic spline interpolation when True, linear interpolation when False -vFuncBool = False # Whether to calculate the value function during solution +BoroCnstArt = 0.0 # Artificial borrowing constraint; imposed minimum level of end-of period assets +CubicBool = ( + True # Use cubic spline interpolation when True, linear interpolation when False +) +vFuncBool = False # Whether to calculate the value function during solution # Make a dictionary to specify an idiosyncratic income shocks consumer -init_idiosyncratic_shocks = { 'CRRA': CRRA, - 'Rfree': Rfree, - 'DiscFac': DiscFac, - 'LivPrb': LivPrb, - 'PermGroFac': PermGroFac, - 'AgentCount': AgentCount, - 'aXtraMin': aXtraMin, - 'aXtraMax': aXtraMax, - 'aXtraNestFac':aXtraNestFac, - 'aXtraCount': aXtraCount, - #'aXtraExtra': [aXtraExtra], - 'PermShkStd': PermShkStd, - 'PermShkCount': PermShkCount, - 'TranShkStd': TranShkStd, - 'TranShkCount': TranShkCount, - 'UnempPrb': UnempPrb, - 'UnempPrbRet': UnempPrbRet, - 'IncUnemp': IncUnemp, - 'IncUnempRet': IncUnempRet, - 'BoroCnstArt': BoroCnstArt, - 'tax_rate':0.0, - 'vFuncBool':vFuncBool, - 'CubicBool':CubicBool, - 'T_retire':T_retire, - 'aNrmInitMean' : aNrmInitMean, - 'aNrmInitStd' : aNrmInitStd, - 'pLvlInitMean' : pLvlInitMean, - 'pLvlInitStd' : pLvlInitStd, - 'PermGroFacAgg' : PermGroFacAgg, - 'T_age' : T_age, - 'T_cycle' : T_cycle - } +init_idiosyncratic_shocks = { + "CRRA": CRRA, + "Rfree": Rfree, + "DiscFac": DiscFac, + "LivPrb": LivPrb, + "PermGroFac": PermGroFac, + "AgentCount": AgentCount, + "aXtraMin": aXtraMin, + "aXtraMax": aXtraMax, + "aXtraNestFac": aXtraNestFac, + "aXtraCount": aXtraCount, + #'aXtraExtra': [aXtraExtra], + "PermShkStd": PermShkStd, + "PermShkCount": PermShkCount, + "TranShkStd": TranShkStd, + "TranShkCount": TranShkCount, + "UnempPrb": UnempPrb, + "UnempPrbRet": UnempPrbRet, + "IncUnemp": IncUnemp, + "IncUnempRet": IncUnempRet, + "BoroCnstArt": BoroCnstArt, + "tax_rate": 0.0, + "vFuncBool": vFuncBool, + "CubicBool": CubicBool, + "T_retire": T_retire, + "aNrmInitMean": aNrmInitMean, + "aNrmInitStd": aNrmInitStd, + "pLvlInitMean": pLvlInitMean, + "pLvlInitStd": pLvlInitStd, + "PermGroFacAgg": PermGroFacAgg, + "T_age": T_age, + "T_cycle": T_cycle, +} # Make a dictionary to specify a lifecycle consumer with a finite horizon # ----------------------------------------------------------------------------- # ----- Define additional parameters for the aggregate shocks model ----------- # ----------------------------------------------------------------------------- -MgridBase = np.array([0.1,0.3,0.6,0.8,0.9,0.98,1.0,1.02,1.1,1.2,1.6,2.0,3.0]) # Grid of capital-to-labor-ratios (factors) +MgridBase = np.array( + [0.1, 0.3, 0.6, 0.8, 0.9, 0.98, 1.0, 1.02, 1.1, 1.2, 1.6, 2.0, 3.0] +) # Grid of capital-to-labor-ratios (factors) # Parameters for a Cobb-Douglas economy -PermGroFacAgg = 1.00 # Aggregate permanent income growth factor -PermShkAggCount = 1 # Number of points in discrete approximation to aggregate permanent shock dist -TranShkAggCount = 1 # Number of points in discrete approximation to aggregate transitory shock dist -PermShkAggStd = 0.00 # Standard deviation of log aggregate permanent shocks -TranShkAggStd = 0.00 # Standard deviation of log aggregate transitory shocks -DeprFac = 0.025 # Capital depreciation rate -CapShare = 0.36 # Capital's share of income -DiscFacPF = DiscFac # Discount factor of perfect foresight calibration -CRRAPF = CRRA # Coefficient of relative risk aversion of perfect foresight calibration -intercept_prev = 0.0 # Intercept of aggregate savings function -slope_prev = 1.0 # Slope of aggregate savings function -verbose_cobb_douglas = True # Whether to print solution progress to screen while solving -T_discard = 200 # Number of simulated "burn in" periods to discard when updating AFunc -DampingFac = 0.5 # Damping factor when updating AFunc; puts DampingFac weight on old params, rest on new -max_loops = 20 # Maximum number of AFunc updating loops to allow +PermGroFacAgg = 1.00 # Aggregate permanent income growth factor +PermShkAggCount = ( + 1 # Number of points in discrete approximation to aggregate permanent shock dist +) +TranShkAggCount = ( + 1 # Number of points in discrete approximation to aggregate transitory shock dist +) +PermShkAggStd = 0.00 # Standard deviation of log aggregate permanent shocks +TranShkAggStd = 0.00 # Standard deviation of log aggregate transitory shocks +DeprFac = 0.025 # Capital depreciation rate +CapShare = 0.36 # Capital's share of income +DiscFacPF = DiscFac # Discount factor of perfect foresight calibration +CRRAPF = CRRA # Coefficient of relative risk aversion of perfect foresight calibration +intercept_prev = 0.0 # Intercept of aggregate savings function +slope_prev = 1.0 # Slope of aggregate savings function +verbose_cobb_douglas = ( + True # Whether to print solution progress to screen while solving +) +T_discard = 200 # Number of simulated "burn in" periods to discard when updating AFunc +DampingFac = 0.5 # Damping factor when updating AFunc; puts DampingFac weight on old params, rest on new +max_loops = 20 # Maximum number of AFunc updating loops to allow # Make a dictionary to specify an aggregate shocks consumer init_agg_shocks = copy(init_idiosyncratic_shocks) -del init_agg_shocks['Rfree'] # Interest factor is endogenous in agg shocks model -del init_agg_shocks['CubicBool'] # Not supported yet for agg shocks model -del init_agg_shocks['vFuncBool'] # Not supported yet for agg shocks model -init_agg_shocks['PermGroFac'] = [1.0] -init_agg_shocks['MgridBase'] = MgridBase -init_agg_shocks['aXtraCount'] = 24 -init_agg_shocks['aNrmInitStd'] = 0.0 -init_agg_shocks['LivPrb'] = LivPrb +del init_agg_shocks["Rfree"] # Interest factor is endogenous in agg shocks model +del init_agg_shocks["CubicBool"] # Not supported yet for agg shocks model +del init_agg_shocks["vFuncBool"] # Not supported yet for agg shocks model +init_agg_shocks["PermGroFac"] = [1.0] +init_agg_shocks["MgridBase"] = MgridBase +init_agg_shocks["aXtraCount"] = 24 +init_agg_shocks["aNrmInitStd"] = 0.0 +init_agg_shocks["LivPrb"] = LivPrb # Make a dictionary to specify a Cobb-Douglas economy -init_cobb_douglas = {'PermShkAggCount': PermShkAggCount, - 'TranShkAggCount': TranShkAggCount, - 'PermShkAggStd': PermShkAggStd, - 'TranShkAggStd': TranShkAggStd, - 'DeprFac': DeprFac, - 'CapShare': CapShare, - 'DiscFac': DiscFacPF, - 'CRRA': CRRAPF, - 'PermGroFacAgg': PermGroFacAgg, - 'AggregateL':1.0, - 'act_T':1200, - 'intercept_prev': intercept_prev, - 'slope_prev': slope_prev, - 'verbose': verbose_cobb_douglas, - 'T_discard': T_discard, - 'DampingFac': DampingFac, - 'max_loops': max_loops - } +init_cobb_douglas = { + "PermShkAggCount": PermShkAggCount, + "TranShkAggCount": TranShkAggCount, + "PermShkAggStd": PermShkAggStd, + "TranShkAggStd": TranShkAggStd, + "DeprFac": DeprFac, + "CapShare": CapShare, + "DiscFac": DiscFacPF, + "CRRA": CRRAPF, + "PermGroFacAgg": PermGroFacAgg, + "AggregateL": 1.0, + "act_T": 1200, + "intercept_prev": intercept_prev, + "slope_prev": slope_prev, + "verbose": verbose_cobb_douglas, + "T_discard": T_discard, + "DampingFac": DampingFac, + "max_loops": max_loops, +} diff --git a/examples/LifecycleModel/LifecycleModel.ipynb b/examples/LifecycleModel/LifecycleModel.ipynb index e57fab58b..ac94fb46e 100644 --- a/examples/LifecycleModel/LifecycleModel.ipynb +++ b/examples/LifecycleModel/LifecycleModel.ipynb @@ -59,25 +59,25 @@ "outputs": [], "source": [ "# Set up default values for CRRA, DiscFac, and simulation variables in the dictionary\n", - "Params.init_consumer_objects[\n", - " \"CRRA\"\n", - "] = 2.00 # Default coefficient of relative risk aversion (rho)\n", - "Params.init_consumer_objects[\n", - " \"DiscFac\"\n", - "] = 0.97 # Default intertemporal discount factor (beta)\n", - "Params.init_consumer_objects[\n", - " \"PermGroFacAgg\"\n", - "] = 1.0 # Aggregate permanent income growth factor\n", + "Params.init_consumer_objects[\"CRRA\"] = (\n", + " 2.00 # Default coefficient of relative risk aversion (rho)\n", + ")\n", + "Params.init_consumer_objects[\"DiscFac\"] = (\n", + " 0.97 # Default intertemporal discount factor (beta)\n", + ")\n", + "Params.init_consumer_objects[\"PermGroFacAgg\"] = (\n", + " 1.0 # Aggregate permanent income growth factor\n", + ")\n", "Params.init_consumer_objects[\"aNrmInitMean\"] = -10.0 # Mean of log initial assets\n", - "Params.init_consumer_objects[\n", - " \"aNrmInitStd\"\n", - "] = 1.0 # Standard deviation of log initial assets\n", - "Params.init_consumer_objects[\n", - " \"pLvlInitMean\"\n", - "] = 0.0 # Mean of log initial permanent income\n", - "Params.init_consumer_objects[\n", - " \"pLvlInitStd\"\n", - "] = 0.0 # Standard deviation of log initial permanent income" + "Params.init_consumer_objects[\"aNrmInitStd\"] = (\n", + " 1.0 # Standard deviation of log initial assets\n", + ")\n", + "Params.init_consumer_objects[\"pLvlInitMean\"] = (\n", + " 0.0 # Mean of log initial permanent income\n", + ")\n", + "Params.init_consumer_objects[\"pLvlInitStd\"] = (\n", + " 0.0 # Standard deviation of log initial permanent income\n", + ")" ] }, { diff --git a/examples/MonteCarlo/Generic Monte Carlo Perfect Foresight.ipynb b/examples/MonteCarlo/Generic Monte Carlo Perfect Foresight.ipynb index 2699e7125..9fae87065 100644 --- a/examples/MonteCarlo/Generic Monte Carlo Perfect Foresight.ipynb +++ b/examples/MonteCarlo/Generic Monte Carlo Perfect Foresight.ipynb @@ -8,7 +8,6 @@ "outputs": [], "source": [ "from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType\n", - "from HARK.distribution import Bernoulli\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np" From bca2586e6a098e0ebb00868e829c806c234252b3 Mon Sep 17 00:00:00 2001 From: alanlujan91 Date: Sun, 10 Mar 2024 20:33:51 -0400 Subject: [PATCH 3/3] fix failing test --- HARK/ConsumptionSaving/ConsIndShockModel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HARK/ConsumptionSaving/ConsIndShockModel.py b/HARK/ConsumptionSaving/ConsIndShockModel.py index b1f1e015f..604528bc5 100644 --- a/HARK/ConsumptionSaving/ConsIndShockModel.py +++ b/HARK/ConsumptionSaving/ConsIndShockModel.py @@ -44,8 +44,8 @@ combine_indep_dstns, expected, ) -from HARK.interpolation import CubicHermiteInterp as CubicInterp from HARK.interpolation import ( + CubicInterp, LinearInterp, LowerEnvelope, MargMargValueFuncCRRA,