Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 41 additions & 12 deletions activitysim/abm/models/disaggregate_accessibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,11 +774,18 @@ def get_disaggregate_logsums(
state, "disaggregate_accessibility.yaml"
)

for model_name in [
location_models = [
"workplace_location",
"school_location",
"non_mandatory_tour_destination",
]:
]

tour_models = {
"non_mandatory_tour_destination": "non_mandatory",
"joint_tour_destination": "joint",
"atwork_subtour_destination": "atwork",
}

for model_name in [*location_models, *tour_models]:
trace_label = tracing.extend_trace_label(model_name, "accessibilities")
print(f"Running model {trace_label}")

Expand Down Expand Up @@ -814,14 +821,20 @@ def get_disaggregate_logsums(
suffixes.insert(0, str(model_settings.LOGSUM_SETTINGS))
model_settings.LOGSUM_SETTINGS = " ".join(suffixes)

if model_name != "non_mandatory_tour_destination":
if model_name in location_models:
spc = shadow_pricing.load_shadow_price_calculator(state, model_settings)
# explicitly turning off shadow pricing for disaggregate accessibilities
spc.use_shadow_pricing = False
# filter to only workers or students
chooser_filter_column = model_settings.CHOOSER_FILTER_COLUMN_NAME
choosers = persons_merged[persons_merged[chooser_filter_column]]

if choosers.empty:
logger.info(
f"{model_name} skipped: no eligible proto persons (filter column {chooser_filter_column})"
)
continue

# run location choice and return logsums
_logsums, _ = location_choice.run_location_choice(
state,
Expand All @@ -847,7 +860,18 @@ def get_disaggregate_logsums(

else:
tours = state.get_dataframe("proto_tours")
tours = tours[tours.tour_category == "non_mandatory"]
tours = tours[tours.tour_category == tour_models[model_name]]

if tours.empty:
logger.info(
f"{model_name} skipped: no eligible proto tours (tour_category {tour_models[model_name]})"
)
continue

if model_name == "atwork_subtour_destination":
# set the workplace location as the home zone for the atwork subtour destination choice model
# this means that the output atwork subtour destination logsums should be merged on the workplace_zone_id
persons_merged["workplace_zone_id"] = persons_merged["home_zone_id"]

_logsums, _ = tour_destination.run_tour_destination(
state,
Expand Down Expand Up @@ -923,19 +947,24 @@ def compute_disaggregate_accessibility(
)
logsums = {k + "_accessibility": v for k, v in logsums.items()}

# Combined accessibility table
# Setup dict for fixed location accessibilities
# Combine person-level location and tour-destination accessibility results.
# Tour results are pivoted by purpose so that multiple tour categories or
# purposes for the same person do not duplicate rows in the final table.
access_list = []
for k, df in logsums.items():
if "non_mandatory_tour_destination" in k:
# cast non-mandatory purposes to wide
df = pd.pivot(
df,
if "tour_destination" in k:
model_name = k.removesuffix("_accessibility")
column_prefix = {
"non_mandatory_tour_destination": "",
"joint_tour_destination": "joint_",
"atwork_subtour_destination": "atwork_",
}[model_name]
df = df.pivot_table(
index=["proto_household_id", "proto_person_id"],
columns="tour_type",
values="logsums",
)
df.columns = ["_".join([str(x), "accessibility"]) for x in df.columns]
df.columns = [f"{column_prefix}{purpose}_accessibility" for purpose in df]
access_list.append(df)
else:
access_list.append(
Expand Down
181 changes: 181 additions & 0 deletions activitysim/abm/test/test_disaggregate_accessibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
from types import SimpleNamespace

import pandas as pd
import yaml
from pandas.testing import assert_frame_equal, assert_series_equal

from activitysim.abm.models import disaggregate_accessibility as accessibility
from activitysim.core import workflow


def test_proto_accessibility_by_tour_category_and_auto_ownership(tmp_path, monkeypatch):
"""Verify how the model builds the proto accessibility table.

The test checks which people reach workplace and school location choice and
which tours reach each destination-choice model. It also checks that at-work
subtours use the proto home zone as their origin and that the stored
workplace zones are preserved.

The choice-model stand-ins return fixed logsums by auto ownership. The test
checks that the output has one row per proto person and that each logsum
appears in the expected column for zero- and one-auto households.

The test starts with prepared proto tables and ends at the published proto
accessibility table. Population generation, destination sampling, utility,
logsum, and shadow-price calculations, and matching to synthetic households
are outside its scope. The fixture uses one person per household, leaving
assignment among members of a shared household outside the test.
"""
configs = tmp_path / "configs"
configs.mkdir()
(tmp_path / "data").mkdir()
(configs / "disaggregate_accessibility.yaml").write_text(
"ORIGIN_WEIGHTING_COLUMN: population\nMERGE_ON:\n by: [auto_ownership]\n",
encoding="utf-8",
)
# Use real settings loading with only the fields the step and stand-ins need.
for model_name, origin_column, chooser_filter in [
("workplace_location", "home_zone_id", "is_worker"),
("school_location", "home_zone_id", "is_student"),
("non_mandatory_tour_destination", "home_zone_id", None),
("joint_tour_destination", "home_zone_id", None),
("atwork_subtour_destination", "workplace_zone_id", None),
]:
(configs / f"{model_name}.yaml").write_text(
yaml.safe_dump(
{
"SPEC": f"{model_name}.csv",
"SAMPLE_SPEC": "sample.csv",
"SAMPLE_SIZE": 0,
"CHOOSER_FILTER_COLUMN_NAME": chooser_filter,
"CHOOSER_ORIG_COL_NAME": origin_column,
"ALT_DEST_COL_NAME": "destination",
}
),
encoding="utf-8",
)
state = workflow.State().default_settings()
state.initialize_filesystem(working_dir=tmp_path, configs_dir=("configs",))

# Pair workers and students across ownership levels while holding home zone fixed.
households = pd.DataFrame(
{"home_zone_id": [10, 10, 10, 10], "auto_ownership": [0, 1, 0, 1]},
index=pd.Index([1, 2, 3, 4], name="proto_household_id"),
)
persons = pd.DataFrame(
{
"proto_household_id": [1, 2, 3, 4],
"is_worker": [True, True, False, False],
"is_student": [False, False, True, True],
"workplace_zone_id": [90, 90, -1, -1],
},
index=pd.Index([101, 102, 201, 202], name="proto_person_id"),
)
# Work and school rows catch accidental dispatch to tour destination choice.
# Shopping appears in two categories to check that both columns survive.
tours = pd.DataFrame(
[
(1, 101, "mandatory", "work"),
(2, 102, "mandatory", "work"),
(3, 201, "mandatory", "school"),
(4, 202, "mandatory", "school"),
(5, 101, "non_mandatory", "shopping"),
(6, 102, "non_mandatory", "shopping"),
(7, 201, "non_mandatory", "shopping"),
(8, 202, "non_mandatory", "shopping"),
(9, 101, "joint", "shopping"),
(10, 102, "joint", "shopping"),
(11, 101, "atwork", "eat"),
(12, 102, "atwork", "eat"),
],
columns=["proto_tour_id", "proto_person_id", "tour_category", "tour_type"],
).set_index("proto_tour_id")
tours["proto_household_id"] = tours["proto_person_id"].map(
persons["proto_household_id"]
)
state.add_table("proto_households", households)
state.add_table("proto_persons", persons)
state.add_table("proto_tours", tours)
state.add_table(
"proto_persons_merged", persons.join(households, on="proto_household_id")
)

monkeypatch.setattr(
accessibility.shadow_pricing,
"load_shadow_price_calculator",
lambda *_: SimpleNamespace(use_shadow_pricing=True),
)

# Stand-ins look up values from chooser auto ownership to expose a lost or
# misassigned segment during routing or assembly.
logsums_by_auto_ownership = {
"workplace_location": {0: 20.0, 1: 21.0},
"school_location": {0: 30.0, 1: 31.0},
"non_mandatory_tour_destination": {0: 2.0, 1: 3.0},
"joint_tour_destination": {0: 7.0, 1: 8.0},
"atwork_subtour_destination": {0: 11.0, 1: 12.0},
}
location_calls = []
tour_calls = []

def fixed_location_logsums(_state, choosers, _network_los, **kwargs):
assert kwargs["want_logsums"] and kwargs["skip_choice"]
assert not kwargs["shadow_price_calculator"].use_shadow_pricing
model_name = kwargs["model_settings"].SPEC.stem
location_calls.append((model_name, choosers.index.tolist()))
logsums = choosers["auto_ownership"].map(logsums_by_auto_ownership[model_name])
return logsums.to_frame("logsums"), None

def tour_destination_logsums(_state, model_tours, choosers, **kwargs):
assert kwargs["want_logsums"] and kwargs["skip_choice"]
model_settings = kwargs["model_settings"]
model_name = model_settings.SPEC.stem
tour_calls.append((model_name, model_tours.index.tolist()))
person_ids = model_tours[model_settings.CHOOSER_ID_COLUMN]
if model_name == "atwork_subtour_destination":
# The at-work runner should see the proto home zone as the work origin.
assert person_ids.map(choosers["workplace_zone_id"]).tolist() == [10, 10]
auto_ownership = person_ids.map(choosers["auto_ownership"])
logsums = auto_ownership.map(logsums_by_auto_ownership[model_name])
return logsums.to_frame("logsums"), None

monkeypatch.setattr(
accessibility.location_choice, "run_location_choice", fixed_location_logsums
)
monkeypatch.setattr(
accessibility.tour_destination, "run_tour_destination", tour_destination_logsums
)

accessibility.compute_disaggregate_accessibility(state, network_los=None)

# Mandatory accessibility comes from eligible people through location choice.
assert sorted(location_calls) == [
("school_location", [201, 202]),
("workplace_location", [101, 102]),
]
assert sorted(tour_calls) == [
("atwork_subtour_destination", [11, 12]),
("joint_tour_destination", [9, 10]),
("non_mandatory_tour_destination", [5, 6, 7, 8]),
]
# The temporary origin should leave the stored workplace zones intact.
assert_series_equal(
state.get_dataframe("proto_persons_merged")["workplace_zone_id"],
persons["workplace_zone_id"],
)

# The expected index also checks for dropped or duplicated proto persons.
# Missing values represent chooser roles and tour categories absent for a person.
expected = pd.DataFrame(
{
"auto_ownership": [0, 1, 0, 1],
"workplace_location_accessibility": [20.0, 21.0, None, None],
"school_location_accessibility": [None, None, 30.0, 31.0],
"shopping_accessibility": [2.0, 3.0, 2.0, 3.0],
"joint_shopping_accessibility": [7.0, 8.0, None, None],
"atwork_eat_accessibility": [11.0, 12.0, None, None],
},
index=pd.Index([101, 102, 201, 202], name="proto_person_id"),
)
actual = state.get_dataframe("proto_disaggregate_accessibility")
assert_frame_equal(actual[expected.columns].sort_index(), expected)
Loading