Null Models

Most segregation and polarization measures contain a null model that compares the excess polarization in the observed network. The most basic example can be given from Freeman’s segregation index, which calculates the excess ratio of cross-group tie density. Most of the measures assume a random graph with the same edge density as the observed network to quantify the excess polarization. If a measure contains a null model, it basically aims to return 0 when the observed network’s segregation is similar to a random network with the same edge density.

netseg allows picking your own null models, adjusting the null model of the original metric, or adding a null model difference calculation. These null models might contain graphs with a similar degree distribution (Salloum, 2024) or counterfactual simulations directly generated from a statistical model such as an Exponential Random Graph Model (Duxbury, 2023).

The following lists the measures and indicates whether they inherently contain a null model:

Metric Name

Year

Contains a Null Model

Boundary Connectivity

2013

True

Random Walk Controversy

2018

False

Dipole Moment

2015

False

Freeman’s Segregation Index

1978

True

Krackhardt E-I

1988

False

Segregation Matrix Index

1997

False

Coleman’s Homophily Index

1958

True

GAM Index

1989

True

ORWG

2001

False

Spectral Segregation Index

2007

False

Assortativity

2003

True

Moran’s I

1950

True

If a metric contains a null model, netseg measures the score in the given null model list and changes the value accordingly; if it does not contain a null model, netseg directly returns the excess amount of segregation compared to a null model. netseg explicitly avoids double subtraction that subtracts a null model’s score from a metric with a null model.

Inherited Null Models

This section discusses what it means for a metric to carry a null model. We do not redefine the metrics in full here. Instead we examine the null model each one inherits from its original definition, so as to justify whether a supplied ensemble should replace that inherited null model or instead be subtracted from the observed score.

The distinction rests on separability. If a metric compares its observed quantity against an expected value that is a separable, recomputable term (a quantity you evaluate on a graph), the ensemble replaces that term and the metric returns the average over the ensemble. If the inherited reference is not a recomputable term (for instance an additive constant), the ensemble is subtracted from the observed score. As shown below, when the inherited null is an additive constant these two operations coincide.

Boundary Connectivity

Boundary Connectivity is defined as (Guerra, 2013):

\[P = \frac{1}{|B|} \sum_{v \in B} \left[ \frac{d_i(v)}{d_b(v) + d_i(v)} - 0.5 \right]\]

where \(d_i(v)\) is the number of internal edges of node \(v\), \(d_b(v)\) is the number of its cross-boundary edges, and \(B\) is the set of boundary nodes.

The inherited null model is the additive constant \(0.5\). It encodes the expectation that, absent polarization, a boundary node splits its ties evenly between its own group and the opposing group, so the balance \(d_i / (d_b + d_i)\) centers on \(0.5\). Subtracting \(0.5\) recenters the no-polarization case at \(0\).

This constant is an inherited reference, but it is not a recomputable graph-level quantity. There is no term to evaluate on an ensemble graph in the way one recomputes, say, an expected edge count. It is a fixed scalar. A supplied ensemble therefore substitutes an empirical center for the analytic \(0.5\): for each null graph \(g\) in the ensemble we compute the mean boundary balance \(\bar{b}(g)\) and average these to obtain \(\mathbb{E}[\bar{b}]\). Because the inherited null is additive, replacing the constant and subtracting the ensemble score are the same operation:

\[\left( \bar{b}_{\text{obs}} - 0.5 \right) \quad \longrightarrow \quad \bar{b}_{\text{obs}} - \mathbb{E}[\bar{b}]\]

The \(0.5\) drops out entirely, replaced by the data-driven expectation. Under the hood netseg computes the boundary connectivity balance of each null graph in the ensemble, averages these, and subtracts that mean from the observed balance. The user receives this exact difference if null_models argument is supplied.

Two consequences follow. First, the range of the metric changes after subtraction: the analytic form is bounded on roughly \([-0.5, 0.5]\), whereas the ensemble-adjusted form is bounded by the observed and expected balances and is no longer centered on a fixed constant. Second, the empirical centering absorbs any bias in the balance estimate (for example from low-degree boundary nodes) because the same computation applies to observed and null graphs alike, which the fixed \(0.5\) does not.

Random Walk Controversy

Random Walk Controversy is defined for two groups as (Garimella, 2018):

\[\text{RWC} = C_{00} \, C_{11} - C_{01} \, C_{10}\]

