Skip to content

Commit 315dabc

Browse files
authored
Merge branch 'main' into copilot/deprecate-chooser-columns-settings
2 parents 0f5234e + 3fd4e80 commit 315dabc

21 files changed

Lines changed: 347 additions & 172 deletions

‎activitysim/abm/models/location_choice.py‎

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -927,34 +927,6 @@ def run_location_choice(
927927
)
928928
estimator.write_override_choices(choices_df.choice)
929929

930-
if want_logsums:
931-
# if we override choices, we need to to replace choice logsum with ologsim for override location
932-
# fortunately, as long as we aren't sampling dest alts, the logsum will be in location_sample_df
933-
934-
# if we start sampling dest alts, we will need code below to compute override location logsum
935-
assert estimator.want_unsampled_alternatives
936-
937-
# merge mode_choice_logsum for the overridden location
938-
# alt_logsums columns: ['person_id', 'choice', 'logsum']
939-
alt_dest_col = model_settings.ALT_DEST_COL_NAME
940-
alt_logsums = (
941-
location_sample_df[[alt_dest_col, ALT_LOGSUM]]
942-
.rename(columns={alt_dest_col: "choice", ALT_LOGSUM: "logsum"})
943-
.reset_index()
944-
)
945-
946-
# choices_df columns: ['person_id', 'choice']
947-
choices_df = choices_df[["choice"]].reset_index()
948-
949-
# choices_df columns: ['person_id', 'choice', 'logsum']
950-
choices_df = pd.merge(choices_df, alt_logsums, how="left").set_index(
951-
"person_id"
952-
)
953-
954-
logger.debug(
955-
f"{trace_label} segment {segment_name} estimation: override logsums"
956-
)
957-
958930
if state.settings.trace_hh_id:
959931
estimation_trace_label = tracing.extend_trace_label(
960932
trace_label, f"estimation.{segment_name}.survey_choices"

‎activitysim/abm/models/trip_mode_choice.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ def trip_mode_choice(
228228
trace_choice_name="trip_mode_choice",
229229
estimator=estimator,
230230
compute_settings=model_settings.compute_settings,
231+
explicit_chunk_size=model_settings.explicit_chunk,
231232
)
232233

233234
if state.settings.trace_hh_id:

‎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/abm/models/util/mode.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ def mode_choice_simulate(
3636
trace_column_names=None,
3737
estimator: Optional[Estimator] = None,
3838
compute_settings: ComputeSettings | None = None,
39+
explicit_chunk_size: float = 0,
3940
):
4041
"""
4142
common method for both tour_mode_choice and trip_mode_choice
@@ -47,13 +48,15 @@ def mode_choice_simulate(
4748
nest_spec
4849
skims
4950
locals_d
50-
chunk_size
5151
mode_column_name
5252
logsum_column_name
5353
trace_label
5454
trace_choice_name
5555
estimator
56-
compute_settings : ComputeSettings
56+
compute_settings : ComputeSettings, optional
57+
explicit_chunk_size : float, default 0
58+
If > 0, the fixed number of choosers per chunk (explicit chunking); if 0, chunk sizing
59+
follows the run's chunk_training_mode / adaptive sizing.
5760
5861
Returns
5962
-------
@@ -74,6 +77,7 @@ def mode_choice_simulate(
7477
estimator=estimator,
7578
trace_column_names=trace_column_names,
7679
compute_settings=compute_settings,
80+
explicit_chunk_size=explicit_chunk_size,
7781
)
7882

7983
# for consistency, always return dataframe, whether or not logsums were requested
@@ -176,6 +180,7 @@ def run_tour_mode_choice_simulate(
176180
trace_column_names=trace_column_names,
177181
estimator=estimator,
178182
compute_settings=model_settings.compute_settings,
183+
explicit_chunk_size=model_settings.explicit_chunk,
179184
)
180185

181186
return choices
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from __future__ import annotations
2+
3+
from types import SimpleNamespace
4+
from unittest.mock import Mock
5+
6+
import pandas as pd
7+
import pandas.testing as pdt
8+
9+
from activitysim.abm.models import location_choice
10+
11+
12+
def test_estimation_override_preserves_destination_choice_logsum(monkeypatch):
13+
"""Survey overrides should only change the chosen destination's mode logsum."""
14+
person_index = pd.Index([1], name="person_id")
15+
location_sample = pd.DataFrame(
16+
{
17+
"alt_dest": [101, 202],
18+
location_choice.ALT_LOGSUM: [5.0, 7.0],
19+
},
20+
index=pd.Index([1, 1], name="person_id"),
21+
)
22+
modeled_choices = pd.DataFrame(
23+
{"choice": [101], "logsum": [-1.5]}, index=person_index
24+
)
25+
26+
# Keep the test focused on the estimation override and final logsum merge.
27+
monkeypatch.setattr(
28+
location_choice,
29+
"run_location_sample",
30+
lambda *args, **kwargs: location_sample.copy(),
31+
)
32+
monkeypatch.setattr(
33+
location_choice,
34+
"run_location_logsums",
35+
lambda *args, **kwargs: location_sample.copy(),
36+
)
37+
monkeypatch.setattr(
38+
location_choice,
39+
"run_location_simulate",
40+
lambda *args, **kwargs: modeled_choices.copy(),
41+
)
42+
43+
estimator = Mock()
44+
estimator.get_survey_values.return_value = pd.Series(
45+
[202], index=person_index, name="choice"
46+
)
47+
shadow_price_calculator = Mock()
48+
shadow_price_calculator.dest_size_terms.return_value = pd.Series(
49+
[1.0, 1.0], index=[101, 202]
50+
)
51+
model_settings = SimpleNamespace(
52+
ALT_DEST_COL_NAME="alt_dest",
53+
CHOOSER_SEGMENT_COLUMN_NAME="segment",
54+
DEST_CHOICE_COLUMN_NAME="workplace_zone_id",
55+
LOGSUM_SETTINGS="tour_mode_choice.yaml",
56+
SEGMENT_IDS={"workers": 1},
57+
)
58+
state = SimpleNamespace(
59+
settings=SimpleNamespace(
60+
sample_method="inverse_cdf",
61+
trace_hh_id=None,
62+
use_explicit_error_terms=False,
63+
)
64+
)
65+
persons = pd.DataFrame({"segment": [1]}, index=person_index)
66+
67+
choices, sample = location_choice.run_location_choice(
68+
state=state,
69+
persons_merged_df=persons,
70+
network_los=Mock(),
71+
shadow_price_calculator=shadow_price_calculator,
72+
want_logsums=True,
73+
want_sample_table=False,
74+
estimator=estimator,
75+
model_settings=model_settings,
76+
chunk_size=0,
77+
chunk_tag="workplace_location",
78+
trace_label="workplace_location",
79+
)
80+
81+
expected = pd.DataFrame(
82+
{
83+
"choice": [202],
84+
"logsum": [-1.5],
85+
location_choice.ALT_LOGSUM: [7.0],
86+
},
87+
index=person_index,
88+
)
89+
pdt.assert_frame_equal(choices, expected)
90+
assert sample is None

‎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/logit.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,14 @@ class TemplatedLogitComponentSettings(LogitComponentSettings, extra="forbid"):
200200
segment-specific names.
201201
"""
202202

203+
explicit_chunk: float = 0
204+
"""
205+
If > 0, use this fixed chunk size (number of chooser rows) instead of adaptive
206+
chunking. If less than 1, use this fraction of the total number of rows. Plumbed
207+
through mode_choice_simulate -> simple_simulate so mode-choice models can be chunked
208+
(default 0 = unchanged chunkless/adaptive behavior).
209+
"""
210+
203211

204212
class LocationComponentSettings(BaseLogitComponentSettings):
205213
"""

‎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

0 commit comments

Comments
 (0)