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 ()
Before measuring stability, the tool translates raw data into two binary adjacency matrices, where means two data points share a connection and means they do not:
- The Spatial Matrix
():
If you provide latitude and longitude, the
engine projects those coordinates onto a 3D
Cartesian sphere using Earth’s radius
().
It computes pairwise Euclidean distances and
draws an edge
()
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. - The Structural Matrix
():
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
and
,
it counts how many ancestral nodes they share
(
shared_depth).- In
fixedmode (ideal for species trees), an edge is drawn ifshared_depthexceeds an integer threshold. - In
adaptivemode (ideal for uneven language families), an edge is drawn if the shared path exceeds a percentage threshold of both lineages’ total lengths.
- In
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 (): The ratio of active connections to all possible connections in the dataset:
- Isolation Ratio (): The proportion of rows that have zero connections (node degree ) and sit completely detached from the rest of the sample.
- Giant Component Size (): Using compressed sparse graph traversal, the engine finds the single largest connected cluster of nodes and divides its size by . (If every cluster is a singleton, ).
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
()
from your Newick string and computes a
scale-invariant Disconnection
Ratio
()—mathematically
equivalent to the squared coefficient of
variation:
If a tree has highly erratic, uneven branch lengths, 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:
Using this factor alongside the total number of structural components (), it computes a logarithmic Partition Penalty:
Finally, we arrive at the TSI formula:
What this means intuitively: High edge density () and low isolation () push your stability score up. Extreme branch variance () and fractured, multi-island trees () 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:
This formula balances two competing forces: it rewards depths that preserve high stability () and low isolation, while the term prevents the algorithm from cheating by lumping the entire world into one giant, uninformative super-cluster ().
For linguistic and cultural datasets with spatial coordinates, it applies an extra Cross-Domain Penalty:
This ensures the chosen tree depth aligns naturally with your geographic clusters.
Step 6: The Dynamic Critical Horizon ()
A
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
().
First, it calculates the mass-weighted effective number of components (—the inverse Simpson concentration index of cluster sizes) for both your spatial and structural graphs:
Taking whichever domain is more fragmented (), it sets your custom safety threshold:
If
,
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.