Reference

cellpylib.apen

apen(sequence, m=1, r=0)

Calculates the Approximate Entropy, or ApEn, of the given sequence, as described in:

Pincus, S. M.; Gladstone, I. M.; Ehrenkranz, R. A. (1991).
"A Regularity Statistic For Medical Data Analysis".
Journal of Clinical Monitoring and Computing. 7 (4): 335-345.

The implementation here is based on the Python implementation described in: https://en.wikipedia.org/wiki/Approximate_entropy

Parameters
  • sequence – a string of whole numbers, such as ‘012301’, or an array of whole numbers, such as [0,1,2,3,0,1], or a numpy array of whole numbers

  • m – the length of compared runs of data

  • r – a filtering level

Returns

a real number, representing the approximate entropy (ApEn) for the given sequence

cellpylib.bien

bien(string)

Calculate the BiEntropy of the given binary string, according to:

Croll, G. J. (2013). BiEntropy-The Approximate Entropy of a Finite Binary String.
arXiv preprint arXiv:1305.0954.

The BiEntropy can be used to compare two binary strings in terms of the relative order and disorder of all the digits. It makes use of a weighted average of the Shannon entropies of all but the last binary derivative of the given string. This version of BiEntropy is suitable for strings with length <= 32.

Parameters

string – a binary string, such as ‘110011’

Returns

a real number representing the BiEntropy of the given string

binary_derivative(string)

Calculates the binary derivative of the given string, according to:

Nathanson, M. B. (1971). Derivatives of binary sequences.
SIAM Journal on Applied Mathematics, 21(3), 407-412

The derivative of a binary string is simply the bitwise exclusive OR between a binary digit in the string and its successor, if a successor exists. For example, the derivative of the binary string ‘01010101’ is the binary string ‘1111111’.

Parameters

string – a binary string, such as ‘110011’

Returns

a binary string representing the binary derivative of the given string

cyclic_binary_derivative(string)

Calculates the cyclic binary derivative, which is the “binary string of length n formed by XORing adjacent pairs of digits including the last and the first.” See:

Croll, G. J. (2018). The BiEntropy of Some Knots on the Simple Cubic Lattice.
arXiv preprint arXiv:1802.03772.

The cyclic derivative of a binary string is simply the bitwise exclusive OR between a binary digit in the string and its successor, where the successor of the last digit in the string is the first digit in the string. For example, the cyclic derivative of the binary string ‘01010101’ is the binary string ‘11111111’.

Parameters

string – a binary string, such as ‘110011’

Returns

a binary string representing the cyclic binary derivative of the given string

ktbien(string)

Calculates the knot logarithmic weighting BiEntropy of the given string, according to:

Croll, G. J. (2018). The BiEntropy of Some Knots on the Simple Cubic Lattice.
arXiv preprint arXiv:1802.03772.

The Logarithmic Knot BiEntropy can be used to compare two binary strings in terms of the relative order and disorder of all the digits. It makes use of a logarithmic weighted average of the Shannon entropies of all but the last cyclic binary derivative of the given string. This version of BiEntropy is suitable for strings with length > 32.

Parameters

string – a binary string, such as ‘110011’

Returns

a real number representing the knot logarithmic weighting BiEntropy of the given string

tbien(string)

Calculates the logarithmic weighting BiEntropy of the given string, according to:

Croll, G. J. (2013). BiEntropy-The Approximate Entropy of a Finite Binary String.
arXiv preprint arXiv:1305.0954.

The Logarithmic BiEntropy can be used to compare two binary strings in terms of the relative order and disorder of all the digits. It makes use of a logarithmic weighted average of the Shannon entropies of all but the last binary derivative of the given string. This version of BiEntropy is suitable for strings with length > 32.

Parameters

string – a binary string, such as ‘110011’

Returns

a real number representing the logarithmic weighting BiEntropy of the given string

cellpylib.ca_functions

class AsynchronousRule(apply_rule, update_order=None, num_cells=None, randomize_each_cycle=False)

Creates an asynchronous cellular automaton rule with a cyclic update scheme. Also known as a sequential cellular automaton rule, in NKS. This rule wraps a given rule, making the given rule asynchronous. This rule works for both 1D and 2D cellular automata.

