Beispiel #1
0
def test_case(year):

    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          reforme=False,
                          nmen=4,
                          maxrev=25 * 9 * 12 * 3,
                          x_axis='sal0')
    # Adding a husband/wife on the same tax sheet (foyer)

    simulation.set_param()
    df = simulation.get_results_dataframe()
    print df.to_string()
def get_child_results_datatframe(pension_alimentaire=0):
    simulation = ScenarioSimulation()
    simulation.set_config(year=2013, nmen=1)

    scenario = simulation.scenario

    # Set the number of major kids in the
    scenario.declar[0]['alr'] = pension_alimentaire
    # Set legislative parameters
    simulation.set_param()

    # Compute the pandas dataframe of the household case_study
    df = simulation.get_results_dataframe()
    return df
def test_nonsal_celib():
    """
    test pour un célibataire
    """
    tests_list = [
             {"year" : 2013,
              "input_vars":
                    {
                     "activite": 3,
                     "rsti" : 12500,
                    },
              "output_vars" :
                     {
                      "rst": 12500,
                    }
              },
            ]

    passed = True
    for test in tests_list:
        year = test["year"]
        simulation = ScenarioSimulation()
        simulation.set_config(year = test["year"], nmen = 1)
        simulation.set_param()

        test_case = simulation.scenario
        for variable, value in test['input_vars'].iteritems():
                if variable in ['rsti']:
                    test_case.indiv[0].update({variable: value})
                else:
                    print variable
                    assert False

        for variable, value in test['output_vars'].iteritems():
            df = simulation.get_results_dataframe(index_by_code = True)
            if variable in df.columns:
                val = df.loc[variable][0]
            else:
                val = simulation.output_table.table[variable][0]
            to_test = abs(val - value)
            if True:  # not (to_test < 1):
                print "Il y a une différence : ", to_test
                print "Pour le scénario", test['input_vars']
                print year
                print variable
                print "OpenFisca :", val
                print "Real value :", value , "\n \n"
                print df.to_string()

    assert passed, "Test failed for some variables"
Beispiel #4
0
def test_case_study(year = 2013, verbose = False):
    '''
    Tests that _salbrut which computes "salaire brut" from "imposable" yields an amount compatbe
    with the one obtained from running openfisca satrting with a "salaire brut"
    '''

    for type_sal_category in ['prive_non_cadre', 'prive_cadre']:  # , 'public_titulaire_etat']:
        simulation = ScenarioSimulation()
        maxrev = 50000
        simulation.set_config(year = year, reforme = False, nmen = 11, maxrev = maxrev, x_axis = 'salbrut')
        simulation.scenario.indiv[0]['salbrut'] = maxrev
        simulation.scenario.indiv[0]['type_sal'] = CAT[type_sal_category]
        if type_sal_category == 'public_titulaire_etat':
            from openfisca_france.model.cotisations_sociales.travail import TAUX_DE_PRIME
            simulation.scenario.indiv[0]['primes'] = TAUX_DE_PRIME * maxrev

        simulation.set_param()

        # The aefa prestation can be disabled by uncommenting the following line:
        # simulation.disable_prestations( ['aefa'])
        df = simulation.get_results_dataframe(index_by_code = True)

        from openfisca_france.model.inversion_revenus import _salbrut_from_salnet
        df_b2n = df.transpose()
        if verbose:

            print df_b2n.to_string()

        salnet = df_b2n['salnet'].get_values()
        hsup = simulation.input_table.table['hsup'].get_values()
        type_sal = simulation.input_table.table['type_sal'].get_values()
        primes = simulation.input_table.table['hsup'].get_values()

        defaultP = simulation.P_default
        from pandas import DataFrame
        df_n2b = DataFrame({'salnet': salnet, 'salbrut' : _salbrut_from_salnet(salnet, hsup, type_sal, defaultP) })

        if verbose:
            print df_n2b.to_string()


        for var in ['salnet', 'salbrut']:
            passed = ((df_b2n[var] - df_n2b[var]).abs() < .01).all()

            if (not passed) or type_sal_category in ['public_titulaire_etat']:
                print (df_b2n / 12).to_string()
                print (df_n2b / 12).to_string()

            assert passed, "difference in %s for %s" % (var, type_sal_category)
def check_test_case(year=2013):
    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          nmen=2,
                          maxrev=2000,
                          reforme=False,
                          x_axis='sali')
    #    simulation.scenario.indiv[0]['sali'] = 16207
    #    # Add husband/wife on the same tax sheet (foyer)
    #    simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')
    simulation.set_param()

    # The aefa prestation can be disabled by uncommenting the following line:
    # simulation.disable_prestations( ['aefa'])
    df = simulation.get_results_dataframe()
    print df.to_string().encode('utf-8')
Beispiel #6
0
def complete_2012_param(P):
    # Hack to get rid of missing parameters in 2012
    dummy_simulation = ScenarioSimulation()

    dummy_simulation.set_config(year=2012 - 1,
                                nmen=1,
                                reforme=False,
                                mode='castype',
                                decomp_file="decomp_contrib.xml")
    dummy_simulation.set_param()

    P.fam = dummy_simulation.P.fam
    P.minim = dummy_simulation.P.minim
    P.al = dummy_simulation.P.al
    P.ir.crl = dummy_simulation.P.ir.crl
    P.isf = dummy_simulation.P.isf
Beispiel #7
0
def couple_38ans_avec_3enfants(year=2013):
    simulation = ScenarioSimulation()
    simulation.set_config(
        year=year,
        nmen=1,
        maxrev=500000,
        x_axis='sali',
    )
    print simulation.scenario
    simulation.scenario.addIndiv(1,
                                 datetime(1975, 1, 1).date(), 'conj', 'part')
    simulation.scenario.addIndiv(2,
                                 datetime(2000, 1, 1).date(), 'pac1', 'enf1')
    simulation.scenario.addIndiv(3,
                                 datetime(2005, 1, 1).date(), 'pac2', 'enf2')
    simulation.scenario.addIndiv(4,
                                 datetime(2010, 1, 1).date(), 'pac3', 'enf3')
def test_case(year):
    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          reforme=False,
                          nmen=11,
                          maxrev=12000,
                          x_axis='salaire_imposable')
    # Adding a husband/wife on the same tax sheet (foyer)
    simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')
    simulation.scenario.addIndiv(2, datetime.date(2000, 1, 1), 'pac', 'enf')
    simulation.scenario.addIndiv(3, datetime.date(2000, 1, 1), 'pac', 'enf')

    simulation.set_param()
    simulation.P.impot_revenu.reforme.exemption.active = 1

    df = simulation.get_results_dataframe()
    print df.to_string()
