示例#1
0
def test_read_tax_func_estimate():
    specs = Specifications()
    tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_baseline.pkl')
    expected_dict = utils.safe_read_pickle(tax_func_path)
    test_dict, _ = specs.read_tax_func_estimate(tax_func_path)
    assert np.allclose(expected_dict['tfunc_avg_etr'],
                       test_dict['tfunc_avg_etr'])
示例#2
0
def get_inputs(meta_param_dict):
    meta_params = MetaParams()
    meta_params.adjust(meta_param_dict)
    # Set default OG-USA parameters
    ogusa_params = Specifications()
    ogusa_params.start_year = meta_params.year
    filtered_ogusa_params = OrderedDict()
    filter_list = [
        'chi_n_80', 'chi_b', 'eta', 'zeta', 'constant_demographics', 'ltilde',
        'use_zeta', 'constant_rates', 'zero_taxes', 'analytical_mtrs',
        'age_specific', 'gamma', 'epsilon', 'start_year'
    ]
    for k, v in ogusa_params.dump().items():
        if ((k not in filter_list)
                and (v.get("section_1", False) != "Model Solution Parameters")
                and (v.get("section_2", False) != "Model Dimensions")):
            filtered_ogusa_params[k] = v
            print('filtered ogusa = ', k)
    # Set default TC params
    iit_params = TCParams()
    iit_params.set_state(year=meta_params.year.tolist())
    filtered_iit_params = OrderedDict()
    for k, v in iit_params.dump().items():
        if k == "schema" or v.get("section_1", False):
            filtered_iit_params[k] = v

    default_params = {
        "OG-USA Parameters": filtered_ogusa_params,
        "Tax-Calculator Parameters": filtered_iit_params
    }

    return {
        "meta_parameters": meta_params.dump(),
        "model_parameters": default_params
    }
示例#3
0
def test_D_G_path(baseline_spending, Y, T_H, REVENUE, Gbaseline,
                  D_expected, G_expected):
    p = Specifications()
    new_param_values = {
        'T': 320,
        'S': 80,
        'debt_ratio_ss': 1.2,
        'tG1': 20,
        'tG2': 256,
        'alpha_T': [0.09],
        'alpha_G': [0.05],
        'rho_G': 0.1,
        'g_y_annual': 0.03,
        'budget_balance': False,
        'baseline_spending': baseline_spending
    }
    p.update_specifications(new_param_values, raise_errors=False)
    r_gov = np.ones(p.T + p.S) * 0.03
    p.g_n = np.ones(p.T + p.S) * 0.02
    D0 = 0.59
    G0 = 0.05
    dg_fixed_values = (Y, REVENUE, T_H, D0, G0)
    test_D, test_G = fiscal.D_G_path(r_gov, dg_fixed_values, Gbaseline,
                                     p)
    assert np.allclose(test_D, D_expected)
    assert np.allclose(test_G, G_expected)
示例#4
0
def test_D_G_path(baseline_spending, Y, T_H, REVENUE, Gbaseline,
                  D_expected, G_expected):
    p = Specifications()
    new_param_values = {
        'T': 320,
        'S': 80,
        'debt_ratio_ss': 1.2,
        'tG1': 20,
        'tG2': 256,
        'alpha_T': [0.09],
        'alpha_G': [0.05],
        'rho_G': 0.1,
        'g_y_annual': 0.03,
        'budget_balance': False,
        'baseline_spending': baseline_spending
    }
    p.update_specifications(new_param_values, raise_errors=False)
    r_gov = np.ones(p.T + p.S) * 0.03
    p.g_n = np.ones(p.T + p.S) * 0.02
    D0 = 0.59
    G0 = 0.05
    dg_fixed_values = (Y, REVENUE, T_H, D0, G0)
    test_D, test_G = fiscal.D_G_path(r_gov, dg_fixed_values, Gbaseline,
                                     p)
    assert np.allclose(test_D, D_expected)
    assert np.allclose(test_G, G_expected)
def generate_plots():
    base_ss = utils.safe_read_pickle(
        "./cs_config/OUTPUT_BASELINE/SS/SS_vars.pkl")
    base_tpi = utils.safe_read_pickle(
        "./cs_config/OUTPUT_BASELINE/TPI/TPI_vars.pkl")
    reform_ss = utils.safe_read_pickle(
        "./cs_config/OUTPUT_REFORM/SS/SS_vars.pkl")
    reform_tpi = utils.safe_read_pickle(
        "./cs_config/OUTPUT_REFORM/TPI/TPI_vars.pkl")
    time_path = True
    base_params = Specifications()
    reform_params = Specifications()

    # outputs = functions.run_model(meta_param_dict, adjustment_dict)
    outputs = functions.comp_output(
        base_params,
        base_ss,
        reform_params,
        reform_ss,
        time_path,
        base_tpi=base_tpi,
        reform_tpi=reform_tpi,
        var="cssmat",
    )

    for output in outputs["renderable"]:
        serializer = cs_storage.get_serializer(output["media_type"])
        ser = serializer.serialize(output["data"])
        deserialized = dict(output,
                            data=serializer.deserialize(
                                ser, json_serializable=True))
        res = write_template(deserialized)
        with open(f"{output['title']}.html", "w") as f:
            f.write(res)
示例#6
0
def test_D_G_path(baseline_spending, Y, TR, Revenue, Gbaseline, budget_balance,
                  expected_tuple):
    p = Specifications()
    new_param_values = {
        'T': 320,
        'S': 80,
        'debt_ratio_ss': 1.2,
        'tG1': 20,
        'tG2': 256,
        'alpha_T': [0.09],
        'alpha_G': [0.05],
        'rho_G': 0.1,
        'g_y_annual': 0.03,
        'baseline_spending': baseline_spending,
        'budget_balance': budget_balance
    }
    p.update_specifications(new_param_values, raise_errors=False)
    r_gov = np.ones(p.T + p.S) * 0.03
    p.g_n = np.ones(p.T + p.S) * 0.02
    D0_baseline = 0.59
    Gbaseline[0] = 0.05
    dg_fixed_values = (Y, Revenue, TR, Gbaseline, D0_baseline)
    test_tuple = fiscal.D_G_path(r_gov, dg_fixed_values, p)
    for i, v in enumerate(test_tuple):
        assert np.allclose(v[:p.T], expected_tuple[i][:p.T])
def test_simple_eval():
    specs = Specifications()
    specs.T = 100
    assert specs.simple_eval('T / 2') == 50
    assert specs.simple_eval('T * 2') == 200
    assert specs.simple_eval('T - 2') == 98
    assert specs.simple_eval('T + 2') == 102
示例#8
0
def test_update_specifications_with_dict():
    spec = Specifications()
    new_spec_dict = {
        'frisch': 0.3,
    }
    spec.update_specifications(new_spec_dict)
    assert spec.frisch == 0.3
    assert len(spec.errors) == 0
