Skip to content

Game of Life

Conway's Game of Life, or another life-like rule, on a torus.

  • Class: GameOfLifeSystem
  • Import: from skcomplex.systems.computer_science.automata import GameOfLifeSystem
  • Field: computer_science/automata
  • Topics: lattice, life, emergence
  • References:
    • Gardner 1970
    • Downey 2018

The game_of_life example

Example

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.computer_science.automata import GameOfLifeSystem

trajectory = GameOfLifeSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
shape (100, 100)
density 0.3
initial None
born (3,)
survive (2, 3)
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space lattice
Laws update
Randomness unknown
Domains boolean
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class GameOfLifeSystem(BaseSystem):
    """Conway's Game of Life, or another life-like rule, on a torus.

    The system has the cells `cells.alive`.

    Args:
        shape:
            The number of rows and columns.

        density:
            The probability that a cell starts alive, when no initial cells are given.

        initial:
            The initial cells, an array of the shape, or `None` for random cells.

        born:
            The numbers of live neighbours that bring a dead cell to life.

        survive:
            The numbers of live neighbours that keep a live cell alive.

        random_state:
            The seed or generator of the random initial cells.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import GameOfLifeSystem
        >>> GameOfLifeSystem((20, 30)).prepare().simulate(until=1).get_lattice('cells.alive').shape
        (2, 20, 30)
    """

    field = 'computer_science/automata'
    topics = ('lattice', 'life', 'emergence')
    references = ('Gardner 1970', 'Downey 2018')
    until = 100
    dt = 1

    def __init__(
        self,
        shape: Sequence[int] = (100, 100),
        *,
        density: float = 0.3,
        initial: npt.ArrayLike | None = None,
        born: Sequence[int] = (3,),
        survive: Sequence[int] = (2, 3),
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.shape = shape
        self.density = density
        self.initial = initial
        self.born = born
        self.survive = survive
        self.random_state = random_state

    def _get_cells(self) -> Array:
        """Return the initial cells, given or alive with the probability `density`."""
        if self.initial is not None:
            return np.asarray(self.initial, dtype=float)
        random = np.random.default_rng(self.random_state).random(tuple(self.shape))
        return (random < self.density).astype(float)

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the cells of a torus and their life-like rule."""
        super()._prepare(context)
        cells = BinaryCellElement('cells', alive=self._get_cells().ravel(), space=LatticeSpace(tuple(self.shape)))
        rule = LifeRuleInteraction('rule', target='cells', born=self.born, survive=self.survive)
        self.system_ = System(self.label, elements=[cells], interactions=[rule])

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • LifeRuleInteraction, from Interaction
class BinaryCellElement(Element):
    """Cell of an automaton whose value `alive` is 0 or 1.

    The local rule of an interaction changes the value. With `space`, the element holds one cell on every site.

    Args:
        label:
            The label of the cells.

        alive:
            The initial value, 0 or 1, or one value per cell.

        space:
            The space with one cell on every site, such as a lattice, or `None` for one cell.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import BinaryCellElement
        >>> BinaryCellElement('cell', alive=1).alive
        1
    """

    def __init__(
        self,
        label: str,
        *,
        alive: Annotated[float | Array, {0, 1}] = 0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.alive = alive

class LifeRuleInteraction(Interaction):
    """Life-like rule of cells, such as `B3/S23` of Conway's Game of Life.

    A dead cell comes to life when its number of live neighbours is one of `born`, and a live cell stays alive when it
    is one of `survive`. Every other cell is dead at the next step.

    Args:
        label:
            The label of the interaction.

        target:
            The cells whose state `alive` the rule updates.

        born:
            The numbers of live neighbours that bring a dead cell to life.

        survive:
            The numbers of live neighbours that keep a live cell alive.

        neighborhood:
            The neighbours every cell counts, the eight cells around it by default.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import LifeRuleInteraction
        >>> LifeRuleInteraction('rule', target='cells', born=(3, 6)).born
        (3, 6)
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role = 'cells',
        born: Sequence[int] = (3,),
        survive: Sequence[int] = (2, 3),
        neighborhood: BaseNeighborhood = MOORE,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.born = born
        self.survive = survive
        self.neighborhood = neighborhood

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the local rule of the cells as the law.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        rule = life(self.born, self.survive)
        alive = context.target.alive
        self.laws_: list[BaseLaw] = [UpdateLaw(alive, rule, neighborhood=self.neighborhood, label=self.label)]