Beispiel #9
0
def test_case(year):
    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          reforme=False,
                          nmen=3,
                          maxrev=12 * 400,
                          x_axis='sali')
    # Adding a husband/wife on the same tax sheet (foyer)
    simulation.scenario.addIndiv(1,
                                 datetime(1975, 1, 1).date(), 'conj', 'part')

    simulation.scenario.addIndiv(2, datetime(2000, 1, 1).date(), 'pac', 'enf')
    simulation.scenario.addIndiv(3, datetime(2000, 1, 1).date(), 'pac', 'enf')

    simulation.set_param()
    df = simulation.get_results_dataframe()
    print df.to_string()
Beispiel #10
0
def test_case(year):
    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          reforme=False,
                          nmen=3,
                          maxrev=1180 * 12,
                          x_axis='sali')
    # Adding a husband/wife on the same tax sheet (foyer)
    simulation.scenario.addIndiv(1,
                                 datetime(1975, 1, 1).date(), 'conj', 'part')
    simulation.scenario.addIndiv(2, datetime(2000, 1, 1).date(), 'pac', 'enf')
    simulation.scenario.addIndiv(3, datetime(2000, 1, 1).date(), 'pac', 'enf')
    simulation.set_param()

    # A the aefa prestation can be disabled by uncommenting the following line
    # simulation.disable_prestations( ['aefa'])
    df = simulation.get_results_dataframe()
    print df.to_string()
Beispiel #11
0
def get_vous_results_dataframe(sali_single_maxrev=12 * 4000, nmen=11):

    simulation = ScenarioSimulation()
    simulation.set_config(year=2013,
                          nmen=nmen,
                          maxrev=sali_single_maxrev,
                          x_axis='sali')

    # Set legislative parameters
    simulation.set_param()

    df = simulation.get_results_dataframe()

    df2 = df.transpose()[[u'Salaires imposables', u'Impôt sur le revenu']]
    df2.rename(columns={u'Salaires imposables': u'Salaires imposables vous'},
               inplace=True)
    df2.rename(columns={u'Impôt sur le revenu': u'Impôt sur le revenu vous'},
               inplace=True)
    return df2
Beispiel #12
0
def test_case(year):

    country = 'france'
    salaires_nets = 50000
    nmen = 100 #nombre de ménages que je fait varier

    for reforme in [False, True]: #fais tourner un fois pour faux et une fois pour vrai
        #print reforme
        simulation = ScenarioSimulation()
        simulation.set_config(year = year,
                              reforme = reforme,
                              nmen = nmen,
                              maxrev = salaires_nets,
                              x_axis = 'sali')

        # Adding a husband/wife on the same tax sheet (foyer)
        simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')
    #     simulation.scenario.addIndiv(2, datetime(2000,1,1).date(), 'pac', 'enf')
    #     simulation.scenario.addIndiv(3, datetime(2000,1,1).date(), 'pac', 'enf')

        # Loyers set statut d'occupation
        simulation.scenario.menage[0].update({"loyer": 2000}) #fixe les variables au niveau du ménage
        simulation.scenario.menage[0].update({"so": 4}) #

        simulation.set_param() #va chercher des params de la législation
        simulation.P.ir.autre.charge_loyer.active = 1  #simulation.p est un attribu de simulation
        simulation.P.ir.autre.charge_loyer.plaf = 1000
        simulation.P.ir.autre.charge_loyer.plaf_nbp = 0
        #print simulation.P #montre ce qui est écrit dans param.xml
        reduc = 0
        #print simulation.P.ir.bareme #change le barème de l'impot sur le revenu
        #print simulation.P.ir.bareme.nb #nb de tranche du brarème de l'impot
        for i in range(2, simulation.P.ir.bareme.nb):
            simulation.P.ir.bareme.setSeuil(i, simulation.P.ir.bareme.seuils[i] * (1 - reduc)) #a partir de la 2nd tranche réduit les seuils des barèmes

        #print simulation.P.ir.bareme #nouvea barème
        #print simulation.P.ir.bareme.nb

        if simulation.reforme is True:
            df = simulation.get_results_dataframe(default = True , difference = False) # prends la différence(argument de la fonction getresultdataframe
            return df
        else:
            df = simulation.get_results_dataframe()
def run_simulation(apply_reform=False,
                   reforme=False,
                   conj=False,
                   kids=0,
                   sal_conj=False,
                   year=2011):

    simulation = ScenarioSimulation()
    simulation.set_config(year=year,
                          nmen=1001,
                          x_axis='salaire_imposable',
                          maxrev=10000,
                          reforme=reforme,
                          mode='bareme',
                          same_rev_couple=False)
    simulation.set_param()

    if sal_conj:
        conj = True

    if conj:
        simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'vous',
                                     'part')
        if sal_conj:
            simulation.scenario.indiv[1].update({
                'salaire_imposable':
                simulation.P.cotisations_sociales.gen.smig
            })

        if kids > 0:
            for n in range(1, kids + 1):
                simulation.scenario.addIndiv(n + 1, datetime.date(2000, 1, 1),
                                             'pac', 'enf')

    print simulation.scenario
    if apply_reform:
        simulation.P.impot_revenu.reforme.exemption.active = 1
        simulation.P.cotisations_sociales.gen.smig = 320
        simulation.P_default.cotisations_sociales.gen.smig = 320

    return simulation
Beispiel #14
0
def case_study2(year=2013):
    simulation = ScenarioSimulation(
    )  #on instancie on prends une instance de ScenarioSimulation, on prends un exemple de cette classe là
    simulation.set_config(
        year=year,
        nmen=8,  #nombre de ménages
        maxrev=10000,
        x_axis='sali')  #salaire imposable (une seule personne dans le ménage)
    #print simulation.scenario

    simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')

    simulation.set_param()  #prends les paramètres par défaut de la législation
    df = simulation.get_results_dataframe(
        index_by_code=True)  #renvoie la dataframe avec tout calculé

    print df.to_string()
    #print df.transpose()['logt']

    a = df.loc['sal']
    print a
Beispiel #15
0
def test_af2b():
    for yr in range(2006, 2010):
        simulation = ScenarioSimulation()
        simulation.set_config(year=yr, nmen=2, maxrev=100000, x_axis='sali')
        # Adding a husband/wife on the same tax sheet (foyer)
        simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj',
                                     'part')
        simulation.scenario.addIndiv(2, datetime.date(1975, 2, 2), 'conj',
                                     'part')
        simulation.set_param()
        # Adding children on the same tax sheet (foyer)
        simulation.scenario.addIndiv(3, datetime.date(1992, 1, 1), 'pac',
                                     'enf')
        simulation.scenario.addIndiv(4, datetime.date(1990, 1, 1), 'pac',
                                     'enf')
        df = simulation.get_results_dataframe(index_by_code=True)
        #        print df.loc["af"][0]
        #        print af_2enf[yr]
        #        print type(df.loc["af"][0])
        #        print type(af_2enf[yr])
        #        print abs(df.loc["af"][0] - af_2enf[yr]) < 1e-3
        assert abs(df.loc["af"][0] - af_2enfb[yr]) < 1e-3
