def test_check():
    for employee_type, test_parameters in test_case_by_employee_type.iteritems():

        period = test_parameters.get("period", default_period)
        parent1 = dict(
            birth = datetime.date(periods.period(period).start.year - 40, 1, 1),
            )
        parent1.update(test_parameters['input_variables'])

        simulation = tax_benefit_system.new_scenario().init_single_entity(
            period = period,
            parent1 = parent1,
            ).new_simulation(debug = True)

        for variable, amounts in test_parameters['output_variables'].iteritems():
            if isinstance(amounts, dict):
                for period_str, amount in amounts.iteritems():
                    output = simulation.calculate(variable, period = periods.period(period_str))
                    variable_message = "{} at {}".format(variable, period_str)
                    yield assert_variable, variable_message, employee_type, amount, output
            else:
                output = simulation.calculate(variable)
                variable_message = variable
                amount = amounts
                yield assert_variable, variable_message, employee_type, amount, output
Exemplo n.º 2
0
def create_simulation(year = 2014, bareme = False):
    simulation_period = periods.period('year', year)
    reform = prime_activite.build_reform(tax_benefit_system)
    parent1 = dict(
        birth = datetime.date(year - 40, 1, 1),
        salaire_de_base = 10000 if bareme is False else None,
        )
    #    parent2 = dict(
    #        birth = datetime.date(year - 40, 1, 1),
    #        salaire_de_base = 0,
    #        )
    # Adding a husband/wife on the same tax sheet (foyer)
    menage = dict(
        loyer = 1000,
        so = 4,
        )
    axes = [
        dict(
            count = 200,
            name = 'salaire_de_base',
            max = 300000,
            min = 0,
            ),
        ]
    scenario = reform.new_scenario().init_single_entity(
        axes = axes if bareme else None,
        # menage = menage,
        parent1 = parent1,
        # parent2 = parent2,
        period = periods.period('year', year),
        )
    reference_simulation = scenario.new_simulation(debug = True, reference = True)
    reform_simulation = scenario.new_simulation(debug = True)
    return reform_simulation, reference_simulation
def test_check():
    for employee_type, test_parameters in test_case_by_employee_type.iteritems():
        Reform = reforms.make_reform(
            key = u'smic_h_b_9_euros',
            name = u"Réforme pour simulation ACOSS SMIC horaire brut fixe à 9 euros",
            reference = tax_benefit_system,
            )
        reform = Reform()
        reform.modify_legislation_json(modifier_function = modify_legislation_json)

        simulation_period = 2011
        parent1 = dict(
            birth = datetime.date(periods.period(simulation_period).start.year - 40, 1, 1),
            )
        parent1.update(test_parameters['input_variables'])

        simulation = reform.new_scenario().init_single_entity(
            period = simulation_period,
            parent1 = parent1,
            ).new_simulation(debug = True)

        for variable, amounts in test_parameters['output_variables'].iteritems():
            if isinstance(amounts, dict):
                for period_str, amount in sorted(amounts.iteritems()):
                    output = simulation.calculate_add_divide(variable, period = periods.period(period_str))
                    variable_message = "{} at {}".format(variable, period_str)
                    yield assert_variable, variable_message, employee_type, amount, output
            else:
                output = simulation.calculate(variable)
                variable_message = variable
                amount = amounts
                yield assert_variable, variable_message, employee_type, amount, output
def test_cesthra_invalidee():
    year = 2012
    reform = cesthra_invalidee.build_reform(base.tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 10,
                max = 30000,
                min = 0,
                name = 'sal',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(birth = datetime.date(year - 40, 1, 1)),
        parent2 = dict(birth = datetime.date(year - 40, 1, 1)),
        enfants = [
            dict(birth = datetime.date(year - 9, 1, 1)),
            dict(birth = datetime.date(year - 9, 1, 1)),
            ],
        )

    reference_simulation = scenario.new_simulation(debug = True, reference = True)

    reference_impo = reference_simulation.calculate('impo')
    reference_revdisp = reference_simulation.calculate('revdisp', period = periods.period('year', year))

    reform_impo = reference_simulation.calculate('impo')
    reform_revdisp = reference_simulation.calculate('revdisp', period = periods.period('year', year))
def create_randomly_initialized_survey_scenario_from_table(nb_persons, nb_groups, salary_max_value, rent_max_value, collection):
    variable_generators_by_period = {
        periods.period('2017-01'): [
            {
                'variable': 'salary',
                'max_value': salary_max_value,
                },
            {
                'variable': 'rent',
                'max_value': rent_max_value,
                }
            ],
        periods.period('2018-01'): [
            {
                'variable': 'salary',
                'max_value': salary_max_value,
                },
            ],
        }
    table_by_entity_by_period = random_data_generator(tax_benefit_system, nb_persons, nb_groups,
        variable_generators_by_period, collection)
    survey_scenario = AbstractSurveyScenario()
    survey_scenario.set_tax_benefit_systems(tax_benefit_system = tax_benefit_system)
    survey_scenario.used_as_input_variables = ['salary', 'rent', 'housing_occupancy_status']
    survey_scenario.year = 2017
    survey_scenario.collection = collection
    data = {
        'input_data_table_by_entity_by_period': table_by_entity_by_period
        }
    survey_scenario.init_from_data(data = data)
    return survey_scenario
    def init_variable_values(self, entity, instance_object, instance_id):
        for variable_name, variable_values in instance_object.items():
            path_in_json = [entity.plural, instance_id, variable_name]
            try:
                entity.check_variable_defined_for_entity(variable_name)
            except ValueError as e:  # The variable is defined for another entity
                raise SituationParsingError(path_in_json, e.args[0])
            except VariableNotFound as e:  # The variable doesn't exist
                raise SituationParsingError(path_in_json, str(e), code = 404)

            instance_index = self.get_ids(entity.plural).index(instance_id)

            if not isinstance(variable_values, dict):
                if self.default_period is None:
                    raise SituationParsingError(path_in_json,
                        "Can't deal with type: expected object. Input variables should be set for specific periods. For instance: {'salary': {'2017-01': 2000, '2017-02': 2500}}, or {'birth_date': {'ETERNITY': '1980-01-01'}}.")
                variable_values = {self.default_period: variable_values}

            for period_str, value in variable_values.items():
                try:
                    period(period_str)
                except ValueError as e:
                    raise SituationParsingError(path_in_json, e.args[0])
                variable = entity.get_variable(variable_name)
                self.add_variable_value(entity, variable, instance_index, instance_id, period_str, value)
def test_check():

    reform = smic_h_b_9_euros(tax_benefit_system)

    for employee_type, test_parameters in test_case_by_employee_type.iteritems():
        simulation_period = 2013
        parent1 = dict(
            date_naissance = datetime.date(periods.period(simulation_period).start.year - 40, 1, 1),
            )
        parent1.update(test_parameters['input_variables'])

        simulation = reform.new_scenario().init_single_entity(
            period = simulation_period,
            parent1 = parent1,
            ).new_simulation()

        for variable, amounts in test_parameters['output_variables'].iteritems():
            if isinstance(amounts, dict):
                for period_str, amount in sorted(amounts.iteritems()):
                    output = simulation.calculate_add_divide(variable, period = periods.period(period_str))
                    variable_message = "{} at {}".format(variable, period_str)
                    yield assert_variable, variable_message, employee_type, amount, output
            else:
                output = simulation.calculate(variable)
                variable_message = variable
                amount = amounts
                yield assert_variable, variable_message, employee_type, amount, output
