Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve tdc clustering options #3658

Merged
merged 9 commits into from
Feb 19, 2025
9 changes: 9 additions & 0 deletions src/spikeinterface/sorters/internal/tridesclous2.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,16 @@ class Tridesclous2Sorter(ComponentsBasedSorter):
"selection": {"n_peaks_per_channel": 5000, "min_n_peaks": 20000},
"svd": {"n_components": 6},
"clustering": {
"recursive_depth": 3,
"split_radius_um": 40.0,
"clusterer": "hdbscan",
"clusterer_kwargs": {
"min_cluster_size": 10,
"min_samples": 1,
"allow_single_cluster": True,
"cluster_selection_method": "eom",
},
"do_merge": True,
"merge_radius_um": 40.0,
"threshold_diff": 1.5,
},
Expand Down
6 changes: 5 additions & 1 deletion src/spikeinterface/sortingcomponents/clustering/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def merge_clusters(
fig, ax = plt.subplots()
clusterer = hdbscan.HDBSCAN(metric="precomputed", min_cluster_size=2, allow_single_cluster=True)
clusterer.fit(pair_values)
print(clusterer.labels_)
# print(clusterer.labels_)
clusterer.single_linkage_tree_.plot(cmap="viridis", colorbar=True)
# ~ fig, ax = plt.subplots()
# ~ clusterer.minimum_spanning_tree_.plot(edge_cmap='viridis',
Expand Down Expand Up @@ -294,6 +294,10 @@ def find_merge_pairs(
template_locs = channel_locs[max_chans, :]
template_dist = scipy.spatial.distance.cdist(template_locs, template_locs, metric="euclidean")

# print("template_locs", template_locs.shape, template_locs)
# print("template_locs", np.unique(template_locs[:, 1]).shape)
# print("radius_um", radius_um)

pair_mask = pair_mask & (template_dist <= radius_um)
indices0, indices1 = np.nonzero(pair_mask)

Expand Down
4 changes: 2 additions & 2 deletions src/spikeinterface/sortingcomponents/clustering/split.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,10 +205,10 @@ def split(
recursion_level=1,
debug_folder=None,
clusterer="hdbscan",
clusterer_kwargs={"min_cluster_size": 25, "min_samples": 5},
feature_name="sparse_tsvd",
neighbours_mask=None,
waveforms_sparse_mask=None,
clusterer_kwargs={"min_cluster_size": 25},
min_size_split=25,
n_pca_features=2,
minimum_overlap_ratio=0.25,
Expand Down Expand Up @@ -261,7 +261,7 @@ def split(
if clusterer == "hdbscan":
from hdbscan import HDBSCAN

clust = HDBSCAN(**clusterer_kwargs)
clust = HDBSCAN(**clusterer_kwargs, core_dist_n_jobs=1)
clust.fit(final_features)
possible_labels = clust.labels_
is_split = np.setdiff1d(possible_labels, [-1]).size > 1
Expand Down
90 changes: 55 additions & 35 deletions src/spikeinterface/sortingcomponents/clustering/tdc.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,16 @@ class TdcClustering:
},
"svd": {"n_components": 6},
"clustering": {
"recursive_depth": 3,
"split_radius_um": 40.0,
"clusterer": "hdbscan",
"clusterer_kwargs": {
"min_cluster_size": 10,
"min_samples": 1,
"allow_single_cluster": True,
"cluster_selection_method": "eom",
},
"do_merge": True,
"merge_radius_um": 40.0,
"threshold_diff": 1.5,
},
Expand Down Expand Up @@ -142,18 +151,24 @@ def main_function(cls, recording, peaks, params, job_kwargs=dict()):
min_cluster_size = 50
# min_cluster_size = 10

clusterer = params["clustering"].get("clusterer", "hdbscan")
clusterer_kwargs = params["clustering"].get("clusterer_kwargs", {})

post_split_label, split_count = split_clusters(
original_labels,
recording,
features_folder,
method="local_feature_clustering",
method_kwargs=dict(
clusterer="hdbscan",
clusterer_kwargs={
"min_cluster_size": min_cluster_size,
"allow_single_cluster": True,
"cluster_selection_method": "eom",
},
clusterer=clusterer,
clusterer_kwargs=clusterer_kwargs,
# clusterer="hdbscan",
# clusterer_kwargs={
# "min_cluster_size": min_cluster_size,
# "allow_single_cluster": True,
# # "cluster_selection_method": "eom",
# "cluster_selection_method": "leaf",
# },
# clusterer="isocut5",
# clusterer_kwargs={"min_cluster_size": min_cluster_size},
feature_name="sparse_tsvd",
Expand All @@ -164,39 +179,44 @@ def main_function(cls, recording, peaks, params, job_kwargs=dict()):
n_pca_features=3,
),
recursive=True,
recursive_depth=3,
recursive_depth=params["clustering"]["recursive_depth"],
returns_split_count=True,
debug_folder=clustering_folder / "figure_debug_split",
**job_kwargs,
)

merge_radius_um = params["clustering"]["merge_radius_um"]
threshold_diff = params["clustering"]["threshold_diff"]

post_merge_label, peak_shifts = merge_clusters(
peaks,
post_split_label,
recording,
features_folder,
radius_um=merge_radius_um,
# method="project_distribution",
# method_kwargs=dict(
# waveforms_sparse_mask=sparse_mask,
# feature_name="sparse_wfs",
# projection="centroid",
# criteria="distrib_overlap",
# threshold_overlap=0.3,
# min_cluster_size=min_cluster_size + 1,
# num_shift=5,
# ),
method="normalized_template_diff",
method_kwargs=dict(
waveforms_sparse_mask=sparse_mask,
threshold_diff=threshold_diff,
min_cluster_size=min_cluster_size + 1,
num_shift=5,
),
**job_kwargs,
)
if params["clustering"]["do_merge"]:
merge_radius_um = params["clustering"]["merge_radius_um"]
threshold_diff = params["clustering"]["threshold_diff"]

post_merge_label, peak_shifts = merge_clusters(
peaks,
post_split_label,
recording,
features_folder,
radius_um=merge_radius_um,
# method="project_distribution",
# method_kwargs=dict(
# waveforms_sparse_mask=sparse_mask,
# feature_name="sparse_wfs",
# projection="centroid",
# criteria="distrib_overlap",
# threshold_overlap=0.3,
# min_cluster_size=min_cluster_size + 1,
# num_shift=5,
# ),
method="normalized_template_diff",
method_kwargs=dict(
waveforms_sparse_mask=sparse_mask,
threshold_diff=threshold_diff,
min_cluster_size=min_cluster_size + 1,
num_shift=5,
),
**job_kwargs,
)
else:
post_merge_label = post_split_label.copy()
peak_shifts = np.zeros(post_split_label.size, dtype="int64")

# sparse_wfs = np.load(features_folder / "sparse_wfs.npy", mmap_mode="r")

Expand Down
5 changes: 3 additions & 2 deletions src/spikeinterface/sortingcomponents/peak_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,8 +678,8 @@ def __init__(
random_data = get_random_data_chunks(recording, return_scaled=False, **random_chunk_kwargs)
conv_random_data = self.get_convolved_traces(random_data)
medians = np.median(conv_random_data, axis=1)
medians = medians[:, None]
noise_levels = np.median(np.abs(conv_random_data - medians), axis=1) / 0.6744897501960817
self.medians = medians[:, None]
noise_levels = np.median(np.abs(conv_random_data - self.medians), axis=1) / 0.6744897501960817
self.abs_thresholds = noise_levels * detect_threshold
self._dtype = np.dtype(base_peak_dtype + [("z", "float32")])

Expand All @@ -693,6 +693,7 @@ def compute(self, traces, start_frame, end_frame, segment_index, max_margin):

assert HAVE_NUMBA, "You need to install numba"
conv_traces = self.get_convolved_traces(traces)
# conv_traces -= self.medians
conv_traces /= self.abs_thresholds[:, None]
conv_traces = conv_traces[:, self.conv_margin : -self.conv_margin]
traces_center = conv_traces[:, self.exclude_sweep_size : -self.exclude_sweep_size]
Expand Down