Beispiel #16
0
def test_cho_rst(year = 2013, verbose = False):
    '''
    Tests that _chobrut which computes "chômage brut" from "imposable" yields an amount compatbe
    with the one obtained from running openfisca satrting with a "chômage brut"
    '''
    remplacement = {'cho' : 'chobrut', 'rst': 'rstbrut'}

    for var, varbrut in remplacement.iteritems():
        simulation = ScenarioSimulation()
        maxrev = 24000
        simulation.set_config(year = year, reforme = False, nmen = 11, maxrev = maxrev, x_axis = varbrut)
        simulation.set_param()
        df = simulation.get_results_dataframe(index_by_code = True)

        from openfisca_france.model.inversion_revenus import _chobrut
        df_b2i = df.transpose()
        if verbose:
            print df_b2i.to_string()

            vari = df_b2i[var].get_values()
            csg_rempl = vari * 0 + 1

            defaultP = simulation.P_default
            from pandas import DataFrame
            df_i2b = DataFrame({var: vari, varbrut : _chobrut(vari, csg_rempl, defaultP) })

            if verbose:
                print df_i2b.to_string()


            for variable in [var, varbrut]:
                passed = ((df_b2i[variable] - df_i2b[variable]).abs() < .01).all()

                if (not passed):
                    print (df_b2i / 12).to_string()
                    print (df_i2b / 12).to_string()

                assert passed, "difference in %s " % (var)
Beispiel #17
0
def case_study(year=2013):

    # Creating a case_study household with one individual whose taxable income (salaire imposable, sali
    # varies from 0 to maxrev = 100000 in nmen = 3 steps

    simulation = ScenarioSimulation()

    simulation.set_config(year=2013, nmen=11, maxrev=10000, x_axis='sali')

    print simulation.scenario

    simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')

    print simulation.scenario

    simulation.set_param()  # Va chercher la legislation par défaut

    df = simulation.get_results_dataframe()

    print df.to_string()

    print simulation.input_table.table.to_string()
    print simulation.output_table.table.to_string()
Beispiel #18
0
def modify_parameters(simulation=None):

    if simulation is None:
        simulation = ScenarioSimulation()
        simulation.set_config(year=2013)
        simulation.set_param()

    for _P in [simulation.P, simulation.P_default]:

        sal = build_sal(_P)
        pat = build_pat(_P)

        _P.cotsoc.__dict__['cotisations_patronales'] = CompactNode()
        _P.cotsoc.__dict__['cotisations_salariales'] = CompactNode()

        for cotisation_name, bareme_dict in {
                'cotisations_patronales': pat,
                'cotisations_salariales': sal
        }.iteritems():
            for category in bareme_dict:
                if category in CAT._nums:
                    _P.cotsoc.__dict__[cotisation_name].__dict__[
                        category] = bareme_dict[category]
def get_couple_without_child_results_datatframe(sali_vous=0,
                                                sali_conj=0,
                                                pension_alimentaire=0):
    simulation = ScenarioSimulation()
    simulation.set_config(year=2013, nmen=1)

    # Adding a husband/wife on the same tax sheet (ie foyer, as conj) and of course same family (as part)
    simulation.scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')

    # Changing the revenu of the parents
    scenario = simulation.scenario
    scenario.indiv[0]['sali'] = sali_vous
    scenario.indiv[1]['sali'] = sali_conj

    # Set the number of major kids in the
    scenario.declar[0]['f6gi'] = pension_alimentaire

    # Set legislative parameters
    simulation.set_param()

    # Compute the pandas dataframe of the household case_study
    df = simulation.get_results_dataframe()
    return df
Beispiel #20
0
def get_alloc(maxrev=30000,
              conj=False,
              nbenf=0,
              zone_apl=1,
              loyer_mensuel=500,
              nmen=51):

    # Creating a case_study household with one individual whose taxable income (salaire imposable, sali
    # varies from 0 to maxrev = 100000 in nmen = 3 steps
    simulation = ScenarioSimulation()
    simulation.set_config(year=2013, nmen=nmen, maxrev=maxrev, x_axis='sali')

    scenario = simulation.scenario
    if conj:
        # Adding a husband/wife on the same tax sheet (ie foyer, as conj) and of course same family (as part)
        scenario.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')

    for i in range(nbenf):

        # Adding 3 kids on the same tax sheet and family
        scenario.addIndiv(1 + conj + i, datetime.date(2001, 1, 1), 'pac',
                          'enf')

    # Add caracteristics of menage
    scenario.menage[0]['loyer'] = loyer_mensuel
    scenario.menage[0]['zone_apl'] = zone_apl

    # Set legislative parameters
    simulation.set_param()
    # print scenario
    # Compute the pandas dataframe of the household case_study
    df = simulation.get_results_dataframe()  #(index_by_code= True)
    print df
    df2 = df.transpose()[[
        'Salaires imposables', 'Revenu disponible', 'Prestations logement'
    ]]
    return df2
Beispiel #21
0
def get_avg_tax_rate_dataframe(x_axis="sali", maxrev=50000, year=2006):
    """
    Returns avgerage tax rate dataframe

    Parameters
    ----------

    x_axis : string
            sali choi etc
    maxrev : float
             Maximal revenu
    year : int, default 2006
           year of the legislation
    """
    simulation = ScenarioSimulation()

    # Changes in individualized caracteristics
    # salaires: sali
    # retraites: choi
    # intérêts: f2ee intpfl; f2tr intb
    # dividendes: f2da divplf; f2dc divb
    # foncier  f4ba fon (micro foncier f4be)

    simulation.set_config(year=year,
                          nmen=101,
                          x_axis=x_axis,
                          maxrev=maxrev,
                          reforme=False,
                          mode='bareme',
                          decomp_file="decomp_contrib.xml")
    simulation.set_param()

    if year == 2012:
        complete_2012_param(simulation.P)

    test_case = simulation.scenario
    df = simulation.get_results_dataframe(index_by_code=True)
    rev_cols = [
        "salsuperbrut", "chobrut", "rstbrut", "fon", "rev_cap_bar",
        "rev_cap_lib", "f3vz", "f3vg"
    ]
    prelev_cols = [
        "cotpat_noncontrib",
        "cotsal_noncontrib",
        "csgsald",
        "csgsali",
        "crdssal",
        "cotpat_noncontrib",
        "cotsal_noncontrib",
        "csgsald",
        "csgsali",
        "crdssal",
        "csgchod",
        "csgchoi",
        "crdscho",
        "csgrstd",
        "csgrsti",
        "crdsrst",
        "prelsoc_cap_bar",
        "prelsoc_cap_lib",
        "csg_cap_bar",
        "csg_cap_lib",
        "crds_cap_bar",
        "crds_cap_lib",
        "prelsoc_fon",
        "csg_fon",
        "crds_fon",
        "prelsoc_pv_immo",
        "csg_pv_immo",
        "crds_pv_immo",
        "prelsoc_pv_mo",
        "csg_pv_mo",
        "crds_pv_mo",
        "imp_lib",
        "ppe",
        "irpp",
        "ir_pv_immo",
    ]

    # TODO: vérifier pour la ppe qu'il n'y ait pas de problème
    #    print df[100].to_string()
    rev_df = df.loc[rev_cols]
    rev = rev_df.sum(axis=0)
    prelev_df = df.loc[prelev_cols]
    prelev = prelev_df.sum(axis=0)
    avg_rate = -prelev / rev

    # Adding IS
    if x_axis in ["f2dc", "f2tr"]:
        rate_is = .3443
        rev_before_is = rev / (1 - rate_is)
        prelev = prelev - rate_is * rev_before_is
        avg_rate = (-prelev) / rev_before_is

        rev = rev_before_is

    output_df = DataFrame({
        "Revenus": rev,
        "Prélèvements": prelev,
        "Taux moyen d'imposition": avg_rate
    })
    output_df.set_index(keys=["Revenus"], inplace=True)

    x_axis_long_name = simulation.io_column_by_name[x_axis].label
    return output_df, x_axis_long_name