where \(C\) is the column-normalized walk matrix. The entry \(C_{ij}\) is the conditional probability that a walk started in group \(i\), given that it terminated on an influential node of group \(j\). Walks originate from non-influential nodes, one start group drawn with equal probability, and terminate on first contact with an influential node. netseg generalizes the two-group form to \(K\) groups by two strategies, individual (the full \(K \times K\) matrix, product of the diagonal minus the product of the off-diagonal) and ovso (one-vs-others, collapsing to a \(2 \times 2\) matrix per focal group and averaging), but the null model question is the same for both.

Unlike Boundary Connectivity, RWC carries no inherited null model. The statistic is a difference of empirical probability products read directly off the walk matrix. There is no expected-value term inside the formula, separable or otherwise, and in particular no additive constant analogous to the \(0.5\) of Boundary Connectivity. Nothing in \(C_{00} C_{11} - C_{01} C_{10}\) is a baseline recomputed from a graph.

It is worth being explicit about why this metric admits no analytic baseline that one could subtract in closed form. One might expect that measuring RWC on a random graph yields a fixed reference level. It does not. For balanced groups on an unstructured graph the walk mixes freely, so \(C_{ij} \approx 0.5\) for all \(i, j\) and \(\text{RWC} \approx 0.25 - 0.25 = 0\). But this near-zero level is not a constant of the formula. It is a product of the walk dynamics, the group sizes, the degree sequence, and the choice of influential nodes. Under unequal group sizes or heterogeneous degrees the expected level drifts off zero, and it does so as a function of structure that cannot be written down as a separable term. The baseline is therefore not analytically available, and only a matched ensemble can supply it. For this metric subtraction is not merely the default treatment for a metric without an inherited null. It is the only coherent correction, because there is no fixed reference to replace.

Accordingly, when an ensemble is supplied, netseg computes RWC on each null graph and returns

\[\text{RWC}_{\text{obs}} - \mathbb{E}[\text{RWC}_{\text{null}}]\]

the observed score minus the mean over the ensemble.

The influential nodes are central to RWC and the way they are specified changes the null hypothesis the ensemble encodes. Two paths exist, and they are mutually exclusive: supplying k_top (an integer), or supplying influential_nodes (an explicit list of vertex IDs). Passing both raises an error.

If k_top is used, the influential nodes are re-derived on every graph as its own \(k\) highest-degree nodes. On each null graph in the ensemble the selection is recomputed from that graph’s own degrees. The null then asks whether the observed controversy exceeds what the ensemble produces when each rewired graph is allowed its own hubs.

If influential_nodes is supplied as an explicit list, those same vertex IDs are held fixed across the observed graph and every null graph. The k_top selection does not run in this case, on the observed graph or on any null graph. The null then asks whether the observed controversy exceeds what the ensemble produces for the same fixed set of actors under rewired topology. This is a different and often stricter null, and the user should choose deliberately between the two. The walk start nodes are likewise held fixed across the ensemble, so the correction varies topology while holding the group of origin constant.

Dipole Moment

The Dipole Moment is defined as (Morales, 2015):

\[\text{dipole} = (1 - \Delta A)\, d\]

with

\[\Delta A = \frac{|V^{+} - V^{-}|}{|V|}, \qquad d = \frac{|\bar{gc}^{+} - \bar{gc}^{-}|}{2}\]

where the opinion vector \(x \in [-1, 1]^{|V|}\) is obtained by fixing the influential nodes at \(\pm 1\) by group and running the propagation to convergence. \(V^{+}\) and \(V^{-}\) are the counts of nodes with positive and negative opinion, and \(\bar{gc}^{+}\), \(\bar{gc}^{-}\) are the mean opinions of the positive and negative camps. The term \(d\) measures how far apart the two poles sit and \(1 - \Delta A\) penalizes imbalance between the camp sizes, so the product peaks when the network splits into two equal and oppositely signed halves.

Like Random Walk Controversy, the Dipole Moment carries no inherited null model. It is a raw functional of the converged opinion vector, a product of two descriptive quantities each read directly off \(x\). There is no expected-value term inside the formula, no separable baseline, and no additive constant of the kind Boundary Connectivity subtracts. The classification is therefore the same as for RWC: with no inherited null to replace, a supplied ensemble is subtracted from the observed score,

\[\text{dipole}_{\text{obs}} - \mathbb{E}[\text{dipole}_{\text{null}}].\]

