Network Core

driada.network.net_base.check_matrix_type(mode, is_directed)[source]

Validate matrix type for directed/undirected networks.

Ensures the requested matrix type is compatible with the network’s directionality.

Parameters:
  • mode (str) – Matrix type to validate. Options include: - ‘adj’: adjacency matrix - ‘lap’: Laplacian matrix - ‘nlap’: normalized Laplacian - ‘trans’: transition matrix - ‘rwlap’: random walk Laplacian - ‘lap_out’, ‘lap_in’: directed Laplacians

  • is_directed (bool) – Whether the network is directed.

Raises:

ValueError – If mode is not recognized or incompatible with network type.

Notes

Directed networks support: ‘adj’, ‘lap_out’, ‘lap_in’. Undirected networks support: ‘adj’, ‘trans’, ‘lap’, ‘nlap’, ‘rwlap’.

driada.network.net_base.check_adjacency(a)[source]

Validate that matrix is square (valid adjacency matrix).

Parameters:

a (numpy.ndarray or scipy.sparse matrix) – Matrix to validate.

Raises:

ValueError – If matrix is not square.

Notes

This function only checks if the matrix is square. It does not validate other adjacency matrix properties like non-negativity or symmetry.

driada.network.net_base.check_directed(directed, real_world)[source]

Validate directionality parameter.

Parameters:
  • directed (float) – Directionality value (0.0 for undirected, 1.0 for directed, fractional for partially directed).

  • real_world (bool) – Whether this is a real-world network (must be fully directed or undirected).

Raises:

Exception – If directed value is invalid or fractional for real networks.

Notes

Real-world networks must have directed in {0, 1}. Synthetic networks can have 0 <= directed <= 1.

driada.network.net_base.check_weights_and_directions(a, weighted, directed)[source]

Verify adjacency matrix properties match specified parameters.

Checks if the actual matrix properties (weighted/directed) match the declared parameters.

Parameters:
  • a (scipy.sparse matrix or numpy.ndarray) – Adjacency matrix to check.

  • weighted (bool) – Whether the network is expected to be weighted.

  • directed (bool or float) – Whether the network is expected to be directed.

Raises:

ValueError – If actual matrix properties don’t match declared parameters.

Notes

  • Directed: matrix is not symmetric (A != A^T)

  • Weighted: matrix has non-binary values

  • For sparse matrices, checks are done without converting to dense

driada.network.net_base.calculate_directionality_fraction(adj)[source]

Calculate the fraction of directed edges in an adjacency matrix.

A fully symmetric matrix has directionality = 0.0 A fully asymmetric matrix has directionality = 1.0 A partially directed matrix has 0.0 < directionality < 1.0

Parameters:

adj (scipy.sparse matrix or numpy array) – Adjacency matrix. For weighted networks, edges are considered symmetric only if weights are equal.

Returns:

Fraction of directed edges (0.0 to 1.0)

Return type:

float

Notes

For weighted networks, this function correctly checks weight equality. An edge (i,j) with weight w1 and edge (j,i) with weight w2 are only considered symmetric if w1 == w2.

Uses vectorized sparse matrix operations instead of Python loops. For weighted networks, edges (i,j) and (j,i) are symmetric only if their weights are equal (checked via subtraction). Self-loops are ignored.

driada.network.net_base.select_construction_pipeline(a, graph)[source]

Select construction pipeline and determine directionality.

Determines whether to initialize from adjacency matrix or NetworkX graph, and calculates the fraction of directed edges for auto-detection of network directionality.

Parameters:
  • a (scipy.sparse matrix or None) – Adjacency matrix. If provided, graph must be None.

  • graph (networkx.Graph/DiGraph or None) – NetworkX graph object. If provided, a must be None.

Returns:

(pipeline, directed_fraction) where: - pipeline: ‘adj’ or ‘graph’ indicating initialization method - directed_fraction: float in [0.0, 1.0], fraction of asymmetric edges

Return type:

tuple

Raises:
  • ValueError – If both a and graph are None, or if both are provided.

  • TypeError – If graph is not a supported NetworkX type.

Notes

The directed_fraction is always calculated and never None. For undirected NetworkX graphs, it returns 0.0. For directed graphs and adjacency matrices, it calculates the actual fraction of asymmetric edges.

class driada.network.net_base.Network(adj=None, graph=None, preprocessing='giant_cc', name='', pos=None, verbose=False, create_nx_graph=True, node_attrs=None, logger=None, **network_args)[source]

Network analysis class with focus on spectral graph theory.

This class provides a comprehensive interface for analyzing networks using spectral methods. It supports both directed and undirected, weighted and unweighted networks, and can be initialized from adjacency matrices or NetworkX graphs.

Parameters:
  • adj (scipy.sparse matrix, optional) – Sparse adjacency matrix. Either adj or graph must be provided.

  • graph (networkx.Graph or networkx.DiGraph, optional) – NetworkX graph object. Either adj or graph must be provided.

  • preprocessing (str, default='giant_cc') – Preprocessing method to apply: - None: No preprocessing (may cause connectivity issues) - ‘remove_isolates’: Remove isolated nodes and self-loops - ‘giant_cc’: Extract giant connected component (undirected) - ‘giant_scc’: Extract giant strongly connected component (directed)

  • name (str, default='') – Name identifier for the network.

  • pos (dict, optional) – Node positions as {node: (x, y)} or {node: (x, y, z)}.

  • verbose (bool, default=False) – Whether to print progress messages.

  • create_nx_graph (bool, default=True) – Whether to create NetworkX graph from adjacency matrix. Set to False for large networks to save memory.

  • node_attrs (dict, optional) – Node attributes as {node: attribute_dict}.

  • logger (logging.Logger, optional) – Logger instance for debugging. If None, creates default logger.

  • **network_args (dict) – Additional network parameters: - directed : bool, optional (auto-detected if not specified) - weighted : bool, optional (auto-detected if not specified) - real_world : bool, default=True

adj

Adjacency matrix (always stored as sparse).

Type:

scipy.sparse.csr_matrix

graph

NetworkX graph object (None if create_nx_graph=False).

Type:

networkx.Graph or networkx.DiGraph or None

n

Number of nodes in the network.

Type:

int

n_cc

Number of connected components (set to 1 after giant_cc preprocessing).

Type:

int or None

n_scc

Number of strongly connected components (set to 1 after giant_scc).

Type:

int or None

directed

Whether the network is directed.

Type:

bool

weighted

Whether the network is weighted.

Type:

bool

real_world

Whether this is a real-world network (affects certain analyses).

Type:

bool

name

Network name identifier.

Type:

str

pos

Node positions if provided.

Type:

dict or None

node_attrs

Node attributes if provided.

Type:

dict or None

verbose

Verbosity flag.

Type:

bool

logger

Logger instance.

Type:

logging.Logger

init_method

Initialization method used (‘adj’ or ‘graph’).

Type:

str

network_params

Original network parameters passed to __init__.

Type:

dict

create_nx_graph

Whether NetworkX graph was created from adjacency matrix.

Type:

bool

outdeg

Out-degree sequence (automatically computed).

Type:

ndarray

indeg

In-degree sequence (automatically computed).

Type:

ndarray

deg

Total degree sequence - undirected view (automatically computed).

Type:

ndarray

scaled_outdeg

Out-degree normalized to [0, 1] (automatically computed).

Type:

ndarray

scaled_indeg

In-degree normalized to [0, 1] (automatically computed).

Type:

ndarray

lem_emb

Laplacian eigenmaps embedding if computed.

Type:

ndarray or None

