The mathematics of pyTstability: Computing Dataset Connectivity

Published on: 2026-11-24

When you run a hierarchical or multilevel regression model (whether using data from biological species, human languages, or cultural traits) you are making an implicit assumption: your data points are connected enough to share statistical strength.

If your dataset is fractured into isolated “islands” with very few shared historical branches or geographic neighbors, standard models lose regularizing traction. Parameters collapse, standard errors explode, and MCMC chains get stuck exploring topological mirages.

I built pytstability to catch these structural weak spots before you commit to heavy modeling. Instead of relying on continuous smoothing (like Kernel Density Estimation) to allow for estimation (which can introduce inaccuracies in results), the goal is to identify problems in the data that you can then address effectively. To do this, the tool converts your spatial points, categories, and family trees into discrete graphs and audits their topology.

Here is a look under the hood at the math that the tool uses.


Step 1: Building the Adjacency Matrices (AA)

Before measuring stability, the tool translates raw data into two binary N×NN \times N adjacency matrices, where 11 means two data points share a connection and 00 means they do not:

  1. The Spatial Matrix (AspaceA_{\text{space}}): If you provide latitude and longitude, the engine projects those coordinates onto a 3D Cartesian sphere using Earth’s radius (R=6371.0 kmR = 6371.0\text{ km}). It computes pairwise Euclidean distances and draws an edge (Aij=1A_{ij} = 1) if two points fall within your distance threshold (default 500 km). If you provide spatial categories (like macroareas), it overlays matching rules so points must also share a region.
  2. The Structural Matrix (AstructA_{\text{struct}}): When given a phylogenetic or linguistic Newick tree, the engine traces the path of nodes from the root to every tip. For any two tips ii and jj, it counts how many ancestral nodes they share (shared_depth).
    • In fixed mode (ideal for species trees), an edge is drawn if shared_depth exceeds an integer threshold.
    • In adaptive mode (ideal for uneven language families), an edge is drawn if the shared path exceeds a percentage threshold of both lineages’ total lengths.

The reasoning behind this transformation is that both geographic coordinates and branching Newick trees live in completely different mathematical spaces, making them difficult to audit side by side. Translating both into binary adjacency matrices puts spatial proximity and evolutionary relatedness on equal footing, turning messy domain-specific structures into standard discrete networks. Because hierarchical models pass statistical strength along these pathways of shared history and space, mapping every pairwise link into a matrix makes it fast and straightforward to spot where those pathways break down—allowing us to count isolated nodes, detect disconnected “data islands,” and measure overall network cohesion.


Step 2: Core Graph Diagnostics

A single density score on its own can easily mislead you—a dataset might have plenty of connections overall, yet remain fractured into separate, non-communicating clusters. To get a true picture of structural health, we need to look at how connections are distributed across the network: how saturated the graph is overall, how many observations are completely stranded, and whether the remaining points actually form a single unified backbone. Once the matrices are built, the tool extracts three foundational network metrics:

  • Edge Density (κ\kappa): The ratio of active connections to all possible connections in the dataset:

κ=∑i≠jAijN(N−1)\kappa = \frac{\sum_{i \neq j} A_{ij}}{N(N - 1)}

  • Isolation Ratio (PisolatedP_{\text{isolated}}): The proportion of rows that have zero connections (node degree =0= 0) and sit completely detached from the rest of the sample.
  • Giant Component Size (SgiantS_{\text{giant}}): Using compressed sparse graph traversal, the engine finds the single largest connected cluster of nodes and divides its size by NN. (If every cluster is a singleton, Sgiant=0S_{\text{giant}} = 0).

Step 3: Auditing Tree Variance (Disconnection Ratio)

Two trees can have the exact same branching topology, yet wildly different evolutionary dynamics if one has extreme branch-length outliers. To account for this, pytstability extracts all raw branch lengths (LL) from your Newick string and computes a scale-invariant Disconnection Ratio (DRbase\text{DR}_{\text{base}})—mathematically equivalent to the squared coefficient of variation:

DRbase=Var(L)L‾2\text{DR}_{\text{base}} = \frac{\text{Var}(L)}{\bar{L}^2}

If a tree has highly erratic, uneven branch lengths, DRbase\text{DR}_{\text{base}} increases, signaling higher structural uncertainty.


Step 4: The Topological Stability Index (TSI)

In order to determine actual stability across your dataset, the tool combines your structural graph metrics and branch variance into a single diagnostic score: the Topological Stability Index (TSI).