This rule requires the specification of an update order (if none is provided, then an order is constructed based on the number of cells in the CA). An update order specifies which cell will be updated as the CA evolves. For example, the update order [2, 3, 1] states that cell 2 will be updated in the next timestep, followed by cell 3 in the subsequent timestep, and then cell 1 in the timestep after that. This update order is adhered to for the entire evolution of the CA. Cells that are not being updated do not have the rule applied to them in that timestep.

An option is provided to randomize the update order at the end of each cycle (i.e. timestep). This is equivalent to selecting a cell randomly at each timestep to update, leaving all others unchanged during that timestep.

class BaseRule

A base rule class for custom rules to extend. A rule is a callable that accepts three parameters: 1, the current cell’s neighbourhood; 2, the index identifying the current cell; 3, an int identifying the current timestep. The rule returns the activity of the current cell at the next timestep.

class BinaryRule(rule, scheme=None, powers_of_two=None)

A binary representation of the given rule number, which is used to determine the value to return. The process is approximately described as:

1. convert state to int, so [1,0,1] -> 5, call this state_int

2. convert rule to binary, so 254 -> [1,1,1,1,1,1,1,0], call this rule_bin_array

3. new value is rule_bin_array[7 - state_int]
   we subtract 7 from state_int to be consistent with the numbering scheme used in NKS
   in NKS, rule 254 for a 1D binary cellular automaton is described as:

  [1,1,1]  [1,1,0]  [1,0,1]  [1,0,0]  [0,1,1]  [0,1,0]  [0,0,1]  [0,0,0]
     1        1        1        1        1        1        1        0

If None is provided for the scheme parameter, the neighbourhoods are listed in lexicographic order (the reverse of the NKS convention). If ‘nks’ is provided for the scheme parameter, the NKS convention is used for listing the neighbourhoods.

class NKSRule(nks_rule_number)

An Elementary Cellular Automaton rule, indexed according the scheme in NKS.

class ReversibleRule(init_state, rule_number)

An elementary cellular automaton rule explicitly set up to be reversible.

class TotalisticRule(k, rule)

The totalistic rule as described in NKS. The average color is mapped to a whole number in [0, k - 1]. The rule number is in base 10, but interpreted in base k. For a 1-dimensional cellular automaton, there are 3k - 2 possible average colors in the 3-cell neighbourhood. There are n(k - 1) + 1 possible average colors for a k-color cellular automaton with an n-cell neighbourhood.

binary_rule(neighbourhood, rule, scheme=None, powers_of_two=None)

Converts the given rule number to a binary representation, and uses this to determine the value to return. The process is approximately described as:

1. convert state to int, so [1,0,1] -> 5, call this state_int

2. convert rule to binary, so 254 -> [1,1,1,1,1,1,1,0], call this rule_bin_array

3. new value is rule_bin_array[7 - state_int]
   we subtract 7 from state_int to be consistent with the numbering scheme used in NKS
   in NKS, rule 254 for a 1D binary cellular automaton is described as:

  [1,1,1]  [1,1,0]  [1,0,1]  [1,0,0]  [0,1,1]  [0,1,0]  [0,0,1]  [0,0,0]
     1        1        1        1        1        1        1        0

If None is provided for the scheme parameter, the neighbourhoods are listed in lexicographic order (the reverse of the NKS convention). If ‘nks’ is provided for the scheme parameter, the NKS convention is used for listing the neighbourhoods.

Parameters
  • neighbourhood – a binary array of length 2r + 1

  • rule – an int or a binary array indicating the cellular automaton rule number

  • scheme – can be None (default) or ‘nks’; if ‘nks’ is given, the rule numbering scheme used in NKS is used

  • powers_of_two – a pre-computed array containing the powers of two, e.g. [4,2,1]; can be None (default) or an array of length len(neighbourhood); if an array is given, it will used to speed up the calculation of state_int

Returns

the result, 0 or 1, of applying the given rule on the given state

bits_to_int(bits)

Converts a binary array representing a binary number into the corresponding int.

Parameters

bits – a list of 1s and 0s, representing a binary number

Returns

and int representing the corresponding number

evolve(cellular_automaton, timesteps, apply_rule, r=1, memoize=False)

