From 74535c4f72123fd0ad8c7ba849a75495e50cd313 Mon Sep 17 00:00:00 2001 From: Robert Samples <64489385+robertsamples@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:58:56 -0500 Subject: [PATCH] de novo hca implementation --- code/pvclust.py | 28 ++++++++++++++++++++++++++++ code/tests/test_pvclust.py | 19 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/code/pvclust.py b/code/pvclust.py index d883b9e..7443598 100644 --- a/code/pvclust.py +++ b/code/pvclust.py @@ -174,3 +174,31 @@ def __init__(self, data, method='ward', metric='euclidean', nboot=1000, self.result = pd.DataFrame( [fit(self.r, row, self.nboot) for row in self.bp_by_scale.to_numpy()], columns=COLUMNS) + + def node_positions(self, leaves): + """(x, y) of each cluster's join in a scipy dendrogram whose leaf + order is ``leaves``, in linkage row order. scipy places the i-th leaf + at x = 5 + 10 i and each join midway between its two branches.""" + n_objects = len(leaves) + x = np.empty(2 * n_objects - 1) + x[np.asarray(leaves)] = 5 + 10 * np.arange(n_objects) + for row, (left, right) in enumerate(self.linkage_matrix[:, :2].astype(int)): + x[n_objects + row] = (x[left] + x[right]) / 2 + return x[n_objects:], self.linkage_matrix[:, 2] + + def plot(self, ax, labels=None, link_color_func=None, fontsize=7): + """Draw the dendrogram on a matplotlib ``ax`` with AU (red, left) and + BP (green, right) in percent at each join, as pvclust does. Returns + scipy's dendrogram dictionary.""" + dend = hierarchy.dendrogram( + self.linkage_matrix, ax=ax, labels=labels, leaf_rotation=90, + color_threshold=0, above_threshold_color='black', + link_color_func=link_color_func) + x, y = self.node_positions(dend['leaves']) + lift = 0.01 * (y.max() if len(y) else 1) + for (au, bp), xi, yi in zip(self.result[['AU', 'BP']].to_numpy(), x, y): + ax.text(xi - 1, yi + lift, f'{round(100 * au)}', color='red', + fontsize=fontsize, ha='right', va='bottom') + ax.text(xi + 1, yi + lift, f'{round(100 * bp)}', color='green', + fontsize=fontsize, ha='left', va='bottom') + return dend diff --git a/code/tests/test_pvclust.py b/code/tests/test_pvclust.py index a497b39..aac6327 100644 --- a/code/tests/test_pvclust.py +++ b/code/tests/test_pvclust.py @@ -67,3 +67,22 @@ def test_scales_given_in_tenths_are_read_as_fractions(): tenths = pvclust.PvClust(data, nboot=5, r=np.array(range(5, 15)), seed=0) assert np.allclose(tenths.r, pvclust.PvClust(data, nboot=5, seed=0).r) assert tenths.n_scaled[0] == 100 and tenths.n_scaled[-1] == 280 + + +def test_plot_labels_every_join_at_its_place_in_the_drawing(): + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + + data = separated_groups() + pv = pvclust.PvClust(data, nboot=20, seed=0) + fig, ax = plt.subplots() + dend = pv.plot(ax, labels=list(data.columns)) + x, y = pv.node_positions(dend['leaves']) + # Each join drawn by scipy is a segment whose top midpoint is (x, y). + drawn = sorted((round((seg_x[1] + seg_x[2]) / 2, 6), round(seg_y[1], 6)) + for seg_x, seg_y in zip(dend['icoord'], dend['dcoord'])) + assert drawn == sorted(zip(np.round(x, 6), np.round(y, 6))) + texts = [t.get_text() for t in ax.texts] + assert len(texts) == 2 * len(pv.result) + plt.close(fig)