Exemplo n.º 8
0
    def get(self, period):
        if self.is_eternal:
            period = periods.period(ETERNITY)
        period = periods.period(period)

        values = self._arrays.get(period)
        if values is None:
            return None
        if isinstance(values, dict):
            return next(iter(values.values()))
        return values
Exemplo n.º 9
0
    def put(self, value, period):
        if self.is_eternal:
            period = periods.period(ETERNITY)
        period = periods.period(period)

        filename = str(period)
        path = os.path.join(self.storage_dir, filename) + '.npy'
        if isinstance(value, EnumArray):
            self._enums[path] = value.possible_values
            value = value.view(np.ndarray)
        np.save(path, value)
        self._files[period] = path
Exemplo n.º 10
0
    def delete(self, period = None):
        if period is None:
            self._arrays = {}
            return

        if self.is_eternal:
            period = periods.period(ETERNITY)
        period = periods.period(period)

        self._arrays = {
            period_item: value
            for period_item, value in self._arrays.items()
            if not period.contains(period_item)
            }
def create_simulation(year = 2014, bareme = False):

    simulation_period = periods.period('year', year)
    reference_legislation_json = tax_benefit_system.legislation_json
    reform_legislation_json = reforms.update_legislation(
        legislation_json = reference_legislation_json,
        path = ('children', 'ir', 'children', 'bareme', 'slices', 0, 'rate'),
        period = simulation_period,
        value = 1,
        )

    Reform = reforms.make_reform(
        name =  u"Imposition à 100% dès le premier euro et jusqu'à la fin de la 1ère tranche",
        legislation_json = reform_legislation_json,
        reference = tax_benefit_system
        )
    reform = Reform()
    parent1 = dict(
        birth = datetime.date(year - 40, 1, 1),
        salaire_de_base = 10000 if bareme is False else None,
        type_sal = 0,
        )
#    parent2 = dict(
#        birth = datetime.date(year - 40, 1, 1),
#        salaire_de_base = 0,
#        )
    # Adding a husband/wife on the same tax sheet (foyer)
    menage = dict(
        loyer = 1000,
        statut_occupation = 4,
        )
    axes = [
        dict(
            count = 200,
            name = 'salaire_de_base',
            max = 300000,
            min = 0,
            ),
        ]
    scenario = reform.new_scenario().init_single_entity(
        axes = axes if bareme else None,
        menage = menage,
        parent1 = parent1,
        # parent2 = parent2,
        period = periods.period('year', year),
        )
    reference_simulation = scenario.new_simulation(debug = True, reference = True)
    reform_simulation = scenario.new_simulation(debug = True)

    return reform_simulation, reference_simulation
Exemplo n.º 12
0
def create_simulations(year, ind_variables, foy_variables):
    # couple
    simulation_couple = base.tax_benefit_system.new_scenario().init_single_entity(
        axes = axe(),
        parent1 = parent(2010, 1),
        parent2 = parent(2010, 1),
        menage = dict(statut_occupation = 4),
        period = periods.period('year', year),
        ).new_simulation(debug = True, reference = True)

    # couple_enfant
    simulation_couple_enfant = base.tax_benefit_system.new_scenario().init_single_entity(
        axes = axe(),
        parent1 = parent(2010, 1),
        parent2 = parent(2010, 1),
        enfants = [enfant(2010), enfant(2010)],
        menage = dict(statut_occupation = 4),
        period = periods.period('year', year),
        ).new_simulation(debug = True, reference = True)

    # celibataire
    simulation_celib = base.tax_benefit_system.new_scenario().init_single_entity(
        axes = axe(),
        parent1 = parent(2010, 1),
        menage = dict(statut_occupation = 4),
        period = periods.period('year', year)
        ).new_simulation(debug = True, reference = True)

    # celibataire avec 1 enfant
    simulation_celib_enfant = base.tax_benefit_system.new_scenario().init_single_entity(
        axes = axe(),
        parent1 = parent(2010, 1),
        enfants = [enfant(2010)],
        menage = dict(statut_occupation = 4),
        period = periods.period('year', year),
        ).new_simulation(debug = True, reference = True)

    d_couple = make_sim(simulation_couple, ind_variables=ind_variables, foy_variables = foy_variables)
    d_couple_enfant = make_sim(simulation_couple_enfant, ind_variables=ind_variables, foy_variables = foy_variables)
    d_celib = make_sim(simulation_celib, ind_variables=ind_variables, foy_variables=foy_variables)
    d_celib_enfant = make_sim(simulation_celib_enfant, ind_variables=ind_variables, foy_variables=foy_variables)

    df_by_type_menage = dict()
    df_by_type_menage['couple'] = d_couple
    df_by_type_menage['couple_enfant'] = d_couple_enfant
    df_by_type_menage['celib'] = d_celib
    df_by_type_menage['celib_enfant'] = d_celib_enfant
    return df_by_type_menage
Exemplo n.º 13
0
def test_parametric_reform(year = 2014):
    reference_legislation_json = tax_benefit_system.legislation_json
    reform_legislation_json = copy.deepcopy(reference_legislation_json)
    assert reform_legislation_json['children']['ir']['children']['bareme']['slices'][0]['rate'] == 0
    reform_legislation_json['children']['ir']['children']['bareme']['slices'][0]['rate'] = 1

    reform = reforms.Reform(
        name = "IR_100_tranche_1",
        label = u"Imposition à 100% dès le premier euro et jusqu'à la fin de la 1ère tranche",
        legislation_json = reform_legislation_json,
        reference_legislation_json = reference_legislation_json
        )

    scenario = tax_benefit_system.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 3,
                name = 'sali',
                max = 100000,
                min = 0,
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(birth = datetime.date(year - 40, 1, 1)),
        )

    simulation = scenario.new_simulation(debug = True)
    assert max(abs(simulation.calculate('impo') - [0, -7889.20019531, -23435.52929688])) < .01

    reform_simulation = reform.new_simulation(debug = True, scenario = scenario)
    assert reform_simulation.compact_legislation is not None
    assert max(abs(reform_simulation.calculate('impo') - [0., -13900.20019531, -29446.52929688])) < .0001
