From 47ca344275d9b3abcfe27562e58410a7b7e5ea6d Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 11:22:40 +0200 Subject: [PATCH 1/8] refac: eltype-preserving, AD-ready kernels and concrete structs - Fix eltype handling: use eltype instead of typeof(x[2]) and drop hardcoded Float64 outputs, so Float32/Dual numbers flow through - Fix TCA codeset length for radius != 1 ((states-1)*nsize + 1) - Fix Life for radius != 1 (loop bounds and window size) and make life_application non-mutating - Replace string round-trip ruleset/state decoding with digits() and integer arithmetic (also fixes states > 10) - Handle asymmetric tuple radii uniformly in DCA/CCA/TCA padding - Make CCA evolution non-mutating and ForwardDiff-differentiable (modf -> x - floor(x)); add AD regression test - Use ConcreteStructs.@concrete for all structs - Widen JET compat for Julia 1.12; add compat entries; bump to 0.0.7 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- Project.toml | 16 +++++++-- src/CellularAutomata.jl | 2 ++ src/cellular_automaton.jl | 28 ++++++++-------- src/generics.jl | 2 +- src/rules/cca.jl | 53 ++++++++++-------------------- src/rules/dca.jl | 62 ++++++++++++++--------------------- src/rules/life.jl | 40 +++++++++++------------ src/rules/tca.jl | 68 +++++++++++++-------------------------- test/ad_test.jl | 20 ++++++++++++ test/runtests.jl | 4 +++ 10 files changed, 137 insertions(+), 158 deletions(-) create mode 100644 test/ad_test.jl diff --git a/Project.toml b/Project.toml index 861c9cf..cd16484 100644 --- a/Project.toml +++ b/Project.toml @@ -1,18 +1,28 @@ name = "CellularAutomata" uuid = "878138dc-5b27-11ea-1a71-cb95d38d6b29" authors = ["Francesco Martinuzzi"] -version = "0.0.6" +version = "0.0.7" + +[deps] +ConcreteStructs = "2569d6c7-a4a2-43d3-a901-331e8e4be471" [compat] -JET = "0.9.18" +Aqua = "0.8" +ConcreteStructs = "0.2" +ForwardDiff = "0.10, 1" +JET = "0.9.18, 0.10, 0.11" +Random = "1.10" +SafeTestsets = "0.1" +Test = "1.10" julia = "1.10" [extras] Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" +ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" JET = "c3a54625-cd67-489e-a8e7-0a5a0ff4e31b" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Test", "SafeTestsets", "Random", "Aqua", "JET"] +test = ["Test", "SafeTestsets", "Random", "Aqua", "ForwardDiff", "JET"] diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index 1254edc..3290d19 100644 --- a/src/CellularAutomata.jl +++ b/src/CellularAutomata.jl @@ -1,5 +1,7 @@ module CellularAutomata +using ConcreteStructs: @concrete + include("generics.jl") include("cellular_automaton.jl") include("rules/dca.jl") diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index 4e3f426..7e50bc1 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -35,9 +35,9 @@ For a two-dimensional cellular automaton: ```julia rule = Life(((3,), (2, 3))) # Define or instantiate a two-dimensional rule initial_conditions = [ # Initial state matrix - [0, 1, 0], - [1, 0, 1], - [0, 1, 0], + 0 1 0 + 1 0 1 + 0 1 0 ] generations = 50 # Number of generations to simulate automaton_td = CellularAutomaton(rule, initial_conditions, generations) @@ -60,16 +60,16 @@ automaton_td.evolution - The `rule` parameter determines the dimensionality of the cellular automaton. Ensure that your `initial_conditions` and `rule` are compatible in terms of dimensions. """ -struct CellularAutomaton{F,E} <: AbstractCA +@concrete struct CellularAutomaton <: AbstractCA generations::Int - generation_fun::F - evolution::E + generation_fun + evolution end -function CellularAutomaton(rule::AbstractODRule, initial_conditions, generations) - evolution = zeros( - typeof(initial_conditions[2]), generations, length(initial_conditions) - ) +function CellularAutomaton( + rule::AbstractODRule, initial_conditions::AbstractVector, generations::Int +) + evolution = zeros(eltype(initial_conditions), generations, length(initial_conditions)) evolution[1, :] = initial_conditions for i in 2:generations @@ -79,9 +79,11 @@ function CellularAutomaton(rule::AbstractODRule, initial_conditions, generations return CellularAutomaton(generations, rule, evolution) end -function CellularAutomaton(rule::AbstractTDRule, initial_conditions, generations) +function CellularAutomaton( + rule::AbstractTDRule, initial_conditions::AbstractMatrix, generations::Int +) evolution = zeros( - typeof(initial_conditions[2]), + eltype(initial_conditions), size(initial_conditions, 1), size(initial_conditions, 2), generations, @@ -93,4 +95,4 @@ function CellularAutomaton(rule::AbstractTDRule, initial_conditions, generations end return CellularAutomaton(generations, rule, evolution) -end \ No newline at end of file +end diff --git a/src/generics.jl b/src/generics.jl index 3c544f8..9f1886e 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -1,3 +1,3 @@ abstract type AbstractRule end abstract type AbstractODRule <: AbstractRule end -abstract type AbstractTDRule <: AbstractRule end \ No newline at end of file +abstract type AbstractTDRule <: AbstractRule end diff --git a/src/rules/cca.jl b/src/rules/cca.jl index 61332c4..9f2cd38 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -1,8 +1,8 @@ abstract type AbstractCCARule <: AbstractODRule end -struct CCA{T<:Real} <: AbstractCCARule - rule::T - radius::Int +@concrete struct CCA <: AbstractCCARule + rule + radius end """ @@ -37,46 +37,27 @@ next_generation = cca(starting_array) # Evolve to next generation The evolution is determined by the rule applied to the sum of the neighborhood states, normalized by their count, for each cell in the array. """ -function CCA(rule::T; radius=1) where {T<:Real} +function CCA(rule::Real; radius=1) return CCA(rule, radius) end function (cca::CCA)(starting_array::AbstractArray) - return nextgen = evolution(starting_array, cca.rule, cca.radius) + return evolution(starting_array, cca.rule, cca.radius) end -function c_state_reader(neighborhood::AbstractArray, radius) - return sum(neighborhood) / length(neighborhood) -end - -function evolution(cell::AbstractArray, rule::T, radius::Number) where {T<:Real} - neighborhood_size = radius * 2 + 1 - output = zeros(length(cell)) - cell = vcat( - cell[(end - neighborhood_size ÷ 2 + 1):end], cell, cell[1:(neighborhood_size ÷ 2)] - ) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = modf( - c_state_reader(cell[i:(i + neighborhood_size - 1)], radius) + rule - )[1] - end +fractional_part(value) = value - floor(value) - return output +function evolution(cell::AbstractArray, rule::Real, radius::Int) + return evolution(cell, rule, (radius, radius)) end -function evolution(cell::AbstractArray, rule::T, radius::Tuple) where {T<:Real} - neighborhood_size = sum(radius) + 1 - output = zeros(length(cell)) - cell = vcat( - cell[(end - neighborhood_size ÷ 2 + 1):end], cell, cell[1:(neighborhood_size ÷ 2)] - ) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = modf( - c_state_reader(cell[i:(i + neighborhood_size - 1)], radius) + rule - )[1] - end - - return output +function evolution(cell::AbstractArray, rule::Real, radius::Tuple) + left, right = radius + neighborhood_size = left + right + 1 + padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) + return [ + fractional_part( + sum(view(padded, i:(i + neighborhood_size - 1))) / neighborhood_size + rule + ) for i in eachindex(cell) + ] end diff --git a/src/rules/dca.jl b/src/rules/dca.jl index a3ad71a..a5e1661 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -1,10 +1,10 @@ abstract type AbstractDCARule <: AbstractODRule end -struct DCA{T<:Integer,R,P} <: AbstractDCARule - rule::T - ruleset::R +@concrete struct DCA <: AbstractDCARule + rule + ruleset states::Int - radius::P + radius end """ @@ -35,7 +35,7 @@ starting_array = [0, 1, 0, 1, 1, 0] # Initial state next_generation = dca(starting_array) # Evolve to the next generation ``` """ -function DCA(rule::T; states::Int=2, radius=1) where {T<:Integer} +function DCA(rule::Integer; states::Int=2, radius=1) ruleset = conversion(rule, states, radius) return DCA(rule, ruleset, states, radius) end @@ -44,48 +44,34 @@ function (dca::DCA)(starting_array::AbstractArray) return evolution(starting_array, dca.ruleset, dca.states, dca.radius) end -function conversion(rule::T, states::Int, radius::Int) where {T<:Integer} - rule_len = states^(2 * radius + 1) - rule_bin = parse.(Int, split(string(rule; base=states), "")) - rule_bin = vcat(zeros(typeof(rule_bin[1]), rule_len - length(rule_bin)), rule_bin) - return reverse!(rule_bin) +function conversion(rule::Integer, states::Int, radius::Int) + return digits_ruleset(rule, states, states^(2 * radius + 1)) end -function conversion(rule::T, states::Int, radius::Tuple) where {T<:Integer} - rule_len = states^(sum(radius) + 1) - rule_bin = parse.(Int, split(string(rule; base=states), "")) - rule_bin = vcat(zeros(typeof(rule_bin[1]), rule_len - length(rule_bin)), rule_bin) - return reverse!(rule_bin) +function conversion(rule::Integer, states::Int, radius::Tuple) + return digits_ruleset(rule, states, states^(sum(radius) + 1)) end -#still ugly +digits_ruleset(rule::Integer, states::Int, len::Int) = digits(rule; base=states, pad=len) + function state_reader(neighborhood::AbstractArray, states::Int) - joined = join(convert(Array{Int}, neighborhood)) - return parse(Int, String(joined); base=states) + 1 + index = 0 + for cell in neighborhood + index = index * states + Int(cell) + end + return index + 1 end function evolution(cell::AbstractArray, ruleset, states::Int, radius::Int) - neighborhood_size = radius * 2 + 1 - output = zeros(length(cell)) - cell = vcat( - cell[(end - neighborhood_size ÷ 2 + 1):end], cell, cell[1:(neighborhood_size ÷ 2)] - ) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = ruleset[state_reader(cell[i:(i + neighborhood_size - 1)], states)] - end - - return output + return evolution(cell, ruleset, states, (radius, radius)) end function evolution(cell::AbstractArray, ruleset, states::Int, radius::Tuple) - neighborhood_size = sum(radius) + 1 - output = zeros(length(cell))#da qui in poi da modificare - cell = vcat(cell[(end - radius[1] + 1):end], cell, cell[1:radius[2]]) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = ruleset[state_reader(cell[i:(i + neighborhood_size - 1)], states)] - end - - return output + left, right = radius + neighborhood_size = left + right + 1 + padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) + return eltype(cell)[ + ruleset[state_reader(view(padded, i:(i + neighborhood_size - 1)), states)] for + i in eachindex(cell) + ] end diff --git a/src/rules/life.jl b/src/rules/life.jl index b4a681c..eff3ba7 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -1,9 +1,8 @@ - abstract type AbstractLifeRule <: AbstractTDRule end -struct Life{T,A} <: AbstractLifeRule - born::T - survive::A +@concrete struct Life <: AbstractLifeRule + born + survive radius::Int end @@ -44,14 +43,14 @@ life = Life(((3,), (2, 3)); radius=1) starting_array = zeros(Int, 5, 5) starting_array[2, 3] = 1 starting_array[3, 4] = 1 -starting_array[4, 2:4] = 1 +starting_array[4, 2:4] .= 1 # Compute the next generation next_generation = life(starting_array) ``` """ -function Life(life_description::Tuple; radius=1) - born, survive = life_description[1], life_description[2] +function Life(life_description::Tuple; radius::Int=1) + born, survive = life_description return Life(born, survive, radius) end @@ -77,28 +76,27 @@ function virtual_expansion(starting_array::AbstractMatrix, radius::Int) return hcat(left, middle, right) end -function life_application(state, born, survive) - past_value = state[size(state, 1) ÷ 2 + 1, size(state, 2) ÷ 2 + 1] #save past cell value - state[size(state, 1) ÷ 2 + 1, size(state, 2) ÷ 2 + 1] = 0 #past cell value set to zero - alive = sum(state) #the sum is the number of cell alive in the neighborhood since the central value is equal to zero +function life_application(neighborhood::AbstractMatrix, born, survive) + center_i = size(neighborhood, 1) ÷ 2 + 1 + center_j = size(neighborhood, 2) ÷ 2 + 1 + past_value = neighborhood[center_i, center_j] + alive = sum(neighborhood) - past_value - if past_value == 1 && alive in survive - return 1 - elseif past_value == 0 && alive in born - return 1 + if past_value == 1 + return eltype(neighborhood)(alive in survive) else - return 0 + return eltype(neighborhood)(alive in born) end end -function life_evolution(starting_array::AbstractMatrix, born, survive, radius) +function life_evolution(starting_array::AbstractMatrix, born, survive, radius::Int) height, width = size(starting_array) - output = zeros(typeof(starting_array[2]), height, width) - virtual_output = virtual_expansion(starting_array, radius) + output = similar(starting_array) + expanded = virtual_expansion(starting_array, radius) - for i in 1:(height - radius + 1), j in 1:(width - radius + 1) + for j in 1:width, i in 1:height output[i, j] = life_application( - virtual_output[i:(i + radius + 1), j:(j + radius + 1)], born, survive + expanded[i:(i + 2 * radius), j:(j + 2 * radius)], born, survive ) end return output diff --git a/src/rules/tca.jl b/src/rules/tca.jl index 71c21fb..7c3a0d5 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -1,10 +1,10 @@ abstract type AbstractTCARule <: AbstractDCARule end -struct TCA{B,R,T} <: AbstractTCARule - code::B - codeset::R +@concrete struct TCA <: AbstractTCARule + code + codeset states::Int - radius::T + radius end """ @@ -16,7 +16,7 @@ and configuration, which is used for the automaton's evolution. # Arguments - - `code`: An integer or string representing the rule code for the automaton's evolution. + - `code`: An integer representing the rule code for the automaton's evolution. - `states` (optional): The number of possible states for each cell. Defaults to 2. - `radius` (optional): The neighborhood radius around each cell considered during the evolution. Defaults to 1. @@ -41,59 +41,35 @@ starting_array = [0, 2, 1, 0, 1, 2] next_generation = tca(starting_array) ``` """ -function TCA(code; states=2, radius=1) +function TCA(code::Integer; states::Int=2, radius=1) codeset = tca_conversion(code, states, radius) return TCA(code, codeset, states, radius) end function (tca::TCA)(starting_array::AbstractArray) - return nextgen = tca_evolution(starting_array, tca.codeset, tca.states, tca.radius) + return tca_evolution(starting_array, tca.codeset, tca.states, tca.radius) end -function tca_conversion(code, states, radius::Number) - code_len = (2 * radius + 1) * states - 2 - code_bin = parse.(Int, split(string(code; base=states), "")) - code_bin = vcat(zeros(typeof(code_bin[1]), code_len - length(code_bin)), code_bin) - return reverse!(code_bin) +function tca_conversion(code::Integer, states::Int, radius::Int) + return digits_ruleset(code, states, (states - 1) * (2 * radius + 1) + 1) end -function tca_conversion(code, states, radius::Tuple) - code_len = (sum(radius) + 1) * states - 2 - code_bin = parse.(Int, split(string(code; base=states), "")) - code_bin = vcat(zeros(typeof(code_bin[1]), code_len - length(code_bin)), code_bin) - return reverse!(code_bin) +function tca_conversion(code::Integer, states::Int, radius::Tuple) + return digits_ruleset(code, states, (states - 1) * (sum(radius) + 1) + 1) end -function tca_state_reader(neighborhood::AbstractArray, codeset_len) - return mod1(sum(neighborhood) + 1, codeset_len) -end - -function tca_evolution(cell::AbstractArray, codeset, states, radius::Number) - neighborhood_size = radius * 2 + 1 - output = zeros(length(cell)) - cell = vcat( - cell[(end - neighborhood_size ÷ 2 + 1):end], cell, cell[1:(neighborhood_size ÷ 2)] - ) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = codeset[tca_state_reader( - cell[i:(i + neighborhood_size - 1)], length(codeset) - )] - end +tca_state_reader(neighborhood::AbstractArray) = Int(sum(neighborhood)) + 1 - return output +function tca_evolution(cell::AbstractArray, codeset, states::Int, radius::Int) + return tca_evolution(cell, codeset, states, (radius, radius)) end -function tca_evolution(cell::AbstractArray, codeset, states, radius::Tuple) - neighborhood_size = sum(radius) + 1 - output = zeros(length(cell)) - cell = vcat(cell[(end - radius[1] + 1):end], cell, cell[1:radius[2]]) - - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = codeset[tca_state_reader( - cell[i:(i + neighborhood_size - 1)], length(codeset) - )] - end - - return output +function tca_evolution(cell::AbstractArray, codeset, states::Int, radius::Tuple) + left, right = radius + neighborhood_size = left + right + 1 + padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) + return eltype(cell)[ + codeset[tca_state_reader(view(padded, i:(i + neighborhood_size - 1)))] for + i in eachindex(cell) + ] end diff --git a/test/ad_test.jl b/test/ad_test.jl new file mode 100644 index 0000000..adc9162 --- /dev/null +++ b/test/ad_test.jl @@ -0,0 +1,20 @@ +using CellularAutomata +using ForwardDiff +using Test + +const generations = 5 +const ncells = 11 +const x0 = collect(range(0.1, 0.9; length=ncells)) + +function final_state_loss(x) + ca = CellularAutomaton(CCA(0.45), x, generations) + return sum(abs2, ca.evolution[end, :]) +end + +grad = ForwardDiff.gradient(final_state_loss, x0) +@test length(grad) == ncells +@test any(!iszero, grad) + +# eltype is preserved through the evolution (no hardcoded Float64) +ca32 = CellularAutomaton(CCA(0.45f0), rand(Float32, ncells), generations) +@test eltype(ca32.evolution) == Float32 diff --git a/test/runtests.jl b/test/runtests.jl index 0861cdf..d0aa0b6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -18,6 +18,10 @@ end @safetestset "Size tests" include("cca_test.jl") end +@testset "AD" begin + @safetestset "ForwardDiff through CCA" include("ad_test.jl") +end + @testset "Life-like" begin @safetestset "Life glider" include("glider_test.jl") @safetestset "Life blinker" include("blinker_test.jl") From a6c72a68f729f0e8642f132f31b675bdf33c630b Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 11:35:58 +0200 Subject: [PATCH 2/8] refac: adopt functional core and boundary conditions from codex review Comparison with the fm/codex work (stashed): adopt its stronger design pieces, keep this branch's kernel implementations. Adopted: - Descriptive abstract type names (AbstractCellularAutomatonRule and the per-family supertypes) replacing AbstractODRule/AbstractTDRule - Pure next_state(rule, state; boundary) + rollout(rule, state, steps; save) functional core; CellularAutomaton is now a wrapper over rollout with no in-place history writes - Boundary condition types Periodic/Reflecting/ConstantBoundary with shared Neighborhood1D access (replaces vcat padding and the Life virtual expansion) - Constructor validation (rule fit, states, radius, generations) - spatial_dimensions trait, regression tests, boundary/rollout AD tests, ad_design.md and docs wiring Kept over codex: digits()-based ruleset conversion (its string parsing breaks for states > 10), x - floor(x) for ForwardDiff, closures instead of callable Update structs. Renamed DCA/CCA kernels to dca_evolution/ cca_evolution to resolve a method ambiguity the shared name caused. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- docs/pages.jl | 1 + docs/src/ad_design.md | 78 +++++++++++++++++ docs/src/api/general.md | 15 ++++ src/CellularAutomata.jl | 7 ++ src/cellular_automaton.jl | 170 +++++++++++++++++++++++--------------- src/generics.jl | 99 +++++++++++++++++++++- src/measures.jl | 6 +- src/rules/cca.jl | 71 ++++++++-------- src/rules/dca.jl | 89 ++++++++++++-------- src/rules/life.jl | 120 +++++++++++---------------- src/rules/tca.jl | 84 ++++++++++--------- test/ad_test.jl | 50 ++++++++--- test/regression_test.jl | 55 ++++++++++++ test/runtests.jl | 4 + 14 files changed, 586 insertions(+), 263 deletions(-) create mode 100644 docs/src/ad_design.md create mode 100644 test/regression_test.jl diff --git a/docs/pages.jl b/docs/pages.jl index 6dbd394..6da3010 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -1,5 +1,6 @@ pages = [ "CellularAutomata.jl" => "index.md", + "Differentiable cellular automata" => "ad_design.md", "Examples" => [ "One dimensional CA" => "onedim/onedimensionca.md" "Two dimensional CA" => "twodim/twodimensionca.md" diff --git a/docs/src/ad_design.md b/docs/src/ad_design.md new file mode 100644 index 0000000..c848f31 --- /dev/null +++ b/docs/src/ad_design.md @@ -0,0 +1,78 @@ +# Differentiable cellular automata design + +The rule objects are the user-facing abstraction, but simulation and history +allocation are separated from the local transition. This makes the transition usable +by automatic differentiation (AD), GPU arrays, and neural cellular automata (NCA) +without changing the existing discrete-rule API. + +## Functional core API + +```julia +next_state(rule, state; boundary=Periodic()) -> state +rollout(rule, state, steps; boundary=Periodic(), save=false) -> result +``` + +`next_state` is a pure function: it does not mutate `state` or captured parameter +arrays. `rollout` is the orchestration layer. It returns the final state by default, +which is the preferred path inside a loss function. With `save=true`, it returns the +initial state and all subsequent states with time on the last axis. +`CellularAutomaton` remains a compatibility wrapper and preserves its original +history layout. + +Boundary behavior is represented by small types — `Periodic`, `Reflecting`, and +`ConstantBoundary` — rather than being embedded in every rule implementation. +Neighborhood extraction is likewise shared across rules. + +## State and rule representation + +Discrete automata accept vectors and matrices. Differentiable rules need a documented +channel convention; `channels × spatial... × batch` maps naturally to Julia's +column-major arrays and common Julia ML tooling. Code dispatches on `AbstractArray` +and never forces `Array` or `Float64`, so dual numbers and GPU arrays flow through +unchanged. + +An NCA rule can subtype `AbstractCellularAutomatonRule` and contain a perception +operator and update network. ConcreteStructs keeps its parameter fields concretely +typed without manual type parameters: + +```julia +using ConcreteStructs: @concrete + +@concrete struct NeuralRule <: AbstractCellularAutomatonRule + perceive + update +end + +spatial_dimensions(::NeuralRule) = 2 + +function CellularAutomata.next_state(rule::NeuralRule, x; boundary=Periodic()) + features = rule.perceive(x, boundary) + return x + rule.update(features) +end +``` + +Trainable parameter discovery should be provided through the interface of the chosen +ML ecosystem (for example Functors.jl), while the core simulator does not depend on a +specific AD backend. Avoid custom derivative rules until profiling identifies an +operation for which generic AD is inadequate; then define a ChainRulesCore rule at +that narrow boundary. + +## Migration sequence + + 1. **Implemented:** pure `next_state`, functional `rollout`, explicit boundary types, + shared neighborhood access, compatibility through `CellularAutomaton`, and + multi-step ForwardDiff coverage. Lookup-based DCA/TCA and thresholded Life rules + remain intentionally nondifferentiable. + 2. Test reverse-mode AD and GPU arrays after selecting the package's supported ML + stack. + 3. Add a generic continuous multidimensional local rule with a documented + `channels × spatial... × batch` layout. + 4. Add an optional package extension for the selected neural-network stack with + `NeuralRule`, trainable-parameter integration, batched states, and GPU tests. + 5. Add checkpointed rollout or a custom reverse rule only when long unrolls show + unacceptable memory use. + +The important architectural boundary is that the simulator owns time and boundary +handling, while a rule owns only a single local state transition. That keeps +classical automata simple and gives learned rules a small, composable, +differentiable surface. diff --git a/docs/src/api/general.md b/docs/src/api/general.md index 84dff5a..7ec6f18 100644 --- a/docs/src/api/general.md +++ b/docs/src/api/general.md @@ -1,4 +1,19 @@ # General APIs + ```@docs CellularAutomaton + next_state + rollout + Periodic + Reflecting + ConstantBoundary + AbstractCellularAutomaton + AbstractCellularAutomatonRule + AbstractBoundaryCondition + AbstractDiscreteCellularAutomatonRule + AbstractContinuousCellularAutomatonRule + AbstractTotalisticCellularAutomatonRule + AbstractLifeLikeCellularAutomatonRule + spatial_dimensions + lempel_ziv ``` diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index 3290d19..cb7e376 100644 --- a/src/CellularAutomata.jl +++ b/src/CellularAutomata.jl @@ -10,7 +10,14 @@ include("rules/tca.jl") include("rules/life.jl") include("measures.jl") +export AbstractCellularAutomaton, AbstractCellularAutomatonRule +export AbstractBoundaryCondition, Periodic, Reflecting, ConstantBoundary +export AbstractDiscreteCellularAutomatonRule +export AbstractContinuousCellularAutomatonRule +export AbstractTotalisticCellularAutomatonRule +export AbstractLifeLikeCellularAutomatonRule export CellularAutomaton +export next_state, rollout, spatial_dimensions export DCA export CCA export TCA diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index 7e50bc1..b11fe65 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -1,98 +1,138 @@ -abstract type AbstractCA end +""" + AbstractCellularAutomaton + +Supertype for cellular automata that retain an evolution history. +""" +abstract type AbstractCellularAutomaton end """ - CellularAutomaton(rule::AbstractODRule, initial_conditions, generations) - CellularAutomaton(rule::AbstractTDRule, initial_conditions, generations) + next_state(rule, state; boundary=Periodic()) -Constructs the evolution of a cellular automaton based on a specified rule, -initial conditions, and the number of generations to simulate. -This function supports both one-dimensional (OD) and two-dimensional (TD) cellular automata, -determined by the type of `rule` provided. +Apply one synchronous cellular-automaton transition without mutating `state`. +Rules may specialize this function to define differentiable transitions. # Arguments - - `rule`: An instance of `AbstractODRule` for one-dimensional cellular automata - or `AbstractTDRule` for two-dimensional cellular automata. Defines the evolution - rule for the cellular automaton. - - `initial_conditions`: An array (for OD) or a matrix (for TD) representing the - initial state of the cellular automaton. - - `generations`: The number of generations (or time steps) for which the automaton - should be evolved. + - `rule`: Cellular-automaton transition rule. + - `state`: Current state array. -# Usage +# Keyword arguments -For a one-dimensional cellular automaton: + - `boundary`: Boundary condition used outside the state array. + Defaults to `Periodic()`. + +# Examples ```julia -rule = DCA(30) # Define or instantiate a one-dimensional rule -initial_conditions = [0, 1, 0, 1, 1, 0, 1] # Initial state array -generations = 50 # Number of generations to simulate -automaton_od = CellularAutomaton(rule, initial_conditions, generations) +julia> next_state(DCA(30), [0, 0, 1, 0, 0]) +5-element Vector{Int64}: + 0 + 1 + 1 + 1 + 0 ``` +""" +function next_state( + rule::AbstractCellularAutomatonRule, + state; + boundary::AbstractBoundaryCondition=Periodic(), +) + return _step(rule, state, boundary) +end -For a two-dimensional cellular automaton: +""" + rollout(rule, initial_state, steps; boundary=Periodic(), save=false) -```julia -rule = Life(((3,), (2, 3))) # Define or instantiate a two-dimensional rule -initial_conditions = [ # Initial state matrix - 0 1 0 - 1 0 1 - 0 1 0 -] -generations = 50 # Number of generations to simulate -automaton_td = CellularAutomaton(rule, initial_conditions, generations) -``` +Apply `steps` transitions of `rule` to `initial_state`. By default only the final +state is returned, which is the preferred path inside a loss function. With +`save=true`, return the initial state and every subsequent state stacked with time +on the last axis. + +# Arguments + + - `rule`: Cellular-automaton transition rule. + - `initial_state`: State from which to begin the rollout. + - `steps`: Number of transitions to apply. -This function constructs a CellularAutomaton instance that encapsulates the -entire evolution history of the cellular automaton, according to the provided -rule and initial conditions over the specified number of generations. -The exact nature of the evolution—whether it is for a one-dimensional or -two-dimensional automaton—depends on the type of rule supplied. +# Keyword arguments -You can access the evolution by calling the `evolution` field of `CellularAutomaton` + - `boundary`: Boundary condition used by each transition. Defaults to `Periodic()`. + - `save`: Retain the initial state and every subsequent state. Defaults to `false`. + +# Examples ```julia -automaton_td.evolution +julia> history = rollout(DCA(30), [0, 0, 1, 0, 0], 2; save=true); + +julia> size(history) +(5, 3) ``` +""" +function rollout( + rule::AbstractCellularAutomatonRule, + initial_state, + steps::Integer; + boundary::AbstractBoundaryCondition=Periodic(), + save::Bool=false, +) + steps >= 0 || throw(ArgumentError("steps must be nonnegative")) + isempty(initial_state) && throw(ArgumentError("initial_state cannot be empty")) + transition = (state, _) -> next_state(rule, state; boundary=boundary) + if save + states = accumulate(transition, 1:steps; init=initial_state) + return stack(Iterators.flatten(((initial_state,), states))) + end + return foldl(transition, 1:steps; init=initial_state) +end + +""" + CellularAutomaton(rule, initial_conditions, generations) + +Construct a cellular automaton and retain its complete evolution history. For vector +states, `evolution` stores time on the first axis. For higher-dimensional states, +time is stored on the last axis. + +# Arguments + + - `rule`: Cellular-automaton rule defining one transition. + - `initial_conditions`: Initial state array. + - `generations`: Number of retained generations, including the initial state. -# Notes +# Examples - - The `rule` parameter determines the dimensionality of the cellular automaton. - Ensure that your `initial_conditions` and `rule` are compatible in terms of dimensions. +```julia +julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3); + +julia> automaton.evolution +3×3 Matrix{Int64}: + 0 1 0 + 1 1 1 + 0 0 0 +``` """ -@concrete struct CellularAutomaton <: AbstractCA +@concrete struct CellularAutomaton <: AbstractCellularAutomaton generations::Int generation_fun evolution end function CellularAutomaton( - rule::AbstractODRule, initial_conditions::AbstractVector, generations::Int + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractVector, + generations::Integer, ) - evolution = zeros(eltype(initial_conditions), generations, length(initial_conditions)) - evolution[1, :] = initial_conditions - - for i in 2:generations - evolution[i, :] = rule(evolution[i - 1, :]) - end - - return CellularAutomaton(generations, rule, evolution) + generations >= 1 || throw(ArgumentError("generations must be at least 1")) + history = rollout(rule, initial_conditions, generations - 1; save=true) + return CellularAutomaton(Int(generations), rule, permutedims(history)) end function CellularAutomaton( - rule::AbstractTDRule, initial_conditions::AbstractMatrix, generations::Int + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractArray, + generations::Integer, ) - evolution = zeros( - eltype(initial_conditions), - size(initial_conditions, 1), - size(initial_conditions, 2), - generations, - ) - evolution[:, :, 1] = initial_conditions - - for i in 2:generations - evolution[:, :, i] = rule(evolution[:, :, i - 1]) - end - - return CellularAutomaton(generations, rule, evolution) + generations >= 1 || throw(ArgumentError("generations must be at least 1")) + evolution = rollout(rule, initial_conditions, generations - 1; save=true) + return CellularAutomaton(Int(generations), rule, evolution) end diff --git a/src/generics.jl b/src/generics.jl index 9f1886e..aef3193 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -1,3 +1,96 @@ -abstract type AbstractRule end -abstract type AbstractODRule <: AbstractRule end -abstract type AbstractTDRule <: AbstractRule end +""" + AbstractCellularAutomatonRule + +Supertype for cellular-automaton transition rules. Subtypes must implement +`_step(rule, state, boundary)` returning the next state without mutating `state`, +or specialize [`next_state`](@ref) directly. +""" +abstract type AbstractCellularAutomatonRule end + +""" + AbstractBoundaryCondition + +Supertype for boundary conditions used when neighborhoods cross state-array edges. +""" +abstract type AbstractBoundaryCondition end + +""" + Periodic() + +Wrap indices around the opposite edge of the state array. +""" +struct Periodic <: AbstractBoundaryCondition end + +""" + Reflecting() + +Mirror indices at the edge of the state array. +""" +struct Reflecting <: AbstractBoundaryCondition end + +""" + ConstantBoundary([value = 0]) + +Use `value` for indices outside the state array. +""" +@concrete struct ConstantBoundary <: AbstractBoundaryCondition + value +end + +ConstantBoundary() = ConstantBoundary(0) + +@inline _boundary_index(i, n, ::Periodic) = mod1(i, n) +@inline function _boundary_index(i, n, ::Reflecting) + n == 1 && return 1 + reflected = mod(i - 1, 2n - 2) + 1 + return reflected <= n ? reflected : 2n - reflected +end + +@inline function _boundary_get(array, boundary::Union{Periodic,Reflecting}, i) + return array[_boundary_index(i, length(array), boundary)] +end +@inline function _boundary_get(array, boundary::Union{Periodic,Reflecting}, i, j) + row = _boundary_index(i, size(array, 1), boundary) + column = _boundary_index(j, size(array, 2), boundary) + return array[row, column] +end +@inline function _boundary_get(array, boundary::ConstantBoundary, i) + return checkbounds(Bool, array, i) ? array[i] : boundary.value +end +@inline function _boundary_get(array, boundary::ConstantBoundary, i, j) + return checkbounds(Bool, array, i, j) ? array[i, j] : boundary.value +end + +@concrete struct Neighborhood1D + array + boundary + indices +end + +Base.length(neighborhood::Neighborhood1D) = length(neighborhood.indices) +Base.IteratorSize(::Type{<:Neighborhood1D}) = Base.HasLength() +function Base.iterate(neighborhood::Neighborhood1D, state...) + iteration = iterate(neighborhood.indices, state...) + isnothing(iteration) && return nothing + index, next_iteration = iteration + return _boundary_get(neighborhood.array, neighborhood.boundary, index), next_iteration +end + +_radius_extent(radius::Integer) = (radius, radius) +_radius_extent(radius::Tuple{<:Integer,<:Integer}) = radius + +function _validate_radius(radius) + left, right = _radius_extent(radius) + if left < 0 || right < 0 + throw(ArgumentError("radius must be nonnegative")) + end + return nothing +end + +""" + spatial_dimensions(rule) + +Return the number of spatial dimensions used by a cellular-automaton rule. State arrays +may have additional channel or batch dimensions. +""" +function spatial_dimensions end diff --git a/src/measures.jl b/src/measures.jl index e551f78..7be43c9 100644 --- a/src/measures.jl +++ b/src/measures.jl @@ -21,11 +21,11 @@ function lempel_ziv_complexity(sequence) end """ - function lempel_ziv(ca::AbstractCA) + lempel_ziv(ca::AbstractCellularAutomaton) -Computes the lempel ziv complexity of a given Cellular Automaton. +Compute the mean Lempel-Ziv complexity across rows of an automaton's retained evolution. """ -function lempel_ziv(ca::AbstractCA) +function lempel_ziv(ca::AbstractCellularAutomaton) ca_size = size(ca.evolution, 1) lz_tot = 0 diff --git a/src/rules/cca.jl b/src/rules/cca.jl index 9f2cd38..8b5d335 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -1,63 +1,68 @@ -abstract type AbstractCCARule <: AbstractODRule end +""" + AbstractContinuousCellularAutomatonRule + +Supertype for cellular-automaton rules with continuous cell states. +""" +abstract type AbstractContinuousCellularAutomatonRule <: AbstractCellularAutomatonRule end -@concrete struct CCA <: AbstractCCARule +@concrete struct CCA <: AbstractContinuousCellularAutomatonRule rule radius end +spatial_dimensions(::CCA) = 1 + """ CCA(rule; radius=1) -Create a Continuous Cellular Automaton (CCA) object. +Construct a continuous cellular-automaton rule. Each output is the fractional part +of the neighborhood mean plus `rule`. # Arguments - - `rule`: A numeric code defining the evolution rule for the cellular automaton. - - `radius` (optional): The radius of the neighborhood around each cell considered - for its update at each step. Defaults to `1`. + - `rule`: Value added to each neighborhood mean. -# Returns +# Keyword arguments -`CCA`: A `CCA` object initialized with the given rule and radius. + - `radius`: Symmetric radius or `(left, right)` asymmetric radius. Defaults to 1. # Examples ```julia -cca = CCA(0.5) +julia> cca = CCA(0.45; radius=1); + +julia> next_state(cca, [0.0, 1.0, 0.0, 1.0, 0.5, 1.0]) +6-element Vector{Float64}: + 0.7833333333333333 + 0.7833333333333333 + 0.11666666666666664 + 0.95 + 0.2833333333333333 + 0.95 ``` - -Once created, the `CCA` object can be used to evolve a given starting array of cell states: - -```julia -cca = CCA(0.45; radius=1) # Initialize with rule 0.45 and default radius -starting_array = [0, 1, 0, 1, 0.5, 1] # Initial state -next_generation = cca(starting_array) # Evolve to next generation -``` - -The evolution is determined by the rule applied to the sum of the neighborhood states, -normalized by their count, for each cell in the array. """ function CCA(rule::Real; radius=1) + _validate_radius(radius) return CCA(rule, radius) end function (cca::CCA)(starting_array::AbstractArray) - return evolution(starting_array, cca.rule, cca.radius) + return next_state(cca, starting_array) end -fractional_part(value) = value - floor(value) - -function evolution(cell::AbstractArray, rule::Real, radius::Int) - return evolution(cell, rule, (radius, radius)) +function _step(cca::CCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return cca_evolution(cell, cca.rule, cca.radius, boundary) end -function evolution(cell::AbstractArray, rule::Real, radius::Tuple) - left, right = radius +fractional_part(value) = value - floor(value) + +function cca_evolution( + cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition=Periodic() +) + left, right = _radius_extent(radius) neighborhood_size = left + right + 1 - padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) - return [ - fractional_part( - sum(view(padded, i:(i + neighborhood_size - 1))) / neighborhood_size + rule - ) for i in eachindex(cell) - ] + return map(eachindex(cell)) do i + neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) + return fractional_part(sum(neighborhood) / neighborhood_size + rule) + end end diff --git a/src/rules/dca.jl b/src/rules/dca.jl index a5e1661..16361a2 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -1,60 +1,77 @@ -abstract type AbstractDCARule <: AbstractODRule end +""" + AbstractDiscreteCellularAutomatonRule + +Supertype for cellular-automaton rules based on discrete neighborhood lookup tables. +""" +abstract type AbstractDiscreteCellularAutomatonRule <: AbstractCellularAutomatonRule end -@concrete struct DCA <: AbstractDCARule +@concrete struct DCA <: AbstractDiscreteCellularAutomatonRule rule ruleset states::Int radius end +spatial_dimensions(::DCA) = 1 + """ DCA(rule; states=2, radius=1) -Creates a `DCA` object given a specific rule. It automatically computes the ruleset for -the provided rule, number of states, and radius. +Construct a discrete cellular-automaton rule and its neighborhood lookup table. # Arguments - - `rule`: The rule identifier used for the cellular automaton's evolution. - - `states` (optional): The number of possible states for each cell. Defaults to 2. - - `radius` (optional): The neighborhood radius around each cell considered during the - evolution. Defaults to 1. + - `rule`: Nonnegative Wolfram rule identifier. -# Usage +# Keyword arguments -```julia -dca = DCA(30; states=2, radius=1) # Creates a DCA with rule 30, 2 states, and radius 1. -``` + - `states`: Number of possible cell states. Defaults to 2. + - `radius`: Symmetric radius or `(left, right)` asymmetric radius. Defaults to 1. -Once instantiated, the `DCA` object can evolve a given starting array of cell states -through its callable interface: +# Examples ```julia -dca = DCA(110; states=2, radius=1) # Initialize with rule 110, 2 states, and a radius of 1 -starting_array = [0, 1, 0, 1, 1, 0] # Initial state -next_generation = dca(starting_array) # Evolve to the next generation +julia> dca = DCA(110; states=2, radius=1); + +julia> next_state(dca, [0, 1, 0, 1, 1, 0]) +6-element Vector{Int64}: + 1 + 1 + 1 + 1 + 1 + 0 ``` """ function DCA(rule::Integer; states::Int=2, radius=1) + states >= 2 || throw(ArgumentError("states must be at least 2")) + _validate_radius(radius) ruleset = conversion(rule, states, radius) return DCA(rule, ruleset, states, radius) end function (dca::DCA)(starting_array::AbstractArray) - return evolution(starting_array, dca.ruleset, dca.states, dca.radius) + return next_state(dca, starting_array) end -function conversion(rule::Integer, states::Int, radius::Int) - return digits_ruleset(rule, states, states^(2 * radius + 1)) +function _step(dca::DCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return dca_evolution(cell, dca.ruleset, dca.states, dca.radius, boundary) end -function conversion(rule::Integer, states::Int, radius::Tuple) - return digits_ruleset(rule, states, states^(sum(radius) + 1)) +function conversion(rule::Integer, states::Int, radius) + left, right = _radius_extent(radius) + return digits_ruleset(rule, states, states^(left + right + 1)) end -digits_ruleset(rule::Integer, states::Int, len::Int) = digits(rule; base=states, pad=len) +function digits_ruleset(rule::Integer, states::Int, len::Int) + rule >= 0 || throw(ArgumentError("rule must be nonnegative")) + ruleset = digits(rule; base=states, pad=len) + length(ruleset) <= len || + throw(ArgumentError("rule does not fit the requested states and radius")) + return ruleset +end -function state_reader(neighborhood::AbstractArray, states::Int) +function state_reader(neighborhood, states::Int) index = 0 for cell in neighborhood index = index * states + Int(cell) @@ -62,16 +79,16 @@ function state_reader(neighborhood::AbstractArray, states::Int) return index + 1 end -function evolution(cell::AbstractArray, ruleset, states::Int, radius::Int) - return evolution(cell, ruleset, states, (radius, radius)) -end - -function evolution(cell::AbstractArray, ruleset, states::Int, radius::Tuple) - left, right = radius - neighborhood_size = left + right + 1 - padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) - return eltype(cell)[ - ruleset[state_reader(view(padded, i:(i + neighborhood_size - 1)), states)] for - i in eachindex(cell) - ] +function dca_evolution( + cell::AbstractVector, + ruleset, + states::Int, + radius, + boundary::AbstractBoundaryCondition=Periodic(), +) + left, right = _radius_extent(radius) + return map(eachindex(cell)) do i + neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) + return convert(eltype(cell), ruleset[state_reader(neighborhood, states)]) + end end diff --git a/src/rules/life.jl b/src/rules/life.jl index eff3ba7..21cca7f 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -1,103 +1,83 @@ -abstract type AbstractLifeRule <: AbstractTDRule end +""" + AbstractLifeLikeCellularAutomatonRule + +Supertype for Life-like cellular-automaton rules. +""" +abstract type AbstractLifeLikeCellularAutomatonRule <: AbstractCellularAutomatonRule end -@concrete struct Life <: AbstractLifeRule +@concrete struct Life <: AbstractLifeLikeCellularAutomatonRule born survive radius::Int end +spatial_dimensions(::Life) = 2 + """ Life(life_description; radius=1) -Create a `Life` object to simulate a cellular automaton based on a variation of -the Conway's Game of Life, using custom rules for cell birth and survival. -The rules are defined using the Golly notation. +Construct a Life-like cellular-automaton rule using Golly birth/survival notation. # Arguments - - `life_description`: A tuple of two tuples (`(b, s)`) specifying the birth (`b`) - and survival (`s`) rules. + - `life_description`: `(born, survive)` neighbor counts. `born` contains counts that + activate a dead cell; `survive` contains counts that preserve a live cell. - + `b`: A tuple containing the numbers of neighbouring cells that cause a dead - cell to become alive in the next generation. - + `s`: A tuple containing the numbers of neighbouring cells that allow a live - cell to remain alive in the next generation. +# Keyword arguments - - `radius` (optional): The radius of the neighborhood considered for determining - cell fate. Defaults to 1. + - `radius`: Radius of the square neighborhood. Defaults to 1. -# Usage +# Examples ```julia -life = Life(((3,), (2, 3)); radius=1) # Initializes Life -``` - -After instantiation, the `Life` object can be used to evolve a given starting -array representing the initial state of the cellular automaton: +julia> life = Life(((3,), (2, 3)); radius=1); -```julia -# Initialize Life with custom rules: birth if 3 neighbors, survive if 2 or 3 neighbors -life = Life(((3,), (2, 3)); radius=1) +julia> blinker = [0 0 0 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 0 0 0]; -# Example starting state: a 5x5 grid with a "glider" pattern -starting_array = zeros(Int, 5, 5) -starting_array[2, 3] = 1 -starting_array[3, 4] = 1 -starting_array[4, 2:4] .= 1 - -# Compute the next generation -next_generation = life(starting_array) +julia> next_state(life, blinker) +5×5 Matrix{Int64}: + 0 0 0 0 0 + 0 0 0 0 0 + 0 1 1 1 0 + 0 0 0 0 0 + 0 0 0 0 0 ``` """ function Life(life_description::Tuple; radius::Int=1) + radius >= 1 || throw(ArgumentError("radius must be at least 1")) born, survive = life_description return Life(born, survive, radius) end function (life::Life)(starting_array::AbstractMatrix) - return life_evolution(starting_array, life.born, life.survive, life.radius) -end - -function virtual_expansion(starting_array::AbstractMatrix, radius::Int) - height, width = size(starting_array) - nh, nw = height - radius + 1, width - radius + 1 - left = vcat( - starting_array[nh:end, nw:end], - starting_array[:, nw:end], - starting_array[1:radius, nw:end], - ) - right = vcat( - starting_array[nh:end, 1:radius], - starting_array[:, 1:radius], - starting_array[1:radius, 1:radius], - ) - middle = vcat(starting_array[nh:end, :], starting_array, starting_array[1:radius, :]) - - return hcat(left, middle, right) + return next_state(life, starting_array) end -function life_application(neighborhood::AbstractMatrix, born, survive) - center_i = size(neighborhood, 1) ÷ 2 + 1 - center_j = size(neighborhood, 2) ÷ 2 + 1 - past_value = neighborhood[center_i, center_j] - alive = sum(neighborhood) - past_value - - if past_value == 1 - return eltype(neighborhood)(alive in survive) - else - return eltype(neighborhood)(alive in born) - end +function _step(life::Life, state::AbstractMatrix, boundary::AbstractBoundaryCondition) + return life_evolution(state, life.born, life.survive, life.radius, boundary) end -function life_evolution(starting_array::AbstractMatrix, born, survive, radius::Int) - height, width = size(starting_array) - output = similar(starting_array) - expanded = virtual_expansion(starting_array, radius) - - for j in 1:width, i in 1:height - output[i, j] = life_application( - expanded[i:(i + 2 * radius), j:(j + 2 * radius)], born, survive - ) +function life_evolution( + starting_array::AbstractMatrix, + born, + survive, + radius::Int, + boundary::AbstractBoundaryCondition=Periodic(), +) + return map(CartesianIndices(starting_array)) do index + row, column = Tuple(index) + alive = 0 + for column_offset in (-radius):radius, row_offset in (-radius):radius + if !iszero(row_offset) || !iszero(column_offset) + alive += Int( + _boundary_get( + starting_array, boundary, row + row_offset, column + column_offset + ), + ) + end + end + current = starting_array[index] + lives = (isone(current) && alive in survive) || (iszero(current) && alive in born) + return convert(eltype(starting_array), lives) end - return output end diff --git a/src/rules/tca.jl b/src/rules/tca.jl index 7c3a0d5..dbd8e47 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -1,75 +1,77 @@ -abstract type AbstractTCARule <: AbstractDCARule end +""" + AbstractTotalisticCellularAutomatonRule + +Supertype for rules whose transitions depend on the total neighborhood state. +""" +abstract type AbstractTotalisticCellularAutomatonRule <: + AbstractDiscreteCellularAutomatonRule end -@concrete struct TCA <: AbstractTCARule +@concrete struct TCA <: AbstractTotalisticCellularAutomatonRule code codeset states::Int radius end +spatial_dimensions(::TCA) = 1 + """ TCA(code; states=2, radius=1) -Constructs a Totalistic Cellular Automaton (TCA) with a specified code, number of states, -and neighborhood radius. It automatically computes the codeset for the provided code -and configuration, which is used for the automaton's evolution. +Construct a totalistic cellular-automaton rule and its lookup table. # Arguments - - `code`: An integer representing the rule code for the automaton's evolution. - - `states` (optional): The number of possible states for each cell. Defaults to 2. - - `radius` (optional): The neighborhood radius around each cell considered during the - evolution. Defaults to 1. + - `code`: Nonnegative totalistic rule identifier. -# Usage +# Keyword arguments -```julia -tca = TCA(30; states=2, radius=1) # Creates a TCA with rule code 30, 2 states, and radius 1. -``` + - `states`: Number of possible cell states. Defaults to 2. + - `radius`: Symmetric radius or `(left, right)` asymmetric radius. Defaults to 1. -After instantiation, the `TCA` object can be used to evolve a given starting array of -cell states: +# Examples ```julia -# Initialize TCA with a specific code, default states, and radius -tca = TCA(102; states=3, radius=1) - -# Example starting state: a 1D array of cells -starting_array = [0, 2, 1, 0, 1, 2] - -# Compute the next generation -next_generation = tca(starting_array) +julia> tca = TCA(102; states=3, radius=1); + +julia> next_state(tca, [0, 2, 1, 0, 1, 2]) +6-element Vector{Int64}: + 1 + 0 + 0 + 1 + 0 + 0 ``` """ function TCA(code::Integer; states::Int=2, radius=1) + states >= 2 || throw(ArgumentError("states must be at least 2")) + _validate_radius(radius) codeset = tca_conversion(code, states, radius) return TCA(code, codeset, states, radius) end function (tca::TCA)(starting_array::AbstractArray) - return tca_evolution(starting_array, tca.codeset, tca.states, tca.radius) + return next_state(tca, starting_array) end -function tca_conversion(code::Integer, states::Int, radius::Int) - return digits_ruleset(code, states, (states - 1) * (2 * radius + 1) + 1) +function _step(tca::TCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return tca_evolution(cell, tca.codeset, tca.radius, boundary) end -function tca_conversion(code::Integer, states::Int, radius::Tuple) - return digits_ruleset(code, states, (states - 1) * (sum(radius) + 1) + 1) +function tca_conversion(code::Integer, states::Int, radius) + left, right = _radius_extent(radius) + return digits_ruleset(code, states, (states - 1) * (left + right + 1) + 1) end -tca_state_reader(neighborhood::AbstractArray) = Int(sum(neighborhood)) + 1 - -function tca_evolution(cell::AbstractArray, codeset, states::Int, radius::Int) - return tca_evolution(cell, codeset, states, (radius, radius)) -end +tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 -function tca_evolution(cell::AbstractArray, codeset, states::Int, radius::Tuple) - left, right = radius - neighborhood_size = left + right + 1 - padded = vcat(cell[(end - left + 1):end], cell, cell[1:right]) - return eltype(cell)[ - codeset[tca_state_reader(view(padded, i:(i + neighborhood_size - 1)))] for - i in eachindex(cell) - ] +function tca_evolution( + cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition=Periodic() +) + left, right = _radius_extent(radius) + return map(eachindex(cell)) do i + neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) + return convert(eltype(cell), codeset[tca_state_reader(neighborhood)]) + end end diff --git a/test/ad_test.jl b/test/ad_test.jl index adc9162..0895697 100644 --- a/test/ad_test.jl +++ b/test/ad_test.jl @@ -2,19 +2,45 @@ using CellularAutomata using ForwardDiff using Test -const generations = 5 -const ncells = 11 -const x0 = collect(range(0.1, 0.9; length=ncells)) +@testset "next_state and rollout" begin + initial = [0.1, 0.2, 0.3] + rule = CCA(0.0) -function final_state_loss(x) - ca = CellularAutomaton(CCA(0.45), x, generations) - return sum(abs2, ca.evolution[end, :]) + @test next_state(rule, initial) ≈ [0.2, 0.2, 0.2] + @test next_state(rule, initial; boundary=ConstantBoundary()) ≈ [0.1, 0.2, 1 / 6] + @test next_state(rule, initial; boundary=Reflecting()) ≈ [1 / 6, 0.2, 7 / 30] + @test initial == [0.1, 0.2, 0.3] + @test next_state(CCA(big"0.01"), BigFloat[0.1, 0.2]) isa Vector{BigFloat} + + parent = [0.0, 0.1, 0.2, 0.3, 0.0] + initial_view = @view parent[2:4] + @test next_state(rule, initial_view) ≈ [0.2, 0.2, 0.2] + + history = rollout(rule, initial, 2; save=true) + @test size(history) == (3, 3) + @test history[:, 1] == initial + @test rollout(rule, initial, 0) === initial + @test_throws ArgumentError rollout(rule, initial, -1) end -grad = ForwardDiff.gradient(final_state_loss, x0) -@test length(grad) == ncells -@test any(!iszero, grad) +@testset "multi-step differentiation" begin + initial = fill(0.1, 4) + objective(rule_value) = sum(rollout(CCA(rule_value; radius=0), initial, 3)) + @test ForwardDiff.derivative(objective, 0.01) ≈ 12.0 + @test ForwardDiff.jacobian(x -> rollout(CCA(0.01; radius=0), x, 3), initial) ≈ + [i == j ? 1.0 : 0.0 for i in 1:4, j in 1:4] -# eltype is preserved through the evolution (no hardcoded Float64) -ca32 = CellularAutomaton(CCA(0.45f0), rand(Float32, ncells), generations) -@test eltype(ca32.evolution) == Float32 + function final_state_loss(x) + ca = CellularAutomaton(CCA(0.45), x, 5) + return sum(abs2, ca.evolution[end, :]) + end + x0 = collect(range(0.1, 0.9; length=11)) + grad = ForwardDiff.gradient(final_state_loss, x0) + @test length(grad) == length(x0) + @test any(!iszero, grad) +end + +@testset "eltype preservation" begin + ca32 = CellularAutomaton(CCA(0.45f0), rand(Float32, 8), 4) + @test eltype(ca32.evolution) == Float32 +end diff --git a/test/regression_test.jl b/test/regression_test.jl new file mode 100644 index 0000000..0a329fc --- /dev/null +++ b/test/regression_test.jl @@ -0,0 +1,55 @@ +using CellularAutomata +using Test + +@testset "constructor edge cases" begin + @test CellularAutomaton(DCA(0), [1], 1).evolution == reshape([1], 1, 1) + @test_throws ArgumentError CellularAutomaton(DCA(0), Int[], 1) + @test_throws ArgumentError CellularAutomaton(DCA(0), [1], 0) + @test_throws ArgumentError DCA(-1) + @test_throws ArgumentError DCA(256) + @test length(TCA(0; states=2, radius=2).codeset) == 6 + @test length(TCA(0; states=3, radius=(1, 2)).codeset) == 9 +end + +@testset "concrete fields" begin + objects = ( + CellularAutomaton(DCA(30), [0, 1, 0], 2), + DCA(30), + TCA(3), + CCA(0.1), + Life(((3,), (2, 3))), + ConstantBoundary(0.0), + ) + for object in objects + @test all(isconcretetype, fieldtypes(typeof(object))) + end +end + +@testset "rule hierarchy and spatial traits" begin + @test DCA(30) isa AbstractDiscreteCellularAutomatonRule + @test TCA(3) isa AbstractTotalisticCellularAutomatonRule + @test CCA(0.1) isa AbstractContinuousCellularAutomatonRule + @test Life(((3,), (2, 3))) isa AbstractLifeLikeCellularAutomatonRule + @test spatial_dimensions(DCA(30)) == 1 + @test spatial_dimensions(TCA(3)) == 1 + @test spatial_dimensions(CCA(0.1)) == 1 + @test spatial_dimensions(Life(((3,), (2, 3)))) == 2 +end + +@testset "asymmetric continuous neighborhoods" begin + rule = CCA(0.0; radius=(0, 1)) + @test rule([0.0, 0.0, 1.0]) ≈ [0.0, 0.5, 0.5] + @test eltype(CCA(0.0f0)(Float32[0, 1])) == Float32 +end + +@testset "Life is synchronous and supports larger radii" begin + input = Bool[1 1 0; 0 1 0; 0 0 0] + copy_before = copy(input) + Life(((3,), (2, 3)))(input) + @test input == copy_before + + all_alive = trues(3, 4) + result = Life(((), ()); radius=2)(all_alive) + @test size(result) == size(all_alive) + @test !any(result) +end diff --git a/test/runtests.jl b/test/runtests.jl index d0aa0b6..056b212 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -22,6 +22,10 @@ end @safetestset "ForwardDiff through CCA" include("ad_test.jl") end +@testset "Regression" begin + @safetestset "Edge cases and hierarchy" include("regression_test.jl") +end + @testset "Life-like" begin @safetestset "Life glider" include("glider_test.jl") @safetestset "Life blinker" include("blinker_test.jl") From 3a14cc660827e819a9c03e2fdcd6611505257975 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 11:51:24 +0200 Subject: [PATCH 3/8] style: replace closures with callable structs, add jldoctests SciML style guide says to avoid closures even when a particular closure would not be problematic (accidental type instabilities), so the rollout transition and the per-rule kernels now use @concrete callable structs (Transition, DCAUpdate, CCAUpdate, TCAUpdate, LifeUpdate) as in the codex draft. Convert all docstring examples to jldoctest blocks (verified with Documenter.doctest; docs CI already runs makedocs with doctest=true). Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- src/cellular_automaton.jl | 31 ++++++++++++++++++++---- src/generics.jl | 48 +++++++++++++++++++++++++++++++++++++ src/measures.jl | 11 +++++++++ src/rules/cca.jl | 41 +++++++++++++++++++------------- src/rules/dca.jl | 41 +++++++++++++++++++++++++------- src/rules/life.jl | 50 ++++++++++++++++++++++++++------------- src/rules/tca.jl | 40 +++++++++++++++++++++++-------- 7 files changed, 207 insertions(+), 55 deletions(-) diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index b11fe65..3bda793 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -23,7 +23,9 @@ Rules may specialize this function to define differentiable transitions. # Examples -```julia +```jldoctest +julia> using CellularAutomata + julia> next_state(DCA(30), [0, 0, 1, 0, 0]) 5-element Vector{Int64}: 0 @@ -41,6 +43,15 @@ function next_state( return _step(rule, state, boundary) end +@concrete struct Transition + rule + boundary +end + +function (transition::Transition)(state, _) + return next_state(transition.rule, state; boundary=transition.boundary) +end + """ rollout(rule, initial_state, steps; boundary=Periodic(), save=false) @@ -62,11 +73,21 @@ on the last axis. # Examples -```julia +```jldoctest +julia> using CellularAutomata + julia> history = rollout(DCA(30), [0, 0, 1, 0, 0], 2; save=true); julia> size(history) (5, 3) + +julia> history[:, end] +5-element Vector{Int64}: + 1 + 1 + 0 + 0 + 1 ``` """ function rollout( @@ -78,7 +99,7 @@ function rollout( ) steps >= 0 || throw(ArgumentError("steps must be nonnegative")) isempty(initial_state) && throw(ArgumentError("initial_state cannot be empty")) - transition = (state, _) -> next_state(rule, state; boundary=boundary) + transition = Transition(rule, boundary) if save states = accumulate(transition, 1:steps; init=initial_state) return stack(Iterators.flatten(((initial_state,), states))) @@ -101,7 +122,9 @@ time is stored on the last axis. # Examples -```julia +```jldoctest +julia> using CellularAutomata + julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3); julia> automaton.evolution diff --git a/src/generics.jl b/src/generics.jl index aef3193..f99b4c1 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -18,6 +18,18 @@ abstract type AbstractBoundaryCondition end Periodic() Wrap indices around the opposite edge of the state array. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> next_state(CCA(0 // 1), [0 // 1, 0 // 1, 3 // 10]; boundary=Periodic()) +3-element Vector{Rational{Int64}}: + 1//10 + 1//10 + 1//10 +``` """ struct Periodic <: AbstractBoundaryCondition end @@ -25,6 +37,18 @@ struct Periodic <: AbstractBoundaryCondition end Reflecting() Mirror indices at the edge of the state array. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> next_state(CCA(0 // 1), [0 // 1, 0 // 1, 3 // 10]; boundary=Reflecting()) +3-element Vector{Rational{Int64}}: + 0 + 1//10 + 1//10 +``` """ struct Reflecting <: AbstractBoundaryCondition end @@ -32,6 +56,18 @@ struct Reflecting <: AbstractBoundaryCondition end ConstantBoundary([value = 0]) Use `value` for indices outside the state array. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> next_state(CCA(0 // 1), [0 // 1, 0 // 1, 3 // 10]; boundary=ConstantBoundary()) +3-element Vector{Rational{Int64}}: + 0 + 1//10 + 1//10 +``` """ @concrete struct ConstantBoundary <: AbstractBoundaryCondition value @@ -92,5 +128,17 @@ end Return the number of spatial dimensions used by a cellular-automaton rule. State arrays may have additional channel or batch dimensions. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> spatial_dimensions(DCA(30)) +1 + +julia> spatial_dimensions(Life(((3,), (2, 3)))) +2 +``` """ function spatial_dimensions end diff --git a/src/measures.jl b/src/measures.jl index 7be43c9..d07f6ea 100644 --- a/src/measures.jl +++ b/src/measures.jl @@ -24,6 +24,17 @@ end lempel_ziv(ca::AbstractCellularAutomaton) Compute the mean Lempel-Ziv complexity across rows of an automaton's retained evolution. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3); + +julia> lempel_ziv(automaton) +1.3333333333333333 +``` """ function lempel_ziv(ca::AbstractCellularAutomaton) ca_size = size(ca.evolution, 1) diff --git a/src/rules/cca.jl b/src/rules/cca.jl index 8b5d335..e490a97 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -28,17 +28,16 @@ of the neighborhood mean plus `rule`. # Examples -```julia -julia> cca = CCA(0.45; radius=1); - -julia> next_state(cca, [0.0, 1.0, 0.0, 1.0, 0.5, 1.0]) -6-element Vector{Float64}: - 0.7833333333333333 - 0.7833333333333333 - 0.11666666666666664 - 0.95 - 0.2833333333333333 - 0.95 +```jldoctest +julia> using CellularAutomata + +julia> cca = CCA(1 // 10); + +julia> next_state(cca, [0 // 1, 0 // 1, 3 // 10]) +3-element Vector{Rational{Int64}}: + 1//5 + 1//5 + 1//5 ``` """ function CCA(rule::Real; radius=1) @@ -56,13 +55,23 @@ end fractional_part(value) = value - floor(value) +@concrete struct CCAUpdate + cell + rule + boundary + left + right +end + +function (update::CCAUpdate)(index) + indices = (index - update.left):(index + update.right) + neighborhood = Neighborhood1D(update.cell, update.boundary, indices) + return fractional_part(sum(neighborhood) / length(neighborhood) + update.rule) +end + function cca_evolution( cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition=Periodic() ) left, right = _radius_extent(radius) - neighborhood_size = left + right + 1 - return map(eachindex(cell)) do i - neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) - return fractional_part(sum(neighborhood) / neighborhood_size + rule) - end + return map(CCAUpdate(cell, rule, boundary, left, right), eachindex(cell)) end diff --git a/src/rules/dca.jl b/src/rules/dca.jl index 16361a2..f7d7995 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -30,15 +30,27 @@ Construct a discrete cellular-automaton rule and its neighborhood lookup table. # Examples -```julia -julia> dca = DCA(110; states=2, radius=1); +```jldoctest +julia> using CellularAutomata -julia> next_state(dca, [0, 1, 0, 1, 1, 0]) -6-element Vector{Int64}: +julia> dca = DCA(30); + +julia> dca.ruleset +8-element Vector{Int64}: + 0 1 1 1 1 + 0 + 0 + 0 + +julia> next_state(dca, [0, 0, 1, 0, 0]) +5-element Vector{Int64}: + 0 + 1 + 1 1 0 ``` @@ -79,6 +91,22 @@ function state_reader(neighborhood, states::Int) return index + 1 end +@concrete struct DCAUpdate + cell + ruleset + states + boundary + left + right +end + +function (update::DCAUpdate)(index) + indices = (index - update.left):(index + update.right) + neighborhood = Neighborhood1D(update.cell, update.boundary, indices) + new_state = update.ruleset[state_reader(neighborhood, update.states)] + return convert(eltype(update.cell), new_state) +end + function dca_evolution( cell::AbstractVector, ruleset, @@ -87,8 +115,5 @@ function dca_evolution( boundary::AbstractBoundaryCondition=Periodic(), ) left, right = _radius_extent(radius) - return map(eachindex(cell)) do i - neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) - return convert(eltype(cell), ruleset[state_reader(neighborhood, states)]) - end + return map(DCAUpdate(cell, ruleset, states, boundary, left, right), eachindex(cell)) end diff --git a/src/rules/life.jl b/src/rules/life.jl index 21cca7f..502621b 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -29,7 +29,9 @@ Construct a Life-like cellular-automaton rule using Golly birth/survival notatio # Examples -```julia +```jldoctest +julia> using CellularAutomata + julia> life = Life(((3,), (2, 3)); radius=1); julia> blinker = [0 0 0 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 0 0 0]; @@ -57,6 +59,34 @@ function _step(life::Life, state::AbstractMatrix, boundary::AbstractBoundaryCond return life_evolution(state, life.born, life.survive, life.radius, boundary) end +@concrete struct LifeUpdate + state + born + survive + radius + 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 + end + current = update.state[index] + lives = + (isone(current) && alive in update.survive) || + (iszero(current) && alive in update.born) + return convert(eltype(update.state), lives) +end + function life_evolution( starting_array::AbstractMatrix, born, @@ -64,20 +94,6 @@ function life_evolution( radius::Int, boundary::AbstractBoundaryCondition=Periodic(), ) - return map(CartesianIndices(starting_array)) do index - row, column = Tuple(index) - alive = 0 - for column_offset in (-radius):radius, row_offset in (-radius):radius - if !iszero(row_offset) || !iszero(column_offset) - alive += Int( - _boundary_get( - starting_array, boundary, row + row_offset, column + column_offset - ), - ) - end - end - current = starting_array[index] - lives = (isone(current) && alive in survive) || (iszero(current) && alive in born) - return convert(eltype(starting_array), lives) - end + update = LifeUpdate(starting_array, born, survive, radius, boundary) + return map(update, CartesianIndices(starting_array)) end diff --git a/src/rules/tca.jl b/src/rules/tca.jl index dbd8e47..fc1c15b 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -31,17 +31,25 @@ Construct a totalistic cellular-automaton rule and its lookup table. # Examples -```julia -julia> tca = TCA(102; states=3, radius=1); +```jldoctest +julia> using CellularAutomata -julia> next_state(tca, [0, 2, 1, 0, 1, 2]) -6-element Vector{Int64}: +julia> tca = TCA(3); + +julia> tca.codeset +4-element Vector{Int64}: 1 - 0 - 0 1 0 0 + +julia> next_state(tca, [0, 0, 1, 0, 0]) +5-element Vector{Int64}: + 1 + 1 + 1 + 1 + 1 ``` """ function TCA(code::Integer; states::Int=2, radius=1) @@ -66,12 +74,24 @@ end tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 +@concrete struct TCAUpdate + cell + codeset + boundary + left + right +end + +function (update::TCAUpdate)(index) + indices = (index - update.left):(index + update.right) + neighborhood = Neighborhood1D(update.cell, update.boundary, indices) + new_state = update.codeset[tca_state_reader(neighborhood)] + return convert(eltype(update.cell), new_state) +end + function tca_evolution( cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition=Periodic() ) left, right = _radius_extent(radius) - return map(eachindex(cell)) do i - neighborhood = Neighborhood1D(cell, boundary, (i - left):(i + right)) - return convert(eltype(cell), codeset[tca_state_reader(neighborhood)]) - end + return map(TCAUpdate(cell, codeset, boundary, left, right), eachindex(cell)) end From d7bdd2811283ae32fac93ca17c5624679a76f558 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 11:58:43 +0200 Subject: [PATCH 4/8] chore: housekeeping sweep - CI: bump checkout@v4 and setup-julia@v2, test on lts + latest - README: fix broken docs badge URL (pointed at SpectralIndices.jl), switch style badge Blue -> SciML, https for wolfram/golly links - Switch .JuliaFormatter.toml to style = "sciml" and reformat - Rename CellularAutomaton field generation_fun -> rule - lempel_ziv: clear ArgumentError for 2D automata instead of a confusing BoundsError on the 3D evolution array - Fix "Two Dimensial" typo in docs pages - Bump version to 0.1.0 to signal the API overhaul Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- .JuliaFormatter.toml | 2 +- .github/workflows/CI.yml | 9 +++++---- Project.toml | 2 +- README.md | 22 +++++++++++----------- docs/make.jl | 4 ++-- docs/pages.jl | 14 +++++--------- src/cellular_automaton.jl | 30 +++++++++++++++--------------- src/generics.jl | 6 +++--- src/measures.jl | 2 ++ src/rules/cca.jl | 2 +- src/rules/dca.jl | 10 +++++----- src/rules/life.jl | 20 ++++++++++---------- src/rules/tca.jl | 2 +- test/ad_test.jl | 2 +- test/blinker_test.jl | 2 +- test/glider_test.jl | 2 +- test/regression_test.jl | 2 +- 17 files changed, 66 insertions(+), 67 deletions(-) diff --git a/.JuliaFormatter.toml b/.JuliaFormatter.toml index 86dd6b4..3d6dde2 100644 --- a/.JuliaFormatter.toml +++ b/.JuliaFormatter.toml @@ -1,4 +1,4 @@ -style = "blue" +style = "sciml" whitespace_in_kwargs = false always_use_return = true margin = 92 diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 10525b1..a85c36d 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -15,6 +15,7 @@ jobs: fail-fast: false matrix: version: + - 'lts' - '1' os: - ubuntu-latest @@ -23,8 +24,8 @@ jobs: arch: - x64 steps: - - uses: actions/checkout@v2 - - uses: julia-actions/setup-julia@v1 + - uses: actions/checkout@v4 + - uses: julia-actions/setup-julia@v2 with: version: ${{ matrix.version }} arch: ${{ matrix.arch }} @@ -48,8 +49,8 @@ jobs: name: Documentation runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: julia-actions/setup-julia@v1 + - uses: actions/checkout@v4 + - uses: julia-actions/setup-julia@v2 with: version: '1' - run: | diff --git a/Project.toml b/Project.toml index cd16484..cdde115 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "CellularAutomata" uuid = "878138dc-5b27-11ea-1a71-cb95d38d6b29" authors = ["Francesco Martinuzzi"] -version = "0.0.7" +version = "0.1.0" [deps] ConcreteStructs = "2569d6c7-a4a2-43d3-a901-331e8e4be471" diff --git a/README.md b/README.md index 310ccb8..c79c4ce 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ | **Documentation** | **Build Status** | **Julia** | **Testing** | **DOI** | |:-----------------:|:----------------:|:---------:|:-----------:|:-------:| -| [![docs][docs-img]][docs-url] | [![CI][ci-img]][ci-url] [![codecov][cc-img]][cc-url] | [![Julia][julia-img]][julia-url] [![Code Style: Blue][style-img]][style-url] | [![Aqua QA][aqua-img]][aqua-url] [![JET][jet-img]][jet-url] | [![DOI][doi-img]][doi-url] +| [![docs][docs-img]][docs-url] | [![CI][ci-img]][ci-url] [![codecov][cc-img]][cc-url] | [![Julia][julia-img]][julia-url] [![SciML Code Style][style-img]][style-url] | [![Aqua QA][aqua-img]][aqua-url] [![JET][jet-img]][jet-url] | [![DOI][doi-img]][doi-url] [docs-img]: https://img.shields.io/badge/docs-stable-blue.svg -[docs-url]: [https://awesome-spectral-indices.github.io/SpectralIndices.jl/dev/](https://martinuzzifrancesco.github.io/CellularAutomata.jl/dev/) +[docs-url]: https://martinuzzifrancesco.github.io/CellularAutomata.jl/dev/ [ci-img]: https://github.com/MartinuzziFrancesco/CellularAutomata.jl/actions/workflows/CI.yml/badge.svg [ci-url]: https://github.com/MartinuzziFrancesco/CellularAutomata.jl/actions/workflows/CI.yml @@ -20,8 +20,8 @@ [julia-img]: https://img.shields.io/badge/julia-v1.10+-blue.svg [julia-url]: https://julialang.org/ -[style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg -[style-url]: https://github.com/invenia/BlueStyle +[style-img]: https://img.shields.io/static/v1?label=code%20style&message=SciML&color=9558b2&labelColor=389826 +[style-url]: https://github.com/SciML/SciMLStyle [aqua-img]: https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg [aqua-url]: https://github.com/JuliaTesting/Aqua.jl @@ -57,13 +57,13 @@ pkg> add CellularAutomata ## Discrete Cellular Automata The package offers creation of all the cellular automata described in A New Kind of Science by Wolfram, and the rules for the creation are labelled as in the book. -We will recreate some of the examples that can be found in the [wolfram atlas](http://atlas.wolfram.com/TOC/TOC_200.html) both for elementary and totalistic cellular automata. +We will recreate some of the examples that can be found in the [wolfram atlas](https://atlas.wolfram.com/TOC/TOC_200.html) both for elementary and totalistic cellular automata. ### Elementary Cellular Automata Elementary Cellular Automata (ECA) have a radius of one and can be in only two possible states. Here we show a couple of examples: -[Rule 18](http://atlas.wolfram.com/01/01/18/) +[Rule 18](https://atlas.wolfram.com/01/01/18/) ```julia using CellularAutomata, Plots @@ -88,7 +88,7 @@ heatmap(ca.evolution, ``` ![dca18](https://user-images.githubusercontent.com/10376688/75625854-4a816b00-5bc2-11ea-8337-9132553cd38b.png) -[Rule 30](http://atlas.wolfram.com/01/01/30/) +[Rule 30](https://atlas.wolfram.com/01/01/30/) ```julia using CellularAutomata, Plots @@ -235,7 +235,7 @@ heatmap(ca.evolution, Totalistic Cellular Automata takes the sum of the neighborhood to calculate the value of the next step. -[Rule 1635](http://atlas.wolfram.com/01/02/1635/) +[Rule 1635](https://atlas.wolfram.com/01/02/1635/) ```julia using CellularAutomata, Plots @@ -261,7 +261,7 @@ heatmap(ca.evolution, ``` ![dca1635](https://user-images.githubusercontent.com/10376688/75628258-7eb35680-5bd7-11ea-81c5-b95b25f1369d.png) -[Rule 107398](http://atlas.wolfram.com/01/03/107398/) +[Rule 107398](https://atlas.wolfram.com/01/03/107398/) ```julia using CellularAutomata, Plots @@ -290,7 +290,7 @@ heatmap(ca.evolution, Here are some results for a bigger radius, using a radius of 2 as an example. -[Rule 53](http://atlas.wolfram.com/01/06/Rules/53/index.html#01_06_9_53) +[Rule 53](https://atlas.wolfram.com/01/06/Rules/53/index.html#01_06_9_53) ```julia using CellularAutomata, Plots @@ -374,7 +374,7 @@ heatmap(ca.evolution, ## Game of Life -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](http://golly.sourceforge.net/Help/changes.html) notation. +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. This script reproduces the famous glider: diff --git a/docs/make.jl b/docs/make.jl index 3b95229..30fecea 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -9,10 +9,10 @@ makedocs(; linkcheck=true, format=Documenter.HTML(; assets=["assets/favicon.ico"], - canonical="https://MartinuzziFrancesco.github.io/CellularAutomata.jl", + canonical="https://MartinuzziFrancesco.github.io/CellularAutomata.jl" ), warnonly=[:missing_docs], - pages=pages, + pages=pages ) deploydocs(; diff --git a/docs/pages.jl b/docs/pages.jl index 6da3010..c061fc1 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -1,13 +1,9 @@ pages = [ "CellularAutomata.jl" => "index.md", "Differentiable cellular automata" => "ad_design.md", - "Examples" => [ - "One dimensional CA" => "onedim/onedimensionca.md" - "Two dimensional CA" => "twodim/twodimensionca.md" - ], - "API Documentation" => Any[ - "General APIs" => "api/general.md" - "One Dimensional CA" => "api/onedim.md" - "Two Dimensial CA" => "api/twodim.md" - ], + "Examples" => ["One dimensional CA" => "onedim/onedimensionca.md" + "Two dimensional CA" => "twodim/twodimensionca.md"], + "API Documentation" => Any["General APIs" => "api/general.md" + "One Dimensional CA" => "api/onedim.md" + "Two Dimensional CA" => "api/twodim.md"] ] diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index 3bda793..08d1646 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -36,9 +36,9 @@ julia> next_state(DCA(30), [0, 0, 1, 0, 0]) ``` """ function next_state( - rule::AbstractCellularAutomatonRule, - state; - boundary::AbstractBoundaryCondition=Periodic(), + rule::AbstractCellularAutomatonRule, + state; + boundary::AbstractBoundaryCondition=Periodic() ) return _step(rule, state, boundary) end @@ -91,11 +91,11 @@ julia> history[:, end] ``` """ function rollout( - rule::AbstractCellularAutomatonRule, - initial_state, - steps::Integer; - boundary::AbstractBoundaryCondition=Periodic(), - save::Bool=false, + rule::AbstractCellularAutomatonRule, + initial_state, + steps::Integer; + boundary::AbstractBoundaryCondition=Periodic(), + save::Bool=false ) steps >= 0 || throw(ArgumentError("steps must be nonnegative")) isempty(initial_state) && throw(ArgumentError("initial_state cannot be empty")) @@ -136,14 +136,14 @@ julia> automaton.evolution """ @concrete struct CellularAutomaton <: AbstractCellularAutomaton generations::Int - generation_fun + rule evolution end function CellularAutomaton( - rule::AbstractCellularAutomatonRule, - initial_conditions::AbstractVector, - generations::Integer, + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractVector, + generations::Integer ) generations >= 1 || throw(ArgumentError("generations must be at least 1")) history = rollout(rule, initial_conditions, generations - 1; save=true) @@ -151,9 +151,9 @@ function CellularAutomaton( end function CellularAutomaton( - rule::AbstractCellularAutomatonRule, - initial_conditions::AbstractArray, - generations::Integer, + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractArray, + generations::Integer ) generations >= 1 || throw(ArgumentError("generations must be at least 1")) evolution = rollout(rule, initial_conditions, generations - 1; save=true) diff --git a/src/generics.jl b/src/generics.jl index f99b4c1..45e5133 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -82,10 +82,10 @@ ConstantBoundary() = ConstantBoundary(0) return reflected <= n ? reflected : 2n - reflected end -@inline function _boundary_get(array, boundary::Union{Periodic,Reflecting}, i) +@inline function _boundary_get(array, boundary::Union{Periodic, Reflecting}, i) return array[_boundary_index(i, length(array), boundary)] end -@inline function _boundary_get(array, boundary::Union{Periodic,Reflecting}, i, j) +@inline function _boundary_get(array, boundary::Union{Periodic, Reflecting}, i, j) row = _boundary_index(i, size(array, 1), boundary) column = _boundary_index(j, size(array, 2), boundary) return array[row, column] @@ -113,7 +113,7 @@ function Base.iterate(neighborhood::Neighborhood1D, state...) end _radius_extent(radius::Integer) = (radius, radius) -_radius_extent(radius::Tuple{<:Integer,<:Integer}) = radius +_radius_extent(radius::Tuple{<:Integer, <:Integer}) = radius function _validate_radius(radius) left, right = _radius_extent(radius) diff --git a/src/measures.jl b/src/measures.jl index d07f6ea..406787e 100644 --- a/src/measures.jl +++ b/src/measures.jl @@ -37,6 +37,8 @@ julia> lempel_ziv(automaton) ``` """ function lempel_ziv(ca::AbstractCellularAutomaton) + ca.evolution isa AbstractMatrix || + throw(ArgumentError("lempel_ziv only supports one-dimensional automata")) ca_size = size(ca.evolution, 1) lz_tot = 0 diff --git a/src/rules/cca.jl b/src/rules/cca.jl index e490a97..d9db557 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -70,7 +70,7 @@ function (update::CCAUpdate)(index) end function cca_evolution( - cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition=Periodic() + cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition=Periodic() ) left, right = _radius_extent(radius) return map(CCAUpdate(cell, rule, boundary, left, right), eachindex(cell)) diff --git a/src/rules/dca.jl b/src/rules/dca.jl index f7d7995..0987e64 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -108,11 +108,11 @@ function (update::DCAUpdate)(index) end function dca_evolution( - cell::AbstractVector, - ruleset, - states::Int, - radius, - boundary::AbstractBoundaryCondition=Periodic(), + cell::AbstractVector, + ruleset, + states::Int, + radius, + boundary::AbstractBoundaryCondition=Periodic() ) left, right = _radius_extent(radius) return map(DCAUpdate(cell, ruleset, states, boundary, left, right), eachindex(cell)) diff --git a/src/rules/life.jl b/src/rules/life.jl index 502621b..0bdf6b2 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -72,27 +72,27 @@ function (update::LifeUpdate)(index::CartesianIndex{2}) 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 - ), + update.state, update.boundary, row + row_offset, column + column_offset + ), ) end end current = update.state[index] - lives = - (isone(current) && alive in update.survive) || - (iszero(current) && alive in update.born) + lives = (isone(current) && alive in update.survive) || + (iszero(current) && alive in update.born) return convert(eltype(update.state), lives) end function life_evolution( - starting_array::AbstractMatrix, - born, - survive, - radius::Int, - boundary::AbstractBoundaryCondition=Periodic(), + starting_array::AbstractMatrix, + born, + survive, + radius::Int, + boundary::AbstractBoundaryCondition=Periodic() ) update = LifeUpdate(starting_array, born, survive, radius, boundary) return map(update, CartesianIndices(starting_array)) diff --git a/src/rules/tca.jl b/src/rules/tca.jl index fc1c15b..b29d6bb 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -90,7 +90,7 @@ function (update::TCAUpdate)(index) end function tca_evolution( - cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition=Periodic() + cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition=Periodic() ) left, right = _radius_extent(radius) return map(TCAUpdate(cell, codeset, boundary, left, right), eachindex(cell)) diff --git a/test/ad_test.jl b/test/ad_test.jl index 0895697..bb5271f 100644 --- a/test/ad_test.jl +++ b/test/ad_test.jl @@ -28,7 +28,7 @@ end objective(rule_value) = sum(rollout(CCA(rule_value; radius=0), initial, 3)) @test ForwardDiff.derivative(objective, 0.01) ≈ 12.0 @test ForwardDiff.jacobian(x -> rollout(CCA(0.01; radius=0), x, 3), initial) ≈ - [i == j ? 1.0 : 0.0 for i in 1:4, j in 1:4] + [i == j ? 1.0 : 0.0 for i in 1:4, j in 1:4] function final_state_loss(x) ca = CellularAutomaton(CCA(0.45), x, 5) diff --git a/test/blinker_test.jl b/test/blinker_test.jl index a7caeed..e42a8c9 100644 --- a/test/blinker_test.jl +++ b/test/blinker_test.jl @@ -10,5 +10,5 @@ ca = CellularAutomaton(Life((3, (2, 3))), blinker, gens) [0 0 0 0 0; 0 0 0 0 0; 0 1 1 1 0; 0 0 0 0 0; 0 0 0 0 0], [0 0 0 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 0 0 0], [0 0 0 0 0; 0 0 0 0 0; 0 1 1 1 0; 0 0 0 0 0; 0 0 0 0 0]; - dims=3, + dims=3 ) diff --git a/test/glider_test.jl b/test/glider_test.jl index 030f794..012261a 100644 --- a/test/glider_test.jl +++ b/test/glider_test.jl @@ -15,5 +15,5 @@ ca = CellularAutomaton(Life((3, (2, 3))), space, gens) [0 0 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 1 1 1 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0], [0 0 0 0 0 0; 0 0 0 0 0 0; 0 1 0 1 0 0; 0 0 1 1 0 0; 0 0 1 0 0 0; 0 0 0 0 0 0], [0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 1 0 0; 0 1 0 1 0 0; 0 0 1 1 0 0; 0 0 0 0 0 0]; - dims=3, + dims=3 ) diff --git a/test/regression_test.jl b/test/regression_test.jl index 0a329fc..8737423 100644 --- a/test/regression_test.jl +++ b/test/regression_test.jl @@ -18,7 +18,7 @@ end TCA(3), CCA(0.1), Life(((3,), (2, 3))), - ConstantBoundary(0.0), + ConstantBoundary(0.0) ) for object in objects @test all(isconcretetype, fieldtypes(typeof(object))) From 5cdf0fb5252a2e67e2f9753034536c0b4dc5f984 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 12:03:16 +0200 Subject: [PATCH 5/8] feat: add show methods for rules, boundaries, and CellularAutomaton Rules and ConstantBoundary print in reconstructable constructor form (e.g. DCA(30; states=2, radius=1)). CellularAutomaton gets a compact inline form and a three-line text/plain summary showing the rule and evolution size instead of the raw parameter spew. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- src/cellular_automaton.jl | 18 +++++++++++++++++- src/generics.jl | 4 ++++ src/rules/cca.jl | 4 ++++ src/rules/dca.jl | 5 +++++ src/rules/life.jl | 4 ++++ src/rules/tca.jl | 5 +++++ test/regression_test.jl | 15 +++++++++++++++ 7 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index 08d1646..dec865f 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -125,7 +125,10 @@ time is stored on the last axis. ```jldoctest julia> using CellularAutomata -julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3); +julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3) +CellularAutomaton with 3 generations + rule: DCA(30; states=2, radius=1) + evolution: 3×3 Matrix{Int64} julia> automaton.evolution 3×3 Matrix{Int64}: @@ -159,3 +162,16 @@ function CellularAutomaton( evolution = rollout(rule, initial_conditions, generations - 1; save=true) return CellularAutomaton(Int(generations), rule, evolution) end + +function Base.show(io::IO, automaton::CellularAutomaton) + return print( + io, "CellularAutomaton(", automaton.rule, "; generations=", + automaton.generations, ")" + ) +end + +function Base.show(io::IO, ::MIME"text/plain", automaton::CellularAutomaton) + println(io, "CellularAutomaton with ", automaton.generations, " generations") + println(io, " rule: ", automaton.rule) + return print(io, " evolution: ", summary(automaton.evolution)) +end diff --git a/src/generics.jl b/src/generics.jl index 45e5133..ef43464 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -75,6 +75,10 @@ end ConstantBoundary() = ConstantBoundary(0) +function Base.show(io::IO, boundary::ConstantBoundary) + return print(io, "ConstantBoundary(", boundary.value, ")") +end + @inline _boundary_index(i, n, ::Periodic) = mod1(i, n) @inline function _boundary_index(i, n, ::Reflecting) n == 1 && return 1 diff --git a/src/rules/cca.jl b/src/rules/cca.jl index d9db557..413d46c 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -75,3 +75,7 @@ function cca_evolution( left, right = _radius_extent(radius) return map(CCAUpdate(cell, rule, boundary, left, right), eachindex(cell)) end + +function Base.show(io::IO, cca::CCA) + return print(io, "CCA(", cca.rule, "; radius=", cca.radius, ")") +end diff --git a/src/rules/dca.jl b/src/rules/dca.jl index 0987e64..92b19bf 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -117,3 +117,8 @@ function dca_evolution( left, right = _radius_extent(radius) return map(DCAUpdate(cell, ruleset, states, boundary, left, right), eachindex(cell)) end + +function Base.show(io::IO, dca::DCA) + return print( + io, "DCA(", dca.rule, "; states=", dca.states, ", radius=", dca.radius, ")") +end diff --git a/src/rules/life.jl b/src/rules/life.jl index 0bdf6b2..5d92cb5 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -97,3 +97,7 @@ function life_evolution( update = LifeUpdate(starting_array, born, survive, radius, boundary) return map(update, CartesianIndices(starting_array)) end + +function Base.show(io::IO, life::Life) + return print(io, "Life(", (life.born, life.survive), "; radius=", life.radius, ")") +end diff --git a/src/rules/tca.jl b/src/rules/tca.jl index b29d6bb..ecced4c 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -95,3 +95,8 @@ function tca_evolution( left, right = _radius_extent(radius) return map(TCAUpdate(cell, codeset, boundary, left, right), eachindex(cell)) end + +function Base.show(io::IO, tca::TCA) + return print( + io, "TCA(", tca.code, "; states=", tca.states, ", radius=", tca.radius, ")") +end diff --git a/test/regression_test.jl b/test/regression_test.jl index 8737423..6ae74d9 100644 --- a/test/regression_test.jl +++ b/test/regression_test.jl @@ -42,6 +42,21 @@ end @test eltype(CCA(0.0f0)(Float32[0, 1])) == Float32 end +@testset "show methods" begin + @test repr(DCA(30)) == "DCA(30; states=2, radius=1)" + @test repr(TCA(3)) == "TCA(3; states=2, radius=1)" + @test repr(CCA(0.1)) == "CCA(0.1; radius=1)" + @test repr(Life(((3,), (2, 3)))) == "Life(((3,), (2, 3)); radius=1)" + @test repr(ConstantBoundary(0.5)) == "ConstantBoundary(0.5)" + + automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3) + @test repr(automaton) == "CellularAutomaton(DCA(30; states=2, radius=1); generations=3)" + @test repr(MIME"text/plain"(), automaton) == + "CellularAutomaton with 3 generations\n" * + " rule: DCA(30; states=2, radius=1)\n" * + " evolution: 3×3 Matrix{Int64}" +end + @testset "Life is synchronous and supports larger radii" begin input = Bool[1 1 0; 0 1 0; 0 0 0] copy_before = copy(input) From fe87e6932eeca28d1aff9228056a93782c549cc0 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 14:58:42 +0200 Subject: [PATCH 6/8] ci: fix lts, docs, and format-check failures - Gate JET.test_package to Julia >= 1.12: JET 0.9 (the only release installable on older Julia) reports a false positive inside Base's digits! BigInt path when analyzing digits_ruleset abstractly - Set GKSwstype=100 for the docs build so the Plots @example pages render on the headless runner - Run the format check on x64 instead of x86, where the resolver can pick a different JuliaFormatter - Upgrade remaining http links in docs pages to https (linkcheck 301s) Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- .github/workflows/CI.yml | 1 + .github/workflows/FormatCheck.yml | 4 ++-- docs/src/onedim/onedimensionca.md | 10 +++++----- docs/src/twodim/twodimensionca.md | 2 +- test/qa.jl | 9 +++++++-- 5 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index a85c36d..0fa272e 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -67,3 +67,4 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DOCUMENTER_KEY: ${{ secrets.DOCUMENTER_KEY }} + GKSwstype: "100" diff --git a/.github/workflows/FormatCheck.yml b/.github/workflows/FormatCheck.yml index dd55150..9392f92 100644 --- a/.github/workflows/FormatCheck.yml +++ b/.github/workflows/FormatCheck.yml @@ -14,10 +14,10 @@ jobs: strategy: matrix: julia-version: [1] - julia-arch: [x86] + julia-arch: [x64] os: [ubuntu-latest] steps: - - uses: julia-actions/setup-julia@latest + - uses: julia-actions/setup-julia@v2 with: version: ${{ matrix.julia-version }} diff --git a/docs/src/onedim/onedimensionca.md b/docs/src/onedim/onedimensionca.md index de85914..e9af432 100644 --- a/docs/src/onedim/onedimensionca.md +++ b/docs/src/onedim/onedimensionca.md @@ -3,7 +3,7 @@ ## Elementary Cellular Automata Elementary Cellular Automata (ECA) have a radius of one and can be in only two possible states. Here we show a couple of examples: -[Rule 18](http://atlas.wolfram.com/01/01/18/) +[Rule 18](https://atlas.wolfram.com/01/01/18/) ```@example eca using CellularAutomata, Plots @@ -27,7 +27,7 @@ heatmap(ca.evolution, ticks=false) ``` -[Rule 30](http://atlas.wolfram.com/01/01/30/) +[Rule 30](https://atlas.wolfram.com/01/01/30/) ```@example eca states = 2 @@ -161,7 +161,7 @@ heatmap(ca.evolution, Totalistic Cellular Automata takes the sum of the neighborhood to calculate the value of the next step. -[Rule 1635](http://atlas.wolfram.com/01/02/1635/) +[Rule 1635](https://atlas.wolfram.com/01/02/1635/) ```@example tca using CellularAutomata, Plots @@ -185,7 +185,7 @@ heatmap(ca.evolution, ticks=false) ``` -[Rule 107398](http://atlas.wolfram.com/01/03/107398/) +[Rule 107398](https://atlas.wolfram.com/01/03/107398/) ```@example tca states = 4 @@ -210,7 +210,7 @@ heatmap(ca.evolution, Here are some results for a bigger radius, using a radius of 2 as an example. -[Rule 53](http://atlas.wolfram.com/01/06/Rules/53/index.html#01_06_9_53) +[Rule 53](https://atlas.wolfram.com/01/06/Rules/53/index.html#01_06_9_53) ```julia states = 2 diff --git a/docs/src/twodim/twodimensionca.md b/docs/src/twodim/twodimensionca.md index b20c7f7..52d595d 100644 --- a/docs/src/twodim/twodimensionca.md +++ b/docs/src/twodim/twodimensionca.md @@ -2,7 +2,7 @@ ## Game of Life -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](http://golly.sourceforge.net/Help/changes.html) notation. +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. This script reproduces the famous glider: diff --git a/test/qa.jl b/test/qa.jl index d113e61..7051d7f 100644 --- a/test/qa.jl +++ b/test/qa.jl @@ -1,6 +1,11 @@ using CellularAutomata using Aqua: Aqua -using JET Aqua.test_all(CellularAutomata; ambiguities=false, deps_compat=(check_extras = false)) -JET.test_package(CellularAutomata) + +# JET 0.9 (the only release available on Julia < 1.12) reports false positives +# inside Base's digits! BigInt path when analyzing digits_ruleset abstractly. +@static if VERSION >= v"1.12" + using JET + JET.test_package(CellularAutomata) +end From 45018c7c2f2a844b2b94a0ec7848d23eb2cecb2e Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Fri, 17 Jul 2026 15:16:01 +0200 Subject: [PATCH 7/8] docs: exempt golly.sourceforge.net from linkcheck SourceForge returns 403 to GitHub Actions runners, failing the docs build; keep the link for readers but skip checking it. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01G61PwsNdbkc4nHZW9DhWbQ --- docs/make.jl | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/make.jl b/docs/make.jl index 30fecea..88b0ac0 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -7,6 +7,7 @@ makedocs(; clean=true, doctest=true, linkcheck=true, + linkcheck_ignore=[r"https://golly\.sourceforge\.net"], format=Documenter.HTML(; assets=["assets/favicon.ico"], canonical="https://MartinuzziFrancesco.github.io/CellularAutomata.jl" From 4c14d37b6997cc992f902e641ef5238911a09a80 Mon Sep 17 00:00:00 2001 From: MartinuzziFrancesco Date: Wed, 29 Jul 2026 16:08:11 +0200 Subject: [PATCH 8/8] refac: SciML-style naming, accessor API, state validation, and Runic formatting Prefix internal helpers/structs with `__` per SciML convention, replace direct field access (ca.evolution, dca.ruleset, ...) with accessor functions (evolution_history, rule_lookup_table, ...), and validate discrete rule states in next_state. Switch CI formatting from JuliaFormatter/SciMLStyle to Runic and reformat the tree. Fix docs examples that fed Float64 zeros into discrete rules, now rejected by the new state validation. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_016ytx2Zi8as1AFPNenre9ZB --- .github/workflows/FormatCheck.yml | 30 +----------- README.md | 79 +++++++++++++++---------------- docs/Project.toml | 4 ++ docs/make.jl | 24 +++++----- docs/pages.jl | 14 ++++-- docs/src/api/general.md | 6 +++ docs/src/index.md | 10 ++-- docs/src/onedim/onedimensionca.md | 76 ++++++++++++++--------------- docs/src/twodim/twodimensionca.md | 6 +-- src/CellularAutomata.jl | 2 + src/cellular_automaton.jl | 60 +++++++++++++++-------- src/generics.jl | 54 +++++++++++++-------- src/measures.jl | 9 ++-- src/rules/cca.jl | 35 ++++++++------ src/rules/dca.jl | 68 +++++++++++++++++--------- src/rules/life.jl | 28 ++++++----- src/rules/tca.jl | 54 +++++++++++++-------- test/ad_test.jl | 14 +++--- test/blinker_test.jl | 2 +- test/dca_test.jl | 2 +- test/glider_test.jl | 2 +- test/qa.jl | 4 +- test/regression_test.jl | 31 ++++++++---- test/runtests.jl | 52 ++++++++++++-------- test/tca_test.jl | 2 +- 25 files changed, 383 insertions(+), 285 deletions(-) diff --git a/.github/workflows/FormatCheck.yml b/.github/workflows/FormatCheck.yml index 9392f92..2bf43af 100644 --- a/.github/workflows/FormatCheck.yml +++ b/.github/workflows/FormatCheck.yml @@ -10,33 +10,7 @@ on: jobs: build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - julia-version: [1] - julia-arch: [x64] - os: [ubuntu-latest] + runs-on: ubuntu-latest steps: - - uses: julia-actions/setup-julia@v2 - with: - version: ${{ matrix.julia-version }} - - uses: actions/checkout@v4 - - name: Install JuliaFormatter and format - # This will use the latest version by default but you can set the version like so: - # - # julia -e 'using Pkg; Pkg.add(PackageSpec(name="JuliaFormatter", version="0.13.0"))' - run: | - julia -e 'using Pkg; Pkg.add(PackageSpec(name="JuliaFormatter"))' - julia -e 'using JuliaFormatter; format(".", verbose=true)' - - name: Format check - run: | - julia -e ' - out = Cmd(`git diff --name-only`) |> read |> String - if out == "" - exit(0) - else - @error "Some files have not been formatted !!!" - write(stdout, out) - exit(1) - end' + - uses: fredrikekre/runic-action@v1 diff --git a/README.md b/README.md index c79c4ce..7a5e86c 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,9 @@ julia> using Pkg julia> Pkg.add("CellularAutomata") ``` or, on the REPL: - + ```julia_repl -julia> ] # actually press closed square brackets +julia> ] # actually press closed square brackets pkg> add CellularAutomata ``` @@ -79,8 +79,8 @@ rule = 18 ca = CellularAutomaton(DCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -104,8 +104,8 @@ rule = 30 ca = CellularAutomaton(DCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -128,13 +128,13 @@ ncells = 111 starting_val = zeros(ncells) starting_val[Int(floor(ncells/2)+1)] = 2 -rule = 7110222193934 +rule = 7110222193934 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -157,13 +157,13 @@ ncells = 111 starting_val = zeros(ncells) starting_val[Int(floor(ncells/2)+1)] = 1 -rule = 1388968789 +rule = 1388968789 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -187,13 +187,13 @@ ncells = 111 starting_val = zeros(ncells) starting_val[Int(floor(ncells/2)+1)] = 2 -rule = 914752986721674989234787899872473589234512347899 +rule = 914752986721674989234787899872473589234512347899 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -215,13 +215,13 @@ ncells = 111 starting_val = zeros(ncells) starting_val[Int(floor(ncells/2)+1)] = 1 -rule = 1235 +rule = 1235 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -249,11 +249,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 1635 -ca = CellularAutomaton(TCA(rule, states=states), +ca = CellularAutomaton(TCA(rule, states=states), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -275,11 +275,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 107398 -ca = CellularAutomaton(TCA(rule, states=states), +ca = CellularAutomaton(TCA(rule, states=states), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -304,11 +304,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 53 -ca = CellularAutomaton(TCA(rule, radius=radius), +ca = CellularAutomaton(TCA(rule, radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -335,8 +335,8 @@ rule = 0.025 ca = CellularAutomaton(CCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -359,11 +359,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1.0 rule = 0.2 -ca = CellularAutomaton(CCA(rule, radius=radius), +ca = CellularAutomaton(CCA(rule, radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -390,16 +390,15 @@ gens = 100 space_gliding = CellularAutomaton(Life((3, (2,3))), space, gens) anim = @animate for i = 1:gens - heatmap(space_gliding.evolution[:,:,i], - yflip=true, + heatmap(evolution_history(space_gliding)[:, :, i], + yflip=true, c=cgrad([:white, :black]), legend = :none, size=(1080,1080), axis=false, ticks=false) end - + gif(anim, "glider.gif", fps = 15) ``` ![glider](https://user-images.githubusercontent.com/10376688/137601901-97940211-f6e7-4ab1-9eee-325165000fd4.gif) - diff --git a/docs/Project.toml b/docs/Project.toml index 4a97ffc..74a28b8 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -2,3 +2,7 @@ CellularAutomata = "878138dc-5b27-11ea-1a71-cb95d38d6b29" Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" + +[compat] +Documenter = "1.17" +Plots = "1.41" diff --git a/docs/make.jl b/docs/make.jl index 88b0ac0..a5ff7fb 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -2,20 +2,20 @@ using Documenter, CellularAutomata include("pages.jl") makedocs(; - sitename="CellularAutomata.jl", - modules=[CellularAutomata], - clean=true, - doctest=true, - linkcheck=true, - linkcheck_ignore=[r"https://golly\.sourceforge\.net"], - format=Documenter.HTML(; - assets=["assets/favicon.ico"], - canonical="https://MartinuzziFrancesco.github.io/CellularAutomata.jl" + sitename = "CellularAutomata.jl", + modules = [CellularAutomata], + clean = true, + doctest = true, + linkcheck = true, + linkcheck_ignore = [r"https://golly\.sourceforge\.net"], + format = Documenter.HTML(; + assets = ["assets/favicon.ico"], + canonical = "https://MartinuzziFrancesco.github.io/CellularAutomata.jl" ), - warnonly=[:missing_docs], - pages=pages + warnonly = [:missing_docs], + pages = pages ) deploydocs(; - repo="github.com/MartinuzziFrancesco/CellularAutomata.jl.git", push_preview=true + repo = "github.com/MartinuzziFrancesco/CellularAutomata.jl.git", push_preview = true ) diff --git a/docs/pages.jl b/docs/pages.jl index c061fc1..3432126 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -1,9 +1,13 @@ pages = [ "CellularAutomata.jl" => "index.md", "Differentiable cellular automata" => "ad_design.md", - "Examples" => ["One dimensional CA" => "onedim/onedimensionca.md" - "Two dimensional CA" => "twodim/twodimensionca.md"], - "API Documentation" => Any["General APIs" => "api/general.md" - "One Dimensional CA" => "api/onedim.md" - "Two Dimensional CA" => "api/twodim.md"] + "Examples" => [ + "One dimensional CA" => "onedim/onedimensionca.md" + "Two dimensional CA" => "twodim/twodimensionca.md" + ], + "API Documentation" => Any[ + "General APIs" => "api/general.md" + "One Dimensional CA" => "api/onedim.md" + "Two Dimensional CA" => "api/twodim.md" + ], ] diff --git a/docs/src/api/general.md b/docs/src/api/general.md index 7ec6f18..dbf6b6d 100644 --- a/docs/src/api/general.md +++ b/docs/src/api/general.md @@ -4,6 +4,12 @@ CellularAutomaton next_state rollout + cellular_automaton_rule + evolution_history + generation_count + neighborhood_radius + rule_lookup_table + cell_state_count Periodic Reflecting ConstantBoundary diff --git a/docs/src/index.md b/docs/src/index.md index 35504d8..3848122 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -1,13 +1,13 @@ # CellularAutomata.jl -This package is meant to be a complete Open source reference for everything regarding Cellular Automata. -In it you will find ways to create one and two dimensional Cellular Automata models and functions -to analyze them +This package provides one- and two-dimensional cellular-automaton models and +analysis functions. ## General usage -The main function is given by `CellularAutomaton` where `rule` is a function returning the next state of the Cellular Automata. - +Construct a rule such as `DCA`, `TCA`, `CCA`, or `Life`, then pass it with an +initial state to `CellularAutomaton`. Use `next_state` and `rollout` when retained +history is not required. ## Contributions diff --git a/docs/src/onedim/onedimensionca.md b/docs/src/onedim/onedimensionca.md index e9af432..83164ac 100644 --- a/docs/src/onedim/onedimensionca.md +++ b/docs/src/onedim/onedimensionca.md @@ -19,8 +19,8 @@ rule = 18 ca = CellularAutomaton(DCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -41,8 +41,8 @@ rule = 30 ca = CellularAutomaton(DCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -60,16 +60,16 @@ states = 3 radius = 1 generations = 50 ncells = 111 -starting_val = zeros(ncells) +starting_val = zeros(Int, ncells) starting_val[Int(floor(ncells/2)+1)] = 2 -rule = 7110222193934 +rule = 7110222193934 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -89,16 +89,16 @@ states = 2 radius = 2 generations = 30 ncells = 111 -starting_val = zeros(ncells) +starting_val = zeros(Int, ncells) starting_val[Int(floor(ncells/2)+1)] = 1 -rule = 1388968789 +rule = 1388968789 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -115,16 +115,16 @@ states = 3 radius = 2 generations = 30 ncells = 111 -starting_val = zeros(ncells) +starting_val = zeros(Int, ncells) starting_val[Int(floor(ncells/2)+1)] = 2 -rule = 914752986721674989234787899872473589234512347899 +rule = 914752986721674989234787899872473589234512347899 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -140,16 +140,16 @@ states = 2 radius = (2,1) generations = 30 ncells = 111 -starting_val = zeros(ncells) +starting_val = zeros(Int, ncells) starting_val[Int(floor(ncells/2)+1)] = 1 -rule = 1235 +rule = 1235 -ca = CellularAutomaton(DCA(rule,states=states,radius=radius), +ca = CellularAutomaton(DCA(rule,states=states,radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -174,11 +174,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 1635 -ca = CellularAutomaton(DCA(rule, states=states), +ca = CellularAutomaton(DCA(rule, states=states), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -197,11 +197,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 107398 -ca = CellularAutomaton(DCA(rule, states=states), +ca = CellularAutomaton(DCA(rule, states=states), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -222,11 +222,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1 rule = 53 -ca = CellularAutomaton(DCA(rule, radius=radius), +ca = CellularAutomaton(DCA(rule, radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -251,8 +251,8 @@ rule = 0.025 ca = CellularAutomaton(CCA(rule), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, @@ -270,11 +270,11 @@ starting_val[Int(floor(ncells/2)+1)] = 1.0 rule = 0.2 -ca = CellularAutomaton(CCA(rule, radius=radius), +ca = CellularAutomaton(CCA(rule, radius=radius), starting_val, generations) -heatmap(ca.evolution, - yflip=true, +heatmap(evolution_history(ca), + yflip=true, c=cgrad([:white, :black]), legend = :none, axis=false, diff --git a/docs/src/twodim/twodimensionca.md b/docs/src/twodim/twodimensionca.md index 52d595d..8b65f0a 100644 --- a/docs/src/twodim/twodimensionca.md +++ b/docs/src/twodim/twodimensionca.md @@ -18,14 +18,14 @@ gens = 100 space_gliding = CellularAutomaton(Life((3, (2,3))), space, gens) anim = @animate for i = 1:gens - heatmap(space_gliding.evolution[:,:,i], - yflip=true, + heatmap(evolution_history(space_gliding)[:, :, i], + yflip=true, c=cgrad([:white, :black]), legend = :none, size=(1080,1080), axis=false, ticks=false) end - + gif(anim, "glider.gif", fps = 15) ``` diff --git a/src/CellularAutomata.jl b/src/CellularAutomata.jl index cb7e376..314bd92 100644 --- a/src/CellularAutomata.jl +++ b/src/CellularAutomata.jl @@ -18,6 +18,8 @@ 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 DCA export CCA export TCA diff --git a/src/cellular_automaton.jl b/src/cellular_automaton.jl index dec865f..4cdb32e 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -38,18 +38,19 @@ julia> next_state(DCA(30), [0, 0, 1, 0, 0]) function next_state( rule::AbstractCellularAutomatonRule, state; - boundary::AbstractBoundaryCondition=Periodic() -) - return _step(rule, state, boundary) + boundary::AbstractBoundaryCondition = Periodic() + ) + __validate_state(rule, state) + return __step(rule, state, boundary) end -@concrete struct Transition +@concrete struct __Transition rule boundary end -function (transition::Transition)(state, _) - return next_state(transition.rule, state; boundary=transition.boundary) +function (transition::__Transition)(state, _) + return next_state(transition.rule, state; boundary = transition.boundary) end """ @@ -94,25 +95,25 @@ function rollout( rule::AbstractCellularAutomatonRule, initial_state, steps::Integer; - boundary::AbstractBoundaryCondition=Periodic(), - save::Bool=false -) + boundary::AbstractBoundaryCondition = Periodic(), + save::Bool = false + ) steps >= 0 || throw(ArgumentError("steps must be nonnegative")) isempty(initial_state) && throw(ArgumentError("initial_state cannot be empty")) - transition = Transition(rule, boundary) + transition = __Transition(rule, boundary) if save - states = accumulate(transition, 1:steps; init=initial_state) + states = accumulate(transition, 1:steps; init = initial_state) return stack(Iterators.flatten(((initial_state,), states))) end - return foldl(transition, 1:steps; init=initial_state) + return foldl(transition, 1:steps; init = initial_state) end """ CellularAutomaton(rule, initial_conditions, generations) Construct a cellular automaton and retain its complete evolution history. For vector -states, `evolution` stores time on the first axis. For higher-dimensional states, -time is stored on the last axis. +states, `evolution_history(automaton)` stores time on the first axis. For +higher-dimensional states, time is stored on the last axis. # Arguments @@ -130,7 +131,7 @@ CellularAutomaton with 3 generations rule: DCA(30; states=2, radius=1) evolution: 3×3 Matrix{Int64} -julia> automaton.evolution +julia> evolution_history(automaton) 3×3 Matrix{Int64}: 0 1 0 1 1 1 @@ -147,9 +148,9 @@ function CellularAutomaton( rule::AbstractCellularAutomatonRule, initial_conditions::AbstractVector, generations::Integer -) + ) generations >= 1 || throw(ArgumentError("generations must be at least 1")) - history = rollout(rule, initial_conditions, generations - 1; save=true) + history = rollout(rule, initial_conditions, generations - 1; save = true) return CellularAutomaton(Int(generations), rule, permutedims(history)) end @@ -157,12 +158,33 @@ function CellularAutomaton( rule::AbstractCellularAutomatonRule, initial_conditions::AbstractArray, generations::Integer -) + ) generations >= 1 || throw(ArgumentError("generations must be at least 1")) - evolution = rollout(rule, initial_conditions, generations - 1; save=true) + evolution = rollout(rule, initial_conditions, generations - 1; save = true) return CellularAutomaton(Int(generations), rule, evolution) end +""" + cellular_automaton_rule(automaton::AbstractCellularAutomaton) + +Return the transition rule used by `automaton`. +""" +cellular_automaton_rule(automaton::CellularAutomaton) = automaton.rule + +""" + evolution_history(automaton::AbstractCellularAutomaton) + +Return the retained cellular-automaton evolution. +""" +evolution_history(automaton::CellularAutomaton) = automaton.evolution + +""" + generation_count(automaton::AbstractCellularAutomaton) -> Int + +Return the number of generations retained by `automaton`. +""" +generation_count(automaton::CellularAutomaton) = automaton.generations + function Base.show(io::IO, automaton::CellularAutomaton) return print( io, "CellularAutomaton(", automaton.rule, "; generations=", diff --git a/src/generics.jl b/src/generics.jl index ef43464..872c763 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -2,7 +2,7 @@ AbstractCellularAutomatonRule Supertype for cellular-automaton transition rules. Subtypes must implement -`_step(rule, state, boundary)` returning the next state without mutating `state`, +`__step(rule, state, boundary)` returning the next state without mutating `state`, or specialize [`next_state`](@ref) directly. """ abstract type AbstractCellularAutomatonRule end @@ -79,54 +79,70 @@ function Base.show(io::IO, boundary::ConstantBoundary) return print(io, "ConstantBoundary(", boundary.value, ")") end -@inline _boundary_index(i, n, ::Periodic) = mod1(i, n) -@inline function _boundary_index(i, n, ::Reflecting) +@inline __boundary_index(i, n, ::Periodic) = mod1(i, n) +@inline function __boundary_index(i, n, ::Reflecting) n == 1 && return 1 reflected = mod(i - 1, 2n - 2) + 1 return reflected <= n ? reflected : 2n - reflected end -@inline function _boundary_get(array, boundary::Union{Periodic, Reflecting}, i) - return array[_boundary_index(i, length(array), boundary)] +@inline function __boundary_get(array, boundary::Union{Periodic, Reflecting}, i) + return array[__boundary_index(i, length(array), boundary)] end -@inline function _boundary_get(array, boundary::Union{Periodic, Reflecting}, i, j) - row = _boundary_index(i, size(array, 1), boundary) - column = _boundary_index(j, size(array, 2), boundary) +@inline function __boundary_get(array, boundary::Union{Periodic, Reflecting}, i, j) + row = __boundary_index(i, size(array, 1), boundary) + column = __boundary_index(j, size(array, 2), boundary) return array[row, column] end -@inline function _boundary_get(array, boundary::ConstantBoundary, i) +@inline function __boundary_get(array, boundary::ConstantBoundary, i) return checkbounds(Bool, array, i) ? array[i] : boundary.value end -@inline function _boundary_get(array, boundary::ConstantBoundary, i, j) +@inline function __boundary_get(array, boundary::ConstantBoundary, i, j) return checkbounds(Bool, array, i, j) ? array[i, j] : boundary.value end -@concrete struct Neighborhood1D +@concrete struct __Neighborhood1D array boundary indices end -Base.length(neighborhood::Neighborhood1D) = length(neighborhood.indices) -Base.IteratorSize(::Type{<:Neighborhood1D}) = Base.HasLength() -function Base.iterate(neighborhood::Neighborhood1D, state...) +Base.length(neighborhood::__Neighborhood1D) = length(neighborhood.indices) +Base.IteratorSize(::Type{<:__Neighborhood1D}) = Base.HasLength() +function Base.iterate(neighborhood::__Neighborhood1D, state...) iteration = iterate(neighborhood.indices, state...) isnothing(iteration) && return nothing index, next_iteration = iteration - return _boundary_get(neighborhood.array, neighborhood.boundary, index), next_iteration + return __boundary_get(neighborhood.array, neighborhood.boundary, index), next_iteration end -_radius_extent(radius::Integer) = (radius, radius) -_radius_extent(radius::Tuple{<:Integer, <:Integer}) = radius +__radius_extent(radius::Integer) = (radius, radius) +__radius_extent(radius::Tuple{<:Integer, <:Integer}) = radius -function _validate_radius(radius) - left, right = _radius_extent(radius) +function __validate_radius(radius) + left, right = __radius_extent(radius) if left < 0 || right < 0 throw(ArgumentError("radius must be nonnegative")) end return nothing end +__validate_state(::AbstractCellularAutomatonRule, state) = nothing + +function __validate_discrete_state(state, states) + for value in state + if !(value isa Integer && 0 <= value < states) + throw( + ArgumentError( + "state values must be integers between 0 and $(states - 1), " * + "but found $(repr(value))" + ) + ) + end + end + return nothing +end + """ spatial_dimensions(rule) diff --git a/src/measures.jl b/src/measures.jl index 406787e..84e6eac 100644 --- a/src/measures.jl +++ b/src/measures.jl @@ -1,4 +1,4 @@ -function lempel_ziv_complexity(sequence) +function __lempel_ziv_complexity(sequence) sub_strings = Set() n = length(sequence) @@ -37,13 +37,14 @@ julia> lempel_ziv(automaton) ``` """ function lempel_ziv(ca::AbstractCellularAutomaton) - ca.evolution isa AbstractMatrix || + history = evolution_history(ca) + history isa AbstractMatrix || throw(ArgumentError("lempel_ziv only supports one-dimensional automata")) - ca_size = size(ca.evolution, 1) + ca_size = size(history, 1) lz_tot = 0 for i in 1:ca_size - lz_tot += lempel_ziv_complexity(ca.evolution[i, :]) + lz_tot += __lempel_ziv_complexity(history[i, :]) end return lz_tot / ca_size end diff --git a/src/rules/cca.jl b/src/rules/cca.jl index 413d46c..50b5c44 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -40,8 +40,8 @@ julia> next_state(cca, [0 // 1, 0 // 1, 3 // 10]) 1//5 ``` """ -function CCA(rule::Real; radius=1) - _validate_radius(radius) +function CCA(rule::Real; radius = 1) + __validate_radius(radius) return CCA(rule, radius) end @@ -49,13 +49,13 @@ function (cca::CCA)(starting_array::AbstractArray) return next_state(cca, starting_array) end -function _step(cca::CCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) - return cca_evolution(cell, cca.rule, cca.radius, boundary) +function __step(cca::CCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __cca_evolution(cell, cca.rule, cca.radius, boundary) end -fractional_part(value) = value - floor(value) +__fractional_part(value) = value - floor(value) -@concrete struct CCAUpdate +@concrete struct __CCAUpdate cell rule boundary @@ -63,19 +63,26 @@ fractional_part(value) = value - floor(value) right end -function (update::CCAUpdate)(index) +function (update::__CCAUpdate)(index) indices = (index - update.left):(index + update.right) - neighborhood = Neighborhood1D(update.cell, update.boundary, indices) - return fractional_part(sum(neighborhood) / length(neighborhood) + update.rule) + neighborhood = __Neighborhood1D(update.cell, update.boundary, indices) + return __fractional_part(sum(neighborhood) / length(neighborhood) + update.rule) end -function cca_evolution( - cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition=Periodic() -) - left, right = _radius_extent(radius) - return map(CCAUpdate(cell, rule, boundary, left, right), eachindex(cell)) +function __cca_evolution( + cell::AbstractVector, rule::Real, radius, boundary::AbstractBoundaryCondition = Periodic() + ) + left, right = __radius_extent(radius) + 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) return print(io, "CCA(", cca.rule, "; radius=", cca.radius, ")") end diff --git a/src/rules/dca.jl b/src/rules/dca.jl index 92b19bf..bdb3e82 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -28,6 +28,11 @@ Construct a discrete cellular-automaton rule and its neighborhood lookup table. - `states`: Number of possible cell states. Defaults to 2. - `radius`: Symmetric radius or `(left, right)` asymmetric radius. Defaults to 1. +# Throws + + - `ArgumentError`: If the rule configuration or a transitioned state is outside its + declared discrete domain. + # Examples ```jldoctest @@ -35,7 +40,7 @@ julia> using CellularAutomata julia> dca = DCA(30); -julia> dca.ruleset +julia> rule_lookup_table(dca) 8-element Vector{Int64}: 0 1 @@ -55,10 +60,10 @@ julia> next_state(dca, [0, 0, 1, 0, 0]) 0 ``` """ -function DCA(rule::Integer; states::Int=2, radius=1) +function DCA(rule::Integer; states::Int = 2, radius = 1) states >= 2 || throw(ArgumentError("states must be at least 2")) - _validate_radius(radius) - ruleset = conversion(rule, states, radius) + __validate_radius(radius) + ruleset = __conversion(rule, states, radius) return DCA(rule, ruleset, states, radius) end @@ -66,24 +71,26 @@ function (dca::DCA)(starting_array::AbstractArray) return next_state(dca, starting_array) end -function _step(dca::DCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) - return dca_evolution(cell, dca.ruleset, dca.states, dca.radius, boundary) +__validate_state(dca::DCA, state) = __validate_discrete_state(state, dca.states) + +function __step(dca::DCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __dca_evolution(cell, dca.ruleset, dca.states, dca.radius, boundary) end -function conversion(rule::Integer, states::Int, radius) - left, right = _radius_extent(radius) - return digits_ruleset(rule, states, states^(left + right + 1)) +function __conversion(rule::Integer, states::Int, radius) + left, right = __radius_extent(radius) + return __digits_ruleset(rule, states, states^(left + right + 1)) end -function digits_ruleset(rule::Integer, states::Int, len::Int) +function __digits_ruleset(rule::Integer, states::Int, len::Int) rule >= 0 || throw(ArgumentError("rule must be nonnegative")) - ruleset = digits(rule; base=states, pad=len) + ruleset = digits(rule; base = states, pad = len) length(ruleset) <= len || throw(ArgumentError("rule does not fit the requested states and radius")) return ruleset end -function state_reader(neighborhood, states::Int) +function __state_reader(neighborhood, states::Int) index = 0 for cell in neighborhood index = index * states + Int(cell) @@ -91,7 +98,7 @@ function state_reader(neighborhood, states::Int) return index + 1 end -@concrete struct DCAUpdate +@concrete struct __DCAUpdate cell ruleset states @@ -100,25 +107,42 @@ end right end -function (update::DCAUpdate)(index) +function (update::__DCAUpdate)(index) indices = (index - update.left):(index + update.right) - neighborhood = Neighborhood1D(update.cell, update.boundary, indices) - new_state = update.ruleset[state_reader(neighborhood, update.states)] + neighborhood = __Neighborhood1D(update.cell, update.boundary, indices) + new_state = update.ruleset[__state_reader(neighborhood, update.states)] return convert(eltype(update.cell), new_state) end -function dca_evolution( +function __dca_evolution( cell::AbstractVector, ruleset, states::Int, radius, - boundary::AbstractBoundaryCondition=Periodic() -) - left, right = _radius_extent(radius) - return map(DCAUpdate(cell, ruleset, states, boundary, left, right), eachindex(cell)) + boundary::AbstractBoundaryCondition = Periodic() + ) + left, right = __radius_extent(radius) + return map(__DCAUpdate(cell, ruleset, states, boundary, left, right), eachindex(cell)) end +""" + rule_lookup_table(rule::AbstractDiscreteCellularAutomatonRule) + +Return the neighborhood lookup table used by `rule`. +""" +rule_lookup_table(dca::DCA) = dca.ruleset + +""" + cell_state_count(rule::AbstractDiscreteCellularAutomatonRule) -> Int + +Return the number of possible cell states supported by `rule`. +""" +cell_state_count(dca::DCA) = dca.states + +neighborhood_radius(dca::DCA) = dca.radius + function Base.show(io::IO, dca::DCA) return print( - io, "DCA(", dca.rule, "; states=", dca.states, ", radius=", dca.radius, ")") + io, "DCA(", dca.rule, "; states=", dca.states, ", radius=", dca.radius, ")" + ) end diff --git a/src/rules/life.jl b/src/rules/life.jl index 5d92cb5..540cc81 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -45,7 +45,7 @@ julia> next_state(life, blinker) 0 0 0 0 0 ``` """ -function Life(life_description::Tuple; radius::Int=1) +function Life(life_description::Tuple; radius::Int = 1) radius >= 1 || throw(ArgumentError("radius must be at least 1")) born, survive = life_description return Life(born, survive, radius) @@ -55,11 +55,11 @@ 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) +function __step(life::Life, state::AbstractMatrix, boundary::AbstractBoundaryCondition) + return __life_evolution(state, life.born, life.survive, life.radius, boundary) end -@concrete struct LifeUpdate +@concrete struct __LifeUpdate state born survive @@ -67,7 +67,7 @@ end boundary end -function (update::LifeUpdate)(index::CartesianIndex{2}) +function (update::__LifeUpdate)(index::CartesianIndex{2}) row, column = Tuple(index) radius = update.radius alive = 0 @@ -75,29 +75,31 @@ function (update::LifeUpdate)(index::CartesianIndex{2}) if !iszero(row_offset) || !iszero(column_offset) alive += Int( - _boundary_get( - update.state, update.boundary, row + row_offset, column + column_offset - ), + __boundary_get( + update.state, update.boundary, row + row_offset, column + column_offset + ), ) end end current = update.state[index] lives = (isone(current) && alive in update.survive) || - (iszero(current) && alive in update.born) + (iszero(current) && alive in update.born) return convert(eltype(update.state), lives) end -function life_evolution( +function __life_evolution( starting_array::AbstractMatrix, born, survive, radius::Int, - boundary::AbstractBoundaryCondition=Periodic() -) - update = LifeUpdate(starting_array, born, survive, radius, boundary) + boundary::AbstractBoundaryCondition = Periodic() + ) + update = __LifeUpdate(starting_array, born, survive, radius, boundary) return map(update, CartesianIndices(starting_array)) end +neighborhood_radius(life::Life) = life.radius + function Base.show(io::IO, life::Life) return print(io, "Life(", (life.born, life.survive), "; radius=", life.radius, ")") end diff --git a/src/rules/tca.jl b/src/rules/tca.jl index ecced4c..2d78380 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -4,7 +4,7 @@ Supertype for rules whose transitions depend on the total neighborhood state. """ abstract type AbstractTotalisticCellularAutomatonRule <: - AbstractDiscreteCellularAutomatonRule end +AbstractDiscreteCellularAutomatonRule end @concrete struct TCA <: AbstractTotalisticCellularAutomatonRule code @@ -29,6 +29,11 @@ Construct a totalistic cellular-automaton rule and its lookup table. - `states`: Number of possible cell states. Defaults to 2. - `radius`: Symmetric radius or `(left, right)` asymmetric radius. Defaults to 1. +# Throws + + - `ArgumentError`: If the rule configuration or a transitioned state is outside its + declared discrete domain. + # Examples ```jldoctest @@ -36,7 +41,7 @@ julia> using CellularAutomata julia> tca = TCA(3); -julia> tca.codeset +julia> rule_lookup_table(tca) 4-element Vector{Int64}: 1 1 @@ -52,10 +57,10 @@ julia> next_state(tca, [0, 0, 1, 0, 0]) 1 ``` """ -function TCA(code::Integer; states::Int=2, radius=1) +function TCA(code::Integer; states::Int = 2, radius = 1) states >= 2 || throw(ArgumentError("states must be at least 2")) - _validate_radius(radius) - codeset = tca_conversion(code, states, radius) + __validate_radius(radius) + codeset = __tca_conversion(code, states, radius) return TCA(code, codeset, states, radius) end @@ -63,18 +68,20 @@ function (tca::TCA)(starting_array::AbstractArray) return next_state(tca, starting_array) end -function _step(tca::TCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) - return tca_evolution(cell, tca.codeset, tca.radius, boundary) +__validate_state(tca::TCA, state) = __validate_discrete_state(state, tca.states) + +function __step(tca::TCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __tca_evolution(cell, tca.codeset, tca.radius, boundary) end -function tca_conversion(code::Integer, states::Int, radius) - left, right = _radius_extent(radius) - return digits_ruleset(code, states, (states - 1) * (left + right + 1) + 1) +function __tca_conversion(code::Integer, states::Int, radius) + left, right = __radius_extent(radius) + return __digits_ruleset(code, states, (states - 1) * (left + right + 1) + 1) end -tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 +__tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 -@concrete struct TCAUpdate +@concrete struct __TCAUpdate cell codeset boundary @@ -82,21 +89,26 @@ tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 right end -function (update::TCAUpdate)(index) +function (update::__TCAUpdate)(index) indices = (index - update.left):(index + update.right) - neighborhood = Neighborhood1D(update.cell, update.boundary, indices) - new_state = update.codeset[tca_state_reader(neighborhood)] + neighborhood = __Neighborhood1D(update.cell, update.boundary, indices) + new_state = update.codeset[__tca_state_reader(neighborhood)] return convert(eltype(update.cell), new_state) end -function tca_evolution( - cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition=Periodic() -) - left, right = _radius_extent(radius) - return map(TCAUpdate(cell, codeset, boundary, left, right), eachindex(cell)) +function __tca_evolution( + cell::AbstractVector, codeset, radius, boundary::AbstractBoundaryCondition = Periodic() + ) + left, right = __radius_extent(radius) + return map(__TCAUpdate(cell, codeset, boundary, left, right), eachindex(cell)) end +rule_lookup_table(tca::TCA) = tca.codeset +cell_state_count(tca::TCA) = tca.states +neighborhood_radius(tca::TCA) = tca.radius + function Base.show(io::IO, tca::TCA) return print( - io, "TCA(", tca.code, "; states=", tca.states, ", radius=", tca.radius, ")") + io, "TCA(", tca.code, "; states=", tca.states, ", radius=", tca.radius, ")" + ) end diff --git a/test/ad_test.jl b/test/ad_test.jl index bb5271f..f00ac4f 100644 --- a/test/ad_test.jl +++ b/test/ad_test.jl @@ -7,8 +7,8 @@ using Test rule = CCA(0.0) @test next_state(rule, initial) ≈ [0.2, 0.2, 0.2] - @test next_state(rule, initial; boundary=ConstantBoundary()) ≈ [0.1, 0.2, 1 / 6] - @test next_state(rule, initial; boundary=Reflecting()) ≈ [1 / 6, 0.2, 7 / 30] + @test next_state(rule, initial; boundary = ConstantBoundary()) ≈ [0.1, 0.2, 1 / 6] + @test next_state(rule, initial; boundary = Reflecting()) ≈ [1 / 6, 0.2, 7 / 30] @test initial == [0.1, 0.2, 0.3] @test next_state(CCA(big"0.01"), BigFloat[0.1, 0.2]) isa Vector{BigFloat} @@ -16,7 +16,7 @@ using Test initial_view = @view parent[2:4] @test next_state(rule, initial_view) ≈ [0.2, 0.2, 0.2] - history = rollout(rule, initial, 2; save=true) + history = rollout(rule, initial, 2; save = true) @test size(history) == (3, 3) @test history[:, 1] == initial @test rollout(rule, initial, 0) === initial @@ -25,16 +25,16 @@ end @testset "multi-step differentiation" begin initial = fill(0.1, 4) - objective(rule_value) = sum(rollout(CCA(rule_value; radius=0), initial, 3)) + objective(rule_value) = sum(rollout(CCA(rule_value; radius = 0), initial, 3)) @test ForwardDiff.derivative(objective, 0.01) ≈ 12.0 - @test ForwardDiff.jacobian(x -> rollout(CCA(0.01; radius=0), x, 3), initial) ≈ - [i == j ? 1.0 : 0.0 for i in 1:4, j in 1:4] + @test ForwardDiff.jacobian(x -> rollout(CCA(0.01; radius = 0), x, 3), initial) ≈ + [i == j ? 1.0 : 0.0 for i in 1:4, j in 1:4] function final_state_loss(x) ca = CellularAutomaton(CCA(0.45), x, 5) return sum(abs2, ca.evolution[end, :]) end - x0 = collect(range(0.1, 0.9; length=11)) + x0 = collect(range(0.1, 0.9; length = 11)) grad = ForwardDiff.gradient(final_state_loss, x0) @test length(grad) == length(x0) @test any(!iszero, grad) diff --git a/test/blinker_test.jl b/test/blinker_test.jl index e42a8c9..97524ce 100644 --- a/test/blinker_test.jl +++ b/test/blinker_test.jl @@ -10,5 +10,5 @@ ca = CellularAutomaton(Life((3, (2, 3))), blinker, gens) [0 0 0 0 0; 0 0 0 0 0; 0 1 1 1 0; 0 0 0 0 0; 0 0 0 0 0], [0 0 0 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 0 0 0], [0 0 0 0 0; 0 0 0 0 0; 0 1 1 1 0; 0 0 0 0 0; 0 0 0 0 0]; - dims=3 + dims = 3 ) diff --git a/test/dca_test.jl b/test/dca_test.jl index b83d63a..2a76ced 100644 --- a/test/dca_test.jl +++ b/test/dca_test.jl @@ -9,7 +9,7 @@ const starting_array = rand(0:(states - 1), ncells) const rule = 107396 #testing states > 2 -ca = CellularAutomaton(DCA(rule; states=states), starting_array, generations) +ca = CellularAutomaton(DCA(rule; states = states), starting_array, generations) @test size(ca.evolution) == (generations, ncells) diff --git a/test/glider_test.jl b/test/glider_test.jl index 012261a..4fb294c 100644 --- a/test/glider_test.jl +++ b/test/glider_test.jl @@ -15,5 +15,5 @@ ca = CellularAutomaton(Life((3, (2, 3))), space, gens) [0 0 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 1 1 1 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0], [0 0 0 0 0 0; 0 0 0 0 0 0; 0 1 0 1 0 0; 0 0 1 1 0 0; 0 0 1 0 0 0; 0 0 0 0 0 0], [0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 1 0 0; 0 1 0 1 0 0; 0 0 1 1 0 0; 0 0 0 0 0 0]; - dims=3 + dims = 3 ) diff --git a/test/qa.jl b/test/qa.jl index 7051d7f..7741471 100644 --- a/test/qa.jl +++ b/test/qa.jl @@ -1,10 +1,10 @@ using CellularAutomata using Aqua: Aqua -Aqua.test_all(CellularAutomata; ambiguities=false, deps_compat=(check_extras = false)) +Aqua.test_all(CellularAutomata; ambiguities = false, deps_compat = (check_extras = false)) # JET 0.9 (the only release available on Julia < 1.12) reports false positives -# inside Base's digits! BigInt path when analyzing digits_ruleset abstractly. +# inside Base's `digits!` BigInt path when analyzing `__digits_ruleset` abstractly. @static if VERSION >= v"1.12" using JET JET.test_package(CellularAutomata) diff --git a/test/regression_test.jl b/test/regression_test.jl index 6ae74d9..d02db6e 100644 --- a/test/regression_test.jl +++ b/test/regression_test.jl @@ -7,8 +7,23 @@ using Test @test_throws ArgumentError CellularAutomaton(DCA(0), [1], 0) @test_throws ArgumentError DCA(-1) @test_throws ArgumentError DCA(256) - @test length(TCA(0; states=2, radius=2).codeset) == 6 - @test length(TCA(0; states=3, radius=(1, 2)).codeset) == 9 + @test_throws ArgumentError next_state(DCA(30), [0, 2, 0]) + @test_throws ArgumentError next_state(DCA(30), [0.0, 1.0, 0.0]) + @test_throws ArgumentError next_state(TCA(3), [0, -1, 0]) + @test length(TCA(0; states = 2, radius = 2).codeset) == 6 + @test length(TCA(0; states = 3, radius = (1, 2)).codeset) == 9 +end + +@testset "public accessors" begin + automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3) + @test cellular_automaton_rule(automaton) === automaton.rule + @test evolution_history(automaton) === automaton.evolution + @test generation_count(automaton) == 3 + @test rule_lookup_table(automaton.rule) === automaton.rule.ruleset + @test cell_state_count(automaton.rule) == 2 + @test neighborhood_radius(automaton.rule) == 1 + @test neighborhood_radius(CCA(0.1; radius = (1, 2))) == (1, 2) + @test neighborhood_radius(Life(((3,), (2, 3)); radius = 2)) == 2 end @testset "concrete fields" begin @@ -18,7 +33,7 @@ end TCA(3), CCA(0.1), Life(((3,), (2, 3))), - ConstantBoundary(0.0) + ConstantBoundary(0.0), ) for object in objects @test all(isconcretetype, fieldtypes(typeof(object))) @@ -37,7 +52,7 @@ end end @testset "asymmetric continuous neighborhoods" begin - rule = CCA(0.0; radius=(0, 1)) + rule = CCA(0.0; radius = (0, 1)) @test rule([0.0, 0.0, 1.0]) ≈ [0.0, 0.5, 0.5] @test eltype(CCA(0.0f0)(Float32[0, 1])) == Float32 end @@ -52,9 +67,9 @@ end automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3) @test repr(automaton) == "CellularAutomaton(DCA(30; states=2, radius=1); generations=3)" @test repr(MIME"text/plain"(), automaton) == - "CellularAutomaton with 3 generations\n" * - " rule: DCA(30; states=2, radius=1)\n" * - " evolution: 3×3 Matrix{Int64}" + "CellularAutomaton with 3 generations\n" * + " rule: DCA(30; states=2, radius=1)\n" * + " evolution: 3×3 Matrix{Int64}" end @testset "Life is synchronous and supports larger radii" begin @@ -64,7 +79,7 @@ end @test input == copy_before all_alive = trues(3, 4) - result = Life(((), ()); radius=2)(all_alive) + result = Life(((), ()); radius = 2)(all_alive) @test size(result) == size(all_alive) @test !any(result) end diff --git a/test/runtests.jl b/test/runtests.jl index 056b212..2995bed 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,32 +1,42 @@ using Test using SafeTestsets -@testset "Quality Assurance" begin - @safetestset "Quality Assurance" include("qa.jl") -end +const GROUP = get(ENV, "GROUP", "All") +const VALID_GROUPS = ("All", "Core", "QA") -@testset "DCA" begin - @safetestset "Size tests" include("dca_test.jl") - @safetestset "ECA ruleset tests" include("eca_ruleset_test.jl") -end +GROUP in VALID_GROUPS || + throw(ArgumentError("GROUP must be one of $(join(VALID_GROUPS, ", ")); got $(repr(GROUP))")) -@testset "TCA" begin - @safetestset "Size tests" include("tca_test.jl") +if GROUP in ("All", "QA") + @testset "Quality Assurance" begin + @safetestset "Quality Assurance" include("qa.jl") + end end -@testset "CCA" begin - @safetestset "Size tests" include("cca_test.jl") -end +if GROUP in ("All", "Core") + @testset "DCA" begin + @safetestset "Size tests" include("dca_test.jl") + @safetestset "ECA ruleset tests" include("eca_ruleset_test.jl") + end -@testset "AD" begin - @safetestset "ForwardDiff through CCA" include("ad_test.jl") -end + @testset "TCA" begin + @safetestset "Size tests" include("tca_test.jl") + end -@testset "Regression" begin - @safetestset "Edge cases and hierarchy" include("regression_test.jl") -end + @testset "CCA" begin + @safetestset "Size tests" include("cca_test.jl") + end + + @testset "AD" begin + @safetestset "ForwardDiff through CCA" include("ad_test.jl") + end + + @testset "Regression" begin + @safetestset "Edge cases and hierarchy" include("regression_test.jl") + end -@testset "Life-like" begin - @safetestset "Life glider" include("glider_test.jl") - @safetestset "Life blinker" include("blinker_test.jl") + @testset "Life-like" begin + @safetestset "Life glider" include("glider_test.jl") + @safetestset "Life blinker" include("blinker_test.jl") + end end diff --git a/test/tca_test.jl b/test/tca_test.jl index 618dbbc..524bf03 100644 --- a/test/tca_test.jl +++ b/test/tca_test.jl @@ -9,7 +9,7 @@ const starting_array = rand(0:(states - 1), ncells) const rule = 107396 #testing states > 2 -ca = CellularAutomaton(DCA(rule; states=states), starting_array, generations) +ca = CellularAutomaton(DCA(rule; states = states), starting_array, generations) @test size(ca.evolution) == (generations, ncells)