Skip to content

Elementary Cellular Automata

cax.cs.elementary.cs.Elementary

Bases: ComplexSystem[Array, Array]

Elementary Cellular Automata class.

A one-dimensional cellular automaton where each cell evolves based on its current state and the states of its two immediate neighbors according to a Wolfram rule. The system supports all 256 possible rules and can simulate classic patterns such as Rule 30, Rule 110, and Rule 184.

Source code in src/cax/cs/elementary/cs.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Elementary(ComplexSystem[Array, Array]):
    """Elementary Cellular Automata class.

    A one-dimensional cellular automaton where each cell evolves based on its current
    state and the states of its two immediate neighbors according to a Wolfram rule. The
    system supports all 256 possible rules and can simulate classic patterns such as
    Rule 30, Rule 110, and Rule 184.
    """

    def __init__(
        self,
        *,
        wolfram_code: Array,
        padding: Literal["CIRCULAR", "ZERO"] = "CIRCULAR",
    ):
        """Initialize Elementary Cellular Automaton.

        Args:
            wolfram_code: Array of 8 binary values defining the Wolfram rule. Each
                element corresponds to the output for one of the 8 possible three-cell
                neighborhood configurations (111, 110, 101, 100, 011, 010, 001, 000).
            padding: Boundary condition mode. "CIRCULAR" for periodic boundaries,
                "ZERO" for a border of permanently dead cells.

        """
        self.perceive = ElementaryPerceive(padding=padding)
        self.update = ElementaryUpdate(wolfram_code=wolfram_code)

    @override
    def _step(self, state: Array, input: Array | None = None) -> Array:
        perception = self.perceive(state)
        next_state = self.update(state, perception, input)

        return next_state

    @classmethod
    def wolfram_code_from_rule_number(cls, rule_number: int) -> Array:
        """Create Wolfram code array from a rule number.

        Converts a Wolfram rule number (0-255) to its binary representation as an array
        of 8 floats. For example, rule 30 becomes [0, 0, 0, 1, 1, 1, 1, 0].

        Args:
            rule_number: Integer between 0 and 255 representing the Wolfram rule.

        Returns:
            Array of shape (8,) containing binary values (0.0 or 1.0) representing
                the rule's lookup table.

        """
        if not 0 <= rule_number < 256:
            raise ValueError(f"rule_number must be in [0, 255], got {rule_number!r}")
        return ((rule_number >> 7 - jnp.arange(8)) & 1).astype(jnp.float32)

    @nnx.jit
    @override
    def render(self, state: Array) -> Array:
        """Render state to RGB image.

        Converts the one-dimensional cellular automaton state to an RGB visualization
        by replicating the single-channel state values across all three color channels,
        resulting in a grayscale image.

        Args:
            state: Array with shape (num_steps, width, 1) representing the
                cellular automaton state, where each cell contains a value in [0, 1].

        Returns:
            RGB image with dtype uint8 and shape (num_steps, width, 3), where cell
            values are mapped to grayscale colors in the range [0, 255].

        """
        rgb = jnp.repeat(state, 3, axis=-1)

        return clip_and_uint8(rgb)

__init__(*, wolfram_code, padding='CIRCULAR')

Initialize Elementary Cellular Automaton.

Parameters:

Name Type Description Default
wolfram_code Array

Array of 8 binary values defining the Wolfram rule. Each element corresponds to the output for one of the 8 possible three-cell neighborhood configurations (111, 110, 101, 100, 011, 010, 001, 000).

required
padding Literal['CIRCULAR', 'ZERO']

Boundary condition mode. "CIRCULAR" for periodic boundaries, "ZERO" for a border of permanently dead cells.

'CIRCULAR'
Source code in src/cax/cs/elementary/cs.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __init__(
    self,
    *,
    wolfram_code: Array,
    padding: Literal["CIRCULAR", "ZERO"] = "CIRCULAR",
):
    """Initialize Elementary Cellular Automaton.

    Args:
        wolfram_code: Array of 8 binary values defining the Wolfram rule. Each
            element corresponds to the output for one of the 8 possible three-cell
            neighborhood configurations (111, 110, 101, 100, 011, 010, 001, 000).
        padding: Boundary condition mode. "CIRCULAR" for periodic boundaries,
            "ZERO" for a border of permanently dead cells.

    """
    self.perceive = ElementaryPerceive(padding=padding)
    self.update = ElementaryUpdate(wolfram_code=wolfram_code)

wolfram_code_from_rule_number(rule_number) classmethod

Create Wolfram code array from a rule number.

Converts a Wolfram rule number (0-255) to its binary representation as an array of 8 floats. For example, rule 30 becomes [0, 0, 0, 1, 1, 1, 1, 0].

Parameters:

Name Type Description Default
rule_number int

Integer between 0 and 255 representing the Wolfram rule.

required

Returns:

Type Description
Array

Array of shape (8,) containing binary values (0.0 or 1.0) representing the rule's lookup table.