示例#9
0
def validate_inputs(meta_param_dict, adjustment, errors_warnings):
    # ogusa doesn't look at meta_param_dict for validating inputs.
    params = Specifications()
    params.adjust(adjustment["ogusa"], raise_errors=False)
    # errors_warnings = revision_warnings_errors(adjustment["ogusa"])
    # return {"errors_warnings": errors_warnings}

    return {"errors_warnings": {"ogusa": {"errors": params.errors}}}
示例#10
0
def test_get_tax_function_parameters_baseline():
    specs = Specifications(baseline=True)
    tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_baseline.pkl')
    specs.get_tax_function_parameters(None,
                                      run_micro=False,
                                      tax_func_path=tax_func_path)
    assert specs.etr_params.shape == (specs.T, specs.S, 12)
    assert specs.mtrx_params.shape == (specs.T, specs.S, 12)
    assert specs.mtry_params.shape == (specs.T, specs.S, 12)
def test_implement_bad_reform2():
    specs = Specifications()
    # tG1 has an upper bound at T / 2
    new_specs = {'T': 80, 'tax_func_type': 'not_a_functional_form'}

    specs.update_specifications(new_specs, raise_errors=False)

    assert len(specs.parameter_errors) > 0
    assert specs.parameter_errors == "ERROR: tax_func_type value ['not_a_functional_form'] not in possible values ['DEP', 'DEP_totalinc', 'GS', 'linear']\n"
    assert len(specs.parameter_warnings) == 0
示例#12
0
def test_update_specification_with_json():
    spec = Specifications()
    new_spec_json = """
        {
            "frisch": 0.3
        }
    """
    spec.update_specifications(new_spec_json)
    assert spec.frisch == 0.3
    assert len(spec.errors) == 0
示例#13
0
def test_implement_reform():
    specs = Specifications()
    new_specs = {'tG1': 30, 'T': 80, 'frisch': 0.3, 'tax_func_type': 'DEP'}

    specs.update_specifications(new_specs)
    assert specs.frisch == 0.3
    assert specs.tG1 == 30
    assert specs.T == 80
    assert specs.tax_func_type == 'DEP'
    assert len(specs.errors) == 0
示例#14
0
def test_get_tax_function_zero_taxes():
    specs = Specifications()
    specs.zero_taxes = True
    tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_baseline.pkl')
    specs.get_tax_function_parameters(None,
                                      run_micro=False,
                                      tax_func_path=tax_func_path)
    assert np.allclose(specs.etr_params, np.zeros((specs.T, specs.S, 12)))
    assert np.allclose(specs.mtrx_params, np.zeros((specs.T, specs.S, 12)))
    assert np.allclose(specs.mtry_params, np.zeros((specs.T, specs.S, 12)))
示例#15
0
def test_implement_bad_reform1():
    specs = Specifications()
    # tG1 has an upper bound at T / 2
    new_specs = {
        'tG1': 50,
        'T': 80,
    }

    specs.update_specifications(new_specs, raise_errors=False)

    assert len(specs.errors) == 0
示例#16
0
def get_inputs(meta_param_dict):
    meta_params = MetaParams()
    meta_params.adjust(meta_param_dict)
    params = Specifications()
    params.start_year = meta_params.year
    return {
        "meta_parameters": meta_params.dump(),
        "model_parameters": {
            "ogusa": params.dump()
        }
    }
示例#17
0
def test_implement_bad_reform2():
    specs = Specifications()
    # tG1 has an upper bound at T / 2
    new_specs = {'T': 80, 'tax_func_type': 'not_a_functional_form'}

    specs.update_specifications(new_specs, raise_errors=False)

    assert len(specs.errors) > 0
    assert specs.errors['tax_func_type'][0] == (
        'tax_func_type "not_a_functional_form" must be in list of ' +
        'choices DEP, DEP_totalinc, GS, linear.')
示例#18
0
def test_get_biz_tax():
    # Test function for business tax receipts
    p = Specifications()
    new_param_values = {'tau_b': [0.20], 'delta_tau_annual': [0.06]}
    p.update_specifications(new_param_values)
    p.T = 3
    w = np.array([1.2, 1.1, 1.2])
    Y = np.array([3.0, 7.0, 3.0])
    L = np.array([2.0, 3.0, 2.0])
    K = np.array([5.0, 6.0, 5.0])
    biz_tax = tax.get_biz_tax(w, Y, L, K, p, 'TPI')
    assert np.allclose(biz_tax, np.array([0.06, 0.668, 0.06]))
def test_implement_bad_reform1():
    specs = Specifications()
    # tG1 has an upper bound at T / 2
    new_specs = {
        'tG1': 50,
        'T': 80,
    }

    specs.update_specifications(new_specs, raise_errors=False)

    assert len(specs.parameter_errors) > 0
    assert specs.parameter_errors == 'ERROR: tG1 value 50 > max value 40.0\n'
    assert len(specs.parameter_warnings) == 0
示例#20
0
def test_constant_demographics_TPI():
    '''
    This tests solves the model under the assumption of constant
    demographics, a balanced budget, and tax functions that do not vary
    over time.
    In this case, given how initial guesss for the time
    path are made, the time path should be solved for on the first
    iteration and the values all along the time path should equal their
    steady-state values.
    '''
    output_base = "./OUTPUT"
    baseline_dir = "./OUTPUT"
    user_params = {'constant_demographics': True,
                   'budget_balance': True,
                   'zero_taxes': True,
                   'maxiter': 2}
    # Create output directory structure
    ss_dir = os.path.join(output_base, "SS")
    tpi_dir = os.path.join(output_base, "TPI")
    dirs = [ss_dir, tpi_dir]
    for _dir in dirs:
        try:
            print("making dir: ", _dir)
            os.makedirs(_dir)
        except OSError as oe:
            pass
    spec = Specifications(run_micro=False, output_base=output_base,
                          baseline_dir=baseline_dir, test=False,
                          time_path=True, baseline=True, reform={},
                          guid='')
    spec.update_specifications(user_params)
    print('path for tax functions: ', spec.output_base)
    spec.get_tax_function_parameters(None, False)
    # Run SS
    ss_outputs = SS.run_SS(spec, None)
    # save SS results
    utils.mkdirs(os.path.join(baseline_dir, "SS"))
    ss_dir = os.path.join(baseline_dir, "SS/SS_vars.pkl")
    pickle.dump(ss_outputs, open(ss_dir, "wb"))
    # Save pickle with parameter values for the run
    param_dir = os.path.join(baseline_dir, "model_params.pkl")
    pickle.dump(spec, open(param_dir, "wb"))
    tpi_output = TPI.run_TPI(spec, None)
    print('Max diff btwn SS and TP bsplus1 = ',
          np.absolute(tpi_output['bmat_splus1'][:spec.T, :, :] -
                      ss_outputs['bssmat_splus1']).max())
    print('Max diff btwn SS and TP Y = ',
          np.absolute(tpi_output['Y'][:spec.T] -
                      ss_outputs['Yss']).max())
    assert(np.allclose(tpi_output['bmat_splus1'][:spec.T, :, :],
                       ss_outputs['bssmat_splus1']))