There is a further reason subtraction is the correct treatment here, and it is specific to how the metric is computed. The propagation from the \(\pm 1\) seeds produces a nonzero opinion spread even on an unstructured graph, so \(d > 0\) and the two camps are usually near balanced (\(1 - \Delta A \approx 1\)). The raw dipole is therefore positive in the absence of any real polarization, and the size of that positive offset depends on the degree sequence, the group sizes, and the influential-node configuration filtered through the propagation dynamics. This offset is not a constant one could write down and remove analytically. Only a matched ensemble recovers it. Subtraction is thus not merely the default for a metric without an inherited null; it corrects a structure-dependent positive bias that no fixed reference could capture.

As with RWC, the way the influential nodes are specified sets the null hypothesis, and the two paths are mutually exclusive.

If k_top is used, the influential nodes are re-derived on every null graph as that graph’s own \(k\) highest-degree nodes. The null asks whether the observed dipole exceeds what the ensemble produces when each rewired graph is allowed its own hubs.

If influential_nodes is supplied as an explicit list, that same fixed set is reused on every null graph, and the k_top selection does not run on any graph. The null then asks whether the observed dipole exceeds what the ensemble produces for the same fixed set of actors under rewired topology. The two nulls answer different questions and the user should choose deliberately between them.

Because the explicit path holds vertex IDs fixed across the ensemble, those IDs must refer to the same actors in every null graph. Ensembles that preserve the node set and its ordering (degree-preserving rewiring, edge swaps, configuration models on the same vertex set) satisfy this. An ensemble whose graphs relabel or resize the vertex set does not, and the fixed IDs would then no longer denote the intended nodes.

Freeman’s Segregation Index

Freeman’s index is defined as (Freeman, 1978; multi-group form in Bojanowski & Corten, 2014):

\[S_{\text{Freeman}} = 1 - \frac{p}{\pi}\]

where \(p\) is the observed fraction of between-group ties,

\[p = \frac{\sum_{i,j\,:\,t_i \neq t_j} x_{ij}}{\sum_{i,j} x_{ij}},\]

and \(\pi\) is the fraction of between-group ties expected under random tie formation with the same group sizes. In the analytic case this expectation is that of an Erdős–Rényi graph,

\[\pi = \frac{\left(\sum_k n_k\right)^2 - \sum_k n_k^2}{N(N-1)}.\]

Unlike the previous metrics, Freeman’s index carries an inherited null model, and it is separable: \(\pi\) is an isolated term standing for the expected between-group tie fraction under a baseline. The index compares the observed \(p\) against this single expected quantity. Because \(\pi\) isolates cleanly, a supplied ensemble replaces it, which is the treatment the design principle prescribes for a separable inherited null.

When an ensemble is supplied, netseg computes the between-group tie fraction on each null graph,

\[p^{(g)} = \frac{\text{between-group edges in } g}{\text{total edges in } g},\]

averages these to obtain \(\hat{\pi} = \mathbb{E}[p^{(g)}]\), and returns

\[1 - \frac{p_{\text{obs}}}{\hat{\pi}}.\]

The analytic \(\pi\) is not used in this case. The ensemble defines the baseline in full, which is the reason for supplying null models in the first place.

It is important that the replaced quantity is the between-group tie fraction and not the overall density. The two coincide only for an Erdős–Rényi ensemble. For a density-preserving ensemble (configuration model, degree-preserving rewiring, edge swaps) the overall density is fixed at the observed value by construction, so a baseline built from density alone would not move the score and the ensemble would have no effect. The between-group fraction does move under such rewiring, because rewiring changes how many ties fall across groups even when the edge count is held fixed. Replacing \(\pi\) with the ensemble’s mean between-group fraction is therefore what makes a degree-preserving null meaningful for this metric.

Krackhardt’s E-I Index

The E-I Index is defined as (Krackhardt & Stern, 1988):

\[S_{\text{EI}} = \frac{EL - IL}{EL + IL}\]

where \(EL\) is the number of external (between-group) edges and \(IL\) the number of internal (within-group) edges. The index runs from \(-1\) (all ties internal) to \(+1\) (all ties external).

The E-I Index carries no inherited null model. It is a raw ratio of edge counts with no expected-value term and no additive constant. With nothing to replace, a supplied ensemble is subtracted from the observed score.

netseg computes the full E-I Index on each null graph, averages these, and returns

\[S_{\text{EI, obs}} - \mathbb{E}[S_{\text{EI, null}}].\]

Spectral Segregation Index

The Spectral Segregation Index is defined as (Echenique & Fryer, 2007; multi-group treatment in Bojanowski & Corten, 2014). Let \(R = D^{-1}A\) be the row-normalized adjacency of the whole graph, let \(R^{(t)}\) be its submatrix on the members of group \(t\), and let \(C\) be the block of \(R^{(t)}\) for one connected component of the within-group subgraph. With \(\lambda\) the dominant eigenvalue of \(C\) and \(v\) its eigenvector, the score of node \(i\) in that component is