Evolves the given cellular automaton for the specified time steps. Applies the given function to each cell during the evolution. A cellular automaton is represented here as an array of arrays, or matrix. This function expects an array containing the initial time step (i.e. initial condition, an array) for the cellular automaton. The final result is a matrix, where the number of rows equal the number of time steps specified.

Parameters
  • cellular_automaton – the cellular automaton starting condition representing the first time step, e.g. [[0,0,0,0,1,0,0,0,0]], or a history of previous states, with the last item in the given array being the starting condition for the evolution, e.g. [[0,0,0,0,0,0,0,0,0], [0,0,0,0,1,0,0,0,0]]

  • timesteps – the number of time steps in this evolution, or a callable that accepts the cellular automaton (in terms of the history of its evolution) and the current timestep number, and is expected to return a boolean indicating whether the evolution should continue; note that if a number is given, this value refers to the total number of time steps in this cellular automaton evolution, which includes the initial condition

  • apply_rule – a function representing the rule to be applied to each cell during the evolution; this function will be given three arguments, in the following order: the neighbourhood, which is a numpy array of length 2r + 1 representing the neighbourhood of the cell; the cell identity, which is a scalar representing the index of the cell in the cellular automaton array; the time step, which is a scalar representing the time step in the evolution

  • r – the neighbourhood radius; the neighbourhood size will be 2r + 1 (default is 1)

  • memoize – allowed values are True, False, and “recursive”; if True, then the result of applying the rule on a given neighbourhood will be cached, and used on subsequent invocations of the rule; if “recursive”, then a recursive memoized algorithm will be used, in which recursively wider neighbourhoods are cached, along with the result of applying the rule on the cells in the widened neighbourhood; the True and “recursive” options can result in a significant improvement to execution speed if the rule is expensive to invoke; the “recursive” option works best when there are strongly repetitive patterns in the CA, and when the state consists of 2^k cells; if False, then no caching will be used; NOTE: this should only be set to True or “recursive” for rules which do not store any state upon invocation, and for rules which do not depend in the cell index or timestep number (default is False)

Returns

a matrix, containing the results of the evolution, where the number of rows equal the number of time steps specified

evolve_block(cellular_automaton, block_size, timesteps, apply_rule)

Evolves the given block cellular automaton for the specified time steps. Applies the given function to each block during the evolution. A cellular automaton is represented here as an array of arrays, or matrix. This function expects an array containing the initial time step (i.e. initial condition, an array) for the cellular automaton. The final result is a matrix, where the number of rows equal the number of time steps specified.

Parameters
  • cellular_automaton – the cellular automaton starting condition representing the first time step, e.g. [[0,0,0,0,1,0,0,0,0]]

  • block_size – the number of cells in the block; the total number of cells in the CA must be divisible by the block size

  • timesteps – the number of time steps in this evolution; this value refers to the total number of time steps in this cellular automaton evolution, which includes the initial condition

  • apply_rule – a function representing the rule to be applied to each block during the evolution; this function will be given two arguments, in the following order: a tuple containing the activities of the cells in the block, and a scalar representing the timestep in the evolution; this function must return a tuple with the new activities for the block

Returns

a matrix, containing the results of the evolution, where the number of rows equal the number of time steps specified

init_random(size, k=2, n_randomized=None, empty_value=0, dtype=<class 'numpy.int32'>)

Returns a randomly initialized array with values consisting of numbers in {0,…,k - 1}, where k = 2 by default. If dtype is not an integer type, then values will be uniformly distributed over the half-open interval [0, k - 1).

Parameters
  • size – the size of the array to be created

  • k – the number of states in the cellular automaton (2, by default)

  • n_randomized – the number of randomized sites in the array; this value must be >= 0 and <= size, if specified; if this value is not specified, all sites in the array will be randomized; the randomized sites will be centered in the array, while all others will have an empty value

  • empty_value – the value to use for non-randomized sites (0, by default)

  • dtype – the data type

Returns

a vector with shape (1, size), randomly initialized with numbers in {0,…,k - 1}

init_simple(size, val=1, dtype=<class 'numpy.int32'>)

Returns an array initialized with zeroes, with its center value set to the specified value, or 1 by default.

Parameters
  • size – the size of the array to be created

  • val – the value to be used in the center of the array (1, by default)

  • dtype – the data type

