Skip to content
Draft
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-subsample-preserve-roles.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`Simulation.subsample` carries loaded person IDs, membership IDs and roles for fields without recorded inputs, including distinct integer role slots, and the dataset loader leaves the structural columns it reads out of ignored-column warnings.
6 changes: 5 additions & 1 deletion docs/usage/simulation.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1115,7 +1115,11 @@
"source": [
"### Subsampling simulations\n",
"\n",
"Often, we're running simulations over very large (100,000+) datasets. This can be slow, so we might want to subsample the dataset to speed up the simulation. This can be done by using `Simulation.subsample` or `Microsimulation.subsample`, which will return a new `Simulation` or `Microsimulation` object with a smaller dataset."
"Use `Simulation.subsample` or `Microsimulation.subsample` to run a simulation on a smaller dataset. The method rebuilds the simulation in place and returns the same object.\n",
"\n",
"Recorded structural inputs take precedence and can change household membership or roles. The loader uses the first matching column in dataset order, while subsampling exports recorded periods in sorted order. With multiple recorded periods, the rebuild can use a different period from the original load.\n",
"\n",
"For fields without recorded inputs, subsampling uses the loaded person and membership IDs and carries roles by key or, for integer variables, by flattened role index. This also works for fields without backing variables. If subsampling cannot identify a flattened role for a member when reconstructing an integer role column, it raises `ValueError` before rebuilding the simulation."
]
},
{
Expand Down
12 changes: 11 additions & 1 deletion policyengine_core/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ class Dataset:
FLAT_FILE = "flat_file"

_table_cache: Dict[str, pd.DataFrame] = None
_preserve_group_ids: bool = False

def __init__(self, require: bool = False):
# Setup dataset
Expand Down Expand Up @@ -481,9 +482,17 @@ def from_file(file_path: str, time_period: str = None):
return dataset

@staticmethod
def from_dataframe(dataframe: pd.DataFrame, time_period: str = None):
def from_dataframe(
dataframe: pd.DataFrame,
time_period: str = None,
*,
preserve_group_ids: bool = False,
):
"""Creates a dataset from a DataFrame.

If ``preserve_group_ids`` is true, the simulation uses the membership
labels as group IDs when loading the dataset.

Returns:
Dataset: The dataset.
"""
Expand All @@ -497,6 +506,7 @@ def from_dataframe(dataframe: pd.DataFrame, time_period: str = None):
"file_path": "dataframe",
"time_period": time_period,
"load": lambda self: dataframe,
"_preserve_group_ids": preserve_group_ids,
},
)()

Expand Down
104 changes: 79 additions & 25 deletions policyengine_core/simulations/simulation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hashlib
import os
from collections import Counter
from contextlib import nullcontext
import types
from contextvars import ContextVar
Expand Down Expand Up @@ -1120,9 +1121,11 @@ def build_from_dataset(self) -> None:

Entity-specific role columns take precedence over a generic ``role``
column, including period-suffixed entity role columns in flat files.
Without either, each person receives the literal ``default_role``
key. Only flattened-role keys match: unmatched and compound keys remain
unrecognized rather than selecting a first role or subrole.
The loader uses the first matching column in dataset order.
Integer role arrays index flattened role slots. String role arrays
match flattened role keys literally, leaving other keys unmatched.
Without a role column, each person receives the literal
``default_role`` key.

A recognized implicit default with a finite role maximum must fit every
group's membership count. Otherwise an explicit role column is required.
Expand Down Expand Up @@ -1151,14 +1154,19 @@ def build_from_dataset(self) -> None:

person_entity = self.tax_benefit_system.person_entity
entity_id_field = f"{person_entity.key}_id"
# Columns read to build the populations are used even when no
# variable has their name, so they are not reported as ignored.
structural_columns = set()

def get_eternity_array(name):
if self.dataset.data_format == Dataset.FLAT_FILE:
# Look for any column with variablename__timeperiod
for col in data:
if col.split("__")[0] == name:
structural_columns.add(col)
return data[col]
elif self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS:
structural_columns.add(name)
if self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS:
return data[name][list(data[name].keys())[0]]
return data[name]

