def test_inner_loop_extra(baseline, param_updates, filename, dask_client): # Test SS.inner_loop function. Provide inputs to function and # ensure that output returned matches what it has been before. p = Specifications(baseline=baseline, num_workers=NUM_WORKERS) p.update_specifications(param_updates) p.output_base = CUR_PATH r = 0.05 TR = 0.12 Y = 1.3 factor = 100000 BQ = np.ones(p.J) * 0.00019646295986015257 outer_loop_vars = (bssmat, nssmat, r, BQ, Y, TR, factor) test_tuple = SS.inner_loop(outer_loop_vars, p, dask_client) expected_tuple = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', filename)) for i, v in enumerate(expected_tuple): print('Max diff = ', np.absolute(test_tuple[i] - v).max()) print('Checking item = ', i) assert (np.allclose(test_tuple[i], v, atol=1e-05))
def test_get_data(baseline, dask_client): """ Test of get_micro_data.get_data() function Note that this test may fail if the Tax-Calculator is not v 3.2.1 """ expected_data = utils.safe_read_pickle( os.path.join(CUR_PATH, "test_io_data", "micro_data_dict_for_tests.pkl") ) test_data, _ = get_micro_data.get_data( baseline=baseline, start_year=2030, reform={}, data="cps", client=dask_client, num_workers=NUM_WORKERS, ) for k, v in test_data.items(): try: assert_frame_equal(expected_data[k], v) except KeyError: pass
''' Tests of output_plots.py module ''' import pytest import os import numpy as np import matplotlib.image as mpimg from ogcore import utils, output_plots # Load in test results and parameters CUR_PATH = os.path.abspath(os.path.dirname(__file__)) base_ss = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'SS_vars_baseline.pkl')) base_ss['r_p_ss'] = base_ss.pop('r_hh_ss') base_tpi = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TPI_vars_baseline.pkl')) base_tpi['r_p'] = base_tpi.pop('r_hh') base_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_baseline.pkl')) reform_ss = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'SS_vars_reform.pkl')) reform_ss['r_p_ss'] = reform_ss.pop('r_hh_ss') reform_tpi = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TPI_vars_reform.pkl')) reform_tpi['r_p'] = reform_tpi.pop('r_hh') reform_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_reform.pkl')) reform_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_reform.pkl'))
def run_SS(p, client=None): ''' Solve for steady-state equilibrium of OG-Core. Args: p (OG-Core Specifications object): model parameters client (Dask client object): client Returns: output (dictionary): dictionary with steady-state solution results ''' # For initial guesses of w, r, TR, and factor, we use values that # are close to some steady state values. if p.baseline: if p.zeta_K[-1] == 1.0: rguess = p.world_int_rate[-1] else: rguess = p.initial_guess_r_SS if p.use_zeta: b_guess = np.ones((p.S, p.J)) * 0.0055 n_guess = np.ones((p.S, p.J)) * .4 * p.ltilde else: b_guess = np.ones((p.S, p.J)) * 0.07 n_guess = np.ones((p.S, p.J)) * .35 * p.ltilde TRguess = p.initial_guess_TR_SS factorguess = p.initial_guess_factor_SS BQguess = aggr.get_BQ(rguess, b_guess, None, p, 'SS', False) ss_params_baseline = (b_guess, n_guess, None, None, p, client) if p.use_zeta: BQguess = 0.12231465279007188 guesses = [rguess] + list([BQguess]) + [TRguess, factorguess] else: guesses = [rguess] + list(BQguess) + [TRguess, factorguess] [solutions_fsolve, infodict, ier, message] =\ opt.fsolve(SS_fsolve, guesses, args=ss_params_baseline, xtol=p.mindist_SS, full_output=True) if ENFORCE_SOLUTION_CHECKS and not ier == 1: raise RuntimeError('Steady state equilibrium not found') rss = solutions_fsolve[0] BQss = solutions_fsolve[1:-2] TR_ss = solutions_fsolve[-2] factor_ss = solutions_fsolve[-1] Yss = TR_ss / p.alpha_T[-1] # may not be right - if budget_balance # = True, but that's ok - will be fixed in SS_solver fsolve_flag = True # Return SS values of variables output = SS_solver(b_guess, n_guess, rss, BQss, TR_ss, factor_ss, Yss, p, client, fsolve_flag) else: # Use the baseline solution to get starting values for the reform baseline_ss_dir = os.path.join(p.baseline_dir, 'SS', 'SS_vars.pkl') ss_solutions = utils.safe_read_pickle(baseline_ss_dir) # use baseline solution as starting values if dimensions match if ss_solutions['bssmat_splus1'].shape == (p.S, p.J): (b_guess, n_guess, rguess, BQguess, TRguess, Yguess, factor) =\ (ss_solutions['bssmat_splus1'], ss_solutions['nssmat'], ss_solutions['rss'], ss_solutions['BQss'], ss_solutions['TR_ss'], ss_solutions['Yss'], ss_solutions['factor_ss']) else: if p.use_zeta: b_guess = np.ones((p.S, p.J)) * 0.0055 n_guess = np.ones((p.S, p.J)) * .4 * p.ltilde else: b_guess = np.ones((p.S, p.J)) * 0.07 n_guess = np.ones((p.S, p.J)) * .4 * p.ltilde if p.zeta_D[-1] == 1.0: rguess = p.world_int_rate[-1] else: rguess = p.initial_guess_r_SS TRguess = p.initial_guess_TR_SS factor = p.initial_guess_factor_SS BQguess = aggr.get_BQ(rguess, b_guess, None, p, 'SS', False) if p.baseline_spending: TR_ss = TRguess ss_params_reform = (b_guess, n_guess, TR_ss, factor, p, client) if p.use_zeta: guesses = [rguess] + list([BQguess]) + [Yguess] else: guesses = [rguess] + list(BQguess) + [Yguess] [solutions_fsolve, infodict, ier, message] =\ opt.fsolve(SS_fsolve, guesses, args=ss_params_reform, xtol=p.mindist_SS, full_output=True) rss = solutions_fsolve[0] BQss = solutions_fsolve[1:-1] Yss = solutions_fsolve[-1] else: ss_params_reform = (b_guess, n_guess, None, factor, p, client) if p.use_zeta: guesses = [rguess] + list([BQguess]) + [TRguess] else: guesses = [rguess] + list(BQguess) + [TRguess] [solutions_fsolve, infodict, ier, message] =\ opt.fsolve(SS_fsolve, guesses, args=ss_params_reform, xtol=p.mindist_SS, full_output=True) rss = solutions_fsolve[0] BQss = solutions_fsolve[1:-1] TR_ss = solutions_fsolve[-1] Yss = TR_ss / p.alpha_T[-1] # may not be right - if # budget_balance = True, but that's ok - will be fixed in # SS_solver if ENFORCE_SOLUTION_CHECKS and not ier == 1: raise RuntimeError('Steady state equilibrium not found') # Return SS values of variables fsolve_flag = True # Return SS values of variables output = SS_solver(b_guess, n_guess, rss, BQss, TR_ss, factor, Yss, p, client, fsolve_flag) if output['Gss'] < 0.: warnings.warn('Warning: The combination of the tax policy ' + 'you specified and your target debt-to-GDP ' + 'ratio results in an infeasible amount of ' + 'government spending in order to close the ' + 'budget (i.e., G < 0)') return output
from ogcore.utils import safe_read_pickle CUR_PATH = os.path.abspath(os.path.dirname(__file__)) NUM_WORKERS = min(multiprocessing.cpu_count(), 7) @pytest.fixture(scope="module") def dask_client(): cluster = LocalCluster(n_workers=NUM_WORKERS, threads_per_worker=2) client = Client(cluster) yield client # teardown client.close() cluster.close() input_tuple = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'SS_fsolve_inputs.pkl')) (bssmat, nssmat, TR_ss, factor_ss) = input_tuple # Parameterize the baseline, closed econ case p1 = Specifications(baseline=True) p1.update_specifications({'zeta_D': [0.0], 'zeta_K': [0.0]}) guesses1 = np.array( [0.06, 0.016, 0.02, 0.02, 0.01, 0.01, 0.02, 0.003, -0.07, 0.051]) args1 = (bssmat, nssmat, None, None, p1, None) expected1 = np.array([ -0.026632037158481975, -0.0022739752626707334, -0.01871875707724979, -0.01791935965422934, 0.005996289165268601, 0.00964100151012603, -0.01953460990186908, -0.0029633389016814967, 0.1306862551496613, 0.11574464544202477 ]) # Parameterize the reform, closed econ case p2 = Specifications(baseline=False)
def main(year: int = 2019): year = str(year) # read in tax function parameters from pickle tax_funcs_base = safe_read_pickle( "./examples/OG-UK-Example/OUTPUT_BASELINE/TxFuncEst_baseline.pkl" ) try: tax_funcs_reform = safe_read_pickle( "./examples/OG-UK-Example/OUTPUT_REFORM/TxFuncEst_policy.pkl" ) except: tax_funcs_reform = tax_funcs_base # read in micro data from pickle micro_data = safe_read_pickle( "./examples/OG-UK-Example/OUTPUT_BASELINE/micro_data_baseline.pkl" ) for ftype, name in zip( ("etr", "mtrx", "mtry"), ("etr", "mtr_labinc", "mtr_capinc") ): tax = get_tax_fn( year, year, [tax_funcs_base, tax_funcs_reform], age=None, tax_func_type=["DEP"], rate_type=ftype, over_labinc=True, other_inc_val=1000, max_inc_amt=100000, data_list=[micro_data], labels=["Baseline", "Reform"], title=f"Rate type: DEP, over labour income", path=None, ) df = pd.DataFrame( { "Labour income": micro_data[year]["total_labinc"], "Capital income": micro_data[year]["total_capinc"], name: micro_data[year][name], "Type": "Actual", } ) second_df = df.copy() second_df[name] = tax(df["Labour income"], df["Capital income"]) second_df["Type"] = "Fitted" df = pd.concat([df, second_df]) px.scatter_3d( df, x="Labour income", y="Capital income", z=name, opacity=0.1, color="Type", ).update_layout( title=f"{name} function in {year}", template="plotly_white", ).show()
def main(): # Define parameters to use for multiprocessing client = Client() num_workers = min(multiprocessing.cpu_count(), 7) print("Number of workers = ", num_workers) # Directories to save data CUR_DIR = os.path.dirname(os.path.realpath(__file__)) base_dir = os.path.join(CUR_DIR, "OG-USA-Example", "OUTPUT_BASELINE") reform_dir = os.path.join(CUR_DIR, "OG-USA-Example", "OUTPUT_REFORM") """ ------------------------------------------------------------------------ Run baseline policy ------------------------------------------------------------------------ """ # Set up baseline parameterization p = Specifications( baseline=True, num_workers=num_workers, baseline_dir=base_dir, output_base=base_dir, ) # Update parameters for baseline from default json file p.update_specifications( json.load( open( os.path.join(CUR_DIR, "..", "ogusa", "ogusa_default_parameters.json")))) # Run model start_time = time.time() runner(p, time_path=True, client=client) print("run time = ", time.time() - start_time) """ ------------------------------------------------------------------------ Run reform policy ------------------------------------------------------------------------ """ # Grab a reform JSON file already in Tax-Calculator # In this example the 'reform' is a change to 2017 law (the # baseline policy is tax law in 2018) reform_url = ("github://*****:*****@main/psl_examples/" + "taxcalc/2017_law.json") ref = Calculator.read_json_param_objects(reform_url, None) iit_reform = ref["policy"] # create new Specifications object for reform simulation p2 = Specifications( baseline=False, num_workers=num_workers, baseline_dir=base_dir, output_base=reform_dir, ) # Update parameters for baseline from default json file p2.update_specifications( json.load( open( os.path.join(CUR_DIR, "..", "ogusa", "ogusa_default_parameters.json")))) # Use calibration class to estimate reform tax functions from # Tax-Calculator, specifing reform for Tax-Calculator in iit_reform c2 = Calibration(p2, iit_reform=iit_reform, estimate_tax_functions=True, client=client) # update tax function parameters in Specifications Object d = c2.get_dict() # additional parameters to change updated_params = { "cit_rate": [0.35], "etr_params": d["etr_params"], "mtrx_params": d["mtrx_params"], "mtry_params": d["mtry_params"], "mean_income_data": d["mean_income_data"], "frac_tax_payroll": d["frac_tax_payroll"], } p2.update_specifications(updated_params) # Run model start_time = time.time() runner(p2, time_path=True, client=client) print("run time = ", time.time() - start_time) client.close() """ ------------------------------------------------------------------------ Save some results of simulations ------------------------------------------------------------------------ """ base_tpi = safe_read_pickle(os.path.join(base_dir, "TPI", "TPI_vars.pkl")) base_params = safe_read_pickle(os.path.join(base_dir, "model_params.pkl")) reform_tpi = safe_read_pickle( os.path.join(reform_dir, "TPI", "TPI_vars.pkl")) reform_params = safe_read_pickle( os.path.join(reform_dir, "model_params.pkl")) ans = ot.macro_table( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=["Y", "C", "K", "L", "r", "w"], output_type="pct_diff", num_years=10, start_year=base_params.start_year, ) # create plots of output op.plot_all(base_dir, reform_dir, os.path.join(CUR_DIR, "OG-USA_example_plots")) print("Percentage changes in aggregates:", ans) # save percentage change output to csv file ans.to_csv("ogusa_example_output.csv")
def main(): # Define parameters to use for multiprocessing client = Client() num_workers = min(multiprocessing.cpu_count(), 7) print('Number of workers = ', num_workers) run_start_time = time.time() # Directories to save data CUR_DIR = os.path.dirname(os.path.realpath(__file__)) base_dir = os.path.join(CUR_DIR, BASELINE_DIR) reform_dir = os.path.join(CUR_DIR, REFORM_DIR) # Set some OG model parameters # See default_parameters.json for more description of these parameters alpha_T = np.zeros(50) # Adjusting the path of transfer spending alpha_T[0:2] = 0.09 alpha_T[2:10] = 0.09 + 0.01 alpha_T[10:40] = 0.09 - 0.01 alpha_T[40:] = 0.09 alpha_G = np.zeros(7) # Adjusting the path of non-transfer spending alpha_G[0:3] = 0.05 - 0.01 alpha_G[3:6] = 0.05 - 0.005 alpha_G[6:] = 0.05 # Set start year for baseline and reform. START_YEAR = 2021 # Also adjust the Frisch elasticity, the start year, the # effective corporate income tax rate, and the SS debt-to-GDP ratio og_spec = { 'frisch': 0.41, 'start_year': START_YEAR, 'cit_rate': [0.21], 'debt_ratio_ss': 1.0, 'alpha_T': alpha_T.tolist(), 'alpha_G': alpha_G.tolist() } ''' ------------------------------------------------------------------------ Run baseline policy first ------------------------------------------------------------------------ ''' p = Specifications( baseline=True, num_workers=num_workers, baseline_dir=base_dir, output_base=base_dir, ) # Update parameters for baseline from default json file p.update_specifications(og_spec) start_time = time.time() runner(p, time_path=True, client=client) print('run time = ', time.time() - start_time) ''' ------------------------------------------------------------------------ Run reform policy ------------------------------------------------------------------------ ''' # update the effective corporate income tax rate og_spec.update({'cit_rate': [0.35]}) p2 = Specifications( baseline=False, num_workers=num_workers, baseline_dir=base_dir, output_base=reform_dir, ) # Update parameters for baseline from default json file p2.update_specifications(og_spec) start_time = time.time() runner(p2, time_path=True, client=client) print('run time = ', time.time() - start_time) # return ans - the percentage changes in macro aggregates and prices # due to policy changes from the baseline to the reform base_tpi = safe_read_pickle(os.path.join(base_dir, 'TPI', 'TPI_vars.pkl')) base_params = safe_read_pickle(os.path.join(base_dir, 'model_params.pkl')) reform_tpi = safe_read_pickle( os.path.join(reform_dir, 'TPI', 'TPI_vars.pkl')) reform_params = safe_read_pickle( os.path.join(reform_dir, 'model_params.pkl')) ans = ot.macro_table(base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['Y', 'C', 'K', 'L', 'r', 'w'], output_type='pct_diff', num_years=10, start_year=og_spec['start_year']) # create plots of output op.plot_all(base_dir, reform_dir, os.path.join(CUR_DIR, 'run_example_plots')) print("total time was ", (time.time() - run_start_time)) print('Percentage changes in aggregates:', ans) # save percentage change output to csv file ans.to_csv('ogcore_example_output.csv') client.close()
def read_tax_func_estimate(self, p, tax_func_path): """ This function reads in tax function parameters from pickle files. Args: tax_func_path (str): path to pickle with tax function parameter estimates Returns: dict_params (dict): dictionary containing arrays of tax function parameters run_micro (bool): whether to estimate tax function parameters """ flag = 0 if os.path.exists(tax_func_path): print("Tax Function Path Exists") dict_params = safe_read_pickle(tax_func_path) # check to see if tax_functions compatible current_taxcalc = pkg_resources.get_distribution("taxcalc").version try: if current_taxcalc != dict_params["tax_calc_version"]: print( "WARNING: Tax function parameters estimated" + " from Tax Calculator version that is not " + " the one currently installed on this machine." ) print( "Current TC version is ", current_taxcalc, ", Estimated tax functions from version ", dict_params.get("tax_calc_version", None), ) flag = 1 except KeyError: pass try: if p.start_year != dict_params["start_year"]: print( "Model start year not consistent with tax " + "function parameter estimates" ) flag = 1 except KeyError: pass try: if p.BW != dict_params["BW"]: print( "Model budget window length is " + str(p.BW) + "but the tax function parameter " + "estimates have a budget window length of " + str(dict_params["BW"]) ) flag = 1 except KeyError: pass try: if p.tax_func_type != dict_params["tax_func_type"]: print( "Model tax function type is not " + "consistent with tax function parameter " + "estimates" ) flag = 1 except KeyError: pass if flag >= 1: raise RuntimeError( "Tax function parameter estimates at given path" + " are not consistent with model parameters" + " specified." ) else: flag = 1 print( "Tax function parameter estimates do not exist at" + " given path. Running new estimation." ) if flag >= 1: dict_params = None run_micro = True else: run_micro = False return dict_params, run_micro
def main(reform=None): if reform is None: reform = get_default_reform() # Define parameters to use for multiprocessing client = Client() num_workers = min(multiprocessing.cpu_count(), 7) print("Number of workers = ", num_workers) # Directories to save data CUR_DIR = os.path.dirname(os.path.realpath(__file__)) base_dir = os.path.join(CUR_DIR, "OG-UK-Example", "OUTPUT_BASELINE") reform_dir = os.path.join(CUR_DIR, "OG-UK-Example", "OUTPUT_REFORM") """ ------------------------------------------------------------------------ Run baseline policy ------------------------------------------------------------------------ """ # Set up baseline parameterization p = Specifications( baseline=True, num_workers=num_workers, baseline_dir=base_dir, output_base=base_dir, ) # Update parameters for baseline from default json file p.update_specifications( json.load( open( os.path.join(CUR_DIR, "..", "oguk", "oguk_default_parameters.json")))) # specify tax function form and start year p.update_specifications({ "tax_func_type": "DEP", "age_specific": False, "start_year": START_YEAR, "alpha_T": [5e-3], "alpha_G": [5e-3], }) # Estimate baseline tax functions from OpenFisca-UK c = Calibration(p, estimate_tax_functions=True, client=client) # update tax function parameters in Specifications Object d = c.get_dict() updated_params = { "etr_params": d["etr_params"], "mtrx_params": d["mtrx_params"], "mtry_params": d["mtry_params"], "mean_income_data": d["mean_income_data"], "frac_tax_payroll": d["frac_tax_payroll"], } p.update_specifications(updated_params) # Run model start_time = time.time() runner(p, time_path=True, client=client) print("run time = ", time.time() - start_time) """ ------------------------------------------------------------------------ Run reform policy ------------------------------------------------------------------------ """ # create new Specifications object for reform simulation p2 = Specifications( baseline=False, num_workers=num_workers, baseline_dir=base_dir, output_base=reform_dir, ) # Update parameters for baseline from default json file p2.update_specifications( json.load( open( os.path.join(CUR_DIR, "..", "oguk", "oguk_default_parameters.json")))) # specify tax function form and start year p2.update_specifications({ "tax_func_type": "DEP", "age_specific": False, "start_year": START_YEAR, "alpha_T": [5e-3], "alpha_G": [5e-3], }) # Estimate reform tax functions from OpenFisca-UK, passing Reform # class object c2 = Calibration(p2, iit_reform=reform, estimate_tax_functions=True, client=client) # update tax function parameters in Specifications Object d2 = c2.get_dict() updated_params2 = { "etr_params": d2["etr_params"], "mtrx_params": d2["mtrx_params"], "mtry_params": d2["mtry_params"], "mean_income_data": d2["mean_income_data"], "frac_tax_payroll": d2["frac_tax_payroll"], } p2.update_specifications(updated_params2) # Run model start_time = time.time() runner(p2, time_path=True, client=client) print("run time = ", time.time() - start_time) """ ------------------------------------------------------------------------ Save some results of simulations ------------------------------------------------------------------------ """ base_tpi = safe_read_pickle(os.path.join(base_dir, "TPI", "TPI_vars.pkl")) base_params = safe_read_pickle(os.path.join(base_dir, "model_params.pkl")) reform_tpi = safe_read_pickle( os.path.join(reform_dir, "TPI", "TPI_vars.pkl")) reform_params = safe_read_pickle( os.path.join(reform_dir, "model_params.pkl")) ans = ot.macro_table( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=["Y", "C", "K", "L", "r", "w"], output_type="pct_diff", num_years=10, start_year=base_params.start_year, ) # create plots of output op.plot_all(base_dir, reform_dir, os.path.join(CUR_DIR, "OG-UK_example_plots")) print("Percentage changes in aggregates:", ans) # save percentage change output to csv file ans.to_csv("oguk_example_output.csv") client.close()
''' Tests of parameter_plots.py module ''' import pytest import os import numpy as np import scipy.interpolate as si import matplotlib.image as mpimg from ogcore import utils, parameter_plots, Specifications # Load in test results and parameters CUR_PATH = os.path.abspath(os.path.dirname(__file__)) base_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_baseline.pkl')) base_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_baseline.pkl')) GS_nonage_spec_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_GS_nonage.pkl')) micro_data = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'micro_data_dict_for_tests.pkl')) def test_plot_imm_rates(): fig = parameter_plots.plot_imm_rates(base_params, include_title=True) assert fig def test_plot_imm_rates_save_fig(tmpdir): parameter_plots.plot_imm_rates(base_params, path=tmpdir) img = mpimg.imread(os.path.join(tmpdir, 'imm_rates_orig.png'))
def plot_all(base_output_path, reform_output_path, save_path): ''' Function to plot all default output plots. Args: base_output_path (str): path to baseline results reform_output_path (str): path to reform results save_path (str): path to save plots to Returns: None: All output figures saved to disk. ''' # Make directory in case it doesn't exist utils.mkdirs(save_path) # Read in data # Read in TPI output and parameters base_tpi = utils.safe_read_pickle( os.path.join(base_output_path, 'TPI', 'TPI_vars.pkl')) base_ss = utils.safe_read_pickle( os.path.join(base_output_path, 'SS', 'SS_vars.pkl')) base_params = utils.safe_read_pickle( os.path.join(base_output_path, 'model_params.pkl')) reform_tpi = utils.safe_read_pickle( os.path.join(reform_output_path, 'TPI', 'TPI_vars.pkl')) reform_ss = utils.safe_read_pickle( os.path.join(reform_output_path, 'SS', 'SS_vars.pkl')) reform_params = utils.safe_read_pickle( os.path.join(reform_output_path, 'model_params.pkl')) # Percentage changes in macro vars (Y, K, L, C) plot_aggregates(base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['Y', 'K', 'L', 'C'], plot_type='pct_diff', num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Percentage Changes in Macro Aggregates', path=os.path.join(save_path, 'MacroAgg_PctChange.png')) # Percentage change in fiscal vars (D, G, TR, Rev) plot_aggregates(base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['D', 'G', 'TR', 'total_tax_revenue'], plot_type='pct_diff', num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Percentage Changes in Fiscal Variables', path=os.path.join(save_path, 'Fiscal_PctChange.png')) # r and w in baseline and reform -- vertical lines at tG1, tG2 plot_aggregates(base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['r'], plot_type='levels', num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Real Interest Rates Under Baseline and Reform', path=os.path.join(save_path, 'InterestRates.png')) plot_aggregates(base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['w'], plot_type='levels', num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Wage Rates Under Baseline and Reform', path=os.path.join(save_path, 'WageRates.png')) # Debt-GDP in base and reform-- vertical lines at tG1, tG2 plot_gdp_ratio(base_tpi, base_params, reform_tpi, reform_params, var_list=['D'], num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Debt-to-GDP', path=os.path.join(save_path, 'DebtGDPratio.png')) # Tax revenue to GDP in base and reform-- vertical lines at tG1, tG2 plot_gdp_ratio(base_tpi, base_params, reform_tpi, reform_params, var_list=['total_tax_revenue'], num_years_to_plot=150, start_year=base_params.start_year, vertical_line_years=[ base_params.start_year + base_params.tG1, base_params.start_year + base_params.tG2 ], plot_title='Tax Revenue to GDP', path=os.path.join(save_path, 'RevenueGDPratio.png')) # Pct change in c, n, b, y, etr, mtrx, mtry by ability group over 10 years var_list = [ 'c_path', 'n_mat', 'bmat_splus1', 'etr_path', 'mtrx_path', 'mtry_path', 'y_before_tax_mat' ] title_list = [ 'consumption', 'labor supply', 'savings', 'effective tax rates', 'marginal tax rates on labor income', 'marginal tax rates on capital income', 'before tax income' ] path_list = ['Cons', 'Labor', 'Save', 'ETR', 'MTRx', 'MTRy', 'Income'] for i, v in enumerate(var_list): ability_bar(base_tpi, base_params, reform_tpi, reform_params, var=v, num_years=10, start_year=base_params.start_year, plot_title='Percentage changes in ' + title_list[i], path=os.path.join(save_path, 'PctChange_' + path_list[i] + '.png')) # lifetime profiles, base vs reform, SS for c, n, b, y - not by j var_list = [ 'cssmat', 'nssmat', 'bssmat_splus1', 'etr_ss', 'mtrx_ss', 'mtry_ss' ] for i, v in enumerate(var_list): ss_profiles(base_ss, base_params, reform_ss, reform_params, by_j=False, var=v, plot_title='Lifecycle Profile of ' + title_list[i], path=os.path.join( save_path, 'SSLifecycleProfile_' + path_list[i] + '.png')) # lifetime profiles, c, n , b, y by j, separately for base and reform for i, v in enumerate(var_list): ss_profiles(base_ss, base_params, by_j=True, var=v, plot_title='Lifecycle Profile of ' + title_list[i], path=os.path.join( save_path, 'SSLifecycleProfile_' + path_list[i] + '_Baseline.png')) ss_profiles(reform_ss, reform_params, by_j=True, var=v, plot_title='Lifecycle Profile of ' + title_list[i], path=os.path.join( save_path, 'SSLifecycleProfile_' + path_list[i] + '_Reform.png'))
''' Tests of parameter_table.py module ''' import pytest import os from ogcore import utils, parameter_tables from ogcore.parameters import Specifications # Load in test results and parameters CUR_PATH = os.path.abspath(os.path.dirname(__file__)) base_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_baseline.pkl')) base_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_baseline.pkl')) @pytest.mark.parametrize('rate_type', ['ETR', 'MTRx', 'MTRy', 'all'], ids=['ETR', 'MTRx', 'MTRy', 'All rates']) def test_tax_rate_table(rate_type): str = parameter_tables.tax_rate_table(base_taxfunctions, base_params, reform_TxFuncEst=base_taxfunctions, reform_params=base_params, rate_type=rate_type) assert str def test_tax_rate_table_exception1(): '''
def get_initial_SS_values(p): ''' Get values of variables for the initial period and the steady state equilibrium values. Args: p (OG-Core Specifications object): model parameters Returns: (tuple): initial period and steady state values: * initial_values (tuple): initial period variable values, (b_sinit, b_splus1init, factor, initial_b, initial_n) * ss_vars (dictionary): dictionary with steady state solution results * theta (Numpy array): steady-state retirement replacement rates, length J * baseline_values (tuple): (TRbaseline, Gbaseline, D0_baseline), lump sum transfer and government spending amounts from the baseline model run ''' baseline_ss = os.path.join(p.baseline_dir, "SS", "SS_vars.pkl") ss_baseline_vars = utils.safe_read_pickle(baseline_ss) factor = ss_baseline_vars['factor_ss'] B0 = aggr.get_B(ss_baseline_vars['bssmat_splus1'], p, 'SS', True) initial_b = (ss_baseline_vars['bssmat_splus1'] * (ss_baseline_vars['Bss'] / B0)) initial_n = ss_baseline_vars['nssmat'] TRbaseline = None Gbaseline = None if p.baseline_spending: baseline_tpi = os.path.join(p.baseline_dir, "TPI", "TPI_vars.pkl") tpi_baseline_vars = utils.safe_read_pickle(baseline_tpi) TRbaseline = tpi_baseline_vars['TR'] Gbaseline = tpi_baseline_vars['G'] if p.baseline: ss_vars = ss_baseline_vars else: reform_ss_path = os.path.join(p.output_base, "SS", "SS_vars.pkl") ss_vars = utils.safe_read_pickle(reform_ss_path) theta = ss_vars['theta'] ''' ------------------------------------------------------------------------ Set other parameters and initial values ------------------------------------------------------------------------ ''' # Get an initial distribution of wealth with the initial population # distribution. When small_open=True, the value of K0 is used as a # placeholder for first-period wealth B0 = aggr.get_B(initial_b, p, 'SS', True) b_sinit = np.array( list(np.zeros(p.J).reshape(1, p.J)) + list(initial_b[:-1])) b_splus1init = initial_b # Intial gov't debt must match that in the baseline if not p.baseline: baseline_tpi = os.path.join(p.baseline_dir, "TPI", "TPI_vars.pkl") tpi_baseline_vars = utils.safe_read_pickle(baseline_tpi) D0_baseline = tpi_baseline_vars['D'][0] else: D0_baseline = None initial_values = (B0, b_sinit, b_splus1init, factor, initial_b, initial_n) baseline_values = (TRbaseline, Gbaseline, D0_baseline) return initial_values, ss_vars, theta, baseline_values