1
1
import numpy as np
2
- from mesa import Model
2
+ from mesa import DataCollector , Model
3
3
from mesa .space import PropertyLayer
4
4
from scipy .signal import convolve2d
5
5
6
+
6
7
# fmt: off
7
8
class GameOfLifeModel (Model ):
8
9
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):
12
13
# Randomly set cells to alive
13
14
self .cell_layer .data = np .random .choice ([True , False ], size = (width , height ), p = [alive_fraction , 1 - alive_fraction ])
14
15
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
+
15
26
def step (self ):
16
27
self ._advance_time ()
17
28
# Define a kernel for counting neighbors. The kernel has 1s around the center cell (which is 0).
@@ -34,3 +45,8 @@ def step(self):
34
45
# Rule for live cells
35
46
np .logical_and (~ self .cell_layer .data , neighbor_count == 3 ) # Rule for dead cells
36
47
)
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