lgca.ms_cubic.MSLGCA_Cubic

class lgca.ms_cubic.MSLGCA_Cubic(*, n_species=1, **kwargs)

Bases: MultiSpeciesLGCA_base, LGCA_Cubic

Classical multi-species LGCA on a cubic lattice.

animate_density(density_t=None, colormap='viridis', opacity=0.5, cbar=True, interval=100, **kwargs)

Animate the density surface over time using Mayavi.

Parameters:
  • density_t (np.ndarray, optional) – Time series of density states. Shape: (time, lx, ly, lz).

  • threshold (float, default=0.5) – Density threshold for surface plotting.

  • colormap (str, default='viridis') – Colormap for the surface.

  • opacity (float, default=0.5) – Opacity of the surface.

  • interval (int, default=100) – Delay between frames in milliseconds.

  • **kwargs – Additional arguments passed to mlab.contour3d.

Returns:

animate_flux(nodes_t=None, scale_factor=1.0, opacity=0.6, interval=100, cbar=False, **kwargs)

Animate the flux vectors over time in the 3D lattice using Mayavi.

Parameters:
  • nodes_t (np.ndarray, optional) – Time series of node states. Shape: (time, lx, ly, lz, K).

  • scale_factor (float, default=1.0) – Scaling factor for the arrows.

  • opacity (float, default=0.6) – Opacity of the flux vectors.

  • interval (int, default=100) – Delay between frames in milliseconds.

  • **kwargs – Additional arguments passed to mlab.quiver3d.

Returns:

apply_abc()

Apply absorbing boundary conditions.

Update self.nodes, using the shadow border nodes and respecting the geometry.

apply_inflowbc()

Apply inflow boundary conditions.

Update self.nodes, using the shadow border nodes and respecting the geometry.

apply_pbc()

Apply periodic boundary conditions.

Update self.nodes, using the shadow border nodes and respecting the geometry.

apply_rbc()

Apply reflecting boundary conditions.

Update self.nodes, using the shadow border nodes and respecting the geometry.

c = array([[ 1., -1.,  0.,  0.,  0.,  0.],        [ 0.,  0.,  1., -1.,  0.,  0.],        [ 0.,  0.,  0.,  0.,  1., -1.]])
calc_flux(nodes)

Calculate the flux vector for all lattice sites in nodes.

The elements of the flux vectors are computed as the dot product between the LGCA’s neighborhood vectors and the velocity channel configuration in nodes.

Parameters:

nodes (numpy.ndarray) – Lattice configuration to compute the flux for. Must have more than or the same number of dimensions as self.nodes and nodes.shape[-1] >= self.velocitychannels. Is typically self.nodes.

Returns:

Array of flux vectors at each lattice site. Dimensions: nodes.shape[:-1] + (len(self.c),).

calc_permutations()

Initialize lazy computation structures for permutations. Only compute permutations when actually needed.

channel_weight(qty)

Calculate weights for the velocity channels in interactions depending on a field qty.

The weight for each velocity channel is given by the value of qty of the respective neighboring node.

Parameters:

qty (numpy.ndarray) – Scalar field with the same shape as self.cell_density.

Returns:

Weights for the velocity channels of shape self.dims + (self.velocitychannels,).

cix = array([ 1., -1.,  0.,  0.,  0.,  0.])
ciy = array([ 0.,  0.,  1., -1.,  0.,  0.])
ciz = array([ 0.,  0.,  0.,  0.,  1., -1.])
get_flux_permutations(n_particles)

Get flux permutations for n_particles.

get_permutations(n_particles)

Get permutations for n_particles.

Parameters:

n_particles (int) – Number of occupied channels.

Returns:

Array of permutations for n_particles.

gradient(qty)

Compute the gradient of qty along all axes.

Parameters:

qty (numpy.ndarray) – Quantity to take the gradient of. Needs to have the same number of dimensions as self.nodes. If qty.shape == self.nodes.shape[:-1] the result can be indexed with the LGCA coordinates (see example).

Returns:

Computed gradient. Dimensions: qty.shape + (len(self.c),). If self and qty are 2D arrays, gradient(qty)[...,0] is the gradient in x direction and gradient(qty)[...,1] the gradient in y direction.

Notes

The gradient is calculated using numpy.gradient() with stepwidth h=0.5 (s.t. no normalization takes place). It is computed as the central finite difference with equidistant support points and supports one-sided differences at the boundaries.

In most cases this yields the simple difference between the two closest array elements in the given direction. For example, the gradient at position 1 of np.array([1, 2, 4]) would be (4 - 1)/(2 * 0.5) = 3.

