Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/fix-person-entity-id-int-2267.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Store `person_household_id` and `person_benunit_id` as integers, like the other identifier variables, so identifiers above 16,777,216 read back exactly from `calculate`, `to_input_dataframe()` and `UKSingleYearDataset.from_simulation`. A simulation built from a policyengine-core dataset file no longer merges households or benefit units whose identifiers rounded to the same number. A simulation now gives an `EntityIdWarning` when an identifier is not a whole number from -2,147,483,648 to 2,147,483,647, the range it can store exactly.
7 changes: 7 additions & 0 deletions docs/book/usage/simulations.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,13 @@ Each table should contain the ID columns needed to link entities together:
- `benunit`: `benunit_id`, plus any benefit-unit variables
- `household`: `household_id`, plus any household-level variables

Whatever the data source, keep identifiers to whole numbers from
-2,147,483,648 to 2,147,483,647. A simulation stores them as 32-bit integers,
so within that range the identifiers it returns (for example
`sim.calculate("person_household_id", 2025)`) are the ones in your tables.
Outside it, the simulation gives an `EntityIdWarning`: the identifiers it
returns differ from yours, and so may anything rebuilt from them.

Benefit-unit and household rows can be in any order. The loader aligns each
year's group inputs by its ID column to the simulation's sorted group IDs;
person rows keep their supplied order. This alignment does not reorder the
Expand Down
21 changes: 21 additions & 0 deletions policyengine_uk/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
UKMultiYearDataset,
UKSingleYearDataset,
)
from policyengine_uk.utils.entity_ids import ENTITY_ID_VARIABLES, check_entity_ids
from policyengine_uk.utils.scenario import ConstructionReformState, Scenario
from policyengine_uk.data.economic_assumptions import (
extend_single_year_dataset,
Expand Down Expand Up @@ -1254,13 +1255,33 @@ def build_from_ids(
person_household_id: Array mapping persons to households
benunit_id: Array of benefit unit IDs
household_id: Array of household IDs

Warns:
EntityIdWarning: If an ID is not a whole number, or is outside the
range of the variable that stores it, so that the stored ID
differs from the one given.
"""
# Every data source (DataFrame, dataset, file, URL) builds through here.
self._start_new_population(built_from_dataset=True)
from policyengine_core.simulations.simulation_builder import (
SimulationBuilder,
) # Import here to avoid circular dependency

# The callers store these columns as the variables' values after
# building the entities, and exports and rebuilds read them from there.
# The populations below take the arrays as given.
for variable_name, ids in zip(
ENTITY_ID_VARIABLES,
(
person_id,
person_benunit_id,
person_household_id,
benunit_id,
household_id,
),
):
check_entity_ids(self.tax_benefit_system.variables[variable_name], ids)

builder = SimulationBuilder()
builder.populations = self.tax_benefit_system.instantiate_entities()

Expand Down
48 changes: 33 additions & 15 deletions policyengine_uk/tests/test_dataframe_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1018,14 +1018,18 @@ def test_identifiers_too_large_for_64_bits_are_refused(values):


def test_an_exported_frame_saved_as_csv_loads_back():
# The exported person_ columns hold 32-bit floats: 906,000,001 is
# 906,000,000. CSV gives them back as 64-bit floats, which still name the
# groups the exact benunit_id and household_id columns give.
# Membership identifiers stay exact integers through export and CSV,
# including neighbouring groups that float32 would round together.
original = Simulation(dataset=dataset())
exported = original.to_input_dataframe()
from_csv = pd.read_csv(io.StringIO(exported.to_csv(index=False)))
assert from_csv["person_benunit_id__2025"].dtype == np.float64
assert from_csv["person_benunit_id__2025"].iloc[0] == 906_000_000
for group in GROUPS:
column = f"person_{group}_id__{YEAR}"
expected = group_of_each_person(original, group)
assert exported[column].dtype.kind == "i"
assert exported[column].tolist() == expected
assert from_csv[column].dtype == np.int64
assert from_csv[column].tolist() == expected

reloaded = Simulation(dataset=from_csv)

Expand Down Expand Up @@ -1139,8 +1143,7 @@ def test_object_person_columns_are_checked_value_by_value():


def test_integer_group_columns_must_agree_exactly():
# Integer columns hold identifiers exactly (as they will once #2267 makes
# the person_ variables integers), so they must name the same group.
# Integer columns hold identifiers exactly, so they must name the same group.
refused(
couple(
**{
Expand Down Expand Up @@ -1261,19 +1264,20 @@ def test_an_exported_frame_loads_back_and_exports_itself(population, id_columns)

reloaded = Simulation(dataset=exported)

# 5. Round trip: the same people, groups and inputs, including for
# identifiers the exported person_ columns hold rounded.
# 5. Round trip: the same people, groups and inputs, with exact identifiers.
assert_holds(reloaded, population)
pd.testing.assert_frame_equal(reloaded.to_input_dataframe(), exported)
for group in GROUPS:
exact = population.groups[group]
assert exported[f"{group}_id__{YEAR}"].tolist() == exact.tolist()
assert (
exported[f"person_{group}_id__{YEAR}"].tolist()
== exact.astype(np.float32).tolist()
)
# Saved as CSV, the rounded person_ columns come back as 64-bit floats.
assert exported[f"person_{group}_id__{YEAR}"].dtype.kind == "i"
assert exported[f"person_{group}_id__{YEAR}"].tolist() == exact.tolist()
# CSV parses the integer text without passing the memberships through float32.
from_csv = pd.read_csv(io.StringIO(exported.to_csv(index=False)))
for group in GROUPS:
column = f"person_{group}_id__{YEAR}"
assert from_csv[column].dtype == np.int64
assert from_csv[column].tolist() == population.groups[group].tolist()
assert_holds(Simulation(dataset=from_csv), population)


Expand Down Expand Up @@ -1488,6 +1492,19 @@ def give_values_for(
# their place in their year of age, in a year before the data.
@example(population=ONE_PERSON, id_columns="both", input_years={YEAR - 3}, weight=1)
@example(population=TWINS, id_columns="own", input_years={YEAR - 1}, weight=1_000_000)
@example(
population=Population(
person_ids=np.array([900_000_034, 900_000_035]),
groups={
"benunit": np.array([900_000_036, 900_000_036]),
"household": np.array([900_000_037, 900_000_037]),
},
values=TWINS.values,
),
id_columns="exported",
input_years={YEAR - 1},
weight=1_000_000,
)
def test_a_reloaded_simulation_reads_the_same_identifiers_in_each_year_given_inputs(
identifier_readers, population, id_columns, input_years, weight
):
Expand Down Expand Up @@ -1518,7 +1535,8 @@ def test_a_reloaded_simulation_reads_the_same_identifiers_in_each_year_given_inp
built, group
)
membership = built.calculate(f"person_{group}_id", year)
exact = population.groups[group].astype(np.float32)
exact = population.groups[group]
assert membership.dtype.kind == "i"
assert membership.tolist() == exact.tolist()
pd.testing.assert_frame_equal(reloaded.to_input_dataframe(), exported)

Expand Down
Loading
Loading