Source code for graphclust.vat
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
r"""Visual assessment of cluster tendency.
:func:`vat` (Bezdek and Hathaway 2002) reorders a dissimilarity matrix along
the order in which Prim's algorithm adds the samples to the minimal spanning
tree; clusters then appear as dark blocks on the diagonal of the image.
:func:`ivat` (Havens and Bezdek 2012) replaces every dissimilarity by the
largest edge on the MST path between the two samples (the minimax path
distance), which sharpens the blocks considerably for elongated or
chained clusters. Both work on any dissimilarity, e.g. Euclidean, geodesic
or fuzzy neighborhood distances.
"""
from __future__ import annotations
import numpy as np
__all__ = ["ivat", "vat", "vat_order"]
[docs]
def vat_order(D) -> tuple[np.ndarray, np.ndarray]:
"""VAT ordering (Prim's order starting from an end point of the largest dissimilarity) and the
MST edge weight by which every sample was attached (``0`` for the first)."""
D = np.asarray(D, dtype=float)
n = len(D)
i, _ = np.unravel_index(np.argmax(D), D.shape)
order = [int(i)]
attach = [0.0]
in_tree = np.zeros(n, bool)
in_tree[i] = True
best = D[i].copy()
best[in_tree] = np.inf
for _ in range(n - 1):
j = int(np.argmin(best))
order.append(j)
attach.append(float(best[j]))
in_tree[j] = True
best = np.minimum(best, D[j])
best[in_tree] = np.inf
return np.array(order), np.array(attach)
[docs]
def vat(D) -> tuple[np.ndarray, np.ndarray]:
"""Reordered dissimilarity image and the permutation.
Examples
--------
>>> import numpy as np
>>> D = np.abs(np.subtract.outer([0, 5, 1, 6], [0, 5, 1, 6])).astype(float)
>>> vat(D)[1].tolist()
[0, 2, 1, 3]
"""
D = np.asarray(D, dtype=float)
p, _ = vat_order(D)
return D[np.ix_(p, p)], p
[docs]
def ivat(D) -> tuple[np.ndarray, np.ndarray]:
r"""Improved VAT image: minimax (largest MST edge on the path) distances in VAT order."""
D = np.asarray(D, dtype=float)
p, _ = vat_order(D)
R = D[np.ix_(p, p)]
n = len(R)
out = np.zeros_like(R)
for r in range(1, n):
j = int(np.argmin(R[r, :r]))
out[r, :r] = np.maximum(R[r, j], out[j, :r])
out[r, j] = R[r, j]
out[:r, r] = out[r, :r]
return out, p