Skip to content

Centralities, assortativity, communities, and motifs

A recorded network with centralities, degree mixing, communities, and motifs.

  • Class: NetworkStructureAnalysisSystem
  • Import: from skcomplex.systems.mathematics.networks import NetworkStructureAnalysisSystem
  • Field: mathematics/networks
  • Topics: network, centrality, communities, motifs, assortativity
  • References:
    • Newman 2010
    • Milo et al. 2002
    • Blondel et al. 2008
    • Bertin 2021

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 NetworkStructureAnalysisSystem

trajectory = NetworkStructureAnalysisSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
graph None
reference 'block'
null_samples 10
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 NetworkStructureAnalysisSystem(BaseSystem):
    """A recorded network with centralities, degree mixing, communities, and motifs.

    The motifs are measured by the triangle z-score.

    Every node is an agent that carries its degree, clustering, betweenness, and the community found by Louvain
    modularity maximization. The observables report the clustering, the mean path length of the largest component, the
    degree assortativity, the modularity, the agreement of the communities with a reference partition, and the z-score
    of triangles against degree-preserving edge switches. The system has the node group `nodes` and the network measures
    `measures`.

    Args:
        graph:
            The undirected NetworkX graph, or `None` for a stochastic block system of 4 blocks of 100 nodes with mean
            in-block degree 16 and out-block degree 2.

        reference:
            The node attribute that holds the reference partition, such as `'block'` of a stochastic block system or
            `'club'` of Zachary's karate club, or `None`. The agreement is reported only when every node has it.

        null_samples:
            The number of edge-switched graphs of the triangle z-score, which is reported only when positive.

        random_state:
            The seed of the block system, the community detection, and the null graphs.

        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.

    Examples:
        >>> import networkx as nx
        >>> from skcomplex.systems.mathematics.networks import NetworkStructureAnalysisSystem
        >>> karate = NetworkStructureAnalysisSystem(nx.karate_club_graph(), reference='club', null_samples=0)
        >>> karate.prepare().system_.elements[0].degree.size
        34
    """

    field = 'mathematics/networks'
    topics = ('network', 'centrality', 'communities', 'motifs', 'assortativity')
    references = ('Newman 2010', 'Milo et al. 2002', 'Blondel et al. 2008', 'Bertin 2021')
    until = 1
    dt = 1
    observables = (
        Observable('clustering', group='nodes', variable='clustering', reduce='mean'),
        Observable('path_length', _get_path_length),
        Observable('assortativity', _get_assortativity),
        Observable('modularity', _get_modularity),
        Observable('agreement', _get_agreement),
        Observable('triangle_zscore', _get_triangle_zscore),
    )

    def __init__(
        self,
        graph: nx.Graph | None = None,
        *,
        reference: str | None = 'block',
        null_samples: int = 10,
        random_state: int | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.graph = graph
        self.reference = reference
        self.null_samples = null_samples
        self.random_state = random_state

    @staticmethod
    def _get_planted_partition(random_state: int | None) -> nx.Graph:
        """Return a stochastic block graph of 4 blocks of 100 nodes.

        The mean degree is 16 in a block and 2 out of it.
        """
        inside = IN_DEGREE / (BLOCK_SIZE - 1)
        outside = OUT_DEGREE / ((BLOCKS - 1) * BLOCK_SIZE)
        probabilities = [[inside if row == column else outside for column in range(BLOCKS)] for row in range(BLOCKS)]
        return nx.stochastic_block_model([BLOCK_SIZE] * BLOCKS, probabilities, seed=random_state)

    @staticmethod
    def _get_reference(graph: nx.Graph, attribute: str | None) -> list[object] | None:
        """Return the reference community of every node from an attribute.

        The community is `None` when a node lacks the attribute.
        """
        if attribute is None:
            return None
        values = nx.get_node_attributes(graph, attribute)
        return [values[node] for node in graph.nodes()] if len(values) == graph.number_of_nodes() else None

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Return a recorded network with centralities, mixing, communities, and motifs.

        The mixing is degree mixing, and the motifs are measured by the triangle z-score.
        """
        super()._prepare(context)
        network = self._get_planted_partition(self.random_state) if self.graph is None else self.graph
        found = network_measures(
            network,
            kind='communities',
            reference=self._get_reference(network, self.reference),
            random_state=self.random_state,
        )
        summary = network_measures(network)
        clustering = nx.clustering(network)
        centrality = network_measures(network, kind='centrality', measure='betweenness').centrality
        assortativity = network_measures(network, kind='assortativity').assortativity
        labels, modularity, path_length = found.labels, found.modularity, summary.path_length
        if labels is None or modularity is None or path_length is None or centrality is None or assortativity is None:
            error_msg = 'The network measures miss the communities, the summary, the centrality, or the assortativity.'
            raise AnalysisError(error_msg)
        betweenness = centrality[0]
        nodes = NetworkNodeElement(
            'nodes',
            degree=np.asarray([network.degree(node) for node in network], dtype=float),
            clustering=np.asarray([clustering[node] for node in network], dtype=float),
            betweenness=np.asarray([betweenness[node] for node in network], dtype=float),
            community=labels[0].astype(float),
            space=NetworkSpace(network),
        )
        zscore = 0.0
        if self.null_samples:
            scores = motifs(
                network,
                kind='z-scores',
                samples=self.null_samples,
                random_state=self.random_state,
            ).z_scores
            zscore = 0.0 if scores is None else scores[0]['triangle']
        measures = NetworkMeasuresElement(
            'measures',
            path_length=float(path_length[0]),
            assortativity=float(assortativity[0]),
            modularity=float(modularity[0]),
            agreement=0.0 if found.agreement is None else float(found.agreement[0]),
            triangle_zscore=zscore,
        )
        self.system_ = System(self.label, elements=[nodes, measures])

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • NetworkNodeElement, from Element
  • NetworkMeasuresElement, from Element
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

class NetworkMeasuresElement(Element):
    """Measures of a whole network, which the observables of a system report.

    Args:
        label:
            The label of the element.

        path_length:
            The mean shortest path length of the largest component.

        assortativity:
            The degree assortativity.

        modularity:
            The modularity of the communities found.

        agreement:
            The agreement of the communities found with a reference partition.

        triangle_zscore:
            The z-score of the number of triangles against degree-preserving edge switches.

    Examples:
        >>> from skcomplex.systems.mathematics.networks import NetworkMeasuresElement
        >>> NetworkMeasuresElement('measures', modularity=0.4).modularity
        0.4
    """

    def __init__(
        self,
        label: str,
        *,
        path_length: float = 0.0,
        assortativity: float = 0.0,
        modularity: float = 0.0,
        agreement: float = 0.0,
        triangle_zscore: float = 0.0,
    ) -> None:
        super().__init__(label)
        self.path_length = path_length
        self.assortativity = assortativity
        self.modularity = modularity
        self.agreement = agreement
        self.triangle_zscore = triangle_zscore