Networks (m.net)

Network models and utilities.

m.net.betweenness

m.net.betweenness(
    adjacency_matrix: jax.Array,
    n_nodes: int,
    k: int = None,
    weight_matrix: jax.Array = None,
    normalized: bool = True,
    endpoints: bool = False,
    directed: bool = False,
)

Betweenness centrality of each node (Brandes’ algorithm, JAX).

The fraction of shortest paths between other pairs of nodes that pass through each node. Matches networkx.betweenness_centrality.

Argument Type Description
adjacency_matrix jax.Array Binary adjacency matrix, shape (N, N).
n_nodes int Number of nodes, N.
k int Sample k source nodes. Not implemented; must be None.
weight_matrix jax.Array Edge lengths (distances) for weighted shortest paths. Defaults to unweighted paths.
normalized bool Normalise by the number of node pairs. Defaults to True.
endpoints bool Count path endpoints. Defaults to False.
directed bool Treat the network as directed. Defaults to False.

Returns

  • jax.Array: Betweenness per node, shape (N,).

Raises

  • NotImplementedError: If k is given.

m.net.bfs

m.net.bfs(adjacency_matrix, source, n_nodes)

Breadth-First Search (BFS)

m.net.block_build_mu_ij

m.net.block_build_mu_ij(N_by_group, N_group)

Build block-model prior means matching STRAND’s internal logic.

This function programmatically replicates the formula in STRAND’s block_set_to_dyadic_block_set.R.

Formula

Base = 0.1 (diagonal/ingroup) or 0.01 (off-diagonal/outgroup) SS = sqrt(N_i * 0.5 + N_j * 0.5) Mu = Base / SS

m.net.block_model

m.net.block_model(
    group,
    N_group,
    N_by_group,
    b_ij_sd=2.5,
    b_ij_mu=None,
    sample=False,
    name='',
)

Sample block-model B matrix and convert to dyadic edgelist contributions.

Argument Type Description
group 1D int array 0-indexed group membership for each node (length N).
N_group int Number of groups.
N_by_group 1D int array Number of nodes per group.
b_ij_sd float or (N_group,N_group) array Prior SD for B[i,j] on logit scale. Defaults to 2.5.
b_ij_mu (N_group,N_group) array Prior mean for B[i,j] on the logit scale. When provided (e.g. STRAND’s block_mu_np reshaped as a matrix), it replaces the generic block_build_mu_ij formula so that wide- format and long-format models share identical block priors. When None (default), the prior mean is computed via block_build_mu_ij.
sample bool Whether to draw samples. Defaults to False.
name str Name suffix for the sampled site (‘b_’).

Returns

  • (N_dyads, 2) array: Logit-scale block contributions for each directed dyad.

m.net.block_prior_to_edglelist

m.net.block_prior_to_edglelist(v, b)

Convert block vector id group belonging to edgelist of i->j group values

Argument Type Description
v 1D array Vector of id group belonging
b 2D array Matrix of block model prior matrix (squared)

Returns

  • 2D array: Shape (N_dyads, 2): the block prior for i -> j and for j -> i of each dyad.

m.net.cc

m.net.cc(m, nodes=None, weighted=False)

Local clustering coefficient of each node.

Argument Type Description
m jax.Array Adjacency (or weight) matrix, shape (N, N); entry [i, j] is the tie from i to j.
nodes array of int Return only these nodes (default: all).
weighted bool Use the weighted (Onnela et al. 2005) coefficient instead of the binary one. Defaults to False.

Returns

  • jax.Array: Clustering coefficient per node, in [0, 1].

m.net.clustering_coefficient

m.net.clustering_coefficient()

Computes the clustering coefficient for each node in the graph. This function is optimized for JAX and is JIT-compatible.

m.net.degree

m.net.degree(m, sym=False, normalize=False)

Degree (number of ties) of each node.

Argument Type Description
m jax.Array Adjacency (or weight) matrix, shape (N, N); entry [i, j] is the tie from i to j.
sym bool The network is symmetric (undirected): count each tie once. Defaults to False (in-degree + out-degree).
normalize bool Divide by the maximum possible degree, N - 1. Defaults to False.