Source code in src/cax/cs/elementary/cs.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@classmethod
def wolfram_code_from_rule_number(cls, rule_number: int) -> Array:
    """Create Wolfram code array from a rule number.

    Converts a Wolfram rule number (0-255) to its binary representation as an array
    of 8 floats. For example, rule 30 becomes [0, 0, 0, 1, 1, 1, 1, 0].

    Args:
        rule_number: Integer between 0 and 255 representing the Wolfram rule.

    Returns:
        Array of shape (8,) containing binary values (0.0 or 1.0) representing
            the rule's lookup table.

    """
    if not 0 <= rule_number < 256:
        raise ValueError(f"rule_number must be in [0, 255], got {rule_number!r}")
    return ((rule_number >> 7 - jnp.arange(8)) & 1).astype(jnp.float32)

render(state)

Render state to RGB image.

Converts the one-dimensional cellular automaton state to an RGB visualization by replicating the single-channel state values across all three color channels, resulting in a grayscale image.

Parameters:

Name Type Description Default
state Array

Array with shape (num_steps, width, 1) representing the cellular automaton state, where each cell contains a value in [0, 1].

required

Returns:

Type Description
Array

RGB image with dtype uint8 and shape (num_steps, width, 3), where cell

Array

values are mapped to grayscale colors in the range [0, 255].

Source code in src/cax/cs/elementary/cs.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@nnx.jit
@override
def render(self, state: Array) -> Array:
    """Render state to RGB image.

    Converts the one-dimensional cellular automaton state to an RGB visualization
    by replicating the single-channel state values across all three color channels,
    resulting in a grayscale image.

    Args:
        state: Array with shape (num_steps, width, 1) representing the
            cellular automaton state, where each cell contains a value in [0, 1].

    Returns:
        RGB image with dtype uint8 and shape (num_steps, width, 3), where cell
        values are mapped to grayscale colors in the range [0, 255].

    """
    rgb = jnp.repeat(state, 3, axis=-1)

    return clip_and_uint8(rgb)

__call__(state, input=None, *, num_steps=1, input_in_axis=None, return_states=False)

Step the system for multiple time steps.

This method wraps _step inside a JAX scan for efficiency and JIT-compiles the loop. If input is time-varying, set input_in_axis to the axis containing the time dimension so that each step receives the corresponding slice of input.

Under return_states=True, the per-step states are also returned as the scan's stacked outputs, mirroring the (carry, ys) convention of jax.lax.scan. The trajectory holds the state after each step, stacked along a new leading axis of size num_steps — its first element is the state after one step, its last equals the final state, and the initial state is not included.

When remat is enabled, the scan body is wrapped with nnx.remat to reduce memory usage during backpropagation at the cost of recomputing intermediates.

Note that num_steps, input_in_axis, and return_states are static: each distinct combination compiles once, so sweeps over horizons should batch their step counts.

Parameters:

Name Type Description Default
state State

Current state.

required
input Input | None

Optional input.

None
num_steps int

Number of steps.

1
input_in_axis int | None

Axis for input if provided for each step.

None
return_states bool

Whether to also return the stacked per-step states.

False

Returns:

Type Description
State | tuple[State, State]

Final state after num_steps applications of _step, or a (final_state, states) tuple under return_states=True, where states stacks the per-step states along a new leading axis of size num_steps.

Source code in src/cax/core/cs.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@nnx.jit(static_argnames=("num_steps", "input_in_axis", "return_states"))
def __call__(
    self,
    state: State,
    input: Input | None = None,
    *,
    num_steps: int = 1,
    input_in_axis: int | None = None,
    return_states: bool = False,
) -> State | tuple[State, State]:
    """Step the system for multiple time steps.

    This method wraps `_step` inside a JAX scan for efficiency and JIT-compiles the
    loop. If `input` is time-varying, set `input_in_axis` to the axis containing the
    time dimension so that each step receives the corresponding slice of input.

    Under `return_states=True`, the per-step states are also returned as the scan's
    stacked outputs, mirroring the `(carry, ys)` convention of `jax.lax.scan`. The
    trajectory holds the state *after* each step, stacked along a new leading axis
    of size `num_steps` — its first element is the state after one step, its last
    equals the final state, and the initial state is not included.

    When `remat` is enabled, the scan body is wrapped with `nnx.remat` to reduce
    memory usage during backpropagation at the cost of recomputing intermediates.

    Note that `num_steps`, `input_in_axis`, and `return_states` are static: each
    distinct combination compiles once, so sweeps over horizons should batch their
    step counts.

    Args:
        state: Current state.
        input: Optional input.
        num_steps: Number of steps.
        input_in_axis: Axis for input if provided for each step.
        return_states: Whether to also return the stacked per-step states.

    Returns:
        Final state after `num_steps` applications of `_step`, or a
            `(final_state, states)` tuple under `return_states=True`, where `states`
            stacks the per-step states along a new leading axis of size `num_steps`.

    """

    def step_fn(
        cs: ComplexSystem[State, Input], state: State, input: Input | None
    ) -> tuple[State, State | None]:
        next_state = cs._step(state, input)
        return next_state, (next_state if return_states else None)

    if self.remat:
        step_fn = nnx.remat(step_fn)

    state, states = nnx.scan(
        step_fn,
        in_axes=(nnx.StateAxes({...: nnx.Carry}), nnx.Carry, input_in_axis),
        out_axes=(nnx.Carry, 0),
        length=num_steps,
    )(self, state, input)

    return (state, states) if return_states else state