Beispiel #22
0
    marginal = True

    for n_enf_final in range(1, 5):
        if n_enf_final == 1:
            title = str(n_enf_final) + ' enfant'
            if marginal:
                title = str(n_enf_final) + 'er enfant'
        else:
            title = str(n_enf_final) + ' enfants'
            if marginal:
                title = str(n_enf_final) + 'e enfant'

        win = ApplicationWindow()
        ax = win.mplwidget.axes

        simu = ScenarioSimulation()
        simu.set_config(year=yr,
                        nmen=201,
                        x_axis='sali',
                        maxrev=130000,
                        reforme=False,
                        mode='bareme',
                        same_rev_couple=True)
        simu.set_param()
        simu.scenario.addIndiv(1, datetime(1975, 1, 1).date(), 'conj', 'part')

        if marginal is True:
            for i in range(1, n_enf_final):
                print 'adding %s kid(s)' % i
                simu.scenario.addIndiv(1 + i,
                                       datetime(2000, 1, 1).date(), 'pac',
Beispiel #23
0
def test_bareme(x_axis="sali"):
    """
    Use to test and debug bareme mode test-case
    """

    yr = 2012
    # Changes in individualized characteristics
    # salaires: sali
    # retraites: choi
    # intérêts: f2ee intpfl; f2tr intb
    # dividendes: f2da divplf; f2dc divb
    # foncier  f4ba fon (micro foncier f4be)

    maxrev = 500000
    year = 2012
    simulation = ScenarioSimulation()

    # Changes in individualized caracteristics
    # salaires: sali
    # retraites: choi
    # intérêts: f2ee intpfl; f2tr intb
    # dividendes: f2da divplf; f2dc divb
    # foncier  f4ba fon (micro foncier f4be)

    simulation.set_config(year=yr,
                          nmen=101,
                          x_axis=x_axis,
                          maxrev=maxrev,
                          reforme=False,
                          mode='bareme',
                          decomp_file="decomp_contrib.xml")
    simulation.set_param()
    # Hack to get rid of missing parameters in 2012
    if yr == 2012:
        complete_2012_param(simulation.P)

    test_case = simulation.scenario

    if SHOW_OPENFISCA:
        app = QApplication(sys.argv)
        win = ApplicationWindow()
        ax = win.mplwidget.axes
        title = "Barème openfisca"
        ax.set_title(title)
        graph_x_axis = simulation.get_varying_revenues(x_axis)
        draw_simulation_bareme(simulation,
                               ax,
                               graph_x_axis=graph_x_axis,
                               legend=True,
                               position=4)
        win.resize(1400, 700)
        win.mplwidget.draw()
        win.show()

    if EXPORT:
        win.mplwidget.print_figure(DESTINATION_DIR + title + '.png')

    if ax:
        del ax
    del simulation
    sys.exit(app.exec_())
def test_cotsoc_cap_celib():
    """
    test pour un célibataire
    """
    tests_list = [
#   Célibataires (pas de supplément familial de traitement
             {"year" : 2013,
              "input_vars":
                    {"f2dc" : 20000,
                     "f2ca" : 5000,
                    },
              "output_vars" :
                    {
                     "csg_cap_bar":-1640,
                     "crds_cap_bar":-100,
                     "prelsoc_cap_bar":-1360,
                     "rev_cat_rvcm" : 7000,
                     "irpp" : 0,
                    },
              },
# Revenus fonciers
            {"year" : 2013,
              "input_vars":
                    {"f4ba" : 20000,
                    },
              "output_vars" :
                    {"csg_fon":-1640,
                     "crds_fon":-100,
                     "prelsoc_fon":-1360,
                     "ir_plaf_qf" : 1450,
                     "rev_cat_rfon" : 20000,
                     "irpp" :-1450,
                    },
                },
             {"year" : 2013,
              "input_vars":
                    {"f4ba" : 20000,
                     "f4bb" : 1000,
                     "f4bc" : 1000,
                     "f4bd" : 1000,
                    },
              "output_vars" :
                    {"csg_fon":-1394,
                     "crds_fon":-85,
                     "prelsoc_fon":-1156,
                     "ir_plaf_qf" : 1030,
                     "rev_cat_rfon" : 17000,
                     "irpp" :-1030,
                    },
                },
            {"year" : 2006,
              "input_vars":
                    {"f4ba" : 20000,
                     "f4bb" : 1000,
                     "f4bc" : 1000,
                     "f4bd" : 1000,
                    },
              "output_vars" :
                    {"csg_fon":-1394,
                     "crds_fon":-85,
                     "prelsoc_fon":-391,
                     "rev_cat_rfon" : 17000,
                     "irpp" :-1119,
                    },
                },
             {"year" : 2013,
              "input_vars":
                    {
                     "f4be" : 10000,
                    },
              "output_vars" :
                    {"csg_fon":-574,
                     "crds_fon":-35,
                     "prelsoc_fon":-476,
                     "rev_cat_rfon" : 7000,
                     "irpp" : 0,
                    },
                },

        ]

    passed = True
    for test in tests_list:
        year = test["year"]
        simulation = ScenarioSimulation()
        simulation.set_config(year = test["year"], nmen = 1)
        simulation.set_param()

        test_case = simulation.scenario
        for variable, value in test['input_vars'].iteritems():
                if variable in []:
                    test_case.indiv[0].update({ variable: value})
                elif variable in ["f2da", "f2dh", "f2dc", "f2ts", "f2tr", "f4ba", "f3vg", "f3vz", "f2fu", "f4ba", "f2go", "f2dc", "f2ca", "f4ba", "f4bb", "f4bc", "f4bd", "f4be", "f4bf"]:
                    test_case.declar[0].update({variable: value})
                else:
                    print variable
                    assert False

        for variable, value in test['output_vars'].iteritems():
            df = simulation.get_results_dataframe(index_by_code = True)
            if variable in df.columns:
                val = df.loc[variable][0]
            else:
                val = simulation.output_table.table[variable][0]
            to_test = abs(val - value)
            if not (to_test < 1):
                print "Il y a une différence : ", to_test
                print "Pour le scénario", test['input_vars']
                print year
                print variable
                print "OpenFisca :", val
                print "Real value :", value , "\n \n"
def test_cotsoc_celib():
    """
    test pour un célibataire
    """
    # Comparaison avec la fiche de paie IPP calculé avec une cotisation transport correspondant à Paris ((.026)
    # alors qu'Openfisca la cacule pour Lyon (.0175)
    tests_list = [
#   Célibataires (pas de supplément familial de traitement
             {"year" : 2012,
              "input_vars":
                    {
                     "type_sal" : CAT["public_titulaire_etat"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "zone_apl": 1,
                    },
              "output_vars" :
                    {
                     "indemnite_residence": 60,
                     "cot_pat_pension_civile": 1371.80,
                     "cot_sal_pension_civile": 167.80,
                     "cot_sal_rafp": 20,
                     "cot_pat_rafp": 20,
                     "cotpat_transport": 2000 * 0.0175,
                     "cotpat" : 1371.80 + 6.6 + 20 + 194 + 108 + 2 + 8 + 2000 * 0.0175 + 6,
#                               pension,  ati, rafp, maladie, famille, fnal1, fnal2, csa,
                     "cotsal" : 167.80 + 20 + 23.72,
#                               pension rafp
                     "salsuperbrut": 4328.40 + 2000 * (0.0175 - 0.026),  # Correction transport
                     "csgsald" : 128.28,
                     "csgsali" : 60.36,
                     "crdssal": 12.58,
                     "salnet": 2147.26,
                    }
              },
             {"year" : 2012,
              "input_vars":
                    {
                     "type_sal" : CAT["public_titulaire_territoriale"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "zone_apl": 1,
                    },
              "output_vars" :
                    {
                     "indemnite_residence": 60,
                     "cot_pat_pension_civile": 546,
                     "cot_sal_pension_civile": 167.80,
                     "cot_sal_rafp": 20,
                     "cot_pat_rafp": 20,
                     "cotpat_transport": 2000 * 0.0175,
                     "cotpat" : 546 + 10 + 20 + 230 + 108 + 2 + 8 + 2000 * 0.0175 + 6,
#                               pension,  ati, rafp, maladie, famille, fnal1, fnal2, csa,
                     "cotsal" : 167.80 + 20 + 23.72,
#                               pension rafp, fds
                     "csgsald" : 128.28,
                     "csgsali" : 60.36,
                     "crdssal": 12.58,
                     "salsuperbrut": 3542 + 2000 * (0.0175 - 0.026),
                     "salnet": 2147.26,
                    }
              },
             {"year" : 2012,
              "input_vars":
                    {
                     "type_sal" : CAT["public_titulaire_hospitaliere"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "zone_apl": 1,
                    },
              "output_vars" :
                    {
                     "indemnite_residence": 60,
                     "cot_pat_pension_civile": 546,
                     "cot_sal_pension_civile": 167.80,
                     "cot_sal_rafp": 20,
                     "cot_pat_rafp": 20,
                     "cotpat_transport": 2000 * 0.0175,
                     "cotpat" : 546 + 10 + 20 + 230 + 108 + 20 + 2 + 8 + 2000 * 0.0175 + 6,
#                               pension,  ati, rafp, maladie, famille, feh, fnal1, fnal2, transport, csa
                     "cotpat_contrib": 546 + 20 + 20,
#                               pension,  rafp, feh
                     "cotsal" : 167.80 + 20 + 23.72,
#                               pension, rafp, except de solidarité
                     "csgsald" : 128.28,
                     "csgsali" : 60.36,
                     "crdssal": 12.58,
                     "salsuperbrut": 3562 + 2000 * (0.0175 - 0.026),  # second term is correction of transport
                     "salnet": 2147.26,
                    }
              },
             {"year" : 2011,
              "input_vars":
                    {
                     "type_sal" : CAT["public_non_titulaire"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "zone_apl": 1,
                    },
              "output_vars" :
                    {
                     "indemnite_residence": 60,
                     "cot_pat_pension_civile": 0,
                     "cot_sal_pension_civile": 0,
                     "cot_sal_rafp": 0,
                     "cot_pat_rafp": 0,
                     "cotpat_transport": 2560 * .0175,
                     "cotpat" : 212.48 + 40.96 + 90.24 + 327.68 + 138.24 + 2.56 + 10.24 + 2560 * 0.0175 + 7.68,
#                               viellesse plaf, deplaf, ircantec, maladie, famille, fnal1, fnal2, transport, csa,
                     "cotsal" : 170.24 + 2.56 + 58.24 + 19.20 + 23.16,
#                              viel_plaf viel_deplaf ircantecA maladie, cot excep de solidarite
                     "cotsal_contrib": 170.24 + 2.56 + 58.24,
#                                      viel_plaf viel_deplaf ircantecA
                     "csgsald" : 128.28,
                     "csgsali" : 60.36,
                     "crdssal": 12.58,
                     "salsuperbrut": 3367.36 + 2000 * (0.0175 - 0.026),
                     "salnet": 2091.20,
                    }
              },
            ]

    passed = True
    for test in tests_list:
        year = test["year"]
        simulation = ScenarioSimulation()
        simulation.set_config(year = test["year"], nmen = 1)
        simulation.set_param()

        test_case = simulation.scenario
        for variable, value in test['input_vars'].iteritems():
            if variable in ['zone_apl']:
                test_case.menage[0].update({ variable: value})
            else:
                test_case.indiv[0].update({ variable: value})

        df = simulation.get_results_dataframe(index_by_code = True)
        simulation.output_table.calculate_prestation(simulation.prestation_by_name['salnet'])
        simulation.output_table.calculate_prestation(simulation.prestation_by_name['sal'])

        for variable, value in test['output_vars'].iteritems():

            computed_value = (simulation.output_table.table[variable] / 12).sum()
            test_assertion = abs(abs(computed_value) - value) < 1
            expression = "Test failed for variable %s on year %i and case %s: \n OpenFisca value : %s \n Real value : %s \n" % (variable, year, test['input_vars'], abs(computed_value), value)

            if not test_assertion:
                print expression
                passed = False

    assert passed, "Test failed for some variables"
def test_cotsoc_famille():
    """
    test pour un couple de fonctionnaire
    """
    tests_list = [
#  Famille avec 2 enfants
             {"year" : 2012,
              "input_vars":
                    {
                     "type_sal" : CAT["public_titulaire_etat"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "zone_apl": 1,
                    },
              "output_vars" :
                    {
                     "cot_pat_pension_civile": 1371.80,
                     "cot_sal_pension_civile": 167.80,
                     "cot_sal_rafp": 20,
                     "cot_pat_rafp": 20,
                     "csgsald" : 131.94,
                     "csgsali" : 62.09,
                     "indemnite_residence": 60,
                     "supp_familial_traitement":73.04,
                     "crdssal": 12.93,
                     "cotpat_transport": 2000 * 0.0175,
                     "cotpat" : 1371.80 + 6.6 + 20 + 194 + 108 + 2 + 8 + 2000 * 0.0175 + 6,
#                               pension,  ati, rafp, maladie, famille, fnal1, fnal2, csa,
                     "cotsal" : 167.80 + 20 + 24.45,  # cot excep de solidarité
#                               pension rafp
                     "salsuperbrut": 4401.44 + 2000 * (.0175 - .026),
                     "salnet": 2213.83,
                    }
              },
            {"year" : 2012,
              "input_vars":
                    {
                     "type_sal" : CAT["public_titulaire_etat"],
                     "salbrut" : 12 * 2000,
                     "primes" : 12 * 500,
                     "type_sal_c" : CAT["public_titulaire_etat"],
                     "salbrut_c" : 12 * 2000,
                     "primes_c" : 12 * 500,
                     "zone_apl": 2,

                    },
              "output_vars" :
                    {
                     "cot_pat_pension_civile": 1371.80 * 2,
                     "cot_sal_pension_civile": 167.80 * 2,
                     "cot_sal_rafp": 20 * 2,
                     "cot_pat_rafp": 20 * 2,
                     "csgsald" : 131.94 * 2,
                     "csgsali" : 62.09 * 2,
                     "indemnite_residence": 240 * 2 / 12,
                     "supp_familial_traitement":73.04,
                     "crdssal": 12.93 * 2,
                     "cotpat_transport": 2000 * 0.0175 * 2,
                     "cotpat" : (1371.80 + 6.6 + 20 + 194 + 108 + 2 + 8 + 2000 * 0.0175 + 6) * 2,
#                               pension,  ati, rafp, maladie, famille, fnal1, fnal2, csa,
                     "cotsal" : (167.80 + 20 + 24.45) * 2 ,  # cot excep de solidarité
#                               pension rafp
                     "salsuperbrut": (2000 + 500 + 20 + 1751.4) * 2 + 73.04,
                     "salnet": (2000 + 500 + 20 - 131.94 - 62.09 - 12.93 - (167.80 + 20 + 24.45)) * 2 + 73.04,
                    }
              },
                  ]

    passed = True
    for test in tests_list:

        year = test["year"]
        simulation = ScenarioSimulation()
        simulation.set_config(year = test["year"], nmen = 1)
        simulation.set_param()

        test_case = simulation.scenario

        test_case.addIndiv(1, datetime.date(1975, 1, 1), 'conj', 'part')
        test_case.addIndiv(2, datetime.date(2000, 1, 1), 'pac', 'enf')
        test_case.addIndiv(3, datetime.date(2009, 1, 1), 'pac', 'enf')

        for variable, value in test['input_vars'].iteritems():

            if variable in ['zone_apl']:
                test_case.menage[0].update({ variable: value})
            elif variable in ['type_sal', 'salbrut', 'primes']:
                test_case.indiv[0].update({ variable: value})
            elif variable in ['type_sal_c', 'salbrut_c', 'primes_c']:
                test_case.indiv[1].update({ variable[:-2] : value})
            else:
                print "Variable non prise en charge : ", variable
                pdb.set_trace()

        df = simulation.get_results_dataframe(index_by_code = True)
        simulation.output_table.calculate_prestation(simulation.prestation_by_name['salnet'])
        simulation.output_table.calculate_prestation(simulation.prestation_by_name['sal'])

        for variable, value in test['output_vars'].iteritems():

            computed_value = (simulation.output_table.table[variable] / 12).sum()
            test_assertion = abs(abs(computed_value) - value) < 2
            expression = "Test failed for variable %s on year %i and case %s: \n OpenFisca value : %s \n Real value : %s \n" % (variable, year, test['input_vars'], abs(computed_value), value)

            if not test_assertion:
                print expression
                passed = False

    assert passed, "Test failed for some variables"
def test_irpp():
    """
    test pour un célibataire pour un revenu de 20 000, 50 000 € et 150 000 €
    et des revenus de différentes origines
    """
    dico = {
        # test pour un célibataire ayant un revenu salarial (1AJ)
        "sali": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -7934
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -7934
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -7934
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -42338
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -42338
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -43222
            },
        ],
        # test pour un retraité célibataire ayant une pension (1AS)
        "rsti": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -1181
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -8336
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -8336
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -8336
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -46642
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -46642
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -46642
            },
        ],
        # test sur un revenu des actions soumises à un prélèvement libératoire de 21 % (2DA)
        "f2da": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": 0
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": 0
            },
        ],
        # test sur un revenu (2DH) issu des produits d'assurance vie  et de capitalisation soumis au prélèvement libératoire de 7.5 %
        "f2dh": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": 345
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": 345
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": 345
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": 345
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": 345
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": 345
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": 345
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": 345
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": 345
            },
        ],
        # test sur un revenu des actions et  parts (2DC)
        "f2dc": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -31
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -2976
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -2976
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -3434
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -22917
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -22917
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -23542
            },
        ],
        # test sur le revenu de valeurs mobilières (2TS)
        "f2ts": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -48142
            },
        ],
        # test sur les intérêts (2TR)
        "f2tr": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -48142
            },
        ],
        # test sur les revenus fonciers (4BA)
        "f4ba": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -1461
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -9434
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -48142
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -48142
            },
        ],
        # test sur les plus-values mobilières (3VG)
        "f3vg": [
            {
                "year": 2010,
                "amount": 20000,
                "irpp": -3600
            },
            {
                "year": 2011,
                "amount": 20000,
                "irpp": -3800
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": -4800
            },
            {
                "year": 2010,
                "amount": 50000,
                "irpp": -9000
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": -9500
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": -12000
            },
            {
                "year": 2010,
                "amount": 150000,
                "irpp": -27000
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": -28500
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": -36000
            },
        ],
        # test sur les plus-values immobilières (3VZ)
        "f3vz": [
            {
                "year": 2011,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 20000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 50000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 50000,
                "irpp": 0
            },
            {
                "year": 2011,
                "amount": 150000,
                "irpp": 0
            },
            {
                "year": 2012,
                "amount": 150000,
                "irpp": 0
            },
        ],
    }

    for revenu, test_list in dico.iteritems():
        for item in test_list:
            year = item["year"]
            amount = item["amount"]
            irpp = item["irpp"]
            simulation = ScenarioSimulation()
            simulation.set_config(year=year, nmen=1)
            simulation.set_param()
            test_case = simulation.scenario
            if revenu in ["rsti", "sali"]:
                test_case.indiv[0].update({revenu: amount})
            elif revenu in [
                    "f2da", "f2dh", "f2dc", "f2ts", "f2tr", "f4ba", "f3vg",
                    "f3vz"
            ]:
                test_case.declar[0].update({revenu: amount})
            else:
                assert False
            df = simulation.get_results_dataframe(index_by_code=True)
            if not abs(df.loc["irpp"][0] - irpp) < 1:
                print year
                print revenu
                print amount
                print "OpenFisca :", abs(df.loc["irpp"][0])
                print "Real value :", irpp

            assert abs(df.loc["irpp"][0] - irpp
                       ) < 1, "error in irpp for revenu %s in year %s \n" % (
                           revenu, year)