示例#21
0
def test_get_D_ss(budget_balance, expected_tuple):
    '''
    Test of the fiscla.get_D_ss() function.
    '''
    r_gov = 0.03
    Y = 1.176255339
    p = Specifications()
    p.debt_ratio_ss = 1.2
    p.budget_balance = budget_balance
    p.g_n_ss = 0.02
    test_tuple = fiscal.get_D_ss(r_gov, Y, p)

    for i, v in enumerate(test_tuple):
        assert np.allclose(v, expected_tuple[i])
示例#22
0
def test_get_biz_tax():
    # Test function for business tax receipts
    p = Specifications()
    new_param_values = {
        'tau_b': [0.20],
        'delta_tau_annual': [0.06]
    }
    p.update_specifications(new_param_values)
    p.T = 3
    w = np.array([1.2, 1.1, 1.2])
    Y = np.array([3.0, 7.0, 3.0])
    L = np.array([2.0, 3.0, 2.0])
    K = np.array([5.0, 6.0, 5.0])
    biz_tax = tax.get_biz_tax(w, Y, L, K, p, 'TPI')
    assert np.allclose(biz_tax, np.array([0.06, 0.668, 0.06]))
示例#23
0
def test_get_G_ss(budget_balance, expected_G):
    '''
    Test of the fiscla.get_G_ss() function.
    '''
    Y = 2.2
    total_revenue = 2.3
    TR = 1.6
    new_borrowing = 0.072076633
    debt_service = 0.042345192
    p = Specifications()
    p.budget_balance = budget_balance
    test_G = fiscal.get_G_ss(Y, total_revenue, TR, new_borrowing, debt_service,
                             p)

    assert np.allclose(test_G, expected_G)
示例#24
0
def test_get_tax_function_parameters_constant_rates():
    specs = Specifications()
    specs.constant_rates = True
    tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_baseline.pkl')
    specs.get_tax_function_parameters(None,
                                      run_micro=False,
                                      tax_func_path=tax_func_path)
    assert specs.etr_params.shape == (specs.T, specs.S, 12)
    assert specs.mtrx_params.shape == (specs.T, specs.S, 12)
    assert specs.mtry_params.shape == (specs.T, specs.S, 12)
    assert np.allclose(specs.etr_params[:, :, :10],
                       np.zeros((specs.T, specs.S, 10)))
    assert np.allclose(specs.mtrx_params[:, :, :10],
                       np.zeros((specs.T, specs.S, 10)))
    assert np.allclose(specs.mtry_params[:, :, :10],
                       np.zeros((specs.T, specs.S, 10)))
示例#25
0
def validate_inputs(meta_param_dict, adjustment, errors_warnings):
    # ogusa doesn't look at meta_param_dict for validating inputs.
    params = Specifications()
    params.adjust(adjustment["OG-USA Parameters"], raise_errors=False)
    errors_warnings["OG-USA Parameters"]["errors"].update(params.errors)
    # Validate TC parameter inputs
    pol_params = {}
    # drop checkbox parameters.
    for param, data in list(adjustment["Tax-Calculator Parameters"].items()):
        if not param.endswith("checkbox"):
            pol_params[param] = data
    iit_params = TCParams()
    iit_params.adjust(pol_params, raise_errors=False)
    errors_warnings["Tax-Calculator Parameters"]["errors"].update(
        iit_params.errors)

    return {"errors_warnings": errors_warnings}
def test_get_y():
    '''
    Test of household.get_y() function.
    '''
    r_hh = np.array([0.05, 0.04, 0.09])
    w = np.array([1.2, 0.8, 2.5])
    b_s = np.array([0.5, 0.99, 9])
    n = np.array([0.8, 3.2, 0.2])
    expected_y = np.array([0.9754, 3.8796, 0.91])
    p = Specifications()
    # p.update_specifications({'S': 4, 'J': 1})
    p.S = 3
    p.e = np.array([0.99, 1.5, 0.2])

    test_y = household.get_y(r_hh, w, b_s, n, p)

    assert np.allclose(test_y, expected_y)
示例#27
0
def test_SS_solver(baseline, param_updates, filename, dask_client):
    # Test SS.SS_solver function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    p = Specifications(baseline=baseline,
                       client=dask_client,
                       num_workers=NUM_WORKERS)
    p.update_specifications(param_updates)
    p.output_base = CUR_PATH
    p.get_tax_function_parameters(None, run_micro=False)
    b_guess = np.ones((p.S, p.J)) * 0.07
    n_guess = np.ones((p.S, p.J)) * .35 * p.ltilde
    if p.zeta_K[-1] == 1.0:
        rguess = p.world_int_rate[-1]
    else:
        rguess = 0.06483431412921253
    TRguess = 0.05738932081035772
    factorguess = 139355.1547340256
    BQguess = aggregates.get_BQ(rguess, b_guess, None, p, 'SS', False)
    Yguess = 0.6376591201150815

    test_dict = SS.SS_solver(b_guess, n_guess, rguess, BQguess, TRguess,
                             factorguess, Yguess, p, None, False)
    expected_dict = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', filename))

    for k, v in expected_dict.items():
        print('Testing ', k)
        assert (np.allclose(test_dict[k], v, atol=1e-07, equal_nan=True))
示例#28
0
def test_inner_loop(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,
                       client=dask_client,
                       num_workers=NUM_WORKERS)
    p.update_specifications(param_updates)
    p.output_base = CUR_PATH
    p.get_tax_function_parameters(None, run_micro=False)
    bssmat = np.ones((p.S, p.J)) * 0.07
    nssmat = np.ones((p.S, p.J)) * .4 * p.ltilde
    if p.zeta_K[-1] == 1.0:
        r = p.world_int_rate[-1]
    else:
        r = 0.05
    TR = 0.12
    Y = 1.3
    factor = 100000
    BQ = np.ones(p.J) * 0.00019646295986015257
    if p.budget_balance:
        outer_loop_vars = (bssmat, nssmat, r, BQ, TR, factor)
    else:
        outer_loop_vars = (bssmat, nssmat, r, BQ, Y, TR, factor)
    test_tuple = SS.inner_loop(outer_loop_vars, p, None)
    expected_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', filename))
    for i, v in enumerate(expected_tuple):
        assert (np.allclose(test_tuple[i], v, atol=1e-05))
