Repository navigation
Expand file tree
/
Copy pathfitting_base.py
More file actions
233 lines (189 loc) · 7.86 KB
/
Copy pathfitting_base.py
File metadata and controls
233 lines (189 loc) · 7.86 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
"""
PSF Fitting: shared pieces
==========================
LocalizationResult (result container), BaseFitter (camera parameters) and the
2D Gaussian PSF models used by the fitters in fitting.py. Re-exported from
fitting.py, so `from thunderstorm_python.fitting import gaussian_2d` still works.
"""
import numpy as np
from scipy.special import erf
from .uncertainty import excess_noise_factor
class LocalizationResult:
"""Container for localization results.
Positions are in camera pixels with a pixel-centre origin: the centre of
pixel (row 0, col 0) is (x, y) = (0, 0), x along columns, y along rows.
Candidates whose fit failed are not localizations: they go to the
`rejected` table (candidate pixel and a reason) instead.
"""
def __init__(self):
self.rejected = {'x': [], 'y': [], 'reason': []} # failed fits (candidate pixel)
self.x = [] # x position (col)
self.y = [] # y position (row)
self.z = [] # z position (if 3D)
self.intensity = [] # Fitted intensity
self.background = [] # Fitted background
self.sigma_x = [] # PSF width in x
self.sigma_y = [] # PSF width in y (for elliptical)
self.frame = [] # Frame number
self.uncertainty = [] # Localization uncertainty
self.chi_squared = [] # Goodness of fit
def add_localization(self, x, y, intensity, background, sigma_x,
sigma_y=None, frame=None, uncertainty=None,
chi_squared=None, z=None):
"""Add a localization."""
self.x.append(x)
self.y.append(y)
self.intensity.append(intensity)
self.background.append(background)
self.sigma_x.append(sigma_x)
self.sigma_y.append(sigma_y if sigma_y is not None else sigma_x)
self.frame.append(frame)
self.uncertainty.append(uncertainty)
self.chi_squared.append(chi_squared)
if z is not None:
self.z.append(z)
def add_rejected(self, x, y, reason):
"""Record a candidate whose fit failed (x = column, y = row of the candidate pixel)."""
self.rejected['x'].append(x)
self.rejected['y'].append(y)
self.rejected['reason'].append(reason)
def rejected_to_array(self):
"""Rejected candidates as {'x', 'y' (pixels), 'reason'} arrays."""
return {'x': np.array(self.rejected['x'], float), 'y': np.array(self.rejected['y'], float),
'reason': np.array(self.rejected['reason'], dtype=object)}
def to_array(self):
"""Convert to numpy array."""
data = {
'x': np.array(self.x),
'y': np.array(self.y),
'intensity': np.array(self.intensity),
'background': np.array(self.background),
'sigma_x': np.array(self.sigma_x),
'sigma_y': np.array(self.sigma_y),
'frame': np.array(self.frame),
'uncertainty': np.array(self.uncertainty),
'chi_squared': np.array(self.chi_squared)
}
if self.z:
data['z'] = np.array(self.z)
return data
def __len__(self):
return len(self.x)
class BaseFitter:
"""Base class for PSF fitters."""
def __init__(self, name="BaseFitter"):
self.name = name
self.pixel_size = 100.0 # nm/pixel
self.photons_per_adu = 1.0 # Conversion factor
self.baseline = 0.0 # Camera baseline offset
self.em_gain = 1.0 # EM gain for EMCCD
def set_camera_params(self, pixel_size=None, photons_per_adu=None,
baseline=None, em_gain=None):
"""Set camera parameters."""
if pixel_size is not None:
self.pixel_size = pixel_size
if photons_per_adu is not None:
self.photons_per_adu = photons_per_adu
if baseline is not None:
self.baseline = baseline
if em_gain is not None:
if em_gain < 1:
raise ValueError("em_gain must be >= 1 (1 = no electron multiplication)")
self.em_gain = em_gain
def counts_to_photons(self, counts, subtract_baseline=False):
"""Camera counts (ADU) -> photons: (counts [- baseline]) * photons_per_adu / em_gain."""
c = counts - self.baseline if subtract_baseline else counts
return c * self.photons_per_adu / self.em_gain
def excess_noise_factor(self):
"""EMCCD excess-noise factor for the uncertainty (2 if em_gain > 1, else 1)."""
return excess_noise_factor(self.em_gain)
def fit(self, image, positions, fit_radius=3):
"""Fit PSF at given positions.
Parameters
----------
image : ndarray
Image to fit
positions : ndarray
Array of (row, col) approximate positions
fit_radius : int
Radius of fitting region
Returns
-------
result : LocalizationResult
Fitted localizations
"""
raise NotImplementedError
def gaussian_2d(xy, x0, y0, amplitude, sigma_x, sigma_y, background):
"""2D Gaussian function.
Parameters
----------
xy : tuple
(x, y) coordinates
x0, y0 : float
Center position
amplitude : float
Peak amplitude
sigma_x, sigma_y : float
Standard deviations
background : float
Background offset
Returns
-------
values : ndarray
Gaussian values at xy positions
"""
x, y = xy
g = amplitude * np.exp(-(((x - x0) ** 2) / (2 * sigma_x ** 2) +
((y - y0) ** 2) / (2 * sigma_y ** 2)))
return (g + background).ravel()
def integrated_gaussian_2d(xy, x0, y0, amplitude, sigma_x, sigma_y, background):
"""Integrated 2D Gaussian (accounts for pixel integration).
More accurate for fitting to pixel data.
"""
x, y = xy
# Pixel boundaries
x_left = x - 0.5
x_right = x + 0.5
y_bottom = y - 0.5
y_top = y + 0.5
# Integrated Gaussian using error function
norm_x = np.sqrt(2) * sigma_x
norm_y = np.sqrt(2) * sigma_y
int_x = 0.5 * (erf((x_right - x0) / norm_x) - erf((x_left - x0) / norm_x))
int_y = 0.5 * (erf((y_top - y0) / norm_y) - erf((y_bottom - y0) / norm_y))
g = amplitude * int_x * int_y
return (g + background).ravel()
def psf_model(integrated=True, elliptical=False):
"""Model function for curve_fit / likelihoods.
elliptical=False: f(xy, x0, y0, amplitude, sigma, background), one width.
elliptical=True: f(xy, x0, y0, amplitude, sigma_x, sigma_y, background).
"""
base = integrated_gaussian_2d if integrated else gaussian_2d
if elliptical:
return base
def symmetric(xy, x0, y0, amplitude, sigma, background):
return base(xy, x0, y0, amplitude, sigma, sigma, background)
return symmetric
def initial_params(x0, y0, amplitude, sigma, background, elliptical=False):
"""Start vector matching psf_model(..., elliptical)."""
if elliptical:
return [x0, y0, amplitude, sigma, sigma, background]
return [x0, y0, amplitude, sigma, background]
def split_params(p, elliptical=False):
"""(x0, y0, amplitude, sigma_x, sigma_y, background) from a parameter vector; widths made positive."""
if elliptical:
x0, y0, amp, sx, sy, bg = p
else:
x0, y0, amp, sx, bg = p
sy = sx
return x0, y0, amp, abs(sx), abs(sy), bg
def effective_sigma(sigma_x, sigma_y):
"""Single PSF width for the uncertainty formula: geometric mean sqrt(sigma_x * sigma_y)."""
return float(np.sqrt(sigma_x * sigma_y))
def rejection_reason(params, amplitude):
"""Why a converged fit is not a localization, or None: non-finite parameters or no signal."""
if not np.all(np.isfinite(params)):
return 'non-finite fit parameters'
if not amplitude > 0:
return 'non-positive fitted intensity'
return None