Skip to content

Commit 78d8297

Browse files
authored
Add global option to skip households on simulation failure (#1023)
* skip hh in simple simulate * retain `household_id` by default in the drop_unused_columns() we need it for debug tracing and skipping failed hh * skip choice for interaction sample simulate * don't log hh id when bad choice df is empy * add hh id to user specified `chooser_columns` when `chooser_columns` exist * blacken * update test utils to probs raises * [skip ci] shadow price calc without failed choices * [skip ci] special case in trip mode choice * [skip ci] adjust sample_rate * [skip ci] add final logging of num hh skipped * unit test * update CI * track and summarize failed households by component * `skipped_household_ids` is now a dictionary * print more loggings about trips missing modes * adjust trip expansion factor using hh weight instead of count * update state tables only when new households are skipped * put a limit on num of households allowed to skip * auto debug tracing newly failed choice * update test * Add documentation to user guide * update doc * increase sample rate decimals * handle zero `sample_rate` when calculating weights * black * [skip ci] confirm trace files are generated for skipped hh * Revert "increase sample rate decimals" This reverts commit a734c16. * add note for not rounding sample rate * write trip matrices even when `sample_rate` is all zero To pass this single hh test: https://github.com/ActivitySim/activitysim/actions/runs/23202170408/job/67427319813?pr=1023
1 parent 67f4e19 commit 78d8297

23 files changed

Lines changed: 855 additions & 4 deletions

‎.github/workflows/core_tests.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ jobs:
130130
131131
- run: uv run pytest test/test_skim_name_conflicts.py
132132
- run: uv run pytest test/random_seed/test_random_seed.py
133+
- run: uv run pytest test/skip_failed_choices/test_skip_failed_choices.py
133134
- run: uv run pytest test/trace_id/test_trace_id.py
134135

135136
builtin_regional_models:

‎activitysim/abm/models/location_choice.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,11 @@ def location_sample(
234234
):
235235
# FIXME - MEMORY HACK - only include columns actually used in spec
236236
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
237+
# Drop this when PR #1017 is merged
238+
if ("household_id" not in chooser_columns) and (
239+
"household_id" in persons_merged.columns
240+
):
241+
chooser_columns = chooser_columns + ["household_id"]
237242
choosers = persons_merged[chooser_columns]
238243

239244
# create wrapper with keys for this lookup - in this case there is a home_zone_id in the choosers
@@ -390,6 +395,11 @@ def location_presample(
390395
# FIXME maybe we should add it for multi-zone (from maz_taz) if missing?
391396
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
392397
chooser_columns = [HOME_TAZ if c == HOME_MAZ else c for c in chooser_columns]
398+
# Drop this when PR #1017 is merged
399+
if ("household_id" not in chooser_columns) and (
400+
"household_id" in persons_merged.columns
401+
):
402+
chooser_columns = chooser_columns + ["household_id"]
393403
choosers = persons_merged[chooser_columns]
394404

395405
# create wrapper with keys for this lookup - in this case there is a HOME_TAZ in the choosers
@@ -620,6 +630,11 @@ def run_location_simulate(
620630

621631
# FIXME - MEMORY HACK - only include columns actually used in spec
622632
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
633+
# Drop this when PR #1017 is merged
634+
if ("household_id" not in chooser_columns) and (
635+
"household_id" in persons_merged.columns
636+
):
637+
chooser_columns = chooser_columns + ["household_id"]
623638
choosers = persons_merged[chooser_columns]
624639

625640
alt_dest_col_name = model_settings.ALT_DEST_COL_NAME
@@ -1072,6 +1087,33 @@ def iterate_location_choice(
10721087
else:
10731088
choices_df = choices_df_
10741089

1090+
if (
1091+
state.settings.skip_failed_choices
1092+
and state.get("num_skipped_households", 0) > 0
1093+
):
1094+
# drop choices that belong to the failed households: state.skipped_household_ids
1095+
# so that their choices are not considered in shadow price calculations
1096+
# first append household_id to choices_df
1097+
choices_df = choices_df.merge(
1098+
persons_merged_df[["household_id"]],
1099+
left_index=True,
1100+
right_index=True,
1101+
how="left",
1102+
)
1103+
if len(choices_df) > 0:
1104+
# Get all household IDs from all trace_labels in the dictionary
1105+
import itertools
1106+
1107+
skipped_household_ids_dict = state.get("skipped_household_ids", dict())
1108+
all_skipped_hh_ids = set(
1109+
itertools.chain.from_iterable(skipped_household_ids_dict.values())
1110+
)
1111+
1112+
choices_df = choices_df[
1113+
~choices_df["household_id"].isin(all_skipped_hh_ids)
1114+
]
1115+
choices_df = choices_df.drop(columns=["household_id"])
1116+
10751117
spc.set_choices(
10761118
choices=choices_df["choice"],
10771119
segment_ids=persons_merged_df[chooser_segment_column].reindex(

‎activitysim/abm/models/school_escorting.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,11 @@ def school_escorting(
468468
# reduce memory by limiting columns if selected columns are supplied
469469
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
470470
if chooser_columns is not None:
471+
# Drop this when PR #1017 is merged
472+
if ("household_id" not in chooser_columns) and (
473+
"household_id" in choosers.columns
474+
):
475+
chooser_columns = chooser_columns + ["household_id"]
471476
chooser_columns = chooser_columns + participant_columns
472477
choosers = choosers[chooser_columns]
473478

‎activitysim/abm/models/trip_matrices.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,70 @@ def write_trip_matrices(
9090

9191
trips_df = annotate_trips(state, trips, network_los, model_settings)
9292

93+
# This block adjusts household sample rate column to account for skipped households.
94+
# Note: the `HH_EXPANSION_WEIGHT_COL` is pointing to the `sample_rate` column in the households table.
95+
# Based on the calculation in write_matrices() function, the sample_rate is used to calculate the expansion weight as 1 / sample_rate.
96+
# A sample_rate of 0.01 means the sample household should be expanded 1/0.01 = 100 times in the actual population households.
97+
# In simulation, the `sample_rate` is calculated and added to the synthetic households
98+
# based on household_sample_size / total_household_count, and therefore is the same for all households.
99+
# In estimation, the `sample_rate` may vary by household, but weights are not used in estimation, and write_trip_matrices is not called during estimation.
100+
# But we still try to cover both cases (when rates are the same vs when they vary) here for consistency.
101+
hh_weight_col = model_settings.HH_EXPANSION_WEIGHT_COL
102+
household_sample_rate = state.get_dataframe("households")[hh_weight_col]
103+
zero_household_sample_rate = household_sample_rate == 0
104+
105+
# Check if there are households with zero `sample_rate`, which will result in inf expansion weight.
106+
# If all households have zero `sample_rate`, then all trips will have inf expansion weight, we will use household count instead of weight for adjustment factor calculation
107+
# If some households have zero `sample_rate`, we will print a warning and skip trips from those households in the trip matrix generation.
108+
if zero_household_sample_rate.all():
109+
logger.warning(
110+
f"All households have {hh_weight_col} of 0, which will result in inf expansion weight. "
111+
f"Trip matrix generation will be based on household count instead of weight."
112+
)
113+
elif zero_household_sample_rate.any():
114+
logger.warning(
115+
f"Some households have {hh_weight_col} of 0, which will result in inf expansion weight. "
116+
f"Trips from those households will be skipped in trip matrix generation."
117+
)
118+
trips_df = trips_df[trips_df[hh_weight_col] != 0]
119+
# skip trip matrix generation if there are no trips left after filtering out zero sample_rate households
120+
if trips_df.empty:
121+
logger.warning(
122+
f"All trips have {hh_weight_col} of 0, which will result in inf expansion weight. "
123+
f"Trip matrix generation will be skipped."
124+
)
125+
return
126+
127+
if state.get("num_skipped_households", 0) > 0:
128+
logger.info(
129+
f"Adjusting household sample rate in {hh_weight_col} to account for {state.get('num_skipped_households', 0)} skipped households."
130+
)
131+
skipped_sample_rate = state.get_dataframe("households_skipped")[hh_weight_col]
132+
remaining_sample_rate = household_sample_rate
133+
134+
if zero_household_sample_rate.all():
135+
# if all households have zero sample rate, we will use household count instead of weight for adjustment factor calculation
136+
skipped_household_count = state.get("num_skipped_households", 0)
137+
remaining_household_count = len(state.get_dataframe("households"))
138+
total_household_count = skipped_household_count + remaining_household_count
139+
adjustment_factor = remaining_household_count / total_household_count
140+
else:
141+
# adjust the hh sample rates to account for skipped households
142+
# first get the total expansion weight of the skipped households, which will be the sum of inverse of their sample rates
143+
skipped_household_weights = (
144+
1 / skipped_sample_rate[skipped_sample_rate != 0]
145+
).sum()
146+
# next get the total expansion weight of the remaining households
147+
remaining_household_weights = (
148+
1 / remaining_sample_rate[remaining_sample_rate != 0]
149+
).sum()
150+
# the adjustment factor is the remaining household weight / (remaining household weight + skipped household weight)
151+
total_household_weights = (
152+
remaining_household_weights + skipped_household_weights
153+
)
154+
adjustment_factor = remaining_household_weights / total_household_weights
155+
trips_df[hh_weight_col] = trips_df[hh_weight_col] * adjustment_factor
156+
93157
if model_settings.SAVE_TRIPS_TABLE:
94158
state.add_table("trips", trips_df)
95159

‎activitysim/abm/models/trip_mode_choice.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,20 @@ def trip_mode_choice(
366366
"trip_mode_choice choices", trips_df[mode_column_name], value_counts=True
367367
)
368368

369-
assert not trips_df[mode_column_name].isnull().any()
369+
# if we're skipping failed choices, the trip modes for failed simulations will be null
370+
if state.settings.skip_failed_choices:
371+
# Get all household IDs from all trace_labels in the dictionary - more efficient flattening
372+
import itertools
373+
374+
skipped_household_ids_dict = state.get("skipped_household_ids", dict())
375+
all_skipped_hh_ids = set(
376+
itertools.chain.from_iterable(skipped_household_ids_dict.values())
377+
)
378+
379+
mask_skipped = trips_df["household_id"].isin(all_skipped_hh_ids)
380+
assert not trips_df.loc[~mask_skipped, mode_column_name].isnull().any()
381+
else:
382+
assert not trips_df[mode_column_name].isnull().any()
370383

371384
state.add_table("trips", trips_df)
372385

@@ -382,6 +395,8 @@ def trip_mode_choice(
382395
# need to update locals_dict to access skims that are the same .shape as trips table
383396
locals_dict = {}
384397
locals_dict.update(constants)
398+
if state.settings.skip_failed_choices:
399+
trips_merged = trips_merged.loc[~mask_skipped]
385400
simulate.set_skim_wrapper_targets(trips_merged, skims)
386401
locals_dict.update(skims)
387402
locals_dict["timeframe"] = "trip"

‎activitysim/abm/models/util/school_escort_tours_trips.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1043,6 +1043,41 @@ def force_escortee_trip_modes_to_match_chauffeur(state: workflow.State, trips):
10431043
f"Changed {diff.sum()} trip modes of school escortees to match their chauffeur"
10441044
)
10451045

1046+
# trip_mode can be na if the run allows skipping failed choices and the trip mode choice has failed
1047+
# in that case we can't assert that all trip modes are filled
1048+
# instead, we throw a warning about how many are missing, and return early
1049+
if state.settings.skip_failed_choices:
1050+
missing_count = trips.trip_mode.isna().sum()
1051+
if missing_count > 0:
1052+
# check if the missing trip modes are all because of simulation failures
1053+
# i.e., they are from households that are in the skipped_household_ids set
1054+
import itertools
1055+
1056+
skipped_household_ids_dict = state.get("skipped_household_ids", dict())
1057+
skipped_household_ids = set(
1058+
itertools.chain.from_iterable(skipped_household_ids_dict.values())
1059+
)
1060+
missing_household_ids = set(
1061+
trips[trips.trip_mode.isna()]["household_id"].unique()
1062+
)
1063+
# log a warning about the missing trip modes for skipped households
1064+
missing_count_due_to_sim_fail = len(
1065+
trips[
1066+
trips.trip_mode.isna()
1067+
& trips.household_id.isin(skipped_household_ids)
1068+
]
1069+
)
1070+
logger.warning(
1071+
f"Missing trip mode for {missing_count_due_to_sim_fail} trips due to simulation failures in trip mode choice, "
1072+
f"these records and their corresponding households are being skipped: {missing_household_ids}"
1073+
)
1074+
# throw assertion error if there are missing trip modes for households that were not skipped
1075+
assert missing_household_ids.issubset(skipped_household_ids), (
1076+
f"Missing trip modes for households that were not skipped: {missing_household_ids - skipped_household_ids}. "
1077+
f"Missing trip modes for: {trips[trips.trip_mode.isna() & ~trips.household_id.isin(skipped_household_ids)]}"
1078+
)
1079+
return trips
1080+
10461081
assert (
10471082
~trips.trip_mode.isna()
10481083
).all(), f"Missing trip mode for {trips[trips.trip_mode.isna()]}"

‎activitysim/abm/models/util/tour_destination.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,11 @@ def run_destination_sample(
625625
# if special person id is passed
626626
chooser_id_column = model_settings.CHOOSER_ID_COLUMN
627627

628+
# Drop this when PR #1017 is merged
629+
if ("household_id" not in chooser_columns) and (
630+
"household_id" in persons_merged.columns
631+
):
632+
chooser_columns = chooser_columns + ["household_id"]
628633
persons_merged = persons_merged[
629634
[c for c in persons_merged.columns if c in chooser_columns]
630635
]
@@ -799,6 +804,11 @@ def run_destination_simulate(
799804
# if special person id is passed
800805
chooser_id_column = model_settings.CHOOSER_ID_COLUMN
801806

807+
# Drop this when PR #1017 is merged
808+
if ("household_id" not in chooser_columns) and (
809+
"household_id" in persons_merged.columns
810+
):
811+
chooser_columns = chooser_columns + ["household_id"]
802812
persons_merged = persons_merged[
803813
[c for c in persons_merged.columns if c in chooser_columns]
804814
]

‎activitysim/abm/models/util/tour_od.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,9 @@ def run_od_sample(
692692
choosers = tours
693693
# FIXME - MEMORY HACK - only include columns actually used in spec
694694
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
695+
# Drop this when PR #1017 is merged
696+
if ("household_id" not in chooser_columns) and ("household_id" in choosers.columns):
697+
chooser_columns = chooser_columns + ["household_id"]
695698
choosers = choosers[chooser_columns]
696699

697700
# interaction_sample requires that choosers.index.is_monotonic_increasing
@@ -951,6 +954,9 @@ def run_od_simulate(
951954

952955
# FIXME - MEMORY HACK - only include columns actually used in spec
953956
chooser_columns = model_settings.SIMULATE_CHOOSER_COLUMNS
957+
# Drop this when PR #1017 is merged
958+
if ("household_id" not in chooser_columns) and ("household_id" in choosers.columns):
959+
chooser_columns = chooser_columns + ["household_id"]
954960
choosers = choosers[chooser_columns]
955961

956962
# interaction_sample requires that choosers.index.is_monotonic_increasing

‎activitysim/abm/models/util/tour_scheduling.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ def run_tour_scheduling(
4040
c for c in model_columns if c not in logsum_columns
4141
]
4242

43+
# Drop this when PR #1017 is merged
44+
if ("household_id" not in chooser_columns) and (
45+
"household_id" in persons_merged.columns
46+
):
47+
chooser_columns = chooser_columns + ["household_id"]
48+
4349
persons_merged = expressions.filter_chooser_columns(persons_merged, chooser_columns)
4450

4551
timetable = state.get_injectable("timetable")

‎activitysim/abm/tables/households.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ def households(state: workflow.State) -> pd.DataFrame:
9999
if households_sample_size == 0:
100100
sample_rate = 1
101101
else:
102+
# TODO: do not round, keep full precision to avoid creating 0 sample_rate for small samples
103+
# Existing CI tests will fail when performing bitwise comparisons with the unrounded sample_rate
104+
# We should update the CI tests
102105
sample_rate = round(households_sample_size / tot_households, 3)
103106

104107
df["sample_rate"] = sample_rate
@@ -110,6 +113,12 @@ def households(state: workflow.State) -> pd.DataFrame:
110113

111114
# replace table function with dataframe
112115
state.add_table("households", df)
116+
if state.settings.skip_failed_choices:
117+
logger.info(
118+
"Note: 'skip_failed_choices' is enabled; households may be skipped when simulation fails."
119+
)
120+
# initialize skipped households table as empty and same columns as households
121+
state.add_table("households_skipped", df.iloc[0:0])
113122

114123
state.get_rn_generator().add_channel("households", df)
115124

0 commit comments

Comments
 (0)