def test_cotsoc():
    """
    test pour un célibataire pour un revenu de 20 000, 50 000 € et 150 000 €
    et des revenus de différentes origines
    """
    dico = {
# test pour un célibataire ayant un revenu salarial (1AJ)
#            "sali": [
#            {"year" : 2010, "amount": 20000, "irpp":-1181 },
#            {"year" : 2011, "amount": 20000, "irpp":-1181 },
#            {"year" : 2010, "amount": 50000, "irpp":-7934 },
#            {"year" : 2011, "amount": 50000, "irpp":-7934 },
#            {"year" : 2010, "amount": 150000, "irpp":-42338},
#            {"year" : 2011, "amount": 150000, "irpp":-42338}
#                    ],
# test pour un retraité célibataire ayant une pension (1AS)
#            "rsti": [
#            {"year" : 2010, "amount": 20000, "irpp":-1181 },
#            {"year" : 2011, "amount": 20000, "irpp":-1181 },
#            {"year" : 2010, "amount": 50000, "irpp":-8336 },
#            {"year" : 2011, "amount": 50000, "irpp":-8336 },
#            {"year" : 2010, "amount": 150000, "irpp":-46642 },
#            {"year" : 2011, "amount": 150000, "irpp":-46642 },
#                    ],
# test sur un revenu des actions soumises à un prélèvement libératoire de 21 % (2DA)
            "f2da" : [
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_cap_lib":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_cap_lib":-.082 * 20000,
                 "crds_cap_lib":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_cap_lib":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_lib":-.082 * 20000,
                 "crds_cap_lib":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" : {"prelsoc_cap_lib":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_lib":-.082 * 20000,
                 "crds_cap_lib":-.005 * 20000 } }
                    ],
