Skip to content

Commit 590bedb

Browse files
committedMar 23, 2016
examples: add fit_image
1 parent 3c624c7 commit 590bedb

File tree

1 file changed

+138
-0
lines changed

1 file changed

+138
-0
lines changed
 

‎examples/fit_image.py

+138
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import numpy as np
2+
from scipy.optimize import least_squares
3+
from scipy import constants
4+
# from numba import jit
5+
6+
7+
class Fit:
8+
variables = [] # fixed ordering
9+
10+
def build(self, data, meta):
11+
self.data = data
12+
self.meta = meta
13+
14+
def variables_dict(self, param):
15+
return dict(zip(self.variables, param))
16+
17+
def guess(self):
18+
raise NotImplementedError
19+
20+
def model(self, *param, **kwargs):
21+
raise NotImplementedError
22+
23+
def fit(self, *param, **kwargs):
24+
def fun(x, *args, **kwargs):
25+
return (self.model(x, *args, **kwargs) - self.data).ravel()
26+
27+
try:
28+
mjac = self.model_jacobian
29+
30+
def jac(x, *args, **kwargs):
31+
return mjac(x, *args, **kwargs).reshape(-1, x.size)
32+
except AttributeError:
33+
jac = "2-point"
34+
35+
res = least_squares(fun, param, jac, **kwargs)
36+
_, s, v = np.linalg.svd(res.jac, full_matrices=False)
37+
threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]
38+
s = s[s > threshold]
39+
v = v[:s.size]
40+
pcov = np.dot(v.T/s**2, v)
41+
return res.x, pcov
42+
43+
def process(self, cov, *param):
44+
return self.variables_dict(param)
45+
46+
def run(self, data, meta, **kwargs):
47+
self.build(data, meta)
48+
param = self.guess()
49+
param, cov = self.fit(*param, **kwargs)
50+
results = self.process(cov, *param)
51+
return param, results
52+
53+
54+
def od_to_n(od, meta):
55+
return (od*meta["pitch_x"]*meta["pitch_x"] *
56+
(1.+4.*meta["detuning"]**2)/meta["sigma0"])
57+
58+
59+
def area_gauss(p, h, w):
60+
return 2.*np.pi*p*abs(w*h)
61+
62+
63+
def area_parabola(p, h, w):
64+
return p*2/5.*np.pi/abs(w*h)**.5
65+
66+
67+
def t_gauss(mass, omega, width, tof):
68+
return mass/constants.Boltzmann*(omega*width)**2/(1. + (tof*omega)**2)
69+
70+
71+
class Fit2DGaussParabola(Fit):
72+
variables = ["i_offset", "x_center", "y_center",
73+
"a_parabola", "v_parabola", "w_parabola",
74+
"a_gauss", "v_gauss", "w_gauss"]
75+
76+
def build(self, data, meta):
77+
super(Fit2DGaussParabola, self).build(data, meta)
78+
self.xy = np.ogrid[:data.shape[0], :data.shape[1]]
79+
80+
def guess(self):
81+
# TODO: this is usually smarter, based on self.data and self.meta
82+
return [1000, 100, 100, 2000, 4, 4, 2000, 20, 20]
83+
84+
# @jit
85+
def model(self, param):
86+
p = self.variables_dict(param)
87+
x, y = self.xy
88+
x2 = (x - p["x_center"])**2
89+
y2 = (y - p["y_center"])**2
90+
gauss = p["a_gauss"]*np.exp(
91+
-(x2/p["v_gauss"]**2 + y2/p["w_gauss"]**2)/2)
92+
r = 1 - p["v_parabola"]*x2 - p["w_parabola"]*y2
93+
parabola = p["a_parabola"]*np.where(r > 0, r, 0)**1.5
94+
return p["i_offset"] + gauss + parabola
95+
96+
def process(self, cov, *param):
97+
r = self.variables_dict(param)
98+
r["cov"] = np.diag(cov)
99+
# TODO: handle cov, compute confidence intervals
100+
r["n_condensate"] = area_parabola(od_to_n(r["a_parabola"], self.meta),
101+
r["v_parabola"], r["w_parabola"])
102+
r["n_thermal"] = area_gauss(od_to_n(r["a_gauss"], self.meta),
103+
r["v_gauss"], r["w_gauss"])
104+
r["t_x"] = t_gauss(self.meta["mass"], self.meta["omega_x"],
105+
r["v_gauss"]*self.meta["pitch_x"], self.meta["tof"])
106+
r["t_y"] = t_gauss(self.meta["mass"], self.meta["omega_y"],
107+
r["w_gauss"]*self.meta["pitch_y"], self.meta["tof"])
108+
r["t"] = (r["t_x"] + r["t_y"])/2
109+
return r
110+
111+
112+
if __name__ == "__main__":
113+
# generate some test data
114+
f = Fit2DGaussParabola()
115+
f.xy = np.ogrid[:300, :300]
116+
i = f.model(f.guess())
117+
# make it noisy
118+
i += 100 + np.random.randn(*i.shape)*200 + i*np.random.randn(*i.shape)*.1
119+
meta = dict(mass=constants.atomic_mass*87, tof=25e-3,
120+
omega_x=2*np.pi*30, omega_y=2*np.pi*100,
121+
pitch_x=2e-6, pitch_y=2e-6,
122+
detuning=0, sigma0=1e-12)
123+
124+
# fit it
125+
f = Fit2DGaussParabola()
126+
p, r = f.run(i, meta)
127+
print(r)
128+
129+
from timeit import timeit
130+
print(timeit("f.model(p)", globals=globals(), number=10))
131+
132+
import matplotlib.pyplot as plt
133+
fig, ax = plt.subplots(2, 2)
134+
for axi, ii in zip(ax.ravel(),
135+
(i, f.model(f.guess()),
136+
f.model(p), (f.model(p) - i) + 1000)):
137+
axi.imshow(ii, cmap=plt.cm.Greys, vmin=0, vmax=5000)
138+
plt.show()

0 commit comments

Comments
 (0)
Please sign in to comment.