Skip to content

Commit a669e59

Browse files
committed
model: Automatically increase time and step count
This pull request adds automatically increasing of time and step counters in the Mesa model, even if the users overwrites the Model.step() method.
1 parent de01c3f commit a669e59

File tree

3 files changed

+15
-13
lines changed

3 files changed

+15
-13
lines changed

mesa/model.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,20 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
8383
self._steps: int = 0
8484
self._time: TimeT = 0 # the model's clock
8585

86+
# Wrap the user-defined step method
87+
if hasattr(self, "step"):
88+
self._user_step = self.step
89+
self.step = self._wrapped_step
90+
91+
def _wrapped_step(self, *args: Any, **kwargs: Any) -> None:
92+
"""Automatically increments time and steps after calling the user's step method."""
93+
# Automatically increment time and step counters
94+
self._time += kwargs.get("time", 1)
95+
self._steps += kwargs.get("step", 1)
96+
# Call the original user-defined step method
97+
if self._user_step:
98+
self._user_step(*args, **kwargs)
99+
86100
@property
87101
def agents(self) -> AgentSet:
88102
"""Provides an AgentSet of all agents in the model, combining agents from all types."""
@@ -180,11 +194,6 @@ def run_model(self) -> None:
180194
def step(self) -> None:
181195
"""A single step. Fill in here."""
182196

183-
def _advance_time(self, deltat: TimeT = 1):
184-
"""Increment the model's steps counter and clock."""
185-
self._steps += 1
186-
self._time += deltat
187-
188197
def next_id(self) -> int:
189198
"""Return the next unique ID for agents, increment current_id"""
190199
self.current_id += 1

mesa/time.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ def __init__(self, model: Model, agents: Iterable[Agent] | None = None) -> None:
6969
self.model = model
7070
self.steps = 0
7171
self.time: TimeT = 0
72-
self._original_step = self.step
73-
self.step = self._wrapped_step
7472

7573
if agents is None:
7674
agents = []
@@ -113,11 +111,6 @@ def step(self) -> None:
113111
self.steps += 1
114112
self.time += 1
115113

116-
def _wrapped_step(self):
117-
"""Wrapper for the step method to include time and step updating."""
118-
self._original_step()
119-
self.model._advance_time()
120-
121114
def get_agent_count(self) -> int:
122115
"""Returns the current number of agents in the queue."""
123116
return len(self._agents)

tests/test_batch_run.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ def get_local_model_param(self):
8383
return 42
8484

8585
def step(self):
86-
self.datacollector.collect(self)
8786
self.schedule.step()
87+
self.datacollector.collect(self)
8888

8989

9090
def test_batch_run():

0 commit comments

Comments
 (0)