def check_sal(type_sal, year = 2014):
    period = periods.period("{}-01".format(year))
    single_entity_kwargs = dict(
        axes = [dict(count = 101, max = 2000, min = 40, name = 'salaire_de_base')],  # TODO: min = 0
        period = period,
        parent1 = dict(
            birth = datetime.date(year - 40, 1, 1),
            type_sal = type_sal,
            ),
        )
    simulation = tax_benefit_system.new_scenario().init_single_entity(
        **single_entity_kwargs
        ).new_simulation(debug = False)
    brut = simulation.get_holder('salaire_de_base').array
    smic_horaire = simulation.legislation_at(period.start).cotsoc.gen.smic_h_b
    smic_mensuel = smic_horaire * 35 * 52 / 12
    brut = simulation.get_holder('salaire_de_base').array
    simulation.get_or_new_holder('contrat_de_travail').array = brut < smic_mensuel  # temps plein ou temps partiel
    simulation.get_or_new_holder('heures_remunerees_volume').array = brut // smic_horaire  # temps plein ou partiel

    imposable = simulation.calculate('salaire_imposable')

    inversion_reform = inversion_revenus.build_reform(tax_benefit_system)
    inverse_simulation = inversion_reform.new_scenario().init_single_entity(
        **single_entity_kwargs).new_simulation(debug = True)

    inverse_simulation.get_holder('salaire_de_base').delete_arrays()
    inverse_simulation.get_or_new_holder('salaire_imposable_pour_inversion').array = imposable.copy()
    inverse_simulation.get_or_new_holder('contrat_de_travail').array = brut < smic_mensuel  # temps plein ou partiel
    inverse_simulation.get_or_new_holder('heures_remunerees_volume').array = (
        (brut // smic_horaire) * (brut < smic_mensuel)
        )

    new_brut = inverse_simulation.calculate('salaire_de_base')
    assert_near(new_brut, brut, absolute_error_margin = 1)
Exemplo n.º 15
0
def test_cesthra_invalidee():
    year = 2012
    period = periods.period(year)
    reform = cesthra_invalidee(tax_benefit_system)
    scenario = init_single_entity(reform.new_scenario(),
        axes = [[
            dict(
                count = 10,
                max = 30000,
                min = 0,
                name = 'salaire_imposable',
                ),
            ]],
        period = period,
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        enfants = [
            dict(date_naissance = datetime.date(year - 9, 1, 1)),
            dict(date_naissance = datetime.date(year - 9, 1, 1)),
            ],
        )

    reference_simulation = scenario.new_simulation(use_baseline = True)
    reference_impo = reference_simulation.calculate('impots_directs', period = period)
    assert reference_impo is not None
    reference_revenu_disponible = reference_simulation.calculate('revenu_disponible', period = period)
    assert reference_revenu_disponible is not None

    reform_simulation = scenario.new_simulation()
    reform_impots_directs = reform_simulation.calculate('impots_directs', period = period)
    assert reform_impots_directs is not None
    reform_revenu_disponible = reform_simulation.calculate('revenu_disponible', period = period)
    assert reform_revenu_disponible is not None
def test():
    year = 2013
    reform = landais_piketty_saez(tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 3,
                max = 30000,
                min = 0,
                name = 'salaire_de_base',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        # parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        # enfants = [
        #     dict(date_naissance = datetime.date(year - 9, 1, 1)),
        #     dict(date_naissance = datetime.date(year - 9, 1, 1)),
        #     ],
        )

#    reference_simulation = scenario.new_simulation(reference = True)
#

    reform_simulation = scenario.new_simulation()
    reform_assiette_csg = reform_simulation.calculate('assiette_csg')
    reform_impot_revenu_lps = reform_simulation.calculate('impot_revenu_lps')
    assert_near(
        -reform_impot_revenu_lps,
        ((reform_assiette_csg - 10000) * .25 / 30000 + .25) * reform_assiette_csg,
        absolute_error_margin = 0.01,
        )
def net_plot(revenu, count = 11, max_revenu = 5000, min_revenu = 0):
    year = 2014
    period = periods.period("{}-01".format(year))
    if revenu == 'chomage':
        brut_name = 'chobrut'
        net_name = 'chonet'
    elif revenu == 'retraite':
        brut_name = 'rstbrut'
        net_name = 'rstnet'
    elif revenu == 'salaire':
        brut_name = 'salaire_de_base'
        net_name = 'salaire_net'
    else:
        return

    single_entity_kwargs = dict(
        axes = [[
            dict(count = count, max = max_revenu, min = min_revenu, name = brut_name)
            ]],
        period = period,
        parent1 = dict(
            birth = datetime.date(year - 40, 1, 1),
            ),
        )
    simulation = tax_benefit_system.new_scenario().init_single_entity(
        **single_entity_kwargs).new_simulation(debug = True)

    smic_horaire = simulation.legislation_at(period.start).cotsoc.gen.smic_h_b
    smic_mensuel =  smic_horaire * 35 * 52 / 12
    brut = simulation.get_holder(brut_name).array
    simulation.get_or_new_holder('contrat_de_travail').array =  brut < smic_mensuel # temps plein ou temps partiel
    simulation.get_or_new_holder('heures_remunerees_volume').array =  brut // smic_horaire # temps plein ou temps partiel

    net = simulation.calculate(net_name)

    inversion_reform = inversion_revenus.build_reform(tax_benefit_system)
    inverse_simulation = inversion_reform.new_scenario().init_single_entity(
        **single_entity_kwargs).new_simulation(debug = True)

    inverse_simulation.get_holder(brut_name).delete_arrays()
    inverse_simulation.get_or_new_holder(net_name).array = net.copy()
    inverse_simulation.get_or_new_holder('contrat_de_travail').array =  brut < smic_mensuel # temps plein ou temps partiel
    inverse_simulation.get_or_new_holder('heures_remunerees_volume').array =  (
        (brut // smic_horaire)  * (brut < smic_mensuel)
        )

    print inverse_simulation.get_or_new_holder('contrat_de_travail').array
    print inverse_simulation.get_or_new_holder('heures_remunerees_volume').array

    new_brut = inverse_simulation.calculate(brut_name)
    pyplot.subplot(2, 1, 1)
    pyplot.plot(brut, net, 'ro', label = "direct")
    pyplot.plot(new_brut, net, 'db', label = "inversed")
    pyplot.legend()

    pyplot.subplot(2, 1, 2)
    pyplot.plot(brut, new_brut - brut, 'r-')

    pyplot.show()
    assert_near(new_brut, brut, absolute_error_margin = 1)
Exemplo n.º 18
0
def create_simulation(data, period):
    result = simulations.Simulation(debug=False, period=period, tax_benefit_system=model.tax_benefit_system)
    # Initialize entities, assuming there is only one person and one of each other entities ("familles",
    # "foyers fiscaux", etc).
    for entity in result.entity_by_key_plural.itervalues():
        entity.count = 1
        entity.roles_count = 1
        entity.step_size = 1
    # Link person to its entities using ID & role.
    for entity in result.entity_by_key_plural.itervalues():
        if not entity.is_persons_entity:
            holder = result.get_or_new_holder(entity.index_for_person_variable_name)
            holder.set_array(period, np.array([0]))
            holder = result.get_or_new_holder(entity.role_for_person_variable_name)
            holder.set_array(period, np.array([0]))

    # Inject all variables from query string into arrays.
    for column_name, value in data.iteritems():
        column = model.tax_benefit_system.column_by_name[column_name]
        holder = result.get_or_new_holder(column_name)

        if period.unit == "year":
            holder.set_array(period, np.array([value], dtype=column.dtype))
        elif period.unit == "month":
            # Inject inputs for all months of year
            year = period.start.year
            month_index = 1
            while month_index <= 12:
                month = periods.period("{}-{:02d}".format(year, month_index))
                holder.set_array(month, np.array([value], dtype=column.dtype))
                month_index += 1

    return result
Exemplo n.º 19
0
def test_check_rsa():
    '''test rsa pour un célibataire avec différent sali'''
    tests_list = [
        {"year": 2014, "amount": 0, "rsa": 439},
        {"year": 2014, "amount": 5000, "rsa": 281},
        {"year": 2014, "amount": 10000, "rsa": 123},
        {"year": 2014, "amount": 12000, "rsa": 59},
        {"year": 2014, "amount": 13000, "rsa": 28},
        {"year": 2014, "amount": 14000, "rsa": 0},
        {"year": 2014, "amount": 15000, "rsa": 0},
        {"year": 2014, "amount": 20000, "rsa": 0},
        ]

    error_margin = 1
    year = 2014
    age = 29
    revenu = "sali"
    for test in tests_list:
        print test
        amount = test["amount"]
        TaxBenefitSystem = openfisca_france.init_country()
        tax_benefit_system = TaxBenefitSystem()
        simulation = tax_benefit_system.new_scenario().init_single_entity(
            period = periods.period('year', year),
            parent1 = {
                'birth': datetime.date(year - age + 1, 1, 1),
                revenu: amount,
                },
            ).new_simulation(debug = True)
        calculated_rsa = simulation.calculate('rsa') / 12
        assert abs(calculated_rsa - test['rsa']) < error_margin, \
            'calculated_rsa {} is not equal to expected value {}'.format(test['rsa'], calculated_rsa)
Exemplo n.º 20
0
 def custom_initialize(self, simulation):
     three_year_span_variables = [
         'categorie_salarie',
         # 'chomage_brut',
         'chomage_imposable',
         'contrat_de_travail',
         'effectif_entreprise',
         'heures_remunerees_volume',
         # 'hsup',
         'pensions_alimentaires_percues',
         'retraite_brute',
         'retraite_imposable',
         'salaire_de_base',
         ]
     for offset in [-1, -2]:
         for variable in three_year_span_variables:
             assert variable in self.used_as_input_variables, \
                 '{} is not a in the input_varaibles to be used {}'.format(
                     variable, self.used_as_input_variables)
             holder = simulation.get_holder(variable)
             try:
                 holder.set_input(simulation.period.offset(offset), simulation.calculate_add(
                     variable, period = self.year))
             except TypeError:  # TODO Should explicitly test about Enums, avoid enums sum which is forbidden
                 holder.set_input(simulation.period.offset(offset), simulation.calculate(
                     variable, period = periods.period(self.year).first_month))
def run(reform_key, year):
    max_sal = 18000
    count = 2
    people = 1
    reform = base.get_cached_reform(
        reform_key = reform_key,
        tax_benefit_system = base.tax_benefit_system,
        )
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = count,
                max = max_sal,
                min = 0,
                name = 'salaire_imposable',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)) if people >= 2 else None,
        enfants = [
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 3 else None,
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 4 else None,
            ] if people >= 3 else None,
        )

    reference_simulation = scenario.new_simulation(reference = True)
    reform_simulation = scenario.new_simulation()
