def test_graph(reformfile1):
    """
    Test TaxCalcIO with output_graph=True.
    """
    # create graphable input
    nobs = 100
    idict = dict()
    idict['RECID'] = [i for i in range(1, nobs + 1)]
    idict['MARS'] = [2 for i in range(1, nobs + 1)]
    idict['s006'] = [10.0 for i in range(1, nobs + 1)]
    idict['e00300'] = [10000 * i for i in range(1, nobs + 1)]
    idict['_expanded_income'] = idict['e00300']
    idf = pd.DataFrame(idict, columns=list(idict))
    # create TaxCalcIO graph files
    tcio = TaxCalcIO(input_data=idf,
                     tax_year=2020,
                     reform=reformfile1.name,
                     assump=None,
                     growdiff_response=None,
                     aging_input_data=False,
                     exact_calculations=False)
    tcio.static_analysis(writing_output_file=False,
                         output_graph=True)
    # delete graph files
    output_filename = tcio.output_filepath()
    fname = output_filename.replace('.csv', '-atr.html')
    if os.path.isfile(fname):
        os.remove(fname)
    fname = output_filename.replace('.csv', '-mtr.html')
    if os.path.isfile(fname):
        os.remove(fname)
Example #2
0
def test_custom_dump_variables(dumpvar_str, str_valid, num_vars):
    """
    Test TaxCalcIO custom_dump_variables method.
    """
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    year = 2018
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=year,
                     baseline=None,
                     reform=None,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=recdf,
              tax_year=year,
              baseline=None,
              reform=None,
              assump=None,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    varset = tcio.custom_dump_variables(dumpvar_str)
    assert isinstance(varset, set)
    valid = len(tcio.errmsg) == 0
    assert valid == str_valid
    if valid:
        assert len(varset) == num_vars