\[\text{SSI}_i = \lambda \, \frac{v_i}{\bar{v}}, \qquad \bar{v} = \frac{1}{n_c}\sum_{j} v_j .\]

Because \(R\) is normalized by full degree before restriction, the rows of \(R^{(t)}\) do not sum to one; the deficit is the share of ties leaving the group, which is what makes \(\lambda\) a segregation quantity rather than a property of the induced subgraph alone.

The SSI carries no inherited null model. It is a raw functional of the within-group ties, with no expected-value term and no additive constant of the kind Boundary Connectivity subtracts; the lower bound of \(0\) is a property of the spectrum, not a baseline already removed. A supplied ensemble is therefore subtracted. As with the Dipole Moment there is a second reason subtraction is correct here: the ratio \(v_i / \bar{v}\) is defined relative to the component a node falls in, so the score depends on how the group fragments under rewiring. That offset is a function of the degree sequence and group sizes filtered through the component structure and cannot be written as a separable term, so only a matched ensemble recovers it.

The subtraction is performed at the node level: netseg averages the null graphs’ score vectors element-wise and returns \(\text{SSI}_i - \mathbb{E}[\text{SSI}^{(g)}_i]\), reporting the mean of these differences when aggregate=True. At the network level this agrees with the aggregate-first ordering, but only the node-level convention yields the per-node deviations returned by aggregate=False. Two consequences follow. Node identity is load-bearing across the ensemble, as on the explicit influential_nodes path of the Dipole Moment, so the ensemble must preserve the vertex set and its ordering; degree-preserving rewiring, edge swaps, and configuration models on the same vertex set satisfy this, while ensembles that relabel or resize the vertex set do not. And isolates score \(0\) on the observed graph and on every null graph, so they contribute exactly \(0\) after subtraction rather than depressing the network mean as they do in the raw form.

Segregation Matrix Index

The Segregation Matrix Index is defined per group as (Fershtman, 1997; multi-group treatment in Bojanowski & Corten, 2014). Writing \(d_{gh}\) for the density of ties between groups \(g\) and \(h\), the score of group \(g\) is

\[\text{SMI}_g = \frac{d_{gg} - \sum_{h \neq g} d_{gh}}{d_{gg} + \sum_{h \neq g} d_{gh}} .\]

The original formulation contrasts a group’s internal density with the density of its ties to the single remaining group; netseg generalizes this by summing over all \(h \neq g\).

The SMI carries no inherited null model. It is a normalized difference of two observed densities, structurally the E-I Index with densities in place of raw edge counts, and contains no expected-value term and no additive constant. A supplied ensemble is therefore subtracted. The density normalization is not a baseline: the clique matrix it divides by is the maximum possible number of ties given the group sizes, computed from membership alone and hence identical on the observed graph and on every null graph. The score sits at zero when within- and between-group densities coincide, which they do in expectation under an Erdős–Rényi graph, so the ensemble buys little against that null. It buys a great deal against a degree-preserving one, where heterogeneous degrees correlated with group membership pull the block densities apart at fixed edge count.

The subtraction is performed at the group level: netseg computes the per-group vector on each null graph, averages element-wise, and returns the aligned difference, reporting its mean across groups when aggregated=True. Group identity is therefore load-bearing. The membership vector is held fixed and applied unchanged to every null graph, so the ensemble must preserve the vertex set and its ordering; degree-preserving rewiring, edge swaps, and configuration models on the same vertex set satisfy this, while ensembles that relabel or resize the vertex set do not. Groups of a single node have an undefined internal density when loops=False and yield \(\text{NA}\); these are dropped from the aggregate, and the warning issued at call time flags the omission. Setting loops=True avoids it.

Coleman’s Homophily Index

Coleman’s index is defined per group as (Coleman, 1958; multi-group treatment in Bojanowski & Corten, 2014). Let \(\omega_g = M_{gg}\) be the ties group \(g\) sends to itself, \(\eta_g = \sum_h M_{gh}\) the total ties it sends, and \(\omega_g^{*}\) the number of within-group ties expected under random choice of targets,

\[\begin{split}\omega_g^{*} = \eta_g \, \frac{n_g - 1}{N - 1}, \qquad S_g = \begin{cases} \dfrac{\omega_g - \omega_g^{*}}{\eta_g - \omega_g^{*}}, & \omega_g \geq \omega_g^{*} \\[2ex] \dfrac{\omega_g - \omega_g^{*}}{\omega_g^{*}}, & \omega_g < \omega_g^{*} \end{cases}\end{split}\]

