comet.graph

comet.graph.avg_clustering_onella(G: ndarray) ndarray[source]

Compute the average clustering coefficient as described by Onnela et al. (2005).

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected connectivity matrix (binary or weighted).

Returns:

Average clustering coefficient. If 2D, a single float is returned; if 3D, a 1D array of clustering coefficients is returned, one for each time slice.

Return type:

np.ndarray

References

Onnela, J. P., Saramäki, J., Kertész, J., & Kaski, K. (2005). Intensity and coherence of motifs in weighted complex networks. Physical Review E, 71(6), 065103. DOI: https://doi.org/10.1103/PhysRevE.71.065103

comet.graph.avg_shortest_path(G: ndarray, include_diagonal: bool = False, include_infinite: bool = False) ndarray[source]

Compute the average shortest path length for a 2D or 3D connectivity matrix.

For binary matrices, the connection length matrix is identical to the connectivity matrix. For weighted matrices, the connection length matrix can be obtained via invert().

Parameters:
  • G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected connectivity matrix (binary or weighted).

  • include_diagonal (bool, optional) – If False, diagonal values are ignored when computing the average. Default is False.

  • include_infinite (bool, optional) – If False, infinite path lengths are ignored when computing the average. Default is False.

Returns:

Average shortest path length(s). If 2D, a single float is returned; if 3D, a 1D array of average path lengths is returned, one for each time slice.

Return type:

np.ndarray

comet.graph.backbone_wu(G: ndarray, avgdeg: int = 0, verbose: bool = False) tuple[ndarray, ndarray][source]

Wrapper for bct.backbone_wu() from the Brain Connectivity Toolbox.

The network backbone contains the dominant connections in the network and may be used to aid network visualization. This function computes the backbone of a given weighted and undirected connectivity matrix G, using a minimum-spanning-tree based algorithm.

Parameters:
  • G (np.ndarray) – 2D (NxN) or 3D (NxN x T) weighted undirected connectivity matrix.

  • avgdeg (int, optional) – Desired average degree of the backbone. Default is 0.

  • verbose (bool, optional) – If True, prints out edges while building the spanning tree.

Returns:

GtreeNxN (or NxN x T) np.ndarray

Connection matrix of the minimum spanning tree of G.

GclusNxN (or NxN x T) np.ndarray

Connection matrix of the minimum spanning tree plus strongest connections up to the specified average degree.

Return type:

tuple[np.ndarray, np.ndarray]

comet.graph.betweenness(G: ndarray) ndarray[source]

This is a wrapper function for the betweenness_bin() and betweenness_wei() functions of the bctpy toolbox: https://github.com/aestrivex/bctpy.

Node betweenness centrality is the fraction of all shortest paths in the network that contain a given node. Nodes with high values of betweenness centrality participate in a large number of shortest paths.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) binary/weighted directed/undirected connectivity matrix.

Returns:

Node betweenness centrality vector. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

Notes

  • For binary graphs, betweenness is normalized as BC/[(N-1)(N-2)].

  • For weighted graphs, it is based on connection lengths and similarly normalized.

  • If the input is 3D, each time slice is computed independently.

comet.graph.binarise(G: ndarray, copy: bool = True) ndarray[source]

Binarise connectivity/adjacency matrix

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – binarised adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.clustering_coef(G: ndarray) ndarray[source]

This is a wrapper function for the clustering_coef_*() functions of the bctpy toolbox: https://github.com/aestrivex/bctpy.

The binary clustering coefficient is the fraction of triangles around a node (equiv. the fraction of nodes neighbors that are neighbors of each other).

The weighted clustering coefficient is the average “intensity” of triangles around a node.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) weighted undirected connectivity matrix.

Returns:

Clustering coefficient vector. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

comet.graph.degrees_und(G: ndarray) ndarray[source]

This is a wrapper function for the degrees_und() function of the bctpy toolbox: https://github.com/aestrivex/bctpy.

Node degree is the number of links connected to the node.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected binary/weighted connectivity matrix.

