-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclustering.py
More file actions
1321 lines (1163 loc) · 52.5 KB
/
clustering.py
File metadata and controls
1321 lines (1163 loc) · 52.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster, dendrogram, optimal_leaf_ordering
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import cophenet, linkage
from scipy.stats import wilcoxon
from sklearn.metrics import silhouette_score, calinski_harabasz_score, davies_bouldin_score
from sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score
from typing import List, Sequence, Optional, Tuple, Dict, Any
from sklearn.cluster import MiniBatchKMeans
# ---------------------------------------------------------------------
# Original Clustering
# ---------------------------------------------------------------------
def _hierarchical_clustering(data, k_min=3, k_max=40, metric="euclidean", method="ward"):
"""
"""
n_obs = data.shape[0]
k_min = max(k_min, 2)
k_max = min(k_max, n_obs - 1)
if k_max < k_min:
raise ValueError("Not enough observations for the requested k-range.")
if method.lower() == "ward":
Z = linkage(data, method="ward", metric="euclidean")
pairwise_dists = pdist(data, metric="euclidean")
else:
pairwise_dists = pdist(data, metric=metric)
Z = linkage(pairwise_dists, method=method)
Z = optimal_leaf_ordering(Z, pairwise_dists)
D_square = squareform(pairwise_dists)
best_k, best_score, best_labels = None, -np.inf, None
score_recording, cut_thresholds = {}, {}
for k in range(k_min, k_max + 1):
labels = fcluster(Z, k, criterion="maxclust")
score = silhouette_score(D_square, labels, metric="precomputed")
score_recording[k] = score
cut_idx = (n_obs - k) - 1
if 0 <= cut_idx < Z.shape[0]:
cut_thresholds[k] = float(np.nextafter(Z[cut_idx, 2], np.inf))
else:
cut_thresholds[k] = None
if score > best_score:
best_k, best_score, best_labels = k, score, labels
leaf_order = dendrogram(Z, no_plot=True)["leaves"]
return dict(
linkage=Z,
leaf_order=leaf_order,
labels=best_labels,
k=best_k,
silhouette=best_score,
score_recording=score_recording,
cut_threshold=cut_thresholds.get(best_k, None)
)
def cluster_variance_matrix(V, k_min=3, k_max=40, metric="euclidean", method="ward"):
"""
"""
V = np.asarray(V)
row_res = _hierarchical_clustering(V, k_min, k_max, metric, method)
col_res = _hierarchical_clustering(V.T, k_min, k_max, metric, method)
return dict(
row_order=row_res["leaf_order"],
col_order=col_res["leaf_order"],
row_labels=row_res["labels"],
col_labels=col_res["labels"],
row_k=row_res["k"],
col_k=col_res["k"],
row_linkage=row_res["linkage"],
col_linkage=col_res["linkage"],
row_score_recording=row_res["score_recording"],
col_score_recording=col_res["score_recording"],
row_cut_threshold=row_res["cut_threshold"],
col_cut_threshold=col_res["cut_threshold"],
)
# ---------------------------------------------------------------------
# Clustering with multiple repeats
# ---------------------------------------------------------------------
def _breaks(lbls):
"""
"""
idx = np.nonzero(np.diff(lbls))[0] + 1
return idx.tolist()
def labels_at_k(Z, k):
"""
"""
# Z has shape (n_obs-1, 4); Z[i,2] is the merge height of the (i+1)-th merge
n_obs = Z.shape[0] + 1
# index of the last merge included when you still have exactly k clusters
cut_idx = (n_obs - k) - 1 # 0-based
# choose a threshold strictly between the two adjacent heights
t_low = Z[cut_idx, 2]
t_high = Z[cut_idx + 1, 2] if (cut_idx + 1) < Z.shape[0] else np.inf
t = np.nextafter(t_low, t_high) # just above t_low, still below t_high
return fcluster(Z, t, criterion="distance")
def _score_threshold_from_best(best_score, silhouette_tol=0.02, tol_mode="relative"):
"""
Compute the score threshold used for tolerance-based model selection.
Parameters
----------
best_score : float
Reference silhouette score.
silhouette_tol : float
Tolerance value. Interpreted according to ``tol_mode``.
tol_mode : {"relative", "absolute"}
- "relative": threshold = best_score * (1 - silhouette_tol)
- "absolute": threshold = best_score - silhouette_tol
"""
if tol_mode == "relative":
return float(best_score) * (1.0 - float(silhouette_tol))
if tol_mode == "absolute":
return float(best_score) - float(silhouette_tol)
raise ValueError("tol_mode must be 'relative' or 'absolute'.")
def _select_k(candidates, tol_k_select):
"""Pick one k from a non-empty list of candidate k values.
tol_k_select:
"min" — smallest k in the tolerance band (fewest clusters).
"max" — largest k in the tolerance band (most clusters).
"mean" — k closest to the arithmetic mean of the band (middle ground).
Ties are broken by choosing the smaller k.
Note: "ari" and "gap" are handled separately in the caller.
"""
if tol_k_select == "min":
return min(candidates)
if tol_k_select == "max":
return max(candidates)
# "mean": pick candidate closest to the arithmetic mean of the band
mean_val = float(np.mean(candidates))
return min(candidates, key=lambda k: (abs(k - mean_val), k))
def _gap_k(Z, candidates):
"""Pick k from candidates with the largest Ward merge-height gap.
gap(k) = Z[n-k, 2] - Z[n-k-1, 2]:
height of the merge that reduces k → k-1 clusters
minus height of the merge that reduces k+1 → k clusters.
A large gap means those k clusters are a natural stopping point —
merging further would bridge a large geometric distance.
Ties broken by smaller k.
"""
n = Z.shape[0] + 1 # number of leaf observations
def _gap(k):
idx_above = n - k # merge index for k → k-1 transition
idx_below = n - k - 1 # merge index for k+1 → k transition
h_above = float(Z[idx_above, 2]) if 0 <= idx_above < Z.shape[0] else np.inf
h_below = float(Z[idx_below, 2]) if 0 <= idx_below < Z.shape[0] else 0.0
return h_above - h_below
return max(candidates, key=lambda k: (_gap(k), -k))
def _hierarchical_clustering_repeat(
data,
k_min=3,
k_max=40,
metric="euclidean",
method="ward",
*,
n_repeats=1,
resample_features_frac=1.0,
jitter_std=0.0,
random_state=None,
select_min_k_within_tol=True,
silhouette_tol=0.02,
tol_mode="relative",
score_quantile=None,
unresponsive_norm_frac=1e-3,
skip_unresponsive_detection=False,
tol_k_select="min",
max_ari_pairs=50,
):
"""
Hierarchical clustering with stability repeats.
Key behavior:
- Repeats (feature bootstrap / jitter) are used ONLY to estimate the
silhouette-vs-k curve.
- The returned linkage / leaf_order are computed ONCE on the original
unperturbed data.
- The primary returned labels / k correspond to the strict argmax of
the aggregated silhouette across repeats.
- The alt/tol returned labels / k correspond to the smallest (or
largest, depending on tol_k_select) k whose aggregated silhouette
is within tolerance of that strict best score.
- Aggregation is mean by default; set score_quantile (e.g. 0.75, 0.90)
to use that quantile across repeats instead.
- We still pick a representative repeat (max mean ARI at the selected
tolerant k) for diagnostics, but we do NOT return its linkage as the
final dendrogram.
- jitter_std is a RELATIVE fraction: each entry is multiplied by
(1 + N(0, jitter_std)), so jitter_std=0.01 means ±1% per-entry noise.
This is scale-invariant and behaves consistently across normalized and
unnormalized matrices. Zero entries receive no jitter.
- tol_k_select controls which k within the tolerance band is selected:
"min" picks the smallest, "max" the largest, "mean" the one closest
to the arithmetic mean of all candidates (ties broken by smaller k).
"""
if tol_k_select not in ("min", "max", "mean", "ari", "gap"):
raise ValueError("tol_k_select must be 'min', 'max', 'mean', 'ari', or 'gap'.")
_k_select = lambda cands: _select_k(cands, tol_k_select) # noqa: E731
rng = np.random.default_rng(random_state)
data = np.asarray(data)
n_obs, n_feat = data.shape
# ------------------------------------------------------------------
# Unresponsive row detection (active for all metrics).
#
# Rows whose L2 norm is < unresponsive_norm_frac * max_norm are
# considered "unresponsive" (silent neuron or silent task period).
# For cosine/correlation metrics this is essential because the
# distance is undefined for zero vectors. For Euclidean/Ward it is
# also beneficial: near-zero rows form a trivial cluster that can
# inflate silhouette scores and obscure meaningful structure among
# the active rows. Excluding them and assigning a dedicated label
# (k+1) keeps the clustering focused on informative observations.
# Using a relative threshold (fraction of the max norm) keeps the
# criterion scale-invariant across normalised and unnormalised data.
# ------------------------------------------------------------------
if skip_unresponsive_detection:
unresponsive_mask = np.zeros(n_obs, dtype=bool)
else:
row_means = data.mean(axis=1)
max_mean = row_means.max() if row_means.max() > 0 else 1.0
unresponsive_mask = row_means < unresponsive_norm_frac * max_mean
n_unresponsive = int(unresponsive_mask.sum())
if n_unresponsive > 0:
warnings.warn(
f"{n_unresponsive} unresponsive row(s) detected "
f"(mean < {unresponsive_norm_frac} * max_mean = "
f"{unresponsive_norm_frac * max_mean:.3g}); "
f"excluding from clustering and assigning to dedicated cluster (label = k+1).",
RuntimeWarning,
stacklevel=3,
)
active_mask = ~unresponsive_mask
active_idx = np.where(active_mask)[0] # original row indices of active rows
unres_idx = np.where(unresponsive_mask)[0] # original row indices of unresponsive rows
active_data = data[active_mask] # shape: (n_active, n_feat)
n_active = active_data.shape[0]
def _expand_labels(labels_active, k_active):
"""Map labels from n_active rows back to n_obs; unresponsive rows get label k+1."""
full = np.zeros(n_obs, dtype=int)
full[active_mask] = labels_active
if n_unresponsive > 0:
full[unresponsive_mask] = k_active + 1
return full
def _expand_leaf_order(leaf_order_active):
"""Map leaf order from active-row indices back to original indices.
Unresponsive rows are appended at the end so they form a contiguous
block in downstream heatmaps.
"""
return list(active_idx[np.array(leaf_order_active)]) + list(unres_idx)
def _compute_linkage_leaforder(X):
"""Compute linkage + optimal leaf order; return (Z, condensed_dists, leaf_order).
X must already be free of unresponsive rows — handled by the caller.
leaf_order indices are relative to the rows of X (0..len(X)-1).
"""
X = np.asarray(X, dtype=float)
if method.lower() == "ward":
Z = linkage(X, method="ward")
d = pdist(X, metric="euclidean")
else:
d = pdist(X, metric=metric)
Z = linkage(d, method=method)
Z = optimal_leaf_ordering(Z, d)
leaf_order = dendrogram(Z, no_plot=True)["leaves"]
return Z, d, leaf_order
def _cut_threshold_from_Z(Z, k):
"""Threshold just above the last merge height when there are k clusters."""
cut_idx = (n_active - k) - 1
if 0 <= cut_idx < Z.shape[0]:
return float(np.nextafter(Z[cut_idx, 2], np.inf))
return None
k_min = max(int(k_min), 2)
k_max = min(int(k_max), n_active - 1)
if k_max < k_min:
raise ValueError("Not enough observations for the requested k-range.")
k_range = range(k_min, k_max + 1)
k_values = np.array(list(k_range), dtype=int)
per_repeat = []
for _ in range(int(n_repeats)):
if resample_features_frac < 1.0:
m = max(1, int(np.ceil(resample_features_frac * n_feat)))
feat_idx = rng.choice(n_feat, size=m, replace=True)
Xr = active_data[:, feat_idx]
else:
Xr = active_data
if jitter_std > 0.0:
# Relative jitter: each entry is perturbed by jitter_std fraction of
# its own magnitude, i.e. Xr_ij *= (1 + N(0, jitter_std)).
# Zero entries receive no jitter, which is intentional.
Xr = Xr * (1.0 + rng.normal(0.0, jitter_std, size=Xr.shape))
Zr, dr, leaf_order_r = _compute_linkage_leaforder(Xr)
D_square = squareform(dr)
labels_by_k = {}
scores_by_k = {}
cut_thresholds = {}
for k in k_range:
labels = fcluster(Zr, k, criterion="maxclust")
n_clusters = np.unique(labels).size
if n_clusters < 2 or n_clusters >= n_active:
scores_by_k[k] = -np.inf
else:
scores_by_k[k] = float(silhouette_score(D_square, labels, metric="precomputed"))
labels_by_k[k] = labels
cut_thresholds[k] = _cut_threshold_from_Z(Zr, k)
per_repeat.append(
dict(
Z=Zr,
leaf_order=leaf_order_r,
labels_by_k=labels_by_k,
scores_by_k=scores_by_k,
cut_thresholds=cut_thresholds,
)
)
score_recording_all = np.array(
[[rep["scores_by_k"][k] for k in k_values] for rep in per_repeat],
dtype=float,
)
score_recording_mean = {
int(k): float(np.mean(score_recording_all[:, idx])) for idx, k in enumerate(k_values)
}
score_recording_std = {
int(k): float(np.std(score_recording_all[:, idx])) for idx, k in enumerate(k_values)
}
if score_quantile is not None:
score_recording_agg = {
int(k): float(np.quantile(score_recording_all[:, idx], score_quantile))
for idx, k in enumerate(k_values)
}
else:
score_recording_agg = score_recording_mean
# ------------------------------------------------------------------
# ARI stability curve: for each k, compute the mean pairwise ARI
# across all (n_repeats choose 2) pairs of repeat clusterings.
# High ARI at k means the repeat clusterings agree at that k —
# i.e. k is stable — independent of whether silhouette is high.
# With a single repeat all values are trivially 1.0.
# ------------------------------------------------------------------
R = len(per_repeat)
ari_recording_mean = {}
ari_recording_std = {}
if R > 1:
# Build all unique pairs then cap to max_ari_pairs to avoid O(R^2) cost.
all_pairs = [(i, j) for i in range(R) for j in range(i + 1, R)]
if max_ari_pairs is not None and len(all_pairs) > max_ari_pairs:
rng_ari = np.random.default_rng(0)
chosen = rng_ari.choice(len(all_pairs), size=max_ari_pairs, replace=False)
sampled_pairs = [all_pairs[p] for p in chosen]
else:
sampled_pairs = all_pairs
for k in k_range:
labels_k = [rep["labels_by_k"][k] for rep in per_repeat]
ari_vals = [
adjusted_rand_score(labels_k[i], labels_k[j])
for i, j in sampled_pairs
]
ari_recording_mean[k] = float(np.mean(ari_vals))
ari_recording_std[k] = float(np.std(ari_vals))
else:
for k in k_range:
ari_recording_mean[k] = 1.0
ari_recording_std[k] = 0.0
strict_best_k = max(score_recording_agg, key=score_recording_agg.get)
strict_best_score = score_recording_agg[strict_best_k]
if select_min_k_within_tol:
primary_thresh = _score_threshold_from_best(
strict_best_score, silhouette_tol=silhouette_tol, tol_mode=tol_mode
)
primary_candidates = [k for k in k_range if score_recording_agg[k] >= primary_thresh]
else:
primary_thresh = strict_best_score
primary_candidates = [strict_best_k]
# Final linkage on the original unperturbed active rows.
# Computed here (before k selection) so gap-based selection can use Z0.
Z0, d0, leaf0 = _compute_linkage_leaforder(active_data)
leaf0_full = _expand_leaf_order(leaf0)
# ARI-based k selection — resolved here so "ari" mode can feed into best_k.
# ari_best_k: global argmax of the ARI stability curve (ignores silhouette).
# ari_tol_k: best ARI within the silhouette tolerance band —
# combines both criteria (silhouette screens, ARI breaks ties).
ari_best_k = max(ari_recording_mean, key=ari_recording_mean.get)
ari_tol_k = (
max(primary_candidates, key=lambda k: ari_recording_mean[k])
if primary_candidates else ari_best_k
)
# Gap-based k selection — uses Z0 (unperturbed linkage).
# gap_tol_k: k in the silhouette tolerance band with the largest merge-height gap.
gap_tol_k = _gap_k(Z0, primary_candidates) if primary_candidates else strict_best_k
# Select best_k according to tol_k_select.
if tol_k_select == "ari":
best_k = ari_tol_k
elif tol_k_select == "gap":
best_k = gap_tol_k
else:
best_k = _k_select(primary_candidates) if primary_candidates else strict_best_k
best_k_score_mean = score_recording_mean[best_k]
labels_list = [rep["labels_by_k"][best_k] for rep in per_repeat]
if len(labels_list) == 1:
best_rep_idx = 0
mean_ari_val = 1.0
else:
R = len(labels_list)
ari_mat = np.zeros((R, R), dtype=float)
for i in range(R):
for j in range(i + 1, R):
ari = adjusted_rand_score(labels_list[i], labels_list[j])
ari_mat[i, j] = ari_mat[j, i] = ari
mean_ari = ari_mat.mean(axis=1)
best_rep_idx = int(np.argmax(mean_ari))
mean_ari_val = float(mean_ari[best_rep_idx])
best_rep = per_repeat[best_rep_idx]
alt_thresh = _score_threshold_from_best(
strict_best_score, silhouette_tol=silhouette_tol, tol_mode=tol_mode
)
alt_candidates = [k for k in k_range if score_recording_agg[k] >= alt_thresh]
if tol_k_select == "ari":
alt_k = ari_tol_k
elif tol_k_select == "gap":
alt_k = gap_tol_k
else:
alt_k = _k_select(alt_candidates) if alt_candidates else strict_best_k
strict_labels = _expand_labels(fcluster(Z0, strict_best_k, criterion="maxclust"), strict_best_k)
strict_cut_threshold = _cut_threshold_from_Z(Z0, strict_best_k)
final_alt_labels = _expand_labels(fcluster(Z0, alt_k, criterion="maxclust"), alt_k)
final_alt_cut_threshold = _cut_threshold_from_Z(Z0, alt_k)
ari_best_labels = _expand_labels(fcluster(Z0, ari_best_k, criterion="maxclust"), ari_best_k)
ari_tol_labels = _expand_labels(fcluster(Z0, ari_tol_k, criterion="maxclust"), ari_tol_k)
gap_tol_labels = _expand_labels(fcluster(Z0, gap_tol_k, criterion="maxclust"), gap_tol_k)
return dict(
linkage=Z0,
leaf_order=leaf0_full,
labels=strict_labels,
k=strict_best_k,
cut_threshold=strict_cut_threshold,
alt_k=alt_k,
alt_labels=final_alt_labels,
alt_linkage=Z0,
alt_leaf_order=leaf0_full,
alt_cut_threshold=final_alt_cut_threshold,
silhouette_strict_best=strict_best_score,
silhouette_at_k=best_k_score_mean,
score_recording_mean=score_recording_mean,
score_recording_std=score_recording_std,
score_recording_all=score_recording_all,
k_values=k_values,
ari_recording_mean=ari_recording_mean,
ari_recording_std=ari_recording_std,
ari_best_k=ari_best_k,
ari_best_labels=ari_best_labels,
ari_tol_k=ari_tol_k,
ari_tol_labels=ari_tol_labels,
gap_tol_k=gap_tol_k,
gap_tol_labels=gap_tol_labels,
rep_linkage=best_rep["Z"],
rep_leaf_order=_expand_leaf_order(best_rep["leaf_order"]),
rep_labels_at_k=_expand_labels(best_rep["labels_by_k"][best_k], best_k),
rep_cut_threshold_at_k=best_rep["cut_thresholds"][best_k],
_repeats=len(per_repeat),
_params=dict(
resample_features_frac=resample_features_frac,
jitter_std=jitter_std,
method=method,
metric=metric,
mean_ari_at_best_k=mean_ari_val,
select_min_k_within_tol=select_min_k_within_tol,
silhouette_tol=silhouette_tol,
tol_mode=tol_mode,
score_quantile=score_quantile,
chosen_k=best_k,
chosen_score=best_k_score_mean,
strict_best_k=strict_best_k,
strict_best_score=strict_best_score,
primary_thresh=primary_thresh,
primary_candidates=primary_candidates,
alt_thresh=alt_thresh,
alt_candidates=alt_candidates,
),
)
def cluster_variance_matrix_repeat(
V,
k_min=3, k_max=40, metric="euclidean", method="ward",
row_metric=None, row_method=None,
col_metric=None, col_method=None,
*,
n_repeats=10,
resample_features_frac=1.0,
jitter_std=0.0,
random_state=None,
select_min_k_within_tol=True,
silhouette_tol=0.02,
tol_mode="relative",
score_quantile=None,
unresponsive_norm_frac=1e-3,
skip_unresponsive_detection=False,
tol_k_select="min",
max_ari_pairs=300,
):
"""
Cluster a variance matrix V (shape: N_features * M_neurons)
for both rows (features) and columns (neurons), with repeat-based stabilization.
Returns mean/std silhouette curves for rows and cols.
row_k / col_k correspond to the strict argmax of the aggregated silhouette.
row_tol_* / col_tol_* correspond to the smaller tolerance-selected solution.
Aggregation is mean by default; set score_quantile (e.g. 0.75, 0.90) to use
that quantile across repeats instead.
Row and column axes can use different distance metrics and linkage methods via
row_metric / row_method / col_metric / col_method. When any of these is None
it falls back to the shared metric / method defaults. This allows, for example,
keeping euclidean + ward for rows (task periods) while using cosine + average
for columns (neurons) on unnormalized data.
"""
# Resolve per-axis metric/method, falling back to shared defaults.
_row_metric = row_metric if row_metric is not None else metric
_row_method = row_method if row_method is not None else method
_col_metric = col_metric if col_metric is not None else metric
_col_method = col_method if col_method is not None else method
print(f"Row — method: {_row_method}, metric: {_row_metric}")
print(f"Col — method: {_col_method}, metric: {_col_metric}")
V = np.asarray(V)
row_res = _hierarchical_clustering_repeat(
V, k_min, k_max, _row_metric, _row_method,
n_repeats=n_repeats,
resample_features_frac=resample_features_frac,
jitter_std=jitter_std,
random_state=random_state,
select_min_k_within_tol=select_min_k_within_tol,
silhouette_tol=silhouette_tol,
tol_mode=tol_mode,
score_quantile=score_quantile,
unresponsive_norm_frac=unresponsive_norm_frac,
skip_unresponsive_detection=skip_unresponsive_detection,
tol_k_select=tol_k_select,
max_ari_pairs=max_ari_pairs,
)
col_res = _hierarchical_clustering_repeat(
V.T, k_min, k_max, _col_metric, _col_method,
n_repeats=n_repeats,
resample_features_frac=resample_features_frac,
jitter_std=jitter_std,
random_state=None if random_state is None else (random_state + 1),
select_min_k_within_tol=select_min_k_within_tol,
silhouette_tol=silhouette_tol,
tol_mode=tol_mode,
score_quantile=score_quantile,
unresponsive_norm_frac=unresponsive_norm_frac,
skip_unresponsive_detection=skip_unresponsive_detection,
tol_k_select=tol_k_select,
max_ari_pairs=max_ari_pairs,
)
return dict(
row_order=row_res["leaf_order"],
col_order=col_res["leaf_order"],
# Tolerance-selected labels and k (primary result).
# Use row_strict_best_k / col_strict_best_k for the raw silhouette argmax.
row_labels=row_res["alt_labels"],
col_labels=col_res["alt_labels"],
row_k=row_res["alt_k"],
col_k=col_res["alt_k"],
row_linkage=row_res["linkage"],
col_linkage=col_res["linkage"],
row_score_recording_mean=row_res["score_recording_mean"],
row_score_recording_std=row_res["score_recording_std"],
row_score_recording_all=row_res["score_recording_all"],
row_k_values=row_res["k_values"],
col_score_recording_mean=col_res["score_recording_mean"],
col_score_recording_std=col_res["score_recording_std"],
col_score_recording_all=col_res["score_recording_all"],
col_k_values=col_res["k_values"],
row_ari_recording_mean=row_res["ari_recording_mean"],
row_ari_recording_std=row_res["ari_recording_std"],
row_ari_best_k=row_res["ari_best_k"],
row_ari_tol_k=row_res["ari_tol_k"],
col_ari_recording_mean=col_res["ari_recording_mean"],
col_ari_recording_std=col_res["ari_recording_std"],
col_ari_best_k=col_res["ari_best_k"],
col_ari_tol_k=col_res["ari_tol_k"],
row_gap_tol_k=row_res["gap_tol_k"],
col_gap_tol_k=col_res["gap_tol_k"],
row_cut_threshold=row_res["alt_cut_threshold"],
col_cut_threshold=col_res["alt_cut_threshold"],
_row_meta=row_res["_params"],
_col_meta=col_res["_params"],
# Strict argmax (before tolerance).
row_strict_best_k=row_res["k"],
col_strict_best_k=col_res["k"],
row_strict_labels=row_res["labels"],
col_strict_labels=col_res["labels"],
row_strict_cut_threshold=row_res["cut_threshold"],
col_strict_cut_threshold=col_res["cut_threshold"],
# Aliases — tol_* == primary (row_k / row_labels) for API consistency
# with cluster_variance_matrix_forgroup.
row_tol_labels=row_res["alt_labels"],
col_tol_labels=col_res["alt_labels"],
row_tol_k=row_res["alt_k"],
col_tol_k=col_res["alt_k"],
row_cut_tol_threshold=row_res["alt_cut_threshold"],
col_cut_tol_threshold=col_res["alt_cut_threshold"],
)
# ---------------------------------------------------------------------
# Group clustering (taken some grouping prior and
# re-ordering/grouping based on this information)
# ---------------------------------------------------------------------
def _pca1_order(X):
"""
"""
# X: (n_items, n_features)
Xc = X - X.mean(axis=0, keepdims=True)
# first PC score via SVD (stable)
U, S, _ = np.linalg.svd(Xc, full_matrices=False)
score = U[:, 0] * S[0]
return np.argsort(score)
def _within_block_leaf_order(
X,
metric="euclidean",
method="ward",
max_items=2000,
fallback="pca1",
):
n = X.shape[0]
if n <= 2:
return np.arange(n)
# Ward is only coherent with Euclidean
if method == "ward" and metric != "euclidean":
metric = "euclidean"
if n > max_items:
return _pca1_order(X) if fallback == "pca1" else np.arange(n)
d = pdist(X, metric=metric)
Z = linkage(d, method=method)
leaves = dendrogram(Z, no_plot=True)["leaves"]
return np.asarray(leaves, dtype=int)
def _cut_distance_for_k(Z: np.ndarray, k: int) -> float:
"""
Given a SciPy linkage matrix Z (n-1 merges; Z[:,2] are merge heights)
return a distance threshold t such that fcluster(Z, t, criterion='distance')
yields exactly k clusters (for standard monotone linkages like 'ward').
We choose t midway between the (i-1)-th and i-th merge heights, where
i = n - k (number of merges included). Handle edges robustly.
"""
n = Z.shape[0] + 1 # number of original observations
d = Z[:, 2] # non-decreasing merge heights
if n <= 1:
return 0.0
i = n - k # merges included to reach k clusters
if i <= 0:
# No merges: want n clusters → pick any t < first height
return (d[0] * 0.5) if d.size > 0 else 0.0
elif i >= n - 1:
# All merges: want 1 cluster → pick t just above max height
return (d[-1] + np.finfo(float).eps) if d.size > 0 else 0.0
else:
# Midpoint between previous and next merge heights
return 0.5 * (d[i - 1] + d[i])
def _build_groups(
n_items: int,
blocks: Optional[Sequence[Sequence[int]]] = None,
) -> Tuple[List[List[int]], np.ndarray]:
"""
Ensure a full, disjoint partition of {0,…,n_items-1}.
"""
item_to_group = -np.ones(n_items, dtype=int)
groups: List[List[int]] = []
if blocks is not None:
for b in blocks:
b = sorted(set(b))
if len(b) == 0:
continue
g_idx = len(groups)
groups.append(b)
for i in b:
if i < 0 or i >= n_items:
raise IndexError(f"index {i} out of range 0…{n_items-1}")
if item_to_group[i] != -1:
raise ValueError(f"index {i} appears in multiple blocks")
item_to_group[i] = g_idx
for i in range(n_items):
if item_to_group[i] == -1:
item_to_group[i] = len(groups)
groups.append([i])
return groups, item_to_group
def _aggregate_along_axis(
arr: np.ndarray,
groups: List[List[int]],
axis: int = 0,
reduce: str = "mean",
) -> np.ndarray:
"""
Stack aggregated slices along the chosen axis.
* axis=0 : groups act on rows → output shape (n_groups, …)
* axis=1 : groups act on cols → output shape (…, n_groups)
"""
if reduce not in {"mean", "median"}:
raise ValueError("reduce must be 'mean' or 'median'")
agg_fn = np.mean if reduce == "mean" else np.median
out = []
for idxs in groups:
if axis == 0:
out.append(agg_fn(arr[idxs, :], axis=0))
else: # axis==1
out.append(agg_fn(arr[:, idxs], axis=1))
return np.stack(out, axis=axis)
def _hierarchical_clustering_forgroup(
data: np.ndarray,
k_min: int = 3,
k_max: int = 40,
metric: str = "euclidean",
method: str = "ward",
*,
select_min_k_within_tol: bool = True,
silhouette_tol: float = 0.02,
tol_mode: str = "relative",
tol_k_select: str = "min",
skip_unresponsive_detection: bool = False,
unresponsive_norm_frac: float = 1e-3,
) -> Dict[str, Any]:
"""
Hierarchical clustering on `data` (observations × features)
with tolerance-based k selection and an alternative k near the chosen k.
metric/method: use "euclidean"/"ward" (default) or "cosine"/"average".
tol_k_select : "min" selects the smallest k within the tolerance band of
the best silhouette score; "max" selects the largest; "mean" selects
the k closest to the arithmetic mean of the band.
skip_unresponsive_detection : when False (default), rows whose L2 norm is
below unresponsive_norm_frac * max_norm are excluded from clustering
and assigned a dedicated label (k+1), appended at the end of leaf_order.
Set to True to disable detection (e.g. already-normalised data).
"""
if tol_k_select not in ("min", "max", "mean", "ari", "gap"):
raise ValueError("tol_k_select must be 'min', 'max', 'mean', 'ari', or 'gap'.")
_k_select = lambda cands: _select_k(cands, tol_k_select) # noqa: E731
n_obs = data.shape[0]
# ------------------------------------------------------------------
# Unresponsive observation detection.
# Rows whose L2 norm is < unresponsive_norm_frac * max_norm are
# excluded from clustering. They are assigned label k+1 and appended
# at the end of leaf_order so they form a contiguous block in heatmaps.
# ------------------------------------------------------------------
if skip_unresponsive_detection:
unresponsive_mask = np.zeros(n_obs, dtype=bool)
else:
row_means = data.mean(axis=1)
max_mean = row_means.max() if row_means.max() > 0 else 1.0
unresponsive_mask = row_means < unresponsive_norm_frac * max_mean
n_unresponsive = int(unresponsive_mask.sum())
if n_unresponsive > 0:
warnings.warn(
f"{n_unresponsive} unresponsive observation(s) detected "
f"(mean < {unresponsive_norm_frac} * max_mean = "
f"{unresponsive_norm_frac * max_mean:.3g}); "
f"excluding from clustering and assigning to dedicated cluster (label = k+1).",
RuntimeWarning,
stacklevel=3,
)
active_mask = ~unresponsive_mask
active_idx = np.where(active_mask)[0]
unres_idx = np.where(unresponsive_mask)[0]
active_data = data[active_mask]
n_active = active_data.shape[0]
def _expand_labels(labels_active, k_active):
"""Map labels from n_active observations back to n_obs; unresponsive get label k+1."""
full = np.zeros(n_obs, dtype=int)
full[active_mask] = labels_active
if n_unresponsive > 0:
full[unresponsive_mask] = k_active + 1
return full
def _expand_leaf_order(leaf_order_active):
"""Map active-observation leaf order back to original indices, unresponsive appended."""
return list(active_idx[np.array(leaf_order_active)]) + list(unres_idx)
# Degenerate case: fewer than 2 active observations
if n_active < 2:
k_deg = 1
labels_deg = _expand_labels(np.ones(max(n_active, 1), dtype=int), k_deg)
return dict(
linkage=None,
leaf_order=_expand_leaf_order(list(range(n_active))),
labels=labels_deg,
k=k_deg,
silhouette=np.nan,
score_recording={},
cophenet_score=np.nan,
cut_distance_by_k={},
best_cut_distance=None,
labels_by_k={},
strict_best_k=k_deg,
strict_best_score=np.nan,
alt_k=k_deg,
alt_labels=labels_deg,
alt_cut_distance=None,
primary_candidates=[k_deg],
)
pairwise = pdist(active_data, metric=metric)
Z = linkage(pairwise, method=method)
c, _ = cophenet(Z, pairwise) # cophenetic correlation
D_sq = squareform(pairwise)
k_min_eff = max(k_min, 2)
k_max_eff = min(k_max, n_active - 1)
if k_max_eff < k_min_eff:
# n_active is too small to reach the requested k_min.
# Clamp to the largest available k (n_active - 1).
warnings.warn(
f"n_active={n_active} is too small for k_min={k_min}; "
f"clamping k range to [2, {n_active - 1}].",
RuntimeWarning,
stacklevel=3,
)
k_min_eff = 2
k_max_eff = n_active - 1
k_range = range(k_min_eff, k_max_eff + 1)
score_recording: Dict[int, float] = {}
cut_distance_by_k: Dict[int, float] = {}
labels_by_k: Dict[int, np.ndarray] = {}
# Precompute cut distances
for k in k_range:
cut_distance_by_k[k] = _cut_distance_for_k(Z, k)
# Silhouette per k
for k in k_range:
labels = fcluster(Z, k, criterion="maxclust")
labels_by_k[k] = labels
score = silhouette_score(D_sq, labels, metric="precomputed")
score_recording[k] = float(score)
# Strict argmax (global best)
strict_best_k = max(score_recording, key=score_recording.get)
strict_best_score = score_recording[strict_best_k]
# Tolerance threshold for primary selection
if select_min_k_within_tol:
if tol_mode == "relative":
primary_thresh = strict_best_score * (1.0 - float(silhouette_tol))
elif tol_mode == "absolute":
primary_thresh = strict_best_score - float(silhouette_tol)
else:
raise ValueError("tol_mode must be 'relative' or 'absolute'.")
primary_candidates = [k for k in k_range if score_recording[k] >= primary_thresh]
if tol_k_select == "gap":
best_k = _gap_k(Z, primary_candidates) if primary_candidates else strict_best_k
else:
best_k = _k_select(primary_candidates) if primary_candidates else strict_best_k
else:
best_k = strict_best_k
primary_candidates = [strict_best_k]
best_labels = labels_by_k[best_k]
best_score = score_recording[best_k]
best_cut_distance = cut_distance_by_k.get(best_k, _cut_distance_for_k(Z, best_k))
# Secondary tolerance (alt_k) relative to chosen best_k
if tol_mode == "relative":
alt_thresh = best_score * (1.0 - float(silhouette_tol))
else:
alt_thresh = best_score - float(silhouette_tol)
alt_candidates = [k for k in k_range if score_recording[k] >= alt_thresh]
if tol_k_select == "gap":
alt_k = _gap_k(Z, alt_candidates) if alt_candidates else best_k
else:
alt_k = _k_select(alt_candidates) if alt_candidates else best_k
alt_labels = labels_by_k[alt_k]
alt_cut_distance = cut_distance_by_k.get(alt_k, _cut_distance_for_k(Z, alt_k))
leaf_order_active = dendrogram(Z, no_plot=True)["leaves"]
return dict(
linkage=Z,
leaf_order=_expand_leaf_order(leaf_order_active),
labels=_expand_labels(best_labels, best_k),
k=best_k,
silhouette=best_score,
score_recording=score_recording,
cophenet_score=c,
cut_distance_by_k=cut_distance_by_k,
best_cut_distance=best_cut_distance,
labels_by_k={k: _expand_labels(lbls, k) for k, lbls in labels_by_k.items()},
strict_best_k=strict_best_k,
strict_best_score=strict_best_score,
primary_candidates=primary_candidates,
alt_k=alt_k,
alt_labels=_expand_labels(alt_labels, alt_k),
alt_cut_distance=alt_cut_distance,
)
def cluster_variance_matrix_forgroup(
V: np.ndarray,
k_min: int = 3,
k_max: int = 40,
row_groups: Optional[Sequence[Sequence[int]]] = None,
col_groups_all_lst: Optional[List[Sequence[Sequence[int]]]] = None,
*,
metric: str = "euclidean",
row_metric: Optional[str] = None,
row_method: Optional[str] = None,
col_metric: Optional[str] = None,
col_method: Optional[str] = None,
select_min_k_within_tol: bool = True,
silhouette_tol: float = 0.02,