# # test sur un revenu (2DH) issu des produits d'assurance vie
# # et de capitalisation soumis au prélèvement libératoire de 7.5 %
#            "f2dh" :[
#            {"year" : 2010, "amount": 20000, "irpp":345},
#            {"year" : 2011, "amount": 20000, "irpp":345},
#            {"year" : 2010, "amount": 50000, "irpp":345},
#            {"year" : 2011, "amount": 50000, "irpp":345},
#            {"year" : 2010, "amount": 150000, "irpp":345},
#            {"year" : 2011, "amount": 150000, "irpp":345},
# Célibataire sans enfant                   ],
# test sur un revenu des actions et  parts (2DC)
            "f2dc" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-1360,
                 "csg_cap_bar":-1640,
                 "crds_cap_bar":-100,
                 "ir_plaf_qf": 330,
                 "irpp":-0} },
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
                     ],
            
# # test sur le Revenus imposables des titres non côtés détenus dans le PEA et distributions perçues via votre entreprise
# ## donnant droit à abattement (2fu)
            "f2fu" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-1360,
                 "csg_cap_bar":-1640,
                 "crds_cap_bar":-100,
                 "ir_plaf_qf": 330,
                 "irpp":0} },
                     ],
# Autres revenus distribués et revenus des structures soumises hors de France à un régime fiscal privilégié (2Go)
            "f2go" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"rev_cat_rvcm" : 25000,
                 "prelsoc_cap_bar":-1700,
                 "csg_cap_bar":-2050,
                 "crds_cap_bar":-125,
                 "ir_plaf_qf": 2150,
                 "irpp":-2150 } },
                     ],
            "f2ts" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"rev_cat_rvcm" : 20000,
                 "prelsoc_cap_bar":-1360,
                 "csg_cap_bar":-1640,
                 "crds_cap_bar":-100,
                 "ir_plaf_qf": 1450,
                 "irpp":-1450 } },
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
                     ],