Returns:

Node degree vector. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

Notes

  • If the graph is 3D (NxN x T), each slice is processed independently.

  • Weight information is discarded.

comet.graph.density_und(G: ndarray) tuple[ndarray, ndarray, ndarray][source]

This is a wrapper function for the density_und() function of the bctpy toolbox: https://github.com/aestrivex/bctpy.

Density is the fraction of present connections to possible connections.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected weighted/binary connectivity matrix.

Returns:

  • kden: Density of the graph. If G is 2D, returns a float, if G is 3D, returns a 1D array.

  • N: Number of vertices. If G is 2D, returns an integer, if G is 3D, returns a 1D array.

  • k: Number of edges. If G is 2D, returns an integer, if G is 3D, returns a 1D array.

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

Notes

  • Assumes G is undirected and has no self-connections.

  • Weight information is discarded.

  • If G is 3D (NxN x T), each slice is processed independently.

comet.graph.distance_bin(G: ndarray, inv: bool = False) ndarray[source]

Distance matrix calculation for binary networks with significantly improved performance due to numba compilation.

Parameters:

G (PxP np.ndarray) – undireted weighted adjacency/connectivity matrix

Returns:

D – (inverse) distance matrix

Return type:

PxP np.ndarray

Notes

Algorithm: Matrix multiplication to find paths, faster than original Dijkstra’s algorithm

comet.graph.distance_wei(G: ndarray, inv: bool = False) ndarray[source]

(Inverse) distance matrix for weighted networks with significantly improved performance due to numba compilation.

Parameters:
  • G (PxP np.ndarray) – undireted weighted adjacency/connectivity matrix

  • inv (bool, optional) – if True, the element wise inverse of the distance matrux is returned. Default is True

Returns:

D – (inverse) distance matrix

Return type:

PxP np.ndarray

Notes

Algorithm: Modified Dijkstra’s algorithm

comet.graph.efficiency(G: ndarray, local: bool = False) ndarray[source]

Efficiency for binary and weighted networks (global and local)

Optimized version of the bctpy implelementation by Roan LaPlante (https://github.com/aestrivex/bctpy)

Global efficiency is the average of inverse shortest path length, and is inversely related to the characteristic path length. Local efficiency is the global efficiency computed on the neighborhood of the node, and is related to the clustering coefficient.

Parameters:
  • G (np.ndarray) – 2D (NxN) or 3D (NxNxT) undirected connectivity matrix (binary or weighted).

  • local (bool, optional) – if True, local efficiency is computed. Default is False (global efficiency)

Returns:

  • E (global) (float) – global efficiency, if local is False

  • E (local) (Nx1 np.ndarray) – local efficiency, if local is True

References

Latora, V., & Marchiori, M. (2001). Efficient behavior of small-world networks. Physical review letters, 87(19), 198701. DOI: https://doi.org/10.1103/PhysRevLett.87.198701

Onnela, J. P., Saramäki, J., Kertész, J., & Kaski, K. (2004). Intensity and coherence of motifs in weighted c omplex networks. Physical Review E, 71(6), 065103. DOI: https://doi.org/10.1103/PhysRevE.71.065103

Fagiolo, G. (2007). Clustering in complex directed networks. Physical Review E, 76(2), 026107. DOI: https://doi.org/10.1103/PhysRevE.76.026107

Rubinov, M., & Sporns, O. (2010). Complex network measures of brain connectivity: uses and interpretations. Neuroimage, 52(3), 1059-1069. DOI: https://doi.org/10.1016/j.neuroimage.2009.10.003

Wang, Y., Ghumare, E., Vandenberghe, R., & Dupont, P. (2017). Comparison of different generalizations of clustering coefficient and local efficiency for weighted undirected graphs. Neural computation, 29(2), 313-331. DOI: https://doi.org/10.1162/NECO_a_00914

comet.graph.eigenvector_centrality_und(G: ndarray) ndarray[source]

This is a wrapper function for the eigenvector_centrality_und() function of the bctpy toolbox: https://github.com/aestrivex/bctpy.

Eigenvector centrality is a self-referential measure of centrality: nodes have high eigenvector centrality if they connect to other nodes that have high eigenvector centrality. The eigenvector centrality of node i is equivalent to the ith element in the eigenvector corresponding to the largest eigenvalue of the adjacency matrix.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) binary/weighted undirected adjacency matrix.