The two branches normalize by the room remaining above and below the expectation, which fixes the range at \([-1, 1]\). With network_level=True the same construction is applied to the summed quantities \(\Omega = \sum_g \omega_g\) and \(\Omega^{*} = \sum_g \omega_g^{*}\).

Coleman’s index carries an inherited null model, and it is separable: \(\omega_g^{*}\) is an isolated expected-value term, the within-group tie count of a graph in which each group’s ties are distributed at random over the remaining nodes while its out-degree total is held fixed. A supplied ensemble replaces it. netseg takes the subgraph induced on group \(g\) in each null graph, counts its edges, averages across the ensemble to obtain \(\hat{\omega}_g^{*}\), and evaluates \(S_g\) with that estimate in place of the analytic term. The analytic \((n_g - 1)/(N - 1)\) expression is not used in this case, and the ensemble defines the baseline in full. Note that replacement here does not reduce to subtraction, as it did for Boundary Connectivity: \(\omega_g^{*}\) enters the numerator and the denominator of a ratio, and the branch condition depends on its value, so substituting the term is not the same operation as shifting the finished score.

That branch condition is the one place where an ensemble estimate behaves differently from the analytic term. \(\hat{\omega}_g^{*}\) carries sampling noise, so a group sitting near \(\omega_g \approx \omega_g^{*}\) can fall on either side of the boundary and be normalized by a different denominator, which makes the score of such groups unstable across ensembles and asymmetric in a way the analytic form is not. Enlarging the ensemble is the remedy. Two further points constrain the choice of ensemble. The margin \(\eta_g\) is not replaced; it is read from the observed graph and combined with \(\hat{\omega}_g^{*}\), so ensembles that preserve group-level out-degree — degree-preserving rewiring, edge swaps, configuration models on the same vertex set — keep the numerator and denominator on a common footing, while ensembles that do not leave the two inconsistent. And because groups are addressed by the fixed membership vector applied unchanged to every null graph, the ensemble must preserve the vertex set and its ordering.

A point made in the metrics documentation bears repeating here, because it follows directly from what the ensemble replaces. netseg allows custom null models, but in Coleman’s case the selection should be evaluated carefully, since the metric is designed for the ER model only. The ensemble is read through \(\omega_g^{*}\) alone, a count of within-group edges; nothing about the null graphs’ cross-group structure enters the index. Two ensembles differing only in their between-group density therefore return identical scores. Because the index is calculated differently according to the relationship between \(\omega\) and \(\omega^{*}\), only when \(\omega \geq \omega^{*}\) can an SBM act as a null model. Generating null networks with \(P_{\text{Null,Self}} = 0.5\) and \(P_{\text{Null,Other}} = 0.1\) shows this insensitivity directly: the index reaches \(0\) where the realized within-group edge count equals the null’s, which is the \(P_{\text{self}} = 0.5\) threshold, and below that threshold altering the cross-group edges leaves the score unmoved.

The Gupta-Anderson-May Index

The GAM index is defined as (Gupta, Anderson & May, 1989; multi-group treatment in Bojanowski & Corten, 2014). Let \(p_{gh} = m_{gh} / m_{g+}\) be the proportion of group \(g\)’s ties running to group \(h\), and \(K\) the number of groups:

\[S_{\text{GAM}} = \frac{\sum_{g} \lambda_g - 1}{K - 1} = \frac{\sum_{g} p_{gg} - 1}{K - 1},\]

where the \(\lambda_g\) are the eigenvalues of \([p_{gh}]\). netseg evaluates the trace directly, the two being equal for a square matrix. The index runs from \(-1/(K-1)\) under maximal disassortativity to \(1\) when every group’s ties are internal.

The GAM index carries an inherited null model: the additive constant \(1\), which is the diagonal sum under proportionate mixing, the pattern in which the rows of \([p_{gh}]\) are identical. That constant is an inherited reference but not a recomputable graph-level quantity, so as with Boundary Connectivity a supplied ensemble is subtracted. Because the constant is additive and the \(K-1\) divisor is fixed by membership and shared across graphs, subtraction and replacement coincide: the \(1\) cancels and the ensemble’s mean diagonal sum takes its place. netseg computes the full index on each null graph, averages, and returns the difference.

