Skip to content

Commit e23bb12

Browse files
Copilotjpn--dhensle
authored
Make global constants available to interaction-based model expressions (#1095)
* Initial plan * Make global constants available in interaction utility expressions * Apply remaining changes * ✨ Refactor `test_interaction_sample_simulate.py` to include tests for global constants Refactor the test file to include a new test case that verifies global constants (`SAMPLE_SCALE` and `SIMULATE_SCALE`) are available in both destination-choice substeps. This ensures consistency across sampling and simulation operations, enhancing reliability and maintainability of the codebase. * adding global constants in sharrow and tests explicitly --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Jeff Newman <jeff@driftless.xyz> Co-authored-by: David Hensle <51132108+dhensle@users.noreply.github.com>
1 parent 131f09a commit e23bb12

10 files changed

Lines changed: 217 additions & 12 deletions

‎activitysim/abm/models/trip_destination.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def _destination_sample(
189189
f"SAMPLE_SIZE set to 0 for {trace_label} because disable_destination_sampling is set"
190190
)
191191

192-
locals_dict = state.get_global_constants().copy()
192+
locals_dict = {}
193193
locals_dict.update(model_settings.CONSTANTS)
194194

195195
# size_terms of destination zones are purpose-specific, and trips have various purposes

‎activitysim/core/expressions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,8 +321,8 @@ def annotate_tables(
321321
"Failed to set skim wrapper targets: %s. Skims wrappers may not be used in expressions.",
322322
e,
323323
)
324-
if locals_dict:
325-
locals_d.update(locals_dict)
324+
325+
locals_d.update(locals_dict or {})
326326

327327
results = compute_columns(
328328
state,

‎activitysim/core/flow.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -808,8 +808,10 @@ def apply_flow(
808808
"""
809809
if sh is None:
810810
return None, None
811-
if locals_d is None:
812-
locals_d = {}
811+
812+
# Global constants are always available, but can be overridden by locals_d.
813+
locals_d = {**state.get_global_constants(), **(locals_d or {})}
814+
813815
with logtime("apply_flow"):
814816
try:
815817
flow = get_flow(

‎activitysim/core/interaction_simulate.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def eval_interaction_utilities(
100100
assert len(spec.columns) == 1
101101

102102
# avoid altering caller's passed-in locals_d parameter (they may be looping)
103-
locals_d = locals_d.copy() if locals_d is not None else {}
103+
locals_d = dict(locals_d or {})
104104

105105
utilities = None
106106

@@ -210,6 +210,9 @@ def replace_in_index_level(mi, level, *repls):
210210
or estimator
211211
or (sharrow_enabled == "test" and extra_data is None)
212212
):
213+
# Global constants are always available, but can be overridden by locals_d.
214+
# Sharrow calculations receive them in flow.apply_flow instead.
215+
locals_d = {**state.get_global_constants(), **locals_d}
213216

214217
def to_series(x):
215218
if np.isscalar(x):

‎activitysim/core/simulate.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,6 @@ def eval_utilities(
655655
from .flow import apply_flow # import inside func to prevent circular imports
656656

657657
locals_dict = {}
658-
locals_dict.update(state.get_global_constants())
659658
if locals_d is not None:
660659
locals_dict.update(locals_d)
661660
sh_util, sh_flow, sh_tree = apply_flow(

‎activitysim/core/test/configs/preprocessor.csv‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ count persons test,num_persons,persons.groupby('household_id').size().reindex(df
55
skim dict test,od_distance,"skim_dict.lookup(df.origin, df.destination, 'DIST')"
66
skim wrapper test,od_distance_wrapper,skims2d['DIST']
77
sov time,od_sov_time,skims3d['SOV_TIME']
8-
testing constant from locals_dict,constant_test,test_constant / 2
8+
testing constant from locals_dict,constant_test,test_constant / 2
9+
testing global constant,global_constant_test,global_test_constant / 2

‎activitysim/core/test/test_interaction_sample_simulate.py‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pandas as pd
88
import pytest
99

10-
from activitysim.core import interaction_sample_simulate, workflow
10+
from activitysim.core import interaction_sample, interaction_sample_simulate, workflow
1111
from activitysim.core.logit import AltsContext
1212

1313

@@ -18,6 +18,64 @@ def state() -> workflow.State:
1818
return state
1919

2020

21+
def test_global_constants_available_in_sampling_and_simulation(tmp_path):
22+
"""Global constants are available in both destination-choice substeps."""
23+
configs_dir = tmp_path.joinpath("configs")
24+
configs_dir.mkdir()
25+
configs_dir.joinpath("constants.yaml").write_text(
26+
"SAMPLE_SCALE: 3.0\nSIMULATE_SCALE: 2.0\n"
27+
)
28+
tmp_path.joinpath("data").mkdir()
29+
30+
state = workflow.State()
31+
state.initialize_filesystem(
32+
working_dir=tmp_path, configs_dir=("configs",)
33+
).default_settings()
34+
state.settings.check_for_variability = False
35+
36+
choosers = pd.DataFrame(
37+
{"chooser_attr": [1.0, 2.0]},
38+
index=pd.Index([0, 1], name="person_id"),
39+
)
40+
alternatives = pd.DataFrame(
41+
{"alt_attr": [1.0, 2.0]},
42+
index=pd.Index([10, 20], name="alt_id"),
43+
)
44+
45+
# Sampling and simulation use separate specifications in location and
46+
# destination choice, so exercise each expression-evaluation path.
47+
sample_spec = pd.DataFrame(
48+
{"coefficient": [1.0]},
49+
index=pd.Index(["alt_attr * SAMPLE_SCALE"], name="Expression"),
50+
)
51+
sample = interaction_sample.interaction_sample(
52+
state,
53+
choosers,
54+
alternatives,
55+
sample_spec,
56+
sample_size=0,
57+
alt_col_name="alt_id",
58+
)
59+
sampled_alternatives = sample.join(alternatives, on="alt_id")
60+
61+
simulate_spec = pd.DataFrame(
62+
{"coefficient": [1.0]},
63+
index=pd.Index(["alt_attr * SIMULATE_SCALE"], name="Expression"),
64+
)
65+
results = interaction_sample_simulate.interaction_sample_simulate(
66+
state,
67+
choosers,
68+
sampled_alternatives,
69+
simulate_spec,
70+
choice_column="alt_id",
71+
want_logsums=True,
72+
skip_choice=True,
73+
)
74+
75+
expected_logsum = np.logaddexp(2.0, 4.0)
76+
np.testing.assert_allclose(results["logsums"], expected_logsum)
77+
78+
2179
def test_interaction_sample_simulate_parity(state):
2280
# Run interaction_sample_simulate with and without explicit error terms and check that results are similar.
2381

‎activitysim/core/test/test_interaction_simulate.py‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# ActivitySim
22
# See full license in LICENSE.txt.
33

4+
from __future__ import annotations
5+
46
import numpy as np
57
import pandas as pd
68
import pytest
79

8-
from activitysim.core import interaction_simulate, workflow
10+
from activitysim.core import flow, interaction_simulate, workflow
911

1012

1113
@pytest.fixture
@@ -15,6 +17,39 @@ def state() -> workflow.State:
1517
return state
1618

1719

20+
def test_apply_flow_global_constants_and_local_override(state, monkeypatch):
21+
class FakeFlow:
22+
name = "test_flow"
23+
compiled_recently = False
24+
tree = object()
25+
26+
def dot(self, coefficients, dtype, compile_watch):
27+
return np.array([[1.0]])
28+
29+
captured_locals = {}
30+
31+
def fake_get_flow(_state, _spec, locals_d, *_args, **_kwargs):
32+
captured_locals.update(locals_d)
33+
return FakeFlow()
34+
35+
state.get_global_constants = lambda: {"GLOBAL_SCALE": 2, "GLOBAL_ONLY": 4}
36+
monkeypatch.setattr(flow, "sh", object())
37+
monkeypatch.setattr(flow, "get_flow", fake_get_flow)
38+
39+
spec = pd.DataFrame(
40+
{"alt": [1.0]}, index=pd.Index(["GLOBAL_SCALE"], name="Expression")
41+
)
42+
result, _, _ = flow.apply_flow(
43+
state,
44+
spec,
45+
pd.DataFrame({"value": [1.0]}),
46+
locals_d={"GLOBAL_SCALE": 3},
47+
)
48+
49+
np.testing.assert_allclose(result, [[1.0]])
50+
assert captured_locals == {"GLOBAL_SCALE": 3, "GLOBAL_ONLY": 4}
51+
52+
1853
def test_interaction_simulate_explicit_error_terms_parity(state):
1954
# Run interaction_simulate with and without explicit error terms and check that results are similar.
2055

@@ -172,3 +207,73 @@ def test_interaction_simulate_eet_large_utilities(state):
172207
assert not choices_eet.isna().any()
173208
# With such a large difference, Alt 1 should be the dominant choice
174209
assert (choices_eet == 1).all()
210+
211+
212+
def test_eval_interaction_utilities_global_constants(tmp_path):
213+
# global constants (from constants.yaml) should be available to expressions
214+
# evaluated for interaction models (e.g. location choice, destination choice,
215+
# tour scheduling), see issue #1015
216+
217+
configs_dir = tmp_path.joinpath("configs")
218+
configs_dir.mkdir()
219+
configs_dir.joinpath("constants.yaml").write_text("KM_TO_MILE: 0.621371\n")
220+
tmp_path.joinpath("data").mkdir()
221+
222+
state = workflow.State()
223+
state.initialize_filesystem(
224+
working_dir=tmp_path, configs_dir=("configs",)
225+
).default_settings()
226+
state.settings.check_for_variability = False
227+
228+
df = pd.DataFrame({"distance_km": [1.0, 10.0]}, index=[0, 1])
229+
230+
spec = pd.DataFrame(
231+
{"coefficient": [1.0]},
232+
index=pd.Index(["distance_km * KM_TO_MILE"], name="Expression"),
233+
)
234+
235+
utilities, _ = interaction_simulate.eval_interaction_utilities(
236+
state,
237+
spec,
238+
df,
239+
locals_d=None,
240+
trace_label="test_global_constants",
241+
trace_rows=None,
242+
)
243+
244+
np.testing.assert_allclose(
245+
utilities.utility.to_numpy(), df.distance_km.to_numpy() * 0.621371
246+
)
247+
248+
249+
def test_eval_interaction_utilities_locals_override_global_constants(tmp_path):
250+
# values passed in locals_d take precedence over global constants
251+
252+
configs_dir = tmp_path.joinpath("configs")
253+
configs_dir.mkdir()
254+
configs_dir.joinpath("constants.yaml").write_text("KM_TO_MILE: 0.621371\n")
255+
tmp_path.joinpath("data").mkdir()
256+
257+
state = workflow.State()
258+
state.initialize_filesystem(
259+
working_dir=tmp_path, configs_dir=("configs",)
260+
).default_settings()
261+
state.settings.check_for_variability = False
262+
263+
df = pd.DataFrame({"distance_km": [1.0, 10.0]}, index=[0, 1])
264+
265+
spec = pd.DataFrame(
266+
{"coefficient": [1.0]},
267+
index=pd.Index(["distance_km * KM_TO_MILE"], name="Expression"),
268+
)
269+
270+
utilities, _ = interaction_simulate.eval_interaction_utilities(
271+
state,
272+
spec,
273+
df,
274+
locals_d={"KM_TO_MILE": 1.0},
275+
trace_label="test_global_constants_override",
276+
trace_rows=None,
277+
)
278+
279+
np.testing.assert_allclose(utilities.utility.to_numpy(), df.distance_km.to_numpy())

‎activitysim/core/test/test_preprocessing.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ def check_outputs(tours):
8787
"od_distance_wrapper",
8888
"od_sov_time",
8989
"constant_test",
90+
"global_constant_test",
9091
]
9192

9293
# check all new columns are added
@@ -109,6 +110,7 @@ def check_outputs(tours):
109110
"od_distance_wrapper": [0.24, 0.28, 0.57],
110111
"od_sov_time": [0.78, 0.89, 1.76],
111112
"constant_test": [21, 21, 21],
113+
"global_constant_test": [21, 21, 21],
112114
}
113115
).set_index("tour_id")
114116
pd.testing.assert_frame_equal(tours[new_cols], exppected_output, check_dtype=False)
@@ -124,7 +126,11 @@ def setup_skims(state: workflow.State):
124126
return {"skims3d": skims3d, "skims2d": skims2d}
125127

126128

127-
def test_preprocessor(state: workflow.State, households, persons, tours):
129+
def test_preprocessor(state: workflow.State, households, persons, tours, monkeypatch):
130+
monkeypatch.setattr(
131+
state, "get_global_constants", lambda: {"global_test_constant": 42}
132+
)
133+
128134
# adding dataframes to state so they can be accessed in preprocessor
129135
state.add_table("households", households)
130136
state.add_table("persons", persons)
@@ -156,7 +162,11 @@ def test_preprocessor(state: workflow.State, households, persons, tours):
156162
pd.testing.assert_frame_equal(state_tours, original_tours)
157163

158164

159-
def test_annotator(state, households, persons, tours):
165+
def test_annotator(state, households, persons, tours, monkeypatch):
166+
monkeypatch.setattr(
167+
state, "get_global_constants", lambda: {"global_test_constant": 42}
168+
)
169+
160170
# adding dataframes to state so they can be accessed in annotator
161171
state.add_table("households", households)
162172
state.add_table("persons", persons)

‎activitysim/core/test/test_simulate.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,33 @@ def test_eval_variables(state, spec, data):
8282
pdt.assert_frame_equal(result, expected, check_names=False)
8383

8484

85+
def test_standard_utilities_global_constants_and_local_override(state):
86+
state.get_global_constants = lambda: {"GLOBAL_SCALE": 2}
87+
choosers = pd.DataFrame({"value": [1.0, 2.0]})
88+
spec = pd.DataFrame(
89+
{"alt": [1.0]},
90+
index=pd.Index(["@df.value * GLOBAL_SCALE"], name="Expression"),
91+
)
92+
chunk_sizer = chunk.ChunkSizer(state, "", "", len(choosers))
93+
94+
utilities = simulate.eval_utilities(
95+
state,
96+
spec,
97+
choosers,
98+
chunk_sizer=chunk_sizer,
99+
)
100+
overridden_utilities = simulate.eval_utilities(
101+
state,
102+
spec,
103+
choosers,
104+
locals_d={"GLOBAL_SCALE": 3},
105+
chunk_sizer=chunk_sizer,
106+
)
107+
108+
npt.assert_allclose(utilities["alt"], [2.0, 4.0])
109+
npt.assert_allclose(overridden_utilities["alt"], [3.0, 6.0])
110+
111+
85112
def test_simple_simulate(state, data, spec):
86113
state.settings.check_for_variability = False
87114

0 commit comments

Comments
 (0)