Skip to content

Commit 2447cc7

Browse files
janzillCopilot
andauthored
post EET merge clean up (#1098)
* fallback poisson without zero prob alts, mathjax rendering for doco * removes todo * fix trip_schedulin_choice comment * use standard terminology * Apply suggestions from code review Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent da0d9b1 commit 2447cc7

15 files changed

Lines changed: 237 additions & 141 deletions

‎activitysim/abm/models/trip_scheduling_choice.py‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -279,14 +279,28 @@ def run_trip_scheduling_choice(
279279
) in chunk.adaptive_chunked_choosers(state, indirect_tours, trace_label):
280280
# Sort the choosers and get the schedule alternatives
281281
choosers = choosers.sort_index()
282-
# FIXME-EET: For explicit error term choices, we need a stable alternative ID. Currently, we use
283-
# SCHEDULE_ID, which justs enumerates all schedule alternatives, of which there are choosers times
284-
# alternative, in the order they are processed, which depends on if there stops on outward/return leg.
285-
# We might want to change SCHEDULE_ID to a fixed pattern of all possible combinations of
286-
# (outbound, main, inbound) duration for the maximum possible tour duration (max time window). For
287-
# 30min intervals, this leads to 1225 alternatives and therefore reasonable memory-wise for random numbers.
288-
# It looks like all that would need to change for this is the generation of the schedule alternatives and
289-
# the lookup of choices as elements in schedule after simulation because choosers are indexed by tour_id.
282+
# FIXME-EET: under use_explicit_error_terms, error terms here are aligned positionally, not keyed
283+
# to a stable alternative ID: no alts_context is passed to _interaction_sample_simulate (this direct
284+
# private call also bypasses the public wrapper's warning about that), so each tour draws one EV1
285+
# error per alternative slot from its own tour_id-keyed channel, and the j-th draw attaches to the
286+
# j-th row of the tour's block in `schedules`. SCHEDULE_ID plays no role in the alignment; it is a
287+
# per-call running enumeration used only to look up the chosen row after the simulation.
288+
#
289+
# The per-tour row order is canonical: get_pattern_index_and_arrays sorts each tour's feasible
290+
# windows lexicographically by (main, outbound, inbound) duration via np.unique, independent of
291+
# chunk composition and processing order. Error terms are therefore stable across scenarios for
292+
# every tour whose stop pattern (outbound/inbound) and duration are unchanged. They are NOT aligned
293+
# for a tour whose duration or stop pattern changes: the lexicographic enumeration shifts, so
294+
# position j maps to a different duration triple.
295+
#
296+
# To keep draws aligned across such changes too, key them to a canonical universe of schedule
297+
# patterns -- e.g. all (outbound, inbound) duration pairs up to the maximum time window, with the
298+
# main leg implied by the tour duration; for 30min intervals that is 1225 stable IDs, reasonable
299+
# memory-wise for random numbers, and a duration change then keeps the error terms of unchanged
300+
# (outbound, inbound) allocations. This would mean making SCHEDULE_ID that stable pattern ID and
301+
# passing an alts_context (see the alt_nrs_df machinery in _interaction_sample_simulate); the
302+
# post-simulation lookup below would then need to match on (tour_id, SCHEDULE_ID) pairs since IDs
303+
# would repeat across tours.
290304

291305
schedules = generate_schedule_alternatives(choosers).sort_index()
292306

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ def maybe_bias_logsums(state: workflow.State, choices_df: pd.DataFrame, model_se
4141
else:
4242
logger.warning(
4343
"Using Poisson sampling method for location choice logsum calculations. Currently the logsums results will"
44-
+ " differ from those obtained with monte_carlo or eet sampling by a constant shift of"
44+
+ " differ from those obtained with inverse_cdf or eet sampling by a constant shift of"
4545
+ f" log({model_settings.SAMPLE_SIZE}) if using the common correction factor"
4646
+ " `log(pick_count / prob)` in location choice specs. The results of the Poisson method are unbiased,"
4747
+ " i.e., they agree with the results obtained with a full destination sample, unlike those for"
48-
+ " monte_carlo or eet sampling."
48+
+ " inverse_cdf or eet sampling."
4949
)
5050

5151
return choices_df

‎activitysim/core/configuration/base.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,12 +135,12 @@ class ComputeSettings(PydanticBase):
135135
Sharrow settings for a component.
136136
"""
137137

138-
sample_method: None | Literal["monte_carlo", "eet", "poisson"] = None
138+
sample_method: None | Literal["inverse_cdf", "eet", "poisson"] = None
139139
"""
140140
Override the alternative sampling method used by `interaction_sample`.
141141
142142
When unset, `interaction_sample` preserves legacy behavior: it uses
143-
`monte_carlo` when explicit error terms are off and `poisson` when they
143+
`inverse_cdf` when explicit error terms are off and `poisson` when they
144144
are on.
145145
"""
146146

‎activitysim/core/configuration/top.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -786,17 +786,18 @@ def _check_store_skims_in_shm(self):
786786
Make choice from random utility model by drawing from distribution of unobserved
787787
part of utility and taking the maximum of total utility.
788788
789-
Defaults to standard Monte Carlo method, i.e., calculating probabilities and then
790-
drawing a single uniform random number to draw from cumulative probabily.
789+
Defaults to the standard inverse-CDF (probability-based) method, i.e., calculating
790+
probabilities and then drawing a single uniform random number against the
791+
cumulative probability.
791792
792793
.. versionadded:: 1.6
793794
"""
794795

795-
sample_method: None | Literal["monte_carlo", "eet", "poisson"] = None
796+
sample_method: None | Literal["inverse_cdf", "eet", "poisson"] = None
796797
"""
797798
Sampling method to use in `activitysim.core.interaction_sample`.
798799
799-
When unset, `monte_carlo` is used when `use_explicit_error_terms` is false and
800+
When unset, `inverse_cdf` is used when `use_explicit_error_terms` is false and
800801
`poisson` is used when it is true.
801802
802803
.. versionadded:: 1.6
@@ -806,7 +807,7 @@ def _check_store_skims_in_shm(self):
806807
"""
807808
Whether to apply a bias of `log(sample_size)` to the Poisson sampling results.
808809
This is a temporary workaround to align Poisson sampling results with the biased
809-
results of the monte_carlo and eet sampling methods, such that models that were
810+
results of the inverse_cdf and eet sampling methods, such that models that were
810811
estimated with historical biased sampling results can be run with Poisson sampling
811812
without needing to re-estimate the model.
812813

‎activitysim/core/interaction_sample.py‎

Lines changed: 47 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
DUMP = False
3333

34-
InteractionSampleMethod = typing.Literal["monte_carlo", "eet", "poisson"]
34+
InteractionSampleMethod = typing.Literal["inverse_cdf", "eet", "poisson"]
3535

3636
# Threshold on P0, the probability that a chooser's Poisson draw comes up empty, below
3737
# which the fallback term is dropped from the reported inclusion probabilities. Choosers
@@ -82,7 +82,7 @@ def resolve_sample_method(
8282
sampling_method = state.settings.sample_method
8383
if sampling_method is None:
8484
sampling_method = (
85-
"poisson" if state.settings.use_explicit_error_terms else "monte_carlo"
85+
"poisson" if state.settings.use_explicit_error_terms else "inverse_cdf"
8686
)
8787
if sampling_method not in typing.get_args(InteractionSampleMethod):
8888
raise ValueError(
@@ -134,6 +134,10 @@ def _poisson_fallback_positions(
134134
alternatives for each row of `probs_values` (all of them if there are fewer
135135
than `sample_size` alternatives), with ties broken by column position.
136136
137+
A row with fewer than `sample_size` positive-probability alternatives gets
138+
zero-probability positions in its trailing columns; the caller drops those
139+
pairs so that an unavailable alternative can never enter the choice set.
140+
137141
This is deliberately *deterministic* and consumes no random numbers, so every
138142
chooser row advances its RNG channel by exactly the same amount whether or not
139143
the fallback fires. That keeps random number streams aligned across scenarios,
@@ -166,7 +170,7 @@ def make_sample_choices_eet(
166170
167171
Each chooser receives `sample_size` EV1 draw sets and the argmax-over-utility
168172
winner is recorded per draw, so duplicates are possible (same with-replacement
169-
semantics as the Monte Carlo sampling path).
173+
semantics as the inverse-CDF sampling path).
170174
171175
`utilities` drives the Gumbel argmax. `probs` (the MNL choice probabilities
172176
computed from the same utilities by the caller) supplies the `prob` column
@@ -225,7 +229,7 @@ def make_sample_choices_poisson(
225229
226230
where `p_i` is the chooser's MNL choice probability for alternative `i`. That is the
227231
probability the alternative would have been drawn at least once across `sample_size`
228-
Monte Carlo draws, which is what makes Poisson sampling interchangeable with the other
232+
inverse-CDF draws, which is what makes Poisson sampling interchangeable with the other
229233
sampling methods. `pick_count` is 1 by definition (the draw is a yes/no per
230234
alternative), so the standard sampling correction factor is recoverable in the usual
231235
way as `np.log(df.pick_count / df.prob)`.
@@ -238,8 +242,11 @@ def make_sample_choices_poisson(
238242
Since the probabilities sum to one and 1 - p <= exp(-p), this is bounded above by
239243
exp(-sample_size): very small at the sample sizes these models use (~1e-13
240244
for `sample_size=30`), but not negligible at small sample sizes or for a chooser whose
241-
probability mass is spread thinly. Those choosers fall back to the `sample_size`
242-
highest-probability alternatives (see `_poisson_fallback_positions`). The fallback is
245+
probability mass is spread thinly. Those choosers fall back to their
246+
`min(sample_size, n_available)` highest-probability available alternatives, where
247+
`n_available` counts the alternatives with non-zero probability (see
248+
`_poisson_fallback_positions`) -- an unavailable alternative can never enter the
249+
choice set through either branch. The fallback is
243250
deterministic and draws no random numbers, so every chooser advances its RNG channel by
244251
exactly the same amount whether or not it fires -- unlike a retry scheme, this cannot
245252
desynchronise random number streams between scenarios.
@@ -293,9 +300,9 @@ def make_sample_choices_poisson(
293300
if n_empty > 0:
294301
logger.warning(
295302
f"Poisson sampling drew an empty choice set for {n_empty} of {len(probs)} "
296-
f"chooser(s) in {trace_label}; falling back to the "
297-
f"{min(sample_size, probs_values.shape[1])} highest-probability alternatives "
298-
f"for those choosers. Highest empty-sample probability was "
303+
f"chooser(s) in {trace_label}; falling back to (at most) the "
304+
f"{min(sample_size, probs_values.shape[1])} highest-probability available "
305+
f"alternatives for those choosers. Highest empty-sample probability was "
299306
f"{empty_sample_probs[empty_rows].max():.2g} against a requested sample size "
300307
f"of {sample_size} and a mean expected sample size of "
301308
f"{inclusion_probs[empty_rows].sum(axis=1).mean():.1f}."
@@ -312,6 +319,17 @@ def make_sample_choices_poisson(
312319
)
313320
row_positions = np.repeat(fallback_rows, fallback_cols.shape[1])
314321
col_positions = fallback_cols.reshape(-1)
322+
323+
# drop zero-probability pairs: a chooser with fewer available (p > 0)
324+
# alternatives than the fallback window would otherwise get it padded with
325+
# unavailable alternatives, which would enter the final choice set carrying a
326+
# large positive correction term log(1/P0). The fallback set remains a
327+
# deterministic function of the probabilities, so the closed form for the
328+
# reported prob is unchanged.
329+
available = probs_values[row_positions, col_positions] > 0.0
330+
row_positions = row_positions[available]
331+
col_positions = col_positions[available]
332+
315333
inclusion_probs[row_positions, col_positions] += empty_sample_probs[
316334
row_positions
317335
]
@@ -763,10 +781,10 @@ def _interaction_sample(
763781

764782
sampling_method = resolve_sample_method(state, compute_settings)
765783

766-
# Estimation requires MC sampling and MC choice for now
767-
if estimation.manager.enabled and sampling_method != "monte_carlo":
784+
# Estimation requires inverse-CDF sampling and choice for now
785+
if estimation.manager.enabled and sampling_method != "inverse_cdf":
768786
raise ValueError(
769-
f"{trace_label}: estimation requires monte_carlo sampling and choice. Set sample_method='monte_carlo'"
787+
f"{trace_label}: estimation requires inverse_cdf sampling and choice. Set sample_method='inverse_cdf'"
770788
+ " (or leave it unset) and use_explicit_error_terms=False for estimation runs."
771789
)
772790

@@ -817,7 +835,7 @@ def _interaction_sample(
817835
column_labels=["alternative", "probability"],
818836
)
819837

820-
if sampling_method == "monte_carlo":
838+
if sampling_method == "inverse_cdf":
821839
del utilities
822840
chunk_sizer.log_df(trace_label, "utilities", None)
823841

@@ -872,8 +890,8 @@ def _interaction_sample(
872890
del probs
873891
chunk_sizer.log_df(trace_label, "probs", None)
874892
else:
875-
# eet and poisson: optionally trim choosers with all-zero probs. The MC
876-
# path handles this inside make_sample_choices
893+
# eet and poisson: optionally trim choosers with all-zero probs. The
894+
# inverse-CDF path handles this inside make_sample_choices
877895
if allow_zero_probs:
878896
non_zero = probs.sum(axis=1) != 0
879897
if not non_zero.any():
@@ -1075,20 +1093,25 @@ def interaction_sample(
10751093
sampling_method = resolve_sample_method(state, compute_settings)
10761094
logger.debug(f" interaction_sample sample method = {sampling_method}")
10771095

1078-
if sampling_method == "monte_carlo":
1079-
# The MC sampling path (make_sample_choices) does not consume stable_alt_positions
1080-
# or n_total_alts. Null them out so callers that conservatively pass values along
1081-
# don't accidentally rely on them under MC sampling.
1096+
if sampling_method == "inverse_cdf":
1097+
# The inverse-CDF sampling path (make_sample_choices) does not consume
1098+
# stable_alt_positions or n_total_alts. Null them out so callers that
1099+
# conservatively pass values along don't accidentally rely on them under
1100+
# inverse-CDF sampling.
10821101
stable_alt_positions = None
10831102
n_total_alts = None
10841103

1085-
# FIXME - legacy logic - not sure this is needed or even correct?
10861104
if sampling_method != "poisson":
1105+
# legacy clamp for the with-replacement methods; statistically harmless because
1106+
# the omitted log(sample_size) term in the correction is constant per chooser
10871107
sample_size = min(sample_size, len(alternatives.index))
1088-
# with poisson sampling, definitely don't want to reduce sample size - it's not a sample size but a number
1089-
# of theoretical draws. Another options would be to disable sampling if # alts < sample size to ensure
1090-
# all are included (but this wouldn't behave well if there were land use changes in the project case which
1091-
# switched regimes)
1108+
# with poisson sampling the sample size must not be clamped: it is not a count of
1109+
# draws but the rate parameter of the inclusion probabilities. When a chooser has
1110+
# fewer available alternatives than sample_size, its inclusion probabilities
1111+
# saturate towards 1 and the final choice approaches exact MNL over its full
1112+
# availability set, which is the desired behavior. (Disabling sampling entirely
1113+
# in that regime would behave badly if a project-case land use change switched
1114+
# regimes.)
10921115

10931116
logger.debug(f" interaction_sample sample size = {sample_size}")
10941117

‎activitysim/core/interaction_sample_simulate.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,7 @@ def _interaction_sample_simulate(
9191
9292
choices : pandas.Series
9393
A series where index should match the index of the choosers DataFrame
94-
and values will match the index of the alternatives DataFrame -
95-
choices are simulated in the standard Monte Carlo fashion
94+
and values will match the index of the alternatives DataFrame
9695
9796
if want_logsums is True:
9897
@@ -546,8 +545,7 @@ def interaction_sample_simulate(
546545
547546
choices : pandas.Series
548547
A series where index should match the index of the choosers DataFrame
549-
and values will match the index of the alternatives DataFrame -
550-
choices are simulated in the standard Monte Carlo fashion
548+
and values will match the index of the alternatives DataFrame
551549
552550
if want_logsums is True:
553551
@@ -565,10 +563,11 @@ def interaction_sample_simulate(
565563
# are NOT guaranteed to be consistent across scenarios that differ in alternative
566564
# availability. We cannot make this a hard error today because two production callers
567565
# rely on the warning-only fallback:
568-
# - trip_scheduling_choice: SCHEDULE_ID is a per-call enumeration that depends on
569-
# chunk composition and tour duration distribution (see FIXME in
570-
# trip_scheduling_choice.py:282-289 for the proposed redesign that would key
571-
# SCHEDULE_ID to a fixed (OB, MAIN, IB) duration tuple).
566+
# - trip_scheduling_choice: draws align positionally to each tour's canonical
567+
# schedule enumeration, which is stable while a tour's stop pattern and duration
568+
# are unchanged but shifts when either changes (see the FIXME-EET in
569+
# trip_scheduling_choice.py for the proposed stable-id redesign; note it calls
570+
# _interaction_sample_simulate directly and so does not pass through this warning).
572571
# - tour_od_choice: OD id is a string concatenation `f"{orig}_{dest}"`; a stable
573572
# integer universe would be O(n_zones^2) error terms per chooser, which is too
574573
# large to allocate.

‎activitysim/core/interaction_simulate.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -704,8 +704,7 @@ def _interaction_simulate(
704704
-------
705705
ret : pandas.Series
706706
A series where index should match the index of the choosers DataFrame
707-
and values will match the index of the alternatives DataFrame -
708-
choices are simulated in the standard Monte Carlo fashion
707+
and values will match the index of the alternatives DataFrame
709708
"""
710709

711710
trace_label = tracing.extend_trace_label(trace_label, "interaction_simulate")
@@ -1031,8 +1030,7 @@ def interaction_simulate(
10311030
-------
10321031
choices : pandas.Series
10331032
A series where index should match the index of the choosers DataFrame
1034-
and values will match the index of the alternatives DataFrame -
1035-
choices are simulated in the standard Monte Carlo fashion
1033+
and values will match the index of the alternatives DataFrame
10361034
"""
10371035

10381036
trace_label = tracing.extend_trace_label(trace_label, "interaction_simulate")

‎activitysim/core/logit.py‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,10 @@ def make_choices_explicit_error_term_nl(
584584
pandas.Series
585585
Choice indices aligned to `alt_utilities` columns.
586586
"""
587-
# TODO assert alts_context and alt_nrs_df are both None - no sampling from nested models for now.
587+
if alts_context is not None or alt_nrs_df is not None:
588+
raise NotImplementedError(
589+
f"{trace_label} - Sampling from nested models is not implemented; do not pass alts_context or alt_nrs_df."
590+
)
588591

589592
utilities_incl_unobs = sample_nested_logit_exact_leaf_error_terms(
590593
state,
@@ -688,15 +691,6 @@ def make_choices_utility_based(
688691
rands : pandas.Series
689692
A series of 0s for compatibility with make_choices. For EET, we do not have per-row random numbers.
690693
691-
Notes
692-
-----
693-
An argmax always returns a position, so a chooser with no available alternative gets a
694-
choice here rather than an error: with every utility at `UTIL_UNAVAILABLE` the alternatives
695-
are tied and the error terms decide, and with every utility at `-inf` the first column wins.
696-
The Monte Carlo path does not go quiet in that situation -- `make_choices` reports it unless
697-
`allow_bad_probs` is set -- so this function reports it too. Most callers reach here having
698-
already run `validate_utils`, which makes the same check; the duplication is deliberate and
699-
mirrors `make_choices` re-checking what `utils_to_probs` has already looked at.
700694
"""
701695
trace_label = tracing.extend_trace_label(trace_label, "make_choices_utility_based")
702696

0 commit comments

Comments
 (0)