#    error_margin = 1

    impo = reference_simulation.calculate('impo')
    reform_impo = reform_simulation.calculate('impo')
def test():
    year = 2013
    reform = landais_piketty_saez.build_reform(tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 3,
                max = 30000,
                min = 0,
                name = 'sali',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(birth = datetime.date(year - 40, 1, 1)),
#        parent2 = dict(birth = datetime.date(year - 40, 1, 1)),
#        enfants = [
#            dict(birth = datetime.date(year - 9, 1, 1)),
#            dict(birth = datetime.date(year - 9, 1, 1)),
#            ],
        )

#    reference_simulation = scenario.new_simulation(debug = True, reference = True)
#
    error_margin = 0.01

    reform_simulation = scenario.new_simulation(debug = True)
    reform_assiette_csg = reform_simulation.calculate('assiette_csg')
    reform_impot_revenu_lps = reform_simulation.calculate('impot_revenu_lps')
    assert ((abs(
        -reform_impot_revenu_lps - ((reform_assiette_csg - 10000) * .25 / 30000 + .25) * reform_assiette_csg
        )) < error_margin).all(), "Error in LPS reform"
Exemplo n.º 23
0
 def finalize_variables_init(self, population):
     # Due to set_input mechanism, we must bufferize all inputs, then actually set them,
     # so that the months are set first and the years last.
     plural_key = population.entity.plural
     if plural_key in self.entity_counts:
         population.count = self.get_count(plural_key)
         population.ids = self.get_ids(plural_key)
     if plural_key in self.memberships:
         population.members_entity_id = np.array(self.get_memberships(plural_key))
         population.members_role = np.array(self.get_roles(plural_key))
     for variable_name in self.input_buffer.keys():
         try:
             holder = population.get_holder(variable_name)
         except ValueError:  # Wrong entity, we can just ignore that
             continue
         buffer = self.input_buffer[variable_name]
         periods = [period(period_str) for period_str in self.input_buffer[variable_name].keys()]
         # We need to handle small periods first for set_input to work
         sorted_periods = sorted(periods, key=key_period_size)
         for period_value in sorted_periods:
             values = buffer[str(period_value)]
             # Hack to replicate the values in the persons entity
             # when we have an axis along a group entity but not persons
             array = np.tile(values, population.count // len(values))
             variable = holder.variable
             # TODO - this duplicates the check in Simulation.set_input, but
             # fixing that requires improving Simulation's handling of entities
             if (variable.end is None) or (period_value.start.date <= variable.end):
                 holder.set_input(period_value, array)
Exemplo n.º 24
0
def test(year = 2014):

    reform = plf2015.build_reform(base.tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 10,
                max = 30000,
                min = 0,
                name = 'sali',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(birth = datetime.date(year - 40, 1, 1)),
#        parent2 = dict(birth = datetime.date(year - 40, 1, 1)),
#        enfants = [
#            dict(birth = datetime.date(year - 9, 1, 1)),
#            dict(birth = datetime.date(year - 9, 1, 1)),
#            ],
        )

    reference_simulation = scenario.new_simulation(debug = True, reference = True)

    error_margin = 0.01
    impo = reference_simulation.calculate('impo')
    print impo

    reform_simulation = scenario.new_simulation(debug = True)
    reform_impo = reform_simulation.calculate('impo')
    print reform_impo
Exemplo n.º 25
0
def test_agem_from_age():
    year = 2013
    simulation = tax_benefit_system.new_scenario().init_single_entity(
        period = periods.period('year', year),
        parent1 = dict(age = 40),
        ).new_simulation(debug = True)
    assert_equal(simulation.calculate('agem'), 40 * 12)
Exemplo n.º 26
0
def define_scenario(year = 2013):
    scenario = tax_benefit_system.new_scenario()
    scenario.init_single_entity(
        period = periods.period('year', year),
        parent1 = dict(
            activite = u'Actif occupé',
            birth = 1970,
            sali = 24000,
            statmarit = u'Célibataire',
            ),
        enfants = [
            dict(
                activite = u'Étudiant, élève',
                birth = '2002-02-01',
                ),
            dict(
                activite = u'Étudiant, élève',
                birth = '2000-04-17',
                ),
            ],
        foyer_fiscal = dict(
            f8ta = 3000,
            ),
        )
    scenario.suggest()
    return scenario
Exemplo n.º 27
0
def test(year = 2013):
    max_sal = 18000
    count = 2
    people = 1
    reform = plfr2014(tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = count,
                max = max_sal,
                min = 0,
                name = 'salaire_imposable',
                ),
            ],
        period = periods.period(year),
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)) if people >= 2 else None,
        enfants = [
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 3 else None,
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 4 else None,
            ] if people >= 3 else None,
        )

    reference_simulation = scenario.new_simulation(use_baseline = True)
    reform_simulation = scenario.new_simulation()
    # error_margin = 1
    impots_directs = reference_simulation.calculate('impots_directs', period = year) # noqa F841
    reform_impots_directs = reform_simulation.calculate('impots_directs', period = year) # noqa F841