Examples

If the input quantity has the same x (and y) dimensions as the LGCA’s nodes, the gradient at each node position can be accessed the same way as the node itself.

>>> from lgca import get_lgca
>>> import numpy as np
>>> # define a square LGCA to illustrate dimensions
>>> lgca = get_lgca(geometry='square', dims=(2,3))
>>> lgca.nodes.shape  # (xdim, ydim, number of channels)
(4, 5, 4)
>>> my_qty = np.array([[0,0,0,0,0],
>>>                    [1,1,1,1,1],
>>>                    [2,2,2,3,2],
>>>                    [3,3,3,3,3]])
>>> my_qty.shape  # (xdim, ydim)
(4, 5)
>>> grad = lgca.gradient(my_qty)
>>> grad.shape  # (xdim, ydim, number of dimensions)
(4, 5, 2)
>>> # address like internal LGCA fields: first dimension is x (printed vertically),
>>> # second dimension is y (printed horizontally), this can be a bit confusing
>>> for coord in lgca.coord_pairs:
>>>     if np.any(grad[coord]>2):
>>>         print("Gradient at index", coord, "is ", grad[coord])
>>>         print("Configuration at index ", coord, " is ", lgca.nodes[coord],
>>>               ", with cell density ", lgca.cell_density[coord])
Gradient at index (1, 3) is  [3. 0.]
Configuration at index  (1, 3)  is  [False False False  True] , with cell density  1

The first element of the gradient holds the gradient in x direction, the second element the gradient in y direction. Note that (1, 3) is the index corresponding to a logical non-border coordinate (0, 2) if the interaction radius is 1. This is relevant for defining a custom field qty: Only the field values at non-border indices will be “felt” by the particles in the LGCA if the interaction is defined accordingly, but border nodes can be used to specify the field’s boundary conditions.

The gradient in x direction is 3 = (3 - 0)/1. In y direction it is 0 = (1 - 1)/1.

init_coords()

Initialize LGCA coordinates for a 3D cubic lattice.

init_nodes(density=0.1, nodes=None, **kwargs)

Initialize LGCA lattice configuration. Create the lattice and then assign particles to channels in the nodes. In the implementation, set self.nodes.

Must match what is done in set_dims() and init_coords(). For arguments and attribute types see lgca.base.LGCA_base.

Return type:

None

live_animate_density(**kwargs)

Live plot a 3D density surface based on a specified threshold using Mayavi.

Parameters:
  • threshold (float, default=0.5) – Density threshold for surface plotting.

  • colormap (str, default='viridis') – Colormap for the surface.

  • opacity (float, default=0.5) – Opacity of the surface.

  • **kwargs – Additional arguments passed to mlab.contour3d.

Returns:

live_animate_flux(scale_factor=1.0, opacity=0.5, cbar=False, **kwargs)

Live plot the flux vectors in the 3D lattice using Mayavi.

This method updates the plot in real-time as the simulation progresses.

Parameters:
  • scale_factor (float, default=1.0) – Scaling factor for the arrows.

  • opacity (float, default=0.6) – Opacity of the flux vectors.

  • **kwargs – Additional arguments passed to mlab.quiver3d.

Returns:

Mayavi quiver3d object.

nb_sum(qty)

For each node, sum up the contents of qty for the 6 neighboring nodes, excluding the center.

Parameters:

qty (numpy.ndarray) – Array holding some quantity of the LGCA, e.g. a flux. Of shape self.dims + x, where x is the shape of the quantity for one node, e.g. (2,) if it is a vector with 2 elements. self.dims ensures that lattice positions can be indexed the same way as in self.nodes.

Returns:

Sum of the content of qty in each node’s neighborhood, shape: qty.shape. Lattice positions can be indexed the same way as in self.nodes.

plot_density(density=None, colormap='viridis', opacity=0.5, cbar=True, **kwargs)

Plot a 3D surface based on the local density using a specified threshold using Mayavi.

Parameters:
  • threshold (float, default=0.5) – Density threshold for surface plotting.

  • colormap (str, default='viridis') – Colormap for the surface.

  • opacity (float, default=0.5) – Opacity of the surface.

  • **kwargs – Additional arguments passed to mlab.contour3d.

Returns:

Mayavi contour3d object.

plot_density_cubes(density=None, colormap='viridis', opacity=0.5, cbar=True, **kwargs)

Plot a 3D surface based on the local density using a specified threshold using Mayavi.