示例#29
0
def test_get_TR(baseline, budget_balance, baseline_spending, method,
                expected_TR):
    '''
    Test of the fiscal.get_TR() function.
    '''
    Y = 3.2
    TR = 1.5
    G = 0.0
    total_revenue = 1.9
    p = Specifications(baseline=baseline)
    p.budget_balance = budget_balance
    p.baseline_spending = baseline_spending
    if method == 'TPI':
        Y = np.ones(p.T * p.S) * Y
        TR = np.ones(p.T * p.S) * TR
        total_revenue = np.ones(p.T * p.S) * total_revenue
    test_TR = fiscal.get_TR(Y, TR, G, total_revenue, p, method)

    assert np.allclose(test_TR, expected_TR)
示例#30
0
def test_resource_constraint():
    """
    Test resource constraint equation.
    """
    p = Specifications()
    p.delta = 0.05
    Y = np.array([48, 55, 2, 99, 8])
    C = np.array([33, 44, 0.4, 55, 6])
    G = np.array([4, 5, 0.01, 22, 0])
    I = np.array([20, 5, 0.6, 10, 1])
    K_f = np.array([0, 0, 0.2, 3, 0.05])
    new_borrowing_f = np.array([0, 0.1, 0.3, 4, 0.5])
    debt_service_f = np.array([0.1, 0.1, 0.3, 2, 0.02])
    r = np.array([0.03, 0.04, 0.03, 0.06, 0.01])
    expected = np.array([-9.1, 1, 0.974, 13.67, 1.477])
    test_RC = aggr.resource_constraint(Y, C, G, I, K_f, new_borrowing_f,
                                       debt_service_f, r, p)

    assert (np.allclose(test_RC, expected))
示例#31
0
def test_run_SS(baseline, param_updates, filename, dask_client):
    # Test SS.run_SS function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    if baseline is False:
        tax_func_path_baseline = os.path.join(CUR_PATH,
                                              'TxFuncEst_baseline.pkl')
        tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_policy.pkl')
        execute.runner(constants.BASELINE_DIR,
                       constants.BASELINE_DIR,
                       time_path=False,
                       baseline=True,
                       og_spec=param_updates,
                       run_micro=False,
                       tax_func_path=tax_func_path_baseline)
    else:
        tax_func_path = os.path.join(CUR_PATH, 'TxFuncEst_baseline.pkl')
    p = Specifications(baseline=baseline,
                       client=dask_client,
                       num_workers=NUM_WORKERS)
    p.update_specifications(param_updates)
    p.get_tax_function_parameters(None,
                                  run_micro=False,
                                  tax_func_path=tax_func_path)
    test_dict = SS.run_SS(p, None)
    expected_dict = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', filename))

    for k, v in expected_dict.items():
        assert (np.allclose(test_dict[k], v))
示例#32
0
def test_get_initial_SS_values(baseline, param_updates, filename, dask_client):
    p = Specifications(baseline=baseline,
                       test=False,
                       client=dask_client,
                       num_workers=NUM_WORKERS)
    p.update_specifications(param_updates)
    p.baseline_dir = os.path.join(CUR_PATH, 'test_io_data', 'OUTPUT')
    p.output_base = os.path.join(CUR_PATH, 'test_io_data', 'OUTPUT')
    test_tuple = TPI.get_initial_SS_values(p)
    (test_initial_values, test_ss_vars, test_theta,
     test_baseline_values) = test_tuple
    expected_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', filename))

    (exp_initial_values, exp_ss_vars, exp_theta,
     exp_baseline_values) = expected_tuple

    for i, v in enumerate(exp_initial_values):
        assert (np.allclose(test_initial_values[i], v, equal_nan=True))

    if p.baseline_spending:
        for i, v in enumerate(exp_baseline_values):
            assert (np.allclose(test_baseline_values[i], v, equal_nan=True))

    assert (np.allclose(test_theta, exp_theta))

    for k, v in exp_ss_vars.items():
        assert (np.allclose(test_ss_vars[k], v, equal_nan=True))
示例#33
0
def test_run_TPI(baseline, param_updates, filename, tmp_path, dask_client):
    '''
    Test TPI.run_TPI function.  Provide inputs to function and
    ensure that output returned matches what it has been before.
    '''
    baseline_dir = os.path.join(CUR_PATH, 'baseline')
    if baseline:
        output_base = baseline_dir
    else:
        output_base = os.path.join(CUR_PATH, 'reform')
    p = Specifications(baseline=baseline,
                       baseline_dir=baseline_dir,
                       output_base=output_base,
                       test=True,
                       client=dask_client,
                       num_workers=NUM_WORKERS)
    p.update_specifications(param_updates)
    p.maxiter = 2  # this test runs through just two iterations
    p.get_tax_function_parameters(None,
                                  run_micro=False,
                                  tax_func_path=os.path.join(
                                      CUR_PATH, '..', 'data', 'tax_functions',
                                      'TxFuncEst_baseline_CPS.pkl'))

    # Need to run SS first to get results
    SS.ENFORCE_SOLUTION_CHECKS = False
    ss_outputs = SS.run_SS(p, None)

    if p.baseline:
        utils.mkdirs(os.path.join(p.baseline_dir, "SS"))
        ss_dir = os.path.join(p.baseline_dir, "SS", "SS_vars.pkl")
        with open(ss_dir, "wb") as f:
            pickle.dump(ss_outputs, f)
    else:
        utils.mkdirs(os.path.join(p.output_base, "SS"))
        ss_dir = os.path.join(p.output_base, "SS", "SS_vars.pkl")
        with open(ss_dir, "wb") as f:
            pickle.dump(ss_outputs, f)

    TPI.ENFORCE_SOLUTION_CHECKS = False
    test_dict = TPI.run_TPI(p, None)
    expected_dict = utils.safe_read_pickle(filename)

    for k, v in expected_dict.items():
        try:
            assert (np.allclose(test_dict[k][:p.T],
                                v[:p.T],
                                rtol=1e-04,
                                atol=1e-04))
        except ValueError:
            assert (np.allclose(test_dict[k][:p.T, :, :],
                                v[:p.T, :, :],
                                rtol=1e-04,
                                atol=1e-04))
示例#34
0
        'budget_balance': False,
        'baseline_spending': baseline_spending
    }
    p.update_specifications(new_param_values, raise_errors=False)
    r_gov = np.ones(p.T + p.S) * 0.03
    p.g_n = np.ones(p.T + p.S) * 0.02
    D0 = 0.59
    G0 = 0.05
    dg_fixed_values = (Y, REVENUE, T_H, D0, G0)
    test_D, test_G = fiscal.D_G_path(r_gov, dg_fixed_values, Gbaseline,
                                     p)
    assert np.allclose(test_D, D_expected)
    assert np.allclose(test_G, G_expected)


