diff --git a/changelog.d/export-source-inputs.added.md b/changelog.d/export-source-inputs.added.md new file mode 100644 index 000000000..841af2a08 --- /dev/null +++ b/changelog.d/export-source-inputs.added.md @@ -0,0 +1 @@ +Export recorded IDs and declared observations, carry or uprate inputs for a requested period, and name the supplied formula values omitted from input exports. diff --git a/changelog.d/flat-file-datasets.fixed.md b/changelog.d/flat-file-datasets.fixed.md new file mode 100644 index 000000000..6cba4739e --- /dev/null +++ b/changelog.d/flat-file-datasets.fixed.md @@ -0,0 +1 @@ +Load flat files with exact variable names and optional person IDs, preserve population structure through exports, and name missing group membership columns. diff --git a/changelog.d/map-categorical-to-groups.fixed.md b/changelog.d/map-categorical-to-groups.fixed.md new file mode 100644 index 000000000..8f7f28a91 --- /dev/null +++ b/changelog.d/map-categorical-to-groups.fixed.md @@ -0,0 +1 @@ +Map text and enums to the value each group's members share, use the first enum member for empty groups, and raise when members disagree. diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 0b65c1dd9..5efd7694f 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -12,6 +12,24 @@ The `policyengine_core.simulations` module contains the definition of `Simulatio :show-inheritance: ``` +### Exporting flat-file inputs + +`Simulation.to_input_dataframe(period=...)` exports stored inputs for the +requested period, all-time inputs, and the inputs the simulation carries or +uprates for that period. It also exports person IDs, group membership and +roles. A group appears in the file if it has at least one member. A formula +that reads another period needs inputs from that period too. Omit `period` +to include inputs from every stored period. + +### Mapping text and enums + +A group receives the text or enum value its members share. Members with +different values raise a `ValueError`. An empty group receives an empty string +or the first enum member. Enum mapping returns an `EnumArray` by default. Use +`calculate(..., map_to=..., decode_enums=True)` to compare enum labels, such +as `"IA"`. If you need arithmetic on enum codes, convert the source values to +a numeric array before mapping. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/data/dataset.py b/policyengine_core/data/dataset.py index 1f87103ca..b233e438d 100644 --- a/policyengine_core/data/dataset.py +++ b/policyengine_core/data/dataset.py @@ -482,7 +482,29 @@ def from_file(file_path: str, time_period: str = None): @staticmethod def from_dataframe(dataframe: pd.DataFrame, time_period: str = None): - """Creates a dataset from a DataFrame. + """Creates a dataset from a person-level DataFrame. + + Each row is one person. A column named ``variable__period`` holds that + variable for that period, and a column named ``variable`` holds it for + ``time_period``. An exact registered name takes precedence over splitting + at the last ``__``. Variables defined for all time accept any period, + and ``Simulation.to_input_dataframe`` spells theirs ``ETERNITY``. + + Each row also says which group the person belongs to, through a + ``person_{entity}_id`` or ``{entity}_id`` column for every group entity. + A ``person_id`` column is optional, and rows number people without one. + A group variable reads its value from the first member's row. + + Period exports reserve ``person_id__STRUCTURE`` for person labels and + ``person_{entity}_id__STRUCTURE`` for group positions. They repeat the + group label in ``{entity}_id__STRUCTURE`` and give each person's role key + in ``person_{entity}_role__STRUCTURE``. These columns take precedence + when building the population. Their values never become variable inputs. + A group needs a member row to appear in the file. + + Args: + dataframe (pd.DataFrame): The person-level data. + time_period (str, optional): The period of unsuffixed columns. Returns: Dataset: The dataset. diff --git a/policyengine_core/reforms/reform.py b/policyengine_core/reforms/reform.py index afcee0358..6f4b60864 100644 --- a/policyengine_core/reforms/reform.py +++ b/policyengine_core/reforms/reform.py @@ -136,6 +136,9 @@ def __init__(self, baseline: TaxBenefitSystem): # by previously-computed baseline ``ParameterNodeAtInstant`` objects. self._parameters_at_instant_cache = {} self.variables = baseline.variables.copy() + self.source_input_variables = ( + baseline.source_input_variables | self.source_input_variables + ) self.decomposition_file_path = baseline.decomposition_file_path self.key = self.__class__.__name__ if not hasattr(self, "apply"): diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index de5824c59..230dd19b8 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -29,7 +29,7 @@ from policyengine_core.holders.holder import Holder from policyengine_core.periods import Period from policyengine_core.periods.config import ETERNITY, MONTH, YEAR -from policyengine_core.periods.helpers import period +from policyengine_core.periods.helpers import period, unit_weight from policyengine_core.tracers import ( FullTracer, SimpleTracer, @@ -73,6 +73,19 @@ def __init__(self, simulation: "Simulation"): ) +_FLAT_STRUCTURE_SUFFIX = "__STRUCTURE" + + +def _flat_column_variable(column: str) -> str: + """The variable a flat-file column belongs to: ``variable__period``.""" + return column.rsplit("__", 1)[0] + + +def _is_categorical(values: ArrayLike) -> bool: + """Whether values are text or enums, which have no sum or share.""" + return isinstance(values, EnumArray) or np.asarray(values).dtype.kind in "USO" + + def _stable_hash_to_seed(value: str) -> int: """Deterministically hash a string to an int suitable for numpy.random.seed. @@ -1107,37 +1120,54 @@ def build_from_dataset(self) -> None: + "Make sure you have downloaded or built it using the `policyengine-core data` command." ) from e - if self.dataset.data_format == Dataset.FLAT_FILE: - data_copy = {col: data[col].values for col in data.copy().columns} - data = {col: data[col].values for col in data.columns} + is_flat_file = self.dataset.data_format == Dataset.FLAT_FILE + if is_flat_file: + row_count = len(data) + data = {column: data[column].values for column in data.columns} person_entity = self.tax_benefit_system.person_entity entity_id_field = f"{person_entity.key}_id" + def flat_column_variable(column): + if column in self.tax_benefit_system.variables: + return column + return column.rsplit("__", 1)[0] + + def take_flat_structure(name): + return data.pop(f"{name}{_FLAT_STRUCTURE_SUFFIX}", None) + def get_eternity_array(name): - if self.dataset.data_format == Dataset.FLAT_FILE: - # Look for any column with variablename__timeperiod + if is_flat_file: for col in data: - if col.split("__")[0] == name: + if flat_column_variable(col) == name: return data[col] elif self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS: return data[name][list(data[name].keys())[0]] return data[name] - if self.dataset.data_format != Dataset.FLAT_FILE: + def has_column(name): + if is_flat_file: + return any(flat_column_variable(column) == name for column in data) + return name in data + + entity_ids = None + if is_flat_file: + entity_ids = take_flat_structure(entity_id_field) + if entity_ids is None and not has_column(entity_id_field): + entity_ids = np.arange(row_count) + else: assert entity_id_field in data, ( f"Missing {entity_id_field} column in the dataset. Each person entity must have an ID array defined for ETERNITY." ) - elif entity_id_field not in data: - data[entity_id_field] = np.arange(len(get_eternity_array("person_id"))) - entity_ids = get_eternity_array(entity_id_field) + if entity_ids is None: + entity_ids = get_eternity_array(entity_id_field) builder.declare_person_entity(person_entity.key, entity_ids) for group_entity in self.tax_benefit_system.group_entities: entity_id_field = f"{group_entity.key}_id" person_membership_id_field = f"{person_entity.key}_{group_entity.key}_id" - if self.dataset.data_format != Dataset.FLAT_FILE: + if not is_flat_file: assert entity_id_field in data, ( f"Missing {entity_id_field} column in the dataset. Each group entity must have an ID array defined for ETERNITY." ) @@ -1147,36 +1177,66 @@ def get_eternity_array(name): ) person_membership_ids = get_eternity_array(person_membership_id_field) else: - # A flat file has one row per person, so it declares each - # group only through its members' rows: their membership - # column or, failing that, the group's ID column repeated on - # each member's row. Number the distinct IDs 0, 1, ... and - # give each person their group's number. - membership_field = next( - ( - field - for field in (person_membership_id_field, entity_id_field) - if any(column.split("__")[0] == field for column in data) - ), - person_membership_id_field, - ) - membership_values = get_eternity_array(membership_field) + group_labels = take_flat_structure(entity_id_field) + membership_values = take_flat_structure(person_membership_id_field) + if membership_values is not None: + membership_field = ( + f"{person_membership_id_field}{_FLAT_STRUCTURE_SUFFIX}" + ) + else: + if group_labels is not None: + raise ValueError( + f"{entity_id_field}{_FLAT_STRUCTURE_SUFFIX} requires " + f"{person_membership_id_field}{_FLAT_STRUCTURE_SUFFIX}." + ) + membership_field = next( + ( + field + for field in (person_membership_id_field, entity_id_field) + if has_column(field) + ), + None, + ) + if membership_field is None: + raise ValueError( + f"The dataset has no {person_membership_id_field} or " + f"{entity_id_field} column. A flat file needs one, on " + f"every person's row, to say which {group_entity.key} " + "that person belongs to." + ) + membership_values = get_eternity_array(membership_field) if pd.isna(membership_values).any(): - # np.unique would merge every missing membership into one - # group. raise ValueError( f"{int(pd.isna(membership_values).sum())} person(s) " f"have no {membership_field} in the dataset." ) - distinct_ids, person_membership_ids = np.unique( - membership_values, return_inverse=True - ) - entity_ids = np.arange(len(distinct_ids)) + if group_labels is None: + # Number the distinct groups in an ordinary flat file. + distinct_ids, person_membership_ids = np.unique( + membership_values, return_inverse=True + ) + entity_ids = np.arange(len(distinct_ids)) + else: + # Rebuild the original group order and labels from member rows. + _, first_rows, positions = np.unique( + membership_values, return_index=True, return_inverse=True + ) + person_membership_ids = np.asarray(group_labels) + entity_ids = person_membership_ids[first_rows] + if not np.array_equal(person_membership_ids, entity_ids[positions]): + raise ValueError( + f"Members of a {group_entity.key} position must share an ID." + ) builder.declare_entity(group_entity.key, entity_ids) person_role_field = f"{person_entity.key}_{group_entity.key}_role" - if any(column.split("__")[0] == person_role_field for column in data): + structural_roles = ( + take_flat_structure(person_role_field) if is_flat_file else None + ) + if structural_roles is not None: + person_roles = structural_roles + elif has_column(person_role_field): person_roles = get_eternity_array(person_role_field) elif "role" in data: person_roles = get_eternity_array("role") @@ -1214,12 +1274,8 @@ def get_eternity_array(name): self.build_from_populations(builder.populations) - if self.dataset.data_format == Dataset.FLAT_FILE: - # Ensure we're back to all person-level data. - data = data_copy - unknown_columns = [] - if self.dataset.data_format != Dataset.FLAT_FILE: + if not is_flat_file: for variable in data: if variable in self.tax_benefit_system.variables: if self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS: @@ -1237,11 +1293,11 @@ def get_eternity_array(name): unknown_columns.append(variable) else: for variable in data: - if "__" in variable: - variable_name, time_period = variable.split("__") - else: - variable_name = variable + variable_name = flat_column_variable(variable) + if variable_name == variable: time_period = self.dataset.time_period or self.default_input_period + else: + time_period = variable.rsplit("__", 1)[1] if variable_name not in self.tax_benefit_system.variables: unknown_columns.append(variable) @@ -1525,14 +1581,20 @@ def calculate( if requested is None: requested = self._get_requested_variables() requested.add(variable_name) - if isinstance(result, EnumArray) and decode_enums: - result = result.decode_to_str() - self.tracer.record_calculation_result(result) - if map_to is not None: - source_entity = self.tax_benefit_system.get_variable( - variable_name - ).entity.key - result = self.map_result(result, source_entity, map_to) + traced_result = ( + result.decode_to_str() + if decode_enums and isinstance(result, EnumArray) + else result + ) + self.tracer.record_calculation_result(traced_result) + if map_to is None: + return traced_result + source_entity = self.tax_benefit_system.get_variable( + variable_name + ).entity.key + result = self.map_result(result, source_entity, map_to) + if decode_enums and isinstance(result, EnumArray): + return result.decode_to_str() return result finally: try: @@ -1555,20 +1617,34 @@ def map_result( ): """Maps values from one entity to another. + With the default mapping to another group, a text or enum value must + agree across all members of each target group. An empty group receives + an empty string or the first enum member. Enum results retain their + enum type. Use ``calculate(..., map_to=..., decode_enums=True)`` to get + string labels for comparisons. + Args: - arr (np.array): The values in their original position. + values (np.array): The values in their original position. source_entity (str): The source entity key. target_entity (str): The target entity key. how (str, optional): A function to use when mapping. Defaults to None. Raises: - ValueError: If an invalid (dis)aggregation function is passed. + ValueError: If the aggregation function is invalid or members of a + target group have different text or enum values. Returns: np.array: The mapped values. """ entity_pop = self.populations[source_entity] target_pop = self.populations[target_entity] + if ( + how is None + and target_entity in self.tax_benefit_system.group_entity_keys + and source_entity != target_entity + and _is_categorical(values) + ): + return self._map_categorical_to_group(values, source_entity, target_entity) if ( source_entity == "person" and target_entity in self.tax_benefit_system.group_entity_keys @@ -1606,6 +1682,41 @@ def map_result( how="sum", ) + def _map_categorical_to_group( + self, values: ArrayLike, source_entity: str, target_entity: str + ) -> ArrayLike: + """Give each group the string or enum value its members share. + + Amounts map between entities by summing and sharing, which strings and + enums cannot do. A group takes its members' common value, and members + with different values have no common value to take. A group with no + members takes an empty string, or an enum's first value. + """ + person_key = self.tax_benefit_system.person_entity.key + person_values = ( + values + if source_entity == person_key + else self.populations[source_entity].project(values) + ) + person_values = np.asarray(person_values) + target_pop = self.populations[target_entity] + is_enum = isinstance(values, EnumArray) + group_values = target_pop.value_nth_person( + 0, person_values, default=0 if is_enum else "" + ) + differs = target_pop.project(group_values) != person_values + if np.any(differs): + groups = np.unique(target_pop.members_entity_id[differs]).size + raise ValueError( + f"Cannot map this {source_entity} value to {target_entity}: the " + f"members of {groups} {target_entity} group(s) hold different " + "values, and text values cannot be summed or shared. Map it to " + "the person entity instead." + ) + if is_enum: + return EnumArray(group_values, values.possible_values) + return group_values + def calculate_dataframe( self, variable_names: List[str], @@ -1763,9 +1874,9 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: # Registration rejects a non-numeric defined_for variable (see # ``TaxBenefitSystem._check_defined_for``). This catches one set, # or a variable replaced, afterwards. It reads the variable's - # type, not the values: mapped to a group entity, an Enum's - # indices are summed into numbers, and str or date values fail - # inside the mapping. + # type, not the values: mapped to a group entity, a str or Enum + # value gives its members' shared value or a mapping error, and a + # date fails inside the mapping. defined_for_variable = self.tax_benefit_system.get_variable( variable.defined_for ) @@ -3190,8 +3301,28 @@ def true_input_variables(self) -> List[str]: return self.get_input_variables(include_computed_variables=False) def _is_exportable_input_variable(self, variable_name: str) -> bool: - variable = self.tax_benefit_system.get_variable(variable_name) - return variable is not None and variable.is_input_variable() + system = self.tax_benefit_system + variable = system.get_variable(variable_name) + if variable is None: + return False + return ( + variable.is_input_variable() + or variable_name in system.source_input_variables + or variable_name in self._population_id_variables() + ) + + def _population_id_variables(self) -> set: + """Variables that say who exists and who belongs together. + + A model can give these formulas, but a stored value is a population + leaf rather than a calculated result, so an export keeps it. Reloaded + IDs also keep each entity's random seed. + """ + person_key = self.tax_benefit_system.person_entity.key + names = {f"{person_key}_id"} + for entity in self.tax_benefit_system.group_entities: + names.update({f"{entity.key}_id", f"{person_key}_{entity.key}_id"}) + return names def _get_visible_branch_names(self) -> List[str]: branch_names = [getattr(self, "branch_name", "default")] @@ -3256,28 +3387,188 @@ def _get_recorded_input_array(self, variable_name: str, period: Period): def to_input_dataframe( self, include_computed_variables: bool = False, + period: Period = None, ) -> pd.DataFrame: - """Exports a DataFrame that can be loaded back into a new Simulation. + """Exports input columns on person rows. - By default, only structurally input variables populated through - ``set_input`` are exported from their recorded storage tiers. This - avoids serializing pseudo-inputs and stale calculated values that - would override formulas when reloaded. + Input columns use ``variable__period``, including ``variable__ETERNITY`` + for all-time inputs. Period exports also use reserved ``__STRUCTURE`` + columns for person IDs and groups with members. + + By default, only inputs populated through ``set_input`` are exported + from their recorded storage tiers: variables with no formula, the IDs + that define the population, and the formula variables the model + declares in ``source_input_variables``. This avoids serializing + pseudo-inputs and stale calculated values that would override formulas + when reloaded. Any other value the simulation was given for a formula + variable stays out, and a warning names those variables, because + reloading the export runs their formulas instead. Args: include_computed_variables: If ``True``, export every variable with a known period, matching the historical unsafe behavior. + period: Export stored inputs for this period, all-time inputs, and + inputs the period carries or uprates. A formula that reads + another period needs that period's inputs too. Omit ``period`` + to export inputs from every stored period. Returns: pd.DataFrame: The DataFrame containing the input values. """ + if not include_computed_variables: + self._warn_about_inputs_left_out_of_export("to_input_dataframe") + + requested = None if period is None else periods.period(period) - return self._to_person_dataframe( - lambda variable: self._get_exportable_input_periods( + def get_periods(variable: str) -> List[Period]: + exportable = self._get_exportable_input_periods( variable, include_computed_variables - ), + ) + if requested is None: + return exportable + return [ + known + for known in exportable + if known.unit == ETERNITY + or requested.contains(known) + or known.contains(requested) + ] + + df = self._to_person_dataframe( + get_periods, include_computed_variables=include_computed_variables, ) + if requested is not None: + if not include_computed_variables: + self._export_carried_inputs(df, requested) + self._export_flat_file_structure(df) + return df + + def _warn_about_inputs_left_out_of_export(self, exporter: str) -> None: + left_out = self._recorded_inputs_left_out_of_export() + if left_out: + logging.warning( + f"{exporter} left out the values given for " + f"{len(left_out)} formula variable(s), so reloading the " + f"export runs their formulas instead: {', '.join(left_out)}" + ) + + def _export_carried_inputs(self, df: pd.DataFrame, requested: Period) -> None: + """Add the inputs ``requested`` reads from earlier periods. + + A period with no stored input reads the latest earlier one, carried + over or uprated. Without these columns, an export for that period + would reload as defaults. + """ + if requested.unit == ETERNITY: + return + system = self.tax_benefit_system + person_key = self.persons.entity.key + for name, variable in system.variables.items(): + stored = self._get_exportable_input_periods(name, False) + unit = variable.definition_period + carries = variable.uprating is not None or ( + system.auto_carry_over_input_variables + and variable.calculate_output is None + ) + if not stored or unit == ETERNITY or not carries: + continue + read_periods = ( + requested.get_subperiods(unit) + if unit_weight(unit) <= unit_weight(requested.unit) + else [requested.start.offset("first-of", unit).period(unit)] + ) + for period in read_periods: + earlier = [known for known in stored if known.start <= period.start] + if not earlier or any(known.contains(period) for known in earlier): + continue + if variable.is_input_variable(): + df[f"{name}__{period}"] = Simulation.calculate( + self, name, period, map_to=person_key + ) + else: + # Replay observations so a formula can still run and may fall back. + for known in earlier: + column = f"{name}__{known}" + if column in df: + continue + values = self._get_recorded_input_array(name, known) + if values is not None: + df[column] = self.map_result( + values, variable.entity.key, person_key + ) + + def _export_flat_file_structure(self, df: pd.DataFrame) -> None: + person_key = self.persons.entity.key + df[f"{person_key}_id{_FLAT_STRUCTURE_SUFFIX}"] = self.persons.ids + for entity in self.tax_benefit_system.group_entities: + population = self.populations[entity.key] + positions = population.members_entity_id + field = f"{person_key}_{entity.key}" + df[f"{entity.key}_id{_FLAT_STRUCTURE_SUFFIX}"] = np.asarray(population.ids)[ + positions + ] + df[f"{field}_id{_FLAT_STRUCTURE_SUFFIX}"] = positions + roles = np.broadcast_to(population.members_role, self.persons.count) + df[f"{field}_role{_FLAT_STRUCTURE_SUFFIX}"] = np.array( + [getattr(role, "key", "") for role in roles], dtype=str + ) + + def _retain_population_structure(self, df: pd.DataFrame, period: Period) -> None: + """Add the IDs, memberships and roles ``df`` needs to rebuild this population. + + These are loaded population leaves, not calculated ID formulas. A + simulation built from populations may have no stored ID inputs, and + one export period may hold none of those it has. + """ + + def retain_structure(name, values): + variable = self.tax_benefit_system.get_variable(name) + if variable is None or any( + _flat_column_variable(column) == name for column in df + ): + return + structural_period = ( + ETERNITY + if variable.definition_period == ETERNITY + else periods.period(period) + .start.offset("first-of", variable.definition_period) + .period(variable.definition_period) + ) + df[f"{name}__{structural_period}"] = values + + person_key = self.persons.entity.key + retain_structure(f"{person_key}_id", self.persons.ids) + for entity in self.tax_benefit_system.group_entities: + population = self.populations[entity.key] + retain_structure( + f"{person_key}_{entity.key}_id", + population.ids[population.members_entity_id], + ) + role_name = f"{person_key}_{entity.key}_role" + role_variable = self.tax_benefit_system.get_variable(role_name) + roles = np.broadcast_to(population.members_role, self.persons.count) + if role_variable is not None and role_variable.value_type == int: + role_values = [ + entity.flattened_roles.index(role) + if role in entity.flattened_roles + else 0 + for role in roles + ] + else: + role_values = [getattr(role, "key", "") for role in roles] + retain_structure(role_name, role_values) + + def _recorded_inputs_left_out_of_export(self) -> List[str]: + """Variables whose given values ``to_input_dataframe`` does not export.""" + recorded = {name for name, _, _ in getattr(self, "_user_input_keys", set())} + return sorted( + name + for name in recorded + if self.tax_benefit_system.get_variable(name) is not None + and not self._is_exportable_input_variable(name) + and self._get_set_input_periods(name) + ) def _to_person_dataframe( self, get_periods, include_computed_variables: bool = False @@ -3307,10 +3598,9 @@ def _to_person_dataframe( def to_input_dict(self, include_computed_variables: bool = False) -> dict: """Exports a dictionary that can be loaded back into a new Simulation. - By default, only structurally input variables populated through - ``set_input`` are exported from their recorded storage tiers. This - avoids serializing pseudo-inputs and stale calculated values that - would override formulas when reloaded. + By default, exports recorded inputs, including population ID inputs + and formula variables declared in ``source_input_variables``. It logs a + warning naming other formula variables whose supplied values it omits. Args: include_computed_variables: If ``True``, export every variable with @@ -3319,6 +3609,9 @@ def to_input_dict(self, include_computed_variables: bool = False) -> dict: Returns: dict: The dictionary containing the input values. """ + if not include_computed_variables: + self._warn_about_inputs_left_out_of_export("to_input_dict") + data = {} for variable in self.tax_benefit_system.variables: @@ -3455,42 +3748,8 @@ def subsample( # be calculated before subsampling. df = self._to_person_dataframe(self._get_set_input_periods) - def retain_structure(name, values): - variable = self.tax_benefit_system.get_variable(name) - if variable is None or any(column.split("__")[0] == name for column in df): - return - structural_period = ( - ETERNITY - if variable.definition_period == ETERNITY - else periods.period(self.dataset.time_period).start.period( - variable.definition_period - ) - ) - df[f"{name}__{structural_period}"] = values - - # These are loaded population leaves, not calculated ID formulas. - # A simulation built from populations may have no stored ID inputs. + self._retain_population_structure(df, self.dataset.time_period) person_key = self.persons.entity.key - retain_structure(f"{person_key}_id", self.persons.ids) - for entity in self.tax_benefit_system.group_entities: - population = self.populations[entity.key] - retain_structure( - f"{person_key}_{entity.key}_id", - population.ids[population.members_entity_id], - ) - role_name = f"{person_key}_{entity.key}_role" - role_variable = self.tax_benefit_system.get_variable(role_name) - roles = np.broadcast_to(population.members_role, self.persons.count) - if role_variable is not None and role_variable.value_type == int: - role_values = [ - entity.flattened_roles.index(role) - if role in entity.flattened_roles - else 0 - for role in roles - ] - else: - role_values = [getattr(role, "key", "") for role in roles] - retain_structure(role_name, role_values) # Flat-file loading can infer households from membership IDs even # when the household ID variable has a formula. Use the same leaves diff --git a/policyengine_core/taxbenefitsystems/tax_benefit_system.py b/policyengine_core/taxbenefitsystems/tax_benefit_system.py index ccadd2a39..b3ca3ba27 100644 --- a/policyengine_core/taxbenefitsystems/tax_benefit_system.py +++ b/policyengine_core/taxbenefitsystems/tax_benefit_system.py @@ -143,6 +143,10 @@ class TaxBenefitSystem: stored for the period itself is read back as stored. An input never carries backwards, and values the simulation calculated never carry (see ``Holder.is_derived``), so the result does not depend on which periods were calculated first.""" + source_input_variables: frozenset[str] = frozenset() + """Formula variables that may hold recorded observations. The default + DataFrame and dictionary exports include their supplied values. Reforms + inherit the baseline declaration.""" basic_inputs: List[str] = None """Short list of basic inputs to get medium accuracy.""" modelled_policies: str = None diff --git a/tests/core/test_flat_file_datasets.py b/tests/core/test_flat_file_datasets.py new file mode 100644 index 000000000..1ce3121bb --- /dev/null +++ b/tests/core/test_flat_file_datasets.py @@ -0,0 +1,361 @@ +"""A person-level DataFrame loads, exports and reloads without surprises.""" + +import logging + +import numpy as np +import pandas as pd +import pytest + +from policyengine_core.country_template import CountryTaxBenefitSystem +from policyengine_core.data import Dataset +from policyengine_core.entities import build_entity +from policyengine_core.parameters import ParameterNode +from policyengine_core.periods import ETERNITY, YEAR +from policyengine_core.reforms import Reform +from policyengine_core.simulations import Simulation +from policyengine_core.taxbenefitsystems import TaxBenefitSystem +from policyengine_core.variables import Variable + +Person = build_entity(key="person", plural="persons", label="Person", is_person=True) +Household = build_entity( + key="household", + plural="households", + label="Household", + roles=[{"key": "member", "plural": "members", "label": "Members"}], +) +Family = build_entity( + key="family", + plural="families", + label="Family", + roles=[{"key": "member", "plural": "members", "label": "Members"}], +) + + +def person_variable(name, value_type=float, period=YEAR, entity=Person, **attributes): + return type( + name, + (Variable,), + { + "value_type": value_type, + "entity": entity, + "definition_period": period, + "label": name, + **attributes, + }, + ) + + +def formula_of_ages(person, period): + return person("age", period) * 0 + + +class Countable(TaxBenefitSystem): + source_input_variables = frozenset({"observed_role"}) + + +def build(data, time_period=2024, system_class=Countable): + system = system_class([Person, Household, Family]) + system.add_variable(person_variable("household_id", int, entity=Household)) + system.add_variable(person_variable("family_id", int, entity=Family)) + system.add_variable(person_variable("person_household_id", int)) + system.add_variable(person_variable("person_family_id", int)) + system.add_variable(person_variable("age")) + system.add_variable(person_variable("is_head", bool, ETERNITY)) + system.add_variable( + person_variable("observed_role", bool, ETERNITY, formula=formula_of_ages) + ) + system.add_variable( + person_variable("saved_result", formula=formula_of_ages), + ) + system.add_variable( + person_variable( + "person_id", + int, + formula=lambda person, period: np.arange(person.count), + ) + ) + return Simulation( + tax_benefit_system=system, + dataset=Dataset.from_dataframe(data, time_period), + ) + + +def people(): + return pd.DataFrame( + { + "household_id": [1, 1, 2], + "family_id": [1, 1, 2], + "age": [35.0, 5.0, 60.0], + } + ) + + +def test_rows_number_people_when_no_column_does(): + simulation = build(people()) + assert simulation.persons.ids.tolist() == [0, 1, 2] + + +def test_a_person_id_column_with_a_period_keeps_its_values(): + data = people().assign(person_id__2024=[10, 20, 30]) + assert build(data).persons.ids.tolist() == [10, 20, 30] + + +def test_group_ids_on_person_rows_declare_the_groups(): + simulation = build(people()) + assert simulation.populations["household"].count == 2 + assert simulation.populations["family"].count == 2 + + +@pytest.mark.parametrize( + "missing, named", + [ + ("household_id", "person_household_id or household_id"), + ("family_id", "person_family_id or family_id"), + ], +) +def test_a_missing_group_column_names_the_fix(missing, named): + with pytest.raises(ValueError, match=named): + build(people().drop(columns=missing)) + + +def test_a_column_name_with_two_separators_loads_as_an_unknown_column(caplog): + data = people().assign(**{"survey__note__2024": ["a", "b", "c"]}) + with caplog.at_level(logging.WARNING): + simulation = build(data) + assert simulation.calculate("age", 2024).tolist() == [35.0, 5.0, 60.0] + assert "survey__note__2024" in caplog.text + + +@pytest.mark.parametrize( + "column", ["is_head", "is_head__2024", "is_head__ETERNITY", "is_head__2019"] +) +def test_an_all_time_variable_loads_from_any_column_spelling(column): + simulation = build(people().assign(**{column: [True, False, True]})) + assert simulation.calculate("is_head", 2030).tolist() == [True, False, True] + + +def test_an_export_spells_an_all_time_variable_eternity(): + simulation = build(people().assign(is_head=[True, False, True])) + assert "is_head__ETERNITY" in simulation.to_input_dataframe().columns + + +def test_a_period_export_keeps_that_period_and_all_time_variables(): + data = people().assign( + age__2025=[36.0, 6.0, 61.0], + is_head=[True, False, True], + ) + columns = set(build(data).to_input_dataframe(period=2025).columns) + assert "age__2025" in columns + assert "is_head__ETERNITY" in columns + assert "age__2024" not in columns + + +def test_a_period_export_reloads_on_its_own(): + data = people().assign(age__2025=[36.0, 6.0, 61.0], is_head=[True, False, True]) + exported = build(data).to_input_dataframe(period=2025) + reloaded = build(exported, time_period=2025) + assert reloaded.calculate("age", 2025).tolist() == [36.0, 6.0, 61.0] + assert reloaded.calculate("is_head", 2025).tolist() == [True, False, True] + + +class Carrying(Countable): + auto_carry_over_input_variables = True + + +def test_a_period_export_holds_the_inputs_an_earlier_period_carries(): + simulation = build(people(), system_class=Carrying) + exported = simulation.to_input_dataframe(period=2026) + assert exported["age__2026"].tolist() == [35.0, 5.0, 60.0] + reloaded = build(exported, time_period=2026, system_class=Carrying) + assert reloaded.calculate("age", 2026).tolist() == [35.0, 5.0, 60.0] + + +def test_a_later_input_stays_out_of_an_earlier_period_export(): + data = people().drop(columns="age").assign(age__2025=[35.0, 5.0, 60.0]) + exported = build(data, system_class=Carrying).to_input_dataframe(period=2024) + assert not any(column.startswith("age__") for column in exported) + + +def test_a_period_export_adds_nothing_a_system_does_not_carry(): + exported = build(people()).to_input_dataframe(period=2026) + assert not any(column.startswith("age__") for column in exported) + + +def test_a_period_export_inside_a_stored_year_keeps_that_year(): + exported = build(people()).to_input_dataframe(period="2024-03") + assert exported["age__2024"].tolist() == [35.0, 5.0, 60.0] + + +def test_a_month_read_after_a_stored_year_carries_within_that_month_year(): + exported = build(people(), system_class=Carrying).to_input_dataframe( + period="2025-03" + ) + assert exported["age__2025"].tolist() == [35.0, 5.0, 60.0] + + +def test_a_declared_source_input_survives_the_round_trip(): + data = people().assign(observed_role=[True, False, True]) + simulation = build(data) + assert simulation.calculate("observed_role", 2024).tolist() == [True, False, True] + reloaded = build(simulation.to_input_dataframe()) + assert reloaded.calculate("observed_role", 2024).tolist() == [True, False, True] + assert "observed_role" in simulation.true_input_variables + + +def test_population_ids_survive_the_round_trip_when_they_have_formulas(): + data = people().assign(person_id=[10, 20, 30]) + exported = build(data).to_input_dataframe() + assert exported["person_id__2024"].tolist() == [10, 20, 30] + assert build(exported).persons.ids.tolist() == [10, 20, 30] + + +def test_an_undeclared_formula_value_stays_out_and_the_export_says_so(caplog): + simulation = build(people().assign(saved_result=[9.0, 9.0, 9.0])) + with caplog.at_level(logging.WARNING): + exported = simulation.to_input_dataframe() + assert "saved_result__2024" not in exported.columns + assert "saved_result" in caplog.text + assert build(exported).calculate("saved_result", 2024).tolist() == [0.0] * 3 + + +def test_a_clean_export_warns_about_nothing(caplog): + simulation = build(people()) + with caplog.at_level(logging.WARNING): + simulation.to_input_dataframe() + assert caplog.text == "" + + +def test_exporting_computed_variables_warns_about_nothing(caplog): + simulation = build(people().assign(saved_result=[9.0, 9.0, 9.0])) + with caplog.at_level(logging.WARNING): + exported = simulation.to_input_dataframe(include_computed_variables=True) + assert "saved_result__2024" in exported.columns + assert caplog.text == "" + + +@pytest.mark.parametrize("column", ["survey__score", "survey__score__2024"]) +def test_registered_variable_with_double_underscores(column): + system = build(people()).tax_benefit_system + system.add_variable(person_variable("survey__score")) + data = people().assign(**{column: [1.0, 2.0, 3.0]}) + sim = Simulation(system, dataset=Dataset.from_dataframe(data, 2024)) + assert sim.calculate("survey__score", 2024).tolist() == [1.0, 2.0, 3.0] + + +def test_a_zero_column_frame_keeps_its_people(): + sim = Simulation( + TaxBenefitSystem([Person]), + dataset=Dataset.from_dataframe(pd.DataFrame(index=range(3))), + ) + assert sim.persons.ids.tolist() == [0, 1, 2] + + +def reload_frame(source, frame, period): + dataset = Dataset.from_dataframe(frame, period) + return Simulation(source.tax_benefit_system, dataset=dataset) + + +def test_situation_period_export_preserves_labels_group_order_and_roles(): + source = Simulation( + CountryTaxBenefitSystem(), + situation={ + "persons": {"a": {"salary": {"2024-01": 100}}, "b": {}, "c": {}}, + "households": { + "z": {"children": ["c"]}, + "h": {"parents": ["a"], "children": ["b"]}, + }, + }, + ) + reloaded = reload_frame( + source, source.to_input_dataframe(period="2024-01"), "2024-01" + ) + np.testing.assert_array_equal(reloaded.persons.ids, source.persons.ids) + np.testing.assert_array_equal(reloaded.household.ids, source.household.ids) + np.testing.assert_array_equal( + reloaded.household.members_entity_id, source.household.members_entity_id + ) + np.testing.assert_array_equal( + reloaded.household.members_role, source.household.members_role + ) + assert "person_household_role" not in reloaded.true_input_variables + + +def test_period_export_does_not_override_an_id_formula(): + source = build(people()) + source.tax_benefit_system.replace_variable( + person_variable( + "person_id", + int, + formula=lambda person, period: np.arange(person.count) + 100, + ) + ) + reloaded = reload_frame(source, source.to_input_dataframe(period=2025), 2025) + assert source.calculate("person_id", 2025).tolist() == [100, 101, 102] + assert reloaded.calculate("person_id", 2025).tolist() == [100, 101, 102] + + +def test_period_export_replays_an_observation_when_its_formula_returns_none(): + system = build(people(), system_class=Carrying).tax_benefit_system + system.source_input_variables |= {"optional_income"} + system.add_variable( + person_variable("optional_income", formula=lambda person, period: None) + ) + dataset = Dataset.from_dataframe( + people().assign(optional_income=[10, 20, 30]), 2024 + ) + source = Simulation(system, dataset=dataset) + frame = source.to_input_dataframe(period=2025) + reloaded = reload_frame(source, frame, 2025) + assert source.calculate("optional_income", 2025).tolist() == [10, 20, 30] + assert reloaded.calculate("optional_income", 2025).tolist() == [10, 20, 30] + assert "optional_income__2024" in frame + assert "optional_income__2025" not in frame + + +def test_period_export_round_trips_uprating(): + system = build(people()).tax_benefit_system + system.parameters = ParameterNode( + "root", data={"index": {"2024-01-01": 100, "2025-01-01": 120}} + ) + system.add_variable(person_variable("indexed_income", uprating="index")) + dataset = Dataset.from_dataframe(people().assign(indexed_income=[10, 20, 30]), 2024) + source = Simulation(system, dataset=dataset) + reloaded = reload_frame(source, source.to_input_dataframe(period=2025), 2025) + assert source.calculate("indexed_income", 2025).tolist() == [12, 24, 36] + assert reloaded.calculate("indexed_income", 2025).tolist() == [12, 24, 36] + + +def test_dict_export_warns_and_keeps_declared_formula_inputs(caplog): + data = people().assign(observed_role=[True, False, True], saved_result=[9.0] * 3) + exported = build(data).to_input_dict() + assert exported["observed_role"]["ETERNITY"] == [True, False, True] + assert "saved_result" not in exported + assert "to_input_dict" in caplog.text and "saved_result" in caplog.text + + +def test_reform_inherits_declared_source_inputs(): + class NoOp(Reform): + def apply(self): + pass + + system = NoOp(build(people()).tax_benefit_system) + dataset = Dataset.from_dataframe( + people().assign(observed_role=[True, False, True]), 2024 + ) + source = Simulation(system, dataset=dataset) + assert source.to_input_dict()["observed_role"]["ETERNITY"] == [True, False, True] + + +def test_formula_reading_a_prior_period_needs_that_period_exported(): + source = build(people()) + source.tax_benefit_system.add_variable( + person_variable( + "previous_age", + formula=lambda person, period: person("age", period.last_year), + ) + ) + one_period = reload_frame(source, source.to_input_dataframe(period=2025), 2025) + all_periods = reload_frame(source, source.to_input_dataframe(), 2025) + assert source.calculate("previous_age", 2025).tolist() == [35, 5, 60] + assert one_period.calculate("previous_age", 2025).tolist() == [0, 0, 0] + assert all_periods.calculate("previous_age", 2025).tolist() == [35, 5, 60] diff --git a/tests/core/test_flat_file_property.py b/tests/core/test_flat_file_property.py new file mode 100644 index 000000000..c050706b4 --- /dev/null +++ b/tests/core/test_flat_file_property.py @@ -0,0 +1,123 @@ +"""Properties of flat-file export and of mapping text between entities.""" + +import numpy as np +import pandas as pd +import pytest + +# The country-package smoke job installs no dev dependencies. +hypothesis = pytest.importorskip("hypothesis") +st = hypothesis.strategies + +from tests.core.test_flat_file_datasets import Carrying, reload_frame +from tests.core.test_flat_file_datasets import build as build_flat +from tests.core.test_map_result_categorical import build as build_groups + +memberships = st.integers(min_value=1, max_value=8).flatmap( + lambda size: st.tuples( + st.lists(st.integers(1, 4), min_size=size, max_size=size), + st.lists(st.integers(1, 4), min_size=size, max_size=size), + ) +) + + +@hypothesis.given(memberships) +@hypothesis.settings(deadline=None, max_examples=60) +def test_a_person_string_maps_to_a_group_exactly_when_its_members_share_it(partition): + """Members who agree give their value, and members who disagree raise.""" + households, families = partition + simulation = build_groups(households, families) + # Each household's own label, so families that cross households disagree. + labels = np.array([f"h{household}" for household in households], dtype=object) + family_ids = np.asarray(families) + agrees = all( + len(set(labels[family_ids == family])) == 1 for family in set(families) + ) + if agrees: + mapped = simulation.map_result(labels, "person", "family") + expected = {family: label for family, label in zip(families, labels)} + assert list(mapped) == [expected[family] for family in sorted(set(families))] + else: + with pytest.raises(ValueError, match="different values"): + simulation.map_result(labels, "person", "family") + + +@hypothesis.given( + st.lists( + st.tuples( + st.integers(1, 3), + st.floats(0, 120, width=32), + st.booleans(), + st.booleans(), + ), + min_size=1, + max_size=8, + ), + st.integers(1, 1000), +) +@hypothesis.settings(deadline=None, max_examples=60) +def test_an_export_reloads_to_the_same_answers(rows, first_id): + """Export then reload changes neither the people nor what they were given.""" + households, ages, heads, roles = map(list, zip(*rows)) + data = pd.DataFrame( + { + "person_id": [first_id + index for index in range(len(rows))], + "household_id": households, + "family_id": households, + "age": ages, + "is_head": heads, + "observed_role": roles, + } + ) + source = build_flat(data) + reloaded = build_flat(source.to_input_dataframe()) + assert reloaded.persons.ids.tolist() == source.persons.ids.tolist() + assert ( + reloaded.populations["household"].count == source.populations["household"].count + ) + for name in ("age", "is_head", "observed_role"): + assert ( + reloaded.calculate(name, 2024).tolist() + == source.calculate(name, 2024).tolist() + ) + + +@hypothesis.given( + st.lists( + st.tuples(st.integers(1, 3), st.floats(0, 120, width=32)), + min_size=1, + max_size=8, + ), + st.integers(0, 3), +) +@hypothesis.settings(deadline=None, max_examples=40) +def test_a_period_export_reloads_to_what_that_period_reads(rows, years_later): + """Export for a period, reload, and that period reads the same values.""" + households, ages = map(list, zip(*rows)) + data = pd.DataFrame( + {"household_id": households, "family_id": households, "age": ages} + ) + source = build_flat(data, system_class=Carrying) + year = 2024 + years_later + reloaded = build_flat( + source.to_input_dataframe(period=year), + time_period=year, + system_class=Carrying, + ) + assert reloaded.calculate("age", year).tolist() == ( + source.calculate("age", year).tolist() + ) + + +@hypothesis.given(memberships) +@hypothesis.settings(deadline=None, max_examples=40) +def test_period_export_preserves_memberships_without_id_variables(partition): + source = build_groups(*partition) + reloaded = reload_frame(source, source.to_input_dataframe(period=2024), 2024) + for key in ("household", "family"): + np.testing.assert_array_equal( + reloaded.populations[key].ids, source.populations[key].ids + ) + np.testing.assert_array_equal( + reloaded.populations[key].members_entity_id, + source.populations[key].members_entity_id, + ) diff --git a/tests/core/test_map_result_categorical.py b/tests/core/test_map_result_categorical.py new file mode 100644 index 000000000..75cdf671e --- /dev/null +++ b/tests/core/test_map_result_categorical.py @@ -0,0 +1,200 @@ +"""Strings and enums map to a group as the value its members share.""" + +import numpy as np +import pandas as pd +import pytest + +from policyengine_core.data import Dataset +from policyengine_core.entities import build_entity +from policyengine_core.enums import Enum, EnumArray +from policyengine_core.periods import YEAR +from policyengine_core.simulations import Simulation +from policyengine_core.taxbenefitsystems import TaxBenefitSystem +from policyengine_core.variables import Variable + +Person = build_entity(key="person", plural="persons", label="Person", is_person=True) +Household = build_entity( + key="household", + plural="households", + label="Household", + roles=[{"key": "member", "plural": "members", "label": "Members"}], +) +Family = build_entity( + key="family", + plural="families", + label="Family", + roles=[{"key": "member", "plural": "members", "label": "Members"}], +) + + +class Region(Enum): + NORTH = "North" + SOUTH = "South" + + +def variable(name, entity, value_type, **attributes): + return type( + name, + (Variable,), + { + "value_type": value_type, + "entity": entity, + "definition_period": YEAR, + "label": name, + **attributes, + }, + ) + + +def build(households, families): + system = TaxBenefitSystem([Person, Household, Family]) + system.add_variable(variable("amount", Household, float)) + system.add_variable(variable("place", Household, str)) + system.add_variable(variable("name", Person, str)) + system.add_variable(variable("person_amount", Person, float)) + system.add_variable( + variable( + "region", + Household, + Enum, + possible_values=Region, + default_value=Region.NORTH, + ) + ) + return Simulation( + tax_benefit_system=system, + dataset=Dataset.from_dataframe( + pd.DataFrame({"household_id": households, "family_id": families}), 2024 + ), + ) + + +def two_families_in_one_household(): + simulation = build([1, 1, 1, 2], [1, 1, 2, 3]) + simulation.set_input("place", 2024, np.array(["A", "B"], dtype=object)) + simulation.set_input("name", 2024, np.array(["x", "x", "y", "z"], dtype=object)) + simulation.set_input( + "person_amount", 2024, np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32) + ) + simulation.set_input("amount", 2024, np.array([30.0, 40.0], dtype=np.float32)) + simulation.set_input( + "region", 2024, np.array([Region.SOUTH, Region.NORTH], dtype=object) + ) + return simulation + + +def test_a_group_string_maps_across_groups(): + simulation = two_families_in_one_household() + result = simulation.calculate("place", 2024, map_to="family") + assert list(result) == ["A", "A", "B"] + + +def test_a_group_string_maps_to_a_group_its_members_share(): + simulation = build([1, 1, 2, 2], [1, 2, 3, 3]) + simulation.set_input("name", 2024, np.array(["x", "y", "z", "z"], dtype=object)) + result = simulation.calculate("name", 2024, map_to="family") + assert list(result) == ["x", "y", "z"] + + +def test_an_enum_maps_across_groups_and_stays_an_enum(): + simulation = two_families_in_one_household() + result = simulation.calculate("region", 2024, map_to="family") + assert isinstance(result, EnumArray) + assert list(result.decode_to_str()) == ["SOUTH", "SOUTH", "NORTH"] + + +def test_a_decoded_enum_maps_across_groups(): + simulation = two_families_in_one_household() + result = simulation.calculate("region", 2024, map_to="family", decode_enums=True) + assert list(result) == ["SOUTH", "SOUTH", "NORTH"] + + +def with_an_empty_household(simulation): + households = simulation.populations["household"] + households.count = 3 + households.ids = np.array([1, 2, 3]) + households.members_entity_id = np.array([0, 0, 2]) + return simulation + + +def test_a_group_with_no_members_takes_an_empty_string(): + simulation = with_an_empty_household(build([1, 1, 2], [1, 1, 2])) + names = np.array(["x", "x", "y"], dtype=object) + assert list(simulation.map_result(names, "person", "household")) == ["x", "", "y"] + fixed_width = names.astype(str) + assert list(simulation.map_result(fixed_width, "person", "household")) == [ + "x", + "", + "y", + ] + + +def test_a_group_with_no_members_takes_the_first_value_of_an_enum(): + simulation = with_an_empty_household(build([1, 1, 2], [1, 1, 2])) + regions = EnumArray(np.array([1, 1, 1], dtype=np.int16), Region) + mapped = simulation.map_result(regions, "person", "household") + assert list(mapped.decode_to_str()) == ["SOUTH", "NORTH", "SOUTH"] + + +def test_a_person_string_that_differs_within_a_group_says_so(): + simulation = two_families_in_one_household() + with pytest.raises(ValueError, match="1 household group"): + simulation.calculate("name", 2024, map_to="household") + + +def test_a_group_string_that_differs_within_a_target_group_says_so(): + simulation = build([1, 2, 2], [1, 1, 2]) + simulation.set_input("place", 2024, np.array(["A", "B"], dtype=object)) + with pytest.raises(ValueError, match="different values"): + simulation.calculate("place", 2024, map_to="family") + + +def test_a_group_string_still_maps_to_people_and_itself(): + simulation = two_families_in_one_household() + assert list(simulation.calculate("place", 2024, map_to="person")) == [ + "A", + "A", + "A", + "B", + ] + assert list(simulation.calculate("place", 2024, map_to="household")) == ["A", "B"] + + +def test_amounts_still_sum_and_share(): + simulation = two_families_in_one_household() + assert simulation.calculate("amount", 2024, map_to="family").tolist() == [ + 20.0, + 10.0, + 40.0, + ] + assert simulation.calculate("person_amount", 2024, map_to="household").tolist() == [ + 6.0, + 4.0, + ] + + +def test_an_explicit_how_keeps_its_meaning(): + simulation = two_families_in_one_household() + values = np.array(["x", "x", "y", "z"], dtype=object) + assert list( + simulation.map_result( + values, "person", "household", how="value_from_first_person" + ) + ) == ["x", "z"] + + +def test_a_decoded_enum_uses_its_first_value_for_an_empty_group(): + simulation = two_families_in_one_household() + family = simulation.populations["family"] + family.ids = np.arange(4) + family.count = 4 + family.members_entity_id = np.array([0, 0, 2, 3]) + result = simulation.calculate("region", 2024, map_to="family", decode_enums=True) + assert result.tolist() == ["SOUTH", "NORTH", "SOUTH", "NORTH"] + + +def test_different_enum_values_in_a_group_raise(): + simulation = build([1, 2, 2], [1, 1, 2]) + simulation.set_input("region", 2024, np.array([Region.SOUTH, Region.NORTH])) + with pytest.raises(ValueError, match="different values"): + simulation.calculate("region", 2024, map_to="family") diff --git a/tests/core/test_subsample_invalidates_cache.py b/tests/core/test_subsample_invalidates_cache.py index d2174c1be..35b2e7f6f 100644 --- a/tests/core/test_subsample_invalidates_cache.py +++ b/tests/core/test_subsample_invalidates_cache.py @@ -67,14 +67,14 @@ def _build_formula_backed_id_simulation( def test_subsample_preserves_formula_backed_structural_ids( isolated_tax_benefit_system, ) -> None: - """Subsampling needs IDs that safe public exports intentionally omit.""" + """Subsampling and exports keep a stored ID that has a formula.""" sim = _build_formula_backed_id_simulation(isolated_tax_benefit_system) - safe_columns = sim.to_input_dataframe().columns - full_columns = sim.to_input_dataframe(include_computed_variables=True).columns - - assert "person_id__2022" not in safe_columns - assert "person_id__2022" in full_columns + assert "person_id__2022" in sim.to_input_dataframe().columns + assert ( + "person_id__2022" + in sim.to_input_dataframe(include_computed_variables=True).columns + ) sim.subsample(n=1, seed="formula-backed-person-id")