Returns

  • jax.Array: Degree per node, shape (N,).

m.net.degree_jit

m.net.degree_jit(x)

JIT-compiled total degree: in-degree + out-degree of x.

m.net.density

m.net.density(m)

Compute the network density from the weighted adjacency matrix.

Argument Type Description
adj_matrix JAX array representing the weighted adjacency matrix of a graph.

Returns

  • Network density as a float.

m.net.diameter

m.net.diameter(m)

Compute the diameter of a graph using the geodesic distance. Args: adj_matrix: 2D JAX array representing the weighted adjacency matrix of a graph.

Returns

  • The diameter of the graph.

m.net.dijkstra

m.net.dijkstra(
    adjacency_matrix: jax.Array,
    weight_matrix: jax.Array,
    source: int,
    n_nodes: int,
)

Breadth-First Search (BFS)

m.net.dijkstra_jax

m.net.dijkstra_jax(adjacency_matrix, source)

Compute the shortest path from a source node to all other nodes using Dijkstra’s algorithm.

Dijkstra’s algorithm finds the shortest paths between nodes in a graph, particularly useful for graphs with non-negative edge weights. This function uses JAX for efficient computation.

Parameters adjacency_matrix : jax.numpy.ndarray A square (n x n) adjacency matrix representing the graph. The element at (i, j) represents the weight of the edge from node i to node j. Non-zero values indicate a connection, and higher values indicate longer paths.

int

The index of the source node from which the shortest paths are computed.

Returns jax.numpy.ndarray A 1D array of length n where each element represents the shortest distance from the source node to the corresponding node. The source node will have a distance of 0.

m.net.dyad_vec_to_mat

m.net.dyad_vec_to_mat(vec, include_diagonal=False, symmetric=False)

Convert dyad vector to N×N matrix. N deduced from vec length.

Vector length conventions

diag=False, sym=True : N(N-1)/2 — unique undirected dyads diag=False, sym=False : N(N-1) — both directions; first half→upper, second half→lower diag=True, sym=True : N*(N+1)/2 — unique undirected dyads + diagonal diag=True, sym=False : N² — full matrix, row-major

Argument Type Description
vec 1D JAX array
include_diagonal vec includes diagonal elements (default False)
symmetric produce symmetric matrix (default False)

Returns

  • (N, N) JAX array

m.net.dyadic_effect

m.net.dyadic_effect(
    dyadic_predictors=None,
    shape=None,
    d_m=0,
    d_sd=2.5,
    dr_sigma_mu=0,
    dr_sigma_sd=2.5,
    cholesky_dim=2,
    cholesky_density=2.5,
    sample=False,
)

Compute dyadic effects combining both fixed and random components.

Argument Type Description
dyadic_predictors jax array Predictors for dyadic effects.
shape int Shape parameter if predictors are not provided.
d_m float Mean for fixed effects. Defaults to 0.
d_sd float SD for fixed effects. Defaults to 1.
dr_sigma float Sigma parameter for random effects. Defaults to 1.
cholesky_dim int Dimension for Cholesky decomposition. Defaults to 2.
cholesky_density int Density parameter for Cholesky. Defaults to 2.
sample bool Whether to sample from distributions. Defaults to False.

Returns

  • jax array: Combined dyadic effects.

m.net.dyadic_random_effects

m.net.dyadic_random_effects(
    N_dyads,
    dr_sigma_mu=0,
    dr_sigma_sd=2.5,
    cholesky_dim=2,
    cholesky_density=2.5,
    sample=False,
    diag=False,
)

Generate random effects for dyadic models.

Argument Type Description
N_dyads int Number of dyads.
dr_mu float Mean for random effects. Defaults to 0.
dr_sd float SD for random effects. Defaults to 1.
dr_sigma float Sigma parameter for random effects. Defaults to 1.
cholesky_dim int Dimension for Cholesky decomposition. Defaults to 2.
cholesky_density int Density parameter for Cholesky. Defaults to 2.
sample bool Whether to sample from distributions. Defaults to False.
diag bool Whether to print diagnostic information. Defaults to False.

