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..0fa272e 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: | @@ -66,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..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: [x86] - os: [ubuntu-latest] + runs-on: ubuntu-latest steps: - - uses: julia-actions/setup-julia@latest - 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/Project.toml b/Project.toml index 861c9cf..cdde115 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.1.0" + +[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/README.md b/README.md index 310ccb8..7a5e86c 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 @@ -49,21 +49,21 @@ 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 ``` ## 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 @@ -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, @@ -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 @@ -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, @@ -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 @@ -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, @@ -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 @@ -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, @@ -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 @@ -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, @@ -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: @@ -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 3b95229..a5ff7fb 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -2,19 +2,20 @@ using Documenter, CellularAutomata include("pages.jl") makedocs(; - sitename="CellularAutomata.jl", - modules=[CellularAutomata], - clean=true, - doctest=true, - linkcheck=true, - 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 6dbd394..3432126 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" @@ -7,6 +8,6 @@ pages = [ "API Documentation" => Any[ "General APIs" => "api/general.md" "One Dimensional CA" => "api/onedim.md" - "Two Dimensial CA" => "api/twodim.md" + "Two Dimensional CA" => "api/twodim.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..dbf6b6d 100644 --- a/docs/src/api/general.md +++ b/docs/src/api/general.md @@ -1,4 +1,25 @@ # General APIs + ```@docs CellularAutomaton + next_state + rollout + cellular_automaton_rule + evolution_history + generation_count + neighborhood_radius + rule_lookup_table + cell_state_count + Periodic + Reflecting + ConstantBoundary + AbstractCellularAutomaton + AbstractCellularAutomatonRule + AbstractBoundaryCondition + AbstractDiscreteCellularAutomatonRule + AbstractContinuousCellularAutomatonRule + AbstractTotalisticCellularAutomatonRule + AbstractLifeLikeCellularAutomatonRule + spatial_dimensions + lempel_ziv ``` 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 de85914..83164ac 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 @@ -19,15 +19,15 @@ 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, ticks=false) ``` -[Rule 30](http://atlas.wolfram.com/01/01/30/) +[Rule 30](https://atlas.wolfram.com/01/01/30/) ```@example eca states = 2 @@ -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, @@ -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 @@ -174,18 +174,18 @@ 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, ticks=false) ``` -[Rule 107398](http://atlas.wolfram.com/01/03/107398/) +[Rule 107398](https://atlas.wolfram.com/01/03/107398/) ```@example tca states = 4 @@ -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, @@ -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 @@ -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 b20c7f7..8b65f0a 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: @@ -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 1254edc..314bd92 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") @@ -8,7 +10,16 @@ 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 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 4e3f426..4cdb32e 100644 --- a/src/cellular_automaton.jl +++ b/src/cellular_automaton.jl @@ -1,96 +1,199 @@ -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()`. -```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) -``` +# Examples -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], -] -generations = 50 # Number of generations to simulate -automaton_td = CellularAutomaton(rule, initial_conditions, generations) +```jldoctest +julia> using CellularAutomata + +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() + ) + __validate_state(rule, 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) -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. +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. -You can access the evolution by calling the `evolution` field of `CellularAutomaton` +# Arguments + + - `rule`: Cellular-automaton transition rule. + - `initial_state`: State from which to begin the rollout. + - `steps`: Number of transitions to apply. + +# Keyword arguments + + - `boundary`: Boundary condition used by each transition. Defaults to `Periodic()`. + - `save`: Retain the initial state and every subsequent state. Defaults to `false`. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> history = rollout(DCA(30), [0, 0, 1, 0, 0], 2; save=true); -```julia -automaton_td.evolution +julia> size(history) +(5, 3) + +julia> history[:, end] +5-element Vector{Int64}: + 1 + 1 + 0 + 0 + 1 ``` +""" +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 = __Transition(rule, 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) -# Notes +Construct a cellular automaton and retain its complete evolution history. For vector +states, `evolution_history(automaton)` stores time on the first axis. For +higher-dimensional states, time is stored on the last axis. - - The `rule` parameter determines the dimensionality of the cellular automaton. - Ensure that your `initial_conditions` and `rule` are compatible in terms of dimensions. +# Arguments + + - `rule`: Cellular-automaton rule defining one transition. + - `initial_conditions`: Initial state array. + - `generations`: Number of retained generations, including the initial state. + +# Examples + +```jldoctest +julia> using CellularAutomata + +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> evolution_history(automaton) +3×3 Matrix{Int64}: + 0 1 0 + 1 1 1 + 0 0 0 +``` """ -struct CellularAutomaton{F,E} <: AbstractCA +@concrete struct CellularAutomaton <: AbstractCellularAutomaton generations::Int - generation_fun::F - evolution::E + rule + evolution end -function CellularAutomaton(rule::AbstractODRule, initial_conditions, generations) - evolution = zeros( - typeof(initial_conditions[2]), generations, length(initial_conditions) +function CellularAutomaton( + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractVector, + generations::Integer ) - 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, generations) - evolution = zeros( - typeof(initial_conditions[2]), - size(initial_conditions, 1), - size(initial_conditions, 2), - generations, +function CellularAutomaton( + rule::AbstractCellularAutomatonRule, + initial_conditions::AbstractArray, + generations::Integer ) - evolution[:, :, 1] = initial_conditions + 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 - for i in 2:generations - evolution[:, :, i] = rule(evolution[:, :, i - 1]) - end +""" + cellular_automaton_rule(automaton::AbstractCellularAutomaton) - return CellularAutomaton(generations, rule, evolution) -end \ No newline at end of file +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=", + 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 3c544f8..872c763 100644 --- a/src/generics.jl +++ b/src/generics.jl @@ -1,3 +1,164 @@ -abstract type AbstractRule end -abstract type AbstractODRule <: AbstractRule end -abstract type AbstractTDRule <: AbstractRule end \ No newline at end of file +""" + 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. + +# 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 + +""" + 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 + +""" + 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 +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 + 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 + +__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) + +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 e551f78..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) @@ -21,16 +21,30 @@ 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. + +# Examples + +```jldoctest +julia> using CellularAutomata + +julia> automaton = CellularAutomaton(DCA(30), [0, 1, 0], 3); + +julia> lempel_ziv(automaton) +1.3333333333333333 +``` """ -function lempel_ziv(ca::AbstractCA) - ca_size = size(ca.evolution, 1) +function lempel_ziv(ca::AbstractCellularAutomaton) + history = evolution_history(ca) + history isa AbstractMatrix || + throw(ArgumentError("lempel_ziv only supports one-dimensional automata")) + 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 61332c4..50b5c44 100644 --- a/src/rules/cca.jl +++ b/src/rules/cca.jl @@ -1,82 +1,88 @@ -abstract type AbstractCCARule <: AbstractODRule end +""" + AbstractContinuousCellularAutomatonRule + +Supertype for cellular-automaton rules with continuous cell states. +""" +abstract type AbstractContinuousCellularAutomatonRule <: AbstractCellularAutomatonRule end -struct CCA{T<:Real} <: AbstractCCARule - rule::T - radius::Int +@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) -``` +```jldoctest +julia> using CellularAutomata -Once created, the `CCA` object can be used to evolve a given starting array of cell states: +julia> cca = CCA(1 // 10); -```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 +julia> next_state(cca, [0 // 1, 0 // 1, 3 // 10]) +3-element Vector{Rational{Int64}}: + 1//5 + 1//5 + 1//5 ``` - -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) + __validate_radius(radius) return CCA(rule, radius) end function (cca::CCA)(starting_array::AbstractArray) - return nextgen = evolution(starting_array, cca.rule, cca.radius) + return next_state(cca, starting_array) end -function c_state_reader(neighborhood::AbstractArray, radius) - return sum(neighborhood) / length(neighborhood) +function __step(cca::CCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __cca_evolution(cell, cca.rule, cca.radius, boundary) 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)] - ) +__fractional_part(value) = value - floor(value) - 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 +@concrete struct __CCAUpdate + cell + rule + boundary + left + right +end - return output +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 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)] +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 - 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 +""" + neighborhood_radius(rule::AbstractCellularAutomatonRule) + +Return the spatial neighborhood radius used by `rule`. +""" +neighborhood_radius(cca::CCA) = cca.radius - return output +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 a3ad71a..bdb3e82 100644 --- a/src/rules/dca.jl +++ b/src/rules/dca.jl @@ -1,91 +1,148 @@ -abstract type AbstractDCARule <: AbstractODRule end +""" + AbstractDiscreteCellularAutomatonRule + +Supertype for cellular-automaton rules based on discrete neighborhood lookup tables. +""" +abstract type AbstractDiscreteCellularAutomatonRule <: AbstractCellularAutomatonRule end -struct DCA{T<:Integer,R,P} <: AbstractDCARule - rule::T - ruleset::R +@concrete struct DCA <: AbstractDiscreteCellularAutomatonRule + rule + ruleset states::Int - radius::P + 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. + +# Throws + + - `ArgumentError`: If the rule configuration or a transitioned state is outside its + declared discrete domain. -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 +```jldoctest +julia> using CellularAutomata + +julia> dca = DCA(30); + +julia> rule_lookup_table(dca) +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 ``` """ -function DCA(rule::T; states::Int=2, radius=1) where {T<:Integer} - ruleset = conversion(rule, states, radius) +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::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) -end +__validate_state(dca::DCA, state) = __validate_discrete_state(state, dca.states) -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 __step(dca::DCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __dca_evolution(cell, dca.ruleset, dca.states, dca.radius, boundary) end -#still ugly -function state_reader(neighborhood::AbstractArray, states::Int) - joined = join(convert(Array{Int}, neighborhood)) - return parse(Int, String(joined); base=states) + 1 +function __conversion(rule::Integer, states::Int, radius) + left, right = __radius_extent(radius) + return __digits_ruleset(rule, states, states^(left + right + 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)] - ) +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 - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = ruleset[state_reader(cell[i:(i + neighborhood_size - 1)], states)] +function __state_reader(neighborhood, states::Int) + index = 0 + for cell in neighborhood + index = index * states + Int(cell) end + return index + 1 +end - return output +@concrete struct __DCAUpdate + cell + ruleset + states + boundary + left + right 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]]) +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 - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = ruleset[state_reader(cell[i:(i + neighborhood_size - 1)], states)] - end +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)) +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 output +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, ")" + ) end diff --git a/src/rules/life.jl b/src/rules/life.jl index b4a681c..540cc81 100644 --- a/src/rules/life.jl +++ b/src/rules/life.jl @@ -1,105 +1,105 @@ +""" + AbstractLifeLikeCellularAutomatonRule -abstract type AbstractLifeRule <: AbstractTDRule end +Supertype for Life-like cellular-automaton rules. +""" +abstract type AbstractLifeLikeCellularAutomatonRule <: AbstractCellularAutomatonRule end -struct Life{T,A} <: AbstractLifeRule - born::T - survive::A +@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: +```jldoctest +julia> using CellularAutomata -```julia -# Initialize Life with custom rules: birth if 3 neighbors, survive if 2 or 3 neighbors -life = Life(((3,), (2, 3)); radius=1) +julia> life = Life(((3,), (2, 3)); radius=1); -# 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 +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]; -# 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=1) - born, survive = life_description[1], life_description[2] +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) + return next_state(life, starting_array) 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, :]) +function __step(life::Life, state::AbstractMatrix, boundary::AbstractBoundaryCondition) + return __life_evolution(state, life.born, life.survive, life.radius, boundary) +end - return hcat(left, middle, right) +@concrete struct __LifeUpdate + state + born + survive + radius + boundary 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 - - if past_value == 1 && alive in survive - return 1 - elseif past_value == 0 && alive in born - return 1 - else - return 0 +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, + survive, + radius::Int, + boundary::AbstractBoundaryCondition = Periodic() + ) + update = __LifeUpdate(starting_array, born, survive, radius, boundary) + return map(update, CartesianIndices(starting_array)) end -function life_evolution(starting_array::AbstractMatrix, born, survive, radius) - height, width = size(starting_array) - output = zeros(typeof(starting_array[2]), height, width) - virtual_output = virtual_expansion(starting_array, radius) +neighborhood_radius(life::Life) = life.radius - for i in 1:(height - radius + 1), j in 1:(width - radius + 1) - output[i, j] = life_application( - virtual_output[i:(i + radius + 1), j:(j + radius + 1)], born, survive - ) - end - return output +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 71c21fb..2d78380 100644 --- a/src/rules/tca.jl +++ b/src/rules/tca.jl @@ -1,99 +1,114 @@ -abstract type AbstractTCARule <: AbstractDCARule end +""" + AbstractTotalisticCellularAutomatonRule + +Supertype for rules whose transitions depend on the total neighborhood state. +""" +abstract type AbstractTotalisticCellularAutomatonRule <: +AbstractDiscreteCellularAutomatonRule end -struct TCA{B,R,T} <: AbstractTCARule - code::B - codeset::R +@concrete struct TCA <: AbstractTotalisticCellularAutomatonRule + code + codeset states::Int - radius::T + 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 or string 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. + +# Throws + + - `ArgumentError`: If the rule configuration or a transitioned state is outside its + declared discrete domain. -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) +```jldoctest +julia> using CellularAutomata -# Example starting state: a 1D array of cells -starting_array = [0, 2, 1, 0, 1, 2] +julia> tca = TCA(3); -# Compute the next generation -next_generation = tca(starting_array) +julia> rule_lookup_table(tca) +4-element Vector{Int64}: + 1 + 1 + 0 + 0 + +julia> next_state(tca, [0, 0, 1, 0, 0]) +5-element Vector{Int64}: + 1 + 1 + 1 + 1 + 1 ``` """ -function TCA(code; states=2, radius=1) - codeset = tca_conversion(code, states, radius) +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 nextgen = tca_evolution(starting_array, tca.codeset, tca.states, tca.radius) + return next_state(tca, starting_array) 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) -end +__validate_state(tca::TCA, state) = __validate_discrete_state(state, tca.states) -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 __step(tca::TCA, cell::AbstractVector, boundary::AbstractBoundaryCondition) + return __tca_evolution(cell, tca.codeset, tca.radius, boundary) end -function tca_state_reader(neighborhood::AbstractArray, codeset_len) - return mod1(sum(neighborhood) + 1, codeset_len) +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 -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)] - ) +__tca_state_reader(neighborhood) = Int(sum(neighborhood)) + 1 - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = codeset[tca_state_reader( - cell[i:(i + neighborhood_size - 1)], length(codeset) - )] - end +@concrete struct __TCAUpdate + cell + codeset + boundary + left + right +end - return output +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::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]]) +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 - for i in 1:(length(cell) - neighborhood_size + 1) - output[i] = codeset[tca_state_reader( - cell[i:(i + neighborhood_size - 1)], length(codeset) - )] - end +rule_lookup_table(tca::TCA) = tca.codeset +cell_state_count(tca::TCA) = tca.states +neighborhood_radius(tca::TCA) = tca.radius - return output +function Base.show(io::IO, tca::TCA) + return print( + io, "TCA(", tca.code, "; states=", tca.states, ", radius=", tca.radius, ")" + ) end diff --git a/test/ad_test.jl b/test/ad_test.jl new file mode 100644 index 0000000..f00ac4f --- /dev/null +++ b/test/ad_test.jl @@ -0,0 +1,46 @@ +using CellularAutomata +using ForwardDiff +using Test + +@testset "next_state and rollout" begin + initial = [0.1, 0.2, 0.3] + 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 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 + +@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] + + 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/blinker_test.jl b/test/blinker_test.jl index a7caeed..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 030f794..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 d113e61..7741471 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) +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. +@static if VERSION >= v"1.12" + using JET + JET.test_package(CellularAutomata) +end diff --git a/test/regression_test.jl b/test/regression_test.jl new file mode 100644 index 0000000..d02db6e --- /dev/null +++ b/test/regression_test.jl @@ -0,0 +1,85 @@ +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_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 + 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 "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) + 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 0861cdf..2995bed 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,24 +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 "TCA" begin + @safetestset "Size tests" include("tca_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)