Skip to content

Commit aee22c1

Browse files
committed
GoL_fast: Add metrics, datacollector and measure viz
- Add two metrics to the model - Collect those with the datacollector - Plot them as measures in SolaraViz
1 parent 541b004 commit aee22c1

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

examples/conways_game_of_life_fast/app.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
page = SolaraViz(
2424
GameOfLifeModel,
2525
model_params,
26+
measures=["Cells alive", "Fraction alive"],
2627
space_drawer=None,
2728
name="Game of Life Model",
2829
)

examples/conways_game_of_life_fast/model.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import numpy as np
2-
from mesa import Model
2+
from mesa import DataCollector, Model
33
from mesa.space import PropertyLayer
44
from scipy.signal import convolve2d
55

6+
67
# fmt: off
78
class GameOfLifeModel(Model):
89
def __init__(self, width=10, height=10, alive_fraction=0.2):
@@ -12,6 +13,16 @@ def __init__(self, width=10, height=10, alive_fraction=0.2):
1213
# Randomly set cells to alive
1314
self.cell_layer.data = np.random.choice([True, False], size=(width, height), p=[alive_fraction, 1 - alive_fraction])
1415

16+
# Metrics and datacollector
17+
self.cells = width * height
18+
self.alive_count = 0
19+
self.alive_fraction = 0
20+
self.datacollector = DataCollector(
21+
model_reporters={"Cells alive": "alive_count",
22+
"Fraction alive": "alive_fraction"}
23+
)
24+
self.datacollector.collect(self)
25+
1526
def step(self):
1627
self._advance_time()
1728
# Define a kernel for counting neighbors. The kernel has 1s around the center cell (which is 0).
@@ -34,3 +45,8 @@ def step(self):
3445
# Rule for live cells
3546
np.logical_and(~self.cell_layer.data, neighbor_count == 3) # Rule for dead cells
3647
)
48+
49+
# Metrics
50+
self.alive_count = np.sum(self.cell_layer.data)
51+
self.alive_fraction = self.alive_count / self.cells
52+
self.datacollector.collect(self)

0 commit comments

Comments
 (0)