Returns

a vector with shape (1, size), with its center value initialized to the specified value, or 1 by default

int_to_bits(num, num_digits)

Converts the given number, num, to the corresponding binary number in the form of a NumPy array of 1s and 0s comprised of num_digits digits.

Parameters
  • num – the number, in base 10, to convert into binary

  • num_digits – the number of digits the binary number should contain

Returns

a NumPy array of 1s and 0s representing the corresponding binary number

nks_rule(neighbourhood, rule)

A convenience function, that calls binary_rule with scheme = ‘nks’.

Parameters
  • neighbourhood – a binary array of length 2r + 1

  • rule – an int indicating the cellular automaton rule number

Returns

the result, 0 or 1, of applying the given rule on the given state

plot(ca, title='', *, colormap='Greys', xlabel='', ylabel='time', show=True, **imshow_kwargs)

Plots the given cellular automaton.

Parameters
  • ca – the cellular automaton to plot

  • title – the title to place on the plot (default is empty)

  • colormap – the colormap to use (default is ‘Greys’)

  • xlabel – the label of the x-axis (default is empty)

  • ylabel – the label of the y-axis (default ‘time’)

  • show – show the plot (default is True)

  • imshow_kwargs – keyword arguments for the Matplotlib imshow function

plot_multiple(ca_list, titles, *, colormap='Greys', xlabel='', ylabel='time', show=True, **imshow_kwargs)

Plots multiple cellular automata separately.

Parameters
  • ca_list – a list of cellular automata

  • titles – the titles to give the plots; there must be one title for each CA

  • colormap – the colormap to use for the plots (default is ‘Greys’)

  • xlabel – the label of the x-axis (default is empty)

  • ylabel – the label of the y-axis (default ‘time’)

  • show – show the plot (default is True)

  • imshow_kwargs – keyword arguments for the Matplotlib imshow function

totalistic_rule(neighbourhood, k, rule)

The totalistic rule as described in NKS. The average color is mapped to a whole number in [0, k - 1]. The rule number is in base 10, but interpreted in base k. For a 1-dimensional cellular automaton, there are 3k - 2 possible average colors in the 3-cell neighbourhood. There are n(k - 1) + 1 possible average colors for a k-color cellular automaton with an n-cell neighbourhood.

Parameters
  • neighbourhood – a k-color array of any size

  • k – the number of colors in this cellular automaton, where only 2 <= k <= 36 is supported

  • rule – the k-color cellular automaton rule number in base 10, interpreted in base k

Returns

the result, a number from 0 to k - 1, of applying the given rule on the given state

until_fixed_point()

Returns a callable to be used as the timesteps argument to the evolve and evolve2d functions, that will result in the evolution being halted when there have been no changes to the state of the CA in the last timestep. That is, if the last state of the CA is the same as the second-to-last state, the callable will return False, and evolution will be halted.

Returns

a callable to be used as the timesteps argument to the evolve and evolve2d functions

cellpylib.ca_functions2d

evolve2d(cellular_automaton, timesteps, apply_rule, r=1, neighbourhood='Moore', memoize=False)

Evolves the given cellular automaton for the specified time steps. Applies the given function to each cell during the evolution. A cellular automaton is represented here as an array of arrays, or matrix. This function expects an array containing the initial time step (i.e. initial condition, an array) for the cellular automaton. The final result is a matrix, where the number of rows equal the number of time steps specified.