Expand Down Expand Up @@ -1188,8 +1196,7 @@ def get_eternity_array(name):
# 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.
# each member's row.
membership_field = next(
(
field
Expand All @@ -1206,10 +1213,14 @@ def get_eternity_array(name):
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 self.dataset._preserve_group_ids:
entity_ids = np.unique(membership_values)
person_membership_ids = membership_values
else:
distinct_ids, person_membership_ids = np.unique(
membership_values, return_inverse=True
)
entity_ids = np.arange(len(distinct_ids))

builder.declare_entity(group_entity.key, entity_ids)

Expand Down Expand Up @@ -1271,7 +1282,7 @@ def get_eternity_array(name):
self.set_input(
variable, self.dataset.time_period, data[variable]
)
else:
elif variable not in structural_columns:
unknown_columns.append(variable)
else:
for variable in data:
Expand All @@ -1282,7 +1293,8 @@ def get_eternity_array(name):
time_period = self.dataset.time_period or self.default_input_period

if variable_name not in self.tax_benefit_system.variables:
unknown_columns.append(variable)
if variable not in structural_columns:
unknown_columns.append(variable)
continue

variable_meta = self.tax_benefit_system.get_variable(variable_name)
Expand Down Expand Up @@ -3636,9 +3648,15 @@ def subsample(
Calculated weights and other formula results are recomputed on the
sample. Calculation branches are recreated on its populations;
baseline policy is kept.
If structural inputs are absent, loaded population IDs, memberships
and roles supply the leaves needed to rebuild the same partition.
This also supports structural variables whose IDs have formulas.
Recorded structural inputs take precedence in the rebuild and can
change household membership or roles. The dataset loader uses the
first matching column. Subsampling exports recorded periods in sorted
order, so the reload can use a different period from the source.
Fields without recorded inputs use loaded person IDs, membership IDs
and role assignments, including fields without backing variables.
Role columns use keys or, for integer variables, flattened role
indices. Reconstructing an integer column raises ``ValueError`` before
rebuilding if a member's flattened role cannot be identified.

Args:
n (int, optional): The number of households to sample. Defaults to 10_000.
Expand All @@ -3647,7 +3665,7 @@ def subsample(
time_period (str, optional): Sample households based on their weight in this time period. Defaults to the default calculation period.

Returns:
Simulation: The quantized simulation.
Simulation: This simulation, rebuilt in place with the sample.
"""
default_calculation_period = self.default_calculation_period
# Set default key if not provided
Expand All @@ -3668,12 +3686,15 @@ def subsample(
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):
if any(column.split("__")[0] == name for column in df):
return
# The loader reads structural columns by name, so a leaf that no
# variable backs (a role column the system does not define, for
# instance) is still carried. It has no period of its own.
variable = self.tax_benefit_system.get_variable(name)
structural_period = (
ETERNITY
if variable.definition_period == ETERNITY
if variable is None or variable.definition_period == ETERNITY
else periods.period(self.dataset.time_period).start.period(
variable.definition_period
)
Expand All @@ -3691,17 +3712,48 @@ def retain_structure(name, values):
population.ids[population.members_entity_id],
)
role_name = f"{person_key}_{entity.key}_role"
if any(column.split("__")[0] == role_name for column in df):
continue
role_variable = self.tax_benefit_system.get_variable(role_name)
roles = np.broadcast_to(population.members_role, self.persons.count)
roles = np.broadcast_to(
np.asarray(population.members_role, dtype=object),
self.persons.count,
)
flattened_roles = entity.flattened_roles
key_counts = Counter(role.key for role in flattened_roles)
if role_variable is not None and role_variable.value_type == int:
# Canonical role objects identify their slots even when keys
# repeat. A detached role's key can identify a unique slot.
by_role = {role: index for index, role in enumerate(flattened_roles)}
by_key = {
role.key: index
for role, index in by_role.items()
if key_counts[role.key] == 1
}
role_values = [
entity.flattened_roles.index(role)
if role in entity.flattened_roles
else 0
by_role.get(role, by_key.get(getattr(role, "key", None), -1))
for role in roles
]
if -1 in role_values:
unindexed = sorted(
{
getattr(role, "key", "(no role)")
for role, index in zip(roles, role_values)
if index == -1
}
)
raise ValueError(
f"Cannot subsample: {role_name} is an integer role "
f"variable, so it can only hold the {entity.key} roles "
f"{[role.key for role in flattened_roles]}, but "
f"some members hold {unindexed}."
)
else:
role_values = [getattr(role, "key", "") for role in roles]
# Use a key the loader will leave unmatched.
no_role = ""
while no_role in key_counts:
no_role += "_"
role_values = [getattr(role, "key", no_role) for role in roles]
retain_structure(role_name, role_values)

# Flat-file loading can infer households from membership IDs even
Expand Down Expand Up @@ -3815,7 +3867,9 @@ def retain_structure(name, values):
df = subset_df

# Rebuilding replaces storage, its input record, and store history.
self.dataset = Dataset.from_dataframe(df, self.dataset.time_period)
self.dataset = Dataset.from_dataframe(
df, self.dataset.time_period, preserve_group_ids=True
)
self._store_history = StoreHistory()
self._user_input_keys = set()
self.build_from_dataset()
Expand Down
Loading