The empirical center is worth preferring because proportionate mixing is an idealization finite graphs do not attain: a complete graph on sixty nodes split into groups of ten, twenty and thirty returns \(-0.017\) rather than \(0\), since excluding self-loops leaves the rows of \([p_{gh}]\) not quite identical. An ensemble absorbs that offset and any bias from degree heterogeneity, the same normalization applying to observed and null graphs alike. Note that membership is held fixed and applied unchanged to every null graph, so the ensemble must preserve the vertex set and its ordering, and \(K\) is taken from membership rather than from the graphs, so a null graph in which some group has no ties yields a zero row margin rather than a smaller matrix.

Odds-Ratio for Within-Group Ties

The ORWG is defined as (Moody, 2001, after Charles & Grusky, 1995). Collapsing all dyads into a \(2 \times 2\) table of dyad type against tie presence, let \(m_{gg1}\) and \(m_{gg0}\) be the within-group dyads that are and are not tied, and \(m_{gh1}\), \(m_{gh0}\) the same for between-group dyads. The index is the ratio of the two odds,

\[\text{ORWG} = \frac{m_{gg1} / m_{gg0}}{m_{gh1} / m_{gh0}} = \frac{m_{gg1} \, m_{gh0}}{m_{gg0} \, m_{gh1}},\]

reported on the log scale by default. Untied dyad counts come from the complement of the mixing matrix against the clique matrix \(n_g n_h\), with the diagonal \(n_g(n_g - 1)\) when loops=False.

The ORWG carries no inherited null model. Like the E-I Index and the SMI it contrasts two quantities both read off the observed graph, and its neutral value of one is a property of the odds-ratio scale rather than an expectation subtracted inside the formula. A supplied ensemble is therefore subtracted. That the neutral point is analytically known does not make the ensemble redundant: it marks independence between dyad type and tie presence, not what a degree-preserving rewiring of the observed graph would produce, and degree heterogeneity correlated with group membership displaces the ensemble away from one at fixed edge count.

The contrast is taken on the log scale, netseg returning \(\log \text{ORWG}_{\text{obs}} - \mathbb{E}[\log \text{ORWG}_{\text{null}}]\), equivalently the log of the observed odds ratio over the ensemble’s geometric mean. This is the appropriate scale for a ratio: departures from the neutral point are symmetric only under multiplication, so an ensemble containing offsetting deviations of \(2\) and \(0.5\) averages to \(1\) geometrically but to \(1.25\) arithmetically. The sampling distribution of an odds ratio is also right-skewed and floored at zero, so an arithmetic ensemble mean drifts above one even for null graphs with no group structure, most visibly on small or sparse ensembles, and subtracting an inflated baseline would bias every adjusted score downward. Setting log_transform=False exponentiates the contrast back to a ratio rather than returning a difference. One consequence of averaging per graph: a null graph with no within-group ties sends its log odds ratio to \(-\infty\), so such graphs contribute \(\text{NA}\) and are dropped from the ensemble mean. Sparse ensembles should be checked for how often this occurs, since a baseline estimated from a small surviving subset is unreliable. membership is held fixed across the ensemble, so the vertex set and its ordering must be preserved.

Assortativity Coefficient

The assortativity coefficient is defined as (Newman, 2003). Let \(e_{gh}\) be the fraction of edges running from group \(g\) to group \(h\), with margins \(a_g = \sum_h e_{gh}\) and \(b_g = \sum_h e_{hg}\). The coefficient is

\[r = \frac{\sum_g e_{gg} - \sum_g a_g b_g}{1 - \sum_g a_g b_g} .\]

It reaches \(1\) when every edge falls within a group and \(0\) when the within-group edge fraction matches its expectation.

The assortativity coefficient carries an inherited null model, and it is separable. The term \(\sum_g a_g b_g\) is the within-group edge fraction expected when edge endpoints are paired at random subject to the observed distribution of stubs across groups, that is, a configuration-model expectation that holds the degree sequence fixed. This is the strongest inherited null in the package: Freeman’s index assumes an Erdős–Rényi baseline and Coleman’s a random allocation of each group’s ties, whereas Newman’s is degree-preserving by construction. A supplied ensemble replaces the term. netseg computes the within-group edge fraction \(\sum_g e_{gg}^{(\text{null})}\) on each null graph, averages to obtain \(\hat{q}\), and returns

\[\frac{\sum_g e_{gg} - \hat{q}}{1 - \hat{q}} .\]

As with Coleman, replacement does not reduce to subtraction, since the expected term appears in both numerator and denominator.