Parameters
  • cellular_automaton – the cellular automaton starting condition representing the first time step, or a history of previous states, with the last item in the given array being the starting condition for the evolution

  • timesteps – the number of time steps in this evolution, or a callable that accepts the cellular automaton (in terms of the history of its evolution) and the current timestep number, and is expected to return a boolean indicating whether the evolution should continue; note that if a number is given, this value refers to the total number of time steps in this cellular automaton evolution, which includes the initial condition

  • apply_rule – a function representing the rule to be applied to each cell during the evolution; this function will be given three arguments, in the following order: the neighbourhood, which is a numpy 2D array of dimensions 2r+1 x 2r+1, representing the neighbourhood of the cell (if the ‘von Neumann’ neighbourhood is specified, the array will be a masked array); the cell identity, which is a tuple representing the row and column indices of the cell in the cellular automaton matrix, as (row, col); the time step, which is a scalar representing the time step in the evolution

  • r – the neighbourhood radius; the neighbourhood dimensions will be 2r+1 x 2r+1 (default is 1)

  • neighbourhood – the neighbourhood type; valid values are ‘Moore’ or ‘von Neumann’ (default is ‘Moore’)

  • memoize – allowed values are True, False, and “recursive”; if True, then the result of applying the rule on a given neighbourhood will be cached, and used on subsequent invocations of the rule; if “recursive”, then a recursive memoized algorithm will be used, in which recursively wider neighbourhoods are cached, along with the result of applying the rule on the cells in the widened neighbourhood; the True and “recursive” options can result in a significant improvement to execution speed if the rule is expensive to invoke; the “recursive” option works best when there are strongly repetitive patterns in the CA, and when the state consists of 2^k x 2^k cells; if False, then no caching will be used; NOTE: this should only be set to True or “recursive” for rules which do not store any state upon invocation, and for rules which do not depend in the cell index or timestep number (default is False)

Returns

a list of matrices, containing the results of the evolution, where the number of rows equal the number of time steps specified

evolve2d_block(cellular_automaton, block_size, timesteps, apply_rule)

Evolves the given block cellular automaton for the specified time steps. Applies the given function to each block during the evolution. A cellular automaton is represented here as an array of arrays, or matrix. This function expects an array containing the initial time step (i.e. initial condition, an array) for the cellular automaton. The final result is a matrix, where the number of rows equal the number of time steps specified.

Parameters
  • cellular_automaton – the cellular automaton starting condition representing the first time step

  • block_size – a 2-tuple representing the number of rows and columns in the block; the total number of cells in the CA must be divisible by the block size

  • timesteps – the number of time steps in this evolution; this value refers to the total number of time steps in this cellular automaton evolution, which includes the initial condition

  • apply_rule – a function representing the rule to be applied to each block during the evolution; this function will be given two arguments, in the following order: the block, which is a numpy 2D array with the number of rows and columns specified in the block_size, and the time step, which is a scalar representing the time step in the evolution; this function must return a 2D array containing the new values of the block

Returns

a list of matrices, containing the results of the evolution, where the number of rows equal the number of time steps specified

game_of_life_rule(neighbourhood, c, t)

Conway’s Game of Life rule.

Parameters
  • neighbourhood – the current cell’s neighbourhood

  • c – the index of the current cell

  • t – the current timestep

Returns

the state of the current cell at the next timestep

init_random2d(rows, cols, k=2, dtype=<class 'numpy.int32'>)

Returns a randomly initialized matrix with values consisting of numbers in {0,…,k - 1}, where k = 2 by default. If dtype is not an integer type, then values will be uniformly distributed over the half-open interval [0, k - 1).

Parameters
  • rows – the number of rows in the matrix

  • cols – the number of columns in the matrix

  • k – the number of states in the cellular automaton (2, by default)

  • dtype – the data type

Returns

a tensor with shape (1, rows, cols), randomly initialized with numbers in {0,…,k - 1}

init_simple2d(rows, cols, val=1, dtype=<class 'numpy.int32'>, coords=None)

Returns a matrix initialized with zeroes, with its center value set to the specified value, or 1 by default. If the coords argument is specified, then the specified cell at the given coordinates will have its value set to val, otherwise the center cell will be set.

Parameters
  • rows – the number of rows in the matrix

  • cols – the number of columns in the matrix

  • val – the value to be used in the center of the matrix (1, by default)

  • dtype – the data type (np.int32 by default)

  • coords – a 2-tuple specifying the row and column of the cell to be initialized (None by default)

Returns

a tensor with shape (1, rows, cols), with the center value initialized to the specified value, or 1 by default

plot2d(ca, timestep=None, title='', *, colormap='Greys', show_grid=False, show_margin=True, scale=0.6, show=True, **imshow_kwargs)

Plots the state of the given 2D cellular automaton at the given timestep. If no timestep is provided, then the last timestep is plotted.

The show_margin argument controls whether or not a margin is displayed in the resulting plot. When show_margin is set to False, then the plot takes up the entirety of the window. The scale argument is only used when the show_margins argument is False. It controls the resulting scale (i.e. relative size) of the image when there are no margins.