Returns:

Eigenvector associated with the largest eigenvalue of the matrix. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

comet.graph.handle_negative_weights(G: ndarray, type: Literal['absolute', 'discard'] = 'absolute', copy: bool = True) ndarray[source]

Handle negative weights in a connectivity/adjacency matrix

Connectivity methods can produce negative estimates, which can be handled in different ways before graph analysis.

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • type (string, optional) – type of handling, can be absolute or discard default is absolute

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – adjacency/connectivity matrix with only positive weights

Return type:

PxP np.ndarray

comet.graph.invert(G: ndarray, copy: bool = True) ndarray[source]

Invert connectivity/adjacency matrix

Element wise inversion W such that each value W[i,j] will be 1 / W[i,j] (internode strengths internode distances)

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – element wise inverted adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.logtransform(G: ndarray, epsilon: float = 1e-10, copy: bool = True) ndarray[source]

Log transform of connectivity/adjacency matrix

Element wise log transform of W such that each value W[i,j] will be -log(W[i,j]

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • epsilon (float, optional) – clipping value for numeric stability, default is 1e-10

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – element wise log transformed adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.matching_ind_und(G: ndarray) ndarray[source]

Matching index for undirected networks

Based on the MATLAB implementation by Stuart Oldham: https://github.com/StuartJO/FasterMatchingIndex

Matching index is a measure of similarity between two nodes’ connectivity profiles (excluding their mutual connection, should it exist). Weighted matrices will be binarised.

Parameters:

G (np.ndarray) – 2D (PxP) or 3D (PxP x T) undirected adjacency/connectivity matrix.

Returns:

M – matching index matrix

Return type:

PxP np.ndarray

References

Oldham, S., Fulcher, B. D., Aquino, K., Arnatkevičiūtė, A., Paquola, C., Shishegar, R., & Fornito, A. (2022). Modeling spatial, developmental, physiological, and topological constraints on human brain connectivity. Science advances, 8(22), eabm6127. DOI: https://doi.org/10.1126/sciadv.abm6127

Betzel, R. F., Avena-Koenigsberger, A., Goñi, J., He, Y., De Reus, M. A., Griffa, A., … & Sporns, O. (2016). Generative models of the human connectome. Neuroimage, 124, 1054-1064. DOI: https://doi.org/10.1016/j.neuroimage.2015.09.041

Notes

Important note: As of Jan 2024 there is a bug in the bctpy version of this function (ncon2 = c1 * CIJ should instead be ncon2 = CIJ * use)

This bug is irrelevant here due to the opimized implementation.

comet.graph.minmax_scale(G: ndarray, feature_range: tuple[float, float] = (0.0, 1.0), include_diagonal: bool = False, copy: bool = True) ndarray[source]

Min-max scale connectivity/adjacency matrix to a given range (default [0, 1]).

If G contains only non-negative values and has a minimum value of zero (e.g., after discarding negative weights), min–max scaling to [0, 1] becomes equivalent to the normalise function.

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix.

  • feature_range (tuple[float, float], optional) – Target range (min, max). Default is (0.0, 1.0).

  • include_diagonal (bool, optional) – If False, diagonal is ignored when computing min/max. The diagonal itself is left unchanged unless it lies outside the target range. Default is False.

  • copy (bool, optional) – If True, a copy is returned. Default is True.

Returns:

Scaled matrix with values in the specified feature_range.

Return type:

np.ndarray

comet.graph.normalise(G: ndarray, copy: bool = True) ndarray[source]

Rescales the connectivity/adjacency matrix by dividing all values by the maximum absolute value. As a result, the largest absolute weight becomes 1.

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – normalised adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.pagerank_centrality(G: ndarray, d: float = 0.85) ndarray[source]

This is a wrapper function for the pagerank_centrality() function of the bctpy toolbox: https://github.com/aestrivex/bctpy.

The PageRank centrality is a variant of eigenvector centrality. This function computes the PageRank centrality of each vertex in a graph.

Parameters:
  • G (np.ndarray) – 2D (NxN) or 3D (NxN x T) adjacency matrix.

  • d (float, optional) – Damping factor (default is 0.85). Specifies the fraction of the time that a random walker will transition to one of its current state’s neighbors.

Returns:

Vectors of page rankings. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

Notes

  • This function does not currently support the falff parameter from bctpy.

  • If G is 3D, each time slice is processed independently.

comet.graph.participation_coef(G: ndarray, ci: Literal['louvain'] | ndarray | list = 'louvain', degree: Literal['undirected', 'in', 'out'] = 'undirected') ndarray[source]

This is a wrapper function for the participation_coef and participation_coef_sparse functions of the bctpy toolbox: https://github.com/aestrivex/bctpy.

The participation coefficient is a measure of diversity of intermodular connections of individual nodes.

Parameters:
  • G (np.ndarray or scipy.sparse.csr_matrix) – 2D (NxN) or 3D (NxN x T) binary/weighted directed/undirected connectivity matrix.

  • ci (str or array-like) – Community detection method. If “louvain”, uses bct.community_louvain. Otherwise, ci itself is treated as an array of community labels.

  • degree (str, optional) – Flag to describe nature of graph: - ‘undirected’: For undirected graphs - ‘in’: Uses the in-degree - ‘out’: Uses the out-degree Default is “undirected”.

Returns:

Participation coefficient vector. If G is 2D, the output is Nx1. If G is 3D, the output is NxT.

Return type:

np.ndarray

comet.graph.participation_coef_sign(G: ndarray, ci: Literal['louvain'] = 'louvain') tuple[ndarray, ndarray][source]

This is a wrapper function for the participation_coef_sign() function of the bctpy toolbox: https://github.com/aestrivex/bctpy.

The participation coefficient is a measure of diversity of intermodular connections of individual nodes, considering both positive and negative weights.

Parameters:
  • G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected connectivity matrix with positive and negative weights.

  • ci (str or array-like) – Community detection method. If “louvain”, uses bct.community_louvain. Otherwise, ci itself is treated as an array of community labels.

Returns:

  • Ppos: Participation coefficient from positive weights.

  • Pneg: Participation coefficient from negative weights.

If G is 2D, each is Nx1. If G is 3D, each is NxT.

Return type:

tuple[np.ndarray, np.ndarray]

comet.graph.postproc(G: ndarray, diag: float = 0, copy: bool = True) ndarray[source]

Postprocessing of connectivity/adjacency matrix

Ensures G is symmetric, sets diagonal to diag, removes NaNs and infinities, and ensures exact binarity

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • diag (int, optional) – set diagonal to this value default is 0

  • copy (bool, optional) – if True, a copy of G is returned, otherwise G is modified in place default is True

Returns:

G – processed adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.randomise(G: ndarray, copy: bool = True) ndarray[source]

Randomly rewire edges of an adjacency/connectivity matrix

Implemented as in https://github.com/rkdan/small_world_propensity

Parameters:

G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

Returns:

G_rand – randomised adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.regular_matrix(G: ndarray, r: int) ndarray[source]

Create a regular matrix.

Adapted from https://github.com/rkdan/small_world_propensity

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix.

  • r (int) – Average effective radius of the network.

Returns:

M – Regularised adjacency matrix (same shape as input).

Return type:

np.ndarray

comet.graph.small_world_propensity(G: ndarray) ndarray[source]

Small world propensity calculation for undirected and symmetric networks. Clustering is calculated using the approach of Onnela et al. (2005).

Based on the MATLAB and Python implementations by Eric Bridgeford, Sarah F. Muldoon, and Ryan Daniels: https://kk1995.github.io/BauerLab/BauerLab/MATLAB/lib/+mouse/+graph/smallWorldPropensity.html https://github.com/rkdan/small_world_propensity

Parameters:

F (PxP np.ndarray) – undirected and symmetric adjacency/connectivity matrix

Returns:

  • SWP (float) – small world propensity of the matrix

  • delta_C (float) – fractional deviation from the expected culstering coefficient of a random network

  • delta_L (float) – fractional deviation from the expected path length of a random network

  • alpha (float) – angle between delta_C and delta_L

  • delta (float) – scaled version of alpha in the range of [-1,1]

References

Muldoon, S., Bridgeford, E. & Bassett, D. Small-World Propensity and Weighted Brain Networks. Sci Rep 6, 22057 (2016). DOI: https://doi.org/10.1038/srep22057

Onnela, J. P., Saramäki, J., Kertész, J., & Kaski, K. (2005). Intensity and coherence of motifs in weighted complex networks. Physical Review E, 71(6), 065103. DOI: https://doi.org/10.1103/PhysRevE.71.065103

comet.graph.small_world_sigma(G: ndarray, nrand: int = 10) ndarray[source]

Compute the small-worldness sigma for undirected networks (binary or weighted).

Small-worldness sigma is calculated as the ratio of the clustering coefficient and the characteristic path length of the real network to the average clustering coefficient and characteristic path length of the random networks.

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) undirected adjacency/connectivity matrix.

  • nrand (int, optional) – Number of random networks to generate (and average over). Default is 10.