estrada_communicability

Estrada communicability index if computed.

Type:

float or None

estrada_bipartivity

Estrada bipartivity index if computed.

Type:

float or None

_calculated_directionality

Fraction of directed edges detected during initialization (private).

Type:

float or None

_init_to_final_node_mapping

Mapping from initial to final node indices after preprocessing (private, only when using adjacency without creating graph).

Type:

dict or None

Dynamic Matrix Attributes
------------------------
For each matrix type in ['adj', 'trans', 'lap', 'nlap', 'rwlap'] (undirected)
or ['adj', 'lap_out', 'lap_in'] (directed), the following attributes are
dynamically created and initially set to None
{matrix_type}

The matrix itself (computed on demand).

Type:

scipy.sparse matrix or None

{matrix_type}_spectrum

Eigenvalues of the matrix.

Type:

ndarray or None

{matrix_type}_eigenvectors

Eigenvectors of the matrix.

Type:

ndarray or None

{matrix_type}_zvalues

IPR z-values for eigenvector localization.

Type:

ndarray or None

{matrix_type}_ipr

Inverse participation ratio values.

Type:

ndarray or None

is_connected()[source]

Check if the network is connected.

randomize(rmode='shuffle')[source]

Create randomized version preserving certain properties.

get_node_degrees()[source]

Calculate and store degree sequences.

get_degree_distr(mode='all')[source]

Get degree distribution statistics.

get_matrix(mode)[source]

Get or compute specified matrix type.

get_spectrum(mode)[source]

Get eigenvalues for specified matrix.

get_eigenvectors(mode)[source]

Get eigenvectors for specified matrix.

get_ipr(mode)[source]

Get inverse participation ratio for specified matrix.

get_z_values(mode)[source]

Get IPR z-values for specified matrix.

diagonalize(mode='lap', verbose=None)[source]

Compute eigendecomposition for specified matrix.

partial_diagonalize(spectrum_params)[source]

Compute partial eigendecomposition.

calculate_gromov_hyperbolicity(num_samples=100000, return_list=False)[source]

Calculate Gromov hyperbolicity of the network.

calculate_z_values(mode='lap')[source]

Calculate IPR z-values for eigenvector localization.

calculate_ipr(mode='adj')[source]

Calculate inverse participation ratio.

calculate_thermodynamic_entropy(tlist, verbose=False, norm=False)[source]

Calculate von Neumann entropy at different temperatures.

calculate_free_entropy(tlist, norm=False)[source]

Calculate free entropy.

calculate_q_entropy(q, tlist, norm=False)[source]

Calculate q-entropy (Tsallis entropy).

calculate_estrada_communicability()[source]

Calculate Estrada communicability index.

get_estrada_bipartivity_index()[source]

Calculate Estrada bipartivity index.

localization_signatures(mode='lap')[source]

Analyze eigenvector localization.

construct_lem_embedding(dim)[source]

Construct Laplacian eigenmaps embedding.

Notes

The class uses lazy evaluation for matrix computations - matrices and their spectral properties are only computed when first requested. The directionality is automatically detected if not specified, using a fractional approach that can identify partially directed networks.

The diagonalize method may raise exceptions if: - The network has isolated nodes when n_cc=1 is expected - The network has multiple components when only one is expected - Complex eigenvalues/eigenvectors are found for undirected networks

Degree sequences (outdeg, indeg, deg, scaled_outdeg, scaled_indeg) are automatically computed during initialization via get_node_degrees().

Matrix types available: - ‘adj’: Adjacency matrix - ‘trans’: Transition matrix (undirected only) - ‘lap’: Laplacian matrix - ‘nlap’: Normalized Laplacian (undirected only) - ‘rwlap’: Random walk Laplacian (undirected only) - ‘lap_out’: Out-Laplacian (directed only) - ‘lap_in’: In-Laplacian (directed only)

See also

driada.recurrence.RecurrenceGraph

Recurrence graph (subclass via ProximityGraph).

driada.recurrence.VisibilityGraph

Visibility graph (subclass).

driada.recurrence.OrdinalPartitionNetwork

Ordinal partition network (subclass).

driada.dim_reduction.graph.ProximityGraph

k-NN proximity graph (subclass).

__init__(adj=None, graph=None, preprocessing='giant_cc', name='', pos=None, verbose=False, create_nx_graph=True, node_attrs=None, logger=None, **network_args)[source]

Initialize a Network object from adjacency matrix or NetworkX graph.

Creates a network representation with automatic detection of directed/weighted properties if not specified. Supports preprocessing to extract connected components.

Parameters:
  • adj (scipy.sparse matrix or None) – Adjacency matrix. Mutually exclusive with graph parameter.

  • graph (networkx.Graph/DiGraph or None) – NetworkX graph object. Mutually exclusive with adj parameter.

  • preprocessing (str or None, default="giant_cc") –

    Preprocessing method:

    • None: No preprocessing

    • ”remove_isolates”: Remove isolated nodes

    • ”giant_cc”: Extract giant connected component

    • ”giant_scc”: Extract giant strongly connected component (directed only)

  • name (str, default="") – Name identifier for the network.

  • pos (dict or None) – Node positions as {node: (x, y)} dictionary.

  • verbose (bool, default=False) – Whether to print progress messages.

  • create_nx_graph (bool, default=True) – Whether to create NetworkX graph from adjacency matrix.

  • node_attrs (dict or None) – Node attributes as {node: {attr: value}} nested dictionary.

  • logger (logging.Logger or None) – Logger instance for logging messages.

  • **network_args

    Additional network parameters:

    • directed : bool or None (auto-detected if None)

    • weighted : bool or None (auto-detected if None)

    • real_world : bool (affects directionality validation)

adj

Adjacency matrix in sparse format.

Type:

scipy.sparse matrix

graph

NetworkX graph representation.

Type:

networkx.Graph/DiGraph or None

directed

Whether the network is directed.

Type:

bool

weighted

Whether the network has weighted edges.

Type:

bool

n

Number of nodes.

Type:

int

outdeg

Out-degree sequence (set by get_node_degrees()).

Type:

np.ndarray

indeg

In-degree sequence (set by get_node_degrees()).

Type:

np.ndarray

init_method

Initialization method used (‘adj’ or ‘graph’).

Type:

str

_calculated_directionality

Fraction of asymmetric edges (0.0 to 1.0).

Type:

float

network_params

Original network parameters passed to constructor.

Type:

dict

real_world

Whether this is a real-world network.

Type:

bool

_init_to_final_node_mapping

Mapping from initial to final node indices after preprocessing.

Type:

dict

lem_emb

Placeholder for Laplacian eigenmaps embedding.

Type:

None

trans, lap, nlap, rwlap, lap_out, lap_in

Various matrix representations (initialized to None).

Type:

None or array

n_cc

Number of connected components (set during some preprocessing).

Type:

int or None

n_scc

Number of strongly connected components (set during some preprocessing).

Type:

int or None

Raises:

ValueError – If both adj and graph are provided or neither is provided.

Parameters:

logger (Logger | None)

Notes

The constructor automatically computes node degrees after initialization. For large sparse matrices, auto-detection of directed/weighted properties uses efficient sparse operations to avoid memory issues.

is_connected()[source]

Check if the network is connected.

A network is connected if there is a path between every pair of nodes. For directed networks, checks weak connectivity (ignoring edge direction).

Returns:

True if the network has only one connected component, False otherwise.

Return type:

bool

randomize(rmode='shuffle')[source]

Create a randomized version of the network.

Different randomization methods preserve different network properties.

Parameters:

rmode (str, default='shuffle') – Randomization method: - ‘shuffle’: Complete edge shuffling (random graph with same density) - ‘graph_iom’: In-degree, Out-degree, and Mutual degree preserving (via NetworkX) - ‘adj_iom’: In-degree, Out-degree, and Mutual degree preserving (via adjacency matrix) - ‘complete’: Randomize as complete graph

Returns:

New Network object with randomized edges.

Return type:

Network

Notes

IOM methods preserve in-degree, out-degree, and mutual (reciprocal) degree sequences for each node. This maintains the local connectivity patterns while randomizing the global structure. Shuffle method only preserves edge density.

get_node_degrees()[source]

Calculate degree sequences for all nodes.

Computes in-degree, out-degree, and total degree for each node. Also creates scaled versions normalized to [0, 1].

Sets Attributes

outdegnp.ndarray

Out-degree for each node.

indegnp.ndarray

In-degree for each node.

degnp.ndarray

Total degree (considering undirected edges).

scaled_outdegnp.ndarray

Out-degrees scaled to [0, 1].

scaled_indegnp.ndarray

In-degrees scaled to [0, 1].

get_degree_distr(mode='all')[source]

Get degree distribution of the network.

Parameters:

mode (str, default='all') – Type of degree distribution: - ‘all’: Total degree - ‘in’: In-degree only - ‘out’: Out-degree only

Returns:

Normalized histogram of degree values.

Return type:

np.ndarray

Raises:

ValueError – If mode is not recognized.

get_matrix(mode)[source]

Get a specific matrix representation of the network.

Computes and caches various matrix representations lazily.

Parameters:

mode (str) – Matrix type to retrieve: - ‘adj’: Adjacency matrix - ‘lap’/’lap_out’: Laplacian matrix - ‘nlap’: Normalized Laplacian - ‘rwlap’: Random walk Laplacian - ‘trans’: Transition matrix

Returns:

The requested matrix representation.

Return type:

scipy.sparse matrix

Raises:

ValueError – If matrix type is not recognized or not applicable.

Notes

Matrices are computed lazily and cached as instance attributes.

get_spectrum(mode)[source]

Get eigenvalues of a specific matrix representation.

Computes eigendecomposition if not already cached.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

Eigenvalues of the specified matrix, sorted in ascending order.

Return type:

np.ndarray

Notes

Calls diagonalize() if spectrum not already computed.

get_eigenvectors(mode)[source]

Get eigenvectors of a specific matrix representation.

Computes eigendecomposition if not already cached.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

Eigenvectors of the specified matrix (as columns). Column order matches eigenvalue ordering (ascending). Shape is (n_nodes, n_nodes).

Return type:

np.ndarray

Notes

Calls diagonalize() if eigenvectors not already computed.

get_ipr(mode)[source]

Get Inverse Participation Ratio (IPR) for eigenvectors.

IPR measures localization of eigenvectors. Higher values indicate more localized eigenvectors.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

IPR values for each eigenvector.

Return type:

np.ndarray

Notes

IPR = sum(abs(v_i)^4) / (sum(abs(v_i)^2))^2 For normalized eigenvectors, this simplifies to IPR = sum(abs(v_i)^4). Range: 1/n <= IPR <= 1, where n is the number of nodes.

get_z_values(mode)[source]

Get eigenvalue spacing ratios for the specified matrix mode.

Computes the ratio z_i = (λ_nn - λ_i) / (λ_nnn - λ_i) where λ_nn is the nearest neighbor eigenvalue and λ_nnn is the next-nearest neighbor. These ratios are useful for analyzing spectral statistics without requiring eigenvalue unfolding procedures.

Parameters:

mode (str) – Matrix mode to use: - Undirected: ‘adj’, ‘trans’, ‘lap’, ‘nlap’, ‘rwlap’ - Directed: ‘adj’, ‘lap_out’, ‘lap_in’

Returns:

Dictionary mapping eigenvalues to their spacing ratios (z-values).

Return type:

dict

Notes

The spacing ratio is a standard measure in random matrix theory for characterizing level statistics. It avoids the need for eigenvalue unfolding that is required for simple spacing distributions.

If z-values haven’t been calculated yet, this method will trigger their calculation via calculate_z_values().

References

Atas, Y. Y., et al. (2013). Distribution of the ratio of consecutive level spacings in random matrix ensembles. Physical Review Letters, 110(8), 084101.

Sá, L., Ribeiro, P., & Prosen, T. (2020). Complex spacing ratios: A signature of dissipative quantum chaos. Physical Review X, 10(2), 021019. https://link.aps.org/doi/10.1103/PhysRevX.10.021019

partial_diagonalize(spectrum_params)[source]

Partial diagonalization for large matrices.

Parameters:

spectrum_params (dict) – Parameters including ‘neigs’ (number of eigenvalues)

Returns:

eigenvalues, eigenvectors – Partial spectrum and eigenvectors

Return type:

array-like

Raises:

NotImplementedError – This function is not yet implemented.

diagonalize(mode='lap', verbose=None)[source]

Compute eigenvalues and eigenvectors of the specified matrix.

Performs full eigendecomposition of the network matrix specified by mode. Results are cached as attributes for later retrieval.

Parameters:
  • mode (str, optional) – Matrix mode to diagonalize: - Undirected: ‘adj’, ‘trans’, ‘lap’, ‘nlap’, ‘rwlap’ - Directed: ‘adj’, ‘lap_out’, ‘lap_in’ Default is ‘lap’.

  • verbose (bool or None, optional) – Whether to print progress messages. If None, uses self.verbose. Default is None.

Notes

After diagonalization, eigenvalues and eigenvectors are stored as: - self.{mode}_spectrum: eigenvalues (sorted) - self.{mode}_eigenvectors: right eigenvectors (as columns)

The method uses scipy.linalg.eigh for symmetric matrices and scipy.linalg.eig for non-symmetric matrices. Complex eigenvalues and eigenvectors are allowed for directed networks but will raise an error for undirected networks.

calculate_gromov_hyperbolicity(num_samples=100000, return_list=False)[source]

Calculate Gromov hyperbolicity of the network.

Gromov hyperbolicity measures how “tree-like” a graph is. A tree has hyperbolicity 0, while graphs with many cycles have higher values.

This implementation uses random sampling of 4-tuples of nodes to estimate the hyperbolicity efficiently for large graphs.

Parameters:
  • num_samples (int, default=100000) – Number of random 4-tuples to sample

  • return_list (bool, default=False) – If True, return the list of all hyperbolicity values. If False, return the average.

Returns:

Average hyperbolicity value, or list of all values if return_list=True

Return type:

float or list

References

  • Chalopin, J., Chepoi, V., Dragan, F.F., Ducoffe, G., Mohammed, A., Vaxès, Y. (2018). “Fast approximation and exact computation of negative curvature parameters of graphs” arXiv:1803.06324

Notes

Warning: For large graphs, this precomputes ALL shortest paths which requires O(n²) memory. Use with caution on graphs with >10k nodes.

calculate_z_values(mode='lap')[source]

Calculate eigenvalue spacing ratios (z-values) for spectral analysis.

Internal method that computes the spacing ratios z_i = (λ_nn - λ_i) / (λ_nnn - λ_i) where λ_nn and λ_nnn are the nearest and next-nearest neighbor eigenvalues in the complex plane. These ratios characterize level statistics without requiring eigenvalue unfolding.

Parameters:

mode (str, default="lap") – Matrix mode for eigenvalue calculation. See get_matrix() for options.

Raises:

ValueError – If fewer than 3 unique eigenvalues exist (minimum needed for ratios).

Notes

Results are stored in self.<mode>_zvalues as a dictionary mapping eigenvalues to their z-values. Duplicate eigenvalues are removed before calculation. Uses k-d tree search in 2D (real, imaginary) space for efficient nearest neighbor finding.

The spacing ratio avoids the need for eigenvalue unfolding that is required for simple spacing distributions, making it particularly useful for analyzing spectra with non-uniform density.

References

Atas, Y. Y., et al. (2013). Distribution of the ratio of consecutive level spacings in random matrix ensembles. Physical Review Letters, 110(8), 084101.

Sá, L., Ribeiro, P., & Prosen, T. (2020). Complex spacing ratios: A signature of dissipative quantum chaos. Physical Review X, 10(2), 021019. https://link.aps.org/doi/10.1103/PhysRevX.10.021019

See also

get_z_values

Public interface to retrieve calculated z-values

calculate_ipr(mode='adj')[source]

Calculate Inverse Participation Ratio (IPR) for eigenvectors.

Internal method that computes the IPR for each eigenvector of the specified matrix. IPR quantifies the degree of localization of eigenvectors - higher values indicate more localized (less spread out) eigenvectors.

Parameters:

mode (str, default="adj") – Matrix mode for eigenvector calculation. See get_matrix() for options.

Notes

For each eigenvector v_i with components v_{i,j}, the IPR is: IPR_i = sum_j abs(v_{i,j})^4

The IPR ranges from 1/N (completely delocalized) to 1 (completely localized on a single node), where N is the number of nodes.

Results are stored in self.<mode>_ipr as an array of IPR values for each eigenvector. Also computes eigenvector Shannon entropy but does not store it.

The IPR is widely used in physics to characterize Anderson localization and in network science to study eigenvector localization properties.

See also

get_ipr

Public interface to retrieve calculated IPR values

get_eigenvectors

Retrieves the eigenvectors used in calculation

Notes

Also computes Shannon entropy of eigenvectors internally but does not store it. This may be changed in future versions.

calculate_thermodynamic_entropy(tlist, verbose=False, norm=False)[source]

Calculate von Neumann entropy at different temperatures.

Computes the von Neumann entropy S(ρ) = -Tr(ρ log₂ ρ) for density matrices ρ = exp(-tL)/Z constructed from the graph Laplacian spectrum at various inverse temperatures t.

Parameters:
  • tlist (array-like) – List of inverse temperature values (t = β). Higher values correspond to lower temperatures in the thermodynamic analogy.

  • verbose (bool, default=False) – If True, prints intermediate calculation steps.

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Von Neumann entropy values S(ρ) for each temperature in tlist. Values are in bits (using log₂).

Return type:

list of float

Notes

The density matrix ρ = exp(-tL)/Z represents a thermal state where: - L is the graph Laplacian (encoding network structure) - t is inverse temperature (time parameter in diffusion context) - Z = Tr(exp(-tL)) is the partition function

The entropy quantifies the “quantumness” or disorder in the network’s spectral properties. It interpolates between: - t → 0: S → log₂(N) (maximum entropy, uniform distribution) - t → ∞: S → 0 (minimum entropy, ground state dominates)

References

De Domenico, M., & Biamonte, J. (2016). Spectral entropies as information-theoretic tools for complex network comparison. Physical Review X, 6(4), 041062.

See also

calculate_free_entropy

Free entropy (log partition function)

calculate_q_entropy

Generalized Rényi entropy

calculate_free_entropy(tlist, norm=False)[source]

Calculate free entropy (log partition function) at different temperatures.

Computes the free entropy F = log₂(Z) where Z = Tr(exp(-tL)) is the partition function derived from the graph Laplacian spectrum.

Parameters:
  • tlist (array-like) – List of inverse temperature values (t = β). Higher values correspond to lower temperatures.

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Free entropy values F(t) = log₂(Z(t)) for each temperature.

Return type:

list of float

Notes

The free entropy F = log₂(Z) is the logarithm of the partition function in bits. This is also known as the Massieu function in statistical physics. Note: This differs from the Helmholtz free energy F_Helmholtz = -kT ln(Z).

Our measure F = log₂(Z) = ln(Z)/ln(2) represents the effective number of accessible states on a logarithmic scale:

  • Low t (high T): Many states accessible, large F

  • High t (low T): Few states accessible, small F

The partition function Z = sum_i exp(-tλ_i) sums over all eigenvalues λ_i of the Laplacian, encoding the network’s spectral properties.

References

Ghavasieh, A., et al. (2021). Multiscale statistical physics of the pan-viral interactome unravels the systemic nature of SARS-CoV-2 infections. Communications Physics, 4(1), 83. https://www.nature.com/articles/s42005-021-00582-8

See also

calculate_thermodynamic_entropy

Von Neumann entropy

calculate_q_entropy

Generalized Rényi entropy

calculate_q_entropy(q, tlist, norm=False)[source]

Calculate Rényi q-entropy at different temperatures.

Computes the Rényi entropy of order q for density matrices derived from the graph Laplacian spectrum. Generalizes von Neumann entropy (q=1) to a family of entropy measures with different sensitivities to the probability distribution.

Parameters:
  • q (float) – Order parameter for Rényi entropy. Must be positive. Special cases: - q → 0: Hartley entropy (log of support size) - q = 1: Von Neumann entropy (Shannon entropy) - q = 2: Collision entropy (related to purity) - q → ∞: Min-entropy (negative log of max probability)

  • tlist (array-like) – List of inverse temperature values (t = β).

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Rényi q-entropy values S_q(ρ) for each temperature in bits.

Return type:

list of float

Raises:

Exception – If q ≤ 0 or if complex entropy values are detected.

Notes

The Rényi q-entropy is defined as: - For q ≠ 1: S_q(ρ) = (1/(1-q)) log(Tr(ρ^q)) - For q = 1: S_1(ρ) = -Tr(ρ log ρ) (von Neumann entropy)

Different q values emphasize different parts of the spectrum: - Small q: Sensitive to small probabilities (rare events) - Large q: Sensitive to large probabilities (typical events)

References

De Domenico, M., & Biamonte, J. (2016). Spectral entropies as information-theoretic tools for complex network comparison. Physical Review X, 6(4), 041062.

See also

calculate_thermodynamic_entropy

Von Neumann entropy (q=1 case)

calculate_free_entropy

Free entropy (log partition function)

calculate_estrada_communicability()[source]

Calculate Estrada communicability index of the network.

The Estrada communicability is the sum of exponentials of the adjacency matrix eigenvalues: G = sum(exp(λᵢ)). It measures the ease of communication across the entire network.

Returns:

Estrada communicability index G.

Return type:

float

Notes

Higher values indicate better overall network communicability. This metric is sensitive to the number of closed walks of all lengths.

References

Estrada, E., & Hatano, N. (2008). Communicability in complex networks. Physical Review E, 77(3), 036111.

get_estrada_bipartivity_index()[source]

Calculate Estrada bipartivity index of the network.

The bipartivity index measures how close a network is to being bipartite. It is computed as the ratio of sums of hyperbolic functions of eigenvalues: β = (sum(cosh(λᵢ)) - sum(sinh(λᵢ))) / (sum(cosh(λᵢ)) + sum(sinh(λᵢ)))

Returns:

Bipartivity index between 0 and 1, where 1 indicates perfect bipartivity.

Return type:

float

Notes

For bipartite graphs, all eigenvalues come in ±λ pairs, making sinh terms cancel. The index equals 1 for perfectly bipartite graphs and decreases with deviation.