Parameters
  • ca – the 2D cellular automaton to plot

  • timestep – the timestep of interest

  • title – the title to place on the plot

  • colormap – the color map to use (default is “Greys”)

  • show_grid – whether to display a grid (default is False)

  • show_margin – whether to display the margin (default is True)

  • scale – the scale of the figure (default is 0.6)

  • show – show the plot (default is True)

  • imshow_kwargs – keyword arguments for the Matplotlib imshow function

plot2d_animate(ca, title='', *, colormap='Greys', show_grid=False, show_margin=True, scale=0.6, dpi=80, interval=50, save=False, autoscale=False, show=True, **imshow_kwargs)

Animate the given 2D cellular automaton.

The show_margin argument controls whether or not a margin is displayed in the resulting plot. When show_margin is set to False, then the plot takes up the entirety of the window. The scale argument is only used when the show_margins argument is False. It controls the resulting scale (i.e. relative size) of the image when there are no margins.

The dpi argument represents the dots per inch of the animation when it is saved. There will be no visible effect of the dpi argument if the animation is not saved (i.e. when save is False).

Parameters
  • ca – the 2D cellular automaton to animate

  • title – the title to place on the plot (default is “”)

  • colormap – the color map to use (default is “Greys”)

  • show_grid – whether to display a grid (default is False)

  • show_margin – whether to display the margin (default is True)

  • scale – the scale of the figure (default is 0.6)

  • dpi – the dots per inch of the image (default is 80)

  • interval – the delay between frames in milliseconds (default is 50)

  • save – whether to save the animation to a local file (default is False)

  • autoscale – whether to autoscale the images in the animation; this should be set to True if the first frame has a uniform value (e.g. all zeroes) (default is False)

  • show – show the plot (default is True)

  • imshow_kwargs – keyword arguments for the Matplotlib imshow function

Returns

the animation

plot2d_slice(ca, slice=None, title='', *, colormap='Greys', show_grid=False, show_margin=True, scale=0.6, show=True, **imshow_kwargs)

Plots a slice through the evolved states of a 2D cellular automaton. For example, consider the following ca, which may represent the evolution of a 3x3 2D cellular automaton over 3 timesteps:

[[[ 1,  2,  3],
  [ 4,  5,  6],
  [ 7,  8,  9]],
 [[10, 11, 12],
  [13, 14, 15],
  [16, 17, 18]],
 [[19, 20, 21],
  [22, 23, 24],
  [25, 26, 27]]]

By default, the following would be plotted:

[[ 4,  5,  6],
 [13, 14, 15],
 [22, 23, 24]]

If 0 is provided as the slice argument, then the following would be plotted:

[[ 1,  2,  3],
 [10, 11, 12],
 [19, 20, 21]]

The show_margin argument controls whether or not a margin is displayed in the resulting plot. When show_margin is set to False, then the plot takes up the entirety of the window. The scale argument is only used when the show_margins argument is False. It controls the resulting scale (i.e. relative size) of the image when there are no margins.

Parameters
  • ca – the 2D cellular automaton to plot

  • slice – an int representing the index of the row to plot; by default, the “center” row is used

  • title – the title to place on the plot

  • colormap – the color map to use (default is “Greys”)

  • show_grid – whether to display a grid (default is False)

  • show_margin – whether to display the margin (default is True)

  • scale – the scale of the figure (default is 0.6)

  • show – show the plot (default is True)

  • imshow_kwargs – keyword arguments for the Matplotlib imshow function

plot2d_spacetime(ca, alpha=None, title='', show=True)

Plots the evolution of the given 2D cellular automaton as a 3D space-time plot.

Parameters
  • ca – the 2D cellular automaton to plot

  • alpha – the alpha blending value; a real number between 0 (transparent) and 1 (opaque)

  • title – the title to place on the plot

  • show – show the plot (default is True)

cellpylib.ctrbl_rule

class CTRBLRule(rule_table, add_rotations=False)

A rule that operates on von Neumann neighbourhoods, taking into account the states of a cell’s neighbours at the top, right, bottom and left positions. Only supports 2D automata with periodic boundaries and a radius of 1.