Because the inherited null is already degree-preserving, a degree-preserving ensemble should reproduce the analytic coefficient rather than move it. On a homophilous graph of sixty nodes, rewiring gives \(\hat{q} = 0.490\) against an analytic \(\sum_g a_g b_g = 0.501\), and the coefficient reads \(0.506\) against \(0.495\); the residual gap is finite-ensemble noise. This is the natural check that an ensemble is behaving as intended, and it also indicates where supplying one is worthwhile: an ensemble earns its cost when it encodes a null the analytic term cannot express, such as one preserving triangle counts, block structure, or an exogenous constraint on which dyads may form ties. Reproducing the configuration model buys only sampling error. Note that \(\hat{q}\) enters the denominator, so an ensemble whose within-group fraction approaches one drives the coefficient toward an undefined limit, and that membership is held fixed across the ensemble, so the vertex set and its ordering must be preserved.

Moran’s I

Moran’s I measures autocorrelation of a continuous nodal attribute across a weighted graph. With \(w_{ij}\) the weight of the edge from \(i\) to \(j\), \(S_0 = \sum_{ij} w_{ij}\), and \(z_i = x_i - \bar{x}\),

\[I = \frac{N}{S_0} \cdot \frac{\sum_{ij} w_{ij} z_i z_j}{\sum_i z_i^2} .\]

The function returns the statistic along with its expected value, variance, \(z\) score and \(p\) value.

Supplying an ensemble here does something different from every other metric in this section. Elsewhere the ensemble changes the score. Here the score does not move at all: \(I\) is what it is. What the ensemble replaces is the reference distribution used to judge it. Without null models, netseg uses the randomization null, which shuffles the attribute across nodes while holding the graph fixed. That gives \(\mathbb{E}[I] = -1/(N-1)\), a closed-form variance, and a \(p\) value from the normal approximation. With null models, all four quantities come from the ensemble instead: the mean and sample variance of \(I\) across the null graphs, and an empirical two-sided \(p\) value with add-one smoothing.

The choice between them is a choice about what is being held fixed. Randomization fixes the graph and shuffles the attribute. The ensemble fixes the attribute and rewires the graph. Use the ensemble when the attribute is itself a product of network position, because randomization then compares against a world the attribute could not have come from. An example: on a Barabási–Albert graph of 200 nodes, an attribute unrelated to degree gives an ensemble mean of \(-0.006\) and a randomization expectation of \(-0.005\), so the two agree. Set the attribute to log degree and the observed \(I\) is \(0.369\) while the ensemble mean is \(0.464\). Randomization calls this strong positive autocorrelation; the degree-preserving ensemble says the observation sits below what degree structure alone produces. Same data, opposite sign on \(z\).

Three practical constraints. The attribute is held fixed across the ensemble, so every null graph needs the same node count and ordering as the observed graph — a count mismatch raises a ValueError, but a reordering does not and will silently misalign the attribute. At least two null graphs are needed, since the sample variance is otherwise undefined. And the empirical \(p\) value cannot go below \(1/(n+1)\), so an ensemble of 100 bottoms out near \(0.01\).

Examples

from netseg import boundary_connectivity
import igraph as ig 
def make_symmetric_sbm(p_in, p_out, n_groups, nodes_per_group, membership, **kwargs):
    pref_matrix = [
        [p_in if i == j else p_out for j in range(n_groups)] 
        for i in range(n_groups)
    ]
    block_sizes = [nodes_per_group] * n_groups
    g = ig.Graph.SBM(pref_matrix, block_sizes, **kwargs)
    
    g.vs['membership'] = membership
    
    return g 

membership = [0 if i < 100 else 1 for i in range(200)]
g_simple = make_symmetric_sbm(0.4, 0.03, 2, 100, membership )
bc_score_embedded_null = boundary_connectivity("membership", g_simple)
null_models = [make_symmetric_sbm(0.4, 0.03, 2, 100, membership ) for i in range(10)]
bc_score_similar_graphs = boundary_connectivity("membership", g_simple, null_models= null_models)
print("=" * 30)
print("BC Score with Embedded Null:", bc_score_embedded_null)
print("=" * 30)
print("BC Score with Similar Graphs as Null: ", bc_score_similar_graphs)
print("=" * 30)
==============================
BC Score with Embedded Null: 0.46549762535721495
==============================
BC Score with Similar Graphs as Null:  -0.0035322612611077275
==============================

Since we are giving similar graphs as an ensemble of null models, netseg returns a value of approximately zero.

