Agglomerative clustering repeatedly merges the two closest clusters and records a tree. Represent the tree as a linkage matrix in the SciPy convention.
linkage_matrix(D, method): D is an (N, N) symmetric dissimilarity matrix; method is "single" (minimum pairwise dissimilarity), "complete" (maximum) or "average" (mean over all cross pairs). Singletons are clusters ; the cluster created at step (0-based) gets id . At each step merge the pair of current clusters with the smallest linkage dissimilarity, breaking ties by the smallest pair of ids (compare the smaller id first, then the larger). Return an (N-1, 4) float array whose row is [a, b, height, size] with the merged ids, the linkage dissimilarity at which they merged, and the size of the new cluster.
cut_at_height(Z, h): given a linkage matrix for len(Z) + 1 points, apply every merge whose height is at most h and return the flat cluster labels of the points, numbered in order of first appearance (point 0's cluster is 0).