Returns

  • Contains random effects, raw effects, sigma, and Cholesky decomposition matrix.

m.net.dyadic_terms

m.net.dyadic_terms(dyadic_predictors, d_m=0, d_sd=2.5, sample=False)

Calculate fixed effects for dyadic terms.

Argument Type Description
dyadic_predictors jax array Predictors for dyadic terms.
d_m float Mean for dyad effects. Defaults to 0.
d_sd float SD for dyad effects. Defaults to 1.
sample bool Whether to sample from distributions. Defaults to False.
diag bool Whether to print diagnostic information. Defaults to False.

Returns

  • Contains fixed effects and dyadic predictors.

m.net.edge_weights

m.net.edge_weights(
    num_edges,
    prior_mu=0.0,
    prior_sigma=2.5,
    partial_pooling=True,
    sample=False,
    name='edge_weight',
)

Sample edge weight parameters for BISoN-style dyadic inference.

Argument Type Description
num_edges int Number of unique dyads/edges.
prior_mu float Prior mean on logit/log scale. Defaults to 0.0.
prior_sigma float Prior SD (direct) or half-normal scale (partial pooling). Defaults to 2.5.
partial_pooling bool If True, uses non-centered parameterization with a shared sigma hyperprior — decouples edge_sigma from edge geometry for better mixing. Defaults to True.
sample bool Draw from prior (DGP mode) vs declare latent variable. Defaults to False.
name str Base name for sampled sites. Defaults to ‘edge_weight’.

Returns

  • jax array: Edge weight values of shape (num_edges,).

m.net.edgl_to_mat

m.net.edgl_to_mat(edgl, N_id=None)

Dyad edge list (n_dyads, 2) -> (N_id, N_id) adjacency.

N_id is optional: a full dyad list has n_dyads = N_id*(N_id-1)/2 rows, so the node count is recovered from edgl.shape[0] when not given.

m.net.eigenvector

m.net.eigenvector(A, max_iter=100, tol=1e-06)

JAX implementation of eigenvector centrality matching NetworkX behavior.

Computes eigenvector centrality using power iteration with (A + I). For weighted graphs, edge weights are used in the computation.

Argument Type Description
A Adjacency matrix (n x n), can be weighted
max_iter Maximum number of iterations
tol Convergence tolerance (not used in this JIT version)

Returns

  • Eigenvector centrality values (L2 normalized)

m.net.geodesic_distance

m.net.geodesic_distance(m)

Compute the geodesic distance in a weighted graph using Dijkstra’s algorithm in JAX. Args: m: 2D JAX array representing the weighted adjacency matrix of a graph.

Returns

  • A 2D JAX array containing the shortest path distances between all pairs of nodes.

m.net.get_tri

m.net.get_tri(array, type='upper', diag=0)

Extracts the upper, lower, or both triangle elements of a 2D JAX array.

Argument Type Description
array 2D array A JAX 2D array.
type str A string indicating which part of the triangle to extract. It can be ‘upper’, ‘lower’, or ‘both’.
diag int Integer indicating if diagonal must be kept or not. diag=1 excludes the diagonal, diag=0 includes it.

Returns

  • If argument type is ‘upper’, ‘lower’, it return a 1D JAX array containing the requested triangle elements.
  • If argument type is ‘both’, it return a 2D JAX array containing the the first column the lower triangle and in the second ecolumn the upper triangle

m.net.indegree

m.net.indegree(m, normalize=False)

In-degree of each node: number of incoming ties (non-zero column entries).

Argument Type Description
m jax.Array Adjacency (or weight) matrix, shape (N, N); entry [i, j] is the tie from i to j.
normalize bool Divide by N - 1. Defaults to False.

Returns

  • jax.Array: In-degree per node, shape (N,).

m.net.indegree_jit

m.net.indegree_jit(x)

JIT-compiled in-degree: number of non-zero entries in each column of x.

m.net.instrength

m.net.instrength(m)

In-strength of each node: sum of the weights of its incoming ties (column sums).

Argument Type Description
m jax.Array Weight matrix, shape (N, N); entry [i, j] is the tie from i to j.

