COMPASS  5.0.0
End-to-end AO simulation tool using GPU acceleration
correlation_bokeh.py
1 """
2 Created on Wed Oct 5 14:28:23 2016
3 
4 @author: fferreira
5 """
6 
7 import numpy as np
8 import h5py
9 import pandas
10 from bokeh.plotting import Figure, figure
11 from bokeh.models import Range1d, ColumnDataSource, HoverTool
12 from bokeh.models.widgets import Select, Slider, CheckboxButtonGroup, Panel, Tabs, Button, Dialog, Paragraph, RadioButtonGroup, TextInput
13 from bokeh.io import curdoc
14 from bokeh.models.layouts import HBox, VBox
15 from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
16 from bokeh.client import push_session
17 import glob
18 import matplotlib.pyplot as plt
19 from scipy.special import jv # Bessel function
20 plt.ion()
21 
22 
23 def dphi_highpass(r, x0, tabx, taby):
24  return (r**
25  (5. / 3.)) * (1.1183343328701949 - Ij0t83(r * (np.pi / x0), tabx, taby)) * (
26  2 * (2 * np.pi)**(8 / 3.) * 0.0228956)
27 
28 
29 def dphi_lowpass(r, x0, L0, tabx, taby):
30  return rodconan(r, L0) - dphi_highpass(r, x0, tabx, taby)
31  #return (r**(5./3.)) * Ij0t83(r*(np.pi/x0), tabx, taby) * (2*(2*np.pi)**(8/3.)*0.0228956)
32 
33 
34 def Ij0t83(x, tabx, taby):
35  if (x < np.exp(-3.0)):
36  return 0.75 * x**(1. / 3) * (1 - x**2 / 112.)
37  else:
38  return np.interp(x, tabx, taby)
39 
40 
41 def unMoinsJ0(x):
42  # if(x<0.1):
43  # x22 = (x/2.)**2
44  # return (1-x22/4.)*x22
45  # else:
46  return 1 - jv(0, x)
47 
48 
49 def tabulateIj0(L0):
50  n = 10000
51  t = np.linspace(-4, 10, n)
52  dt = (t[-1] - t[0]) / (n - 1)
53  smallx = np.exp(-4.0)
54  A = 0.75 * smallx**(1. / 3) * (1 - smallx**2 / 112.)
55  X = np.exp(t)
56  #Y = np.exp(-t*(5./3.))*unMoinsJ0(X)
57  Y = (np.exp(2 * t) + (1. / L0)**2)**(-8. / 6.) * unMoinsJ0(X) * np.exp(t)
58  Y[1:] = np.cumsum(Y[:-1] + np.diff(Y) / 2.)
59  Y[0] = 0.
60  Y = Y * dt + A
61 
62  return X, Y
63 
64 
65 def asymp_macdo(x):
66  k2 = 1.00563491799858928388289314170833
67  k3 = 1.25331413731550012081
68  a1 = 0.22222222222222222222
69  a2 = -0.08641975308641974829
70  a3 = 0.08001828989483310284
71 
72  x_1 = 1. / x
73  res = k2 - k3 * np.exp(-x) * x**(1. / 3.) * (1.0 + x_1 * (a1 + x_1 *
74  (a2 + x_1 * a3)))
75  return res
76 
77 
78 def macdo(x):
79  a = 5. / 6.
80  x2a = x**(2. * a)
81  x22 = x * x / 4.
82  s = 0.0
83 
84  Ga = [
85  0, 12.067619015983075, 5.17183672113560444, 0.795667187867016068,
86  0.0628158306210802181, 0.00301515986981185091, 9.72632216068338833e-05,
87  2.25320204494595251e-06, 3.93000356676612095e-08, 5.34694362825451923e-10,
88  5.83302941264329804e-12
89  ]
90 
91  Gma = [
92  -3.74878707653729304, -2.04479295083852408, -0.360845814853857083,
93  -0.0313778969438136685, -0.001622994669507603, -5.56455315259749673e-05,
94  -1.35720808599938951e-06, -2.47515152461894642e-08, -3.50257291219662472e-10,
95  -3.95770950530691961e-12, -3.65327031259100284e-14
96  ]
97 
98  x2n = 0.5
99 
100  s = Gma[0] * x2a
101  s *= x2n
102 
103  x2n *= x22
104 
105  for n in np.arange(10) + 1:
106 
107  s += (Gma[n] * x2a + Ga[n]) * x2n
108  x2n *= x22
109 
110  return s
111 
112 
113 def rodconan(r, L0):
114  res = 0
115  k1 = 0.1716613621245709486
116  dprf0 = (2 * np.pi / L0) * r
117  if (dprf0 > 4.71239):
118  res = asymp_macdo(dprf0)
119  else:
120  res = -macdo(dprf0)
121 
122  res *= k1 * L0**(5. / 3.)
123 
124  return res
125 
126 
127 def variance(f, contributors, method="Default"):
128  """ Return the error variance of specified contributors
129  params:
130  f : (h5py.File) : roket hdf5 file opened with h5py
131  contributors : (list of string) : list of the contributors
132  method : (optional, default="Default") : if "Independence", the
133  function returns ths sum of the contributors variances.
134  If "Default", it returns the variance of the contributors sum
135  """
136  P = f["P"][:]
137  nmodes = P.shape[0]
138  swap = np.arange(nmodes) - 2
139  swap[0:2] = [nmodes - 2, nmodes - 1]
140  if (method == b"Default"):
141  err = f[contributors[0]][:] * 0.
142  for c in contributors:
143  err += f[c][:]
144  return np.var(P.dot(err), axis=1)[swap], np.var(
145  P.dot(f["tomography"][:]),
146  axis=1)[swap], np.var(P.dot(f["bandwidth"][:]), axis=1)[swap]
147 
148  elif (method == b"Independence"):
149  nmodes = P.shape[0]
150  v = np.zeros(nmodes)
151  for c in contributors:
152  v += np.var(P.dot(f[c][:]), axis=1)
153  return v[swap]
154 
155  else:
156  raise TypeError("Wrong method input")
157 
158 
159 def varianceMultiFiles(fs, frac_per_layer, contributors):
160  """ Return the variance computed from the sum of contributors of roket
161  files fs, ponderated by frac
162  params:
163  fs : (list) : list of hdf5 files opened with h5py
164  frac_per_layer : (dict) : frac for each layer
165  contributors : (list of string) : list of the contributors
166  return:
167  v : (np.array(dim=1)) : variance vector
168  """
169  f = fs[0]
170  P = f["P"][:]
171  nmodes = P.shape[0]
172  swap = np.arange(nmodes) - 2
173  swap[0:2] = [nmodes - 2, nmodes - 1]
174  err = f[contributors[0]][:] * 0.
175  for f in fs:
176  frac = frac_per_layer[f.attrs["atm.alt"][0]]
177  for c in contributors:
178  err += np.sqrt(frac) * f[c][:]
179 
180  return np.var(P.dot(err), axis=1)[swap]
181 
182 
183 def cumulativeSR(v, Lambda_tar):
184  """ Returns the cumulative Strehl ratio over the modes from the variance
185  on each mode
186  params:
187  v : (np.array(dim=1)) : variance vector
188  return:
189  s : (np.array(dim=1)) : cumulative SR
190  """
191  s = np.cumsum(v)
192  s = np.exp(-s * (2 * np.pi / Lambda_tar)**2)
193 
194  return s
195 
196 
197 def update(attrs, old, new):
198  speed = speed_select.value
199  direction = dir_select.value
200  g = gain_select.value
201  xname = xaxis_select.value
202  yname = yaxis_select.value
203 
204  ydata = ymap[yname]
205  x = xmap[xname]
206 
207  ind = np.ones(ydata.shape[0])
208  if (direction != "All"):
209  ind *= (xmap["Winddir"] == float(direction))
210  if (speed != "All"):
211  ind *= (xmap["Windspeed"] == float(speed))
212  if (g != "All"):
213  ind *= (xmap["Gain"] == float(g))
214 
215  ind = np.where(ind)
216  if (yname == b"Var(t)"):
217  Hthetak = Htheta / xmap["Gain"]
218  y_model = np.ones(ind[0].shape[0])
219  #y_model = y_model * 6.88 * (Htheta/r0)**(5./3.) * 0.5
220  for k in range(ind[0].shape[0]):
221  y_model[k] = dphi_lowpass(Htheta, 0.2, L0, tabx, taby) * (1 / r0)**(
222  5. / 3.) * 0.5 #* xmap["Gain"][ind][k]**2
223  if (yname == b"Var(bp)"):
224  vdt = xmap["Windspeed"] * dt / xmap["Gain"]
225  y_model = np.zeros(vdt[ind].shape[0])
226  for k in range(vdt[ind].shape[0]):
227  y_model[k] = dphi_lowpass(vdt[ind][k], 0.2, L0, tabx,
228  taby) * (1. / r0)**(5. / 3.) * 0.5
229  if (yname == b"Covar"):
230  vdt = xmap["Windspeed"] * dt / xmap["Gain"]
231  Hthetak = Htheta / xmap["Gain"]
232  gamma = np.arctan2(ypos, xpos) - xmap["Winddir"] * np.pi / 180.
233  rho = np.sqrt(Htheta**2 + (vdt)**2 - 2 * Htheta * vdt * np.cos(gamma))
234  Drho = np.zeros(rho[ind].shape[0])
235  Dt = Drho.copy()
236  for k in range(rho[ind].shape[0]):
237  Drho[k] = dphi_lowpass(rho[ind][k], 0.2, L0, tabx,
238  taby) * (1 / r0)**(5. / 3.)
239  #Drho = 6.88 * (rho[ind]/r0)**(5./3.)
240  for k in range(Dt.shape[0]):
241  Dt[k] = dphi_lowpass(Htheta, 0.2, L0, tabx, taby) * (1 / r0)**(
242  5. / 3.) # * xmap["Gain"][ind][k]**2
243  #Dt = 6.88 * (Htheta/r0)**(5./3.)
244  Dbp = np.zeros(vdt[ind].shape[0])
245  for k in range(vdt[ind].shape[0]):
246  Dbp[k] = dphi_lowpass(vdt[ind][k], 0.2, L0, tabx, taby) * (1 / r0)**(5. / 3.)
247  #Dbp = 6.88 * (vdt[ind]/r0) ** (5./3.)
248  y_model = 0.5 * (Dt + Dbp - Drho)
249 
250  source.data = dict(x=x[ind], y=ydata[ind], speed=xmap["Windspeed"][ind],
251  theta=xmap["Winddir"][ind], gain=xmap["Gain"][ind])
252  source_model.data = dict(x=x[ind], y=y_model, speed=xmap["Windspeed"][ind],
253  theta=xmap["Winddir"][ind], gain=xmap["Gain"][ind])
254 
255 
256 datapath = "/home/fferreira/Data/correlation/"
257 filenames = glob.glob(datapath + "roket_8m_1layer_dir*_cpu.h5")
258 
259 files = []
260 for f in filenames:
261  ff = h5py.File(f, mode='r')
262  #if(ff.attrs["validity"]):
263  files.append(ff)
264 
265 nmodes = (files[0])["P"][:].shape[0]
266 xpos = files[0].attrs["wfs.xpos"][0]
267 ypos = files[0].attrs["wfs.ypos"][0]
268 contributors = ["tomography", "bandwidth"]
269 Lambda_tar = files[0].attrs["target.Lambda"][0]
270 Lambda_wfs = files[0].attrs["wfs.Lambda"][0]
271 L0 = files[0].attrs["L0"][0]
272 dt = files[0].attrs["ittime"]
273 H = files[0].attrs["atm.alt"][0]
274 RASC = 180 / np.pi * 3600.
275 Htheta = np.linalg.norm(
276  [xpos, ypos]
277 ) / RASC * H # np.sqrt(2)*4/RASC*H # Hardcoded for angular separation of sqrt(2)*4 arcsec
278 r0 = files[0].attrs["r0"] * (Lambda_tar / Lambda_wfs)**(6. / 5.)
279 nfiles = len(files)
280 data = np.zeros((nmodes, 4, nfiles))
281 theta = np.zeros(nfiles)
282 speeds = np.zeros(nfiles)
283 gain = np.zeros(nfiles)
284 
285 tabx, taby = tabulateIj0(L0)
286 
287 # data[:,0,i] = var(tomo+bp) for file #i
288 # data[:,1,i] = var(tomo) for file #i
289 # data[:,2,i] = var(bp) for file #i
290 # data[:,3,i] = var(tomo)+var(bp) for file #i
291 ind = 0
292 for f in files:
293  data[:, 0, ind], data[:, 1, ind], data[:, 2, ind] = variance(f, contributors)
294  data[:, 3, ind] = variance(f, contributors, method="Independence")
295  theta[ind] = f.attrs["winddir"][0]
296  speeds[ind] = f.attrs["windspeed"][0]
297  gain[ind] = float('%.1f' % f.attrs["gain"][0])
298  ind += 1
299 data = data * ((2 * np.pi / Lambda_tar)**2)
300 covar = (data[:, 0, :] - data[:, 3, :]) / 2.
301 
302 xaxis_select = Select(title="X-axis", value="Windspeed",
303  options=["Windspeed", "Winddir", "Gain"])
304 yaxis_select = Select(
305  title="Y-axis", value="Covar",
306  options=["Covar", "Var(t+bp)", "Var(t)", "Var(bp)", "Var(t)+Var(bp)"])
307 
308 speed_select = Select(title="Windspeeds", value="All",
309  options=["All"] + [str(s) for s in np.unique(speeds)])
310 dir_select = Select(title="Winddirs", value="All",
311  options=["All"] + [str(s) for s in np.unique(theta)])
312 gain_select = Select(title="Gain", value="All",
313  options=["All"] + [str(s)[:3] for s in np.unique(gain)])
314 source = ColumnDataSource(data=dict(x=[], y=[], speed=[], theta=[], gain=[]))
315 source_model = ColumnDataSource(data=dict(x=[], y=[], speed=[], theta=[], gain=[]))
316 hover = HoverTool(tooltips=[("Speed", "@speed"), ("Winddir", "@theta"), ("Gain",
317  "@gain")])
318 TOOLS = "resize,save,pan,box_zoom,tap, box_select, wheel_zoom, lasso_select,reset"
319 
320 p = figure(plot_height=600, plot_width=700, title="", tools=[hover, TOOLS])
321 p.circle(x="x", y="y", source=source, size=7, color="blue")
322 p.circle(x="x", y="y", source=source_model, size=7, color="red")
323 
324 xmap = {"Windspeed": speeds, "Winddir": theta, "Gain": gain}
325 ymap = {
326  "Covar": np.sum(covar, axis=0),
327  "Var(t+bp)": np.sum(data[:, 0, :], axis=0),
328  "Var(t)": np.sum(data[:, 1, :], axis=0),
329  "Var(bp)": np.sum(data[:, 2, :], axis=0),
330  "Var(t)+Var(bp)": np.sum(data[:, 3, :], axis=0)
331 }
332 
333 buttons = [xaxis_select, speed_select, dir_select, yaxis_select, gain_select]
334 for b in buttons:
335  b.on_change('value', update)
336 
337 curdoc().clear()
338 update(None, None, None)
339 curdoc().add_root(
340  HBox(VBox(xaxis_select, yaxis_select, speed_select, dir_select, gain_select), p))
correlation_bokeh.rodconan
def rodconan(r, L0)
Definition: correlation_bokeh.py:113
correlation_bokeh.cumulativeSR
def cumulativeSR(v, Lambda_tar)
Returns the cumulative Strehl ratio over the modes from the variance on each mode params: v (np....
Definition: correlation_bokeh.py:190
correlation_bokeh.update
def update(attrs, old, new)
Definition: correlation_bokeh.py:197
correlation_bokeh.unMoinsJ0
def unMoinsJ0(x)
Definition: correlation_bokeh.py:41
correlation_bokeh.macdo
def macdo(x)
Definition: correlation_bokeh.py:78
correlation_bokeh.Ij0t83
def Ij0t83(x, tabx, taby)
Definition: correlation_bokeh.py:34
correlation_bokeh.asymp_macdo
def asymp_macdo(x)
Definition: correlation_bokeh.py:65
correlation_bokeh.variance
def variance(f, contributors, method="Default")
Return the error variance of specified contributors params: f (h5py.File) : roket hdf5 file opened wi...
Definition: correlation_bokeh.py:135
correlation_bokeh.varianceMultiFiles
def varianceMultiFiles(fs, frac_per_layer, contributors)
Return the variance computed from the sum of contributors of roket files fs, ponderated by frac param...
Definition: correlation_bokeh.py:168
correlation_bokeh.tabulateIj0
def tabulateIj0(L0)
Definition: correlation_bokeh.py:49
correlation_bokeh.dphi_highpass
def dphi_highpass(r, x0, tabx, taby)
Definition: correlation_bokeh.py:23
correlation_bokeh.dphi_lowpass
def dphi_lowpass(r, x0, L0, tabx, taby)
Definition: correlation_bokeh.py:29