References

Estrada, E., & Rodríguez-Velázquez, J. A. (2005). Spectral measures of bipartivity in complex networks. Physical Review E, 72(4), 046105.

localization_signatures(mode='lap')[source]

Compute statistical signatures of eigenstate localization.

Analyzes the z-values (eigenvalue spacing ratios) to extract signatures that distinguish between localized and delocalized eigenstates.

Parameters:

mode (str, default="lap") – Matrix type to analyze. Must be a valid matrix mode.

Returns:

  • mean_inv_r_sq (float) – Average of 1/abs(z)^2 over all non-zero z-values.

  • mean_cos_phi (float) – Average of cos(arg(z)) over all non-zero z-values.

Notes

These signatures help identify Anderson localization transitions. Localized states typically show different statistical properties in their eigenvalue spacing ratios compared to extended states.

Z-values that are exactly zero (from degenerate eigenvalues, see calculate_z_values) are excluded to avoid singularities in 1/abs(z)^2.

Requires prior calculation of z-values via calculate_z_values().

construct_lem_embedding(dim)[source]

Construct Laplacian Eigenmaps (LEM) embedding of the network.

Computes a low-dimensional embedding that preserves local network structure by using the eigenvectors of the graph Laplacian corresponding to the smallest non-zero eigenvalues.

Parameters:

dim (int) – Target embedding dimension. Must be less than number of nodes.

Notes

Sets self.lem_emb to an ndarray of shape (dim, n_nodes) where each row corresponds to one embedding dimension.

The embedding minimizes the weighted sum of squared distances between connected nodes. The first eigenvector (constant) is excluded as it doesn’t provide discriminative information.

For disconnected graphs, only the giant component is embedded.

References

