diff --git a/Project.toml b/Project.toml index 593e25c..905cae3 100644 --- a/Project.toml +++ b/Project.toml @@ -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" diff --git a/README.md b/README.md index e82de56..c1c78de 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 diff --git a/docs/src/api/twodim.md b/docs/src/api/twodim.md index ef62211..8a27e16 100644 --- a/docs/src/api/twodim.md +++ b/docs/src/api/twodim.md @@ -3,3 +3,11 @@ ```@docs Life ``` + +## Neighborhoods +```@docs + AbstractNeighborhood + Moore + VonNeumann + neighborhood_offsets +``` diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index 9b0032b..b2403f9 100644 --- a/src/CellularAutomata.jl +++ b/src/CellularAutomata.jl @@ -14,6 +14,7 @@ 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 @@ -21,7 +22,7 @@ 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 diff --git a/src/generics.jl b/src/generics.jl index d86c03c..47b2dfc 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -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 diff --git a/src/rules/cca.jl b/src/rules/cca.jl index 50b5c44..8a65bc0 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -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) diff --git a/src/rules/life.jl b/src/rules/life.jl index 540cc81..9c2dc58 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -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. @@ -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 @@ -45,10 +48,14 @@ 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) @@ -56,30 +63,26 @@ function (life::Life)(starting_array::AbstractMatrix) 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) || @@ -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 diff --git a/test/neighborhood_test.jl b/test/neighborhood_test.jl new file mode 100644 index 0000000..08e48eb --- /dev/null +++ b/test/neighborhood_test.jl @@ -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 diff --git a/test/regression_test.jl b/test/regression_test.jl index e682b26..2933168 100644 --- a/test/regression_test.jl +++ b/test/regression_test.jl @@ -36,6 +36,8 @@ end ConstantBoundary(0.0), Synchronous(), Stochastic(0.5), + Moore(), + VonNeumann(), ) for object in objects @test all(isconcretetype, fieldtypes(typeof(object))) diff --git a/test/runtests.jl b/test/runtests.jl index f1ab94c..7e3f9d8 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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