def test():
    year = 2013
    reform = landais_piketty_saez.build_reform(base.tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 10,
                max = 30000,
                min = 0,
                name = 'sali',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(birth = datetime.date(year - 40, 1, 1)),
        parent2 = dict(birth = datetime.date(year - 40, 1, 1)),
        enfants = [
            dict(birth = datetime.date(year - 9, 1, 1)),
            dict(birth = datetime.date(year - 9, 1, 1)),
            ],
        )

    reference_simulation = scenario.new_simulation(debug = True, reference = True)

    error_margin = 0.01
    af = reference_simulation.calculate('af')
    expected_af = [1532.16] * 10
    assert_less(max(abs(expected_af - af)), error_margin)
    revdisp = reference_simulation.calculate('revdisp')

    reform_simulation = scenario.new_simulation(debug = True)
    reform_af = reform_simulation.calculate('af')
    assert_less(max(abs(expected_af - reform_af)), error_margin)
    reform_revdisp = reform_simulation.calculate('revdisp')
Exemplo n.º 29
0
def test(year = 2013):
    max_sal = 18000
    count = 2
    people = 1
    reform = plf2015(tax_benefit_system)
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = count,
                max = max_sal,
                min = 0,
                name = 'salaire_imposable',
                ),
            ],
        period = periods.period(year),
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)) if people >= 2 else None,
        enfants = [
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 3 else None,
            dict(date_naissance = datetime.date(year - 9, 1, 1)) if people >= 4 else None,
            ] if people >= 3 else None,
        )

    reference_simulation = scenario.new_simulation(use_baseline = True)
    reform_simulation = scenario.new_simulation()
    error_margin = 1

    impots_directs = reference_simulation.calculate('impots_directs', period = year)
    reform_impots_directs = reform_simulation.calculate('impots_directs', period = year)
    ir_plaf_qf = reference_simulation.calculate('ir_plaf_qf', period = year)
    reform_ir_plaf_qf = reform_simulation.calculate('ir_plaf_qf', period = year)
    assert max(abs([0, 918] - ir_plaf_qf)) < error_margin
    assert max(abs([0, 911.4] - reform_ir_plaf_qf)) < error_margin
    assert max(abs([0, -869] - impots_directs)) < error_margin
    assert max(abs([0, -911.4 + (1135 - 911.4)] - reform_impots_directs)) < error_margin
Exemplo n.º 30
0
def test_charge_loyer():
    year = 2013
    reform = base.get_cached_reform(
        reform_key = 'trannoy_wasmer',
        tax_benefit_system = base.tax_benefit_system,
        )
    scenario = reform.new_scenario().init_single_entity(
        axes = [
            dict(
                count = 10,
                max = 30000,
                min = 0,
                name = 'salaire_de_base',
                ),
            ],
        period = periods.period('year', year),
        parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        parent2 = dict(date_naissance = datetime.date(year - 40, 1, 1)),
        enfants = [
            dict(date_naissance = datetime.date(year - 9, 1, 1)),
            dict(date_naissance = datetime.date(year - 9, 1, 1)),
            ],
        menage = dict(
            loyer = 1000,
            ),
        )
    reform_simulation = scenario.new_simulation()
    absolute_error_margin = 0.01

    reform_charge_loyer = reform_simulation.calculate('charge_loyer')
    assert_near(reform_charge_loyer, [1000] * 10, absolute_error_margin = absolute_error_margin)
def test_check():
    for employee_type, test_parameters in test_case_by_employee_type.iteritems(
    ):

        reference_legislation_json = tax_benefit_system.legislation_json

        reform_legislation_json = reforms.update_legislation(
            legislation_json=reference_legislation_json,
            path=('children', 'cotsoc', 'children', 'gen', 'children',
                  'smic_h_b', 'values'),
            period=periods.period("year", "2011"),
            value=9,
        )
        reform = reforms.Reform(
            name=u'smic_h_b_9_euros',
            label=
            u"Réforme pour simulation ACOSS SMIC horaire brut fixe à 9 euros",
            legislation_json=reform_legislation_json,
            reference=tax_benefit_system,
        )

        simulation_period = 2011
        parent1 = dict(birth=datetime.date(
            periods.period(simulation_period).start.year - 40, 1, 1), )
        parent1.update(test_parameters['input_variables'])

        simulation = reform.new_scenario().init_single_entity(
            period=simulation_period,
            parent1=parent1,
        ).new_simulation(debug=True)

        for variable, amounts in test_parameters['output_variables'].iteritems(
        ):
            if isinstance(amounts, dict):
                for period_str, amount in sorted(amounts.iteritems()):
                    output = simulation.calculate(
                        variable, period=periods.period(period_str))
                    variable_message = "{} at {}".format(variable, period_str)
                    yield assert_variable, variable_message, employee_type, amount, output
            else:
                output = simulation.calculate(variable)
                variable_message = variable
                amount = amounts
                yield assert_variable, variable_message, employee_type, amount, output
Exemplo n.º 32
0
def modify_legislation_json(reference_legislation_json_copy):
    # FIXME update_legislation is deprecated.
    reform_legislation_json = reforms.update_legislation(
        legislation_json=reference_legislation_json_copy,
        path=('children', 'cotsoc', 'children', 'gen', 'children', 'smic_h_b',
              'values'),
        period=periods.period("year", "2013"),
        value=9,
    )
    return reform_legislation_json
Exemplo n.º 33
0
    def modifier_un_parametre(self, parameters):
        print("modifier_un_parametre: {}".format(self.ppa_pente))

        # Ceci décrit la periode sur laquelle va s'appliquer ce changement
        reform_year = 2018
        reform_period = periods.period(reform_year)

        # Cette partie propose un changement de taux pour le barème 1 (le second) de l'impôt sur le revenu à partir du début 2017
        parameters.prestations.minima_sociaux.ppa.pente.update(reform_period, value=self.ppa_pente)
        return parameters