Belkin, M., & Niyogi, P. (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural computation, 15(6), 1373-1396.

General-purpose graph analysis class. Accepts any scipy sparse adjacency matrix or NetworkX graph – connectomes, correlation networks, functional connectivity, or any other graph. Also serves as the base class for ProximityGraph, so graph-based dimensionality reduction methods produce objects with the full Network analysis toolkit.

Network Class

class driada.network.net_base.Network(adj=None, graph=None, preprocessing='giant_cc', name='', pos=None, verbose=False, create_nx_graph=True, node_attrs=None, logger=None, **network_args)[source]

Network analysis class with focus on spectral graph theory.

This class provides a comprehensive interface for analyzing networks using spectral methods. It supports both directed and undirected, weighted and unweighted networks, and can be initialized from adjacency matrices or NetworkX graphs.

Parameters:
  • adj (scipy.sparse matrix, optional) – Sparse adjacency matrix. Either adj or graph must be provided.

  • graph (networkx.Graph or networkx.DiGraph, optional) – NetworkX graph object. Either adj or graph must be provided.

  • preprocessing (str, default='giant_cc') – Preprocessing method to apply: - None: No preprocessing (may cause connectivity issues) - ‘remove_isolates’: Remove isolated nodes and self-loops - ‘giant_cc’: Extract giant connected component (undirected) - ‘giant_scc’: Extract giant strongly connected component (directed)

  • name (str, default='') – Name identifier for the network.

  • pos (dict, optional) – Node positions as {node: (x, y)} or {node: (x, y, z)}.

  • verbose (bool, default=False) – Whether to print progress messages.

  • create_nx_graph (bool, default=True) – Whether to create NetworkX graph from adjacency matrix. Set to False for large networks to save memory.

  • node_attrs (dict, optional) – Node attributes as {node: attribute_dict}.

  • logger (logging.Logger, optional) – Logger instance for debugging. If None, creates default logger.

  • **network_args (dict) – Additional network parameters: - directed : bool, optional (auto-detected if not specified) - weighted : bool, optional (auto-detected if not specified) - real_world : bool, default=True

adj

Adjacency matrix (always stored as sparse).

Type:

scipy.sparse.csr_matrix

graph

NetworkX graph object (None if create_nx_graph=False).

Type:

networkx.Graph or networkx.DiGraph or None

n

Number of nodes in the network.

Type:

int

n_cc

Number of connected components (set to 1 after giant_cc preprocessing).

Type:

int or None

n_scc

Number of strongly connected components (set to 1 after giant_scc).

Type:

int or None

directed

Whether the network is directed.

Type:

bool

weighted

Whether the network is weighted.

Type:

bool

real_world

Whether this is a real-world network (affects certain analyses).

Type:

bool

name

Network name identifier.

Type:

str

pos

Node positions if provided.

Type:

dict or None

node_attrs

Node attributes if provided.

Type:

dict or None

verbose

Verbosity flag.

Type:

bool

logger

Logger instance.

Type:

logging.Logger

init_method

Initialization method used (‘adj’ or ‘graph’).

Type:

str

network_params

Original network parameters passed to __init__.

Type:

dict

create_nx_graph

Whether NetworkX graph was created from adjacency matrix.

Type:

bool

outdeg

Out-degree sequence (automatically computed).

Type:

ndarray

indeg

In-degree sequence (automatically computed).

Type:

ndarray

deg

Total degree sequence - undirected view (automatically computed).

Type:

ndarray

scaled_outdeg

Out-degree normalized to [0, 1] (automatically computed).

Type:

ndarray

scaled_indeg

In-degree normalized to [0, 1] (automatically computed).

Type:

ndarray

lem_emb

Laplacian eigenmaps embedding if computed.

Type:

ndarray or None

estrada_communicability

Estrada communicability index if computed.

Type:

float or None

estrada_bipartivity

Estrada bipartivity index if computed.

Type:

float or None

_calculated_directionality

Fraction of directed edges detected during initialization (private).

Type:

float or None

_init_to_final_node_mapping

Mapping from initial to final node indices after preprocessing (private, only when using adjacency without creating graph).

Type:

dict or None

Dynamic Matrix Attributes
------------------------
For each matrix type in ['adj', 'trans', 'lap', 'nlap', 'rwlap'] (undirected)
or ['adj', 'lap_out', 'lap_in'] (directed), the following attributes are
dynamically created and initially set to None
{matrix_type}

The matrix itself (computed on demand).

Type:

scipy.sparse matrix or None

{matrix_type}_spectrum

Eigenvalues of the matrix.

Type:

ndarray or None

{matrix_type}_eigenvectors

Eigenvectors of the matrix.

Type:

ndarray or None

{matrix_type}_zvalues

IPR z-values for eigenvector localization.

Type:

ndarray or None

{matrix_type}_ipr

Inverse participation ratio values.

Type:

ndarray or None

is_connected()[source]

Check if the network is connected.

randomize(rmode='shuffle')[source]

Create randomized version preserving certain properties.

get_node_degrees()[source]

Calculate and store degree sequences.

get_degree_distr(mode='all')[source]

Get degree distribution statistics.

get_matrix(mode)[source]

Get or compute specified matrix type.

get_spectrum(mode)[source]

Get eigenvalues for specified matrix.

get_eigenvectors(mode)[source]

Get eigenvectors for specified matrix.

get_ipr(mode)[source]

Get inverse participation ratio for specified matrix.

get_z_values(mode)[source]

Get IPR z-values for specified matrix.

diagonalize(mode='lap', verbose=None)[source]

Compute eigendecomposition for specified matrix.

partial_diagonalize(spectrum_params)[source]

Compute partial eigendecomposition.

calculate_gromov_hyperbolicity(num_samples=100000, return_list=False)[source]

Calculate Gromov hyperbolicity of the network.

calculate_z_values(mode='lap')[source]

Calculate IPR z-values for eigenvector localization.

calculate_ipr(mode='adj')[source]

Calculate inverse participation ratio.

calculate_thermodynamic_entropy(tlist, verbose=False, norm=False)[source]

Calculate von Neumann entropy at different temperatures.

calculate_free_entropy(tlist, norm=False)[source]

Calculate free entropy.

calculate_q_entropy(q, tlist, norm=False)[source]

Calculate q-entropy (Tsallis entropy).

calculate_estrada_communicability()[source]

Calculate Estrada communicability index.

get_estrada_bipartivity_index()[source]

Calculate Estrada bipartivity index.

localization_signatures(mode='lap')[source]

Analyze eigenvector localization.

construct_lem_embedding(dim)[source]

Construct Laplacian eigenmaps embedding.

Notes

The class uses lazy evaluation for matrix computations - matrices and their spectral properties are only computed when first requested. The directionality is automatically detected if not specified, using a fractional approach that can identify partially directed networks.

The diagonalize method may raise exceptions if: - The network has isolated nodes when n_cc=1 is expected - The network has multiple components when only one is expected - Complex eigenvalues/eigenvectors are found for undirected networks

Degree sequences (outdeg, indeg, deg, scaled_outdeg, scaled_indeg) are automatically computed during initialization via get_node_degrees().

Matrix types available: - ‘adj’: Adjacency matrix - ‘trans’: Transition matrix (undirected only) - ‘lap’: Laplacian matrix - ‘nlap’: Normalized Laplacian (undirected only) - ‘rwlap’: Random walk Laplacian (undirected only) - ‘lap_out’: Out-Laplacian (directed only) - ‘lap_in’: In-Laplacian (directed only)

See also

driada.recurrence.RecurrenceGraph

Recurrence graph (subclass via ProximityGraph).

driada.recurrence.VisibilityGraph

Visibility graph (subclass).

driada.recurrence.OrdinalPartitionNetwork

Ordinal partition network (subclass).

driada.dim_reduction.graph.ProximityGraph

k-NN proximity graph (subclass).

__init__(adj=None, graph=None, preprocessing='giant_cc', name='', pos=None, verbose=False, create_nx_graph=True, node_attrs=None, logger=None, **network_args)[source]

Initialize a Network object from adjacency matrix or NetworkX graph.

Creates a network representation with automatic detection of directed/weighted properties if not specified. Supports preprocessing to extract connected components.

Parameters:
  • adj (scipy.sparse matrix or None) – Adjacency matrix. Mutually exclusive with graph parameter.

  • graph (networkx.Graph/DiGraph or None) – NetworkX graph object. Mutually exclusive with adj parameter.

  • preprocessing (str or None, default="giant_cc") –

    Preprocessing method:

    • None: No preprocessing

    • ”remove_isolates”: Remove isolated nodes

    • ”giant_cc”: Extract giant connected component

    • ”giant_scc”: Extract giant strongly connected component (directed only)

  • name (str, default="") – Name identifier for the network.

  • pos (dict or None) – Node positions as {node: (x, y)} dictionary.

  • verbose (bool, default=False) – Whether to print progress messages.

  • create_nx_graph (bool, default=True) – Whether to create NetworkX graph from adjacency matrix.

  • node_attrs (dict or None) – Node attributes as {node: {attr: value}} nested dictionary.

  • logger (logging.Logger or None) – Logger instance for logging messages.

  • **network_args

    Additional network parameters:

    • directed : bool or None (auto-detected if None)

    • weighted : bool or None (auto-detected if None)

    • real_world : bool (affects directionality validation)

adj

Adjacency matrix in sparse format.

Type:

scipy.sparse matrix

graph

NetworkX graph representation.

Type:

networkx.Graph/DiGraph or None

directed

Whether the network is directed.

Type:

bool

weighted

Whether the network has weighted edges.

Type:

bool

n

Number of nodes.

Type:

int

outdeg

Out-degree sequence (set by get_node_degrees()).

Type:

np.ndarray

indeg

In-degree sequence (set by get_node_degrees()).

Type:

np.ndarray

init_method

Initialization method used (‘adj’ or ‘graph’).

Type:

str

_calculated_directionality

Fraction of asymmetric edges (0.0 to 1.0).

Type:

float

network_params

Original network parameters passed to constructor.

Type:

dict

real_world

Whether this is a real-world network.

Type:

bool

_init_to_final_node_mapping

Mapping from initial to final node indices after preprocessing.

Type:

dict

lem_emb

Placeholder for Laplacian eigenmaps embedding.

Type:

None

trans, lap, nlap, rwlap, lap_out, lap_in

Various matrix representations (initialized to None).

Type:

None or array

n_cc

Number of connected components (set during some preprocessing).

Type:

int or None

n_scc

Number of strongly connected components (set during some preprocessing).

Type:

int or None

Raises:

ValueError – If both adj and graph are provided or neither is provided.

Parameters:

logger (Logger | None)

Notes

The constructor automatically computes node degrees after initialization. For large sparse matrices, auto-detection of directed/weighted properties uses efficient sparse operations to avoid memory issues.

is_connected()[source]

Check if the network is connected.

A network is connected if there is a path between every pair of nodes. For directed networks, checks weak connectivity (ignoring edge direction).

Returns:

True if the network has only one connected component, False otherwise.

Return type:

bool

randomize(rmode='shuffle')[source]

Create a randomized version of the network.

Different randomization methods preserve different network properties.

Parameters:

rmode (str, default='shuffle') – Randomization method: - ‘shuffle’: Complete edge shuffling (random graph with same density) - ‘graph_iom’: In-degree, Out-degree, and Mutual degree preserving (via NetworkX) - ‘adj_iom’: In-degree, Out-degree, and Mutual degree preserving (via adjacency matrix) - ‘complete’: Randomize as complete graph

Returns:

New Network object with randomized edges.

Return type:

Network

Notes

IOM methods preserve in-degree, out-degree, and mutual (reciprocal) degree sequences for each node. This maintains the local connectivity patterns while randomizing the global structure. Shuffle method only preserves edge density.

get_node_degrees()[source]

Calculate degree sequences for all nodes.

Computes in-degree, out-degree, and total degree for each node. Also creates scaled versions normalized to [0, 1].

Sets Attributes

outdegnp.ndarray

Out-degree for each node.

indegnp.ndarray

In-degree for each node.

degnp.ndarray

Total degree (considering undirected edges).

scaled_outdegnp.ndarray

Out-degrees scaled to [0, 1].

scaled_indegnp.ndarray

In-degrees scaled to [0, 1].

get_degree_distr(mode='all')[source]

Get degree distribution of the network.

Parameters:

mode (str, default='all') – Type of degree distribution: - ‘all’: Total degree - ‘in’: In-degree only - ‘out’: Out-degree only

Returns:

Normalized histogram of degree values.

Return type:

np.ndarray

Raises:

ValueError – If mode is not recognized.

get_matrix(mode)[source]

Get a specific matrix representation of the network.

Computes and caches various matrix representations lazily.

Parameters:

mode (str) – Matrix type to retrieve: - ‘adj’: Adjacency matrix - ‘lap’/’lap_out’: Laplacian matrix - ‘nlap’: Normalized Laplacian - ‘rwlap’: Random walk Laplacian - ‘trans’: Transition matrix

Returns:

The requested matrix representation.

Return type:

scipy.sparse matrix

Raises:

ValueError – If matrix type is not recognized or not applicable.

Notes

Matrices are computed lazily and cached as instance attributes.

get_spectrum(mode)[source]

Get eigenvalues of a specific matrix representation.

Computes eigendecomposition if not already cached.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

Eigenvalues of the specified matrix, sorted in ascending order.

Return type:

np.ndarray

Notes

Calls diagonalize() if spectrum not already computed.

get_eigenvectors(mode)[source]

Get eigenvectors of a specific matrix representation.

Computes eigendecomposition if not already cached.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

Eigenvectors of the specified matrix (as columns). Column order matches eigenvalue ordering (ascending). Shape is (n_nodes, n_nodes).

Return type:

np.ndarray

Notes

Calls diagonalize() if eigenvectors not already computed.

get_ipr(mode)[source]

Get Inverse Participation Ratio (IPR) for eigenvectors.

IPR measures localization of eigenvectors. Higher values indicate more localized eigenvectors.

Parameters:

mode (str) – Matrix type (see get_matrix for options).

Returns:

IPR values for each eigenvector.

Return type:

np.ndarray

Notes

IPR = sum(abs(v_i)^4) / (sum(abs(v_i)^2))^2 For normalized eigenvectors, this simplifies to IPR = sum(abs(v_i)^4). Range: 1/n <= IPR <= 1, where n is the number of nodes.

get_z_values(mode)[source]

Get eigenvalue spacing ratios for the specified matrix mode.

Computes the ratio z_i = (λ_nn - λ_i) / (λ_nnn - λ_i) where λ_nn is the nearest neighbor eigenvalue and λ_nnn is the next-nearest neighbor. These ratios are useful for analyzing spectral statistics without requiring eigenvalue unfolding procedures.

Parameters:

mode (str) – Matrix mode to use: - Undirected: ‘adj’, ‘trans’, ‘lap’, ‘nlap’, ‘rwlap’ - Directed: ‘adj’, ‘lap_out’, ‘lap_in’

Returns:

Dictionary mapping eigenvalues to their spacing ratios (z-values).

Return type:

dict

Notes

The spacing ratio is a standard measure in random matrix theory for characterizing level statistics. It avoids the need for eigenvalue unfolding that is required for simple spacing distributions.

If z-values haven’t been calculated yet, this method will trigger their calculation via calculate_z_values().

References

Atas, Y. Y., et al. (2013). Distribution of the ratio of consecutive level spacings in random matrix ensembles. Physical Review Letters, 110(8), 084101.

Sá, L., Ribeiro, P., & Prosen, T. (2020). Complex spacing ratios: A signature of dissipative quantum chaos. Physical Review X, 10(2), 021019. https://link.aps.org/doi/10.1103/PhysRevX.10.021019

partial_diagonalize(spectrum_params)[source]

Partial diagonalization for large matrices.

Parameters:

spectrum_params (dict) – Parameters including ‘neigs’ (number of eigenvalues)

Returns:

eigenvalues, eigenvectors – Partial spectrum and eigenvectors

Return type:

array-like

Raises:

NotImplementedError – This function is not yet implemented.

diagonalize(mode='lap', verbose=None)[source]

Compute eigenvalues and eigenvectors of the specified matrix.

Performs full eigendecomposition of the network matrix specified by mode. Results are cached as attributes for later retrieval.

Parameters:
  • mode (str, optional) – Matrix mode to diagonalize: - Undirected: ‘adj’, ‘trans’, ‘lap’, ‘nlap’, ‘rwlap’ - Directed: ‘adj’, ‘lap_out’, ‘lap_in’ Default is ‘lap’.

  • verbose (bool or None, optional) – Whether to print progress messages. If None, uses self.verbose. Default is None.

Notes

After diagonalization, eigenvalues and eigenvectors are stored as: - self.{mode}_spectrum: eigenvalues (sorted) - self.{mode}_eigenvectors: right eigenvectors (as columns)

The method uses scipy.linalg.eigh for symmetric matrices and scipy.linalg.eig for non-symmetric matrices. Complex eigenvalues and eigenvectors are allowed for directed networks but will raise an error for undirected networks.

calculate_gromov_hyperbolicity(num_samples=100000, return_list=False)[source]

Calculate Gromov hyperbolicity of the network.

Gromov hyperbolicity measures how “tree-like” a graph is. A tree has hyperbolicity 0, while graphs with many cycles have higher values.

This implementation uses random sampling of 4-tuples of nodes to estimate the hyperbolicity efficiently for large graphs.

Parameters:
  • num_samples (int, default=100000) – Number of random 4-tuples to sample

  • return_list (bool, default=False) – If True, return the list of all hyperbolicity values. If False, return the average.

Returns:

Average hyperbolicity value, or list of all values if return_list=True

Return type:

float or list

References

  • Chalopin, J., Chepoi, V., Dragan, F.F., Ducoffe, G., Mohammed, A., Vaxès, Y. (2018). “Fast approximation and exact computation of negative curvature parameters of graphs” arXiv:1803.06324

Notes

Warning: For large graphs, this precomputes ALL shortest paths which requires O(n²) memory. Use with caution on graphs with >10k nodes.

calculate_z_values(mode='lap')[source]

Calculate eigenvalue spacing ratios (z-values) for spectral analysis.

Internal method that computes the spacing ratios z_i = (λ_nn - λ_i) / (λ_nnn - λ_i) where λ_nn and λ_nnn are the nearest and next-nearest neighbor eigenvalues in the complex plane. These ratios characterize level statistics without requiring eigenvalue unfolding.

Parameters:

mode (str, default="lap") – Matrix mode for eigenvalue calculation. See get_matrix() for options.

Raises:

ValueError – If fewer than 3 unique eigenvalues exist (minimum needed for ratios).

Notes

Results are stored in self.<mode>_zvalues as a dictionary mapping eigenvalues to their z-values. Duplicate eigenvalues are removed before calculation. Uses k-d tree search in 2D (real, imaginary) space for efficient nearest neighbor finding.

The spacing ratio avoids the need for eigenvalue unfolding that is required for simple spacing distributions, making it particularly useful for analyzing spectra with non-uniform density.

References

Atas, Y. Y., et al. (2013). Distribution of the ratio of consecutive level spacings in random matrix ensembles. Physical Review Letters, 110(8), 084101.

Sá, L., Ribeiro, P., & Prosen, T. (2020). Complex spacing ratios: A signature of dissipative quantum chaos. Physical Review X, 10(2), 021019. https://link.aps.org/doi/10.1103/PhysRevX.10.021019

See also

get_z_values

Public interface to retrieve calculated z-values

calculate_ipr(mode='adj')[source]

Calculate Inverse Participation Ratio (IPR) for eigenvectors.

Internal method that computes the IPR for each eigenvector of the specified matrix. IPR quantifies the degree of localization of eigenvectors - higher values indicate more localized (less spread out) eigenvectors.

Parameters:

mode (str, default="adj") – Matrix mode for eigenvector calculation. See get_matrix() for options.

Notes

For each eigenvector v_i with components v_{i,j}, the IPR is: IPR_i = sum_j abs(v_{i,j})^4

The IPR ranges from 1/N (completely delocalized) to 1 (completely localized on a single node), where N is the number of nodes.

Results are stored in self.<mode>_ipr as an array of IPR values for each eigenvector. Also computes eigenvector Shannon entropy but does not store it.

The IPR is widely used in physics to characterize Anderson localization and in network science to study eigenvector localization properties.

See also

get_ipr

Public interface to retrieve calculated IPR values

get_eigenvectors

Retrieves the eigenvectors used in calculation

Notes

Also computes Shannon entropy of eigenvectors internally but does not store it. This may be changed in future versions.

calculate_thermodynamic_entropy(tlist, verbose=False, norm=False)[source]

Calculate von Neumann entropy at different temperatures.

Computes the von Neumann entropy S(ρ) = -Tr(ρ log₂ ρ) for density matrices ρ = exp(-tL)/Z constructed from the graph Laplacian spectrum at various inverse temperatures t.

Parameters:
  • tlist (array-like) – List of inverse temperature values (t = β). Higher values correspond to lower temperatures in the thermodynamic analogy.

  • verbose (bool, default=False) – If True, prints intermediate calculation steps.

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Von Neumann entropy values S(ρ) for each temperature in tlist. Values are in bits (using log₂).

Return type:

list of float

Notes

The density matrix ρ = exp(-tL)/Z represents a thermal state where: - L is the graph Laplacian (encoding network structure) - t is inverse temperature (time parameter in diffusion context) - Z = Tr(exp(-tL)) is the partition function

The entropy quantifies the “quantumness” or disorder in the network’s spectral properties. It interpolates between: - t → 0: S → log₂(N) (maximum entropy, uniform distribution) - t → ∞: S → 0 (minimum entropy, ground state dominates)

References

De Domenico, M., & Biamonte, J. (2016). Spectral entropies as information-theoretic tools for complex network comparison. Physical Review X, 6(4), 041062.

See also

calculate_free_entropy

Free entropy (log partition function)

calculate_q_entropy

Generalized Rényi entropy

calculate_free_entropy(tlist, norm=False)[source]

Calculate free entropy (log partition function) at different temperatures.

Computes the free entropy F = log₂(Z) where Z = Tr(exp(-tL)) is the partition function derived from the graph Laplacian spectrum.

Parameters:
  • tlist (array-like) – List of inverse temperature values (t = β). Higher values correspond to lower temperatures.

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Free entropy values F(t) = log₂(Z(t)) for each temperature.

Return type:

list of float

Notes

The free entropy F = log₂(Z) is the logarithm of the partition function in bits. This is also known as the Massieu function in statistical physics. Note: This differs from the Helmholtz free energy F_Helmholtz = -kT ln(Z).

Our measure F = log₂(Z) = ln(Z)/ln(2) represents the effective number of accessible states on a logarithmic scale:

  • Low t (high T): Many states accessible, large F

  • High t (low T): Few states accessible, small F

The partition function Z = sum_i exp(-tλ_i) sums over all eigenvalues λ_i of the Laplacian, encoding the network’s spectral properties.

References

Ghavasieh, A., et al. (2021). Multiscale statistical physics of the pan-viral interactome unravels the systemic nature of SARS-CoV-2 infections. Communications Physics, 4(1), 83. https://www.nature.com/articles/s42005-021-00582-8

See also

calculate_thermodynamic_entropy

Von Neumann entropy

calculate_q_entropy

Generalized Rényi entropy

calculate_q_entropy(q, tlist, norm=False)[source]

Calculate Rényi q-entropy at different temperatures.

Computes the Rényi entropy of order q for density matrices derived from the graph Laplacian spectrum. Generalizes von Neumann entropy (q=1) to a family of entropy measures with different sensitivities to the probability distribution.

Parameters:
  • q (float) – Order parameter for Rényi entropy. Must be positive. Special cases: - q → 0: Hartley entropy (log of support size) - q = 1: Von Neumann entropy (Shannon entropy) - q = 2: Collision entropy (related to purity) - q → ∞: Min-entropy (negative log of max probability)

  • tlist (array-like) – List of inverse temperature values (t = β).

  • norm (bool, default=False) – If True, uses normalized Laplacian spectrum. If False, uses unnormalized Laplacian. Not supported for directed graphs.

Returns:

Rényi q-entropy values S_q(ρ) for each temperature in bits.

Return type:

list of float

Raises:

Exception – If q ≤ 0 or if complex entropy values are detected.

Notes

The Rényi q-entropy is defined as: - For q ≠ 1: S_q(ρ) = (1/(1-q)) log(Tr(ρ^q)) - For q = 1: S_1(ρ) = -Tr(ρ log ρ) (von Neumann entropy)

Different q values emphasize different parts of the spectrum: - Small q: Sensitive to small probabilities (rare events) - Large q: Sensitive to large probabilities (typical events)

References

De Domenico, M., & Biamonte, J. (2016). Spectral entropies as information-theoretic tools for complex network comparison. Physical Review X, 6(4), 041062.

See also

calculate_thermodynamic_entropy

Von Neumann entropy (q=1 case)

calculate_free_entropy

Free entropy (log partition function)

calculate_estrada_communicability()[source]

Calculate Estrada communicability index of the network.

The Estrada communicability is the sum of exponentials of the adjacency matrix eigenvalues: G = sum(exp(λᵢ)). It measures the ease of communication across the entire network.

Returns:

Estrada communicability index G.

Return type:

float

Notes

Higher values indicate better overall network communicability. This metric is sensitive to the number of closed walks of all lengths.

References

Estrada, E., & Hatano, N. (2008). Communicability in complex networks. Physical Review E, 77(3), 036111.

get_estrada_bipartivity_index()[source]

Calculate Estrada bipartivity index of the network.

The bipartivity index measures how close a network is to being bipartite. It is computed as the ratio of sums of hyperbolic functions of eigenvalues: β = (sum(cosh(λᵢ)) - sum(sinh(λᵢ))) / (sum(cosh(λᵢ)) + sum(sinh(λᵢ)))

Returns:

Bipartivity index between 0 and 1, where 1 indicates perfect bipartivity.

Return type:

float

Notes

For bipartite graphs, all eigenvalues come in ±λ pairs, making sinh terms cancel. The index equals 1 for perfectly bipartite graphs and decreases with deviation.

References

Estrada, E., & Rodríguez-Velázquez, J. A. (2005). Spectral measures of bipartivity in complex networks. Physical Review E, 72(4), 046105.

localization_signatures(mode='lap')[source]

Compute statistical signatures of eigenstate localization.

Analyzes the z-values (eigenvalue spacing ratios) to extract signatures that distinguish between localized and delocalized eigenstates.

Parameters:

mode (str, default="lap") – Matrix type to analyze. Must be a valid matrix mode.

Returns:

  • mean_inv_r_sq (float) – Average of 1/abs(z)^2 over all non-zero z-values.

  • mean_cos_phi (float) – Average of cos(arg(z)) over all non-zero z-values.

Notes

These signatures help identify Anderson localization transitions. Localized states typically show different statistical properties in their eigenvalue spacing ratios compared to extended states.

Z-values that are exactly zero (from degenerate eigenvalues, see calculate_z_values) are excluded to avoid singularities in 1/abs(z)^2.

Requires prior calculation of z-values via calculate_z_values().

construct_lem_embedding(dim)[source]

Construct Laplacian Eigenmaps (LEM) embedding of the network.

Computes a low-dimensional embedding that preserves local network structure by using the eigenvectors of the graph Laplacian corresponding to the smallest non-zero eigenvalues.

Parameters:

dim (int) – Target embedding dimension. Must be less than number of nodes.

Notes

Sets self.lem_emb to an ndarray of shape (dim, n_nodes) where each row corresponds to one embedding dimension.

The embedding minimizes the weighted sum of squared distances between connected nodes. The first eigenvector (constant) is excluded as it doesn’t provide discriminative information.

For disconnected graphs, only the giant component is embedded.

References

Belkin, M., & Niyogi, P. (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural computation, 15(6), 1373-1396.

Validation Functions

The module also contains various validation functions used internally by the Network class.