This score takes into account the diverse connections in data, with a single score that tells you how your data is connected. This calculation, when combined with the estimation of the “Critical Horizon” for a given dataset, can help you determine what modeling frameworks to use with your data.

To derive the TSI, the tool calculates a Manifold Linkage Factor (MLF) to penalize graphs where the giant component is disproportionately small relative to edge density:

MLF=exp⁡(−max⁡(Sgiant,10−6)κt+10−5)\text{MLF} = \exp\left(-\frac{\max(S_{\text{giant}}, 10^{-6})}{\kappa_t + 10^{-5}}\right)

Using this factor alongside the total number of structural components (CstructC_{\text{struct}}), it computes a logarithmic Partition Penalty:

Penalty=1.0+ln⁡(Cstruct⋅MLFmax⁡(Sgiant,10−6)+1.0)\text{Penalty} = 1.0 + \ln\left(\frac{C_{\text{struct}} \cdot \text{MLF}}{\max(S_{\text{giant}}, 10^{-6})} + 1.0\right)

Finally, we arrive at the TSI formula:

TSI=κt⋅(1.0−Pisolated)DRbase⋅Penalty\text{TSI} = \frac{\kappa_t \cdot (1.0 - P_{\text{isolated}})}{\text{DR}_{\text{base}} \cdot \text{Penalty}}

What this means intuitively: High edge density (κt\kappa_t) and low isolation (1−Pisolated1 - P_{\text{isolated}}) push your stability score up. Extreme branch variance (DRbase\text{DR}_{\text{base}}) and fractured, multi-island trees (Penalty\text{Penalty}) push your score down.


Step 5: Self-Tuning via Topological Entropy

Choosing a tree depth cutoff manually can inadvertently bias your connectivity metrics. When you set struct_depth="auto", the engine searches across candidate depths (levels 2 to 10 for fixed biology trees, or ratios 0.50 to 0.98 for adaptive linguistic trees) to maximize Topological Entropy:

Htopo=TSI⋅ln⁡(Cstruct+1.0)⋅(1.0−Pisolated)H_{\text{topo}} = \text{TSI} \cdot \ln(C_{\text{struct}} + 1.0) \cdot (1.0 - P_{\text{isolated}})

This formula balances two competing forces: it rewards depths that preserve high stability (TSI\text{TSI}) and low isolation, while the ln⁡(Cstruct+1)\ln(C_{\text{struct}} + 1) term prevents the algorithm from cheating by lumping the entire world into one giant, uninformative super-cluster (Cstruct=1C_{\text{struct}} = 1).

For linguistic and cultural datasets with spatial coordinates, it applies an extra Cross-Domain Penalty:

Penaltycross=exp⁡(−3.5⋅|Cspace−Cstruct|Cspace)\text{Penalty}_{\text{cross}} = \exp\left(-3.5 \cdot \frac{|C_{\text{space}} - C_{\text{struct}}|}{C_{\text{space}}}\right)

This ensures the chosen tree depth aligns naturally with your geographic clusters.


Step 6: The Dynamic Critical Horizon (Γ\Gamma)

A TSI\text{TSI} of 0.004 might be fine for a small, localized dataset, but catastrophic for a global sample scattered across dozens of disconnected regions. Instead of using a hardcoded pass/fail cutoff, pytstability calculates a dynamic Critical Horizon (Γ\Gamma).

First, it calculates the mass-weighted effective number of components (CeffC_{\text{eff}}—the inverse Simpson concentration index of cluster sizes) for both your spatial and structural graphs:

Ceff=1∑m(nmN)2C_{\text{eff}} = \frac{1}{\sum_{m} \left(\frac{n_m}{N}\right)^2}

Taking whichever domain is more fragmented (Cmax=max⁡(Ceff, space,Ceff, struct)C_{\max} = \max(C_{\text{eff, space}}, C_{\text{eff, struct}})), it sets your custom safety threshold:

Γ=0.0050⋅ln⁡(Cmax+1.0)\Gamma = 0.0050 \cdot \ln(C_{\max} + 1.0)

If TSI≤Γ\text{TSI} \le \Gamma, pytstability triggers a Pipeline Crash Alert—letting you know it is time to rethink your partitions or switch to topology-aware modeling approaches before wasting compute time.


Want to try it on your own data? Check out the code and multi-domain walkthroughs on GitHub.