Exemplo n.º 34
0
 def restore(self):
     self._files = files = {}
     # Restore self._files from content of storage_dir.
     for filename in os.listdir(self.storage_dir):
         if not filename.endswith('.npy'):
             continue
         path = os.path.join(self.storage_dir, filename)
         filename_core = filename.rsplit('.', 1)[0]
         period = periods.period(filename_core)
         files[period] = path
    def __init__(self,
                 tax_benefit_system=None,
                 baseline_tax_benefit_system=None,
                 data=None,
                 year=None):
        super(CoteDIvoireSurveyScenario, self).__init__()
        if tax_benefit_system is None:
            tax_benefit_system = CoteDIvoireTaxBenefitSystem()
        self.set_tax_benefit_systems(
            tax_benefit_system=tax_benefit_system,
            baseline_tax_benefit_system=baseline_tax_benefit_system,
        )

        assert year is not None
        self.year = year

        if data is None:
            return

        if 'input_data_frame_by_entity_by_period' in data:
            period = periods.period(year)
            dataframe_variables = set()
            assert period in data[
                'input_data_frame_by_entity_by_period'], "Period {} is not found in the data. Period(s) available(s) are {}".format(
                    period, [
                        str(key) for key in
                        data['input_data_frame_by_entity_by_period'].keys()
                    ])
            for entity_dataframe in data[
                    'input_data_frame_by_entity_by_period'][period].values():
                if not isinstance(entity_dataframe, pd.DataFrame):
                    continue
                dataframe_variables = dataframe_variables.union(
                    set(entity_dataframe.columns))
            self.used_as_input_variables = list(
                set(tax_benefit_system.variables.keys()).intersection(
                    dataframe_variables))

        else:
            variables_from_stata_files = stata_files_to_data_frames(
                data, period=year)
            self.used_as_input_variables = list(
                set(tax_benefit_system.variables.keys()).intersection(
                    set(variables_from_stata_files)))
            period = data["input_data_frame_by_entity_by_period"].keys()[0]
            input_data_frame_by_entity = data[
                "input_data_frame_by_entity_by_period"].values()[0]
            person_data_frame = input_data_frame_by_entity['person']
            person_data_frame['household_id'] = person_data_frame.id
            person_data_frame['person_id'] = person_data_frame.id
            person_data_frame['household_role_index'] = 0
            data["input_data_frame_by_entity_by_period"][period] = dict(
                person=person_data_frame)

        self.init_from_data(data=data)
Exemplo n.º 36
0
    def calculate(self, variable_name, period, **parameters):
        """
            Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists.

            :returns: A numpy array containing the result of the calculation
        """
        entity = self.get_variable_entity(variable_name)
        holder = entity.get_holder(variable_name)
        variable = self.tax_benefit_system.get_variable(variable_name)

        if period is not None and not isinstance(period, periods.Period):
            period = periods.period(period)

        if self.trace:
            self.tracer.record_calculation_start(variable.name, period,
                                                 **parameters)

        self._check_period_consistency(period, variable)

        extra_params = parameters.get('extra_params', ())

        # First look for a value already cached
        cached_array = holder.get_array(period, extra_params)
        if cached_array is not None:
            if self.trace:
                self.tracer.record_calculation_end(variable.name, period,
                                                   cached_array, **parameters)
            return cached_array

        max_nb_cycles = parameters.get('max_nb_cycles')
        if max_nb_cycles is not None:
            self.max_nb_cycles = max_nb_cycles

        # First, try to run a formula
        array = self._run_formula(variable, entity, period, extra_params,
                                  max_nb_cycles)

        # If no result, try a base function
        if array is None and variable.base_function:
            array = variable.base_function(holder, period, *extra_params)

        # If no result, use the default value
        if array is None:
            array = holder.default_array()

        self._clean_cycle_detection_data(variable.name)
        if max_nb_cycles is not None:
            self.max_nb_cycles = None

        holder.put_in_cache(array, period, extra_params)
        if self.trace:
            self.tracer.record_calculation_end(variable.name, period, array,
                                               **parameters)

        return array
Exemplo n.º 37
0
def modify_legislation_json(reference_legislation_json_copy):
    reform_legislation_json = update_legislation(
        legislation_json=reference_legislation_json_copy,
        path=[
            'children', 'cotsoc', 'children', 'gen', 'children', 'smic_h_b',
            'values'
        ],
        period=periods.period(2013),
        value=9,
    )
    return reform_legislation_json
Exemplo n.º 38
0
    def _scenario(reform: Reform, count: int, _max: int, _min: int, name: str,
                  year: int, people: int) -> object:

        return init_single_entity(
            reform.new_scenario(),
            axes=axes(count, _max, _min, name),
            period=periods.period(year),
            parent1=parent1(year),
            parent2=parent2(year, people),
            enfants=enfants(year, people),
        )
Exemplo n.º 39
0
def test_without_annualize(monthly_variable):
    period = periods.period(2019)

    person = PopulationMock(monthly_variable)

    yearly_sum = sum(
        person('monthly_variable', month)
        for month in period.get_subperiods(MONTH))

    assert monthly_variable.calculation_count == 11
    assert yearly_sum == 1200
Exemplo n.º 40
0
    def put(self, value, period, extra_params=None):
        if self.is_eternal:
            period = periods.period(ETERNITY)
        period = periods.period(period)

        filename = str(period)
        if extra_params:
            extra_params = tuple(str(param) for param in extra_params)
            filename = '{}_{}'.format(filename, '_'.join(extra_params))
        path = os.path.join(self.storage_dir, filename) + '.npy'
        if isinstance(value, EnumArray):
            self._enums[path] = value.possible_values
            value = value.view(np.ndarray)
        np.save(path, value)
        if not extra_params:
            self._files[period] = path
        else:
            if self._files.get(period) is None:
                self._files[period] = {}
            self._files[period][extra_params] = path
Exemplo n.º 41
0
def modify_legislation_json(reference_legislation_json_copy):
    reform_year = 2016
    reform_period = periods.period(reform_year)

    reference_legislation_json_copy = update_legislation(
        legislation_json=reference_legislation_json_copy,
        path=('children', 'ir', 'children', 'bareme', 'brackets', 3, 'rate'),
        period=reform_period,
        value=.27,
    )
    return reference_legislation_json_copy
Exemplo n.º 42
0
def export_node_to_csv(node, output_dir):

    check_for_doublons(node)

    csv_params = {
        param.metadata['ipp_csv_id']: param
        for param in node.get_descendants() if param.metadata.get('ipp_csv_id')
    }

    all_dates = extract_dates(csv_params)
    first_month = period(f"{all_dates[0].split('-')[0]}-01")
    last_month = period("2018-12")

    with open(f'{output_dir}/{node.name}.csv', mode='w') as csv_file:
        fieldnames = ['date'] + list(csv_params.keys())
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        current_month = first_month
        while current_month <= last_month:
            writer.writerow(get_row(csv_params, current_month))
            current_month = current_month.offset(1, MONTH)
Exemplo n.º 43
0
def test_get_memory_usage(single):
    simulation = single
    salary_holder = simulation.person.get_holder('salary')
    memory_usage = salary_holder.get_memory_usage()
    assert memory_usage['total_nb_bytes'] == 0
    salary_holder.set_input(periods.period(2017), numpy.asarray([30000]))
    memory_usage = salary_holder.get_memory_usage()
    assert memory_usage['nb_cells_by_array'] == 1
    assert memory_usage['cell_size'] == 4  # float 32
    assert memory_usage['nb_cells_by_array'] == 1  # one person
    assert memory_usage['nb_arrays'] == 12  # 12 months
    assert memory_usage['total_nb_bytes'] == 4 * 12 * 1