def test_creation_with_aging(rawinputfile, reformfile0):
    """
    Test TaxCalcIO instantiation with/without no policy reform and with aging.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     reform=reformfile0.name,
                     assump=None)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              reform=reformfile0.name,
              assump=None,
              growdiff_response=Growdiff(),
              aging_input_data=True,
              exact_calculations=False)
    assert len(tcio.errmsg) == 0
    assert tcio.tax_year() == taxyear
    taxyear = 2016
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     reform=None,
                     assump=None)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              reform=None,
              assump=None,
              growdiff_response=None,
              aging_input_data=True,
              exact_calculations=False)
    assert len(tcio.errmsg) == 0
    assert tcio.tax_year() == taxyear
Example #4
0
def test_init_errors(reformfile0, assumpfile0, year, asm, gdr):
    """
    Ensure error messages generated by TaxCalcIO.init method.
    """
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    if asm == 'assumpfile0':
        assump = assumpfile0.name
    else:
        assump = asm
    if gdr == 'has_gdiff_response':
        gdiff_response = Growdiff()
        gdiff_response.update_growdiff({2015: {"_ABOOK": [-0.01]}})
    else:
        gdiff_response = gdr
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=year,
                     reform=reformfile0.name,
                     assump=assump)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=recdf,
              tax_year=year,
              reform=reformfile0.name,
              assump=assump,
              growdiff_response=gdiff_response,
              aging_input_data=False,
              exact_calculations=False)
    assert len(tcio.errmsg) > 0
def test_output_options(reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_dump options when writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=reformfile1.name,
              assump=assumpfile1.name,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    outfilepath = tcio.output_filepath()
    # minimal output with no --dump option
    try:
        tcio.analyze(writing_output_file=True, output_dump=False)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(minimal_output)_ok' == 'no'
    # --dump output with full dump
    try:
        tcio.analyze(writing_output_file=True, output_dump=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(full_dump_output)_ok' == 'no'
    # --dump output with partial dump
    try:
        tcio.analyze(writing_output_file=True,
                     dump_varset=set(['combined']),
                     output_dump=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(partial_dump_output)_ok' == 'no'
    # if tries were successful, remove doc file and output file
    docfilepath = outfilepath.replace('.csv', '-doc.text')
    if os.path.isfile(docfilepath):
        os.remove(docfilepath)
    if os.path.isfile(outfilepath):
        os.remove(outfilepath)
Example #6
0
def test_ctor_init_with_cps_files():
    """
    Test use of CPS input files.
    """
    # specify valid tax_year for cps.csv input data
    txyr = 2020
    tcio = TaxCalcIO('cps.csv', txyr, None, None, None)
    tcio.init('cps.csv',
              txyr,
              None,
              None,
              None,
              growdiff_response=None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == txyr
    # specify invalid tax_year for cps.csv input data
    txyr = 2013
    tcio = TaxCalcIO('cps.csv', txyr, None, None, None)
    tcio.init('cps.csv',
              txyr,
              None,
              None,
              None,
              growdiff_response=None,
              aging_input_data=True,
              exact_calculations=False)
    assert tcio.errmsg
def test_dynamic_analysis(reformfile1, assumpfile1):
    """
    Test TaxCalcIO.dynamic_analysis method with no output.
    """
    taxyear = 2015
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    try:
        TaxCalcIO.dynamic_analysis(input_data=recdf,
                                   tax_year=taxyear,
                                   reform=reformfile1.name,
                                   assump=assumpfile1.name,
                                   aging_input_data=False,
                                   exact_calculations=False)
    except:  # pylint: disable=bare-except
        assert 'TaxCalcIO.dynamic_analysis_ok' == 'no'
def test_ceeu_output(lumpsumreformfile):
    """
    Test TaxCalcIO calculate method with no output writing using ceeu option.
    """
    taxyear = 2020
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=taxyear,
                     reform=lumpsumreformfile.name,
                     assump=None,
                     growdiff_response=None,
                     aging_input_data=False,
                     exact_calculations=False)
    tcio.static_analysis(writing_output_file=False, output_ceeu=True)
    assert tcio.tax_year() == taxyear
Example #9
0
def test_ctor_errors(input_data, baseline, reform, assump, outdir):
    """
    Ensure error messages are generated by TaxCalcIO.__init__.
    """
    tcio = TaxCalcIO(input_data=input_data, tax_year=2013,
                     baseline=baseline, reform=reform, assump=assump,
                     outdir=outdir)
    assert tcio.errmsg
Example #10
0
def test_init_errors(reformfile0, reformfilex1, reformfilex2, baselinebad,
                     assumpfile0, year, base, ref, asm, gdr):
    """
    Ensure error messages generated by TaxCalcIO.init method.
    """
    # pylint: disable=too-many-arguments,too-many-locals
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    if base == 'reformfile0':
        baseline = reformfile0.name
    elif base == 'baselinebad':
        baseline = baselinebad.name
    else:
        baseline = base
    if ref == 'reformfile0':
        reform = reformfile0.name
    elif ref == 'reformfilex1':
        reform = reformfilex1.name
    elif ref == 'reformfilex2':  # specify compound reform
        reform = '{}+{}'.format(reformfilex1.name, reformfilex2.name)
    else:
        reform = ref
    if asm == 'assumpfile0':
        assump = assumpfile0.name
    else:
        assump = asm
    if gdr == 'has_gdiff_response':
        gdiff_response = Growdiff()
        gdiff_response.update_growdiff({2015: {"_ABOOK": [-0.01]}})
    else:
        gdiff_response = gdr
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=year,
                     baseline=baseline,
                     reform=reform,
                     assump=assump)
    assert not tcio.errmsg
    tcio.init(input_data=recdf,
              tax_year=year,
              baseline=baseline,
              reform=reform,
              assump=assump,
              growdiff_response=gdiff_response,
              aging_input_data=False,
              exact_calculations=False)
    assert tcio.errmsg
Example #11
0
def test_write_doc_file(rawinputfile, reformfile1, assumpfile1):
    """
    Test write_doc_file with compound reform.
    """
    taxyear = 2021
    compound_reform = '{}+{}'.format(reformfile1.name, reformfile1.name)
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     baseline=None,
                     reform=compound_reform,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              baseline=None,
              reform=compound_reform,
              assump=assumpfile1.name,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    tcio.write_doc_file()
    outfilepath = tcio.output_filepath()
    docfilepath = outfilepath.replace('.csv', '-doc.text')
    if os.path.isfile(docfilepath):
        os.remove(docfilepath)
Example #12
0
def test_sqldb_option(rawinputfile, reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_sqldb option when not writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              baseline=None,
              reform=reformfile1.name,
              assump=assumpfile1.name,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    outfilepath = tcio.output_filepath()
    dbfilepath = outfilepath.replace('.csv', '.db')
    # --sqldb output
    try:
        tcio.analyze(writing_output_file=False, output_sqldb=True)
    except:  # pylint: disable=bare-except
        if os.path.isfile(dbfilepath):
            try:
                os.remove(dbfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(sqldb)_ok' == 'no'
    # if try was successful, remove the db file
    if os.path.isfile(dbfilepath):
        os.remove(dbfilepath)
def test_tables(reformfile1):
    """
    Test TaxCalcIO with output_tables=True and with positive weights.
    """
    # create tabable input
    nobs = 100
    idict = dict()
    idict['RECID'] = [i for i in range(1, nobs + 1)]
    idict['MARS'] = [2 for i in range(1, nobs + 1)]
    idict['s006'] = [10.0 for i in range(1, nobs + 1)]
    idict['e00300'] = [10000 * i for i in range(1, nobs + 1)]
    idict['expanded_income'] = idict['e00300']
    idf = pd.DataFrame(idict, columns=list(idict))
    # create and initialize TaxCalcIO object
    tcio = TaxCalcIO(input_data=idf,
                     tax_year=2020,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=idf,
              tax_year=2020,
              baseline=None,
              reform=reformfile1.name,
              assump=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    # create TaxCalcIO tables file
    tcio.analyze(writing_output_file=False, output_tables=True)
    # delete tables file
    output_filename = tcio.output_filepath()
    fname = output_filename.replace('.csv', '-tab.text')
    if os.path.isfile(fname):
        os.remove(fname)
Example #14
0
def test_growmodel_analysis(reformfile1, assumpfile1):
    """
    Test TaxCalcIO.growmodel_analysis method with no output.
    """
    taxyear = 2015
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    # test growmodel_analysis with legal assumptions
    try:
        TaxCalcIO.growmodel_analysis(input_data=recdf,
                                     tax_year=taxyear,
                                     baseline=None,
                                     reform=reformfile1.name,
                                     assump=assumpfile1.name,
                                     aging_input_data=False,
                                     exact_calculations=False)
    except Exception:  # pylint: disable=broad-except
        assert 'TaxCalcIO.growmodel_analysis_ok' == 'no'
def test_ctor_errors(input_data, reform, assump):
    """
    Ensure error messages are generated by TaxCalcIO.__init__.
    """
    tcio = TaxCalcIO(input_data=input_data,
                     tax_year=2013,
                     reform=reform,
                     assump=assump)
    assert len(tcio.errmsg) > 0
def test_error_message_parsed_correctly(regression_reform_file):
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=2022,
                     baseline=regression_reform_file.name,
                     reform=regression_reform_file.name,
                     assump=None)
    assert not tcio.errmsg

    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=2022,
              baseline=regression_reform_file.name,
              reform=regression_reform_file.name,
              assump=None,
              aging_input_data=False,
              exact_calculations=False)
    assert isinstance(tcio.errmsg, str) and tcio.errmsg
    exp_errmsg = ("AMEDT_rt[year=2021] 1.8 > max 1 \n"
                  "AMEDT_rt[year=2021] 1.8 > max 1 ")
    assert tcio.errmsg == exp_errmsg
Example #17
0
def test_init_errors(reformfile0, errorreformfile, errorassumpfile, year, base,
                     ref, asm):
    """
    Ensure error messages generated correctly by TaxCalcIO.init method.
    """
    # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    # test TaxCalcIO ctor
    if base == 'reformfile0':
        baseline = reformfile0.name
    elif base == 'errorreformfile':
        baseline = errorreformfile.name
    else:
        baseline = base
    if ref == 'reformfile0':
        reform = reformfile0.name
    elif ref == 'errorreformfile':
        reform = errorreformfile.name
    else:
        reform = ref
    if asm == 'errorassumpfile':
        assump = errorassumpfile.name
    else:
        assump = asm
    # call TaxCalcIO constructor
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=year,
                     baseline=baseline,
                     reform=reform,
                     assump=assump)
    assert not tcio.errmsg
    # test TaxCalcIO.init method
    tcio.init(input_data=recdf,
              tax_year=year,
              baseline=baseline,
              reform=reform,
              assump=assump,
              growdiff_growmodel=None,
              aging_input_data=False,
              exact_calculations=True)
    assert tcio.errmsg
Example #18
0
def test_growmodel_analysis(reformfile9, assumpfile3):
    """
    Test TaxCalcIO.growmodel_analysis logic.
    """
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    TaxCalcIO.growmodel_analysis(input_data=recdf,
                                 tax_year=2019,
                                 baseline=None,
                                 reform=reformfile9.name,
                                 assump=assumpfile3.name,
                                 aging_input_data=True,
                                 exact_calculations=False,
                                 writing_output_file=False,
                                 output_tables=False,
                                 output_graphs=False,
                                 output_ceeu=False,
                                 dump_varset=None,
                                 output_dump=False,
                                 output_sqldb=False)
def test_custom_dump_variables(dumpvar_str, str_valid, num_vars):
    """
    Test TaxCalcIO custom_dump_variables method.
    """
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    year = 2018
    tcio = TaxCalcIO(input_data=recdf, tax_year=year,
                     baseline=None, reform=None, assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=recdf, tax_year=year,
              baseline=None, reform=None, assump=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    varset = tcio.custom_dump_variables(dumpvar_str)
    assert isinstance(varset, set)
    valid = len(tcio.errmsg) == 0
    assert valid == str_valid
    if valid:
        assert len(varset) == num_vars
def test_incorrect_creation_1(input_data, exact):
    """
    Ensure a ValueError is raised when created with invalid data pointers.
    """
    with pytest.raises(ValueError):
        TaxCalcIO(input_data=input_data,
                  tax_year=2013,
                  reform=None,
                  assump=None,
                  growdiff_response=None,
                  aging_input_data=False,
                  exact_calculations=exact)
def test_sqldb_option(reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_sqldb option when not writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=reformfile1.name,
              assump=assumpfile1.name,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    outfilepath = tcio.output_filepath()
    dbfilepath = outfilepath.replace('.csv', '.db')
    # --sqldb output
    try:
        tcio.analyze(writing_output_file=False, output_sqldb=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(dbfilepath):
            try:
                os.remove(dbfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(sqldb)_ok' == 'no'
    # if try was successful, remove the db file
    if os.path.isfile(dbfilepath):
        os.remove(dbfilepath)
def test_write_doc_file(reformfile1, assumpfile1):
    """
    Test write_doc_file with compound reform.
    """
    taxyear = 2021
    compound_reform = '{}+{}'.format(reformfile1.name, reformfile1.name)
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=compound_reform,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=compound_reform,
              assump=assumpfile1.name,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    tcio.write_doc_file()
    outfilepath = tcio.output_filepath()
    docfilepath = outfilepath.replace('.csv', '-doc.text')
    if os.path.isfile(docfilepath):
        os.remove(docfilepath)
def test_tables(reformfile1):
    """
    Test TaxCalcIO with output_tables=True and with positive weights.
    """
    # create tabable input
    nobs = 100
    idict = dict()
    idict['RECID'] = [i for i in range(1, nobs + 1)]
    idict['MARS'] = [2 for i in range(1, nobs + 1)]
    idict['s006'] = [10.0 for i in range(1, nobs + 1)]
    idict['e00300'] = [10000 * i for i in range(1, nobs + 1)]
    idict['expanded_income'] = idict['e00300']
    idf = pd.DataFrame(idict, columns=list(idict))
    # create and initialize TaxCalcIO object
    tcio = TaxCalcIO(input_data=idf,
                     tax_year=2020,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=idf,
              tax_year=2020,
              baseline=None,
              reform=reformfile1.name,
              assump=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    # create TaxCalcIO tables file
    tcio.analyze(writing_output_file=False, output_tables=True)
    # delete tables file
    output_filename = tcio.output_filepath()
    fname = output_filename.replace('.csv', '-tab.text')
    if os.path.isfile(fname):
        os.remove(fname)
def test_output_otions(rawinputfile, reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_ceeu & output_dump options when writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     reform=reformfile1.name,
                     assump=assumpfile1.name)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              reform=reformfile1.name,
              assump=assumpfile1.name,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert len(tcio.errmsg) == 0
    outfilepath = tcio.output_filepath()
    # --ceeu output and standard output
    try:
        tcio.analyze(writing_output_file=True, output_ceeu=True)
    except:  # pylint: disable=bare-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(ceeu)_ok' == 'no'
    # --dump output
    try:
        tcio.analyze(writing_output_file=True, output_dump=True)
    except:  # pylint: disable=bare-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(dump)_ok' == 'no'
    # if tries were successful, remove output file and doc file
    if os.path.isfile(outfilepath):
        os.remove(outfilepath)
    docfilepath = outfilepath.replace('.csv', '-doc.text')
    if os.path.isfile(docfilepath):
        os.remove(docfilepath)
def test_init_errors(reformfile0, errorreformfile, errorassumpfile,
                     year, base, ref, asm):
    """
    Ensure error messages generated correctly by TaxCalcIO.init method.
    """
    # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    # test TaxCalcIO ctor
    if base == 'reformfile0':
        baseline = reformfile0.name
    elif base == 'errorreformfile':
        baseline = errorreformfile.name
    else:
        baseline = base
    if ref == 'reformfile0':
        reform = reformfile0.name
    elif ref == 'errorreformfile':
        reform = errorreformfile.name
    else:
        reform = ref
    if asm == 'errorassumpfile':
        assump = errorassumpfile.name
    else:
        assump = asm
    # call TaxCalcIO constructor
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=year,
                     baseline=baseline,
                     reform=reform,
                     assump=assump)
    assert not tcio.errmsg
    # test TaxCalcIO.init method
    tcio.init(input_data=recdf, tax_year=year,
              baseline=baseline, reform=reform, assump=assump,
              aging_input_data=False,
              exact_calculations=True)
    assert tcio.errmsg
def test_bad_assumption_file(reformfile1, assumpfile_bad1, assumpfile_bad2):
    """
    Test TaxCalcIO constructor with illegal assumptions.
    """
    input_stream = StringIO(RAWINPUTFILE_CONTENTS)
    input_dataframe = pd.read_csv(input_stream)
    taxyear = 2022
    with pytest.raises(ValueError):
        TaxCalcIO(input_data=input_dataframe,
                  tax_year=taxyear,
                  reform=reformfile1.name,
                  assump=assumpfile_bad1.name,
                  growdiff_response=None,
                  aging_input_data=False,
                  exact_calculations=False)
    with pytest.raises(ValueError):
        TaxCalcIO(input_data=input_dataframe,
                  tax_year=taxyear,
                  reform=reformfile1.name,
                  assump=assumpfile_bad2.name,
                  growdiff_response=None,
                  aging_input_data=False,
                  exact_calculations=False)
def test_creation_with_aging(reformfile0):
    """
    Test TaxCalcIO instantiation with/without no policy reform and with aging.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile0.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=reformfile0.name,
              assump=None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == taxyear
    taxyear = 2016
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=None,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=None,
              assump=None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == taxyear
