From 45de824c2067d4bf0d6fb18826a4fa367d7f35d8 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Thu, 30 Jul 2026 08:08:34 +0200 Subject: [PATCH 1/4] feat: add Moore/VonNeumann neighborhood abstraction Life hardcoded a square (Moore) neighborhood. Pull the shape out into small types, matching the existing boundary-condition pattern, so Life can use VonNeumann too and future rules (Lenia) can reuse the same offset-generation mechanism as their perception kernel. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HLo6tnomTm1Z3c2hoe8PmH --- docs/src/api/twodim.md | 7 +++++ src/CellularAutomata.jl | 1 + src/generics.jl | 64 +++++++++++++++++++++++++++++++++++++++ src/rules/life.jl | 54 +++++++++++++++++++-------------- test/neighborhood_test.jl | 48 +++++++++++++++++++++++++++++ test/runtests.jl | 1 + 6 files changed, 153 insertions(+), 22 deletions(-) create mode 100644 test/neighborhood_test.jl diff --git a/docs/src/api/twodim.md b/docs/src/api/twodim.md index ef62211..bc28df2 100644 --- a/docs/src/api/twodim.md +++ b/docs/src/api/twodim.md @@ -3,3 +3,10 @@ ```@docs Life ``` + +## Neighborhoods +```@docs + AbstractNeighborhood + Moore + VonNeumann +``` diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index 9b0032b..a540dae 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 diff --git a/src/generics.jl b/src/generics.jl index d86c03c..0001f9c 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -80,6 +80,70 @@ 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). +""" +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). +""" +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. +""" +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 + +function __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 __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 + """ AbstractUpdateScheme diff --git a/src/rules/life.jl b/src/rules/life.jl index 540cc81..923264c 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,13 @@ 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 >= 1 || throw(ArgumentError("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 +62,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 __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 +93,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) = life.neighborhood.radius 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=", + life.neighborhood.radius, ")" + ) + 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..98b2c8a --- /dev/null +++ b/test/neighborhood_test.jl @@ -0,0 +1,48 @@ +using CellularAutomata +using Test + +@testset "constructor validation" begin + @test Moore(2).radius == 2 + @test VonNeumann(; radius = 2).radius == 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(CellularAutomata.__offsets(Moore(1))) + @test length(moore_offsets) == 8 + @test (0, 0) ∉ moore_offsets + @test (1, 1) ∈ moore_offsets + + vonneumann_offsets = Set(CellularAutomata.__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 "neighborhood_radius reflects the configured neighborhood" begin + @test neighborhood_radius(Life(((3,), (2, 3)); neighborhood = VonNeumann(3))) == 3 +end 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 From 0d56b9ab5f9abff2bab2e4729762223a95a7008a Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Thu, 30 Jul 2026 08:26:01 +0200 Subject: [PATCH 2/4] refac: make neighborhood_offsets/neighborhood_radius a public interface Custom AbstractNeighborhood subtypes can now plug into Life by implementing neighborhood_offsets and neighborhood_radius, rather than relying on the internal __offsets helper. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HLo6tnomTm1Z3c2hoe8PmH --- docs/src/api/twodim.md | 1 + src/CellularAutomata.jl | 2 +- src/generics.jl | 38 ++++++++++++++++++++++++++++++++------ src/rules/cca.jl | 5 ----- src/rules/life.jl | 9 +++++---- test/neighborhood_test.jl | 25 +++++++++++++++++++++---- test/regression_test.jl | 2 ++ 7 files changed, 62 insertions(+), 20 deletions(-) diff --git a/docs/src/api/twodim.md b/docs/src/api/twodim.md index bc28df2..8a27e16 100644 --- a/docs/src/api/twodim.md +++ b/docs/src/api/twodim.md @@ -9,4 +9,5 @@ AbstractNeighborhood Moore VonNeumann + neighborhood_offsets ``` diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index a540dae..b2403f9 100644 --- a/src/CellularAutomata.jl +++ b/src/CellularAutomata.jl @@ -22,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 0001f9c..47b2dfc 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -85,17 +85,20 @@ end 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) + 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). """ -struct Moore <: AbstractNeighborhood +@concrete struct Moore <: AbstractNeighborhood radius::Int function Moore(radius::Int) radius >= 0 || throw(ArgumentError("radius must be nonnegative")) @@ -105,12 +108,12 @@ end Moore(; radius::Int = 1) = Moore(radius) """ - VonNeumann(radius=1) + VonNeumann([radius = 1]) Diamond neighborhood: every cell within Manhattan distance `radius`, excluding the center. """ -struct VonNeumann <: AbstractNeighborhood +@concrete struct VonNeumann <: AbstractNeighborhood radius::Int function VonNeumann(radius::Int) radius >= 0 || throw(ArgumentError("radius must be nonnegative")) @@ -126,7 +129,17 @@ function Base.show(io::IO, neighborhood::VonNeumann) return print(io, "VonNeumann(", neighborhood.radius, ")") end -function __offsets(neighborhood::Moore) +""" + 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) @@ -135,7 +148,7 @@ function __offsets(neighborhood::Moore) ) end -function __offsets(neighborhood::VonNeumann) +function neighborhood_offsets(neighborhood::VonNeumann) radius = neighborhood.radius return ( (row, column) @@ -144,6 +157,19 @@ function __offsets(neighborhood::VonNeumann) ) 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 923264c..9c2dc58 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -52,7 +52,8 @@ function Life( life_description::Tuple; radius::Int = 1, neighborhood::AbstractNeighborhood = Moore(radius) ) - neighborhood.radius >= 1 || throw(ArgumentError("radius must be at least 1")) + neighborhood_radius(neighborhood) >= 1 || + throw(ArgumentError("neighborhood radius must be at least 1")) born, survive = life_description return Life(born, survive, neighborhood) end @@ -76,7 +77,7 @@ end function (update::__LifeUpdate)(index::CartesianIndex{2}) row, column = Tuple(index) alive = 0 - for (row_offset, column_offset) in __offsets(update.neighborhood) + for (row_offset, column_offset) in neighborhood_offsets(update.neighborhood) alive += Int( __boundary_get( update.state, update.boundary, row + row_offset, column + column_offset @@ -100,13 +101,13 @@ function __life_evolution( return map(update, CartesianIndices(starting_array)) end -neighborhood_radius(life::Life) = life.neighborhood.radius +neighborhood_radius(life::Life) = neighborhood_radius(life.neighborhood) function Base.show(io::IO, life::Life) if life.neighborhood isa Moore return print( io, "Life(", (life.born, life.survive), "; radius=", - life.neighborhood.radius, ")" + neighborhood_radius(life.neighborhood), ")" ) end return print( diff --git a/test/neighborhood_test.jl b/test/neighborhood_test.jl index 98b2c8a..08e48eb 100644 --- a/test/neighborhood_test.jl +++ b/test/neighborhood_test.jl @@ -1,9 +1,17 @@ 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 Moore(2).radius == 2 - @test VonNeumann(; radius = 2).radius == 2 + @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) @@ -19,12 +27,12 @@ end end @testset "offsets exclude the center and match each neighborhood's shape" begin - moore_offsets = Set(CellularAutomata.__offsets(Moore(1))) + 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(CellularAutomata.__offsets(VonNeumann(1))) + vonneumann_offsets = Set(neighborhood_offsets(VonNeumann(1))) @test length(vonneumann_offsets) == 4 @test (0, 0) ∉ vonneumann_offsets @test (1, 1) ∉ vonneumann_offsets @@ -43,6 +51,15 @@ end @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))) From 7464da83c15fa7141e88927cedeb307d99b8fb1e Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Thu, 30 Jul 2026 08:26:14 +0200 Subject: [PATCH 3/4] chore: bump version to 0.1.3 Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HLo6tnomTm1Z3c2hoe8PmH --- Project.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" From 409096ba97a70913b5a80b1b16cbdadde83a8aaf Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Thu, 30 Jul 2026 08:26:58 +0200 Subject: [PATCH 4/4] docs: mention neighborhood shapes in README Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HLo6tnomTm1Z3c2hoe8PmH --- README.md | 4 ++++ 1 file changed, 4 insertions(+) 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