Returns

  • jax.Array: In-strength per node, shape (N,).

m.net.instrength_jit

m.net.instrength_jit(x)

JIT-compiled in-strength: column sums of the weight matrix x.

m.net.is_symmetric

m.net.is_symmetric(arr, rtol=1e-05, atol=1e-08)

Efficiently check if a 2D array is symmetric using JIT compilation.

Parameters arr : jax.numpy.ndarray Input 2D array to check for symmetry rtol : float, optional Relative tolerance for comparison (default: 1e-5) atol : float, optional Absolute tolerance for comparison (default: 1e-8)

Returns bool True if the array is symmetric, False otherwise

m.net.logit

m.net.logit(x)

Computes the logit transformation.

Argument Type Description
x float or array-like Input value(s) in the range (0, 1).

Returns

  • float or array-like: The logit-transformed value(s): log(x / (1 - x)).

m.net.mat_to_edgl

m.net.mat_to_edgl(mat)

Convert a matrix to an edge list.

Argument Type Description
mat 2D array A JAX 2D array.

Returns

  • 2D array: return and edgelist of all dyads combination (excluding diagonal).
  • First column represent the value fo individual i in the first column of argument sr, the second column the value of j in the second column of argument sr

m.net.nodal_fixed_effects

m.net.nodal_fixed_effects(
    design_fixed,
    num_fixed,
    prior_mu=0.0,
    prior_sigma=2.5,
    sample=False,
    name='beta_fixed',
)

Sample fixed nodal effects and return their predictor contribution.

Argument Type Description
design_fixed jax array Design matrix of shape (num_rows, num_fixed).
num_fixed int Number of fixed predictors.
prior_mu float Prior mean for coefficients. Defaults to 0.0.
prior_sigma float Prior SD for coefficients. Defaults to 2.5.
sample bool Draw from prior (DGP mode) vs declare latent variable. Defaults to False.
name str Name for the sampled site. Defaults to ‘beta_fixed’.

Returns

  • jax array: Predictor contribution of shape (num_rows,).

m.net.nodal_random_effects

m.net.nodal_random_effects(
    design_random,
    random_group_index,
    num_random,
    num_random_groups,
    prior_mean_mu=0.0,
    prior_mean_sigma=1.0,
    prior_std_sigma=1.0,
    centered=False,
    sample=False,
    name='beta_random',
)

Sample hierarchical random nodal effects and return predictor contribution.

Argument Type Description
design_random jax array Design matrix of shape (num_rows, num_random).
random_group_index jax int array 1-based group membership per random effect, shape (num_random,).
num_random int Number of random effect levels (e.g. number of nodes).
num_random_groups int Number of groups (e.g. sex categories).
prior_mean_mu float Prior mean for group-level means. Defaults to 0.0.
prior_mean_sigma float Prior SD for group-level means. Defaults to 1.0.
prior_std_sigma float Half-normal scale for group-level SDs. Defaults to 1.0.
centered bool Use centered parameterization. Preferred for undirected networks where u_i + u_j shift non-identifiability causes non-centered mode-switching. Non-centered (default) is better for directed networks. Defaults to False.
sample bool Draw from prior (DGP mode) vs declare latent variable. Defaults to False.
name str Base name for sampled sites. Defaults to ‘beta_random’.

Returns

  • jax array: Predictor contribution of shape (num_rows,).

m.net.node_effects_to_dyadic_format

m.net.node_effects_to_dyadic_format(sr_effects)

Convert node effects to dyadic (edge list) format.

Argument Type Description
sr_effects jax array Array of node effects with shape [N_nodes, 2].

Returns: jax array: Dyadic effects with shape [N_dyads, 2], where each row represents a dyad (i, j) with sender effect i and receiver effect j.

m.net.nodes_random_effects

m.net.nodes_random_effects(
    N_id,
    sr_sigma_mu=0,
    sr_sigma_sd=2.5,
    cholesky_dim=2,
    cholesky_density=2.5,
    sample=False,
)

Correlated sender and receiver random effects for each node (non-centred).

