Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "CellularAutomata"
uuid = "878138dc-5b27-11ea-1a71-cb95d38d6b29"
authors = ["Francesco Martinuzzi"]
version = "0.1.2"
version = "0.1.3"

[deps]
ConcreteStructs = "2569d6c7-a4a2-43d3-a901-331e8e4be471"
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ cellular automata, one and two dimensional.
- **Boundary conditions**: `Periodic`, `Reflecting`, `ConstantBoundary`.
- **Update schemes**: `Synchronous` (default) and `Stochastic(rate)` for
per-cell probabilistic updates, given an explicit `rng`.
- **Neighborhoods**: `Moore` (default, square) and `VonNeumann` (diamond) shapes
for `Life`, extensible to custom `AbstractNeighborhood` subtypes.
- **Functional core** (`next_state`, `rollout`): non-mutating, AD/GPU-friendly
building blocks for custom or neural cellular automata, alongside the
stateful `CellularAutomaton` wrapper.
Expand Down Expand Up @@ -393,6 +395,8 @@ heatmap(evolution_history(ca),

This package can also reproduce Conway's Game of Life, and any variation based on it. The ```Life()``` function takes in a tuple containing the number of neighbors that will gave birth to a new cell, or that will make an existing cell survive. (For example in the Conways's Life the tuple (3, (2,3)) indicates having 3 live neighbors will give birth to an otherwise dead cell, and having either 2 or 3 lie neighbors will make an alive cell continue living.) The implementation follows the [Golly](https://golly.sourceforge.net/Help/changes.html) notation.

By default neighbors are counted over a `Moore` neighborhood (the surrounding square, as in the classic Game of Life), configurable with the `radius` keyword. A `VonNeumann` (diamond) neighborhood is also available through the `neighborhood` keyword, e.g. `Life((3, (2,3)); neighborhood=VonNeumann(1))`. Custom shapes can be added by subtyping `AbstractNeighborhood` and implementing `neighborhood_offsets` and `neighborhood_radius`.

This script reproduces the famous glider:

```julia
Expand Down
8 changes: 8 additions & 0 deletions docs/src/api/twodim.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,11 @@
```@docs
Life
```

## Neighborhoods
```@docs
AbstractNeighborhood
Moore
VonNeumann
neighborhood_offsets
```
3 changes: 2 additions & 1 deletion src/CellularAutomata.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ include("measures.jl")
export AbstractCellularAutomaton, AbstractCellularAutomatonRule
export AbstractBoundaryCondition, Periodic, Reflecting, ConstantBoundary
export AbstractUpdateScheme, Synchronous, Stochastic
export AbstractNeighborhood, Moore, VonNeumann
export AbstractDiscreteCellularAutomatonRule
export AbstractContinuousCellularAutomatonRule
export AbstractTotalisticCellularAutomatonRule
export AbstractLifeLikeCellularAutomatonRule
export CellularAutomaton
export next_state, rollout, spatial_dimensions
export cellular_automaton_rule, evolution_history, generation_count
export neighborhood_radius, rule_lookup_table, cell_state_count
export neighborhood_offsets, neighborhood_radius, rule_lookup_table, cell_state_count
export DCA
export CCA
export TCA
Expand Down
90 changes: 90 additions & 0 deletions src/generics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,96 @@ function Base.show(io::IO, boundary::ConstantBoundary)
return print(io, "ConstantBoundary(", boundary.value, ")")
end

"""
AbstractNeighborhood

Supertype for two-dimensional neighborhood shapes, used to enumerate the cells
around a given cell (excluding the cell itself).

Subtypes must implement [`neighborhood_offsets`](@ref) and
[`neighborhood_radius`](@ref).
"""
abstract type AbstractNeighborhood end

"""
Moore([radius = 1])

Square neighborhood: every cell within Chebyshev distance `radius`, excluding the
center. This is the classic Game-of-Life neighborhood and the default for
[`Life`](@ref).
"""
@concrete struct Moore <: AbstractNeighborhood
radius::Int
function Moore(radius::Int)
radius >= 0 || throw(ArgumentError("radius must be nonnegative"))
return new(radius)
end
end
Moore(; radius::Int = 1) = Moore(radius)

"""
VonNeumann([radius = 1])

Diamond neighborhood: every cell within Manhattan distance `radius`, excluding the
center.
"""
@concrete struct VonNeumann <: AbstractNeighborhood
radius::Int
function VonNeumann(radius::Int)
radius >= 0 || throw(ArgumentError("radius must be nonnegative"))
return new(radius)
end
end
VonNeumann(; radius::Int = 1) = VonNeumann(radius)

function Base.show(io::IO, neighborhood::Moore)
return print(io, "Moore(", neighborhood.radius, ")")
end
function Base.show(io::IO, neighborhood::VonNeumann)
return print(io, "VonNeumann(", neighborhood.radius, ")")
end

"""
neighborhood_offsets(neighborhood::AbstractNeighborhood)

Return an iterable of `(row_offset, column_offset)` tuples describing the cells in
`neighborhood`. The center offset `(0, 0)` must not be included.

Custom [`AbstractNeighborhood`](@ref) subtypes must implement this method.
"""
function neighborhood_offsets end

function neighborhood_offsets(neighborhood::Moore)
radius = neighborhood.radius
return (
(row, column)
for row in (-radius):radius, column in (-radius):radius
if !(row == 0 && column == 0)
)
end

function neighborhood_offsets(neighborhood::VonNeumann)
radius = neighborhood.radius
return (
(row, column)
for row in (-radius):radius, column in (-radius):radius
if !(row == 0 && column == 0) && abs(row) + abs(column) <= radius
)
end

"""
neighborhood_radius(neighborhood::AbstractNeighborhood)
neighborhood_radius(rule::AbstractCellularAutomatonRule)

Return the spatial radius or extent used by `neighborhood` or `rule`.

Custom [`AbstractNeighborhood`](@ref) subtypes must implement this method.
"""
function neighborhood_radius end

neighborhood_radius(neighborhood::Moore) = neighborhood.radius
neighborhood_radius(neighborhood::VonNeumann) = neighborhood.radius

"""
AbstractUpdateScheme

Expand Down
5 changes: 0 additions & 5 deletions src/rules/cca.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,6 @@ function __cca_evolution(
return map(__CCAUpdate(cell, rule, boundary, left, right), eachindex(cell))
end

"""
neighborhood_radius(rule::AbstractCellularAutomatonRule)

Return the spatial neighborhood radius used by `rule`.
"""
neighborhood_radius(cca::CCA) = cca.radius

function Base.show(io::IO, cca::CCA)
Expand Down
55 changes: 33 additions & 22 deletions src/rules/life.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ abstract type AbstractLifeLikeCellularAutomatonRule <: AbstractCellularAutomaton
@concrete struct Life <: AbstractLifeLikeCellularAutomatonRule
born
survive
radius::Int
neighborhood
end

spatial_dimensions(::Life) = 2

"""
Life(life_description; radius=1)
Life(life_description; radius=1, neighborhood=Moore(radius))

Construct a Life-like cellular-automaton rule using Golly birth/survival notation.

Expand All @@ -25,7 +25,10 @@ Construct a Life-like cellular-automaton rule using Golly birth/survival notatio

# Keyword arguments

- `radius`: Radius of the square neighborhood. Defaults to 1.
- `radius`: Radius of the default [`Moore`](@ref) neighborhood. Defaults to 1. Ignored
if `neighborhood` is passed explicitly.
- `neighborhood`: An [`AbstractNeighborhood`](@ref), such as `Moore(radius)` (default)
or `VonNeumann(radius)`.

# Examples

Expand All @@ -45,41 +48,41 @@ julia> next_state(life, blinker)
0 0 0 0 0
```
"""
function Life(life_description::Tuple; radius::Int = 1)
radius >= 1 || throw(ArgumentError("radius must be at least 1"))
function Life(
life_description::Tuple; radius::Int = 1,
neighborhood::AbstractNeighborhood = Moore(radius)
)
neighborhood_radius(neighborhood) >= 1 ||
throw(ArgumentError("neighborhood radius must be at least 1"))
born, survive = life_description
return Life(born, survive, radius)
return Life(born, survive, neighborhood)
end

function (life::Life)(starting_array::AbstractMatrix)
return next_state(life, starting_array)
end

function __step(life::Life, state::AbstractMatrix, boundary::AbstractBoundaryCondition)
return __life_evolution(state, life.born, life.survive, life.radius, boundary)
return __life_evolution(state, life.born, life.survive, life.neighborhood, boundary)
end

@concrete struct __LifeUpdate
state
born
survive
radius
neighborhood
boundary
end

function (update::__LifeUpdate)(index::CartesianIndex{2})
row, column = Tuple(index)
radius = update.radius
alive = 0
for column_offset in (-radius):radius, row_offset in (-radius):radius

if !iszero(row_offset) || !iszero(column_offset)
alive += Int(
__boundary_get(
update.state, update.boundary, row + row_offset, column + column_offset
),
)
end
for (row_offset, column_offset) in neighborhood_offsets(update.neighborhood)
alive += Int(
__boundary_get(
update.state, update.boundary, row + row_offset, column + column_offset
),
)
end
current = update.state[index]
lives = (isone(current) && alive in update.survive) ||
Expand All @@ -91,15 +94,23 @@ function __life_evolution(
starting_array::AbstractMatrix,
born,
survive,
radius::Int,
neighborhood::AbstractNeighborhood,
boundary::AbstractBoundaryCondition = Periodic()
)
update = __LifeUpdate(starting_array, born, survive, radius, boundary)
update = __LifeUpdate(starting_array, born, survive, neighborhood, boundary)
return map(update, CartesianIndices(starting_array))
end

neighborhood_radius(life::Life) = life.radius
neighborhood_radius(life::Life) = neighborhood_radius(life.neighborhood)

function Base.show(io::IO, life::Life)
return print(io, "Life(", (life.born, life.survive), "; radius=", life.radius, ")")
if life.neighborhood isa Moore
return print(
io, "Life(", (life.born, life.survive), "; radius=",
neighborhood_radius(life.neighborhood), ")"
)
end
return print(
io, "Life(", (life.born, life.survive), "; neighborhood=", life.neighborhood, ")"
)
end
65 changes: 65 additions & 0 deletions test/neighborhood_test.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using CellularAutomata
using Test

struct HorizontalNeighborhood <: AbstractNeighborhood
radius::Int
end

CellularAutomata.neighborhood_radius(neighborhood::HorizontalNeighborhood) =
neighborhood.radius
CellularAutomata.neighborhood_offsets(::HorizontalNeighborhood) = ((0, -1), (0, 1))

@testset "constructor validation" begin
@test neighborhood_radius(Moore(2)) == 2
@test neighborhood_radius(VonNeumann(; radius = 2)) == 2
@test_throws ArgumentError Moore(-1)
@test_throws ArgumentError VonNeumann(-1)
@test_throws ArgumentError Life(((3,), (2, 3)); radius = 0)
@test_throws ArgumentError Life(((3,), (2, 3)); neighborhood = VonNeumann(0))
end

@testset "show methods" begin
@test repr(Moore(1)) == "Moore(1)"
@test repr(VonNeumann(2)) == "VonNeumann(2)"
@test repr(Life(((3,), (2, 3)))) == "Life(((3,), (2, 3)); radius=1)"
@test repr(Life(((3,), (2, 3)); neighborhood = VonNeumann(1))) ==
"Life(((3,), (2, 3)); neighborhood=VonNeumann(1))"
end

@testset "offsets exclude the center and match each neighborhood's shape" begin
moore_offsets = Set(neighborhood_offsets(Moore(1)))
@test length(moore_offsets) == 8
@test (0, 0) ∉ moore_offsets
@test (1, 1) ∈ moore_offsets

vonneumann_offsets = Set(neighborhood_offsets(VonNeumann(1)))
@test length(vonneumann_offsets) == 4
@test (0, 0) ∉ vonneumann_offsets
@test (1, 1) ∉ vonneumann_offsets
@test (1, 0) ∈ vonneumann_offsets
end

@testset "VonNeumann and Moore neighborhoods can disagree" begin
diagonal_corners = zeros(Bool, 5, 5)
diagonal_corners[[2, 4], [2, 4]] .= true

moore_result = next_state(Life(((4,), ()); radius = 1), diagonal_corners)
vonneumann_result = next_state(
Life(((4,), ()); neighborhood = VonNeumann(1)), diagonal_corners
)
@test moore_result[3, 3] == true
@test vonneumann_result[3, 3] == false
end

@testset "custom neighborhoods implement the public interface" begin
neighborhood = HorizontalNeighborhood(1)
life = Life(((2,), ()); neighborhood)
horizontal_pair = Bool[0 0 0; 1 0 1; 0 0 0]

@test neighborhood_radius(life) == 1
@test next_state(life, horizontal_pair)[2, 2]
end

@testset "neighborhood_radius reflects the configured neighborhood" begin
@test neighborhood_radius(Life(((3,), (2, 3)); neighborhood = VonNeumann(3))) == 3
end
2 changes: 2 additions & 0 deletions test/regression_test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ end
ConstantBoundary(0.0),
Synchronous(),
Stochastic(0.5),
Moore(),
VonNeumann(),
)
for object in objects
@test all(isconcretetype, fieldtypes(typeof(object)))
Expand Down
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ if GROUP in ("All", "Core")
@testset "Life-like" begin
@safetestset "Life glider" include("glider_test.jl")
@safetestset "Life blinker" include("blinker_test.jl")
@safetestset "Neighborhoods" include("neighborhood_test.jl")
end
end
Loading