def test_person_variable_with_constructor(): simulation_yaml = """ persons: bill: salary: 2017-11: 1500 2017-12: 2000 bob: salary: {} claudia: salary: 2017-11: 3000 2017-12: 4000 janet: {} tom: {} households: first_household: parents: - bill - bob children: - janet - tom second_household: parents: - claudia """ simulation = SimulationBuilder().build_from_dict(tax_benefit_system, yaml.safe_load(simulation_yaml)) person = simulation.person assert_near(person('salary', "2017-11"), [1500, 0, 3000, 0, 0]) assert_near(person('salary', "2017-12"), [2000, 0, 4000, 0, 0])
def test_charge_loyer(): year = 2013 reform = trannoy_wasmer(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), 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', period=year) assert_near(reform_charge_loyer, [1000] * 10, absolute_error_margin=absolute_error_margin)
def test_apply_thresholds_with_variable_threshold(): input = numpy.array([1000, 1000, 1000]) thresholds = [numpy.array([500, 1500, 1000]) ] # Only one thresold, but varies with the person choice_list = [True, False] # True if input <= threshold, false otherwise result = apply_thresholds(input, thresholds, choice_list) assert_near(result, [False, True, True])
def test_add_dated_variable(): class new_dated_variable(Variable): value_type = int label = u"Nouvelle variable introduite par la réforme" entity = Household definition_period = MONTH def formula_2010_01_01(self, simulation, period): return self.zeros() + 10 def formula_2011_01_01(self, simulation, period): return self.zeros() + 15 class test_add_variable(Reform): def apply(self): self.add_variable(new_dated_variable) reform = test_add_variable(tax_benefit_system) scenario = reform.new_scenario().init_from_attributes(period=2013, ) reform_simulation = scenario.new_simulation(debug=True) new_dated_variable1 = reform_simulation.calculate('new_dated_variable', period='2013-01') assert_near(new_dated_variable1, 15, absolute_error_margin=0)
def test_plaf_qf_2012_sans_modulation_af(): year = 2015 reform = plaf_qf_2012_sans_modulation_af.build_reform(base.tax_benefit_system) scenario = reform.new_scenario().init_single_entity( axes = [ dict( count = 10, max = 10000*12, min = 0, name = 'salaire_de_base', ), ], 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)), dict(birth = datetime.date(year - 9, 1, 1)), ], ) reference_simulation = scenario.new_simulation(debug = True, reference = True) absolute_error_margin = 0.05 af = reference_simulation.calculate_add('af',2017) expected_af = [3558.36] #Todo : check exact values. reform_simulation = scenario.new_simulation(debug = True) reform_af = reform_simulation.calculate_add('af') assert_near(expected_af[0:2], reform_af[0:2], absolute_error_margin = absolute_error_margin) assert abs(af[-1] - reform_af[-1]) > 100 #TODO: that test is not neat
def test_entity_variables_with_constructor(): simulation_yaml = """ persons: bill: {} bob: {} claudia: {} janet: {} tom: {} households: first_household: parents: - bill - bob children: - janet - tom rent: 2017-06: 800 second_household: parents: - claudia rent: 2017-06: 600 """ simulation = SimulationBuilder().build_from_dict(tax_benefit_system, yaml.safe_load(simulation_yaml)) household = simulation.household assert_near(household('rent', "2017-06"), [800, 600])
def test_entity_structure_with_constructor(): simulation_yaml = """ persons: bill: {} bob: {} claudia: {} janet: {} tom: {} households: first_household: parents: - bill - bob children: - janet - tom second_household: parents: - claudia """ simulation = SimulationBuilder().build_from_dict(tax_benefit_system, yaml.safe_load(simulation_yaml)) household = simulation.household assert_near(household.members_entity_id, [0, 0, 1, 0, 0]) assert((household.members_role == [FIRST_PARENT, SECOND_PARENT, FIRST_PARENT, CHILD, CHILD]).all()) assert_near(household.members_position, [0, 1, 0, 2, 3])
def check_rstnet_to_rstbrut(count, rstbrut_max, rstbrut_min, year): scenario_args = dict( axes = [ dict( count = count, name = 'rstbrut', max = rstbrut_max, min = rstbrut_min, ), ], period = year, parent1 = dict( birth = datetime.date(year - 40, 1, 1), ), ) simulation = base.tax_benefit_system.new_scenario().init_single_entity( **scenario_args ).new_simulation(debug = True) rstbrut = simulation.get_holder('rstbrut').array rstnet = simulation.calculate('rstnet') inversion_reform = inversion_revenus.build_reform(base.tax_benefit_system) inverse_simulation = inversion_reform.new_scenario().init_single_entity( **scenario_args ).new_simulation(debug = True) inverse_simulation.get_holder('rstbrut').delete_arrays() inverse_simulation.get_or_new_holder('rstnet').array = rstnet new_rstbrut = inverse_simulation.calculate('rstbrut') assert_near(new_rstbrut, rstbrut, error_margin = 0.1)
def test_person_variable_with_constructor(): simulation_yaml = """ persons: bill: salary: 2017-11: 1500 2017-12: 2000 bob: salary: {} claudia: salary: 2017-11: 3000 2017-12: 4000 janet: {} tom: {} households: first_household: parents: - bill - bob children: - janet - tom second_household: parents: - claudia """ simulation = simulation_builder.build_from_dict(tax_benefit_system, yaml.load(simulation_yaml)) person = simulation.person assert_near(person('salary', "2017-11"), [1500, 0, 3000, 0, 0]) assert_near(person('salary', "2017-12"), [2000, 0, 4000, 0, 0])
def test_charge_loyer(): year = 2013 reform = trannoy_wasmer.build_reform(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(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)), ], menage = dict( loyer = 1000, ), ) reform_simulation = scenario.new_simulation(debug = True) error_margin = 0.01 reform_charge_loyer = reform_simulation.calculate('charge_loyer') assert_near(reform_charge_loyer, [1000] * 10 ,error_margin)
def test_role_index_and_positions(): simulation = new_simulation(TEST_CASE) assert_near(simulation.household.members_entity_id, [0, 0, 0, 0, 1, 1]) assert((simulation.household.members_role == [FIRST_PARENT, SECOND_PARENT, CHILD, CHILD, FIRST_PARENT, CHILD]).all()) assert_near(simulation.household.members_position, [0, 1, 2, 3, 0, 1]) assert(simulation.person.ids == ["ind0", "ind1", "ind2", "ind3", "ind4", "ind5"]) assert(simulation.household.ids == ['h1', 'h2'])
def test_update_variable(): class disposable_income(Variable): definition_period = MONTH def formula(self, simulation, period): return self.zeros() + 10 class test_update_variable(Reform): def apply(self): self.update_variable(disposable_income) reform = test_update_variable(tax_benefit_system) year = 2013 scenario = reform.new_scenario().init_from_attributes(period=year, ) disposable_income_reform = reform.get_variable('disposable_income') disposable_income_reference = tax_benefit_system.get_variable( 'disposable_income') assert disposable_income_reform is not None assert disposable_income_reform.entity.plural == disposable_income_reference.entity.plural assert disposable_income_reform.name == disposable_income_reference.name assert disposable_income_reform.label == disposable_income_reference.label reform_simulation = scenario.new_simulation() disposable_income1 = reform_simulation.calculate('disposable_income', period='2013-01') assert_near(disposable_income1, 10, absolute_error_margin=0)
def test(): year = 2013 reform = build_reform(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 test_combine_tax_scales(): from openfisca_core.parameters import ParameterNode node = ParameterNode('baremes', data = { 'health': { 'brackets': [ { 'rate': {'2015-01-01': 0.05}, 'threshold': {'2015-01-01': 0} }, { 'rate': {'2015-01-01': 0.10}, 'threshold': {'2015-01-01': 2000} }, ]}, 'retirement': { 'brackets': [ { 'rate': {'2015-01-01': 0.02}, 'threshold': {'2015-01-01': 0} }, { 'rate': {'2015-01-01': 0.04}, 'threshold': {'2015-01-01': 3000} }, ] }, })(2015) bareme = combine_tax_scales(node) assert_near(bareme.thresholds, [0, 2000, 3000]) assert_near(bareme.rates, [0.07, 0.12, 0.14], 1e-13)
def test_reform(): year = 2014 input_data_frame = get_fake_input_data_frame(year) # On ne garde que les deux parents input_data_frame.loc[0, 'salaire_imposable'] = 20000 input_data_frame.loc[1, 'salaire_imposable'] = 18000 input_data_frame = input_data_frame.loc[0:1].copy() reform = base.get_cached_reform( reform_key = 'plf2015', tax_benefit_system = base.france_data_tax_benefit_system, ) year = 2013 survey_scenario = ErfsSurveyScenario.create( tax_benefit_system = reform, baseline_tax_benefit_system = base.france_data_tax_benefit_system, year = year, ) survey_scenario.init_from_data( data = dict(input_data_frame = input_data_frame), ) error_margin = 1 assert_near(survey_scenario.calculate_variable('irpp', use_baseline = True, period = year), [-10124, -869], error_margin) assert_near(survey_scenario.calculate_variable('irpp', period = year), [-10118, -911.4 + (1135 - 911.4)], error_margin)
def test_charge_loyer(): year = 2013 reform = trannoy_wasmer.build_reform(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(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)), ], menage=dict(loyer=1000, ), ) reform_simulation = scenario.new_simulation(debug=True) error_margin = 0.01 reform_charge_loyer = reform_simulation.calculate('charge_loyer') assert_near(reform_charge_loyer, [1000] * 10, error_margin)
def test_amount_tax_scale(): base = np.array([1, 8, 10]) amount_tax_scale = AmountTaxScale() amount_tax_scale.add_bracket(6, 0.23) amount_tax_scale.add_bracket(9, 0.29) assert_near(amount_tax_scale.calc(base), [0, 0.23, 0.52])
def test_fake_calibration_float(): year = 2006 calibration = create_fake_calibration() calibration.total_population = calibration.initial_total_population * 1.123 revenu_disponible_target = 7e6 calibration.set_target_margin('revenu_disponible', revenu_disponible_target) calibration.calibrate() calibration.set_calibrated_weights() simulation = calibration.survey_scenario.simulation assert_near( simulation.calculate("wprm", period = year).sum(), calibration.total_population, absolute_error_margin = None, relative_error_margin = .00001 ) assert_near( (simulation.calculate('revenu_disponible', period = year) * simulation.calculate("wprm", period = year)).sum(), revenu_disponible_target, absolute_error_margin = None, relative_error_margin = .00001 ) return calibration
def test_cotisation_1_level(): month = reference_period.last_month simulation = tax_benefit_system.new_scenario().init_from_attributes( period=month, # December ).new_simulation(debug=True) cotisation = simulation.calculate('cotisation', period=month) assert_near(cotisation, [2])
def test_sum_following_bug_ipp_2(): test_case = { 'persons': [{ 'id': 'ind0' }, { 'id': 'ind1' }, { 'id': 'ind2' }, { 'id': 'ind3' }], 'households': [{ 'parents': ['ind1'], 'children': ['ind2', 'ind3'] }, { 'parents': ['ind0'] }], } test_case['persons'][0]['salary'] = 2000 test_case['persons'][1]['salary'] = 2000 test_case['persons'][2]['salary'] = 1000 test_case['persons'][3]['salary'] = 1000 simulation = new_simulation(test_case) household = simulation.household eligible_i = household.members('salary', period=MONTH) < 1500 nb_eligibles_by_household = household.sum(eligible_i, role=CHILD) assert_near(nb_eligibles_by_household, [2, 0])
def check_revenu_disponible(year, depcom, expected_revenu_disponible): simulation = tax_benefit_system.new_scenario().init_single_entity( axes=[ dict( count=3, name='salaire_brut', max=100000, min=0, ), ], famille=dict(depcom=depcom), period=periods.period(year), parent1=dict(), parent2=dict(), ).new_simulation(debug=True) revenu_disponible = simulation.calculate('revenu_disponible') assert_near(revenu_disponible, expected_revenu_disponible, absolute_error_margin=0.005) revenu_disponible_famille = simulation.calculate( 'revenu_disponible_famille') expected_revenu_disponible_famille = np.array([ expected_revenu_disponible[i] + expected_revenu_disponible[i + 1] for i in range(0, len(expected_revenu_disponible), 2) ]) assert_near(revenu_disponible_famille, expected_revenu_disponible_famille, absolute_error_margin=0.005)
def test_2_parallel_axes_1_constant(): year = 2013 simulation = tax_benefit_system.new_scenario().init_single_entity( axes=[ [ dict( count=3, name='salaire_brut', max=100000, min=0, ), dict( count=3, index=1, name='salaire_brut', max=0.0001, min=0, ), ], ], period=year, parent1={}, parent2={}, ).new_simulation(debug=True) assert_near(simulation.calculate('revenu_disponible_famille'), [7200, 28800, 54000], absolute_error_margin=0.005)
def check(name, period_str, test, force): scenario = test['scenario'] scenario.suggest() simulation = scenario.new_simulation(debug=True) output_variables = test.get(u'output_variables') if output_variables is not None: output_variables_name_to_ignore = test.get( u'output_variables_name_to_ignore') or set() for variable_name, expected_value in output_variables.iteritems(): if not force and variable_name in output_variables_name_to_ignore: continue if isinstance(expected_value, dict): for requested_period, expected_value_at_period in expected_value.iteritems( ): assert_near( simulation.calculate(variable_name, requested_period), expected_value_at_period, absolute_error_margin=test.get( 'absolute_error_margin'), message=u'{}@{}: '.format(variable_name, requested_period), relative_error_margin=test.get( 'relative_error_margin'), ) else: assert_near( simulation.calculate(variable_name), expected_value, absolute_error_margin=test.get('absolute_error_margin'), message=u'{}@{}: '.format(variable_name, period_str), relative_error_margin=test.get('relative_error_margin'), )
def test_essence_ticpe(): year = 2013 simulation = base.tax_benefit_system.new_scenario().init_single_entity( period = year, personne_de_reference = dict( birth = datetime.date(year - 40, 1, 1), ), menage = dict( depenses_carburants = 100, veh_essence = 1, veh_diesel = 0, ), ).new_simulation(debug = True) depenses_htva = 100 / (1.196) sp95_depenses_htva = depenses_htva * 0.627 / 0.996 sp98_depenses_htva = depenses_htva * 0.188 / 0.996 sp_e10_depenses_hta = depenses_htva * 0.181 / 0.996 taux_implicite_95 = ((0.6069 + 0.025) * 1.196) / (1.5367 - ((0.6069 + 0.025) * 1.196)) taux_implicite_98 = ((0.6069 + 0.025) * 1.196) / (1.5943 - ((0.6069 + 0.025) * 1.196)) taux_implicite_e10 = ((0.6069 + 0.025) * 1.196) / (1.51 - ((0.6069 + 0.025) * 1.196)) coefficient_95 = taux_implicite_95 / (1 + taux_implicite_95) coefficient_98 = taux_implicite_98 / (1 + taux_implicite_98) coefficient_e10 = taux_implicite_e10 / (1 + taux_implicite_e10) assert_near(simulation.calculate('ticpe_totale'), coefficient_95 * sp95_depenses_htva + coefficient_98 * sp98_depenses_htva + coefficient_e10 * sp_e10_depenses_hta, .01)
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_sum_following_bug_ipp_2(): test_case = { 'individus': [{ 'id': 'ind0' }, { 'id': 'ind1' }, { 'id': 'ind2' }, { 'id': 'ind3' }], 'familles': [{ 'parents': ['ind1'], 'enfants': ['ind2', 'ind3'] }, { 'parents': ['ind0'] }], } test_case['individus'][0]['a_charge_fiscale'] = False test_case['individus'][1]['a_charge_fiscale'] = False test_case['individus'][2]['a_charge_fiscale'] = True test_case['individus'][3]['a_charge_fiscale'] = True simulation = new_simulation(test_case) famille = simulation.famille elibible_i = famille.members('a_charge_fiscale') nb_eligibles_par_famille = famille.sum(elibible_i, role=ENFANT) assert_near(nb_eligibles_par_famille, [2, 0])
def check_rstnet_to_rstbrut(count, rstbrut_max, rstbrut_min, year): scenario_args = dict( axes=[ dict( count=count, name='rstbrut', max=rstbrut_max, min=rstbrut_min, ), ], period=year, parent1=dict(birth=datetime.date(year - 40, 1, 1), ), ) simulation = base.tax_benefit_system.new_scenario().init_single_entity( **scenario_args).new_simulation(debug=True) rstbrut = simulation.get_holder('rstbrut').array rstnet = simulation.calculate('rstnet') inversion_reform = inversion_revenus.build_reform(base.tax_benefit_system) inverse_simulation = inversion_reform.new_scenario().init_single_entity( **scenario_args).new_simulation(debug=True) inverse_simulation.get_holder('rstbrut').delete_arrays() inverse_simulation.get_or_new_holder('rstnet').array = rstnet new_rstbrut = inverse_simulation.calculate('rstbrut') assert_near(new_rstbrut, rstbrut, error_margin=0.1)
def check_salaire_net_to_salbrut(count, salbrut_max, salbrut_min, type_sal, year): scenario_args = dict( axes = [ dict( count = count, name = 'salbrut', max = salbrut_max, min = salbrut_min, ), ], period = year, parent1 = dict( birth = datetime.date(year - 40, 1, 1), type_sal = type_sal, ), ) simulation = base.tax_benefit_system.new_scenario().init_single_entity( **scenario_args ).new_simulation() salbrut = simulation.get_holder('salbrut').array salaire_net = simulation.calculate('salaire_net') inversion_reform = inversion_revenus.build_reform(base.tax_benefit_system) inverse_simulation = inversion_reform.new_scenario().init_single_entity( **scenario_args ).new_simulation() inverse_simulation.get_holder('salbrut').delete_arrays() inverse_simulation.get_or_new_holder('salaire_net').array = salaire_net new_salbrut = inverse_simulation.calculate('salbrut') assert_near(new_salbrut, salbrut, absolute_error_margin = 0.1)
def test_entity_variables_with_constructor(): simulation_yaml = """ persons: bill: {} bob: {} claudia: {} janet: {} tom: {} households: first_household: parents: - bill - bob children: - janet - tom rent: 2017-06: 800 second_household: parents: - claudia rent: 2017-06: 600 """ simulation = simulation_builder.build_from_dict(tax_benefit_system, yaml.load(simulation_yaml)) household = simulation.household assert_near(household('rent', "2017-06"), [800, 600])
def test_irpp(year, irpp, **variables_value_by_name): simulation = simulations.Simulation(period=periods.period(year), tax_benefit_system=tax_benefit_system, debug=args.verbose) famille = simulation.entity_by_key_singular['famille'] foyer_fiscal = simulation.entity_by_key_singular['foyer_fiscal'] individu = simulation.entity_by_key_singular['individu'] menage = simulation.entity_by_key_singular['menage'] # Dispatch arguments to their respective entities. variables_value_by_name_by_entity = {} for variable_name, value in variables_value_by_name.iteritems(): variable_holder = simulation.get_or_new_holder(variable_name) entity_variables_value_by_name = variables_value_by_name_by_entity.setdefault( variable_holder.entity, {}) entity_variables_value_by_name[variable_name] = value add_member(famille, **variables_value_by_name_by_entity.get(famille, {})) add_member(foyer_fiscal, **variables_value_by_name_by_entity.get(foyer_fiscal, {})) add_member(menage, **variables_value_by_name_by_entity.get(menage, {})) add_member(individu, quifam=1, quifoy=1, quimen=1, **variables_value_by_name_by_entity.get(individu, {})) assert_near(simulation.calculate('irpp'), irpp, absolute_error_margin=0.51)
def test_parametric_reform(): reform = ir_100_tranche_1(tax_benefit_system) scenario = reform.new_scenario().init_single_entity( axes = [ dict( count = 3, name = 'salaire_imposable', max = 100000, min = 0, ), ], period = simulation_period, parent1 = dict(date_naissance = datetime.date(simulation_year - 40, 1, 1)), ) reference_simulation = scenario.new_simulation(use_baseline = True) assert_near(reference_simulation.calculate('impots_directs', period = simulation_period), [0, -7889.20019531, -23435.52929688], absolute_error_margin = 1) reform_simulation = scenario.new_simulation() assert_near( reform_simulation.calculate('impots_directs', simulation_period), [0, -13900.20019531, -29446.52929688], absolute_error_margin = 1, )
def test_input_variable_neutralization(): class test_salary_neutralization(Reform): def apply(self): self.neutralize_variable('salary') reform = test_salary_neutralization(tax_benefit_system) period = '2017-01' scenario = reform.new_scenario().init_from_attributes( period=period, input_variables=dict(salary=[1200, 1000])) reform = test_salary_neutralization(tax_benefit_system) with warnings.catch_warnings(record=True) as raised_warnings: reform_simulation = scenario.new_simulation() assert 'You cannot set a value for the variable' in raised_warnings[ 0].message.message salary = reform_simulation.calculate('salary', period) assert_near( salary, [0, 0], ) disposable_income_reform = reform_simulation.calculate('disposable_income', period=period) assert_near(disposable_income_reform, [600, 600])
def test_fake_calibration_float(fake_calibration, year: int = 2006): calibration = fake_calibration(year) calibration.total_population = calibration.initial_total_population * 1.123 revenu_disponible_target = 7e6 calibration.set_target_margin("revenu_disponible", revenu_disponible_target) calibration.calibrate() calibration.set_calibrated_weights() simulation = calibration.survey_scenario.simulation assert_near( simulation.calculate("wprm", period=year).sum(), calibration.total_population, absolute_error_margin=None, relative_error_margin=0.00001, ) assert_near( (+simulation.calculate("revenu_disponible", period=year) * simulation.calculate("wprm", period=year)).sum(), revenu_disponible_target, absolute_error_margin=None, relative_error_margin=0.00001, )
def test_fake_calibration_age(fake_calibration, fake_input_data, year: int = 2006): calibration = fake_calibration(fake_input_data, year) survey_scenario = calibration.survey_scenario calibration.total_population = calibration.initial_total_population * 1.123 calibration.set_target_margin("age", [95, 130]) calibration.calibrate() calibration.set_calibrated_weights() simulation = survey_scenario.simulation assert_near( simulation.calculate("wprm").sum(), calibration.total_population, absolute_error_margin=None, relative_error_margin=0.00001, ) age = (survey_scenario.simulation.calculate("age"), ) weight_individus = survey_scenario.simulation.calculate("weight_individus") for category, target in calibration.margins_by_variable["age"][ "target"].items(): actual = ((age == category) * weight_individus).sum() / weight_individus.sum() target = target / numpy.sum( calibration.margins_by_variable["age"]["target"].values()) assert_near( actual, target, absolute_error_margin=None, relative_error_margin=0.00001, )
def test_fake_calibration_age(): calibration = create_fake_calibration() survey_scenario = calibration.survey_scenario calibration.total_population = calibration.initial_total_population * 1.123 calibration.set_target_margin('age', [95, 130]) calibration.calibrate() calibration.set_calibrated_weights() simulation = survey_scenario.simulation assert_near( simulation.calculate("wprm").sum(), calibration.total_population, absolute_error_margin = None, relative_error_margin = .00001 ) age = survey_scenario.simulation.calculate('age'), wprm = survey_scenario.simulation.calculate('wprm') for category, target in calibration.margins_by_variable['age']['target'].iteritems(): assert_near( ((age == category) * wprm).sum() / wprm.sum(), target / numpy.sum(calibration.margins_by_variable['age']['target'].values()), absolute_error_margin = None, relative_error_margin = .00001 ) return calibration
def test_get_formula(simulation): person = simulation.person disposable_income_formula = tax_benefit_system.get_variable('disposable_income').get_formula() disposable_income = person('disposable_income', '2017-01') disposable_income_2 = disposable_income_formula(person, '2017-01', None) # No need for parameters here assert_near(disposable_income, disposable_income_2)
def test_set_input_parallel_axes(): year = "2016-01" simulation = tax_benefit_system.new_scenario().init_single_entity( axes=[ [ dict( count=3, index=0, name='salary', max=100000, min=0, ), dict( count=3, index=1, name='salary', max=100000, min=0, ), ], ], period=year, parent1={}, parent2={}, enfants=[{ "salary": 2000 }]).new_simulation() assert_near(simulation.calculate_add('salary', year), [0, 0, 2000, 50000, 50000, 2000, 100000, 100000, 2000], absolute_error_margin=0.01)
def test_2_parallel_axes(): period = "2016-01" simulation = tax_benefit_system.new_scenario().init_single_entity( axes=[ [ dict( count=3, name='salary', max=10000, min=0, ), dict( count=3, index=1, name='salary', max=1000, min=0, ), ], ], period=period, parent1={}, parent2={}, ).new_simulation() assert_near(simulation.calculate('salary', period), [0, 0, 5000, 500, 10000, 1000])
def test_parametric_reform(): reform = ir_100_tranche_1(tax_benefit_system) scenario = reform.new_scenario().init_single_entity( axes=[ dict( count=3, name='salaire_imposable', max=100000, min=0, ), ], period=simulation_period, parent1=dict(date_naissance=datetime.date(simulation_year - 40, 1, 1)), ) reference_simulation = scenario.new_simulation(use_baseline=True) assert_near(reference_simulation.calculate('impots_directs', period=simulation_period), [0, -7889.20019531, -23435.52929688], absolute_error_margin=1) reform_simulation = scenario.new_simulation() assert_near( reform_simulation.calculate('impots_directs', simulation_period), [0, -13900.20019531, -29446.52929688], absolute_error_margin=1, )
def test_update_variable(make_simulation): class disposable_income(Variable): definition_period = MONTH def formula_2018(household, period): return household.empty_array() + 10 class test_update_variable(Reform): def apply(self): self.update_variable(disposable_income) reform = test_update_variable(tax_benefit_system) disposable_income_reform = reform.get_variable('disposable_income') disposable_income_baseline = tax_benefit_system.get_variable('disposable_income') assert disposable_income_reform is not None assert disposable_income_reform.entity.plural == disposable_income_baseline.entity.plural assert disposable_income_reform.name == disposable_income_baseline.name assert disposable_income_reform.label == disposable_income_baseline.label reform_simulation = make_simulation(reform, 2018, {}) disposable_income1 = reform_simulation.calculate('disposable_income', period = '2018-01') assert_near(disposable_income1, 10, absolute_error_margin = 0) disposable_income2 = reform_simulation.calculate('disposable_income', period = '2017-01') # Before 2018, the former formula is used assert(disposable_income2 > 100)
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 check(name, period_str, test, force): scenario = test['scenario'] # scenario.suggest() simulation = scenario.new_simulation(debug = True) output_variables = test.get(u'output_variables') if output_variables is not None: output_variables_name_to_ignore = test.get(u'output_variables_name_to_ignore') or set() for variable_name, expected_value in output_variables.iteritems(): if not force and variable_name in output_variables_name_to_ignore: continue if isinstance(expected_value, dict): for requested_period, expected_value_at_period in expected_value.iteritems(): assert_near( simulation.calculate(variable_name, requested_period), expected_value_at_period, absolute_error_margin = test.get('absolute_error_margin'), message = u'{}@{}: '.format(variable_name, requested_period), relative_error_margin = test.get('relative_error_margin'), ) else: assert_near( simulation.calculate(variable_name), expected_value, absolute_error_margin = test.get('absolute_error_margin'), message = u'{}@{}: '.format(variable_name, period_str), relative_error_margin = test.get('relative_error_margin'), )
def test(): year = 2013 reform = landais_piketty_saez(tax_benefit_system) scenario = init_single_entity(reform.new_scenario(), axes = [[ dict( count = 3, max = 30000, min = 0, name = 'salaire_de_base', ), ]], period = periods.period(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(use_baseline = True) # reform_simulation = scenario.new_simulation() reform_assiette_csg = reform_simulation.calculate('assiette_csg', period = year) reform_impot_revenu_lps = reform_simulation.calculate('impot_revenu_lps', period = year) assert_near( -reform_impot_revenu_lps, ((reform_assiette_csg - 10000) * .25 / 30000 + .25) * reform_assiette_csg, absolute_error_margin = 0.01, ) reform_simulation.calculate('revenu_disponible', period = year)
def test_2_parallel_axes_same_values(): year = 2013 simulation = tax_benefit_system.new_scenario().init_single_entity( axes = [ [ dict( count = 3, name = 'salaire_brut', max = 100000, min = 0, ), dict( count = 3, index = 1, name = 'salaire_brut', max = 100000, min = 0, ), ], ], period = year, parent1 = {}, parent2 = {}, ).new_simulation(debug = True) assert_near(simulation.calculate('revenu_disponible_famille'), [7200, 50400, 100800], absolute_error_margin = 0.005)
def test_with_enum(): class TypesZone(Enum): z1 = "Zone 1" z2 = "Zone 2" zone = np.asarray([TypesZone.z1, TypesZone.z2, TypesZone.z2, TypesZone.z1]) assert_near(P.single.owner[zone], [100, 200, 200, 100])
def test_cotisation_1_level(): simulation = tax_benefit_system.new_scenario().init_single_entity( period = reference_period.last_month, # December parent1 = dict(), ).new_simulation(debug = True) cotisation = simulation.calculate('cotisation') assert_near(cotisation, [2])
def test_2_parallel_axes_different_periods(): period_1 = "2016-01" period_2 = "2016-02" simulation = tax_benefit_system.new_scenario().init_single_entity( axes=[ [ dict( count=3, name='salary', max=1200, min=0, period=period_1, ), dict( count=3, index=1, name='salary', max=1200, min=0, period=period_2, ), ], ], period=period_2, parent1={}, parent2={}, ).new_simulation() assert_near(simulation.calculate('salary', period_1), [0, 0, 600, 0, 1200, 0]) assert_near(simulation.calculate_add('salary', period_2), [0, 0, 0, 600, 0, 1200])
def test_cycle_1_level(): simulation = tax_benefit_system.new_scenario().init_single_entity( period = reference_period, parent1 = dict(), ).new_simulation(debug = True) variable7 = simulation.calculate('variable7') # variable8 = simulation.calculate('variable8') assert_near(variable7, [22])
def test_value_from_person(): test_case = deepcopy(TEST_CASE_AGES) simulation = new_simulation(test_case) foyer_fiscal = simulation.foyer_fiscal age_conjoint = foyer_fiscal.conjoint('age', period='2013-01') assert_near(age_conjoint, [37, 0])
def test_combination_projections(): test_case = deepcopy(TEST_CASE_AGES) simulation = new_simulation(test_case) individu = simulation.persons age_parent1 = individu.famille.demandeur('age') assert_near(age_parent1, [40, 40, 40, 40, 54, 54])
def test_cache_disk(couple): simulation = couple simulation.memory_config = force_storage_on_disk month = make_period('2017-01') holder = simulation.person.get_holder('disposable_income') data = np.asarray([2000, 3000]) holder.put_in_cache(data, month) stored_data = holder.get_array(month) assert_near(data, stored_data)
def test_simple_linear_average_rate_tax_scale(): base = np.array([1, 1.5, 2, 2.5, 3.0, 4.0]) marginal_tax_scale = MarginalRateTaxScale() marginal_tax_scale.add_bracket(0, 0) marginal_tax_scale.add_bracket(1, 0.1) marginal_tax_scale.add_bracket(2, 0.2) marginal_tax_scale.add_bracket(3, 0) assert_near(marginal_tax_scale.calc(base), [0, .05, .1, .2, .3, .3], absolute_error_margin = 1e-10)
def test_implicit_projection(): test_case = deepcopy(TEST_CASE) test_case['households']['h1']['housing_tax'] = 20000 simulation = new_simulation(test_case, YEAR) individu = simulation.person housing_tax = individu.household('housing_tax', YEAR) assert_near(housing_tax, [20000, 20000, 20000, 20000, 0, 0])
def test_rank(): test_case = deepcopy(TEST_CASE_AGES) simulation = new_simulation(test_case) person = simulation.person age = person('age', MONTH) # [40, 37, 7, 9, 54, 20] rank = person.get_rank(person.household, age) assert_near(rank, [3, 2, 0, 1, 1, 0]) rank_in_siblings = person.get_rank(person.household, - age, condition = person.has_role(Household.CHILD)) assert_near(rank_in_siblings, [-1, -1, 1, 0, -1, 0])
def test_min(): test_case = deepcopy(TEST_CASE_AGES) simulation = new_simulation(test_case) household = simulation.household age = household.members('age', period = MONTH) age_min = household.min(age) assert_near(age_min, [7, 20]) age_min_parents = household.min(age, role = PARENT) assert_near(age_min_parents, [37, 54])
def test_neutralization_variable_with_default_value(make_simulation): class test_goes_to_school_neutralization(Reform): def apply(self): self.neutralize_variable('goes_to_school') reform = test_goes_to_school_neutralization(tax_benefit_system) period = "2017-01" simulation = make_simulation(reform.base_tax_benefit_system, period, {}) goes_to_school = simulation.calculate('goes_to_school', period) assert_near(goes_to_school, [True], absolute_error_margin = 0)