# # test sur les intérêts (2TR)
            "f2tr" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-1360,
                 "csg_cap_bar":-1640,
                 "crds_cap_bar":-100,
                 "ir_plaf_qf": 1450,
                 "irpp":-1450 } },
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_cap_bar":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_cap_bar":-.082 * 20000,
                 "crds_cap_bar":-.005 * 20000 } },
                     ],
# # test sur les revenus fonciers (4BA)
            "f4ba":[
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_fon":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_fon":-.082 * 20000,
                 "crds_fon":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_fon":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_fon":-.082 * 20000,
                 "crds_fon":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_fon":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_fon":-.082 * 20000,
                 "crds_fon":-.005 * 20000 } },
                     ],
# # test (3VG) Plus-values de cession de valeurs mobilières, droits sociaux et gains assimilés
            "f3vg" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"prelsoc_pv_mo":-1360,
                 "csg_pv_mo":-1640,
                 "crds_pv_mo":-100,
                 "ir_plaf_qf": 1450,
                 "irpp":-1450} },
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_pv_mo":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_pv_mo":-.082 * 20000,
                 "crds_pv_mo":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_pv_mo":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_pv_mo":-.082 * 20000,
                 "crds_pv_mo":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_pv_mo":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_pv_mo":-.082 * 20000,
                 "crds_pv_mo":-.005 * 20000 } },
            {"year" : 2006, "amount": 20000,
             "vars" :
                {"prelsoc_pv_mo":-460 ,
                 "csg_pv_mo":-1640,
                 "crds_pv_mo":-100} },
                     ],
# # test sur les plus-values immobilières (3VZ)
            "f3vz" :[
            {"year" : 2012, "amount": 20000,
             "vars" :
                {"prelsoc_pv_immo":-(4.5 + 2 + 0.3) * 0.01 * 20000,
                 "csg_pv_immo":-.082 * 20000,
                 "crds_pv_immo":-.005 * 20000 } },
            {"year" : 2011, "amount": 20000,
             "vars" :
                {"prelsoc_pv_immo":-(3.4 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_pv_immo":-.082 * 20000,
                 "crds_pv_immo":-.005 * 20000 } },
            {"year" : 2010, "amount": 20000,
             "vars" :
                {"prelsoc_pv_immo":-(2.2 + 1.1 + 0.3) * 0.01 * 20000,
                 "csg_pv_immo":-.082 * 20000,
                 "crds_pv_immo":-.005 * 20000 } },
                     ],
# Revenus fonciers imposables" (f4ba)
            "f4ba" :[
            {"year" : 2013, "amount": 20000,
             "vars" :
                {"prelsoc_fon":-1360,
                 "csg_fon":-1640,
                 "crds_fon":-100,
                 "ir_plaf_qf": 1450,
                 "irpp":-1450} },
                 ],

            }


    for revenu, test_list in dico.iteritems():
        for item in test_list:
            year = item["year"]
            amount = item["amount"]

            for var, value in item["vars"].iteritems():
                simulation = ScenarioSimulation()
                simulation.set_config(year = year, nmen = 1)
                simulation.set_param()

