Skip to content

Commit

Permalink
GoL_fast: Add metrics, datacollector and measure viz
Browse files Browse the repository at this point in the history
- Add two metrics to the model
- Collect those with the datacollector
- Plot them as measures in SolaraViz
  • Loading branch information
EwoutH committed Aug 29, 2024
1 parent 1a50528 commit 6cfd08d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions examples/conways_game_of_life_fast/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
page = SolaraViz(
GameOfLifeModel,
model_params,
measures=["Cells alive", "Fraction alive"],
space_drawer=None,
name="Game of Life Model",
)
Expand Down
17 changes: 16 additions & 1 deletion examples/conways_game_of_life_fast/model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numpy as np
from mesa import Model
from mesa import Model, DataCollector
from mesa.space import PropertyLayer
from scipy.signal import convolve2d

Expand All @@ -12,6 +12,16 @@ def __init__(self, width, height, alive_fraction=0.2):
# Randomly set cells to alive
self.cell_layer.data = np.random.choice([True, False], size=(width, height), p=[alive_fraction, 1 - alive_fraction])

# Metrics and datacollector
self.cells = width * height
self.alive_count = 0
self.alive_fraction = 0
self.datacollector = DataCollector(
model_reporters={"Cells alive": "alive_count",
"Fraction alive": "alive_fraction"}
)
self.datacollector.collect(self)

def step(self):
self._advance_time()
# Define a kernel for counting neighbors. The kernel has 1s around the center cell (which is 0).
Expand All @@ -34,3 +44,8 @@ def step(self):
# Rule for live cells
np.logical_and(~self.cell_layer.data, neighbor_count == 3) # Rule for dead cells
)

# Metrics
self.alive_count = np.sum(self.cell_layer.data)
self.alive_fraction = self.alive_count / self.cells
self.datacollector.collect(self)

0 comments on commit 6cfd08d

Please sign in to comment.