property rule_table

The rule table for this CTRBL rule.

Returns

the rule table

cellpylib.entropy

average_cell_entropy(cellular_automaton)

Calculates the average cell entropy in the given cellular automaton, where entropy is the Shannon entropy. In the case of a 1D cellular automaton, the state of a cell over time is represented as a string, and its entropy is calculated. The same is done for all cells in this cellular automaton, and the average entropy is returned.

Parameters

cellular_automaton – the cellular automaton to perform this operation on

Returns

a real number representing the average cell Shannon entropy, in bits

average_mutual_information(cellular_automaton, temporal_distance=1)

Calculates the average mutual information between a cell and itself at the next n time steps, given by the specified temporal distance. A temporal distance of 1 means the next time step.

For example, consider the following string, ‘00101010110’, which represents the state of a cell over 11 time steps. The strings which will be used for the computation of the mutual information between a cell and itself at the next time step are: ‘0010101011’ and ‘0101010110’, since we pair each time-step value with its next value:

" 00101010110"
"00101010110 "
Parameters
  • cellular_automaton – the cellular automaton to perform this operation on

  • temporal_distance – the size of temporal separation, where the value must be greater than 0 and less than the number of time steps.

Returns

a real number representing the average mutual information between a cell and itself at the next time step, in bits

joint_shannon_entropy(stringX, stringY)

Calculates the joint Shannon entropy between the given strings, which must be of the same length.

Parameters
  • stringX – any string, such as ‘000101001’, ‘12402’, or ‘aBcd1234ef5g’

  • stringY – any string, such as ‘000101001’, ‘12402’, or ‘aBcd1234ef5g’

Returns

a real number representing the joint Shannon entropy between the given strings, in bits

mutual_information(stringX, stringY)

Calculates the mutual information between the given strings, which must be of the same length.

Parameters
  • stringX – any string, such as ‘000101001’, ‘12402’, or ‘aBcd1234ef5g’

  • stringY – any string, such as ‘000101001’, ‘12402’, or ‘aBcd1234ef5g’

Returns

a real number representing the mutual information between the given strings, in bits

shannon_entropy(string)

Calculates the Shannon entropy for the given string.

Parameters

string – any string, such as ‘000101001’, ‘12402’, or ‘aBcd1234ef5g’

Returns

a real number representing the Shannon entropy, in bits

cellpylib.hopfield_net

class HopfieldNet(num_cells)

An implementation of the Hopfield network. Due to limitations of this implementation, only an odd number of cells is supported.

For more information on Hopfield networks, see:

Hopfield, J. J. (1982). Neural networks and physical systems with emergent collective
computational abilities. Proceedings of the national academy of sciences, 79(8), 2554-2558.
property W

Returns the learned weight matrix.

Returns

the learned weight matrix

property r

The radius of this automaton.

Returns

the radius

train(P)

The training set consists of patterns to be learned by this net. The patterns should be composed of bipolar ({-1,1}), and not binary ({0,1}), values.

Parameters

P – the set of training patterns

cellpylib.langtons_loop

class LangtonsLoop

An implementation of Langton’s Loop, a kind of CTRBL rule. For more information, see:

Langton, C. G. (1984). Self-reproduction in Cellular Automata.
Physica D: Nonlinear Phenomena, 10(1-2), 135-144.

NOTE: This implementation is meant only for periodic boundary conditions, however, the original Langton’s loops rules here assume an infinitely sized space. There may be errors due to states missing from the rule table if the loops are allowed to overlap. (H. Sayama may have proposed a fix for this in his Ph.D. thesis.)

static init_loops(n, dim, row, col)

Create the initial conditions by specifying the number of loops and their starting positions (as given by the coordinates of the first cell of the first row of the loop).

Parameters
  • n – the number of loops to create

  • dim – a 2-tuple representing the dimensions (number of rows and columns) of the CA

  • row – a list with length n, where the nth item specifies the row number of the nth loop

  • col – a list with length n, where the nth item specifies the column number of the nth loop

Returns

the initial conditions

cellpylib.sdsr_loop

class SDSRLoop

An implementation of H. Sayama’s SDSR loop. For more information, see:

Sayama, H. (1998). Constructing evolutionary systems on a simple deterministic cellular automata space.
PhD, University of Tokyo, Department of Information Science.

