DARTsort 0.3.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dartsort/__init__.py +68 -0
- dartsort/cli.py +105 -0
- dartsort/clustering/__init__.py +3 -0
- dartsort/clustering/cluster_util.py +392 -0
- dartsort/clustering/clustering.py +765 -0
- dartsort/clustering/clustering_features.py +202 -0
- dartsort/clustering/density.py +1299 -0
- dartsort/clustering/forward_backward.py +219 -0
- dartsort/clustering/gmm/mixture.py +5790 -0
- dartsort/clustering/gmm/stable_features.py +993 -0
- dartsort/clustering/kmeans.py +448 -0
- dartsort/clustering/merge.py +501 -0
- dartsort/clustering/modes.py +214 -0
- dartsort/clustering/refine_util.py +191 -0
- dartsort/clustering/relocate.py +109 -0
- dartsort/clustering/split.py +1285 -0
- dartsort/config.py +288 -0
- dartsort/detect/__init__.py +2 -0
- dartsort/detect/detect.py +449 -0
- dartsort/detect/detect_filters.py +37 -0
- dartsort/evaluate/__init__.py +1 -0
- dartsort/evaluate/analysis.py +594 -0
- dartsort/evaluate/comparison.py +534 -0
- dartsort/evaluate/hybrid_util.py +599 -0
- dartsort/evaluate/noise_recording_tools.py +184 -0
- dartsort/evaluate/sim_template_tools.py +842 -0
- dartsort/evaluate/simkit.py +840 -0
- dartsort/evaluate/simlib.py +270 -0
- dartsort/localize/__init__.py +0 -0
- dartsort/localize/localize_torch.py +291 -0
- dartsort/localize/localize_util.py +313 -0
- dartsort/main.py +657 -0
- dartsort/peel/__init__.py +6 -0
- dartsort/peel/grab.py +208 -0
- dartsort/peel/matching.py +628 -0
- dartsort/peel/matching_util/__init__.py +3 -0
- dartsort/peel/matching_util/compressed_upsampled.py +718 -0
- dartsort/peel/matching_util/drifty.py +791 -0
- dartsort/peel/matching_util/matching_base.py +616 -0
- dartsort/peel/matching_util/pairwise.py +359 -0
- dartsort/peel/matching_util/pairwise_util.py +1317 -0
- dartsort/peel/peel_base.py +1000 -0
- dartsort/peel/running_template.py +1498 -0
- dartsort/peel/subtract.py +1123 -0
- dartsort/peel/threshold.py +471 -0
- dartsort/peel/universal.py +191 -0
- dartsort/pretrained/default_temporal_kernel.npy +0 -0
- dartsort/pretrained/detect_np1.pt +0 -0
- dartsort/pretrained/detect_np2.pt +0 -0
- dartsort/pretrained/glasbey1024.npz +0 -0
- dartsort/pretrained/offset_trained_denoiser.pt +0 -0
- dartsort/pretrained/offset_trained_denoiser_added_temp.pt +0 -0
- dartsort/pretrained/offset_trained_denoiser_added_temp_boost.pt +0 -0
- dartsort/pretrained/original_single_chan_denoiser.pt +0 -0
- dartsort/pretrained/single_chan_denoiser.pt +0 -0
- dartsort/templates/__init__.py +11 -0
- dartsort/templates/get_templates.py +771 -0
- dartsort/templates/postprocess_util.py +555 -0
- dartsort/templates/realignment.py +466 -0
- dartsort/templates/superres_util.py +204 -0
- dartsort/templates/template_util.py +518 -0
- dartsort/templates/templates.py +528 -0
- dartsort/transform/__init__.py +2 -0
- dartsort/transform/_multichan_denoiser_kit.py +650 -0
- dartsort/transform/all_transformers.py +58 -0
- dartsort/transform/amortized_localization.py +503 -0
- dartsort/transform/amplitudes.py +197 -0
- dartsort/transform/decollider.py +635 -0
- dartsort/transform/enforce_decrease.py +158 -0
- dartsort/transform/localize.py +86 -0
- dartsort/transform/matching_denoiser.py +44 -0
- dartsort/transform/pipeline.py +391 -0
- dartsort/transform/single_channel_denoiser.py +153 -0
- dartsort/transform/single_channel_templates.py +98 -0
- dartsort/transform/supervised_denoiser.py +486 -0
- dartsort/transform/temporal_pca.py +413 -0
- dartsort/transform/transform_base.py +255 -0
- dartsort/util/__init__.py +0 -0
- dartsort/util/cli_util.py +179 -0
- dartsort/util/data_util.py +1128 -0
- dartsort/util/drift_util.py +1054 -0
- dartsort/util/internal_config.py +1074 -0
- dartsort/util/interpolation_util.py +1012 -0
- dartsort/util/job_util.py +19 -0
- dartsort/util/logging_util.py +91 -0
- dartsort/util/main_util.py +235 -0
- dartsort/util/more_operators.py +269 -0
- dartsort/util/multiprocessing_util.py +211 -0
- dartsort/util/nn_util.py +461 -0
- dartsort/util/noise_util.py +1461 -0
- dartsort/util/peel_util.py +223 -0
- dartsort/util/py_util.py +213 -0
- dartsort/util/registration_util.py +128 -0
- dartsort/util/residual_util.py +30 -0
- dartsort/util/sparse_util.py +81 -0
- dartsort/util/spikeio.py +227 -0
- dartsort/util/spiketorch.py +1198 -0
- dartsort/util/testing_util/__init__.py +0 -0
- dartsort/util/testing_util/matching_debug_util.py +517 -0
- dartsort/util/testing_util/mixture_testing_util.py +291 -0
- dartsort/util/torch_optimization_util.py +156 -0
- dartsort/util/torch_util.py +75 -0
- dartsort/util/universal_util.py +269 -0
- dartsort/util/waveform_util.py +809 -0
- dartsort/vis/__init__.py +19 -0
- dartsort/vis/analysis_plots.py +392 -0
- dartsort/vis/colors.py +36 -0
- dartsort/vis/gt.py +392 -0
- dartsort/vis/layout.py +149 -0
- dartsort/vis/metrics_util.py +23 -0
- dartsort/vis/mixture.py +1489 -0
- dartsort/vis/over_time.py +514 -0
- dartsort/vis/recanim.py +429 -0
- dartsort/vis/scatterplots.py +779 -0
- dartsort/vis/sorting.py +163 -0
- dartsort/vis/unit.py +917 -0
- dartsort/vis/unit_comparison.py +1017 -0
- dartsort/vis/versus.py +300 -0
- dartsort/vis/vismain.py +537 -0
- dartsort/vis/waveforms.py +357 -0
- dartsort-0.3.5.dist-info/METADATA +93 -0
- dartsort-0.3.5.dist-info/RECORD +125 -0
- dartsort-0.3.5.dist-info/WHEEL +5 -0
- dartsort-0.3.5.dist-info/entry_points.txt +2 -0
- dartsort-0.3.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1017 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
import warnings
|
|
3
|
+
from logging import getLogger
|
|
4
|
+
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
from matplotlib.colors import FuncNorm
|
|
7
|
+
from matplotlib.lines import Line2D
|
|
8
|
+
from matplotlib.scale import FuncScale
|
|
9
|
+
import numpy as np
|
|
10
|
+
import seaborn as sns
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from matplotlib_venn import venn2 # type: ignore
|
|
14
|
+
except ImportError:
|
|
15
|
+
|
|
16
|
+
def venn2(*args, **kwargs) -> Any:
|
|
17
|
+
raise ImportError("`matplotlib_venn` is needed for venn plots.")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
from .analysis_plots import correlogram, stackbar
|
|
21
|
+
from .colors import glasbey1024
|
|
22
|
+
from .layout import BasePlot
|
|
23
|
+
from .unit import make_all_summaries, make_unit_summary
|
|
24
|
+
from .waveforms import geomplot
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
logger = getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_class_colors = {
|
|
31
|
+
"tp": "darkorange",
|
|
32
|
+
"fp": "b",
|
|
33
|
+
"fn": "r",
|
|
34
|
+
"unsorted_tp": "blueviolet",
|
|
35
|
+
"unsorted_fn": "tan",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
_nmeth_names = {
|
|
39
|
+
"templates": "local",
|
|
40
|
+
"siagreement": "sitop",
|
|
41
|
+
"greedy": "greedytop",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# -- single-unit
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class UnitComparisonPlot(BasePlot):
|
|
49
|
+
kind = "unit_comparison"
|
|
50
|
+
neighbor_method = "templates"
|
|
51
|
+
which = "tested"
|
|
52
|
+
n_neighbors = 5
|
|
53
|
+
|
|
54
|
+
def draw(self, panel, comparison, unit_id):
|
|
55
|
+
tested_unit_id = comparison.get_match(unit_id)
|
|
56
|
+
return self._draw(panel, comparison, unit_id, tested_unit_id)
|
|
57
|
+
|
|
58
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
59
|
+
raise NotImplementedError
|
|
60
|
+
|
|
61
|
+
def neighbors(self, comparison, unit_id, which=None, method=None, n=None):
|
|
62
|
+
"""Gather neighboring tested or GT ids and templates for a GT unit."""
|
|
63
|
+
# TODO: maybe this should be a method of the comparison? or it should
|
|
64
|
+
# call one which has most of this logic? (nice to set neighbor_method
|
|
65
|
+
# as instance properties of these plots)
|
|
66
|
+
if method is None:
|
|
67
|
+
method = self.neighbor_method
|
|
68
|
+
if n is None:
|
|
69
|
+
n = self.n_neighbors
|
|
70
|
+
if which is None:
|
|
71
|
+
which = self.which
|
|
72
|
+
assert which in ("gt", "tested")
|
|
73
|
+
|
|
74
|
+
if method == "templates" and which == "gt":
|
|
75
|
+
ixs, ids, dists, templates = comparison.nearby_gt_templates(
|
|
76
|
+
unit_id, n_neighbors=n
|
|
77
|
+
)
|
|
78
|
+
del dists # just naming it for clarity
|
|
79
|
+
elif method == "templates" and which == "tested":
|
|
80
|
+
ixs, ids, dists, templates = comparison.nearby_tested_templates(
|
|
81
|
+
unit_id, n_neighbors=n
|
|
82
|
+
)
|
|
83
|
+
del dists
|
|
84
|
+
elif method == "siagreement" and which == "gt":
|
|
85
|
+
# gt units with top agreement to tested match
|
|
86
|
+
tested_unit_id = comparison.get_match(unit_id)
|
|
87
|
+
a = comparison.agreement_scores[tested_unit_id]
|
|
88
|
+
asorted = a.sort_values(ascending=False)
|
|
89
|
+
ids = asorted.index[:n].values if n else []
|
|
90
|
+
ixs = np.searchsorted(comparison.gt_analysis.unit_ids, ids)
|
|
91
|
+
if (ids == unit_id).any():
|
|
92
|
+
ids = [unit_id] + list(ids[ids != unit_id])
|
|
93
|
+
else:
|
|
94
|
+
ids = [unit_id] + list(ids[: n - 1])
|
|
95
|
+
templates = comparison.gt_analysis.coarse_template_data.unit_templates(ids)
|
|
96
|
+
elif method == "siagreement" and which == "tested":
|
|
97
|
+
# tested units with top agreement to gt
|
|
98
|
+
a = comparison.agreement_scores.loc[unit_id]
|
|
99
|
+
ids = a.sort_values(ascending=False).index[:n].values
|
|
100
|
+
ixs = np.searchsorted(comparison.tested_analysis.unit_ids, ids)
|
|
101
|
+
templates = comparison.tested_analysis.coarse_template_data.unit_templates(
|
|
102
|
+
ids
|
|
103
|
+
)
|
|
104
|
+
elif method == "greedy" and which == "gt":
|
|
105
|
+
tested_unit_id = comparison.get_match(unit_id)
|
|
106
|
+
g = comparison.greedy_iou[:, tested_unit_id]
|
|
107
|
+
ids = np.argsort(g)[::-1][: n - 1] if n else []
|
|
108
|
+
ixs = np.searchsorted(comparison.gt_analysis.unit_ids, ids)
|
|
109
|
+
if (ids == unit_id).any():
|
|
110
|
+
ids = [unit_id] + list(ids[ids != unit_id])
|
|
111
|
+
else:
|
|
112
|
+
ids = [unit_id] + list(ids[: n - 1])
|
|
113
|
+
templates = comparison.gt_analysis.coarse_template_data.unit_templates(ids)
|
|
114
|
+
elif method == "greedy" and which == "tested":
|
|
115
|
+
g = comparison.greedy_iou[unit_id]
|
|
116
|
+
ids = np.argsort(g)[::-1][:n]
|
|
117
|
+
ixs = np.searchsorted(comparison.tested_analysis.unit_ids, ids)
|
|
118
|
+
templates = comparison.tested_analysis.coarse_template_data.unit_templates(
|
|
119
|
+
ids
|
|
120
|
+
)
|
|
121
|
+
else:
|
|
122
|
+
raise ValueError(f"Unknown neighbor method {method}.")
|
|
123
|
+
|
|
124
|
+
return np.asarray(ixs), np.asarray(ids), templates
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class GTUnitTextInfo(UnitComparisonPlot):
|
|
128
|
+
kind = "_info"
|
|
129
|
+
width = 3
|
|
130
|
+
height = 2.25
|
|
131
|
+
|
|
132
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
133
|
+
axis = panel.subplots()
|
|
134
|
+
axis.axis("off")
|
|
135
|
+
|
|
136
|
+
gtn = comparison.gt_analysis.name
|
|
137
|
+
tn = comparison.tested_analysis.name
|
|
138
|
+
|
|
139
|
+
msg = f"{gtn} unit: {unit_id}\n"
|
|
140
|
+
msg += f"{tn} Hung. match: {tested_unit_id}\n"
|
|
141
|
+
best_match_id = comparison.get_best_match(unit_id)
|
|
142
|
+
msg += f"{tn} best match: {best_match_id}\n"
|
|
143
|
+
if best_match_id != tested_unit_id:
|
|
144
|
+
msg += " -!!!- Hungarian =/= best. -!!!-\n"
|
|
145
|
+
msg += "\n"
|
|
146
|
+
|
|
147
|
+
gt_nspikes = comparison.gt_analysis.spike_counts[
|
|
148
|
+
comparison.gt_analysis.unit_ids == unit_id
|
|
149
|
+
].sum()
|
|
150
|
+
tested_nspikes = comparison.tested_analysis.spike_counts[
|
|
151
|
+
comparison.tested_analysis.unit_ids == tested_unit_id
|
|
152
|
+
].sum()
|
|
153
|
+
msg += f"{gt_nspikes} spikes in {gtn} unit\n"
|
|
154
|
+
msg += f"{tested_nspikes} spikes in {tn} unit\n"
|
|
155
|
+
msg += "\n"
|
|
156
|
+
|
|
157
|
+
gt_temp = comparison.gt_analysis.coarse_template_data.unit_templates(unit_id)
|
|
158
|
+
gt_ptp = np.ptp(gt_temp, 1).max(1).squeeze()
|
|
159
|
+
assert gt_ptp.size == 1
|
|
160
|
+
msg += f"{gtn} PTP: {gt_ptp:0.1f}\n"
|
|
161
|
+
|
|
162
|
+
td = getattr(comparison, "template_distances", None)
|
|
163
|
+
if td is not None:
|
|
164
|
+
unit_ix = np.searchsorted(comparison.gt_analysis.unit_ids, unit_id)
|
|
165
|
+
tested_unit_ix = np.searchsorted(
|
|
166
|
+
comparison.tested_analysis.unit_ids, tested_unit_id
|
|
167
|
+
)
|
|
168
|
+
temp_dist = td[unit_ix, tested_unit_ix]
|
|
169
|
+
msg += f"Hung. temp dist: {temp_dist:0.1f}\n"
|
|
170
|
+
mn = td[unit_ix].min()
|
|
171
|
+
if mn < temp_dist:
|
|
172
|
+
msg += f"But, min temp dist={temp_dist:0.1f}\n"
|
|
173
|
+
|
|
174
|
+
if tested_unit_id >= 0:
|
|
175
|
+
tested_temp = (
|
|
176
|
+
comparison.tested_analysis.coarse_template_data.unit_templates(
|
|
177
|
+
tested_unit_id
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
tested_ptp = np.ptp(tested_temp, 1).max(1).squeeze()
|
|
181
|
+
msg += f"{tn} Hung. PTP: {tested_ptp:0.1f}\n"
|
|
182
|
+
msg += "\n"
|
|
183
|
+
|
|
184
|
+
inds = comparison.get_spikes_by_category(unit_id)
|
|
185
|
+
tp = inds["matched_gt_indices"].size
|
|
186
|
+
fn = inds["only_gt_indices"].size
|
|
187
|
+
fp = inds["only_tested_indices"].size
|
|
188
|
+
acc = tp / (tp + fn + fp)
|
|
189
|
+
rec = tp / max((tp + fn), 1)
|
|
190
|
+
prec = tp / max((tp + fp), 1)
|
|
191
|
+
fdr = fp / max((tp + fp), 1)
|
|
192
|
+
acc = f"{100 * acc:0.1f}".rstrip("0").rstrip(".")
|
|
193
|
+
rec = f"{100 * rec:0.1f}".rstrip("0").rstrip(".")
|
|
194
|
+
prec = f"{100 * prec:0.1f}".rstrip("0").rstrip(".")
|
|
195
|
+
fdr = f"{100 * fdr:0.1f}".rstrip("0").rstrip(".")
|
|
196
|
+
msg += f"acc (tpr)={acc}%\nrecall={rec}%\nprec={prec}%\nfdr={fdr}%"
|
|
197
|
+
|
|
198
|
+
axis.text(0, 0, msg, fontsize=8)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class MatchVennPlot(UnitComparisonPlot):
|
|
202
|
+
kind = "venn"
|
|
203
|
+
width = 3
|
|
204
|
+
height = 1.5
|
|
205
|
+
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
gt_color=None,
|
|
209
|
+
matched_color=None,
|
|
210
|
+
tested_color=None,
|
|
211
|
+
):
|
|
212
|
+
self.gt_color = gt_color or _class_colors["fn"]
|
|
213
|
+
self.matched_color = matched_color or _class_colors["tp"]
|
|
214
|
+
self.tested_color = tested_color or _class_colors["fp"]
|
|
215
|
+
|
|
216
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
217
|
+
inds = comparison.get_spikes_by_category(unit_id)
|
|
218
|
+
tp = inds["matched_gt_indices"].size
|
|
219
|
+
fn = inds["only_gt_indices"].size
|
|
220
|
+
fp = inds["only_tested_indices"].size
|
|
221
|
+
sizes = {"11": tp, "10": fn, "01": fp}
|
|
222
|
+
|
|
223
|
+
ax = panel.subplots()
|
|
224
|
+
v = venn2(
|
|
225
|
+
sizes,
|
|
226
|
+
set_colors=(self.gt_color, self.tested_color),
|
|
227
|
+
set_labels=(
|
|
228
|
+
f"{comparison.gt_name}#{unit_id}",
|
|
229
|
+
f"{comparison.tested_name}#{inds['tested_unit']}",
|
|
230
|
+
),
|
|
231
|
+
ax=ax,
|
|
232
|
+
)
|
|
233
|
+
if (p := v.get_patch_by_id("11")) is not None:
|
|
234
|
+
p.set_color(self.matched_color)
|
|
235
|
+
v.set_labels[0].set_color(self.gt_color)
|
|
236
|
+
if len(v.set_labels) > 1:
|
|
237
|
+
v.set_labels[1].set_color(self.tested_color)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class UnsortedVennPlot(UnitComparisonPlot):
|
|
241
|
+
kind = "venn"
|
|
242
|
+
width = 3
|
|
243
|
+
height = 1.5
|
|
244
|
+
|
|
245
|
+
def __init__(
|
|
246
|
+
self,
|
|
247
|
+
unsorted_matched_color=None,
|
|
248
|
+
unsorted_missed_color=None,
|
|
249
|
+
):
|
|
250
|
+
self.unsorted_matched_color = (
|
|
251
|
+
unsorted_matched_color or _class_colors["unsorted_tp"]
|
|
252
|
+
)
|
|
253
|
+
self.unsorted_missed_color = (
|
|
254
|
+
unsorted_missed_color or _class_colors["unsorted_fn"]
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
258
|
+
inds = comparison.get_spikes_by_category(unit_id)
|
|
259
|
+
tp = inds["unsorted_tp_indices"].size
|
|
260
|
+
fn = inds["unsorted_fn_indices"].size
|
|
261
|
+
fp = 0 # can't assess here
|
|
262
|
+
sizes = {"11": tp, "10": fn, "01": fp}
|
|
263
|
+
|
|
264
|
+
ax = panel.subplots()
|
|
265
|
+
v = venn2(
|
|
266
|
+
subsets=sizes,
|
|
267
|
+
set_colors=(self.unsorted_missed_color, "k"),
|
|
268
|
+
set_labels=(
|
|
269
|
+
f"{comparison.gt_name}#{unit_id}",
|
|
270
|
+
f"{comparison.tested_name}#unsort",
|
|
271
|
+
),
|
|
272
|
+
ax=ax,
|
|
273
|
+
)
|
|
274
|
+
if (p := v.get_patch_by_id("11")) is not None:
|
|
275
|
+
p.set_color(self.unsorted_matched_color)
|
|
276
|
+
v.set_labels[0].set_color(self.unsorted_missed_color)
|
|
277
|
+
if len(v.set_labels) > 1:
|
|
278
|
+
v.set_labels[1].set_color(self.unsorted_matched_color)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class MatchRawWaveformsPlot(UnitComparisonPlot):
|
|
282
|
+
def __init__(
|
|
283
|
+
self,
|
|
284
|
+
alpha=0.25,
|
|
285
|
+
gt_color=None,
|
|
286
|
+
matched_color=None,
|
|
287
|
+
tested_color=None,
|
|
288
|
+
unsorted_matched_color=None,
|
|
289
|
+
unsorted_missed_color=None,
|
|
290
|
+
count=50,
|
|
291
|
+
single_channel=False,
|
|
292
|
+
order="tprandom",
|
|
293
|
+
show_sorted_matches=True,
|
|
294
|
+
show_unsorted_matches=False,
|
|
295
|
+
average=False,
|
|
296
|
+
):
|
|
297
|
+
self.colors = {}
|
|
298
|
+
self.show_sorted_matches = show_sorted_matches
|
|
299
|
+
self.show_unsorted_matches = show_unsorted_matches
|
|
300
|
+
if show_sorted_matches:
|
|
301
|
+
self.colors["tp"] = matched_color or _class_colors["tp"]
|
|
302
|
+
self.colors["fp"] = tested_color or _class_colors["fp"]
|
|
303
|
+
self.colors["fn"] = gt_color or _class_colors["fn"]
|
|
304
|
+
if show_unsorted_matches:
|
|
305
|
+
self.colors["unsorted_tp"] = (
|
|
306
|
+
unsorted_matched_color or _class_colors["unsorted_tp"]
|
|
307
|
+
)
|
|
308
|
+
self.colors["unsorted_fn"] = (
|
|
309
|
+
unsorted_missed_color or _class_colors["unsorted_fn"]
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
self.count = count
|
|
313
|
+
self.alpha = alpha
|
|
314
|
+
if order == "random":
|
|
315
|
+
self.randomize = True
|
|
316
|
+
if order == "tprandom":
|
|
317
|
+
self.randomize = show_unsorted_matches
|
|
318
|
+
elif order == "tpfpfn":
|
|
319
|
+
# this ordering is because of insertion ordering of colors
|
|
320
|
+
# dict above
|
|
321
|
+
self.randomize = False
|
|
322
|
+
else:
|
|
323
|
+
assert False
|
|
324
|
+
self.order = order
|
|
325
|
+
|
|
326
|
+
self.kind = "traces" if single_channel else "waveforms"
|
|
327
|
+
self.width = 2 if single_channel else 5
|
|
328
|
+
self.height = 3 if single_channel else 5
|
|
329
|
+
self.average = average
|
|
330
|
+
|
|
331
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
332
|
+
w = comparison.get_raw_waveforms_by_category(
|
|
333
|
+
unit_id,
|
|
334
|
+
tested_unit=tested_unit_id,
|
|
335
|
+
max_samples_per_category=self.count,
|
|
336
|
+
random_seed=0,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
waveforms = []
|
|
340
|
+
colors = []
|
|
341
|
+
maa = 1.0
|
|
342
|
+
for kind, color in self.colors.items():
|
|
343
|
+
if w[kind] is None or not w[kind].size or not np.isfinite(w[kind]).any():
|
|
344
|
+
continue
|
|
345
|
+
with warnings.catch_warnings():
|
|
346
|
+
warnings.filterwarnings("ignore", r"All-NaN (slice|axis) encountered")
|
|
347
|
+
maxs = np.nanmax(np.abs(w[kind]), axis=(1, 2))
|
|
348
|
+
maxs = np.nan_to_num(maxs, nan=1.0)
|
|
349
|
+
maa = max(maa, np.percentile(maxs, 90))
|
|
350
|
+
if self.average:
|
|
351
|
+
avg = w[kind].mean(0, keepdims=True)
|
|
352
|
+
waveforms.append(avg)
|
|
353
|
+
else:
|
|
354
|
+
waveforms.append(w[kind])
|
|
355
|
+
colors.append(np.broadcast_to([color], waveforms[-1].shape[:1]))
|
|
356
|
+
|
|
357
|
+
if self.order == "tprandom" and not self.average and len(waveforms) > 1:
|
|
358
|
+
wlast = np.concatenate(waveforms[1:])
|
|
359
|
+
clast = np.concatenate(colors[1:])
|
|
360
|
+
n = len(wlast)
|
|
361
|
+
shuf = np.random.default_rng(0).permutation(n)
|
|
362
|
+
waveforms = [waveforms[0], wlast[shuf]]
|
|
363
|
+
colors = [colors[0], clast[shuf]]
|
|
364
|
+
|
|
365
|
+
waveforms = np.concatenate(waveforms)
|
|
366
|
+
colors = np.concatenate(colors)
|
|
367
|
+
max_channels = np.broadcast_to([w["max_chan"]], colors.shape)
|
|
368
|
+
|
|
369
|
+
ax = panel.subplots()
|
|
370
|
+
max_abs_amp = maa
|
|
371
|
+
chans = w["channel_index"][w["max_chan"]]
|
|
372
|
+
chans = chans[chans < len(w["geom"])]
|
|
373
|
+
geomplot(
|
|
374
|
+
waveforms,
|
|
375
|
+
max_channels=max_channels,
|
|
376
|
+
channel_index=w["channel_index"],
|
|
377
|
+
geom=w["geom"],
|
|
378
|
+
ax=ax,
|
|
379
|
+
show_zero=False,
|
|
380
|
+
max_abs_amp=max_abs_amp,
|
|
381
|
+
annotate_z=True,
|
|
382
|
+
subar=True,
|
|
383
|
+
colors=colors,
|
|
384
|
+
alpha=1.0 if self.average else self.alpha,
|
|
385
|
+
randomize=self.randomize,
|
|
386
|
+
)
|
|
387
|
+
ax.axis("off")
|
|
388
|
+
handles = {
|
|
389
|
+
k: Line2D([0, 1], [0, 0], color=v, lw=1) for k, v in self.colors.items()
|
|
390
|
+
}
|
|
391
|
+
if self.average and tested_unit_id >= 0:
|
|
392
|
+
tested_template = (
|
|
393
|
+
comparison.tested_analysis.coarse_template_data.unit_templates(
|
|
394
|
+
tested_unit_id
|
|
395
|
+
)
|
|
396
|
+
)
|
|
397
|
+
tested_template = tested_template[:, :, chans]
|
|
398
|
+
testedline = geomplot(
|
|
399
|
+
tested_template,
|
|
400
|
+
channels=chans[None],
|
|
401
|
+
geom=w["geom"],
|
|
402
|
+
ax=ax,
|
|
403
|
+
max_abs_amp=max_abs_amp,
|
|
404
|
+
show_zero=False,
|
|
405
|
+
subar=False,
|
|
406
|
+
annotate_z=False,
|
|
407
|
+
color=glasbey1024[tested_unit_id % len(glasbey1024)],
|
|
408
|
+
linestyle=(1, (1, 1)),
|
|
409
|
+
)
|
|
410
|
+
tk = f"{comparison.tested_analysis.name}#{tested_unit_id}"
|
|
411
|
+
handles[tk] = testedline # type: ignore
|
|
412
|
+
if self.average:
|
|
413
|
+
gt_template = comparison.gt_analysis.coarse_template_data.unit_templates(
|
|
414
|
+
unit_id
|
|
415
|
+
)
|
|
416
|
+
gt_template = gt_template[:, :, chans]
|
|
417
|
+
gtline = geomplot(
|
|
418
|
+
gt_template,
|
|
419
|
+
channels=chans[None],
|
|
420
|
+
geom=w["geom"],
|
|
421
|
+
ax=ax,
|
|
422
|
+
max_abs_amp=max_abs_amp,
|
|
423
|
+
show_zero=False,
|
|
424
|
+
subar=False,
|
|
425
|
+
annotate_z=False,
|
|
426
|
+
color="k",
|
|
427
|
+
linestyle=(0, (1, 1)),
|
|
428
|
+
)
|
|
429
|
+
handles["GT"] = gtline # type: ignore
|
|
430
|
+
|
|
431
|
+
ax.legend(
|
|
432
|
+
handles=handles.values(),
|
|
433
|
+
labels=handles.keys(),
|
|
434
|
+
fancybox=False,
|
|
435
|
+
loc="upper center",
|
|
436
|
+
borderpad=0.2,
|
|
437
|
+
labelspacing=0.2,
|
|
438
|
+
handlelength=1.0,
|
|
439
|
+
columnspacing=1.0,
|
|
440
|
+
frameon=False,
|
|
441
|
+
ncols=min(3, len(handles)),
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
k = ""
|
|
445
|
+
if self.show_unsorted_matches:
|
|
446
|
+
k = "unsorted tp/fn"
|
|
447
|
+
if self.show_sorted_matches:
|
|
448
|
+
k = "sorted tp/fp/fn"
|
|
449
|
+
a = ""
|
|
450
|
+
if self.average:
|
|
451
|
+
a = "avg "
|
|
452
|
+
ax.set_title(f"{k} {a}waveforms")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
class TemplateDistanceHistogram(UnitComparisonPlot):
|
|
456
|
+
"""All tested units' distances to a GT unit's template"""
|
|
457
|
+
|
|
458
|
+
kind = "histogram"
|
|
459
|
+
|
|
460
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
461
|
+
ax = panel.subplots()
|
|
462
|
+
d = np.nan_to_num(comparison.template_distances, nan=np.inf)
|
|
463
|
+
vm = min(d.min(0).max(), d.min(1).max())
|
|
464
|
+
bins = np.logspace(np.log10(d.min()), np.log10(vm), 96)
|
|
465
|
+
x = d[unit_id]
|
|
466
|
+
x = x[np.isfinite(x)]
|
|
467
|
+
ax.hist(x, color="orange", bins=bins)
|
|
468
|
+
ax.grid(which="both")
|
|
469
|
+
ax.semilogx()
|
|
470
|
+
ax.set_xlabel("tested template distance to GT")
|
|
471
|
+
ax.set_ylabel("count")
|
|
472
|
+
ax.axvline(d[unit_id][tested_unit_id], c="k", label="Hung. match dist.")
|
|
473
|
+
ax.legend(frameon=False, loc="upper right")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
class NearbyTemplates(UnitComparisonPlot):
|
|
477
|
+
def __init__(
|
|
478
|
+
self,
|
|
479
|
+
n_neighbors=5,
|
|
480
|
+
single_channel=False,
|
|
481
|
+
which="tested",
|
|
482
|
+
neighbor_method="templates",
|
|
483
|
+
):
|
|
484
|
+
self.single_channel = single_channel
|
|
485
|
+
self.n_neighbors = n_neighbors
|
|
486
|
+
self.kind = "traces" if single_channel else "waveforms"
|
|
487
|
+
self.width = 2 if single_channel else 4
|
|
488
|
+
self.height = 2 if single_channel else 7
|
|
489
|
+
self.which = which
|
|
490
|
+
self.neighbor_method = neighbor_method
|
|
491
|
+
|
|
492
|
+
def draw(self, panel, comparison, unit_id):
|
|
493
|
+
try:
|
|
494
|
+
neighb_ixs, neighb_ids, templates = self.neighbors(
|
|
495
|
+
comparison, unit_id, which=self.which
|
|
496
|
+
)
|
|
497
|
+
except Exception:
|
|
498
|
+
neighbor_error_panel(self, panel, unit_id)
|
|
499
|
+
return
|
|
500
|
+
# reverse so matched/gt unit comes last for draw order
|
|
501
|
+
neighb_ids = neighb_ids[::-1]
|
|
502
|
+
templates = templates[::-1]
|
|
503
|
+
|
|
504
|
+
if self.which == "tested":
|
|
505
|
+
sname = comparison.tested_name
|
|
506
|
+
# stack on the GT template
|
|
507
|
+
gt_template = comparison.gt_analysis.coarse_template_data.unit_templates(
|
|
508
|
+
unit_id
|
|
509
|
+
)
|
|
510
|
+
templates = np.concatenate([templates, gt_template], axis=0)
|
|
511
|
+
colors = [*glasbey1024[neighb_ids % len(glasbey1024)], "k"]
|
|
512
|
+
labels = list(map(str, neighb_ids)) + [f"{comparison.gt_name}#{unit_id}"]
|
|
513
|
+
elif self.which == "gt":
|
|
514
|
+
sname = comparison.gt_name
|
|
515
|
+
gt_template = templates[-1]
|
|
516
|
+
colors = list(glasbey1024[neighb_ids[:-1] % len(glasbey1024)]) + ["k"]
|
|
517
|
+
labels = list(map(str, neighb_ids))
|
|
518
|
+
else:
|
|
519
|
+
assert False
|
|
520
|
+
|
|
521
|
+
max_chan = comparison.gt_analysis.unit_max_channel(unit_id)
|
|
522
|
+
geom = comparison.gt_analysis.registered_geom
|
|
523
|
+
channels = comparison.gt_analysis.vis_channel_index[max_chan]
|
|
524
|
+
channels = channels[channels < len(geom)]
|
|
525
|
+
templates = templates[:, :, channels]
|
|
526
|
+
|
|
527
|
+
ax = panel.subplots()
|
|
528
|
+
maa = np.nanmax(np.abs(gt_template))
|
|
529
|
+
handles = []
|
|
530
|
+
for t, c in zip(templates, colors):
|
|
531
|
+
ls = "-"
|
|
532
|
+
if isinstance(c, str) and c == "k":
|
|
533
|
+
ls = (0, (1, 1))
|
|
534
|
+
lines = geomplot(
|
|
535
|
+
t[None],
|
|
536
|
+
channels=channels[None],
|
|
537
|
+
geom=geom,
|
|
538
|
+
ax=ax,
|
|
539
|
+
show_zero=False,
|
|
540
|
+
subar=not self.single_channel,
|
|
541
|
+
color=c,
|
|
542
|
+
zlim="tight",
|
|
543
|
+
max_abs_amp=maa,
|
|
544
|
+
linestyle=ls,
|
|
545
|
+
)
|
|
546
|
+
handles.append(lines)
|
|
547
|
+
ax.axis("off")
|
|
548
|
+
ax.set_xticks([])
|
|
549
|
+
ax.set_yticks([])
|
|
550
|
+
ns = _nmeth_names[self.neighbor_method]
|
|
551
|
+
ax.set_title(f"{ns} {sname} templates")
|
|
552
|
+
if not self.single_channel:
|
|
553
|
+
ax.legend(
|
|
554
|
+
handles=handles,
|
|
555
|
+
labels=labels,
|
|
556
|
+
fancybox=False,
|
|
557
|
+
loc="upper center",
|
|
558
|
+
borderpad=0.2,
|
|
559
|
+
labelspacing=0.2,
|
|
560
|
+
handlelength=1.0,
|
|
561
|
+
columnspacing=1.0,
|
|
562
|
+
frameon=False,
|
|
563
|
+
ncols=min(3, len(templates)),
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
class NearbyTemplatesDistanceMatrix(UnitComparisonPlot):
|
|
568
|
+
kind = "minimatrix"
|
|
569
|
+
width = 3
|
|
570
|
+
height = 2.5
|
|
571
|
+
|
|
572
|
+
def __init__(self, n_neighbors=5, cmap="magma", neighbor_method="templates"):
|
|
573
|
+
self.n_neighbors = n_neighbors
|
|
574
|
+
self.neighbor_method = neighbor_method
|
|
575
|
+
self.cmap = plt.get_cmap(cmap)
|
|
576
|
+
|
|
577
|
+
def draw(self, panel, comparison, unit_id):
|
|
578
|
+
try:
|
|
579
|
+
gt_neighb_ixs, gt_neighb_ids, _ = self.neighbors(
|
|
580
|
+
comparison, unit_id, which="gt"
|
|
581
|
+
)
|
|
582
|
+
except Exception:
|
|
583
|
+
neighbor_error_panel(self, panel, unit_id, which="gt")
|
|
584
|
+
return
|
|
585
|
+
tested_neighb_ixs, tested_neighb_ids, _ = self.neighbors(
|
|
586
|
+
comparison, unit_id, which="tested"
|
|
587
|
+
)
|
|
588
|
+
dists = comparison.template_distances[gt_neighb_ixs][:, tested_neighb_ixs]
|
|
589
|
+
ax = panel.subplots()
|
|
590
|
+
# log1p_norm = FuncNorm((np.log1p, np.expm1), vmin=0)
|
|
591
|
+
sqrt_norm = FuncNorm((np.sqrt, np.square), vmin=0)
|
|
592
|
+
im = ax.imshow(
|
|
593
|
+
dists,
|
|
594
|
+
# norm=log1p_norm,
|
|
595
|
+
norm=sqrt_norm,
|
|
596
|
+
cmap=self.cmap,
|
|
597
|
+
)
|
|
598
|
+
if np.isfinite(dists).any():
|
|
599
|
+
plt.colorbar(im, ax=ax, shrink=0.6)
|
|
600
|
+
ax.set_ylabel(f"{comparison.gt_name} unit")
|
|
601
|
+
ax.set_xlabel(f"{comparison.tested_name} unit")
|
|
602
|
+
ax.set_yticks(range(len(dists)), gt_neighb_ids)
|
|
603
|
+
ax.set_xticks(range(len(dists.T)), tested_neighb_ids, rotation="vertical")
|
|
604
|
+
for t, ix in zip(ax.get_xticklabels(), tested_neighb_ids):
|
|
605
|
+
t.set_color(glasbey1024[int(ix) % len(glasbey1024)])
|
|
606
|
+
ns = _nmeth_names[self.neighbor_method]
|
|
607
|
+
ax.set_title(f"{ns} temp dist")
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
class NearbyTemplatesConfusionMatrix(UnitComparisonPlot):
|
|
611
|
+
kind = "minimatrix"
|
|
612
|
+
width = 3
|
|
613
|
+
height = 2.5
|
|
614
|
+
|
|
615
|
+
def __init__(
|
|
616
|
+
self,
|
|
617
|
+
n_neighbors=5,
|
|
618
|
+
cmap="pink",
|
|
619
|
+
confusion_kind="siconfusion",
|
|
620
|
+
neighbor_method="templates",
|
|
621
|
+
):
|
|
622
|
+
self.n_neighbors = n_neighbors
|
|
623
|
+
self.cmap = plt.get_cmap(cmap)
|
|
624
|
+
self.confusion_kind = confusion_kind
|
|
625
|
+
self.neighbor_method = neighbor_method
|
|
626
|
+
|
|
627
|
+
def draw(self, panel, comparison, unit_id):
|
|
628
|
+
try:
|
|
629
|
+
gt_neighb_ixs, gt_neighb_ids, _ = self.neighbors(
|
|
630
|
+
comparison, unit_id, which="gt"
|
|
631
|
+
)
|
|
632
|
+
except Exception:
|
|
633
|
+
neighbor_error_panel(self, panel, unit_id, which="gt")
|
|
634
|
+
return
|
|
635
|
+
tested_neighb_ixs, tested_neighb_ids, _ = self.neighbors(
|
|
636
|
+
comparison, unit_id, which="tested"
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
if self.confusion_kind == "siconfusion":
|
|
640
|
+
conf = comparison.comparison.get_confusion_matrix()
|
|
641
|
+
elif self.confusion_kind == "siagreement":
|
|
642
|
+
conf = comparison.agreement_scores
|
|
643
|
+
elif self.confusion_kind == "greedy":
|
|
644
|
+
conf = comparison.greedy_confusion
|
|
645
|
+
union = (conf.sum(0, keepdims=True) + conf.sum(1, keepdims=True)) - conf
|
|
646
|
+
conf = conf[gt_neighb_ids][:, tested_neighb_ids]
|
|
647
|
+
conf_rows = gt_neighb_ids
|
|
648
|
+
conf_cols = tested_neighb_ids
|
|
649
|
+
else:
|
|
650
|
+
assert False
|
|
651
|
+
|
|
652
|
+
if self.confusion_kind.startswith("si"):
|
|
653
|
+
conf = conf[conf.index != "FP"].sort_index()
|
|
654
|
+
conf_row_labels = conf.index.values
|
|
655
|
+
conf_rows = (
|
|
656
|
+
np.searchsorted(conf_row_labels, gt_neighb_ids, side="right") - 1
|
|
657
|
+
)
|
|
658
|
+
assert np.array_equal(conf.index[conf_rows], gt_neighb_ids)
|
|
659
|
+
|
|
660
|
+
conf_col_labels = np.array(
|
|
661
|
+
[int(c) if c != "FN" else 1_000_000 for c in conf.columns]
|
|
662
|
+
)
|
|
663
|
+
col_order = np.argsort(conf_col_labels)
|
|
664
|
+
conf_cols = np.searchsorted(
|
|
665
|
+
conf_col_labels, tested_neighb_ids, sorter=col_order
|
|
666
|
+
)
|
|
667
|
+
conf_cols = col_order[conf_cols]
|
|
668
|
+
# sometimes a nearest template has no spikes. sad but true.
|
|
669
|
+
conf_cols_found = tested_neighb_ids == conf_cols
|
|
670
|
+
conf_cols = conf_cols[conf_cols_found]
|
|
671
|
+
tested_neighb_ids = conf_cols
|
|
672
|
+
cfull = conf.values
|
|
673
|
+
union = (cfull.sum(0, keepdims=True) + cfull.sum(1, keepdims=True)) - cfull
|
|
674
|
+
conf = cfull[conf_rows][:, conf_cols]
|
|
675
|
+
|
|
676
|
+
if self.confusion_kind in ("siconfusion", "greedy"):
|
|
677
|
+
union = union[conf_rows][:, conf_cols] # type: ignore[reportPossiblyUnbound]
|
|
678
|
+
union[union == 0] = 1
|
|
679
|
+
conf = conf / union
|
|
680
|
+
suffix = " iou"
|
|
681
|
+
else:
|
|
682
|
+
suffix = ""
|
|
683
|
+
|
|
684
|
+
conf = np.nan_to_num(conf)
|
|
685
|
+
if conf.min() < -1e-3:
|
|
686
|
+
warnings.warn(f"Large {conf.min()=} with {self.confusion_kind=}.")
|
|
687
|
+
conf = np.abs(np.clip(conf, min=0.0)) # type: ignore[reportCallIssue]
|
|
688
|
+
|
|
689
|
+
ax = panel.subplots()
|
|
690
|
+
sqrt_norm = FuncNorm((np.sqrt, np.square), vmin=0, vmax=max(conf.max(), 0.01))
|
|
691
|
+
im = ax.imshow(conf, cmap=self.cmap, norm=sqrt_norm, interpolation="none")
|
|
692
|
+
for (j, i), v in np.ndenumerate(conf):
|
|
693
|
+
ax.text(i, j, f"{v:.2f}".lstrip("0"), ha="center", va="center", fontsize=6)
|
|
694
|
+
plt.colorbar(im, ax=ax, shrink=0.4)
|
|
695
|
+
ax.set_ylabel(f"{comparison.gt_name} unit")
|
|
696
|
+
ax.set_xlabel(f"{comparison.tested_name} unit")
|
|
697
|
+
ns = _nmeth_names[self.neighbor_method]
|
|
698
|
+
ax.set_title(f"{ns} {self.confusion_kind}{suffix}", fontsize=10)
|
|
699
|
+
ax.set_yticks(range(len(conf)), gt_neighb_ids)
|
|
700
|
+
if len(tested_neighb_ids):
|
|
701
|
+
ax.set_xticks(range(len(conf.T)), tested_neighb_ids, rotation="vertical")
|
|
702
|
+
for t, ix in zip(ax.get_xticklabels(), tested_neighb_ids):
|
|
703
|
+
t.set_color(glasbey1024[int(ix) % len(glasbey1024)])
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
class MatchedMisalignmentHist(UnitComparisonPlot):
|
|
707
|
+
kind = "hist"
|
|
708
|
+
width = 3
|
|
709
|
+
height = 2
|
|
710
|
+
|
|
711
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
712
|
+
ax = panel.subplots()
|
|
713
|
+
if tested_unit_id < 0:
|
|
714
|
+
ax.text(0, 0, f"no match for {unit_id}")
|
|
715
|
+
ax.axis("off")
|
|
716
|
+
return
|
|
717
|
+
|
|
718
|
+
match_dt = comparison.matched_misalignment(unit_id)
|
|
719
|
+
if match_dt is None:
|
|
720
|
+
ax.text(0, 0, f"ST shape mismatch (SI issue...?)")
|
|
721
|
+
ax.axis("off")
|
|
722
|
+
return
|
|
723
|
+
|
|
724
|
+
df = comparison.delta_frames
|
|
725
|
+
bins = np.arange(-df, df + 1)
|
|
726
|
+
c = glasbey1024[unit_id % len(glasbey1024)]
|
|
727
|
+
_, _, hist = ax.hist(match_dt, bins=bins, color=c, log=True)
|
|
728
|
+
ax.set_ylabel("frequency")
|
|
729
|
+
ax.grid()
|
|
730
|
+
gn = comparison.gt_name
|
|
731
|
+
tn = comparison.tested_name
|
|
732
|
+
ax.set_xlabel(f"matched {tn} time - {gn} time")
|
|
733
|
+
if match_dt.size:
|
|
734
|
+
rms = np.sqrt(np.square(match_dt).mean())
|
|
735
|
+
ax.legend(
|
|
736
|
+
handles=[hist[0]],
|
|
737
|
+
labels=[f"dt, RMS={rms:.1f}"],
|
|
738
|
+
loc="lower right",
|
|
739
|
+
frameon=False,
|
|
740
|
+
bbox_to_anchor=(0, 1, 1, 1),
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
class NeighborCCGBreakdown(UnitComparisonPlot):
|
|
745
|
+
"""Tested unit's CCG with nearby GT or tested units, broken down by fp/fn."""
|
|
746
|
+
|
|
747
|
+
kind = "ccg"
|
|
748
|
+
width = 3
|
|
749
|
+
|
|
750
|
+
def __init__(
|
|
751
|
+
self,
|
|
752
|
+
n_neighbors=5,
|
|
753
|
+
which="gt",
|
|
754
|
+
neighbor_method="templates",
|
|
755
|
+
categories=("fn", "fp"),
|
|
756
|
+
max_lag=50,
|
|
757
|
+
):
|
|
758
|
+
self.n_neighbors = n_neighbors
|
|
759
|
+
self.which = which
|
|
760
|
+
self.neighbor_method = neighbor_method
|
|
761
|
+
self.height = 1 + 1.5 * len(categories)
|
|
762
|
+
self.categories = categories
|
|
763
|
+
assert all(cat in _class_colors for cat in categories)
|
|
764
|
+
self.max_lag = max_lag
|
|
765
|
+
|
|
766
|
+
def _draw(self, panel, comparison, unit_id, tested_unit_id):
|
|
767
|
+
try:
|
|
768
|
+
ixs, ids, _ = self.neighbors(comparison, unit_id, n=self.n_neighbors + 1)
|
|
769
|
+
except Exception:
|
|
770
|
+
neighbor_error_panel(self, panel, unit_id, tested_unit_id)
|
|
771
|
+
return
|
|
772
|
+
if self.which == "gt":
|
|
773
|
+
ids = ids[1:] # remove main.
|
|
774
|
+
if self.which == "tested":
|
|
775
|
+
ids = np.concatenate([ids, [-1]])
|
|
776
|
+
|
|
777
|
+
ta = comparison.tested_analysis
|
|
778
|
+
va = comparison.gt_analysis if self.which == "gt" else ta
|
|
779
|
+
vsts = {u: va.sorting.times_samples[va.in_unit(u)] for u in ids}
|
|
780
|
+
cat_spikes = comparison.get_spikes_by_category(unit_id, tested_unit_id)
|
|
781
|
+
colors = glasbey1024[ids % len(glasbey1024)]
|
|
782
|
+
|
|
783
|
+
axes = panel.subplots(nrows=len(self.categories), sharex=True)
|
|
784
|
+
h = 1.5 * len(self.categories)
|
|
785
|
+
for cat, ax in zip(self.categories, axes.flat):
|
|
786
|
+
cat_st = cat_spikes[f"{cat}_times_samples"]
|
|
787
|
+
ccgs = []
|
|
788
|
+
clags = None
|
|
789
|
+
for u, vst in vsts.items():
|
|
790
|
+
clags, ccg = correlogram(cat_st, vst, max_lag=self.max_lag)
|
|
791
|
+
ccgs.append(ccg)
|
|
792
|
+
assert clags is not NotImplemented
|
|
793
|
+
|
|
794
|
+
stackbar(ax, clags, ccgs, colors=colors, labels=ids)
|
|
795
|
+
sns.despine(ax=ax, left=True)
|
|
796
|
+
if cat == self.categories[0]:
|
|
797
|
+
ax.legend(
|
|
798
|
+
loc="lower center",
|
|
799
|
+
borderpad=0.2,
|
|
800
|
+
labelspacing=0.2,
|
|
801
|
+
handlelength=1.0,
|
|
802
|
+
columnspacing=1.0,
|
|
803
|
+
frameon=False,
|
|
804
|
+
ncols=min(3, len(ids)),
|
|
805
|
+
bbox_to_anchor=(0, 1, h / (1 + h), 1 / h),
|
|
806
|
+
)
|
|
807
|
+
ax.grid(which="both")
|
|
808
|
+
ax.axvline(0, lw=0.8, color="k", alpha=0.5)
|
|
809
|
+
ax.set_ylabel(f"{va.name} CCG v. {cat}", color=_class_colors[cat])
|
|
810
|
+
if max(map(max, ccgs)) == 0:
|
|
811
|
+
ax.set_yticks([])
|
|
812
|
+
ax.set_xlabel("lag (samples)") # type: ignore
|
|
813
|
+
ns = _nmeth_names[self.neighbor_method]
|
|
814
|
+
cs = " / ".join(self.categories)
|
|
815
|
+
panel.suptitle(f"{ns} {va.name} CCGs for {cs}", fontsize=10)
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
class CollidednessBreakdown(UnitComparisonPlot):
|
|
819
|
+
kind = "hist"
|
|
820
|
+
width = 3
|
|
821
|
+
height = 2
|
|
822
|
+
|
|
823
|
+
def __init__(self, log_x=False, sqrt_x=True, n_bins=64, log=True):
|
|
824
|
+
self.log_x = log_x
|
|
825
|
+
self.sqrt_x = sqrt_x
|
|
826
|
+
self.n_bins = n_bins
|
|
827
|
+
self.log = log
|
|
828
|
+
|
|
829
|
+
def draw(self, panel, comparison, unit_id):
|
|
830
|
+
gt_sorting = comparison.gt_analysis.sorting
|
|
831
|
+
ax = panel.subplots()
|
|
832
|
+
if not hasattr(gt_sorting, "collidedness"):
|
|
833
|
+
ax.text(
|
|
834
|
+
0,
|
|
835
|
+
0,
|
|
836
|
+
"gt sorting has\nno collidedness",
|
|
837
|
+
fontsize=8,
|
|
838
|
+
ha="center",
|
|
839
|
+
va="center",
|
|
840
|
+
)
|
|
841
|
+
ax.axis("off")
|
|
842
|
+
return
|
|
843
|
+
|
|
844
|
+
inu, matchu, missu = comparison.matched_and_missed(unit_id)
|
|
845
|
+
unsorted_masku = comparison.unsorted_detection[inu]
|
|
846
|
+
unsorted_missu = inu[np.logical_not(unsorted_masku)]
|
|
847
|
+
|
|
848
|
+
coll_match = gt_sorting.collidedness[matchu]
|
|
849
|
+
coll_miss = gt_sorting.collidedness[missu]
|
|
850
|
+
coll_umiss = gt_sorting.collidedness[unsorted_missu]
|
|
851
|
+
|
|
852
|
+
colls = [coll_match, coll_miss, coll_umiss]
|
|
853
|
+
nothing = not any(a.size for a in colls)
|
|
854
|
+
if nothing:
|
|
855
|
+
mn = 1
|
|
856
|
+
mx = 10
|
|
857
|
+
else:
|
|
858
|
+
mn = np.floor(min(a.min() for a in colls if a.size))
|
|
859
|
+
mx = np.ceil(max(a.max() for a in colls if a.size))
|
|
860
|
+
if self.log_x:
|
|
861
|
+
bins = np.logspace(np.log10(mn), np.log10(mx), self.n_bins + 1)
|
|
862
|
+
elif self.sqrt_x:
|
|
863
|
+
bins = np.square(np.linspace(mn**0.5, mx**0.5, self.n_bins + 1))
|
|
864
|
+
else:
|
|
865
|
+
bins = np.linspace(mn, mx, self.n_bins + 1)
|
|
866
|
+
|
|
867
|
+
labels = ["tp", "fn", "unsorted_fn"]
|
|
868
|
+
labels = [l for l, c in zip(labels, colls) if c.size]
|
|
869
|
+
colls = [c for c in colls if c.size]
|
|
870
|
+
colors = [_class_colors[k] for k in labels]
|
|
871
|
+
ax.hist(
|
|
872
|
+
colls, label=labels, color=colors, bins=bins, log=self.log, histtype="step"
|
|
873
|
+
)
|
|
874
|
+
if self.log_x:
|
|
875
|
+
ax.set_xscale("log")
|
|
876
|
+
elif self.sqrt_x:
|
|
877
|
+
from matplotlib.scale import FuncScale
|
|
878
|
+
|
|
879
|
+
ax.set_xscale("function", functions=(np.sqrt, np.square))
|
|
880
|
+
ax.grid()
|
|
881
|
+
ticks = [0, 10, 25, 50, 100, 200, 350, 600]
|
|
882
|
+
ticks = [t for t in ticks if mn <= t <= mx]
|
|
883
|
+
ax.set_xticks(ticks)
|
|
884
|
+
ax.legend(
|
|
885
|
+
borderpad=0.2,
|
|
886
|
+
labelspacing=0.2,
|
|
887
|
+
handlelength=1.0,
|
|
888
|
+
columnspacing=0.6,
|
|
889
|
+
frameon=False,
|
|
890
|
+
loc="lower center",
|
|
891
|
+
bbox_to_anchor=(0, 1, 1, 1),
|
|
892
|
+
ncols=min(3, len(colls)),
|
|
893
|
+
)
|
|
894
|
+
ax.set_xlabel("collidedness")
|
|
895
|
+
ax.set_ylabel("frequency")
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _get_default_unit_comparison_plots():
|
|
899
|
+
return (
|
|
900
|
+
GTUnitTextInfo(),
|
|
901
|
+
MatchVennPlot(),
|
|
902
|
+
UnsortedVennPlot(),
|
|
903
|
+
NeighborCCGBreakdown(),
|
|
904
|
+
NeighborCCGBreakdown(which="tested"),
|
|
905
|
+
NeighborCCGBreakdown(neighbor_method="siagreement"),
|
|
906
|
+
NearbyTemplatesDistanceMatrix(),
|
|
907
|
+
# NearbyTemplatesConfusionMatrix(),
|
|
908
|
+
NearbyTemplatesConfusionMatrix(confusion_kind="siagreement"),
|
|
909
|
+
NearbyTemplatesConfusionMatrix(confusion_kind="greedy"),
|
|
910
|
+
NearbyTemplatesConfusionMatrix(
|
|
911
|
+
neighbor_method="siagreement", confusion_kind="siagreement"
|
|
912
|
+
),
|
|
913
|
+
NearbyTemplatesConfusionMatrix(
|
|
914
|
+
neighbor_method="greedy", confusion_kind="greedy"
|
|
915
|
+
),
|
|
916
|
+
MatchedMisalignmentHist(),
|
|
917
|
+
CollidednessBreakdown(),
|
|
918
|
+
# MatchRawWaveformsPlot(single_channel=True),
|
|
919
|
+
# MatchRawWaveformsPlot(
|
|
920
|
+
# show_sorted_matches=False,
|
|
921
|
+
# show_unsorted_matches=True,
|
|
922
|
+
# single_channel=True,
|
|
923
|
+
# ),
|
|
924
|
+
# NearbyTemplates(single_channel=True),
|
|
925
|
+
MatchRawWaveformsPlot(),
|
|
926
|
+
MatchRawWaveformsPlot(
|
|
927
|
+
show_sorted_matches=False,
|
|
928
|
+
show_unsorted_matches=True,
|
|
929
|
+
),
|
|
930
|
+
NearbyTemplates(),
|
|
931
|
+
MatchRawWaveformsPlot(average=True),
|
|
932
|
+
MatchRawWaveformsPlot(
|
|
933
|
+
show_sorted_matches=False,
|
|
934
|
+
show_unsorted_matches=True,
|
|
935
|
+
average=True,
|
|
936
|
+
),
|
|
937
|
+
NearbyTemplates(which="gt"),
|
|
938
|
+
)
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
default_unit_comparison_plots = _get_default_unit_comparison_plots()
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def make_unit_comparison(
|
|
945
|
+
comparison,
|
|
946
|
+
unit_id,
|
|
947
|
+
plots=None,
|
|
948
|
+
max_height=18,
|
|
949
|
+
figsize=(16, 18),
|
|
950
|
+
figure=None,
|
|
951
|
+
**other_global_params,
|
|
952
|
+
):
|
|
953
|
+
if plots is None:
|
|
954
|
+
plots = _get_default_unit_comparison_plots()
|
|
955
|
+
return make_unit_summary(
|
|
956
|
+
comparison,
|
|
957
|
+
unit_id,
|
|
958
|
+
plots=plots,
|
|
959
|
+
max_height=max_height,
|
|
960
|
+
figsize=figsize,
|
|
961
|
+
figure=figure,
|
|
962
|
+
gizmo_name="comparison",
|
|
963
|
+
**other_global_params,
|
|
964
|
+
)
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def make_all_unit_comparisons(
|
|
968
|
+
comparison,
|
|
969
|
+
save_folder,
|
|
970
|
+
plots=None,
|
|
971
|
+
max_height=18,
|
|
972
|
+
figsize=(16, 18),
|
|
973
|
+
dpi=300,
|
|
974
|
+
image_ext="png",
|
|
975
|
+
namebyamp=True,
|
|
976
|
+
n_jobs=0,
|
|
977
|
+
show_progress=True,
|
|
978
|
+
overwrite=False,
|
|
979
|
+
unit_ids=None,
|
|
980
|
+
**other_global_params,
|
|
981
|
+
):
|
|
982
|
+
if plots is None:
|
|
983
|
+
plots = _get_default_unit_comparison_plots()
|
|
984
|
+
return make_all_summaries(
|
|
985
|
+
comparison,
|
|
986
|
+
save_folder,
|
|
987
|
+
plots=plots,
|
|
988
|
+
max_height=max_height,
|
|
989
|
+
figsize=figsize,
|
|
990
|
+
dpi=dpi,
|
|
991
|
+
image_ext=image_ext,
|
|
992
|
+
namebyamp=namebyamp,
|
|
993
|
+
n_jobs=n_jobs,
|
|
994
|
+
show_progress=show_progress,
|
|
995
|
+
overwrite=overwrite,
|
|
996
|
+
gizmo_name="comparison",
|
|
997
|
+
taskname="comparisons",
|
|
998
|
+
unit_ids=unit_ids if unit_ids is not None else comparison.gt_analysis.unit_ids,
|
|
999
|
+
**other_global_params,
|
|
1000
|
+
)
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def neighbor_error_panel(plot_obj, panel, unit_id, tested_unit_id=None, which=None):
|
|
1004
|
+
ax = panel.subplots()
|
|
1005
|
+
ax.text(
|
|
1006
|
+
0,
|
|
1007
|
+
0,
|
|
1008
|
+
f"no {which or plot_obj.which} neighbor\n"
|
|
1009
|
+
f"for gt unit {unit_id}\n and\n"
|
|
1010
|
+
f"tested unit {tested_unit_id} with method\n"
|
|
1011
|
+
f"{plot_obj.neighbor_method} in\n"
|
|
1012
|
+
f"{plot_obj.__class__.__name__}",
|
|
1013
|
+
fontsize=8,
|
|
1014
|
+
ha="center",
|
|
1015
|
+
va="center",
|
|
1016
|
+
)
|
|
1017
|
+
ax.axis("off")
|