Skip to content

Spaces

Define the spaces members live on and the neighbourhoods laws read.

A space places the members of a group and says who neighbours whom, such as a lattice, a network, or a continuous box. A neighbourhood picks the members a law reads around a member.

AdjacencyNeighborhood(*, center=False, layer=None, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the nodes joined to a node by the edges of a network.

A law that reads it sees the values of every node joined to a member by an edge, such as the friends of a voter in AdjacencyNeighborhood(layer='friends'). The neighbours come in node order, after the node itself when center is true, and on a directed graph they are the successors. A local rule receives them padded to the largest number of edges at a node. A person catches a disease from their contacts, a voter copies a friend, and a bus of a power grid trades power with the buses wired to it.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
center bool

Whether the node itself comes first.

False
layer str | None

The label of the layer whose edges join the neighbours, or None for the graph of the network.

None
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'
See Also

NetworkSpace: Holds the graph and the layers whose edges it reads. RadiusNeighborhood: Reads the members within a distance on a lattice or in a box.

Examples:

>>> from skcomplex.core.components.spaces import AdjacencyNeighborhood
>>> AdjacencyNeighborhood(layer='work').layer
'work'
Source code in src/skcomplex/core/components/spaces/_adjacency.py
40
41
42
43
def __init__(self, *, center: bool = False, layer: str | None = None, label: str = 'neighborhood') -> None:
    super().__init__(label)
    self.center = center
    self.layer = layer

AxisSpec(name, size, low, high, periodic=False) dataclass

Bases: BaseSpec

A spec of an extra axis of a phase space, a range cut into equal cells.

It cuts the range from low to high into size cells of width (high - low) / size, so AxisSpec('v', 128, -6.0, 6.0) gives a phase space a velocity axis of 128 cells. A periodic axis joins its two ends, as an angle does. It holds the velocity of gas molecules, the swimming direction of bacteria, or the age of the cells of a tissue.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
name str

The name of the axis, which laws read its coordinate by.

required
size int

The number of cells.

required
low float

The lower end of the range.

required
high float

The upper end of the range.

required
periodic bool

Whether the two ends of the range are joined, as for an angle, rather than edges without flux.

False
See Also

PhaseSpace: Combines a lattice of positions with these axes.

Examples:

>>> from skcomplex.core.components.spaces import AxisSpec, LatticeSpace, PhaseSpace
>>> space = PhaseSpace(LatticeSpace(4), [AxisSpec('v', 3, -1.5, 1.5)]).prepare()
>>> space.coordinates_['v'].tolist()
[-1.0, 0.0, 1.0]

BaseNeighborhood(label)

Bases: BaseComponent[None]

An abstract neighbourhood, the members a law reads around a member of a space.

A subclass says which members count as neighbours of a member, such as the eight cells around a site in RadiusNeighborhood(1, metric='chebyshev'). It stores its arguments in __init__, and prepare checks them and derives what the engine reads, such as the offsets on a lattice. A space rejects a neighbourhood of a kind it cannot read. Its subclasses pick the cells around a tree in a forest fire, the contacts of a person in an epidemic, and the birds within sight of a bird in a flock.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
label str

The name of the neighbourhood, such as 'moore'.

required
See Also

BaseSpace: Places the members whose neighbours it picks.

Examples:

>>> from skcomplex.core.components.spaces import BaseNeighborhood, RadiusNeighborhood
>>> isinstance(RadiusNeighborhood(1), BaseNeighborhood)
True
Source code in src/skcomplex/core/components/base.py
69
70
def __init__(self, label: str) -> None:
    self.label = label

BaseSpace(label)

Bases: BaseComponent[None]

An abstract space, where the members of a group live and who neighbours whom.

A subclass places the members of a group and says which of them are neighbours, such as the 100 sites of LatticeSpace((10, 10)). It holds no values, only the structure the members sit on, and it gives vector values their length. It stores its arguments in __init__, and prepare checks them and derives its size, shape, and positions. A space with sites answers the private hooks the engine reads, such as _get_neighbors for the sites around a site, and a space without sites, such as a continuous box, answers none of them. Its subclasses hold the grid of a forest, the contact network of an epidemic, and the box of a gas.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
label str

The name of the space in its system, such as 'grid'.

required

Attributes:

Name Type Description
size_

The number of sites, or None for a space without sites.

n_dim_

The number of dimensions, the length of the vector states of members of the space.

shape_

The shape of the arrays of the values of the sites, () for a space without sites.

positions_

The position of every site, one row per site, or an empty array of n_dim_ columns without sites.

periodic_

Whether opposite sides of the space join.

default_visual_

The name or class of the visual of groups on the space when neither the group nor its element sets one, or None.

See Also

LatticeSpace: Places the members on a grid of sites. NetworkSpace: Places the members on the nodes of a graph. ContinuousSpace: Lets the members move to any real position. BaseNeighborhood: Picks the members a law reads around a member.

Examples:

>>> from skcomplex.core.components.spaces import BaseSpace, LatticeSpace
>>> space = LatticeSpace((10, 10)).prepare()
>>> isinstance(space, BaseSpace), space.size_
(True, 100)
Source code in src/skcomplex/core/components/base.py
69
70
def __init__(self, label: str) -> None:
    self.label = label

CellComplexSpace(space=None, *, points=None, cells=None, faces=None, dimension=LOWEST_DIMENSION, boundary=None, label='space')

Bases: NetworkSpace

A space of the sites, links, and faces of a lattice, network, or mesh, oriented.

It holds sites, the links between them, and the faces the links enclose, each with a direction, so a value can live on a link or a face, such as the 128 links of CellComplexSpace(LatticeSpace((8, 8))). Its nodes are the sites, its edges the links, and its hyperedges the faces, so groups on edges and hyperedges hold values on links and faces. It derives from a lattice or a network, or it is built from the points and triangles of a mesh, such as the p and t arrays of a scikit-fem mesh, which fits a domain of any shape and is solved by finite elements. A lattice numbers its links by direction and then by site, each pointing along its axis, and a mesh orients each cell by increasing node number. Angles live on the links of a lattice in gauge theory, the flows of a road network split into a flow that runs downhill and a flow that circulates, and heat flows through a machine piece meshed into triangles.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
space LatticeSpace | NetworkSpace | None

The LatticeSpace or the NetworkSpace the cells derive from, or None for a mesh of points and cells.

None
points ArrayLike | None

The coordinates of the nodes of a mesh, one column per node and one row per dimension, or None for a complex that derives from space.

None
cells ArrayLike | None

The node indices of every triangle or tetrahedron of a mesh, one column per cell, or None for a complex that derives from space.

None
faces str | Sequence[Sequence[object]] | None

The faces of a network: None for a minimum cycle basis, 'hyperedges' for the hyperedges of the network, 'cliques' for its cliques up to dimension, or a sequence of node cycles. A lattice and a mesh take None.

None
dimension int

The highest degree of the cells. Cells of degree 3 take part in incidence and topology only, since a group lives on sites, edges, or hyperedges.

LOWEST_DIMENSION
boundary Mapping[str, object] | None

The edge of each state of a field on a mesh by name, 'zero-flux' for an insulated wall or ('fixed', value) for a wall held at a value, a number or a function of the node coordinates, such as {'u': ('fixed', 0.0)}. A state without one has zero flux through the edge. A field on a mesh is solved by finite elements, and a field on a complex that derives from a space by finite differences.

None
label str

The name of the space in its system, such as 'grid'.

'space'

Attributes:

Name Type Description
mesh_

The scikit-fem mesh of the points and cells, a MeshTri in 2D or a MeshTet in 3D, or None for a complex that derives from a space.

cells_

The node indices of every triangle or tetrahedron of a mesh, one column per cell, and empty for a complex that derives from a space.

boundary_nodes_

The indices of the nodes on the boundary of a mesh, and empty for a complex that derives from a space.

incidences_

The oriented incidence of every degree k as a SciPy CSR array with entries of 1 and -1, with one row per cell of degree k + 1 and one column per cell of degree k, so incidences_[k + 1] @ incidences_[k] is 0.

cofaces_

The cells of degree k + 1 that contain every cell of degree k, with one row per cell, padded with the number of cells of degree k + 1.

orientations_

The sign of every coface of cofaces_ relative to its cell, padded with 0.

boundaries_

The edges around every face in the cyclic order of its nodes, from the edge that leaves its first node, with one row per face, padded with -1.

boundary_signs_

The sign of the traversal of every edge of boundaries_, 1 along its orientation and -1 against it, padded with 0, so the path-ordered product of link matrices along a row is the holonomy of the face.

stars_

The diagonal of the Hodge star of every degree, the ratio of dual to primal cell volumes on a lattice and 1 on a network.

link_axes_

The axis of every link of a lattice, empty on a network.

face_planes_

The two axes of the plane of every plaquette of a lattice, empty on a network.

Raises:

Type Description
SpaceError

A face uses a pair of nodes that the graph does not join, the network has a loop, or the lattice is not square.

ValidationError

Neither or both of a space and a mesh are given, or the points or cells of a mesh do not fit.

See Also

NetworkSpace: Knows nodes and edges, with no faces and no directions. LatticeSpace: Places members on a grid of sites, from which a complex can derive.

Examples:

>>> from skcomplex.core.components.spaces import CellComplexSpace, LatticeSpace
>>> square = CellComplexSpace(LatticeSpace((8, 8))).prepare()
>>> [matrix.shape for matrix in square.incidences_]
[(128, 64), (64, 128)]
Source code in src/skcomplex/core/components/spaces/_cell_complex.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def __init__(
    self,
    space: LatticeSpace | NetworkSpace | None = None,
    *,
    points: npt.ArrayLike | None = None,
    cells: npt.ArrayLike | None = None,
    faces: str | Sequence[Sequence[object]] | None = None,
    dimension: int = LOWEST_DIMENSION,
    boundary: Mapping[str, object] | None = None,
    label: str = 'space',
) -> None:
    super().__init__(nx.Graph(), label=label)
    self.space = space
    self.points = points
    self.cells = cells
    self.faces = faces
    self.dimension = dimension
    self.boundary = boundary

CofaceNeighborhood(*, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the cells of the next degree that contain a cell.

On a CellComplexSpace a law that reads it sees the faces around a link, or the links that meet at a site, each with weight one. Inside a sum over it, exterior_derivative of a value on links adds the values around each face with their directions, such as the total angle around a square of a lattice. Gauge theories sum the squares around each link of a lattice, and flows on a mesh read the faces around each edge.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'
See Also

AdjacencyNeighborhood: Reads the nodes joined by edges, cells of the same kind. CellComplexSpace: Holds the links and faces it reads.

Examples:

>>> from skcomplex.core.components.spaces import CofaceNeighborhood
>>> CofaceNeighborhood(label='plaquettes').prepare().label
'plaquettes'
Source code in src/skcomplex/core/components/spaces/_coface.py
33
34
def __init__(self, *, label: str = 'neighborhood') -> None:
    super().__init__(label)

ContinuousSpace(extent=(), *, n_dim=None, boundary='open', regions=None, label='space')

Bases: BaseSpace

A space of real positions, a box with a boundary or the whole of R^d.

Members move to any real position, and a value named after an axis is the position along it, such as x in Element('walker', values={'x': 0.0}, space=ContinuousSpace(n_dim=1)). The axes are x, y, and z, or x0, x1, and so on beyond three dimensions. A box runs from 0 to extent along every dimension, and without an extent the space has no edges. The space has no sites, since the positions are values of the members. A plane can hold named regions of a map, which agents start in, move to, and ask about. Atoms move in the box of a gas, birds fly in a flock, pedestrians walk through a station, and households live in the districts of a city.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
extent Sequence[float]

The side of the box along every dimension, or empty for an unbounded space.

()
n_dim int | None

The number of dimensions of an unbounded space, or None for the number of sides of the box.

None
boundary str

What happens at the walls of the box. Positions stay as they are with 'open'. Opposite sides join with 'periodic', and distances use the nearest copy across a wall. Positions mirror back into the box with 'reflecting', and the velocity across the wall reverses.

'open'
regions Mapping[str, Polygon | Sequence[Polygon]] | None

The polygon of every region, or the polygons of every layer of regions, by name, or None for no regions. A region is one polygon, such as {'tract_1': polygon}, and a layer is a list, such as {'parks': [first, second]}. Agents whose value region names a region start at a random point inside it.

None
label str

The name of the space in its system, such as 'grid'.

'space'

Attributes:

Name Type Description
extent_

The side of the box along every dimension, or () for an unbounded space.

axes_

The names of the axes, such as ('x', 'y') in two dimensions.

regions_

The Shapely STRtree of the polygons of every region or layer of regions by name, one polygon for a region.

Raises:

Type Description
SpaceError

A region is not a valid polygon in two dimensions, or the space has regions and other than two dimensions, raised by prepare.

See Also

LatticeSpace: Places members on fixed sites of a grid. RadiusNeighborhood: Picks the members within a distance in the box. NearestNeighborhood: Picks the closest members in the box.

Examples:

>>> from skcomplex.core.components.spaces import ContinuousSpace
>>> space = ContinuousSpace(extent=(10.0, 5.0), boundary='periodic').prepare()
>>> space.extent_, space.axes_
((10.0, 5.0), ('x', 'y'))
Source code in src/skcomplex/core/components/spaces/_continuous.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    extent: Sequence[float] = (),
    *,
    n_dim: int | None = None,
    boundary: str = 'open',
    regions: Mapping[str, Polygon | Sequence[Polygon]] | None = None,
    label: str = 'space',
) -> None:
    super().__init__(label)
    self.extent = extent
    self.n_dim = n_dim
    self.boundary = boundary
    self.regions = regions

DelaunayNeighborhood(*, center=False, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the members joined by edges of a Delaunay triangulation.

In a continuous space two members are neighbours when the regions of the plane closer to each of them than to any other member touch, whatever their distance. The neighbours are found again at every step, so they follow moving members, and in a periodic box they connect across the walls. A group too small to triangulate gives every member all the others. Cells in a tissue push on the cells that touch them, bubbles share walls in a foam, and animals guard their territories against the animals next door.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
center bool

Whether a member is its own neighbour.

False
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'
See Also

RadiusNeighborhood: Picks every member within a distance. NearestNeighborhood: Picks a fixed number of the closest members.

Examples:

>>> from skcomplex.core.components.spaces import DelaunayNeighborhood
>>> DelaunayNeighborhood(center=True).prepare().center
True
Source code in src/skcomplex/core/components/spaces/_delaunay.py
37
38
39
def __init__(self, *, center: bool = False, label: str = 'neighborhood') -> None:
    super().__init__(label)
    self.center = center

FiniteVolumeSpec(limiter='minmod', riemann='rusanov', speed=None) dataclass

Bases: BaseSpec

A spec of how a finite-volume field moves its values between cells.

On a lattice with discretization='finite-volume', the law u' = -divergence(flux) moves amounts of u between neighbouring cells, so the total stays the same. The spec says how: limiter rebuilds the value inside each cell from its neighbours, and riemann computes the amount that crosses each wall, which keeps a sudden jump sharp, such as LatticeSpace(100, discretization='finite-volume', scheme=FiniteVolumeSpec(limiter='van-leer')). Cars pile up into jams on a road, a gas forms shock waves, and the trees of a forest move along their growth curve.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
limiter str | None

The slope limiter of the MUSCL reconstruction, 'minmod', 'van-leer', or None for first order.

'minmod'
riemann str

The numerical flux, 'rusanov' or 'godunov', the exact solver for one state.

'rusanov'
speed Callable[..., object] | tuple[Callable[..., object], ...] | None

A function f(t, values) of the mapping from the name of every conserved state and parameter of the fluxes to its array over the cells, which returns the wave speed of the Rusanov flux, or one function per dimension. None takes the speeds from the eigenvalues of the flux Jacobians.

None

Raises:

Type Description
ValidationError

The limiter or the numerical flux is unknown, or a speed comes with the Godunov flux, raised when its field checks it.

See Also

LatticeSpace: Takes this spec as the scheme of a finite-volume lattice.

Examples:

>>> from skcomplex.core.components.spaces import FiniteVolumeSpec, LatticeSpace
>>> scheme = FiniteVolumeSpec(limiter='van-leer', riemann='godunov')
>>> LatticeSpace(100, discretization='finite-volume', scheme=scheme).prepare().scheme.limiter
'van-leer'

LatticeNeighborhood(offsets, *, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the ordered lattice offsets that a local rule reads.

Each offset steps from a site to one neighbour, such as (-1,) for the cell on the left, and the offset of zeros is the site itself. A local rule receives the values in the order of the offsets, so LatticeNeighborhood([(-1,), (0,), (1,)]) hands it a cell between its left and right neighbours. A cellular automaton reads a cell and its two neighbours, a river carries a pollutant from the cells upstream, and a queue of traffic reads the car ahead.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
offsets tuple[IntTuple, ...]

The offsets, one tuple of integers per neighbour, in the order rules receive their values.

required
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'

Attributes:

Name Type Description
offsets_

The offsets as tuples of integers.

See Also

RadiusNeighborhood: Builds its offsets from a radius and a metric. LatticeSpace: Holds the sites the offsets step between.

Examples:

>>> from skcomplex.core.components.spaces import LatticeNeighborhood
>>> LatticeNeighborhood([(-1,), (0,), (1,)]).prepare().offsets_
((-1,), (0,), (1,))
Source code in src/skcomplex/core/components/spaces/_lattice_neighborhood.py
49
50
51
def __init__(self, offsets: tuple[IntTuple, ...], *, label: str = 'neighborhood') -> None:
    super().__init__(label)
    self.offsets = offsets

LatticeSpace(shape, *, geometry='square', boundary='periodic', discretization='finite-difference', scheme=None, symmetry=None, fill=0.0, spacing=1.0, metric=None, capacity=None, label='space')

Bases: BaseSpace

A space of a box of Z^d, or of the triangular lattice in two dimensions.

It places the members of a group on a grid of sites with integer coordinates, one member per site, such as the 200 cells of LatticeSpace((10, 20)). The sites are numbered row by row, so site (i, j) of a grid of shape (n, m) is member i * m + j. A triangular site (i, j) sits at (j + i / 2, i sqrt(3) / 2), so it has six neighbours at distance one. A field on the grid turns operators such as laplacian into sums over neighbouring sites. The spins of a magnet sit on a square grid, the trees of a forest fire on a map of cells, and the temperature of a rod on a row of points.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
shape Sequence[int] | int

The number of sites along every dimension.

required
geometry str

'square' for the integer lattice or 'triangular' for the triangular lattice in two dimensions.

'square'
boundary str | Mapping[str, object]

The edges of the lattice, or the edge of each state of a field on it by name.

  • 'periodic': opposite edges join, as on a ring or a torus.
  • 'fixed': the value fill is read outside the box.
  • 'reflecting': the mirror image of the box is read outside it.
  • A mapping such as {'T': ('fixed', 0.0), 'c': 'zero-flux'}: each named state of a field takes 'periodic', 'zero-flux' for an insulated wall, or ('fixed', value) for a wall held at a value, and the other states and the neighbours of members join periodically.
'periodic'
discretization str

How the operators of a field on the lattice, such as laplacian, become numbers.

  • 'finite-difference': stencils of neighbouring sites.
  • 'spectral': products of Fourier modes on a periodic lattice, with the two-thirds rule, which drops the highest modes so that their products create no false ones.
  • 'finite-volume': averages over cells, so a rate -divergence(flux) of a state is a conservation law solved with the scheme of scheme.
'finite-difference'
scheme FiniteVolumeSpec | None

The limiter, numerical flux, and wave speed of a finite-volume field, or None for the minmod limiter and the Rusanov flux.

None
symmetry Mapping[str, Sequence[object]] | None

The parity of each state of a field by name along every axis of a periodic lattice, 'odd', 'even', or None, which the rates keep exactly, such as {'T': ('even', 'odd')}. A lattice twice as long as a domain along an axis, with states odd or even about its middle, stands for walls there, such as the free-slip walls of convection. A vector or tensor state takes one such sequence for its first component, or one sequence per component.

None
fill float

The value read outside a lattice with fixed edges.

0.0
spacing float | Sequence[float]

The distance between neighbouring sites, or one distance per dimension.

1.0
metric str | None

The metric of the ball of radius 1 that agents query. It is 'chebyshev' for the 8 surrounding cells of a two-dimensional square lattice or 'manhattan' for the 4 adjacent ones, and 'hexagonal' for the six neighbours on a triangular lattice. None means 'chebyshev' on a square lattice and 'hexagonal' on a triangular one.

None
capacity int | None

The largest number of agents in a cell, or None for no limit.

None
label str

The name of the space in its system, such as 'grid'.

'space'

Attributes:

Name Type Description
axes_

The names of the coordinates of a cell, such as ('x', 'y') in two dimensions, which an agent's values of the same names place it at.

spacings_

The distance between neighbouring sites along every dimension.

metric_

The metric of the ball agents query.

See Also

NetworkSpace: Places members on the nodes of any graph. ContinuousSpace: Lets members move to any real position. PhaseSpace: Adds axes such as velocity to a lattice of positions.

Examples:

>>> from skcomplex.core.components.spaces import LatticeSpace
>>> space = LatticeSpace((10, 20)).prepare()
>>> space.size_, space.n_dim_, space.shape_
(200, 2, (10, 20))
Source code in src/skcomplex/core/components/spaces/_lattice.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def __init__(
    self,
    shape: Sequence[int] | int,
    *,
    geometry: str = 'square',
    boundary: str | Mapping[str, object] = 'periodic',
    discretization: str = 'finite-difference',
    scheme: FiniteVolumeSpec | None = None,
    symmetry: Mapping[str, Sequence[object]] | None = None,
    fill: float = 0.0,
    spacing: float | Sequence[float] = 1.0,
    metric: str | None = None,
    capacity: int | None = None,
    label: str = 'space',
) -> None:
    super().__init__(label)
    self.shape = shape
    self.geometry = geometry
    self.boundary = boundary
    self.discretization = discretization
    self.scheme = scheme
    self.symmetry = symmetry
    self.fill = fill
    self.spacing = spacing
    self.metric = metric
    self.capacity = capacity

LayerSpec(label, graph) dataclass

Bases: BaseSpec

A spec of a named relation over the nodes of a network space.

It holds a second set of edges over the same people or places as the network, such as who works with whom in LayerSpec('work', nx.path_graph(3)). Interactions and groups on edges name the layer they use, and a law reads the neighbours along it with AdjacencyNeighborhood(layer='work'). People meet at home and at work in an epidemic, banks lend and trade on separate networks, and cities are joined by roads and by flights.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
label str

The name of the layer, unique in its network space.

required
graph Graph

The NetworkX graph of the relation, over the nodes of the network space.

required
See Also

NetworkSpace: Holds the layers over its nodes. AdjacencyNeighborhood: Reads the neighbours along one layer.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.components.spaces import LayerSpec, NetworkSpace
>>> space = NetworkSpace(nx.path_graph(3), layers=[LayerSpec('work', nx.complete_graph(3))]).prepare()
>>> space.graphs_['work'].number_of_edges()
3

NearestNeighborhood(k, *, center=False, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the k members of a continuous space closest to a member.

A law that reads it sees the k members closest to a member, however far they are, such as the seven closest birds in NearestNeighborhood(7). Distances run between the positions of the members, across the walls of a periodic box, and a group of at most k other members gives every member all the others. Starlings follow their seven nearest neighbours, fish school by their closest neighbours, and the robots of a swarm align with the nearest robots.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
k int

The number of neighbours.

required
center bool

Whether a member is its own neighbour, besides its k nearest others.

False
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'
See Also

RadiusNeighborhood: Picks every member within a distance, however many. DelaunayNeighborhood: Picks the members that touch.

Examples:

>>> from skcomplex.core.components.spaces import NearestNeighborhood
>>> NearestNeighborhood(7).prepare().k
7
Source code in src/skcomplex/core/components/spaces/_nearest.py
41
42
43
44
def __init__(self, k: int, *, center: bool = False, label: str = 'neighborhood') -> None:
    super().__init__(label)
    self.k = k
    self.center = center

NetworkSpace(graph, *, layers=(), capacity=None, fill=0.0, hyperedges=(), label='space')

Bases: BaseSpace

A space of a graph whose nodes the members occupy, with layers of relations.

It places one member on every node of a NetworkX graph, in the order of graph.nodes, and the neighbours of a node are the nodes its edges reach, such as the 100 people of NetworkSpace(nx.erdos_renyi_graph(100, 0.1, seed=0)). Edges are numbered in the order of graph.edges, and on an undirected graph an edge starts at the end that comes first. Named layers add more edges over the same nodes, such as work and home, and hyperedges join more than two nodes at once. A disease spreads on a contact network, generators keep in step on a power grid, banks lend to each other, and neurons fire along their synapses.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
graph Graph

The NetworkX graph, the default layer.

required
layers Sequence[LayerSpec]

The named layers over the nodes of the graph.

()
capacity int | None

The largest number of agents on a node, or None for no limit.

None
fill float

The value lattice rules read in the padding slots of nodes with fewer neighbours than the largest degree.

0.0
hyperedges Sequence[Sequence[object]] | Hypergraph

The hyperedges of the network, which hyperedge interactions and groups on hyperedges read: sequences of at least two nodes, an XGI Hypergraph, or an XGI SimplicialComplex, whose faces of at least two nodes are its hyperedges. The members of an XGI hyperedge follow the order of the nodes of the graph.

()
label str

The name of the space in its system, such as 'grid'.

'space'

Attributes:

Name Type Description
axes_

The name of the one coordinate of the network, ('node',), so an agent's value node places it at that node.

graphs_

The graph of every layer by label, None first for the graph of the network.

edges_

The source and target node index of every edge of every layer by label, in the order of graph.edges.

adjacency_

The neighbours of every node of every layer by label in compressed sparse row form: the start of the neighbours of every node with the number of entries last, the sorted neighbours of every node in turn, the successors on a directed graph, and the edge that joins every node to every neighbour.

hyperedges_

The node index of every member of every hyperedge, in the order of the hyperedges.

incidence_

The sparse incidence matrix of the hyperedges, with one row per node and one column per hyperedge.

memberships_

The indices of the hyperedges every node belongs to, in increasing order.

See Also

LatticeSpace: Places members on a regular grid. LayerSpec: Adds a named layer of edges over the nodes. CellComplexSpace: Adds faces and directions to the nodes and edges.

Examples:

>>> import networkx as nx
>>> from skcomplex.core.components.spaces import NetworkSpace
>>> space = NetworkSpace(nx.path_graph(3)).prepare()
>>> space.size_, [edge.tolist() for edge in space.edges_[None]]
(3, [[0, 1], [1, 2]])
Source code in src/skcomplex/core/components/spaces/_network.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    graph: nx.Graph,
    *,
    layers: Sequence[LayerSpec] = (),
    capacity: int | None = None,
    fill: float = 0.0,
    hyperedges: Sequence[Sequence[object]] | xgi.Hypergraph = (),
    label: str = 'space',
) -> None:
    super().__init__(label)
    self.graph = graph
    self.layers = layers
    self.capacity = capacity
    self.fill = fill
    self.hyperedges = hyperedges

PhaseSpace(position, axes, *, limit=DEFAULT_LIMIT, label='space')

Bases: LatticeSpace

A space of positions combined with extra axes, such as velocity.

Each site pairs one position with one cell of every extra axis, so a density can vary over position and a trait together, such as the 64 positions and 128 velocities of PhaseSpace(LatticeSpace(64), [AxisSpec('v', 128, -6.0, 6.0)]). The position axes come first and keep the walls of the lattice, and a field on the space takes the discretization of the lattice. Gas molecules are followed over position and velocity, bacteria over position and swimming direction, and cells over position and age.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
position LatticeSpace

The lattice of the positions.

required
axes Sequence[AxisSpec]

The class axes.

required
limit int

The largest number of sites of the space.

DEFAULT_LIMIT
label str

The name of the space in its system, such as 'grid'.

'space'

Attributes:

Name Type Description
coordinates_

The coordinate of every cell of every class axis, at the cell centres, by the name of the axis.

position_axes_

The indices of the position axes among the axes of the product.

class_axes_

The index of every class axis among the axes of the product, by its name.

position_size_

The number of positions.

axes_periodic_

Whether the edges of every axis of the product are joined.

Raises:

Type Description
PhaseSpaceTooLargeError

The product has more sites than the limit.

See Also

LatticeSpace: Holds the positions alone. AxisSpec: Cuts the range of one extra axis into cells.

Examples:

>>> from skcomplex.core.components.spaces import AxisSpec, LatticeSpace, PhaseSpace
>>> space = PhaseSpace(LatticeSpace(64), [AxisSpec('v', 128, -6.0, 6.0)]).prepare()
>>> space.size_, space.shape_
(8192, (64, 128))
Source code in src/skcomplex/core/components/spaces/_phase.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    position: LatticeSpace,
    axes: Sequence[AxisSpec],
    *,
    limit: int = DEFAULT_LIMIT,
    label: str = 'space',
) -> None:
    super().__init__(
        position.shape,
        geometry=position.geometry,
        boundary=position.boundary,
        discretization=position.discretization,
        scheme=position.scheme,
        symmetry=position.symmetry,
        fill=position.fill,
        spacing=position.spacing,
        label=label,
    )
    self.position = position
    self.axes = axes
    self.limit = limit

RadiusNeighborhood(radius, *, metric='euclidean', angle=math.pi, direction=None, center=False, label='neighborhood')

Bases: BaseNeighborhood

A neighbourhood of the members within a distance under a metric.

A law that reads it sees every member within radius of a member, so the number of neighbours varies, such as the eight cells around a cell in RadiusNeighborhood(1, metric='chebyshev'). In a continuous space the distance runs between positions, across the walls of a periodic box, and an angle below pi keeps only the members in a cone ahead of the member. On a lattice the neighbours are the offsets within the radius under the metric, and with center the site itself comes first. Birds align with the flockmates they can see, atoms push on the atoms within a cutoff, a sandpile topples grains onto its four neighbours, and a cell of the Game of Life counts its eight.

Read more in the user guide, under Spaces.

Parameters:

Name Type Description Default
radius float

The largest distance of a neighbour.

required
metric str

How a lattice measures the length of an offset. With 'euclidean' it is the straight length. With 'chebyshev' it is the largest coordinate, so radius 1 in two dimensions gives the 8 cells around a cell. With 'manhattan' it is the sum of the coordinates, so radius 1 gives the 4 cells beside it. With 'hexagonal' it is max(|a|, |b|, |a + b|) on a triangular lattice, and the offsets come ring by ring, counterclockwise. A continuous space measures straight lengths.

'euclidean'
angle float

The half-angle of the cone, between 0 and pi, which is the whole disk. A lattice takes the whole disk.

pi
direction str | None

The name of the state that holds the direction, or None for the velocity, the vector state declared as the rate of the position. Only a cone, with an angle below pi, reads it.

None
center bool

Whether a member is its own neighbour, the first one on a lattice.

False
label str

The name of the neighbourhood, such as 'moore'.

'neighborhood'
See Also

NearestNeighborhood: Picks a fixed number of the closest members. LatticeNeighborhood: Takes its offsets one by one. DelaunayNeighborhood: Picks the members that touch, whatever the distance.

Examples:

>>> import math
>>> from skcomplex.core.components.spaces import RadiusNeighborhood
>>> RadiusNeighborhood(1.0, angle=math.pi / 2).prepare().angle
1.5707963267948966
Source code in src/skcomplex/core/components/spaces/_radius.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def __init__(
    self,
    radius: float,
    *,
    metric: str = 'euclidean',
    angle: float = math.pi,
    direction: str | None = None,
    center: bool = False,
    label: str = 'neighborhood',
) -> None:
    super().__init__(label)
    self.radius = radius
    self.metric = metric
    self.angle = angle
    self.direction = direction
    self.center = center

ScheduleSpec() dataclass

Bases: BaseSpec

An abstract spec of the order in which updates run within one step.

A subclass orders the updates of a step of discrete time, such as the phases in which agents first move and then trade. It is a frozen dataclass of its own fields that overrides _check, and by default it accepts any schedule. Traders quote and then match orders, animals forage and then breed, and voters listen and then decide.

Read more in the user guide, under Spaces.

See Also

BaseSpace: Holds the members whose updates the schedule orders.

Examples:

>>> from skcomplex.core.base import BaseSpec
>>> from skcomplex.core.components.spaces import ScheduleSpec
>>> isinstance(ScheduleSpec(), BaseSpec)
True