Example #28
0
def test_no_tables_or_graphs(reformfile1):
    """
    Test TaxCalcIO with output_tables=True and output_graphs=True but
    INPUT has zero weights.
    """
    # create input sample that cannot output tables or graphs
    nobs = 10
    idict = dict()
    idict['RECID'] = [i for i in range(1, nobs + 1)]
    idict['MARS'] = [2 for i in range(1, nobs + 1)]
    idict['s006'] = [0.0 for i in range(1, nobs + 1)]
    idict['e00300'] = [10000 * i for i in range(1, nobs + 1)]
    idict['expanded_income'] = idict['e00300']
    idf = pd.DataFrame(idict, columns=list(idict))
    # create and initialize TaxCalcIO object
    tcio = TaxCalcIO(input_data=idf,
                     tax_year=2020,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=idf,
              tax_year=2020,
              baseline=None,
              reform=reformfile1.name,
              assump=None,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    # create TaxCalcIO tables file
    tcio.analyze(writing_output_file=False,
                 output_tables=True,
                 output_graphs=True)
    # delete tables and graph files
    output_filename = tcio.output_filepath()
    fname = output_filename.replace('.csv', '-tab.text')
    if os.path.isfile(fname):
        os.remove(fname)
    fname = output_filename.replace('.csv', '-atr.html')
    if os.path.isfile(fname):
        os.remove(fname)
    fname = output_filename.replace('.csv', '-mtr.html')
    if os.path.isfile(fname):
        os.remove(fname)
    fname = output_filename.replace('.csv', '-pch.html')
    if os.path.isfile(fname):
        os.remove(fname)
def test_incorrect_creation_2(rawinputfile, reformfile0, year, ref, asm, gdr):
    """
    Ensure a ValueError is raised when created with invalid parameters.
    """
    # pylint: disable=too-many-arguments
    if ref == 'reformfile0':
        reform = reformfile0.name
    else:
        reform = ref
    with pytest.raises(ValueError):
        TaxCalcIO(
            input_data=rawinputfile.name,
            tax_year=year,
            reform=reform,
            assump=asm,
            growdiff_response=gdr,
            aging_input_data=False,
            exact_calculations=False)
def test_ctor_init_with_cps_files():
    """
    Test use of CPS input files.
    """
    # specify valid tax_year for cps.csv input data
    txyr = 2020
    tcio = TaxCalcIO('cps.csv', txyr, None, None, None)
    tcio.init('cps.csv', txyr, None, None, None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == txyr
    # specify invalid tax_year for cps.csv input data
    txyr = 2013
    tcio = TaxCalcIO('cps.csv', txyr, None, None, None)
    tcio.init('cps.csv', txyr, None, None, None,
              aging_input_data=True,
              exact_calculations=False)
    assert tcio.errmsg
def test_creation_with_aging(reformfile0):
    """
    Test TaxCalcIO instantiation with/without no policy reform and with aging.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile0.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=reformfile0.name,
              assump=None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == taxyear
    taxyear = 2016
    tcio = TaxCalcIO(input_data=pd.read_csv(StringIO(RAWINPUT)),
                     tax_year=taxyear,
                     baseline=None,
                     reform=None,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=pd.read_csv(StringIO(RAWINPUT)),
              tax_year=taxyear,
              baseline=None,
              reform=None,
              assump=None,
              aging_input_data=True,
              exact_calculations=False)
    assert not tcio.errmsg
    assert tcio.tax_year() == taxyear
def test_ceeu_with_behavior(lumpsumreformfile, assumpfile2):
    """
    Test TaxCalcIO.analyze method when assuming behavior & doing ceeu calcs.
    """
    taxyear = 2020
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=taxyear,
                     reform=lumpsumreformfile.name,
                     assump=assumpfile2.name)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=recdf,
              tax_year=taxyear,
              reform=lumpsumreformfile.name,
              assump=assumpfile2.name,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert len(tcio.errmsg) == 0
    tcio.analyze(writing_output_file=False, output_ceeu=True)
    assert tcio.tax_year() == taxyear
def test_analyze_warnings_print(warnreformfile):
    """
    Test TaxCalcIO.analyze method when there is a reform warning.
    """
    taxyear = 2020
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=taxyear,
                     reform=warnreformfile.name,
                     assump=None)
    assert len(tcio.errmsg) == 0
    tcio.init(input_data=recdf,
              tax_year=taxyear,
              reform=warnreformfile.name,
              assump=None,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert len(tcio.errmsg) == 0
    tcio.analyze(writing_output_file=False, output_ceeu=False)
    assert tcio.tax_year() == taxyear
def test_output_otions(rawinputfile, reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_ceeu & output_dump options when writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     reform=reformfile1.name,
                     assump=assumpfile1.name,
                     growdiff_response=None,
                     aging_input_data=False,
                     exact_calculations=False)
    outfilepath = tcio.output_filepath()
    # --ceeu output and standard output
    try:
        tcio.static_analysis(writing_output_file=True, output_ceeu=True)
    except:  # pylint: disable=bare-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.calculate(ceeu)_ok' == 'no'
    # --dump output
    try:
        tcio.static_analysis(writing_output_file=True, output_dump=True)
    except:  # pylint: disable=bare-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.calculate(dump)_ok' == 'no'
    # if tries were successful, try to remove the output file
    if os.path.isfile(outfilepath):
        try:
            os.remove(outfilepath)
        except OSError:
            pass  # sometimes we can't remove a generated temporary file
Example #35
0
def test_ceeu_output2():
    """
    Test TaxCalcIO calculate method with no output writing using ceeu option.
    """
    taxyear = 2020
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=taxyear,
                     baseline=None,
                     reform=None,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=recdf,
              tax_year=taxyear,
              baseline=None,
              reform=None,
              assump=None,
              growdiff_response=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    tcio.analyze(writing_output_file=False, output_ceeu=True)
    assert tcio.tax_year() == taxyear
def test_analyze_warnings_print(warnreformfile):
    """
    Test TaxCalcIO.analyze method when there is a reform warning.
    """
    taxyear = 2020
    recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8}
    recdf = pd.DataFrame(data=recdict, index=[0])
    tcio = TaxCalcIO(input_data=recdf,
                     tax_year=taxyear,
                     baseline=None,
                     reform=warnreformfile.name,
                     assump=None)
    assert not tcio.errmsg
    tcio.init(input_data=recdf,
              tax_year=taxyear,
              baseline=None,
              reform=warnreformfile.name,
              assump=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    tcio.analyze(writing_output_file=False)
    assert tcio.tax_year() == taxyear
Example #37
0
def cli_tc_main():
    """
    Contains command-line interface (CLI) to Tax-Calculator TaxCalcIO class.
    """
    # parse command-line arguments:
    usage_str = 'tc INPUT TAXYEAR {}{}{}'.format(
        '[--reform REFORM] [--assump  ASSUMP]\n', '          ',
        '[--exact] [--tables] [--graphs] [--ceeu] [--dump] [--sqldb] [--test]')
    parser = argparse.ArgumentParser(
        prog='',
        usage=usage_str,
        description=('Writes to a file the federal income and payroll tax '
                     'OUTPUT for each filing unit specified in the INPUT '
                     'file, with the OUTPUT computed from the INPUT for the '
                     'TAXYEAR using Tax-Calculator. The OUTPUT file is a '
                     'CSV-formatted file that contains tax information for '
                     'each INPUT filing unit.'))
    parser.add_argument('INPUT',
                        nargs='?',
                        help=('INPUT is name of CSV-formatted file that '
                              'contains for each filing unit variables used '
                              'to compute taxes for TAXYEAR. Specifying '
                              '"cps.csv" uses CPS input files included in '
                              'the taxcalc package.'),
                        default='')
    parser.add_argument('TAXYEAR',
                        nargs='?',
                        help=('TAXYEAR is calendar year for which taxes '
                              'are computed.'),
                        type=int,
                        default=0)
    parser.add_argument('--reform',
                        help=('REFORM is name of optional JSON reform file. '
                              'No --reform implies use of current-law '
                              'policy.'),
                        default=None)
    parser.add_argument('--assump',
                        help=('ASSUMP is name of optional JSON economic '
                              'assumptions file.  No --assump implies use '
                              'of no customized assumptions.'),
                        default=None)
    parser.add_argument('--exact',
                        help=('optional flag that suppresses the smoothing of '
                              '"stair-step" provisions in the tax law that '
                              'complicate marginal-tax-rate calculations.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--tables',
                        help=('optional flag that causes distributional '
                              'tables to be written to a text file.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--graphs',
                        help=('optional flag that causes graphs to be written '
                              'to HTML files for viewing in browser.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--ceeu',
                        help=('optional flag that causes normative welfare '
                              'statistics, including certainty-equivalent '
                              'expected-utility (ceeu) of after-tax income '
                              'values for different '
                              'constant-relative-risk-aversion parameter '
                              'values, to be written to screen.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--dump',
                        help=('optional flag that causes OUTPUT to contain '
                              'all INPUT variables (possibly extrapolated '
                              'to TAXYEAR) and all calculated tax variables, '
                              'where all the variables are named using their '
                              'internal Tax-Calculator names.  No --dump '
                              'option implies OUTPUT contains minimal tax '
                              'output.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--sqldb',
                        help=('optional flag that writes SQLite database with '
                              'dump table containing same output as '
                              'produced by --dump option.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--test',
                        help=('optional flag that conducts installation '
                              'test.'),
                        default=False,
                        action="store_true")
    args = parser.parse_args()
    # write test input and expected output files if --test option specified
    if args.test:
        _write_expected_test_output()
        inputfn = TEST_INPUT_FILENAME
        taxyear = TEST_TAXYEAR
    else:
        inputfn = args.INPUT
        taxyear = args.TAXYEAR
    # instantiate taxcalcio object and do tax analysis
    tcio = TaxCalcIO(input_data=inputfn,
                     tax_year=taxyear,
                     reform=args.reform,
                     assump=args.assump)
    if tcio.errmsg:
        sys.stderr.write(tcio.errmsg)
        sys.stderr.write('USAGE: tc --help\n')
        return 1
    aging = inputfn.endswith('puf.csv') or inputfn.endswith('cps.csv')
    tcio.init(input_data=inputfn,
              tax_year=taxyear,
              reform=args.reform,
              assump=args.assump,
              growdiff_response=None,
              aging_input_data=aging,
              exact_calculations=args.exact)
    if tcio.errmsg:
        sys.stderr.write(tcio.errmsg)
        sys.stderr.write('USAGE: tc --help\n')
        return 1
    tcio.analyze(writing_output_file=True,
                 output_tables=args.tables,
                 output_graphs=args.graphs,
                 output_ceeu=args.ceeu,
                 output_dump=args.dump,
                 output_sqldb=args.sqldb)
    # compare test output with expected test output if --test option specified
    if args.test:
        retcode = _compare_test_output_files()
    else:
        retcode = 0
    # return exit code
    return retcode
Example #38
0
def main():
    """
    Contains STATIC command-line interface to Tax-Calculator TaxCalcIO class.
    """
    # pylint: disable=too-many-return-statements
    # parse command-line arguments:
    parser = argparse.ArgumentParser(
        prog='python tc.py',
        description=('Writes to a file the federal income and payroll tax '
                     'OUTPUT for each filing unit specified in the INPUT '
                     'file, with the OUTPUT computed from the INPUT for the '
                     'TAXYEAR using Tax-Calculator operating under STATIC '
                     'analysis assumptions. The OUTPUT file is a '
                     'CSV-formatted file that contains tax information for '
                     'each INPUT filing unit.'))
    parser.add_argument('INPUT',
                        nargs='?',
                        help=('INPUT is name of CSV-formatted file that '
                              'contains for each filing unit variables used '
                              'to compute taxes for TAXYEAR.'),
                        default='')
    parser.add_argument('TAXYEAR',
                        nargs='?',
                        help=('TAXYEAR is calendar year for which taxes '
                              'are computed.'),
                        type=int,
                        default=0)
    parser.add_argument('--reform',
                        help=('REFORM is name of optional JSON reform file. '
                              'No --reform implies use of current-law '
                              'policy.'),
                        default=None)
    parser.add_argument('--assump',
                        help=('ASSUMP is name of optional JSON economic '
                              'assumption file.  No --assump implies use of '
                              'static analysis assumptions.'),
                        default=None)
    parser.add_argument('--exact',
                        help=('optional flag that suppresses the smoothing of '
                              '"stair-step" provisions in the tax law that '
                              'complicate marginal-tax-rate calculations.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--graph',
                        help=('optional flag that causes graphs to be written '
                              'to HTML files for viewing in browser.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--ceeu',
                        help=('optional flag that causes normative welfare '
                              'statistics, including certainty-equivalent '
                              'expected-utility (ceeu) of after-tax income '
                              'values for different '
                              'constant-relative-risk-aversion parameter '
                              'values, to be written to screen.'),
                        default=False,
                        action="store_true")
    parser.add_argument('--dump',
                        help=('optional flag that causes OUTPUT to contain '
                              'all INPUT variables (possibly aged to TAXYEAR) '
                              'and all calculated tax variables, where all '
                              'the variables are named using their internal '
                              'Tax-Calculator names.'),
                        default=False,
                        action="store_true")
    args = parser.parse_args()
    # check INPUT file name
    if args.INPUT == '':
        sys.stderr.write('ERROR: must specify INPUT file name;\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # check TAXYEAR value
    if args.TAXYEAR == 0:
        sys.stderr.write('ERROR: must specify TAXYEAR >= 2013;\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # check consistency of --reform and --assump options
    if args.assump and not args.reform:
        sys.stderr.write('ERROR: cannot use --assump without --reform\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # check consistency of --reform and --graph options
    if args.graph and not args.reform:
        sys.stderr.write('ERROR: cannot specify --graph without --reform\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # check consistency of --reform and --ceeu options
    if args.ceeu and not args.reform:
        sys.stderr.write('ERROR: cannot specify --ceeu without --reform\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # check consistency of --exact and --graph options
    if args.exact and args.graph:
        sys.stderr.write('ERROR: cannot specify both --exact and --graph\n')
        sys.stderr.write('USAGE: python tc.py --help\n')
        return 1
    # instantiate TaxCalcIO object and do STATIC tax analysis
    aging = args.INPUT.endswith('puf.csv') or args.INPUT.endswith('cps.csv')
    tcio = TaxCalcIO(input_data=args.INPUT,
                     tax_year=args.TAXYEAR,
                     reform=args.reform,
                     assump=args.assump,
                     growdiff_response=None,
                     aging_input_data=aging,
                     exact_calculations=args.exact)
    tcio.static_analysis(writing_output_file=True,
                         output_graph=args.graph,
                         output_ceeu=args.ceeu,
                         output_dump=args.dump)
    # return no-error exit code
    return 0
Example #39
0
def test_output_options(rawinputfile, reformfile1, assumpfile1):
    """
    Test TaxCalcIO output_ceeu & output_dump options when writing_output_file.
    """
    taxyear = 2021
    tcio = TaxCalcIO(input_data=rawinputfile.name,
                     tax_year=taxyear,
                     baseline=None,
                     reform=reformfile1.name,
                     assump=assumpfile1.name)
    assert not tcio.errmsg
    tcio.init(input_data=rawinputfile.name,
              tax_year=taxyear,
              baseline=None,
              reform=reformfile1.name,
              assump=assumpfile1.name,
              growdiff_growmodel=None,
              aging_input_data=False,
              exact_calculations=False)
    assert not tcio.errmsg
    outfilepath = tcio.output_filepath()
    # --ceeu output and standard output
    try:
        tcio.analyze(writing_output_file=True, output_ceeu=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(ceeu)_ok' == 'no'
    # --dump output with full dump
    try:
        tcio.analyze(writing_output_file=True, output_dump=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(dump)_ok' == 'no'
    # --dump output with partial dump
    try:
        tcio.analyze(writing_output_file=True,
                     dump_varset=set(['combined']),
                     output_dump=True)
    except Exception:  # pylint: disable=broad-except
        if os.path.isfile(outfilepath):
            try:
                os.remove(outfilepath)
            except OSError:
                pass  # sometimes we can't remove a generated temporary file
        assert 'TaxCalcIO.analyze(dump)_ok' == 'no'
    # if tries were successful, remove doc file and output file
    docfilepath = outfilepath.replace('.csv', '-doc.text')
    if os.path.isfile(docfilepath):
        os.remove(docfilepath)
    if os.path.isfile(outfilepath):
        os.remove(outfilepath)