-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfit_2Dgaussian.py
executable file
·46 lines (38 loc) · 1.54 KB
/
fit_2Dgaussian.py
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
import numpy as np
import scipy
def gaussian_here(height, center_x, center_y, width_x, width_y, rotation):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
rotation = np.deg2rad(rotation)
center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
def rotgauss(x,y):
xp = x * np.cos(rotation) - y * np.sin(rotation)
yp = x * np.sin(rotation) + y * np.cos(rotation)
g = height*np.exp(
-(((center_x-xp)/width_x)**2+
((center_y-yp)/width_y)**2)/2.)
return g
return rotgauss
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
col = data[:, int(y)]
width_x = np.sqrt(abs((np.arange(col.size)-y)**2*col).sum()/col.sum())
row = data[int(x), :]
width_y = np.sqrt(abs((np.arange(row.size)-x)**2*row).sum()/row.sum())
height = data.max()
return height, x, y, width_x, width_y, 0.0
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution found by a fit"""
params = moments(data)
errorfunction = lambda p: np.ravel(gaussian_here(*p)(*np.indices(data.shape)) - data)
p, _ = scipy.optimize.leastsq(errorfunction, params)
return p