cellpylib.evoloop

class Evoloop

An implementation of H. Sayama’s Evoloop. For more information, see:

Sayama, H. (1998). Constructing evolutionary systems on a simple deterministic cellular automata space.
PhD, University of Tokyo, Department of Information Science.
static init_species13_loop(dim, row, col)

Create the initial conditions by specifying the a loop of species 13 and its starting position (as given by the coordinates of the first cell of the first row of the loop).

Parameters
  • dim – a 2-tuple representing the dimensions (number of rows and columns) of the CA

  • row – the row number of the loop

  • col – the column number of the loop

Returns

the initial conditions

cellpylib.rule_tables

random_rule_table(k, r, lambda_val=None, quiescent_state=None, strong_quiescence=False, isotropic=False)

Constructs and returns a random rule table using the “random-table” method, as described in:

Langton, C. G. (1990). Computation at the edge of chaos: phase transitions
and emergent computation.
Physica D: Nonlinear Phenomena, 42(1-3), 12-37.
Parameters
  • k – the number of cell states

  • r – the radius of the cellular automaton neighbourhood

  • lambda_val – a real number in (0., 1.), representing the value of lambda; if None, a default value of 1.0 - 1/k will be used, where all states will be represented equally in the rule table

  • quiescent_state – the state, a number in {0,…,k - 1}, to use as the quiescent state

  • strong_quiescence – if True, all neighbourhood states uniform in cell state i will map to cell state i

  • isotropic – if True, all planar rotations of a neighbourhood state will map to the same cell state

Returns

a tuple containing: a table describing a rule, constructed using the “random-table” table method as described by C. G. Langton, the actual lambda value, and the quiescent state used

table_rule(neighbourhood, table)

A rule where the state is converted into a string, and looked up in the given table, to yield the return value.

Parameters
  • neighbourhood – a k-color array of length 2r + 1

  • table – a table (map) of string representations of each neighbourhood state to the associated next cell state value; for example, for k = 2 and r = 2, a valid table might be: {‘101’: 1, ‘111’: 0, ‘011’: 0, ‘110’: 1, ‘000’: 0, ‘100’: 0, ‘010’: 0, ‘001’: 1}

Returns

a number, from 0 to k - 1, associated with the given state as specified in the given table

table_walk_through(rule_table, lambda_val, k, r, quiescent_state, strong_quiescence=False, isotropic=False)

Perturbs the given rule table using the “table-walk-through” approach described in:

Langton, C. G. (1990). Computation at the edge of chaos: phase transitions
and emergent computation.
Physica D: Nonlinear Phenomena, 42(1-3), 12-37.

The table’s actual lambda value will be increased or decreased, incrementally and stochastically, until it reaches the given lambda value.

Parameters
  • rule_table – a table (map) of string representations of each neighbourhood state to the associated next cell state value; for example, for k = 2 and r = 2, a valid table might be: {‘101’: 1, ‘111’: 0, ‘011’: 0, ‘110’: 1, ‘000’: 0, ‘100’: 0, ‘010’: 0, ‘001’: 1}

  • lambda_val – a real number in (0., 1.), representing the value of lambda

  • k – the number of cell states

  • r – the radius of the cellular automaton neighbourhood

  • quiescent_state – the state, a number in {0,…,k - 1}, to use as the quiescent state

  • strong_quiescence – if True, all neighbourhood states uniform in cell state i will map to cell state i

  • isotropic – if True, all planar rotations of a neighbourhood state will map to the same cell state

Returns

a tuple containing: a table describing a rule, constructed using the “table-walk-through” method as described by C. G. Langton, the actual lambda value

cellpylib.sandpile

class Sandpile(rows, cols, is_closed_boundary=True)

A rule that operates on von Neumann neighbourhoods with a radius of 1. A sandpile is a 2D cellular automaton and dynamical system that displays self-organized criticality. It was introduced by Bak, Tang and Wiesenfeld in 1987.

add_grain(cell_index, timestep)

Drop a grain of sand at the given cell in the given timestep.

Parameters
  • cell_index – a 2-tuple representing the row index and column index of the cell that will have a grain of sand added

  • timestep – the timestep at which the grain addition will occur