Defines sr_raw ~ Normal(0, 1), sr_sigma ~ TruncatedNormal(mu, sd, low=0) and sr_L ~ LKJCholesky, and returns sr_rf = (diag(sr_sigma) sr_L sr_raw)^T.

Argument Type Description
N_id int Number of nodes.
sr_sigma_mu float Location of the prior on the two standard deviations. Defaults to 0.
sr_sigma_sd float Scale of that prior. Defaults to 2.5.
cholesky_dim int Dimension of the correlation matrix (2: sender, receiver).
cholesky_density float LKJ concentration; larger values favour weak correlations. Defaults to 2.5.
sample bool Draw values directly instead of defining model sites.

Returns

  • (sr_rf, sr_raw, sr_sigma, sr_L); sr_rf has shape (N_id, 2)
  • with sender effects in column 0 and receiver effects in column 1.

m.net.nodes_terms

m.net.nodes_terms(
    sender_predictors=None,
    receiver_predictors=None,
    s_mu=0,
    s_sd=1,
    r_mu=0,
    r_sd=1,
    sample=False,
)

Fixed effects of node predictors on sending and receiving ties.

Argument Type Description
sender_predictors 2D jax array Node predictors of sending, shape (N, K_s); each column is a node characteristic.
receiver_predictors 2D jax array Node predictors of receiving, shape (N, K_r). At least one of the two must be given.
s_mu float Prior mean of the sender coefficients. Defaults to 0.
s_sd float Prior sd of the sender coefficients. Defaults to 1.
r_mu float Prior mean of the receiver coefficients. Defaults to 0.
r_sd float Prior sd of the receiver coefficients. Defaults to 1.
sample bool Draw values directly instead of defining model sites.

Returns

  • (terms, sender_effects, receiver_effects); terms has shape
  • N, 2: the linear predictor of sending (column 0) and receiving (column 1).

m.net.normalize

m.net.normalize(m)

Divide a node-level measure by the maximum possible degree, N - 1.

Argument Type Description
x jax.Array Node-level values, shape (N,).
m jax.Array The network’s adjacency matrix, shape (N, N).

Returns

  • jax.Array: x / (N - 1).

m.net.onnela_clustering_coefficient

m.net.onnela_clustering_coefficient(mat)

Weighted clustering coefficient (Onnela et al., 2005).

This is the definition NetworkX computes via nx.clustering(G, weight=...). Unlike clustering_coefficient (which binarizes the input), it uses the geometric mean of each triangle’s edge weights, so weak edges contribute weakly:

w_hat = mat / max(mat)                        # scale by max weight
tri_i = sum_{j,k} (w_hat_ij w_hat_jk w_hat_ki) ** (1/3)
      = diag( cbrt(w_hat) @ cbrt(w_hat) @ cbrt(w_hat) )_i
cc_i  = tri_i / (deg_i * (deg_i - 1))         # deg = unweighted degree

The result is bounded in [0, 1] and reduces to the unweighted clustering coefficient when all edge weights are equal. Assumes a zero diagonal (no self-loops), matching NetworkX. JIT-compatible.

m.net.outdegree

m.net.outdegree(m, normalize=False)

Out-degree of each node: number of outgoing ties (non-zero row entries).

Argument Type Description
m jax.Array Adjacency (or weight) matrix, shape (N, N); entry [i, j] is the tie from i to j.
normalize bool Divide by N - 1. Defaults to False.

Returns

  • jax.Array: Out-degree per node, shape (N,).

m.net.outdegree_jit

m.net.outdegree_jit(x)

JIT-compiled out-degree: number of non-zero entries in each row of x.

m.net.outstrength

m.net.outstrength(m)

Out-strength of each node: sum of the weights of its outgoing ties (row sums).

Argument Type Description
m jax.Array Weight matrix, shape (N, N); entry [i, j] is the tie from i to j.

Returns

  • jax.Array: Out-strength per node, shape (N,).

m.net.outstrength_jit

m.net.outstrength_jit(x)

JIT-compiled out-strength: row sums of the weight matrix x.

m.net.prepare_dyadic_effect

m.net.prepare_dyadic_effect(dyadic_effect_mat)

Prepare dyadic effect matrix for processing.