Random Walk Controversy: For example RWC does not contain any null models, hence if an ensemble of graphs are given, netseg will calculate the difference between the given graphs’ RWC score and the observed network’s RWC score on average.

from netseg import random_walk_controversy

rwc_score_without_null = random_walk_controversy("membership", graph  = g_simple, maximum_walk_length= 1000, n_sim= 10000, k_top= 10, balanced= True)
rwc_score_similar_graphs = random_walk_controversy("membership", graph  = g_simple, maximum_walk_length= 1000, n_sim= 10000, k_top= 10, balanced= True, null_models=null_models)
print("=" * 30)
print("RWC Score with Embedded Null:", rwc_score_without_null)
print("=" * 30)
print("RWC Score with Similar Graphs as Null: ", rwc_score_similar_graphs)
print("=" * 30)
==============================
RWC Score with Embedded Null: 0.38069741977862753
==============================
RWC Score with Similar Graphs as Null:  -0.031161674907683068
==============================

This leads to the possibility of measuring segregation in counterfactual simulations. For example, if you have a network that might be formed due to a myriad of factors, you can create what-if scenarios to measure segregation with certain statistical network models (e.g., you can measure the contribution of triadic closure to the final segregation score (Duxbury, 2023) or homophily across different exogenous nodal attributes).

It is important to note that each graph in the ensemble will increase the calculation time for the metrics, since the metric itself needs to be calculated on the given null graph (\(M \times \text{Original Complexity of the Metric}\)). Currently, only Boundary Connectivity supports parallel computation; nonetheless, this approach is still experimental and is not useful for small graphs. It is recommended only for very large individual graphs. For an ensemble of many small-to-medium graphs, serial execution is typically much faster, since when utilizing multiprocessing, Python must package (pickle) the C-backed igraph objects to send them across process boundaries via Inter-Process Communication (IPC), and the worker processes must unpackage (unpickle) them. For a large ensemble of small-to-medium graphs, the memory overhead and time required to serialize and deserialize these objects vastly exceed the time saved by parallelizing the mathematical operations. Nonetheless, in the future, it might be implemented for certain other measures.

References

  • Bojanowski, M., & Corten, R. (2014). Measuring segregation in social networks. Social Networks, 39, 14-32.

  • Coleman, James S. “Relational analysis: The study of social organizations with survey methods.” Human Organization 17.4 (1958): 28-36.

  • Duxbury, Scott W. “Micro effects on macro structure in social networks.” Sociological Methodology 54.1 (2024): 1-26.

  • Echenique, F., & Fryer Jr., R. G. (2007). “A measure of segregation based on social interactions.” The Quarterly Journal of Economics, 122(2), 441-485.

  • Fershtman, M., 1997. Cohesive group segregation detection in a social network by the Segregation Matrix Index. Soc. Netw. 19, 193-207.

  • Freeman, L. C. (1978). Segregation in social networks. Sociological Methods & Research, 6(4), 411-429.

  • Garimella, Kiran, et al. “Quantifying controversy on social media.” ACM Transactions on Social Computing 1.1 (2018): 1-27.

  • Guerra, Pedro, et al. “A measure of polarization on social media networks based on community boundaries.” Proceedings of the International AAAI Conference on Web and Social Media. Vol. 7. No. 1. 2013.

  • Gupta, Sunetra, Roy M. Anderson, and Robert M. May. “Networks of sexual contacts: implications for the pattern of spread of HIV.” AIDS 3.12 (1989): 807-818.

  • Krackhardt, David, and Robert N. Stern. “Informal networks and organizational crises: An experimental simulation.” Social Psychology Quarterly (1988): 123-140.

  • Moody, James. “Race, school integration, and friendship segregation in America.” American Journal of Sociology 107.3 (2001): 679-716.

  • Morales, Alfredo Jose, et al. “Measuring political polarization: Twitter shows the two sides of Venezuela.” Chaos: An Interdisciplinary Journal of Nonlinear Science 25.3 (2015).

  • Moran, P. A. P. (1950). “Notes on continuous stochastic phenomena.” Biometrika, 37(1), 17-23.

  • Newman, M.E.J., Girvan, M., 2002. Mixing patterns and community structure in networks. arXiv:cond-mat/0210146.

  • Newman, M.E.J., 2003. Mixing patterns in networks. Phys. Rev. E 67 (2), 026126.

  • Salloum, Ali, Ted Hsuan Yun Chen, and Mikko Kivelä. “Separating polarization from noise: comparison and normalization of structural polarization measures.” Proceedings of the ACM on Human-Computer Interaction 6.CSCW1 (2022): 1-33.