Skip to content

Commit 46c9a91

Browse files
Implement deletion of temporary variables in summarize.py (reviewed) (#1116)
* Implement deletion of temporary variables in summarize.py Add functionality to delete temporary variables starting with '_del' from locals_d. * addressing copilot review and adding CI testing * updating documentation for _del feature --------- Co-authored-by: ziocolaandrea <118041510+ziocolaandrea@users.noreply.github.com>
1 parent 8ca6741 commit 46c9a91

4 files changed

Lines changed: 34 additions & 5 deletions

File tree

‎activitysim/abm/models/summarize.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,14 @@ def summarize(
364364
out_file = row["Output"]
365365
expr = row["Expression"]
366366

367+
# delete temporary variables listed in Expression when Output == "_del"
368+
if out_file == "_del":
369+
logger.debug(f"Deleting temporary variable(s): {expr}")
370+
with performance_timer.time_expression(expr):
371+
for var in str(expr).split(","):
372+
locals_d.pop(var.strip(), None)
373+
continue
374+
367375
# Save temporary variables starting with underscores in locals_d
368376
if out_file.startswith("_"):
369377
logger.debug(f"Temp Variable: {expr} -> {out_file}")

‎docs/users-guide/visualization.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ Rows with output values that begin with an alphanumeric character will be saved
3636

3737
Rows with output values that begin with underscores (e.g., ``_output_name``) will be stored as temporary variables in the local namespace so they can be used in following expressions. Expressions defining temporary variables can produce any data type. Users are encouraged to follow the ActivitySim convention using capitals to denote constants (e.g., ``_TEMP_CONSTANT``), though this convention is not formally enforced for summarize expressions.
3838

39+
Temporary variables that are no longer needed can be removed from the local
40+
namespace, allowing their memory to be reclaimed when no other references
41+
remain. Set the ``Output`` column to the reserved value ``_del`` and list one or more
42+
comma-separated temporary variable names in ``Expression``. Missing names are
43+
ignored, and the row does not create an output file. For example::
44+
45+
Description,Output,Expression
46+
Delete intermediate tables,_del,"_trips_with_income, _work_tours"
47+
3948
Summarize expressions can make use of several convenience functions for binning numeric Pandas Series' into quantiles, equal intervals, or manually-specified ranges. These functions are available in the local namespace used to evaluate summarize expressions (as well as for preprocessing the ``trips_merged`` table; see below), so they can be used directly in summary expressions. These functions include:
4049

4150
* ``quantiles``: Construct quantiles from a Series given a number of bins.

‎test/summarize/configs/summarize.csv‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,8 @@ Description,Output,Expression
107107
# TAZ population density quintiles
108108
,_taz_pop_dens,land_use.TOTPOP/land_use.TOTACRE
109109
,taz_population_density_quintiles,"quantiles(_taz_pop_dens, 5, '{rank}').rename('pop_dens_quintile').reset_index()"
110+
111+
# Delete a temporary dataframe (to save memory) and verify it is unavailable to later expressions
112+
,_temporary_dataframe,trips_merged[['number_of_participants']]
113+
,_del,_temporary_dataframe
114+
,temporary_dataframe_deleted,"pd.Series(['_temporary_dataframe' not in locals()], name='deleted')"

‎test/summarize/test_summarize.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest
99

1010
# import models is necessary to initalize the model steps
11-
from activitysim.abm import models
11+
from activitysim.abm import models # noqa: F401
1212
from activitysim.core import los, workflow
1313

1414

@@ -18,12 +18,13 @@ def initialize_pipeline(
1818
tables: dict[str, str],
1919
initialize_network_los: bool,
2020
base_dir: Path,
21+
tmp_path_factory: pytest.TempPathFactory,
2122
) -> workflow.State:
2223
if base_dir is None:
2324
base_dir = Path("test").joinpath(module)
2425
configs_dir = base_dir.joinpath("configs")
2526
data_dir = base_dir.joinpath("data")
26-
output_dir = base_dir.joinpath("output")
27+
output_dir = tmp_path_factory.mktemp("summarize-output")
2728

2829
state = (
2930
workflow.State()
@@ -50,7 +51,7 @@ def initialize_pipeline(
5051

5152
# Add the dataframes to the pipeline
5253
state.checkpoint.restore()
53-
state.checkpoint.add(module)
54+
state.checkpoint.add("init")
5455
state.checkpoint.close_store()
5556

5657
# By convention, this method needs to yield something
@@ -122,8 +123,6 @@ def test_summarize(initialize_pipeline: workflow.State, caplog):
122123
output_location = (
123124
model_settings["OUTPUT"] if "OUTPUT" in model_settings else "summaries"
124125
)
125-
output_dir = state.get_output_file_path(output_location)
126-
127126
# Check that households are counted correctly
128127
households_count = pd.read_csv(
129128
state.get_output_file_path(
@@ -143,3 +142,11 @@ def test_summarize(initialize_pipeline: workflow.State, caplog):
143142
assert int(trips_by_mode_count.BIKE.iloc[0]) == len(
144143
trips[trips.trip_mode == "BIKE"]
145144
)
145+
146+
# Check that _del removes temporary dataframes from the expression namespace
147+
temporary_dataframe_deleted = pd.read_csv(
148+
state.get_output_file_path(
149+
os.path.join(output_location, "temporary_dataframe_deleted.csv")
150+
)
151+
)
152+
assert temporary_dataframe_deleted["deleted"].tolist() == [True]

0 commit comments

Comments
 (0)