Returns:

Small-worldness sigma. If 2D, a single float is returned. If 3D, a 1D array of sigma values is returned, one for each time slice.

Return type:

float or np.ndarray

Notes

This implementation of small worldness relies on matrix operations and is drastically faster than the Networkx implementation. However, it uses a different approach for rewiring edges, so the results may differ.

comet.graph.symmetrise(G: ndarray, copy: bool = True) ndarray[source]

Symmetrise connectivity/adjacency matrix

Symmetrise G such that each value G[i,j] will be G[j,i].

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – symmetrised adjacency/connectivity matrix

Return type:

PxP np.ndarray

comet.graph.threshold(G: ndarray, type: Literal['density', 'absolute'] = 'density', threshold: float = None, density: float = 0.2, copy: bool = True) ndarray[source]

Thresholding of connectivity/adjacency matrix

Performs absolute or density-based thresholding

Parameters:
  • G (np.ndarray) – 2D (PxP) or 3D (PxPxT) adjacency/connectivity matrix

  • type (string, optional) – type of thresholding, can be absolute or density default is absolute

  • threshold (float, optional) – threshold value for absolute thresholding default is None

  • density (float, optional) – density value for density-based thresholding, has to be between 0 and 1 (keep x% of strongest connections) default is 0.2 (20%)

  • copy (bool, optional) – if True, a copy of W is returned, otherwise W is modified in place default is True

Returns:

G – thresholded adjacency/connectivity matrix

Return type:

PxP np.ndarray

Notes

The implemented for density based thresholding always keeps the exact same number of connections. If multiple edges have the same weight, the included edges are chosen “randomly” (based on their order in the sorted indices). This is identical to the behaviour in the BCT implementation.

comet.graph.transitivity_und(G: ndarray) ndarray[source]

Compute transitivity for undirected networks (binary and weighted), adapted from the bctpy implementation: https://github.com/aestrivex/bctpy

Transitivity is the ratio of triangles to triplets in the network and is a classical version of the clustering coefficient.

Parameters:

G (np.ndarray) – 2D (NxN) or 3D (NxN x T) undirected connectivity matrix (binary or weighted).

Returns:

Transitivity scalar(s). If 2D, a single float is returned; if 3D, a 1D array of transitivity values is returned, one for each time slice.

Return type:

np.ndarray