Exemplo n.º 44
0
def test_set_input_dispatch_by_period(single):
    simulation = single
    variable = simulation.tax_benefit_system.get_variable(
        'housing_occupancy_status')
    entity = simulation.household
    holder = Holder(variable, entity)
    holders.set_input_dispatch_by_period(holder, periods.period(2019), 'owner')
    assert holder.get_array('2019-01') == holder.get_array(
        '2019-12')  # Check the feature
    assert holder.get_array('2019-01') is holder.get_array(
        '2019-12'
    )  # Check that the vectors are the same in memory, to avoid duplication
Exemplo n.º 45
0
def poverty_rate(sim, period="2020-01-06", population="people", mode="ahc"):
    pop = sim.calculate("household_weight", period) * sim.calculate(
        f"{population}_in_household", period
    )
    total = np.sum(pop)
    in_poverty = np.sum(
        pop
        * sim.calculate(
            f"in_poverty_{mode}", periods.period(period).first_week
        )
    )
    return in_poverty / total
Exemplo n.º 46
0
def zip_period_with_values(period_str, values):
    period = periods.period(period_str)
    size = period.size
    if not isinstance(values, list):
        assert is_number(values)
        casted_values = [values / size] * size
    else:
        if size < len(values) and size == 1:
            size = len(values)
        casted_values = values
    period_list = [str(period.start.period(period.unit).offset(index)) for index in range(size)]
    return dict(zip(period_list, casted_values))
Exemplo n.º 47
0
def set_table_in_survey(input_dataframe, entity, period, collection, survey_name, survey_label = None,
        table_label = None, table_name = None):
    period = periods.period(period)
    if table_name is None:
        table_name = entity + '_' + str(period)
    if table_label is None:
        table_label = "Input data for entity {} at period {}".format(entity, period)
    try:
        survey_collection = SurveyCollection.load(collection = collection)
    except configparser.NoOptionError:
        survey_collection = SurveyCollection(name = collection)
    except configparser.NoSectionError:  # For tests
        data_dir = os.path.join(
            pkg_resources.get_distribution('openfisca-survey-manager').location,
            'openfisca_survey_manager',
            'tests',
            'data_files',
            )
        survey_collection = SurveyCollection(
            name = collection,
            config_files_directory = data_dir,
            )

    try:
        survey = survey_collection.get_survey(survey_name)
    except AssertionError:
        survey = Survey(
            name = survey_name,
            label = survey_label or None,
            survey_collection = survey_collection,
            )

    if survey.hdf5_file_path is None:
        config = survey.survey_collection.config
        directory_path = config.get("data", "output_directory")
        if not os.path.isdir(directory_path):
            log.warn("{} who should be the HDF5 data directory does not exist: we create the directory".format(
                directory_path))
            os.makedirs(directory_path)
        survey.hdf5_file_path = os.path.join(directory_path, survey.name + '.h5')

    assert survey.hdf5_file_path is not None
    survey.insert_table(label = table_label, name = table_name, dataframe = input_dataframe)
    survey_collection.surveys = [
        kept_survey for kept_survey in survey_collection.surveys if kept_survey.name != survey_name
        ]
    survey_collection.surveys.append(survey)
    collections_directory = survey_collection.config.get('collections', 'collections_directory')
    assert os.path.isdir(collections_directory), """{} who should be the collections' directory does not exist.
Fix the option collections_directory in the collections section of your config file.""".format(collections_directory)
    collection_json_path = os.path.join(collections_directory, "{}.json".format(collection))
    survey_collection.dump(json_file_path = collection_json_path)
Exemplo n.º 48
0
def test_get_memory_usage_with_trace(single):
    simulation = single
    simulation.trace = True
    salary_holder = simulation.person.get_holder('salary')
    salary_holder.set_input(periods.period(2017), numpy.asarray([30000]))
    simulation.calculate('salary', '2017-01')
    simulation.calculate('salary', '2017-01')
    simulation.calculate('salary', '2017-02')
    simulation.calculate_add('salary', '2017')  # 12 calculations
    memory_usage = salary_holder.get_memory_usage()
    assert memory_usage['nb_requests'] == 15
    assert memory_usage[
        'nb_requests_by_array'] == 1.25  # 15 calculations / 12 arrays
Exemplo n.º 49
0
 def cleanup_period_in_json_or_python(value, state=None):
     if value is None:
         return None, None
     value = value.copy()
     if 'date' not in value:
         year = value.pop('year', None)
         if year is not None:
             value['date'] = year
     if 'period' not in value:
         date = value.pop('date', None)
         if date is not None:
             value['period'] = periods.period(date)
     return value, None
Exemplo n.º 50
0
def stata_files_to_data_frames(data, period=None):
    assert period is not None
    period = periods.period(period)

    stata_file_by_entity = data.get('stata_file_by_entity')
    if stata_file_by_entity is None:
        return

    variables_from_stata_files = list()
    input_data_frame_by_entity_by_period = dict()
    input_data_frame_by_entity_by_period[periods.period(
        period)] = input_data_frame_by_entity = dict()
    for entity, file_path in stata_file_by_entity.items():
        assert os.path.exists(file_path), "Invalid file path: {}".format(
            file_path)
        entity_data_frame = input_data_frame_by_entity[entity] = pd.read_stata(
            file_path)
        variables_from_stata_files += list(entity_data_frame.columns)
    data[
        'input_data_frame_by_entity_by_period'] = input_data_frame_by_entity_by_period

    return variables_from_stata_files
Exemplo n.º 51
0
    def calculate(self, variable_name, period):
        if period is not None and not isinstance(period, periods.Period):
            period = periods.period(period)

        self.tracer.enter_calculation(variable_name, period)

        try:
            result = self._calculate(variable_name, period)
            self.tracer.record_calculation_result(result)
            return result

        finally:
            self.tracer.exit_calculation()
            self.purge_cache_of_invalid_values()
Exemplo n.º 52
0
def create_randomly_initialized_survey_scenario_from_table(
        nb_persons, nb_groups, salary_max_value, rent_max_value, collection,
        use_marginal_tax_rate):
    variable_generators_by_period = {
        periods.period('2017-01'): [{
            'variable': 'salary',
            'max_value': salary_max_value,
        }, {
            'variable': 'rent',
            'max_value': rent_max_value,
        }],
        periods.period('2018-01'): [
            {
                'variable': 'salary',
                'max_value': salary_max_value,
            },
        ],
    }
    table_by_entity_by_period = random_data_generator(
        tax_benefit_system, nb_persons, nb_groups,
        variable_generators_by_period, collection)
    survey_scenario = AbstractSurveyScenario()
    survey_scenario.set_tax_benefit_systems(
        tax_benefit_system=tax_benefit_system)
    survey_scenario.used_as_input_variables = [
        'salary', 'rent', 'housing_occupancy_status'
    ]
    survey_scenario.year = 2017
    survey_scenario.collection = collection
    data = {
        'survey': 'input',
        'input_data_table_by_entity_by_period': table_by_entity_by_period
    }
    survey_scenario.varying_variable = 'salary'
    survey_scenario.init_from_data(data=data,
                                   use_marginal_tax_rate=use_marginal_tax_rate)
    return survey_scenario
