DynamicGrids.DynamicGrids
— ModuleDynamicGrids is a generalised framework for building high-performance grid-based spatial simulations, including cellular automata, but also allowing a wider range of behaviours like random jumps and interactions between multiple grids. It is extended by Dispersal.jl for modelling organism dispersal processes.
DynamicGrids can run rules on single CPUs, threaded CPUs, and on CUDA GPUs. Simulation run-time is usually measured in fractions of a second.
A dispersal simulation with quarantine interactions, using Dispersal.jl, custom rules and the GtkOuput from DynamicGridsGtk. Note that this is indicative of the real-time frame-rate on a laptop.
A DynamicGrids.jl simulation is run with a script like this one running the included game of life model Life()
:
using DynamicGrids, Crayons
init = rand(Bool, 150, 200)
output = REPLOutput(init; tspan=1:200, fps=30, color=Crayon(foreground=:red, background=:black, bold=true))
sim!(output, Life())
# Or define it from scratch (yes this is actually the whole implementation!)
const sum_states = (false, false, true, false, false, false, false, false, false),
(false, false, true, true, false, false, false, false, false)
life = Neighbors(Moore(1)) do hood, state
sum_states[state + 1][sum(hood) + 1]
end
sim!(output, life)
A game of life simulation being displayed directly in a terminal.
Concepts
The framework is highly customisable, but there are some central ideas that define how a simulation works: grids, rules, and outputs.
Grids
Simulation grids may be any single AbstractArray
or a NamedTuple
of multiple AbstractArray
. Usually grids contain values of Number
, but other types are possible. Grids are updated by Rule
s that are run for every cell, at every timestep.
The init
grid/s contain whatever initialisation data is required to start a simulation: the array type, size and element type, as well as providing the initial conditions:
init = rand(Float32, 100, 100)
An init
grid can be attached to an Output
:
output = ArrayOutput(init; tspan=1:100)
or passed in to sim!
, where it will take preference over the init
attached to the Output
, but must be the same type and size:
sim!(output, ruleset; init=init)
For multiple grids, init
is a NamedTuple
of equal-sized arrays matching the names given to each Ruleset
:
init = (predator=rand(100, 100), prey=(rand(100, 100))
Handling and passing of the correct grids to a Rule
is automated by DynamicGrids.jl. Rule
s specify which grids they require in what order using the first two (R
and W
) type parameters.
Dimensional or spatial init
grids from DimensionalData.jl or GeoData.jl will propagate through the model to return output with explicit dimensions. This will plot correctly as a map using Plots.jl, to which shape files and observation points can be easily added.
Non-Number Grids
Grids containing custom and non-Number
types are possible, with some caveats. They must define Base.zero
for their element type, and should be a bitstype for performance. Tuple does not define zero
. Array
is not a bitstype, and does not define zero
. SArray
from StaticArrays.jl is both, and can be used as the contents of a grid. Custom structs that defne zero
should also work.
However, for any multi-values grid element type, you will need to define a method of DynamicGrids.to_rgb
that returns an ARGB32
for them to work in ImageOutput
s, and isless
for the REPLoutput
to work. A definition for multiplication by a scalar Real
and addition are required to use Convolution
kernels.
Rules
Rules hold the parameters for running a simulation, and are applied in applyrule
method that is called for each of the active cells in the grid. Rules come in a number of flavours (outlined in the docs), which allow assumptions to be made about running them that can greatly improve performance. Rules can be collected in a Ruleset
, with some additional arguments to control the simulation:
ruleset = Ruleset(Life(2, 3); opt=SparseOpt(), proc=CuGPU())
Multiple rules can be combined in a Ruleset
or simply passed to sim!
. Each rule will be run for the whole grid, in sequence, using appropriate optimisations depending on the parent types of each rule:
ruleset = Ruleset(rule1, rule2; timestep=Day(1), opt=SparseOpt(), proc=ThreadedCPU())
Output
Outputs are ways of storing or viewing a simulation. They can be used interchangeably depending on your needs: ArrayOutput
is a simple storage structure for high performance-simulations. As with most outputs, it is initialised with the init
array, but in this case it also requires the number of simulation frames to preallocate before the simulation runs.
output = ArrayOutput(init; tspan=1:10)
The REPLOutput
shown above is a GraphicOutput
that can be useful for checking a simulation when working in a terminal or over ssh:
output = REPLOutput(init; tspan=1:100)
ImageOutput
is the most complex class of outputs, allowing full color visual simulations using ColorSchemes.jl. It can also display multiple grids using color composites or layouts, as shown above in the quarantine simulation.
DynamicGridsInteract.jl provides simulation interfaces for use in Juno, Jupyter, web pages or electron apps, with live interactive control over parameters, using ModelParameters.jl. DynamicGridsGtk.jl is a simple graphical output for Gtk. These packages are kept separate to avoid dependencies when being used in non-graphical simulations.
Outputs are also easy to write, and high performance applications may benefit from writing a custom output to reduce memory use, or using TransformedOuput
. Performance of DynamicGrids.jl is dominated by cache interactions, so reducing memory use has positive effects.
Example
This example implements a very simple forest fire model:
using DynamicGrids, DynamicGridsGtk, ColorSchemes, Colors
const DEAD, ALIVE, BURNING = 1, 2, 3
rule = let prob_combustion=0.0001, prob_regrowth=0.01
Neighbors(Moore(1)) do neighborhood, cell
if cell == ALIVE
if BURNING in neighborhood
BURNING
else
rand() <= prob_combustion ? BURNING : ALIVE
end
elseif cell == BURNING
DEAD
else
rand() <= prob_regrowth ? ALIVE : DEAD
end
end
end
# Set up the init array and output (using a Gtk window)
init = fill(ALIVE, 400, 400)
processor = ColorProcessor(scheme=ColorSchemes.rainbow, zerocolor=RGB24(0.0))
output = GtkOutput(init; tspan=1:200, fps=25, minval=DEAD, maxval=BURNING, processor=processor)
# Run the simulation
sim!(output, rule)
# Save the output as a gif
savegif("forestfire.gif", output)
Timing the simulation for 200 steps, the performance is quite good:
output = ArrayOutput(init; tspan=1:200)
@time sim!(output, ruleset)
1.384755 seconds (640 allocations: 2.569 MiB)
Alternatives
Agents.jl can also do cellular-automata style simulations. The design of Agents.jl is to iterate over a list of agents, instead of broadcasting over an array of cells. This approach is well suited to when you need to track the movement and details about individual agents throughout the simulation.
However, for simple grid models where you don't need to track individuals, DynamicGrids.jl is orders of magnitude faster than Agents.jl, and usually requires much less code to define a model. For low density simulations like the forest fire model above (especially with some optimisations and threading turned on), it can be an order of magnitude faster, while for higher activity rules like the game of life on a randomised grid, it is two to three, even four order of magnitude faster, increasing with grid size. If you are doing grid-based simulation and you don't need to track individual agents, DynamicGrids.jl is probably the best tool. For other use cases where you need to track individuals, try Agents.jl.
DynamicGrids.AbstractExtent
— TypeAbstractExtent
Abstract supertype for Extent
objects, that hold all variables related to space and time in a simulation. Usually the field of an output.
DynamicGrids.AbstractKernelNeighborhood
— TypeAbstractKernelNeighborhood <: Neighborhood
Abstract supertype for kernel neighborhoods.
These can wrap any other neighborhood object, and include a kernel of the same length and positions as the neighborhood.
DynamicGrids.AbstractPositionalNeighborhood
— TypeAbstractPositionalNeighborhood <: Neighborhood
Neighborhoods are tuples or vectors of custom coordinates tuples that are specified in relation to the central point of the current cell. They can be any arbitrary shape or size, but should be listed in column-major order for performance.
DynamicGrids.AbstractRuleset
— TypeAbstractRuleset <: ModelParameters.AbstractModel
Abstract supertype for Ruleset
objects and variants.
DynamicGrids.ArrayOutput
— TypeArrayOutput <: Output
ArrayOutput(init; tspan::AbstractRange, [aux, mask, padval])
A simple output that stores each step of the simulation in a vector of arrays.
Arguments
init
: initialisationArray
orNamedTuple
ofArray
Keywords
tspan
:AbstractRange
timespan for the simulationaux
: NamedTuple of arbitrary input data. Useget(data, Aux(:key), I...)
to access from aRule
in a type-stable way.mask
:BitArray
for defining cells that will/will not be run.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.
DynamicGrids.Aux
— TypeAux <: ParameterSource
Aux{K}()
Aux(K::Symbol)
Use auxilary array with key K
as a parameter source.
Implemented in rules with:
get(data, rule.myparam, index...)
When an Aux
param is specified at rule construction with:
rule = SomeRule(; myparam=Aux{:myaux})
output = ArrayOutput(init; aux=(myaux=myauxarray,))
If the array is a DimensionalData.jl DimArray
with a Ti
(time) dimension, the correct interval will be selected automatically, precalculated for each timestep so it has no significant overhead.
DynamicGrids.BoundaryCondition
— TypeBoundaryCondition
Abstract supertype for flags that specify the boundary conditions used in the simulation, used in inbounds
and to update NeighborhoodRule
grid padding. These determine what happens when a neighborhood or jump extends outside of the grid.
DynamicGrids.CPU
— TypeCPU <: Processor
Abstract supertype for CPU processors.
DynamicGrids.Cell
— TypeCall <: CellRule
Cell(f)
Cell{R,W}(f)
A CellRule
that applies a function f
to the read
grid cells and returns the write
cells.
Especially convenient with do
notation.
Example
Set the cells of grid :c
to the sum of :a
and :b
:
simplerule = Cell() do a, b
a + b
end
If you need to use multiple grids (a and b), use the read
and write
arguments. If you want to use external variables, wrap the whole thing in a let
block, for performance.
rule = let y = y
rule = Cell{Tuple{:a,:b},:b}() do a, b
a + b * y
end
end
DynamicGrids.CellRule
— TypeCellrule <: Rule
A Rule
that only writes and uses a state from single cell of the read grids, and has its return value written back to the same cell(s).
This limitation can be useful for performance optimisation, such as wrapping rules in Chain
so that no writes occur between rules.
CellRule
is defined with :
struct YourCellRule{R,W} <: CellRule{R,W} end
And applied as:
function applyrule(data::SimData, rule::YourCellRule{R,W}, state, index) where {R,W}
state * 2
end
As the index
is provided in applyrule
, you can look up an aux
array using aux(data, Val{:auxname}())[index...]
to access cell-specific variables for your rule.
It's good to add a struct field to hold the Val{:auxname}()
object instead of using names directly, so that users can set the aux name themselves to suit the scripting context.
DynamicGrids.Chain
— TypeChain(rules...)
Chain(rules::Tuple)
Chain
s allow chaining rules together to be completed in a single processing step, without intermediate reads or writes from grids.
They are potentially compiled together into a single function call, especially if you use @inline
on all applyrule
methods. Chain
can hold either all CellRule
or NeighborhoodRule
followed by CellRule
.
SetRule
can't be used in Chain
, as it doesn't have a return value.
DynamicGrids.Convolution
— TypeConvolution <: NeighborhoodRule
Convolution(f, neighborhood=Moore(1))
Convolution{R,W}(f, neighborhood=Moore(1))
A NeighborhoodRule
that runs a basic convolution kernel over the grid.
Performance
Always use StaticArrays.jl to define the kernel matrix.
Small radius convolutions in DynamicGrids.jl will be comparable or even faster than using DSP.jl or ImageConvolutions.jl. As the radius increases these packages will be a lot faster.
But Convolution
is convenient to chain into a simulation, and combined with some other rules. It should perform reasonably well with all but very large kernels.
Example
DynamicGrids.CopyTo
— TypeCopyTo <: CellRule
CopyTo{W}(from)
CopyTo{W}(; from)
A simple rule that copies aux array slices to a grid over time. This can be used for comparing simulation dynamics to aux data dynamics.
DynamicGrids.Extent
— TypeExtent <: AbstractExtent
Extent(init, mask, aux, padval, tspan)
Extent(; init, tspan, mask=nothing, aux=nothing, padval=zero(eltype(init)), kw...)
Container for extensive variables: spatial and timeseries data. These are kept separate from rules to allow application of rules to alternate spatial and temporal contexts.
Extent is not usually constructed directly by users, but it can be passed to Output
constructors instead of init
, mask
, aux
and tspan
.
Arguments/Keywords
init
: initialisationArray
/NamedTuple
for grid/s.mask
:BitArray
for defining cells that will/will not be run.aux
: NamedTuple of arbitrary input data. Useaux(data, Aux(:key))
to access from aRule
in a type-stable way.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.tspan
: Time span range. Never type-stable, only access this inmodifyrule
methods
DynamicGrids.GifOutput
— TypeGifOutput <: ImageOutput
GifOutput(init; filename, tspan, kw...)
Output that stores the simulation as images and saves a Gif file on completion.
Arguments:
init
: initialisationArray
orNamedTuple
ofArray
Keywords
filename
: File path to save the gif file to.tspan
:AbstractRange
timespan for the simulationaux
: NamedTuple of arbitrary input data. Useget(data, Aux(:key), I...)
to access from aRule
in a type-stable way.mask
:BitArray
for defining cells that will/will not be run.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.font
:String
font name, used in defaultTextConfig
. A default will be guessed.text
:TextConfig
object ornothing
for no text.scheme
: ColorSchemes.jl scheme, orGreyscale()
imagegen
:ImageGenerator
minval
: minimum value(s) to set colour maximummaxval
: maximum values(s) to set colour minimum
DynamicGrids.GraphicConfig
— TypeGraphicConfig
GraphicConfig(; fps=25.0, store=false)
Config and variables for graphic outputs.
DynamicGrids.GraphicOutput
— TypeGraphicOutput <: Output
Abstract supertype for Output
s that display the simulation frames.
All GraphicOutputs
must have a GraphicConfig
object and define a showframe
method.
See REPLOutput
for an example.
Keywords:
The default constructor will generate these objects from other keyword arguments and pass them to the object constructor, which must accept the following:
frames
: aVector
of simulation frames (NamedTuple
orArray
).running
: ABool
.extent
anExtent
object.graphicconfig
aGraphicConfig
object.
DynamicGrids.Greyscale
— TypeGreyscale
Greyscale(min=nothing, max=nothing)
A greeyscale scheme ith better performance than using a Colorschemes.jl scheme as there is not array access or interpolation.
min
and max
are values between 0.0
and 1.0
that define the range of greys used.
DynamicGrids.Grid
— TypeGrid <: ParameterSource
Grid{K}()
Grid(K::Symbol)
Use grid with key K
as a parameter source.
Implemented in rules with:
get(data, rule.myparam, index...)
And specified at rule construction with:
SomeRule(; myparam=Grid{:somegrid})
DynamicGrids.GridData
— TypeGridData <: AbstractArray
Simulation data specific to a single grid.
DynamicGrids.Image
— TypeImage <: SingleGridImageGenerator
Image(; scheme=ObjectScheme(), zerocolor=nothing, maskcolor=nothing)
Converts output grids to a colorsheme.
Keywords
scheme
: a ColorSchemes.jl colorscheme,ObjectScheme
or object that definesBase.get(obj, val)
and returns aColor
or a value that can be converted toColor
usingARGB32(val)
.zerocolor
: aCol
to use when values are zero, ornothing
to ignore.maskcolor
: aColor
to use when cells are masked, ornothing
to ignore.
DynamicGrids.ImageConfig
— TypeImageConfig
ImageConfig(init; kw...)
Common configuration component for all ImageOutput
.
Keywords
init
output init object, used to generate other arguments automatically.minval
: Minimum value in the grid(s) to normalise for conversion to an RGB pixel. Number orTuple
for multiple grids.maxval
: Maximum value in the grid(s) to normalise for conversion to an RGB pixel. Number orTuple
for multiple grids.font
:String
name of font to search for. A default will be guessed.text
:TextConfig()
ornothing
for no text. Default isTextConfig(; font=font)
.scheme
: ColorSchemes.jl scheme, orGreyscale()
. ObjectScheme() by default.imagegen
:ImageGenerator
likeImage
orLayout
Will be detected automatically
DynamicGrids.ImageGenerator
— TypeImageGenerator
Abstract supertype for objects that convert a frame of the simulation into an ARGB32
image for display. Frames may be a single grid or a NamedTuple
of multiple grids.
DynamicGrids.ImageOutput
— TypeImageOutput <: GraphicOutput
Abstract supertype for Graphic outputs that display the simulation frames as RGB images.
ImageOutput
s must have Extent
, GraphicConfig
and ImageConfig
components, and define a showimage
method.
See GifOutput
for an example.
Although the majority of the code is maintained here to enable sharing and reuse, most ImageOutput
s are not provided in DynamicGrids.jl to avoid heavy dependencies on graphics libraries. See DynamicGridsGtk.jl and DynamicGridsInteract.jl for implementations.
DynamicGrids.Kernel
— TypeKernel <: AbstractKernelNeighborhood
Kernel(neighborhood, kernel)
Wrap any other neighborhood object, and includes a kernel of the same length and positions as the neighborhood.
R = 1
gives 3x3 matrices.
DynamicGrids.LayeredPositional
— TypeLayeredPositional <: AbstractPositional
LayeredPositional(layers::Positional...)
Sets of Positional
neighborhoods that can have separate rules for each set.
neighbors
for LayeredPositional
returns a tuple of iterators for each neighborhood layer.
DynamicGrids.Layout
— TypeLayout <: MultiGridImageGenerator
Layout(layout::Array, imagegens::Matrix)
Layout allows displaying multiple grids in a block layout, by specifying a layout matrix and a list of Image
s to be run for each.
Arguments
layout
: A Vector or Matrix containing the keys or numbers of grids in the locations to display them.nothing
,missing
or0
values will be skipped.imagegens
: tuple ofImage
, one for each grid in the simulation. Can benothing
or any other value for grids not in layout.
DynamicGrids.Life
— TypeLife <: NeighborhoodRule
Life(neighborhood, born=3, survive=(2, 3))
Rule for game-of-life style cellular automata. This is a demonstration of Cellular Automata more than a seriously optimised game of life rule.
Cells becomes active if it is empty and the number of neightbors is a number in the b array, and remains active the cell is active and the number of neightbors is in the s array.
Examples (gleaned from CellularAutomata.jl)
using DynamicGrids, Distributions
# Use `Binomial` to tweak the density random true values
init = Bool.(rand(Binomial(1, 0.5), 70, 70))
output = REPLOutput(init; tspan=1:100, fps=25, color=:red)
# Morley
sim!(output, Ruleset(Life(born=[3, 6, 8], survive=[2, 4, 5])))
# 2x2
sim!(output, Ruleset(Life(born=[3, 6], survive=[1, 2, 5])))
# Dimoeba
init = rand(Bool, 400, 300)
init[:, 100:200] .= 0
output = REPLOutput(init; tspan=1:100, fps=25, color=:blue, style=Braile())
sim!(output, Life(born=(3, 5, 6, 7, 8), survive=(5, 6, 7, 8)))
## No death
sim!(output, Life(born=(3, ), survive=(0, 1, 2, 3, 4, 5, 6, 7, 8)))
## 34 life
sim!(output, Life(born=(3, 4), survive=(3, 4)))
# Replicator
init = fill(true, 300,300)
init[:, 100:200] .= false
init[10, :] .= 0
output = REPLOutput(init; tspan=1:100, fps=25, color=:yellow)
sim!(output, Life(born=(1, 3, 5, 7), survive=(1, 3, 5, 7)))
nothing
DynamicGrids.Moore
— TypeMoore <: RadialNeighborhood
Moore(radius::Int=1)
Moore neighborhoods define the neighborhood as all cells within a horizontal or vertical distance of the central cell. The central cell is omitted.
DynamicGrids.MultiGridImageGenerator
— TypeMultiGridImageGenerator <: ImageGenerator
Abstract type for ImageGenerator
s that convert a frame containing multiple grids into a single image.
DynamicGrids.Neighborhood
— TypeNeighborhood
Neighborhoods define the pattern of surrounding cells in the "neighborhood" of the current cell. The neighbors
function returns the surrounding cells as an iterable.
The main kinds of neighborhood are demonstrated below:
Moore{3}()
DynamicGrids.NeighborhoodRule
— TypeNeighborhoodRule <: Rule
A Rule that only accesses a neighborhood centered around the current cell. NeighborhoodRule
is applied with the method:
applyrule(data::SimData, rule::YourNeighborhoodRule, state, I)
NeighborhoodRule
must have a neighborhood
field, that holds a Neighborhood
object. neighbors(rule)
returns an iterator over the surrounding cell pattern defined by the Neighborhood
.
For each cell in the grids the neighborhood buffer will be updated for use in the applyrule
method, managed to minimise array reads.
This allows memory optimisations and the use of high perforance routines on the neighborhood buffer. It also means that and no bounds checking is required in neighborhood code.
For neighborhood rules with multiple read grids, the first is always the one used for the neighborhood, the others are passed in as additional state for the cell. Any grids can be written to, but only for the current cell.
DynamicGrids.Neighbors
— TypeNeighbors <: NeighborhoodRule
Neighbors(f, neighborhood=Moor(1))
Neighbors{R,W}(f, neighborhood=Moore())
A NeighborhoodRule
that receives a neighbors object for the first read
grid and the passed in neighborhood, followed by the cell values for the required grids, as with Cell
.
Returned value(s) are written to the write
/W
grid.
As with all NeighborhoodRule
, you do not have to check bounds at grid edges, that is handled for you internally.
Using SparseOpt
may improve neighborhood performance when zero values are common and can be safely ignored.
Example
rule = let x = 10
Neighbors{Tuple{:a,:b},:b}() do hood, a, b
data[:b][I...] = a + b^x
end
end
The let
block may improve performance.
DynamicGrids.NoOpt
— TypeNoOpt <: PerformanceOpt
NoOpt()
Flag to run a simulation without performance optimisations besides basic high performance programming. Still fast, but not intelligent about the work that it does: all cells are run for all rules.
NoOpt
is the default opt
method.
DynamicGrids.ObjectScheme
— TypeObjectScheme
ObjectScheme()
Default colorscheme. Similar to GreyScale
for Number
.
Other grid objects can define a custom method to return colors from composite objects:
DynamicGrids.to_rgb(::ObjectScheme, obj::MyObjectType) = ...
Which must return an ARGB32
value.
DynamicGrids.Output
— TypeOutput
Abstract supertype for simulation outputs.
Outputs are store or display simulation results, usually as a vector of grids, one for each timestep - but they may also sum, combine or otherwise manipulate the simulation grids to improve performance, reduce memory overheads or similar.
Simulation outputs are decoupled from simulation behaviour, and in many cases can be used interchangeably.
DynamicGrids.ParameterSource
— TypeParameterSource
Abstract supertypes for parameter source wrappers. These allow parameters to be retreived from auxilliary data or from other grids.
DynamicGrids.PerformanceOpt
— TypePerformanceOpt
Abstract supertype for performance optimisation flags.
DynamicGrids.Positional
— TypePositional <: AbstractPositionalNeighborhood
Positional(coord::Tuple{Vararg{Int}}...)
Positional(offsets::Tuple{Tuple{Vararg{Int}}})
Neighborhoods that can take arbitrary shapes by specifying each coordinate, as Tuple{Int,Int}
of the row/column distance (positive and negative) from the central point.
The neighborhood radius is calculated from the most distance coordinate. For simplicity the buffer read from the main grid is a square with sides 2r + 1
around the central point, and is not shrunk or offset to match the coordinates if they are not symmetrical.
DynamicGrids.Processor
— TypeProcessor
Abstract supertype for selecting a hardware processor, such as ia CPU or GPU.
DynamicGrids.REPLOutput
— TypeREPLOutput <: GraphicOutput
REPLOutput(init; tspan, kw...)
An output that is displayed directly in the REPL. It can either store or discard simulation frames.
Arguments:
init
: initialisationArray
orNamedTuple
ofArray
s.
Keywords
tspan
:AbstractRange
timespan for the simulationmask
:BitArray
for defining cells that will/will not be run.aux
:NamedTuple
of arbitrary input data. Useget(data, Aux(:key), I...)
to access from aRule
in a type-stable way.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.fps
:Real
frames per second to display the simulationstore
:Bool
whether ot store the simulation frames for later usecolor
: a color from Crayons.jlcutoff
:Real
cutoff point to display a full or empty cell. Default is0.5
style
:CharStyle
Block()
orBraile()
printing.Braile
uses 1/4 the screen space ofBlock
.
DynamicGrids.RadialNeighborhood
— TypeRadialNeighborhood <: Neighborhood
Square neighborhoods with radius R
, and side length 2R + 1
DynamicGrids.ReadableGridData
— TypeReadableGridData <: GridData
ReadableGridData(grid::GridData)
ReadableGridData{Y,X,R}(init::AbstractArray, mask, opt, boundary, padval)
Simulation data and storage passed to rules for each timestep.
Type parameters
Y
: number of rowsX
: number of columnsR
: grid padding radius
DynamicGrids.Remove
— TypeRemove <: BoundaryCondition
Remove()
BoundaryCondition
flag that specifies to assign padval
to cells that overflow grid boundaries. padval
defaults to zero(eltype(grid))
but can be assigned as a keyword argument to an Output
.
Specifiy with:
ruleset = Ruleset(rule; boundary=Remove())
# or
output = sim!(output, rule; boundary=Remove())
DynamicGrids.ResultOutput
— TypeResultOutput <: Output
ResultOutput(init; tspan::AbstractRange, kw...)
A simple output that only stores the final result, not intermediate frames.
Arguments
init
: initialisationArray
orNamedTuple
ofArray
Keywords
tspan
:AbstractRange
timespan for the simulationaux
: NamedTuple of arbitrary input data. Useget(data, Aux(:key), I...)
to access from aRule
in a type-stable way.mask
:BitArray
for defining cells that will/will not be run.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.
DynamicGrids.Rule
— TypeRule
A Rule
object contains the information required to apply an applyrule
method to every cell of every timestep of a simulation.
Rules are applied to the grid using the applyrule
method:
@inline applyrule(data::SimData, rule::YourRule, state, index) = ...
Where index
is a Tuple
of Int
, and state
is a single value, or a NamedTuple
if multiple grids are requested. the SimData
object can be used to access current timestep and other simulation data and metadata.
Rules can be updated from the original rule before each timestep, in modifyrule
:
modifyrule(rule::YourRule, data::SimData) = ...
Rules can also be run in sequence, often wrapped in a Tuple
or Ruleset
s.
DynamicGrids guarantees that:
modifyrule
is run once for every rule for every timestep. The result is passed toapplyrule
, but not retained after that.applyrule
is run once for every rule, for every cell, for every timestep, unless an optimisation likeSparseOpt
is enable to skips empty cells.- the output of running a rule for any cell does not affect the input of the same rule running anywhere else in the grid.
- rules later in the sequence are passed grid state updated by the earlier rules.
- masked areas and wrapped or removed boundary regions are updated between all rules and timesteps
Multiple grids
The NamedTuple
keys will match the keys in R
, which is a type like Tuple{:key1,:key1}
. Note the names are user-specified, and should never be fixed by a Rule
.
They can be retrieved from the type here as A
and B
:
applyrule(data::SimData, rule::YourCellRule{Tuple{R1,R2},Tuple{W1,W2}}, state, index) where {R1,R2,W1,W2}
By default the output is written to the current cell in the specified W
write grid/s. Rule
s writing to multiple grids, simply return a Tuple
in the order specified by the W
type params.
Rule Performance
Rules may run many millions of times during a simulation. They need to be fast. Some basic guidlines for writing rules are:
- Never allocate memory in a
Rule
if you can help it. - Type stability is essential.
isinferred
is useful to check if your rule is type-stable. - Using the
@inline
macro onapplyrule
can help force inlining your code into the simulation. - Reading and writing from multiple grids is expensive due to additional load on fast cahce memory. Try to limit the number of grids you use.
- Use a graphical profiler, like ProfileView.jl, to check your rules overall performance when run with
sim!
.
DynamicGrids.RuleWrapper
— TypeRuleWrapper <: Rule
A Rule
that wraps other rules, altering their behaviour or how they are run.
DynamicGrids.Ruleset
— TypeRulseset <: AbstractRuleset
Ruleset(rules...; kw...)
A container for holding a sequence of Rule
s and simulation details like boundary handing and optimisation. Rules will be run in the order they are passed, ie. Ruleset(rule1, rule2, rule3)
.
Keywords
proc
: aProcessor
to specificy the hardware to run simulations on, likeSingleCPU
,ThreadedCPU
orCuGPU
when KernelAbstractions.jl and a CUDA gpu is available.opt
: aPerformanceOpt
to specificy optimisations likeSparseOpt
. Defaults toNoOpt
.boundary
: what to do with boundary of grid edges. Options areRemove()
orWrap()
, defaulting toRemove
.cellsize
: size of cells.timestep
: fixed timestep where this is required for some rules. eg.Month(1)
or1u"s"
.
DynamicGrids.RunAt
— TypeRunAt(rules...)
RunAt(rules::Tuple)
RunAt
s allow running a Rule
or multiple Rule
s at a lower frequeny than the main simulation, using a range
matching the main tspan
but with a larger span, or specific events - by using a vector of arbitrary times in tspan
.
DynamicGrids.RunIf
— TypeRunIf(f, rule)
RunIf
s allows wrapping a rule in a condition, passed the SimData
object and the cell state and index.
`$julia RunIf(dispersal) do data, state, I state >= oneunit(state) end$ `
DynamicGrids.SetCell
— TypeSetCell <: SetCellRule
SetCell(f)
SetCell{R,W}(f)
A SetCellRule
to manually write to the array where you need to. f
is passed an indexable data
object, and the index of the current cell, followed by the required grid values for the index.
To update the grid, you can use: add!
, sub!
for Number
, and and!
, or!
for Bool
. These methods safely combined writes from all grid cells - directly using setindex!
would cause bugs.
Example
rule = let x = 10
Set{Tuple{:a,:b},:b}() do data, I, a, b
add!(data[:b], a^x, I...)
end
end
The let
block greatly improves performance.
DynamicGrids.SetCellRule
— TypeSetCellRule <: Rule
Abstract supertype for rules that can manually write to any cells of the grid that they need to.
SetCellRule
is applied with a method like:
function applyrule!(data::SimData, rule::YourSetCellRule, state, index)
inc = 1
add!(data, inc, index...)
return nothing
end
Note the !
bang - this method alters the state of data
.
To update the grid, you can use atomic operators add!
, sub!
, min!
, max!
, and and!
, or!
for Bool
. These methods safely combined writes from all grid cells - directly using setindex!
would cause bugs.
It there are multiple write grids, you will need to get the grid keys from type parameters, here W1
and W2
:
function applyrule(data, rule::YourSetCellRule{R,Tuple{W1,W2}}, state, index) where {R,W1,W2}
inc = 1
add!(data[W1], inc, index...)
add!(data[W2], 2inc, index...)
return nothing
end
DynamicGrids guarantees that:
- values written to anywhere on the grid do not affect other cells in the same rule at the same timestep.
- values written to anywhere on the grid are available to the next rule in the sequence, or the next timestep.
- if atomic operators are always used, race conditions will not occur on any hardware.
DynamicGrids.SetGrid
— TypeSetGrid{R,W}(f)
Apply a function f
to fill whole grid/s.
rule = SetGrid{:a,:b}() do a, b
b .= a
end
DynamicGrids.SetGridRule
— TypeSetGridRule <: Rule
A Rule
applies to whole grids. This is used for operations that don't benefit from having neighborhood buffering or looping over the grid handled for them, or any specific optimisations. Best suited to simple functions like rand
(write)` or using convolutions from other packages like DSP.jl. They may also be useful for doing other custom things that don't fit into the DynamicGrids.jl framework during the simulation.
Grid rules specify the grids they want and are sequenced just like any other grid.
struct YourSetGridRule{R,W} <: SetGridRule{R,W} end
And applied as:
function applyrule!(data::SimData, rule::YourSetGridRule{R,W}) where {R,W}
rand!(data[W])
end
DynamicGrids.SetNeighborhoodRule
— TypeSetNeighborhoodRule <: SetRule
A SetRule
that only writes to its neighborhood.
positions
and offsets
are useful iterators for modifying neighborhood values.
SetNeighborhoodRule
rules must return a Neighborhood
object from neighborhood(rule)
. By default this is rule.neighborhood
. If this property exists, no interface methods are required.
DynamicGrids.SetNeighbors
— TypeSetNeighbors <: SetNeighborhoodRule
SetNeighbors(f, neighborhood=Moor(1))
SetNeighbors{R,W}(f, neighborhood=Moor(1))
A SetCellRule
to manually write to the array with the specified neighborhood. Indexing outside the neighborhood is undefined behaviour.
Function f
is passed an SimData
object data
, the specified neighborhood object and the index of the current cell, followed by the required grid values for the index.
To update the grid, you can use: add!
, sub!
for Number
, and and!
, or!
for Bool
. These methods can be safely combined writes from all grid cells.
Directly using setindex!
is possible, but may cause bugs as multiple cells may write to the same location in an unpredicatble order. As a rule, directly setting a neighborhood index should only be done if it always sets the samevalue - then it can be guaranteed that any writes from othe grid cells reach the same result.
neighbors
, offsets
and positions
are useful methods for SetNeighbors
rules.
Example
SetNeighbors{Tuple{:a,:b},:b}() do data, hood, I, a, b
for pos in positions(hood)
add!(data[:b], a^2, pos...)
end
end
DynamicGrids.SetRule
— TypeSetRule <: Rule
Abstract supertype for rules that manually write to the grid in some way.
These must define methods of applyrule!
.
DynamicGrids.SimData
— TypeSimData <: AbstractSimData
SimData(extent::AbstractExtent, ruleset::AbstractRuleset)
Simulation dataset to hold all intermediate arrays, timesteps and frame numbers for the current frame of the simulation.
A simdata object is accessable in applyrule
as the first parameter.
Multiple grids can be indexed into using their key if you need to read from arbitrary locations:
funciton applyrule(data::SimData, rule::SomeRule{Tuple{A,B}},W}, (a, b), cellindex) where {A,B,W}
grid_a = data[A]
grid_b = data[B]
...
In single grid simulations SimData
can be indexed directly as if it is a Matrix
.
Methods
currentframe(data::SimData)
: get the current frame number, anInt
currenttime(data::SimData)
: the current frame time, whichisa eltype(tspan)
aux(d::SimData, args...)
: get theaux
dataNamedTuple
, orNothing
. adding aSymbol
orVal{:symbol}
argument will get a field of aux.tspan(d::SimData)
: get the simulation time span, anAbstractRange
.timestep(d::SimData)
: get the simulaiton time step.radius(data::SimData)
: returns theInt
radius used on the grid, which is also the amount of border padding.boundary(data::SimData)
: returns theBoundaryCondition
-Remove
orWrap
.padval(data::SimData)
: returns the value to use as grid border padding.
These are available, but you probably shouldn't use them and thier behaviour is not guaranteed in furture versions. They will mean rule is useful only in specific contexts.
extent(d::SimData)
: get the simulationAbstractExtent
object.init(data::SimData)
: get the simulation initAbstractArray
/NamedTuple
mask(data::SimData)
: get the simulation maskAbstractArray
ruleset(d::SimData)
: get the simulationAbstractRuleset
.source(data::SimData)
: get thesource
grid that is being read from.dest(data::SimData)
: get thedest
grid that is being written to.
DynamicGrids.SingleCPU
— TypeSingleCPU <: CPU
SingleCPU()
Processor
flag that specifies to use a single thread on a single CPU.
Specifiy with:
ruleset = Ruleset(rule; proc=SingleCPU())
# or
output = sim!(output, rule; proc=SingleCPU())
DynamicGrids.SingleGridImageGenerator
— TypeSingleGridImageGenerator <: ImageGenerator
Abstract supertype for ImageGenerator
s that convert a single grid into an image array.
The first grid will be displayed if a SingleGridImageGenerator
is used with a NamedTuple
of grids.
DynamicGrids.SparseOpt
— TypeSparseOpt <: PerformanceOpt
SparseOpt()
An optimisation flag that ignores all zero values in the grid.
For low-density simulations performance may improve by orders of magnitude, as only used cells are run.
This is complicated for optimising neighborhoods - they must run if they contain just one non-zero cell.
Specifiy with:
ruleset = Ruleset(rule; opt=SparseOpt())
# or
output = sim!(output, rule; opt=SparseOpt())
SparseOpt
is best demonstrated with this simulation, where the grey areas do not run except where the neighborhood partially hangs over an area that is not grey:
DynamicGrids.SparseOptInspector
— TypeSparseOptInspector()
A ImageGenerator
that checks SparseOpt
visually. Cells that do not run show in gray. Errors show in red, but if they do there's a bug.
DynamicGrids.TextConfig
— TypeTextConfig
TextConfig(; kw...)
TextConfig(face, namepixels, namepos, timepixels, timepos, fcolor, bcolor)
Text configuration for printing timestep and grid name on the image.
Arguments / Keywords
font
:String
font name.namepixels
andtimepixels
: the pixel size of the font.timepos
andnamepos
: tuples that set the label positions, inInt
pixels.fcolor
andbcolor
: the foreground and background colors, asARGB32
.
DynamicGrids.ThreadedCPU
— TypeThreadedCPU <: CPU
ThreadedCPU()
Processor
flag that specifies to use a Threads.nthreads()
CPUs.
Specifiy with:
ruleset = Ruleset(rule; proc=ThreadedCPU())
# or
output = sim!(output, rule; proc=ThreadedCPU())
DynamicGrids.TransformedOutput
— TypeTransformedOutput(f, init; tspan::AbstractRange, kw...)
An output that stores the result of some function f
of the grid/s
Arguments
f
: a function or functor that accepts anAbstractArray
orNamedTuple
ofAbstractArray
with names matchininit
. TheAbstractArray
will be a view into the grid the same size as the init grids, removing any padding that has been added.init
: initialisationArray
orNamedTuple
ofArray
Keywords
tspan
:AbstractRange
timespan for the simulationaux
: NamedTuple of arbitrary input data. Useget(data, Aux(:key), I...)
to access from aRule
in a type-stable way.mask
:BitArray
for defining cells that will/will not be run.padval
: padding value for grids with neighborhood rules. The default iszero(eltype(init))
.
DynamicGrids.Window
— TypeWindow <: RadialNeighborhood
Window{R}()
A neighboorhood of radius R that includes the central cell. R = 1
gives a 3x3 matrix.
DynamicGrids.Wrap
— TypeWrap <: BoundaryCondition
Wrap()
BoundaryCondition
flag to wrap cordinates that boundary boundaries back to the opposite side of the grid.
Specifiy with:
ruleset = Ruleset(rule; boundary=Wrap())
# or
output = sim!(output, rule; boundary=Wrap())
DynamicGrids.WritableGridData
— TypeWritableGridData <: GridData
WritableGridData(grid::GridData)
Passed to rules as write grids, and can be written to directly as an array, or preferably using add!
etc. All writes handle updates to SparseOpt() and writing to the correct source/dest array.
Reads are always from the source array, as rules must not be sequential between cells. This means using e.g. +=
is not supported, instead use add!
.
Base.get
— MethodBase.get(data::SimData, key::Union{Symbol,Aux,Grid}, I...)
Allows parameters to be taken from a single value, another grid or an aux array.
If aux arrays are a DimArray
time sequence (with a Ti
dim) the currect date will be calculated automatically.
Currently this is cycled by default, but will use Cyclic mode in DiensionalData.jl in future.
DynamicGrids.VonNeumann
— FunctionVonNeumann(radius=1) -> Positional
A convenience wrapper to build Von-Neumann neighborhoods as a Positional
neighborhood.
DynamicGrids.add!
— Functionadd!(data::WritableGridData, x, I...)
Add the value x
to a grid cell.
Example useage
function applyrule!(data::SimData, rule::My{A,B}, state, cellindex) where {A,B}
dest, is_inbounds = inbounds(data, (jump .+ cellindex)...)
# Update spotted cell if it's on the grid
is_inbounds && add!(data[W], state, dest...)
end
DynamicGrids.and!
— Functionand!(data::WritableGridData, x, I...)
and!(A::AbstractArray, x, I...)
Set the grid cell c
to c & x
. See add!
for example usage.
DynamicGrids.applyrule
— Functionapplyrule(data::SimData, rule::Rule{R,W}, state, index::Tuple{Int,Int}) -> cell value(s)
Apply a rule to the cell state and return values to write to the grid(s).
This is called in maprule!
methods during the simulation, not by the user. Custom Rule
implementations must define this method.
Arguments:
data
:SimData
rule
:Rule
state
: the value(s) of the current cellindex
: a (row, column) tuple of Int for the current cell coordinates
Returns the value(s) to be written to the current cell(s) of the grids specified by the W
type parameter.
DynamicGrids.applyrule!
— Functionapplyrule!(data::SimData, rule::{R,W}, state, index::Tuple{Int,Int}) -> Nothing
Apply a rule to the cell state and manually write to the grid data array. Used in all rules inheriting from SetCellRule
.
This is called in internal maprule!
methods during the simulation, not by the user. Custom SetCellRule
implementations must define this method.
Only grids specified with the W
type parameter will be writable from data
.
Arguments:
DynamicGrids.aux
— FunctionDynamicGrids.currentframe
— Functioncurrentframe(simdata::SimData) -> Int
Retrieve the current simulation frame a SimData
object.
DynamicGrids.currenttime
— Functioncurrenttime(simdata::SimData)
Retrieve the current simulation time from a SimData
object.
This will be in whatever type/units you specify in tspan
.
DynamicGrids.currenttimestep
— Functioncurrenttimestep(simdata::SimData)
Retrieve the current timestep from a SimData
object.
This may be different from the timestep
. If the timestep is Month
, currenttimestep
will return Seconds
for the length of the specific month.
DynamicGrids.delay
— Functiondelay(o::Output, f::Int) => nothing
GraphicOutput
interface method.
Delay the simulations to match some fps
rate. The default for outputs not <: GraphicOutput
is to do nothing and continue.
DynamicGrids.extent
— FunctionDynamicGrids.finalise!
— Functionfinalise!(o::Output, data::AbstractSimData)
Output
interface method.
Finalise the output at the end of the simulation.
DynamicGrids.finalisegraphics
— Functionfinalisegraphics(o::Output, data::AbstractSimData)
GraphicOutput
interface method.
Finalise the output graphics at the end of the simulation, if it has graphics.
DynamicGrids.fps
— Functionfps(o::Output) => Real
GraphicOutput
interface method.
Get the frames per second the output will run at. The default is nothing
- the simulation runs at full speed.
DynamicGrids.frameindex
— Functionframeindex(o::Output, data::AbstractSimData)
Output
interface method.
Get the index of the current frame in the output. Every frame has an index of 1 if the simulation isn't stored.
DynamicGrids.graphicconfig
— Functiongraphicconfig(output::GraphicOutput) => GraphicConfig
GraphicOutput
interface method. Return an GraphicConfig
object.
DynamicGrids.grid_to_image!
— Functiongrid_to_image!(o::ImageOutput, data::SimData)
grid_to_image!(imbuf, imgen::ImageGenerator, o::ImageOutput, data::SimData, grids)
Convert a grid or NamedRuple
of grids to an ARGB32
image, using an ImageGenerator
.
Generated pixels are written to the image buffer matrix.
DynamicGrids.imageconfig
— Functionimageconfig(output::ImageOutput) => ImageConfig
ImageOutpu
interface method. Return an ImageConfig
object.
DynamicGrids.inbounds
— Functioninbounds(data::SimData, I::Tuple) -> Tuple{NTuple{2,Int}, Bool}
inbounds(data::SimData, I...) -> Tuple{NTuple{2,Int}, Bool}
Check grid boundaries for a coordinate before writing in SetCellRule
.
Returns a Tuple
containing a coordinates Tuple
and a Bool
- true
if the cell is inside the grid bounds, false
if not.
BoundaryCondition
of type Remove
returns the coordinate and false
to skip coordinates that boundary outside of the grid.
Wrap
returns a tuple with the current position or it's wrapped equivalent, and true
as it is allways in-bounds.
DynamicGrids.init
— FunctionDynamicGrids.initialise!
— FunctionDynamicGrids.initialisegraphics
— Functioninitalisegraphics(o::Output, data::AbstractSimData)
GraphicOutput
interface method.
Initialise the output graphics at the start of the simulation, if it has graphics.
DynamicGrids.isasync
— Functionisasync(o::Output) => Bool
Output
interface method.
Check if the output should run asynchonously. Default is false
.
DynamicGrids.isinbounds
— Functionisinbounds(data, I::Tuple) -> Bool
isinbounds(data, I...) -> Bool
Check that a coordinate is within the grid, usually in SetCellRule
.
Unlike inbounds
, BoundaryCondition
status is ignored.
DynamicGrids.isinferred
— Methodisinferred(output::Output, ruleset::Ruleset)
isinferred(output::Output, rules::Rule...)
Test if a custom rule is inferred and the return type is correct when applyrule
or applyrule!
is run.
Type-stability can give orders of magnitude improvements in performance.
DynamicGrids.ismasked
— Methodismasked(data, I...)
Check if a cell is masked, using the mask
array.
Used used internally during simulations to skip masked cells.
If mask
was not passed to the Output
constructor or sim!
it defaults to nothing
and false
is always returned.
DynamicGrids.isrunning
— Functionisrunning(o::Output) => Bool
Output
interface method.
Check if the output is running. Prevents multiple versions of sim!
running on the same output for asynchronous outputs.
DynamicGrids.isshowable
— Functionisshowable(o::Output, f::Int) => Bool
Output
interface method.
Check if the output can be shown visually, where f is the frame number. Default is false
.
DynamicGrids.isstored
— Functionisastored(o::Output) => Bool
Output
interface method.
Check if the output is storing each frame, or just the the current one. Default is true
.
DynamicGrids.kernel
— Functionkernel(hood::AbstractKernelNeighborhood) => iterable
Returns the kernel object, an array or iterable matching the length of the neighborhood.
DynamicGrids.kernelproduct
— Functionkernelproduct(rule::NeighborhoodRule})
kernelproduct(hood::AbstractKernelNeighborhood)
kernelproduct(hood::Neighborhood, kernel)
Returns the vector dot product of the neighborhood and the kernel, although differing from dot
in that the dot product is not take for vector members of the neighborhood - they are treated as scalars.
DynamicGrids.mask
— FunctionDynamicGrids.max!
— Functionmax!(data::WritableGridData, x, I...)
Set a gride cell to the maximum of x
and the current value. See add!
for example usage.
DynamicGrids.min!
— Functionmin!(data::WritableGridData, x, I...)
Set a gride cell to the minimum of x
and the current value. See add!
for example usage.
DynamicGrids.modifyrule
— Functionmodifyrule(rule::Rule, data::SimData) -> Rule
Precalculates rule fields at each timestep. Define this method if a Rule
has fields that need to be updated over time.
Rule
s are usually immutable (it's faster), so precalc is expected to returns a new rule object with changes applied to it. Setfield.jl or Acessors.jl may help with updating the immutable struct.
The default behaviour is to return the existing rule without change.
Updated rules are be discarded, and the rule
argument is always be the original object passed in.
DynamicGrids.neighborhood
— Functionneighborhood(x::Union{NeighborhoodRule,SetNeighborhoodRule}}) -> Neighborhood
Returns a rules neighborhood object
DynamicGrids.neighbors
— Functionneighbors(x::Union{Neighborhood,NeighborhoodRule}}) -> iterable
Returns an iteraterable generator over all cells in the neighborhood.
Custom Neighborhood
s must define this method.
DynamicGrids.offsets
— Functionoffsets(x::Union{Neighborhood,NeighborhoodRule}}) -> iterable
Returns an iteraterable over all cells as a Tuple
of the index offset from the central cell.
Custom Neighborhood
s must define this method.
DynamicGrids.or!
— Functionor!(data::WritableGridData, x, I...)
or!(A::AbstractArray, x, I...)
Set the grid cell c
to c | x
. See add!
for example usage.
DynamicGrids.positions
— Functionpositions(x::Union{Neighborhood,NeighborhoodRule}}, cellindex::Tuple) -> iterable
Returns an iteraterable over all cells as a Tuple
of the index in the main array. Useful in SetNeighborhoodRule
for setting neighborhood values.
DynamicGrids.radius
— Functionradius(rule, [key]) -> Int
Return the radius of a rule or ruleset if it has one, otherwise zero.
DynamicGrids.resume!
— Functionresume!(output::GraphicOutput, ruleset::Ruleset=ruleset(output); tstop, kw...)
Restart the simulation from where you stopped last time. For arguments see sim!
. The keyword arg tstop
can be used to extend the length of the simulation.
Arguments
output
: AnOutput
to store grids or display them on the screen.ruleset
: ARuleset
containing one ore moreRule
s. These will each be run in sequence.
Keyword Arguments (optional
init
: an optional initialisation arraytstop
: the new stop time for the simulation. Taken from the output length by default.fps
: the frames per second to display. Taken from the output by default.simdata
: aSimData
object. Keeping it between simulations can improve performance when that is important
DynamicGrids.savegif
— Functionsavegif(filename::String, o::Output; kw...)
Write the output array to a gif.
Keywords
fps
:Real
frames persecond. Defaults to thefps
of the output, or25
.minval
: Minimum value in the grid(s) to normalise for conversion to an RGB pixel.Number
orTuple
for multiple grids.maxval
: Maximum value in the grid(s) to normalise for conversion to an RGB pixel.Number
orTuple
for multiple grids.font
:String
name of font to search for. A default will be guessed.text
:TextConfig()
ornothing
for no text. Default isTextConfig(; font=font)
.scheme
: ColorSchemes.jl scheme,ObjectScheme()
orGreyscale()
imagegen
:ImageGenerator
likeImage
orLayout
. Will be detected automatically
DynamicGrids.setfps!
— Functionsetfps!(o::Output, x)
GraphicOutput
interface method.
Set the frames per second the output will run at.
DynamicGrids.showframe
— Functionshowframe(o::Output, data::AbstractSimData)
showframe(frame::NamedTuple, o::Output, data::AbstractSimData)
showframe(frame::AbstractArray, o::Output, data::AbstractSimData)
GraphicOutput
interface method.
Display the grid/s somehow in the output, if it can do that.
DynamicGrids.showimage
— Functionshowimage(image::AbstractArray, o::ImageOutput)
showimage(image::AbstractArray, o::ImageOutput, data::AbstractSimData)
ImageOutput
interface method.
Display an image generated from the grid, a required method for all ImageOutput
.
DynamicGrids.sim!
— Functionsim!(output, rules::Rule...; kw...)
sim!(output, rules::Tuple{<:Rule,Vararg}; kw...)
sim!(output, [ruleset::Ruleset=ruleset(output)]; kw...)
Runs the simulation, passing the destination aray to the passed in output for each time-step.
Arguments
output
: AnOutput
to store grids or display them on the screen.ruleset
: ARuleset
containing one or moreRule
s. If the output has aRuleset
attached, it will be used.
Keywords
Theses are the taken from the output
argument by default:
init
: optional array or NamedTuple of arrays.mask
: aBool
array matching the init array size.false
cells do not run.aux
: aNamedTuple
of auxilary data to be used by rules.tspan
: a tuple holding the start and end of the timespan the simulaiton will run for.fps
: the frames per second to display. Will be taken from the output if not passed in.
Theses are the taken from the ruleset
argument by default:
proc
: aProcessor
to specificy the hardware to run simulations on, likeSingleCPU
,ThreadedCPU
orCuGPU
when KernelAbstractions.jl and a CUDA gpu is available.opt
: aPerformanceOpt
to specificy optimisations likeSparseOpt
orNoOpt
. Defaults toNoOpt()
.boundary
: what to do with boundary of grid edges. Options areRemove
orWrap
, defaulting toRemove()
.cellsize
: the size of cells, which may be accessed by rules.timestep
: fixed timestep where this is required for some rules. eg.Month(1)
or1u"s"
.
Other:
simdata
: aSimData
object. Keeping it between simulations can reduce memory allocation a little, when that is important.
DynamicGrids.step!
— Methodstep!(sd::SimData, rules=rules(sd))
Allows stepping a simulation one frame at a time, for a more manual approach to simulation that sim!
. This may be useful if other processes need to be run between steps, or the simulation is of variable length. step!
also removes the use of Output
s, meaning storing of grid data must be handled manually, if that is required. Of course, an output can also be updated manually, using:
DynmicGrids.storeframe!(output, simdata)
Instead of an Output
, the internal SimData
objects are used directly, and can be defined using a Extent
object and a Ruleset
.
Example
ruleset = Ruleset(myrules; proc=ThreadedCPU())
extent = Extent(; init=(a=A, b=B), aux=aux, tspan=tspan)
simdata = SimData(extent, ruleset)
# Run a single step, which returns an updated SimData object
simdata = step!(simdata)
# Get a view of the grid without padding, for NeighborhoodRule/SetNeighborhoodRule
DynmicGrids.gridview(simdata[:a])
This example returns a GridData
object for the :a
grid, which is <: AbstractAray
.
DynamicGrids.storeframe!
— Functionstoreframe!(o::Output, data::AbstractSimData)
Store the current simulaiton frame in the output.
DynamicGrids.sub!
— Functionsub!(data::WritableGridData, x, I...)
Subtract the value x
from a grid cell. See add!
for example usage.
DynamicGrids.timestep
— FunctionDynamicGrids.to_rgb
— Functionto_rgb(val) => ARGB32
to_rgb(scheme, val) => ARGB32
ImageOutput
interface method.
Display an image generated from the grid, a required method for all ImageOutput
.
Custom grid object will need to add methods for converting the object to a color,
to_rgb(::ObjectScheme, obj::CustomObj) = ...`
For use with other colorschemes, a method that calls get
with a Real
value obtained from the object will be required:
to_rgb(scheme, obj::CustomObj) = ARGB32(get(scheme, real_from_obj(obj)))
DynamicGrids.tspan
— FunctionDynamicGrids.xor!
— Functionxor!(data::WritableGridData, x, I...)
xor!(A::AbstractArray, x, I...)
Set the grid cell c
to xor(c, x)
. See add!
for example usage.