[docs]classCA(MCS):"""Cellular automata simulation. Override this class to customize configuration and state-transition function. Attributes: max_step: The max step. size_x: Number of cells in x dimension. size_y: Number of cells in y dimension. seed: NumPy random seed. s: An `~numpy.ndarray` of shape (max_step, size_x) or (max_step, size_y, size_x) representing the states. step: The current step. """def__init__(self,max_step:int,size_x:int,size_y:int=1,seed:int=42):super().__init__(max_step)self.size_x=size_xself.size_y=size_yself.seed=seedifsize_y==1:self.s=np.zeros((max_step,size_x))else:self.s=np.zeros((max_step,size_y,size_x))
[docs]definitialize(self):"""Sets up the initial configuration."""np.random.seed(self.seed)self.s[0]=np.random.randint(2,size=self.s[0].shape)
[docs]defupdate(self,*,F:Callable=None):"""Updates the states in the next step. Args: F: A state transition function which returns an `~numpy.ndarray`. """ifFisNone:F=self._identityconfig=self.s[self.step]self.step+=1self.s[self.step]=F(config)
[docs]defvisualize(self,*,step:int=-1):"""Visualizes the states of the system using an image of shape (step, size_x) or (size_y, size_x). Args: step: The step to plot. Returns: A `matplotlib.figure.Figure` object. """fig,ax=plt.subplots()ifself.s.ndim==2:ax.imshow(self.s[:step],cmap=plt.cm.binary)elifself.s.ndim==3:ax.imshow(self.s[step],cmap=plt.cm.binary)returnfig