Argument Type Description
dyadic_effect_mat jax array Dyadic effect matrix to process.

Returns

  • jax array: Processed dyadic effects in edge list format.

m.net.sender_receiver

m.net.sender_receiver(
    sender_predictors=None,
    receiver_predictors=None,
    s_mu=0,
    s_sd=2.5,
    r_mu=0,
    r_sd=2.5,
    sr_sigma_mu=0,
    sr_sigma_sd=2.5,
    cholesky_dim=2,
    cholesky_density=2.5,
    sample=False,
)

Compute sender-receiver effects combining both fixed and random effects.

Argument Type Description
sender_predictors jax array Predictors for focal individuals.
receiver_predictors jax array Predictors for target individuals.
s_mu float Mean for focal effects. Defaults to 0.
s_sd float SD for focal effects. Defaults to 1.
r_mu float Mean for target effects. Defaults to 0.
r_sd float SD for target effects. Defaults to 1.
sr_mu float Mean for random effects. Defaults to 0.
sr_sd float SD for random effects. Defaults to 1.
sr_sigma_mu float Rate parameter for random effects. Defaults to 0.
sr_sigma_sd float Rate parameter for random effects. Defaults to 1.
cholesky_dim int Dimension for Cholesky decomposition. Defaults to 2.
cholesky_density int Density parameter for Cholesky. Defaults to 2.
sample bool Whether to sample from distributions. Defaults to False.

Returns

  • jax array: Combined dyadic effects.

m.net.single_source_dijkstra

m.net.single_source_dijkstra(m, src)

Computes the shortest path from a source node to all other nodes in a weighted graph using Dijkstra’s algorithm.

m.net.strength

m.net.strength(m, sym=False)

Strength (sum of tie weights) of each node.

Argument Type Description
m jax.Array Weight matrix, shape (N, N); entry [i, j] is the tie from i to j.
sym bool The network is symmetric (undirected): count each tie once, i.e. return the out-strength. Defaults to False (out-strength + in-strength).

Returns

  • jax.Array: Strength per node, shape (N,).

m.net.strength_jit

m.net.strength_jit(x)

JIT-compiled total strength: out-strength + in-strength of x.

m.net.to_binary_matrix

m.net.to_binary_matrix(m)

Binarise a weight matrix: 1 where the weight is positive, 0 elsewhere.

Argument Type Description
m jax.Array Weight matrix.

Returns

  • jax.Array: Integer matrix of 0s and 1s with the same shape.

m.net.triangles_and_degree

m.net.triangles_and_degree(adj_matrix)

Computes the number of triangles and the degree for each node in a graph. This function is optimized for JAX and is JIT-compatible.

m.net.vec_node_to_edgle

m.net.vec_node_to_edgle(sr)

Pair node-level values into dyads (upper triangle, i < j).

Argument Type Description
sr 2D array Node values, shape (N, 2): column 0 is the value used for the first node of a dyad, column 1 for the second.

Returns

  • 2D array: Shape (N*(N-1)/2, 2); row (i, j) holds sr[i, 0] and sr[j, 1].

m.net.vec_to_edgl

m.net.vec_to_edgl(vec)

Convert a vector to an edge list.

Argument Type Description
vec 1D array A JAX 1D array.

Returns

  • 2D array: return and edgelist of all dyads combination (excluding diagonal).
  • First column represent the value fo individual i in the first column of argument sr, the second column the value of j in the second column of argument sr

m.net.vec_to_mat

m.net.vec_to_mat(vec, shape=())

Convert a vector to a matrix.

Argument Type Description
vec 1D array A JAX 1D array.
shape tuple A tuple indicating the shape of the matrix.

Returns

  • 2D array: return a matrix of shape shape.

m.net.weighted_cc

m.net.weighted_cc(m, nodes=None)

Weighted local clustering coefficient (Onnela et al. 2005) of each node.

Same as cc(m, nodes, weighted=True).

Argument Type Description
m jax.Array Weight matrix, shape (N, N).
nodes array of int Return only these nodes (default: all).

Returns

  • jax.Array: Weighted clustering coefficient per node, in [0, 1].