Repository navigation
Expand file tree
/
Copy pathpostprocessing.py
More file actions
348 lines (270 loc) · 10.7 KB
/
Copy pathpostprocessing.py
File metadata and controls
348 lines (270 loc) · 10.7 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
"""
Post-Processing Module
=====================
Implements post-processing methods:
- Drift correction (fiducial markers and cross-correlation; in drift.py)
- Merging of reappearing molecules
- Duplicate removal
- Filtering based on localization quality
- Local density filtering
- Z-stage offset correction
"""
import numpy as np
from scipy.spatial import cKDTree
from .drift import DriftCorrector # noqa: F401 (re-exported for backward compatibility)
class MolecularMerger:
"""Merge molecules appearing in subsequent frames.
Accounts for blinking - molecules can disappear for several frames.
Parameters
----------
max_distance : float
Maximum distance (nm) to consider molecules the same
max_frame_gap : int
Maximum frame gap for reappearance
"""
def __init__(self, max_distance=50, max_frame_gap=1):
self.max_distance = max_distance
self.max_frame_gap = max_frame_gap
def merge(self, localizations):
"""Merge reappearing molecules.
Parameters
----------
localizations : dict
Localization data
Returns
-------
merged : dict
Merged localizations
"""
# Sort by frame
sort_idx = np.argsort(localizations['frame'])
x = localizations['x'][sort_idx]
y = localizations['y'][sort_idx]
frames = localizations['frame'][sort_idx]
# Track which localizations have been merged
merged_into = -np.ones(len(x), dtype=int) # -1 means not merged
# Process frame by frame
unique_frames = np.unique(frames)
for i, frame in enumerate(unique_frames[:-1]):
# Get localizations in current frame
current_mask = frames == frame
current_indices = np.where(current_mask)[0]
# Look ahead up to max_frame_gap
for gap in range(1, self.max_frame_gap + 1):
if i + gap >= len(unique_frames):
break
next_frame = unique_frames[i + gap]
next_mask = frames == next_frame
next_indices = np.where(next_mask)[0]
# Build KD-tree for current frame
current_positions = np.column_stack([x[current_indices], y[current_indices]])
if len(current_positions) == 0:
continue
tree = cKDTree(current_positions)
# Query for each next frame localization
next_positions = np.column_stack([x[next_indices], y[next_indices]])
for j, next_idx in enumerate(next_indices):
if merged_into[next_idx] >= 0:
# Already merged
continue
# Find nearest neighbor in current frame
dist, idx = tree.query(next_positions[j])
if dist <= self.max_distance:
# Merge: mark as merged into current localization
current_idx = current_indices[idx]
merged_into[next_idx] = current_idx
# Create merged localizations
# Keep only localizations that are either:
# 1. Not merged (merged_into == -1)
# 2. Are the target of a merge
keep_mask = merged_into == -1
merged = {}
for key in localizations:
if key in ['x', 'y', 'intensity', 'background', 'sigma_x', 'sigma_y', 'frame']:
merged[key] = localizations[key][sort_idx][keep_mask]
return merged
class LocalizationFilter:
"""Filter localizations based on quality criteria.
Parameters
----------
min_intensity : float, optional
Minimum intensity
max_intensity : float, optional
Maximum intensity
max_uncertainty : float, optional
Maximum localization uncertainty (nm)
min_sigma : float, optional
Minimum PSF sigma
max_sigma : float, optional
Maximum PSF sigma
"""
def __init__(self, min_intensity=None, max_intensity=None,
max_uncertainty=None, min_sigma=None, max_sigma=None):
self.min_intensity = min_intensity
self.max_intensity = max_intensity
self.max_uncertainty = max_uncertainty
self.min_sigma = min_sigma
self.max_sigma = max_sigma
def filter(self, localizations):
"""Apply filters to localizations.
Parameters
----------
localizations : dict
Localization data
Returns
-------
filtered : dict
Filtered localizations
"""
mask = np.ones(len(localizations['x']), dtype=bool)
# Apply intensity filters
if self.min_intensity is not None:
mask &= localizations['intensity'] >= self.min_intensity
if self.max_intensity is not None:
mask &= localizations['intensity'] <= self.max_intensity
# Apply uncertainty filter
if self.max_uncertainty is not None and 'uncertainty' in localizations:
mask &= localizations['uncertainty'] <= self.max_uncertainty
# Apply sigma filters
if self.min_sigma is not None:
mask &= localizations['sigma_x'] >= self.min_sigma
if self.max_sigma is not None:
mask &= localizations['sigma_x'] <= self.max_sigma
# Apply mask
filtered = {}
for key, value in localizations.items():
if isinstance(value, np.ndarray):
filtered[key] = value[mask]
else:
filtered[key] = value
return filtered
class LocalDensityFilter:
"""Filter based on local density (removes isolated localizations).
Parameters
----------
radius : float
Search radius (nm)
min_neighbors : int
Minimum number of neighbors required
use_3d : bool
Use 3D distance (requires 'z' coordinate)
"""
def __init__(self, radius=50, min_neighbors=3, use_3d=False):
self.radius = radius
self.min_neighbors = min_neighbors
self.use_3d = use_3d
def filter(self, localizations):
"""Filter by local density.
Parameters
----------
localizations : dict
Localization data
Returns
-------
filtered : dict
Filtered localizations
"""
# Build position array
if self.use_3d and 'z' in localizations:
positions = np.column_stack([
localizations['x'],
localizations['y'],
localizations['z']
])
else:
positions = np.column_stack([
localizations['x'],
localizations['y']
])
# Build KD-tree
tree = cKDTree(positions)
# Query for neighbors
neighbors = tree.query_ball_point(positions, self.radius)
# Count neighbors (excluding self)
neighbor_counts = np.array([len(n) - 1 for n in neighbors])
# Filter
mask = neighbor_counts >= self.min_neighbors
filtered = {}
for key, value in localizations.items():
if isinstance(value, np.ndarray):
filtered[key] = value[mask]
else:
filtered[key] = value
return filtered
class DuplicateRemover:
"""Remove duplicate localizations from multi-emitter fitting.
Parameters
----------
max_distance : float
Maximum distance (nm) to consider duplicates
"""
def __init__(self, max_distance=20):
self.max_distance = max_distance
def remove_duplicates(self, localizations):
"""Remove duplicate localizations within same frame.
Parameters
----------
localizations : dict
Localization data
Returns
-------
unique : dict
Localizations with duplicates removed
"""
unique_mask = np.ones(len(localizations['x']), dtype=bool)
# Process frame by frame
for frame in np.unique(localizations['frame']):
frame_mask = localizations['frame'] == frame
frame_indices = np.where(frame_mask)[0]
if len(frame_indices) <= 1:
continue
# Build KD-tree for frame
positions = np.column_stack([
localizations['x'][frame_indices],
localizations['y'][frame_indices]
])
tree = cKDTree(positions)
# Find pairs within max_distance
pairs = tree.query_pairs(self.max_distance)
# For each pair, keep the brighter one
for i, j in pairs:
idx_i = frame_indices[i]
idx_j = frame_indices[j]
if localizations['intensity'][idx_i] < localizations['intensity'][idx_j]:
unique_mask[idx_i] = False
else:
unique_mask[idx_j] = False
# Apply mask
unique = {}
for key, value in localizations.items():
if isinstance(value, np.ndarray):
unique[key] = value[unique_mask]
else:
unique[key] = value
return unique
def z_stage_offset_correction(localizations, z_stage_positions, frame_to_zstage):
"""Correct Z positions for multi-Z-stage acquisition.
Parameters
----------
localizations : dict
Localization data with 'z' positions
z_stage_positions : dict
Mapping of Z-stage index to absolute Z position
frame_to_zstage : dict
Mapping of frame number to Z-stage index
Returns
-------
corrected : dict
Z-corrected localizations
"""
if 'z' not in localizations:
return localizations
corrected = localizations.copy()
for frame in np.unique(localizations['frame']):
if frame in frame_to_zstage:
z_stage_idx = frame_to_zstage[frame]
if z_stage_idx in z_stage_positions:
z_offset = z_stage_positions[z_stage_idx]
mask = localizations['frame'] == frame
corrected['z'][mask] += z_offset
return corrected