#                 from openfisca_qt.scripts.cecilia import complete_2012_param  # TODO: FIXME when 2012 done
#                 if year == 2012:
#                     complete_2012_param(simulation.P)

                test_case = simulation.scenario
                if revenu in ["rsti", "sali"]:
                    test_case.indiv[0].update({revenu: amount})
                elif revenu in ["f2da", "f2dh", "f2dc", "f2ts", "f2tr", "f4ba", "f3vg", "f3vz", "f2fu", "f4ba", "f2go"]:
                    test_case.declar[0].update({revenu: amount})
                else:
                    print revenu
                    assert False
                df = simulation.get_results_dataframe(index_by_code = True)
                if var in df.columns:
                    val = df.loc[var][0]
                else:
                    val = simulation.output_table.table[var][0]
                test = abs(val - value)
                if not (test < 1):
                    print test
                    print year
                    print revenu
                    print amount
                    print var
                    print "OpenFisca :", val
                    print "Real value :", value
Beispiel #29
0
def test_case(year):
    """
    Use to test individual test-case for debugging
    """

    app = QApplication(sys.argv)
    win = ApplicationWindow()

    yr = year

    simulation = ScenarioSimulation()
    simulation.set_config(year=yr,
                          nmen=1,
                          reforme=False,
                          mode='castype',
                          decomp_file="decomp_contrib.xml")
    simulation.set_param()

    # Hack to get rid of missing parameters in 2012
    if yr == 2012:
        complete_2012_param(simulation.P)

    test_case = simulation.scenario

    # Changes in individualized caracteristics
    #TRAITEMENTS, SALAIRES, PPE, PENSIONS ET RENTES
    # salaires (case 1AJ)
    test_case.indiv[0].update({"sali": 0})

    # préretraites, chômage (case 1AP)
    test_case.indiv[0].update({"choi": 0})

    # pensions (case 1AS)
    test_case.indiv[0].update({"rsti": 0})

    # Changes in non-individualized items of the declaration
    # REVENUS DES VALEURS ET CAPITAUX MOBILIERS
    # intérêts
    # f2ee intpfl (pdts de placement soumis aux prélèvements obligatoires autres que 2DA et 2DH
    # f2tr intb (intérêts et autres revenus assimilés)
    test_case.declar[0].update({"f2ts": 0})
    test_case.declar[0].update({"f2tr": 0})

    # dividendes
    # f2da divplf (revenus des actions et parts soumis au prélèvement libératoire à 21 %
    # f2dc divb (revenus des actions et parts ouvrant droit à abattement)

    test_case.declar[0].update({"f2da": 0})
    test_case.declar[0].update({"f2dh": 0})

    test_case.declar[0].update({"f2dc": 0})

    # REVENUS FONCIERS
    # foncier  f4ba  (micro foncier f4be)
    test_case.declar[0].update({"f4ba": 0})

    #PLUS-VALUES DE CESSION DE VALEURS MOBILIERES, DROITS SOCIAUX ET GAINS ASSIMILéS
    # plus-values TODO: F3VG

    test_case.declar[0].update({"f3vg": 1000000})

    test_case.declar[0].update({"f3vz": 0})

    df = simulation.get_results_dataframe(index_by_code=True)
    rev_cols = [
        "salsuperbrut", "chobrut", "rstbrut", "fon", "rev_cap_bar",
        "rev_cap_lib"
    ]
    prelev_cols = [
        "cotpat_noncontrib", "cotsal_noncontrib", "csgsald", "csgsali",
        "crdssal", "cotpat_noncontrib", "cotsal_noncontrib", "csgsald",
        "csgsali", "crdssal", "csgchod", "csgchoi", "crdscho", "csgrstd",
        "csgrsti", "crdsrst", "prelsoc_cap_bar", "prelsoc_cap_lib",
        "csg_cap_bar", "csg_cap_lib", "crds_cap_bar", "crds_cap_lib",
        "imp_lib", "ppe", "irpp"
    ]

    rev_df = df.loc[rev_cols]
    rev = rev_df.sum(axis=0)
    prelev_df = df.loc[prelev_cols]
    prelev = prelev_df.sum(axis=0)

    print -prelev / rev
    print rev
    #    print prelev_df, rev, -prelev
    ax = win.mplwidget.axes
    if SHOW_OPENFISCA:
        title = "Mon titre"
        ax.set_title(title)
        draw_simulation_waterfall(simulation, ax)
        win.resize(1400, 700)
        win.mplwidget.draw()
        win.show()
        sys.exit(app.exec_())

    if EXPORT:
        win.mplwidget.print_figure(DESTINATION_DIR + title + '.png')

    del ax, simulation
Beispiel #30
0
def test_nonsal_celib():
    """
    test pour un célibataire
    """
    tests_list = [
        #   Célibataires à partir de : http://www.experts-comptables.fr/csoec/Focus-bases-documentaires/Auto-Entrepreneur/Simulateur-Auto-Entrepreneur-version-entreprise
        {
            "year": 2013,
            "input_vars": {
                "ebic_impv": 20000,
            },
            "output_vars": {
                "rev_microsocial": 20000 - 2820,
                "microsocial": 200,
            }
        },
        {
            "year": 2013,
            "input_vars": {
                "ebic_imps": 20000,
            },
            "output_vars": {
                "rev_microsocial": 20000 - 4920,
                "microsocial": 340,
            }
        },
        {
            "year": 2013,
            "input_vars": {
                "ebnc_impo": 20000,
            },
            "output_vars": {
                "rev_microsocial": 20000 - 4920,
                "microsocial": 440,
            }
        },
    ]

    passed = True
    for test in tests_list:
        year = test["year"]
        simulation = ScenarioSimulation()
        simulation.set_config(year=test["year"], nmen=1)
        simulation.set_param()

        test_case = simulation.scenario
        for variable, value in test['input_vars'].iteritems():
            if variable in ['ebic_impv', 'ebic_imps', 'ebnc_impo']:
                test_case.indiv[0].update({variable: value})
            else:
                print variable
                assert False

        for variable, value in test['output_vars'].iteritems():
            df = simulation.get_results_dataframe(index_by_code=True)
            if variable in df.columns:
                val = df.loc[variable][0]
            else:
                val = simulation.output_table.table[variable][0]
            to_test = abs(val - value)
            if not (to_test < 1):
                print "Il y a une différence : ", to_test
                print "Pour le scénario", test['input_vars']
                print year
                print variable
                print "OpenFisca :", val
                print "Real value :", value, "\n \n"

    assert passed, "Test failed for some variables"