Exemplo n.º 53
0
def test_allocations_familiales_imposables():
    year = 2012
    reform = base.get_cached_reform(
        reform_key='allocations_familiales_imposables',
        tax_benefit_system=base.tax_benefit_system,
    )
    scenario = reform.new_scenario().init_single_entity(
        axes=[
            dict(
                count=10,
                max=30000,
                min=0,
                name='salaire_imposable',
            ),
        ],
        period=periods.period('year', year),
        parent1=dict(date_naissance=datetime.date(year - 40, 1, 1)),
        parent2=dict(date_naissance=datetime.date(year - 40, 1, 1)),
        enfants=[
            dict(date_naissance=datetime.date(year - 9, 1, 1)),
            dict(date_naissance=datetime.date(year - 9, 1, 1)),
        ],
    )

    reference_simulation = scenario.new_simulation(reference=True)

    absolute_error_margin = 0.01
    af = reference_simulation.calculate_add('af')
    expected_af = [(12 * 399.0) * .32
                   ] * 10  # Pas de hangement de BMAF en cours d'année
    assert_near(expected_af, af, absolute_error_margin=absolute_error_margin)
    rbg = reference_simulation.calculate('rbg')

    reform_simulation = scenario.new_simulation()
    reform_af = reform_simulation.calculate_add('af')

    assert_near(expected_af,
                reform_af,
                absolute_error_margin=absolute_error_margin)
    reform_af_imposables = reform_simulation.calculate(
        'allocations_familiales_imposables')
    assert_near(expected_af,
                reform_af_imposables,
                absolute_error_margin=absolute_error_margin)

    reform_rbg = reform_simulation.calculate('rbg')
    assert_near(reform_rbg,
                rbg + af,
                absolute_error_margin=absolute_error_margin)
Exemplo n.º 54
0
def test_basic_scenario():
    period = periods.period('2015')
    scenario = tax_benefit_system.new_scenario()
    scenario.init_single_entity(
        period=period,
        parent1=dict(
            date_de_naissance=datetime.date(1972, 1, 1),
            salaire=50000,
        ),
    )
    simulation = scenario.new_simulation()
    salaire = simulation.calculate('salaire', period)
    assert_equal(salaire, [50000])
    impot_revenu = simulation.calculate('impot_revenu', period)
    assert_near(impot_revenu, [15000], absolute_error_margin=0.01)
Exemplo n.º 55
0
def simple_check(tests):
    for test_parameters in tests:
        name = test_parameters["name"]
        period = test_parameters["period"]
        parent1 = dict(birth=datetime.date(
            periods.period(period).start.year - 40, 1, 1), )
        parent1.update(test_parameters['input_variables'])
        simulation = tax_benefit_system.new_scenario().init_single_entity(
            period=period,
            parent1=parent1,
        ).new_simulation(debug=True)

        for variable, monthly_amount in test_parameters[
                'output_variables'].iteritems():
            check_variable(simulation, variable, name, monthly_amount)
Exemplo n.º 56
0
def test_check():
    for test_parameters in iter_scenarios():
        test_name = test_parameters["name"]
        period = test_parameters["period"]
        parent1 = dict(birth=datetime.date(
            periods.period(period).start.year - 40, 1, 1), )
        parent1.update(test_parameters['input_variables'])
        simulation = tax_benefit_system.new_scenario().init_single_entity(
            period=period,
            parent1=parent1,
        ).new_simulation(debug=True)

        for variable_name, expected_value in test_parameters[
                'output_variables'].iteritems():
            yield check_variable, simulation, variable_name, test_name, expected_value
Exemplo n.º 57
0
    def calculate(self, variable_name, period):
        """Calculate ``variable_name`` for ``period``."""

        if period is not None and not isinstance(period, Period):
            period = periods.period(period)

        self.tracer.record_calculation_start(variable_name, period)

        try:
            result = self._calculate(variable_name, period)
            self.tracer.record_calculation_result(result)
            return result

        finally:
            self.tracer.record_calculation_end()
            self.purge_cache_of_invalid_values()
Exemplo n.º 58
0
def test_nb_enfants():
    test_case = deepcopy(TEST_CASE_AGES)
    year = 2013
    test_case['period'] = year
    simulation = tax_benefit_system.new_scenario().init_from_dict(
        test_case).new_simulation()
    from openfisca_france.model.prestations.prestations_familiales.base_ressource import nb_enf

    month = periods.period(year).first_month
    assert_near(nb_enf(simulation.famille, month, 3, 18), [2, 0])
    assert_near(nb_enf(simulation.famille, month, 19, 50),
                [0, 1])  # Adults don't count

    test_case['individus']['ind5']['autonomie_financiere'] = True
    simulation_2 = new_simulation(test_case)

    assert_near(nb_enf(simulation_2.famille, month, 19, 50), [0, 0])
Exemplo n.º 59
0
def modify_legislation_json(reference_legislation_json_copy):
    reform_legislation_subtree = {
        "@type": "Node",
        "description": u"PLF 2015 sur revenus 2013 (Décote)",
        "children": {
            "seuil_celib": {
                "@type": "Parameter",
                "description": u"Seuil de la décote pour un célibataire",
                "format": "integer",
                "unit": "currency",
                "values": [
                    {'start': u'2014-01-01', },
                    {'start': u'2013-01-01', 'value': 1135},
                    ],
                },
            "seuil_couple": {
                "@type": "Parameter",
                "description": u"Seuil de la décote pour un couple",
                "format": "integer",
                "unit": "currency",
                "values": [
                    {'start': u'2014-01-01', },
                    {'start': u'2013-01-01', 'value': 1870},
                    ],
                },
            },
        }
    reform_year = 2013
    reform_period = periods.period(reform_year)

    reference_legislation_json_copy = update_legislation(
        legislation_json = reference_legislation_json_copy,
        path = ('children', 'impot_revenu', 'children', 'bareme', 'brackets', 1, 'rate'),
        period = reform_period,
        value = 0,
        )
    reference_legislation_json_copy = update_legislation(
        legislation_json = reference_legislation_json_copy,
        path = ('children', 'impot_revenu', 'children', 'bareme', 'brackets', 2, 'threshold'),
        period = reform_period,
        value = 9690,
        )

    reference_legislation_json_copy['children']['plf2015'] = reform_legislation_subtree
    return reference_legislation_json_copy
def test_check():
    for test_parameters in tests:
        name = test_parameters["name"]
        period = test_parameters["period"]
        parent1 = dict(birth=datetime.date(
            periods.period(period).start.year - 40, 1, 1), )
        foyer_fiscal = dict()
        foyer_fiscal.update(test_parameters['input_variables'])
        simulation = tax_benefit_system.new_scenario().init_single_entity(
            period=period,
            parent1=parent1,
            foyer_fiscal=foyer_fiscal,
        ).new_simulation(debug=True)

        for variable, monthly_amount in test_parameters[
                'output_variables'].iteritems():
            output = simulation.calculate(variable)
            yield assert_variable, variable, name, monthly_amount, output