Skip to content

Commit 5c6fae2

Browse files
authored
Fix park-and-ride skim validation with Sharrow (#1113)
1 parent ede8ef0 commit 5c6fae2

4 files changed

Lines changed: 175 additions & 7 deletions

File tree

‎activitysim/abm/models/park_and_ride_lot_choice.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1+
from __future__ import annotations
2+
13
# ActivitySim
24
# See full license in LICENSE.txt.
35
import logging
6+
from typing import Literal
47

58
import numpy as np
69
import pandas as pd
7-
from typing import Literal
810

11+
from activitysim.abm.models.util import logsums
12+
from activitysim.abm.models.util.park_and_ride_capacity import ParkAndRideCapacity
913
from activitysim.core import (
1014
config,
15+
estimation,
1116
expressions,
1217
los,
13-
estimation,
1418
simulate,
1519
tracing,
1620
util,
@@ -21,8 +25,6 @@
2125
PreprocessorSettings,
2226
)
2327
from activitysim.core.interaction_simulate import interaction_simulate
24-
from activitysim.abm.models.util import logsums
25-
from activitysim.abm.models.util.park_and_ride_capacity import ParkAndRideCapacity
2628

2729
logger = logging.getLogger(__name__)
2830

@@ -33,7 +35,7 @@ class ParkAndRideLotChoiceSettings(LogitComponentSettings, extra="forbid"):
3335
"""
3436

3537
CHOOSER_FILTER_EXPR: str | None = None
36-
"""An optional expression to filter the chooser table before simulating the model.
38+
"""An optional expression to filter the chooser table before simulating the model.
3739
Applied after preprocessing as a .query() expression."""
3840

3941
LANDUSE_PNR_SPACES_COLUMN: str
@@ -121,10 +123,10 @@ def filter_chooser_to_transit_accessible_destinations(
121123
# If the skim name contains '__', it is a 3D skim
122124
# we need to pass the skim name as a tuple to the lookup method, e.g. ('WALK_TRANSIT_IVTT', 'MD')
123125
skim_name = tuple(skim_name.split("__"))
124-
if skim_name not in skim_dict.skim_info.omx_keys.keys():
126+
if skim_name not in skim_dict:
125127
raise ValueError(
126128
f"Skim '{skim_name}' not found in the skim dictionary."
127-
"Please update the model setting TRANSIT_SKIMS_FOR_ELIGIBILITY with valid skim names."
129+
" Please update the model setting TRANSIT_SKIMS_FOR_ELIGIBILITY with valid skim names."
128130
)
129131
# Filter choosers to only those with destinations that have transit access
130132
# want to check whether ANY of the lot locations have transit access to EVERY destination
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
"""Exercise park-and-ride eligibility with both concrete skim backends."""
2+
3+
from __future__ import annotations
4+
5+
from types import SimpleNamespace
6+
7+
import numpy as np
8+
import pandas as pd
9+
import pytest
10+
import xarray as xr
11+
12+
from activitysim.abm.models.park_and_ride_lot_choice import (
13+
ParkAndRideLotChoiceSettings,
14+
filter_chooser_to_transit_accessible_destinations,
15+
)
16+
from activitysim.core import workflow
17+
from activitysim.core.skim_dataset import SkimDataset
18+
from activitysim.core.skim_dictionary import SkimDict
19+
20+
21+
@pytest.fixture(params=["numpy", "sharrow"])
22+
def eligibility_skims(request):
23+
"""Use identical zero-based zones and accessibility in both backends."""
24+
walk = np.zeros((5, 5), dtype=np.float32)
25+
transit = np.zeros((5, 5, 2), dtype=np.float32)
26+
walk[0, 2] = 10
27+
# Missing and negative skim values must not count as transit access.
28+
walk[0, 3] = np.nan
29+
walk[1, 4] = -1
30+
transit[1, 3, 0] = 20
31+
transit[0, 4, 1] = 30
32+
33+
if request.param == "sharrow":
34+
return SkimDataset(
35+
xr.Dataset(
36+
{
37+
"WALK": (("otaz", "dtaz"), walk),
38+
"TRANSIT": (("otaz", "dtaz", "time_period"), transit),
39+
},
40+
coords={"time_period": ["AM", "PM"]},
41+
)
42+
)
43+
44+
skim_info = SimpleNamespace(
45+
offset_map=None,
46+
omx_shape=(5, 5),
47+
dtype_name="float32",
48+
block_offsets={"WALK": 0, ("TRANSIT", "AM"): 1, ("TRANSIT", "PM"): 2},
49+
)
50+
skims = SkimDict(
51+
workflow.State().default_settings(),
52+
"taz",
53+
skim_info,
54+
np.stack([walk, transit[:, :, 0], transit[:, :, 1]]),
55+
)
56+
skims.offset_mapper.set_offset_int(0)
57+
return skims
58+
59+
60+
@pytest.mark.parametrize(
61+
"key, expected",
62+
[
63+
("WALK", True),
64+
(("TRANSIT", "AM"), True),
65+
(("TRANSIT", "PM"), True),
66+
("MISSING", False),
67+
(("MISSING", "AM"), False),
68+
(("TRANSIT", "MD"), False),
69+
("TRANSIT", False),
70+
(("WALK", "AM"), False),
71+
(("TRANSIT", "AM", "extra"), False),
72+
("time_period", False),
73+
],
74+
)
75+
def test_skim_membership(eligibility_skims, key, expected):
76+
"""Validation agrees across backends without reading or recording skim usage."""
77+
assert (key in eligibility_skims) is expected
78+
assert eligibility_skims.get_skim_usage() == set()
79+
80+
81+
def _filter_choosers(skims, skim_names, destinations=None):
82+
"""Filter repeated, unordered destinations from two possible lot locations."""
83+
choosers = pd.DataFrame(
84+
{"destination": [4, 2, 3, 2, 0] if destinations is None else destinations},
85+
index=pd.Index([100, 101, 102, 103, 104], name="tour_id"),
86+
)
87+
lots = pd.DataFrame(index=pd.Index([0, 1], name="zone_id"))
88+
settings = ParkAndRideLotChoiceSettings(
89+
SPEC="unused.csv",
90+
LANDUSE_PNR_SPACES_COLUMN="pnr_spaces",
91+
TRANSIT_SKIMS_FOR_ELIGIBILITY=skim_names,
92+
)
93+
return filter_chooser_to_transit_accessible_destinations(
94+
state=None,
95+
choosers=choosers,
96+
land_use=lots,
97+
pnr_alts=lots,
98+
network_los=SimpleNamespace(get_default_skim_dict=lambda: skims),
99+
model_settings=settings,
100+
choosers_dest_col_name="destination",
101+
)
102+
103+
104+
@pytest.mark.parametrize(
105+
"skim_names, expected_ids",
106+
[
107+
(["WALK"], [101, 103]),
108+
(["TRANSIT__AM"], [102]),
109+
(["TRANSIT__PM"], [100]),
110+
(["WALK", "TRANSIT__AM"], [101, 102, 103]),
111+
(["TRANSIT__AM", "TRANSIT__PM"], [100, 102]),
112+
],
113+
)
114+
def test_filter_skim_backends(eligibility_skims, skim_names, expected_ids):
115+
"""Accept access from any lot or configured skim, preserving chooser order."""
116+
result = _filter_choosers(eligibility_skims, skim_names)
117+
expected = pd.DataFrame(
118+
{"destination": [4, 2, 3, 2, 0]},
119+
index=pd.Index([100, 101, 102, 103, 104], name="tour_id"),
120+
).loc[expected_ids]
121+
pd.testing.assert_frame_equal(result, expected)
122+
123+
124+
def test_no_accessible_destinations(eligibility_skims):
125+
"""An available skim with no positive lot-to-destination values rejects all tours."""
126+
result = _filter_choosers(eligibility_skims, ["WALK"], [0, 1, 3, 4, 0])
127+
expected = pd.DataFrame(
128+
{"destination": pd.Series(dtype="int64")},
129+
index=pd.Index([], dtype="int64", name="tour_id"),
130+
)
131+
pd.testing.assert_frame_equal(result, expected)
132+
133+
134+
def test_invalid_skim_after_valid_skim(eligibility_skims):
135+
"""An earlier accessible skim must not bypass validation of later settings."""
136+
with pytest.raises(ValueError, match="Skim 'MISSING' not found"):
137+
_filter_choosers(eligibility_skims, ["WALK", "MISSING"])
138+
139+
140+
@pytest.mark.parametrize(
141+
"skim_name", ["MISSING", "MISSING__AM", "TRANSIT__MD", "TRANSIT", "WALK__AM"]
142+
)
143+
def test_invalid_eligibility_skim(eligibility_skims, skim_name):
144+
"""Missing cores and invalid time periods retain an actionable settings error."""
145+
with pytest.raises(ValueError, match="TRANSIT_SKIMS_FOR_ELIGIBILITY"):
146+
_filter_choosers(eligibility_skims, [skim_name])

‎activitysim/core/skim_dataset.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ def __init__(self, dataset):
4141
)
4242
self.usage = set() # track keys of skims looked up
4343

44+
def __contains__(self, key):
45+
"""Return whether a 2D skim or a specific time-period skim is available."""
46+
if isinstance(key, tuple):
47+
if len(key) != 2:
48+
return False
49+
name, period = key
50+
return (
51+
name in self.dataset.data_vars
52+
and "time_period" in self.dataset[name].dims
53+
and period in self.time_map
54+
)
55+
return (
56+
key in self.dataset.data_vars
57+
and "time_period" not in self.dataset[key].dims
58+
)
59+
4460
@property
4561
def odim(self):
4662
if "omaz" in self.dataset.dims:

‎activitysim/core/skim_dictionary.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,10 @@ def __init__(self, state, skim_tag, skim_info, skim_data):
242242
f"SkimDict.build_3d_skim_block_offset_table registered {len(self.skim_dim3)} 3d keys"
243243
)
244244

245+
def __contains__(self, key):
246+
"""Return whether a 2D skim or a specific time-period skim is available."""
247+
return key in self.skim_info.block_offsets
248+
245249
def _offset_mapper(self, state):
246250
"""
247251
Return an OffsetMapper to set self.offset_mapper for use with skims

0 commit comments

Comments
 (0)