p1 = Specifications()
p1.r_gov_scale = 0.5
p1.r_gov_shift = 0.0
p2 = Specifications()
p2.r_gov_scale = 0.5
p2.r_gov_shift = 0.01
p3 = Specifications()
p3.r_gov_scale = 0.5
p3.r_gov_shift = 0.03
r = 0.04
r_gov1 = 0.02
r_gov2 = 0.01
r_gov3 = 0.0


@pytest.mark.parametrize('r,p,r_gov_expected',
示例#35
0
def test_run_SS(input_path, expected_path):
    # Test SS.run_SS function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', input_path))
    (income_tax_params, ss_params, iterative_params, chi_params,
     small_open_params, baseline, baseline_spending, baseline_dir) =\
        input_tuple
    p = Specifications()
    (p.J, p.S, p.T, p.BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n_ss, tau_payroll,
     tau_bq, p.rho, p.omega_SS, p.budget_balance, alpha_T,
     p.debt_ratio_ss, tau_b, delta_tau, lambdas, imm_rates, p.e,
     retire, p.mean_income_data, h_wealth, p_wealth, m_wealth,
     p.b_ellipse, p.upsilon) = ss_params
    p.Z = np.ones(p.T + p.S) * Z
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.alpha_T = np.ones(p.T + p.S) * alpha_T
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.lambdas = lambdas.reshape(p.J, 1)
    p.imm_rates = imm_rates.reshape(1, p.S)
    p.tax_func_type = 'DEP'
    p.baseline = baseline
    p.baseline_spending = baseline_spending
    p.baseline_dir = baseline_dir
    p.analytical_mtrs, etr_params, mtrx_params, mtry_params =\
        income_tax_params
    p.etr_params = np.transpose(etr_params.reshape(
        p.S, 1, etr_params.shape[-1]), (1, 0, 2))
    p.mtrx_params = np.transpose(mtrx_params.reshape(
        p.S, 1, mtrx_params.shape[-1]), (1, 0, 2))
    p.mtry_params = np.transpose(mtry_params.reshape(
        p.S, 1, mtry_params.shape[-1]), (1, 0, 2))
    p.maxiter, p.mindist_SS = iterative_params
    p.chi_b, p.chi_n = chi_params
    p.small_open, firm_r, hh_r = small_open_params
    p.firm_r = np.ones(p.T + p.S) * firm_r
    p.hh_r = np.ones(p.T + p.S) * hh_r
    p.num_workers = 1
    test_dict = SS.run_SS(p, None)

    expected_dict = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data', expected_path))

    # delete values key-value pairs that are not in both dicts
    del expected_dict['bssmat'], expected_dict['chi_n'], expected_dict['chi_b']
    del test_dict['etr_ss'], test_dict['mtrx_ss'], test_dict['mtry_ss']
    test_dict['IITpayroll_revenue'] = (test_dict['total_revenue_ss'] -
                                       test_dict['business_revenue'])
    del test_dict['T_Pss'], test_dict['T_BQss'], test_dict['T_Wss']
    del test_dict['resource_constraint_error'], test_dict['T_Css']
    del test_dict['r_gov_ss'], test_dict['r_hh_ss']
    test_dict['revenue_ss'] = test_dict.pop('total_revenue_ss')

    for k, v in expected_dict.items():
        assert(np.allclose(test_dict[k], v))
示例#36
0
def test_euler_equation_solver():
    # Test SS.inner_loop function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/euler_eqn_solver_inputs.pkl'))
    (guesses, params) = input_tuple
    p = Specifications()
    (r, w, T_H, factor, j, p.J, p.S, p.beta, p.sigma, p.ltilde, p.g_y,
     p.g_n_ss, tau_payroll, retire, p.mean_income_data, h_wealth,
     p_wealth, m_wealth, p.b_ellipse, p.upsilon, j, p.chi_b,
     p.chi_n, tau_bq, p.rho, lambdas, p.omega_SS, p.e,
     p.analytical_mtrs, etr_params, mtrx_params, mtry_params) = params
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.etr_params = np.transpose(etr_params.reshape(
        p.S, 1, etr_params.shape[-1]), (1, 0, 2))
    p.mtrx_params = np.transpose(mtrx_params.reshape(
        p.S, 1, mtrx_params.shape[-1]), (1, 0, 2))
    p.mtry_params = np.transpose(mtry_params.reshape(
        p.S, 1, mtry_params.shape[-1]), (1, 0, 2))
    p.tax_func_type = 'DEP'
    p.lambdas = lambdas.reshape(p.J, 1)
    b_splus1 = np.array(guesses[:p.S]).reshape(p.S, 1) + 0.005
    BQ = aggregates.get_BQ(r, b_splus1, j, p, 'SS', False)
    bq = household.get_bq(BQ, j, p, 'SS')
    args = (r, w, bq, T_H, factor, j, p)
    test_list = SS.euler_equation_solver(guesses, *args)

    expected_list = np.array([
        -3.62741663e+00, -6.30068841e+00, -6.76592886e+00,
        -6.97731223e+00, -7.05777777e+00, -6.57305440e+00,
        -7.11553046e+00, -7.30569622e+00, -7.45808107e+00,
        -7.89984062e+00, -8.11466111e+00, -8.28230086e+00,
        -8.79253862e+00, -8.86994311e+00, -9.31299476e+00,
        -9.80834199e+00, -9.97333771e+00, -1.08349979e+01,
        -1.13199826e+01, -1.22890930e+01, -1.31550471e+01,
        -1.42753713e+01, -1.55721098e+01, -1.73811490e+01,
        -1.88856303e+01, -2.09570569e+01, -2.30559500e+01,
        -2.52127149e+01, -2.76119605e+01, -3.03141128e+01,
        -3.30900203e+01, -3.62799730e+01, -3.91169706e+01,
        -4.24246421e+01, -4.55740527e+01, -4.92914871e+01,
        -5.30682805e+01, -5.70043846e+01, -6.06075991e+01,
        -6.45251018e+01, -6.86128365e+01, -7.35896515e+01,
        -7.92634608e+01, -8.34733231e+01, -9.29802390e+01,
        -1.01179788e+02, -1.10437881e+02, -1.20569527e+02,
        -1.31569973e+02, -1.43633399e+02, -1.57534056e+02,
        -1.73244610e+02, -1.90066728e+02, -2.07980863e+02,
        -2.27589046e+02, -2.50241670e+02, -2.76314755e+02,
        -3.04930986e+02, -3.36196973e+02, -3.70907934e+02,
        -4.10966644e+02, -4.56684022e+02, -5.06945218e+02,
        -5.61838645e+02, -6.22617808e+02, -6.90840503e+02,
        -7.67825713e+02, -8.54436805e+02, -9.51106365e+02,
        -1.05780305e+03, -1.17435473e+03, -1.30045062e+03,
        -1.43571221e+03, -1.57971603e+03, -1.73204264e+03,
        -1.88430524e+03, -2.03403679e+03, -2.17861987e+03,
        -2.31532884e+03, -8.00654731e+03, -5.21487172e-02,
        -2.80234170e-01, 4.93894552e-01, 3.11884938e-01, 6.55799607e-01,
        5.62182419e-01,  3.86074983e-01,  3.43741491e-01,  4.22461089e-01,
        3.63707951e-01,  4.93150010e-01,  4.72813688e-01,  4.07390308e-01,
        4.94974186e-01,  4.69900128e-01,  4.37562389e-01,  5.67370182e-01,
        4.88965362e-01,  6.40728461e-01,  6.14619979e-01,  4.97173823e-01,
        6.19549666e-01,  6.51193557e-01,  4.48906118e-01,  7.93091492e-01,
        6.51249363e-01,  6.56307713e-01,  1.12948552e+00,  9.50018058e-01,
        6.79613030e-01,  9.51359123e-01,  6.31059147e-01,  7.97896887e-01,
        8.44620817e-01,  7.43683837e-01,  1.56693187e+00,  2.75630011e-01,
        5.32956891e-01,  1.57110727e+00,  1.22674610e+00, 4.63932928e-01,
        1.47225464e+00,  1.16948107e+00,  1.07965795e+00, -3.20557791e-01,
        -1.17064127e+00, -7.84880649e-01, -7.60851182e-01, -1.61415945e+00,
        -8.30363975e-01, -1.68459409e+00, -1.49260581e+00, -1.84257084e+00,
        -1.72143079e+00, -1.43131579e+00, -1.63719219e+00, -1.43874851e+00,
        -1.57207905e+00, -1.72909159e+00, -1.98778122e+00, -1.80843826e+00,
        -2.12828312e+00, -2.24768762e+00, -2.36961877e+00, -2.49117258e+00,
        -2.59914065e+00, -2.82309085e+00, -2.93613362e+00, -3.34446991e+00,
        -3.45445086e+00, -3.74962140e+00, -3.78113417e+00, -4.55643800e+00,
        -4.86929016e+00, -5.08657898e+00, -5.22054177e+00, -5.54606515e+00,
        -5.78478304e+00, -5.93652041e+00, -6.11519786e+00])

    assert(np.allclose(np.array(test_list), np.array(expected_list)))
示例#37
0
def test_inner_loop():
    # Test SS.inner_loop function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/inner_loop_inputs.pkl'))
    (outer_loop_vars_in, params, baseline, baseline_spending) = input_tuple
    ss_params, income_tax_params, chi_params, small_open_params = params
    (bssmat, nssmat, r, Y, T_H, factor) = outer_loop_vars_in
    p = Specifications()
    (p.J, p.S, p.T, p.BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n_ss, tau_payroll,
     tau_bq, p.rho, p.omega_SS, p.budget_balance, alpha_T,
     p.debt_ratio_ss, tau_b, delta_tau, lambdas, imm_rates, p.e,
     retire, p.mean_income_data, h_wealth, p_wealth, m_wealth,
     p.b_ellipse, p.upsilon) = ss_params
    p.Z = np.ones(p.T + p.S) * Z
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.alpha_T = np.ones(p.T + p.S) * alpha_T
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.lambdas = lambdas.reshape(p.J, 1)
    p.imm_rates = imm_rates.reshape(1, p.S)
    p.tax_func_type = 'DEP'
    p.baseline = baseline
    p.baseline_spending = baseline_spending
    p.analytical_mtrs, etr_params, mtrx_params, mtry_params =\
        income_tax_params
    p.etr_params = np.transpose(etr_params.reshape(
        p.S, 1, etr_params.shape[-1]), (1, 0, 2))
    p.mtrx_params = np.transpose(mtrx_params.reshape(
        p.S, 1, mtrx_params.shape[-1]), (1, 0, 2))
    p.mtry_params = np.transpose(mtry_params.reshape(
        p.S, 1, mtry_params.shape[-1]), (1, 0, 2))
    p.chi_b, p.chi_n = chi_params
    p.small_open, firm_r, hh_r = small_open_params
    p.firm_r = np.ones(p.T + p.S) * firm_r
    p.hh_r = np.ones(p.T + p.S) * hh_r
    p.num_workers = 1
    BQ = np.ones(p.J) * 0.00019646295986015257
    outer_loop_vars = (bssmat, nssmat, r, BQ, Y, T_H, factor)
    (euler_errors, new_bmat, new_nmat, new_r, new_r_gov, new_r_hh,
     new_w, new_T_H, new_Y, new_factor, new_BQ,
     average_income_model) = SS.inner_loop(outer_loop_vars, p, None)
    test_tuple = (euler_errors, new_bmat, new_nmat, new_r, new_w,
                  new_T_H, new_Y, new_factor, new_BQ,
                  average_income_model)

    expected_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/inner_loop_outputs.pkl'))

    for i, v in enumerate(expected_tuple):
        assert(np.allclose(test_tuple[i], v, atol=1e-05))
示例#38
0
from __future__ import print_function
import pytest
import numpy as np
import os
from ogusa import SS, utils, aggregates, household
from ogusa.parameters import Specifications
CUR_PATH = os.path.abspath(os.path.dirname(__file__))

input_tuple = utils.safe_read_pickle(
    os.path.join(CUR_PATH, 'test_io_data/SS_fsolve_inputs.pkl'))
guesses_in, params = input_tuple
params = params + (None, 1)
(bssmat, nssmat, chi_params, ss_params, income_tax_params,
 iterative_params, small_open_params, client, num_workers) = params
p1 = Specifications()
(p1.J, p1.S, p1.T, p1.BW, p1.beta, p1.sigma, p1.alpha, p1.gamma, p1.epsilon,
 Z, p1.delta, p1.ltilde, p1.nu, p1.g_y, p1.g_n_ss, tau_payroll,
 tau_bq, p1.rho, p1.omega_SS, p1.budget_balance, alpha_T,
 p1.debt_ratio_ss, tau_b, delta_tau, lambdas, imm_rates, p1.e,
 retire, p1.mean_income_data, h_wealth, p_wealth, m_wealth,
 p1.b_ellipse, p1.upsilon) = ss_params
p1.Z = np.ones(p1.T + p1.S) * Z
p1.tau_bq = np.ones(p1.T + p1.S) * 0.0
p1.tau_payroll = np.ones(p1.T + p1.S) * tau_payroll
p1.alpha_T = np.ones(p1.T + p1.S) * alpha_T
p1.tau_b = np.ones(p1.T + p1.S) * tau_b
p1.delta_tau = np.ones(p1.T + p1.S) * delta_tau
p1.h_wealth = np.ones(p1.T + p1.S) * h_wealth
p1.p_wealth = np.ones(p1.T + p1.S) * p_wealth
p1.m_wealth = np.ones(p1.T + p1.S) * m_wealth
p1.retire = (np.ones(p1.T + p1.S) * retire).astype(int)
示例#39
0
import numpy as np
import copy
import pytest
from ogusa import tax
from ogusa.parameters import Specifications


p = Specifications()
new_param_values = {
    'S': 4,
    'J': 1,
    'T': 4,
}
p.update_specifications(new_param_values)
p.retire = [3, 3, 3, 3, 3, 3, 3, 3]
p1 = copy.deepcopy(p)
p2 = copy.deepcopy(p)
p3 = copy.deepcopy(p)
# Use just a column of e
p1.e = np.transpose(np.array([[0.1, 0.3, 0.5, 0.2], [0.1, 0.3, 0.5, 0.2]]))
# e has two dimensions
p2.e = np.array([[0.4, 0.3], [0.5, 0.4], [.6, .4], [.4, .3]])
p3.e = np.array([[0.35, 0.3], [0.55, 0.4], [.65, .4], [.45, .3]])
p5 = copy.deepcopy(p3)
p5.PIA_minpayment = 125.0
wss = 0.5
n1 = np.array([0.5, 0.5, 0.5, 0.5])
n2 = nssmat = np.array([[0.4, 0.4], [0.4, 0.4], [0.4, 0.4], [0.4, 0.4]])
n3 = nssmat = np.array([[0.3, .35], [0.3, .35], [0.3, .35], [0.3, .35]])
factor1 = 100000
factor3 = 10000
示例#40
0
def test_inner_loop():
    # Test TPI.inner_loop function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/tpi_inner_loop_inputs.pkl'))
    guesses, outer_loop_vars, params, j = input_tuple
    income_tax_params, tpi_params, initial_values, ind = params
    initial_values = initial_values
    tpi_params = tpi_params
    p = Specifications()
    (p.J, p.S, p.T, p.BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n, tau_b, delta_tau,
     tau_payroll, tau_bq, p.rho, p.omega, N_tilde, lambdas,
     p.imm_rates, p.e, retire, p.mean_income_data, factor, h_wealth,
     p_wealth, m_wealth, p.b_ellipse, p.upsilon, p.chi_b, p.chi_n,
     theta, p.baseline) = tpi_params
    p.Z = np.ones(p.T + p.S) * Z
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.tax_func_type = 'DEP'
    p.analytical_mtrs, etr_params, mtrx_params, mtry_params =\
        income_tax_params
    p.etr_params = np.transpose(etr_params, (1, 0, 2))[:p.T, :, :]
    p.mtrx_params = np.transpose(mtrx_params, (1, 0, 2))[:p.T, :, :]
    p.mtry_params = np.transpose(mtry_params, (1, 0, 2))[:p.T, :, :]
    p.lambdas = lambdas.reshape(p.J, 1)
    p.num_workers = 1
    (K0, b_sinit, b_splus1init, factor, initial_b, initial_n,
     p.omega_S_preTP, initial_debt, D0) = initial_values
    initial_values_in = (K0, b_sinit, b_splus1init, factor, initial_b,
                         initial_n, D0)
    (r, K, BQ, T_H) = outer_loop_vars
    wss = firm.get_w_from_r(r[-1], p, 'SS')
    w = np.ones(p.T + p.S) * wss
    w[:p.T] = firm.get_w_from_r(r[:p.T], p, 'TPI')
    outer_loop_vars_in = (r, w, r, BQ, T_H, theta)

    guesses = (guesses[0], guesses[1])
    test_tuple = TPI.inner_loop(guesses, outer_loop_vars_in,
                                initial_values_in, j, ind, p)

    expected_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/tpi_inner_loop_outputs.pkl'))

    for i, v in enumerate(expected_tuple):
        assert(np.allclose(test_tuple[i], v))
示例#41
0
def test_twist_doughnut():
    # Test TPI.twist_doughnut function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/twist_doughnut_inputs.pkl'))
    guesses, r, w, BQ, T_H, j, s, t, params = input_tuple
    income_tax_params, tpi_params, initial_b = params
    tpi_params = tpi_params + [True]
    p = Specifications()
    (p.J, p.S, p.T, p.BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n, tau_b, delta_tau,
     tau_payroll, tau_bq, p.rho, p.omega, N_tilde, lambdas,
     p.imm_rates, p.e, retire, p.mean_income_data, factor, h_wealth,
     p_wealth, m_wealth, p.b_ellipse, p.upsilon, p.chi_b, p.chi_n,
     theta, p.baseline) = tpi_params
    p.Z = np.ones(p.T + p.S) * Z
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_c = np.ones((p.T + p.S, p.S, p.J)) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.tax_func_type = 'DEP'
    p.analytical_mtrs, etr_params, mtrx_params, mtry_params =\
        income_tax_params
    p.lambdas = lambdas.reshape(p.J, 1)
    p.num_workers = 1
    length = int(len(guesses) / 2)
    tau_c_to_use = np.diag(p.tau_c[:p.S, :, j], p.S - (s + 2))
    bq = BQ[t:t + length] / p.lambdas[j]
    test_list = TPI.twist_doughnut(guesses, r, w, bq, T_H, theta,
                                   factor, j, s, t, tau_c_to_use,
                                   etr_params, mtrx_params, mtry_params,
                                   initial_b, p)
    expected_list = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/twist_doughnut_outputs.pkl'))

    assert(np.allclose(np.array(test_list), np.array(expected_list)))
示例#42
0
def test_run_TPI():
    # Test TPI.run_TPI function.  Provide inputs to function and
    # ensure that output returned matches what it has been before.
    input_tuple = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/run_TPI_inputs.pkl'))
    (income_tax_params, tpi_params, iterative_params, small_open_params,
     initial_values, SS_values, fiscal_params, biz_tax_params,
     output_dir, baseline_spending) = input_tuple
    tpi_params = tpi_params + [True]
    initial_values = initial_values + (0.0,)

    p = Specifications()
    (J, S, T, BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n, tau_b, delta_tau,
     tau_payroll, tau_bq, p.rho, p.omega, N_tilde, lambdas,
     p.imm_rates, p.e, retire, p.mean_income_data, factor, h_wealth,
     p_wealth, m_wealth, p.b_ellipse, p.upsilon, p.chi_b, p.chi_n,
     theta, p.baseline) = tpi_params

    new_param_values = {
        'J': J,
        'S': S,
        'T': T
    }
    # update parameters instance with new values for test
    p.update_specifications(new_param_values, raise_errors=False)
    (J, S, T, BW, p.beta, p.sigma, p.alpha, p.gamma, p.epsilon,
     Z, p.delta, p.ltilde, p.nu, p.g_y, p.g_n, tau_b, delta_tau,
     tau_payroll, tau_bq, p.rho, p.omega, N_tilde, lambdas,
     p.imm_rates, p.e, retire, p.mean_income_data, factor, h_wealth,
     p_wealth, m_wealth, p.b_ellipse, p.upsilon, p.chi_b, p.chi_n,
     theta, p.baseline) = tpi_params
    p.Z = np.ones(p.T + p.S) * Z
    p.tau_bq = np.ones(p.T + p.S) * 0.0
    p.tau_payroll = np.ones(p.T + p.S) * tau_payroll
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.h_wealth = np.ones(p.T + p.S) * h_wealth
    p.p_wealth = np.ones(p.T + p.S) * p_wealth
    p.m_wealth = np.ones(p.T + p.S) * m_wealth
    p.retire = (np.ones(p.T + p.S) * retire).astype(int)
    p.small_open, ss_firm_r, ss_hh_r = small_open_params
    p.ss_firm_r = np.ones(p.T + p.S) * ss_firm_r
    p.ss_hh_r = np.ones(p.T + p.S) * ss_hh_r
    p.maxiter, p.mindist_SS, p.mindist_TPI = iterative_params
    (p.budget_balance, alpha_T, alpha_G, p.tG1, p.tG2, p.rho_G,
     p.debt_ratio_ss) = fiscal_params
    p.alpha_T = np.concatenate((alpha_T, np.ones(40) * alpha_T[-1]))
    p.alpha_G = np.concatenate((alpha_G, np.ones(40) * alpha_G[-1]))
    (tau_b, delta_tau) = biz_tax_params
    p.tau_b = np.ones(p.T + p.S) * tau_b
    p.delta_tau = np.ones(p.T + p.S) * delta_tau
    p.analytical_mtrs, etr_params, mtrx_params, mtry_params =\
        income_tax_params
    p.etr_params = np.transpose(etr_params, (1, 0, 2))[:p.T, :, :]
    p.mtrx_params = np.transpose(mtrx_params, (1, 0, 2))[:p.T, :, :]
    p.mtry_params = np.transpose(mtry_params, (1, 0, 2))[:p.T, :, :]
    p.lambdas = lambdas.reshape(p.J, 1)
    p.output = output_dir
    p.baseline_spending = baseline_spending
    p.num_workers = 1
    (K0, b_sinit, b_splus1init, factor, initial_b, initial_n,
     p.omega_S_preTP, initial_debt, D0) = initial_values

    # Need to run SS first to get results
    ss_outputs = SS.run_SS(p, None)

    if p.baseline:
        utils.mkdirs(os.path.join(p.baseline_dir, "SS"))
        ss_dir = os.path.join(p.baseline_dir, "SS/SS_vars.pkl")
        pickle.dump(ss_outputs, open(ss_dir, "wb"))
    else:
        utils.mkdirs(os.path.join(p.output_base, "SS"))
        ss_dir = os.path.join(p.output_base, "SS/SS_vars.pkl")
        pickle.dump(ss_outputs, open(ss_dir, "wb"))

    test_dict = TPI.run_TPI(p, None)

    expected_dict = utils.safe_read_pickle(
        os.path.join(CUR_PATH, 'test_io_data/run_TPI_outputs.pkl'))

    # delete values key-value pairs that are not in both dicts
    del test_dict['etr_path'], test_dict['mtrx_path'], test_dict['mtry_path']
    del test_dict['bmat_s']
    test_dict['b_mat'] = test_dict.pop('bmat_splus1')
    test_dict['REVENUE'] = test_dict.pop('total_revenue')
    test_dict['IITpayroll_revenue'] = (test_dict['REVENUE'][:160] -
                                       test_dict['business_revenue'])
    del test_dict['T_P'], test_dict['T_BQ'], test_dict['T_W']
    del test_dict['resource_constraint_error'], test_dict['T_C']
    del test_dict['r_gov'], test_dict['r_hh']

    for k, v in expected_dict.items():
        try:
            assert(np.allclose(test_dict[k], v, rtol=1e-04, atol=1e-04))
        except ValueError:
            assert(np.allclose(test_dict[k], v[:p.T, :, :], rtol=1e-04,
                               atol=1e-04))
示例#43
0
def runner(output_base, baseline_dir, test=False, time_path=True,
           baseline=True, reform={}, user_params={}, guid='',
           run_micro=True, data=None, client=None, num_workers=1):

    tick = time.time()
    # Create output directory structure
    ss_dir = os.path.join(output_base, "SS")
    tpi_dir = os.path.join(output_base, "TPI")
    dirs = [ss_dir, tpi_dir]
    for _dir in dirs:
        try:
            print("making dir: ", _dir)
            os.makedirs(_dir)
        except OSError:
            pass

    print('In runner, baseline is ', baseline)

    # Get parameter class
    # Note - set run_micro false when initially load class
    # Update later with call to spec.get_tax_function_parameters()
    spec = Specifications(run_micro=False, output_base=output_base,
                          baseline_dir=baseline_dir, test=test,
                          time_path=time_path, baseline=baseline,
                          reform=reform, guid=guid, data=data,
                          client=client, num_workers=num_workers)

    spec.update_specifications(user_params)
    print('path for tax functions: ', spec.output_base)
    spec.get_tax_function_parameters(client, run_micro)

    '''
    ------------------------------------------------------------------------
        Run SS
    ------------------------------------------------------------------------
    '''
    ss_outputs = SS.run_SS(spec, client=client)

    '''
    ------------------------------------------------------------------------
        Pickle SS results
    ------------------------------------------------------------------------
    '''
    if baseline:
        utils.mkdirs(os.path.join(baseline_dir, "SS"))
        ss_dir = os.path.join(baseline_dir, "SS/SS_vars.pkl")
        pickle.dump(ss_outputs, open(ss_dir, "wb"))
        # Save pickle with parameter values for the run
        param_dir = os.path.join(baseline_dir, "model_params.pkl")
        pickle.dump(spec, open(param_dir, "wb"))
    else:
        utils.mkdirs(os.path.join(output_base, "SS"))
        ss_dir = os.path.join(output_base, "SS/SS_vars.pkl")
        pickle.dump(ss_outputs, open(ss_dir, "wb"))
        # Save pickle with parameter values for the run
        param_dir = os.path.join(output_base, "model_params.pkl")
        pickle.dump(spec, open(param_dir, "wb"))

    if time_path:
        '''
        ------------------------------------------------------------------------
            Run the TPI simulation
        ------------------------------------------------------------------------
        '''
        tpi_output = TPI.run_TPI(spec, client=client)

        '''
        ------------------------------------------------------------------------
            Pickle TPI results
        ------------------------------------------------------------------------
        '''
        tpi_dir = os.path.join(output_base, "TPI")
        utils.mkdirs(tpi_dir)
        tpi_vars = os.path.join(tpi_dir, "TPI_vars.pkl")
        pickle.dump(tpi_output, open(tpi_vars, "wb"))

        print("Time path iteration complete.")
    print("It took {0} seconds to get that part done.".format(
        time.time() - tick))