Parameters:
  • threshold (float, default=0.5) – Density threshold for surface plotting.

  • colormap (str, default='viridis') – Colormap for the surface.

  • opacity (float, default=0.5) – Opacity of the surface.

  • **kwargs – Additional arguments passed to mlab.contour3d.

Returns:

Mayavi contour3d object.

plot_flux(nodes=None, scale_factor=1.0, opacity=0.5, cbar=False, **kwargs)

Plot the local flux vectors in the 3D lattice using Mayavi.

Parameters:
  • nodes (np.ndarray, optional) – State of the lattice. If None, uses self.nodes.

  • scale_factor (float, default=1.0) – Scaling factor for the arrows.

  • color (str or tuple, default='blue') – Color of the flux vectors.

  • opacity (float, default=0.6) – Opacity of the flux vectors.

  • **kwargs – Additional arguments passed to mlab.quiver3d.

Returns:

Mayavi quiver3d object.

plot_scalarfield(field, mask=None, colormap='viridis', opacity=0.5, cbar=True, cbarlabel='Scalar field', vmin=None, vmax=None, **kwargs)

Plot a 3D scalar field using Mayavi. Parameters ———- field mask colormap opacity cbar kwargs

Returns:

print_interactions()

Print the list of pre-implemented interactions for this LGCA type.

print_nodes()

Print the full lattice configuration as integers.

propagation()

Perform the transport step of the LGCA: Move particles through the lattice according to their velocity.

Updates self.nodes such that resting particles stay in their position and particles in velocity channels are relocated according to the direction of the channel they reside in. Boundary conditions are enforced later by apply_boundaries().

See also

base.LGCA_base.nodes

State of the lattice showing the structure of the lgca.nodes array.

random_reset(density)

Randomly initialize a total density distributed over all species.

set_bc(bc)

Set the boundary conditions.

Selects a method which is called every timestep to enforce boundary conditions. The methods to select from are implemented in the derived classes. The chosen one is assigned to self.apply_boundaries().

Parameters:

bc ({'absorbing', 'reflecting', 'periodic', 'inflow'}) – Boundary conditions. Not all bc are supported in all geometries (yet).

set_dims(dims=None, nodes=None, restchannels=0, **kwargs)

Set LGCA dimensions.

Initializes self.K, self.restchannels, self.dims, self.lx, self.ly, and self.lz.

Parameters:
  • dims (tuple of int, default=(10, 10, 10)) – Lattice dimensions. Must match with specified geometry.

  • nodes (numpy.ndarray) – Custom initial lattice configuration.

  • restchannels (int, default=0) – Number of resting channels.

See also

init_nodes

Initialize LGCA lattice configuration.

init_coords

Initialize LGCA coordinates.

Return type:

None

set_interaction(**kwargs)

Set the interaction rule and respective needed parameters.

Set self.interaction and possibly add entries in self.interaction_params. Do not use this to specify a custom interaction. In order to do this (as of now), self.interaction and self.interaction_params must be manipulated directly from an external script.

Parameters:
  • kwargs['interaction'] (str, default='random_walk') – Name of the predefined interaction in lgca.interactions.

  • **kwargs – Interaction parameters.

set_r_int(r)

Change the interaction radius. Update shadow border nodes accordingly.

This has effects on self.nodes, the coordinates and the computed fields.

Parameters:

r (int) – New interaction radius.

timeevo(timesteps=100, record=False, recordN=False, recorddens=True, showprogress=True, recordpertype=False)

Perform a simulation of the LGCA for timesteps timesteps.

Different quantities can be recorded during the simulation, e.g. the total number of particles at each timestep. They are stored in LGCA attributes.

Parameters:
  • timesteps (int) – How long the simulation should be performed.

  • record (bool) – Record the full lattice configuration for each timestep in self.nodes_t.

  • recorddens (bool) – Record the number of particles at each lattice site for each timestep in self.dens_t.

  • recordN (bool) – Record the total number of particles in the lattice for each timestep in self.n_t.

  • recordpertype (bool) – Record the number of particles in velocity channels/resting channels at each lattice site for each timestep in self.velcells_t and self.restcells_t, respectively.

  • showprogress (bool) – Show a simple progress bar with a percentage of performed timesteps in the standard output.

Return type:

None

timestep()

Update the state of the LGCA from time k to k+1. Includes the interaction and propagation steps.

total_population()

Calculate the amount of particles in the lattice.

Returns:

Total population size.

update_dynamic_fields()

Update “fields” from the current LGCA state that store important variables to compute other dynamic steps.

Computes self.cell_density, number of particles at each lattice node.

Return type:

None