Configuration model with stub matching and rewiring
The configuration model.
- Class:
ConfigurationModelSystem - Import:
from skcomplex.systems.mathematics.networks import ConfigurationModelSystem - Field:
mathematics/networks - Topics:
network,configuration model,random graph,degree sequence,friendship paradox - References:
- Molloy and Reed 1995
- Jensen 2023
- Thurner et al. 2018
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.mathematics.networks import ConfigurationModelSystem
trajectory = ConfigurationModelSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
degrees |
None |
n_nodes |
1000 |
exponent |
2.5 |
min_degree |
2 |
simple |
True |
random_state |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | any |
| Space | network |
| Laws | any |
| Randomness | deterministic |
| Domains | any |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class ConfigurationModelSystem(BaseSystem):
"""The configuration model.
It is the maximally random network of a given degree sequence.
Every node gets as many half-links as its degree, and pairs of half-links drawn uniformly at random become links
(Jensen 2023, section 8.5.1, and Thurner et al. 2018, section 4.5.1). Without a degree sequence the degrees are
drawn from the power law `P(k) ~ k^-exponent` for `k >= min_degree`, cut at `sqrt(n_nodes)`, and one half-link is
added to a random node when their sum is odd. The pairing leaves self-loops and multilinks, which the rewiring of
Thurner et al. removes while it keeps every degree. A neighbour has the mean degree `<k²> / <k>`, above the mean
degree, the friendship paradox. The system has the group `nodes` and their states `degree` and `clustering`.
Args:
degrees:
The degree of every node, or `None` for degrees drawn from the power law.
n_nodes:
The number of nodes of the drawn degrees.
exponent:
The exponent of the power law of the drawn degrees.
min_degree:
The smallest drawn degree.
simple:
Whether self-loops and multilinks are rewired away, or dropped, which lowers some degrees.
random_state:
The seed or generator of the degrees, the pairing, and the rewiring.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Raises:
ValidationError:
The degree sum of a given sequence is odd, or rewiring cannot make the graph simple.
Examples:
>>> from skcomplex.systems.mathematics.networks import ConfigurationModelSystem
>>> system = ConfigurationModelSystem([3, 3, 2, 2, 2]).prepare().system_
>>> system.elements[0].degree.tolist()
[3.0, 3.0, 2.0, 2.0, 2.0]
"""
field = 'mathematics/networks'
topics = ('network', 'configuration model', 'random graph', 'degree sequence', 'friendship paradox')
references = ('Molloy and Reed 1995', 'Jensen 2023', 'Thurner et al. 2018')
until = 1
dt = 1
def __init__(
self,
degrees: Sequence[int] | None = None,
*,
n_nodes: int = 1000,
exponent: float = 2.5,
min_degree: int = 2,
simple: bool = True,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.degrees = degrees
self.n_nodes = n_nodes
self.exponent = exponent
self.min_degree = min_degree
self.simple = simple
self.random_state = random_state
@staticmethod
def _get_matched_stubs(degrees: npt.NDArray[np.int64], rng: np.random.Generator) -> list[tuple[int, int]]:
"""Return the links of a uniformly random pairing of the half-links of the nodes.
The links may hold loops and multilinks.
"""
stubs = rng.permutation(np.repeat(np.arange(degrees.size), degrees))
return [(int(first), int(second)) for first, second in stubs.reshape(-1, 2)]
@staticmethod
def _get_simple_links(links: list[tuple[int, int]], rng: np.random.Generator) -> list[tuple[int, int]]:
"""Return the links rewired until no self-loop or multilink is left.
The rewiring keeps every degree.
A self-loop or a repeated link and a link drawn at random are cut and their ends glued crosswise, as in the
rewiring of Thurner et al. (2018, section 4.5.1.1).
"""
links = [(min(link), max(link)) for link in links]
for _ in range(100 * len(links)):
seen: set[tuple[int, int]] = set()
bad = []
for index, link in enumerate(links):
if link[0] == link[1] or link in seen:
bad.append(index)
seen.add(link)
if not bad:
return links
first = bad[int(rng.integers(len(bad)))]
second = int(rng.integers(len(links)))
(a, b), (c, d) = links[first], links[second]
crossed = [(min(a, c), max(a, c)), (min(b, d), max(b, d))]
if first != second and all(x != y and (x, y) not in seen for x, y in crossed):
links[first], links[second] = crossed[0], crossed[1]
error_msg = 'The degree sequence admits no simple graph reachable by rewiring. Give a sparser degree sequence.'
raise ValidationError(error_msg)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the network and its nodes."""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
if self.degrees is None:
support = np.arange(self.min_degree, max(self.min_degree, int(np.sqrt(self.n_nodes))) + 1)
weights = support.astype(float) ** -self.exponent
drawn = rng.choice(support, size=self.n_nodes, p=weights / weights.sum())
drawn[int(rng.integers(self.n_nodes))] += int(drawn.sum() % 2)
else:
drawn = np.asarray(self.degrees, dtype=np.int64)
if drawn.sum() % 2:
error_msg = f'The degrees sum to {int(drawn.sum())}. Give a degree sequence with an even sum.'
raise ValidationError(error_msg)
links = self._get_matched_stubs(drawn, rng)
links = self._get_simple_links(links, rng) if self.simple else [link for link in links if link[0] != link[1]]
graph = nx.Graph()
graph.add_nodes_from(range(drawn.size))
graph.add_edges_from(links)
self.system_ = KroneckerGraphSystem._get_static_system(self.label, graph)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
NetworkNodeElement, fromElement
class NetworkNodeElement(Element):
"""Nodes of a network, each with its degree, clustering, betweenness, and community.
Args:
label:
The label of the nodes.
degree:
The degree of every node, one per node or shared.
clustering:
The clustering coefficient of every node, one per node or shared.
betweenness:
The normalized betweenness centrality of every node, one per node or shared.
community:
The index of the community of every node, one per node or shared.
size:
The number of nodes, or `None` for one.
space:
The network with one node per site, or `None`.
Examples:
>>> from skcomplex.systems.mathematics.networks import NetworkNodeElement
>>> NetworkNodeElement('nodes', degree=[1.0, 2.0, 1.0], size=3).degree
[1.0, 2.0, 1.0]
"""
visual = VisualSpec('agents', {'color_by': 'community'})
def __init__(
self,
label: str,
*,
degree: Annotated[object, NN] = 0.0,
clustering: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
betweenness: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
community: Annotated[object, NN] = 0.0,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, size=size, space=space)
self.degree = degree
self.clustering = clustering
self.betweenness = betweenness
self.community = community