COMPASS  5.0.0
End-to-end AO simulation tool using GPU acceleration
correlation_study.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 glob
10 import sys
11 sys.path.append('/home/fferreira/compass/shesha/test/roket/tools/')
12 sys.path.append('/home/fferreira/compass/shesha/test/gamora/')
13 import Dphi
14 import roket_exploitation as rexp
15 import gamora
16 import shesha as ao
17 import matplotlib.pyplot as plt
18 plt.ion()
19 import matplotlib
20 import time
21 font = {'family': 'normal', 'weight': 'bold', 'size': 22}
22 
23 matplotlib.rc('font', **font)
24 
25 
26 def compute_psf(filename):
27  otftel, otf, psf, gpu = gamora.psf_rec_Vii(filename)
28  return psf
29 
30 
32  cov_err = rexp.get_coverr_independence(filename)
33  otfteli, otf2i, psfi, gpu = gamora.psf_rec_Vii(filenames[11], covmodes=cov_err)
34  return psfi
35 
36 
37 def compute_and_compare_PSFs(filename, plot=False):
38  f = h5py.File(filename, 'r')
39  psf_compass = np.fft.fftshift(f["psf"][:])
40  #psf = compute_psf(filename)
41  #psfi = compute_psf_independence(filename)
42  psfc = 0
43  psfs = 0
44  tic = time.time()
45  Caniso, Cbp, Ccov = compute_covariance_model(filename)
46 
47  Nact = f["Nact"][:]
48  N1 = np.linalg.inv(Nact)
49  Caniso = N1.dot(Caniso).dot(N1)
50  Cbp = N1.dot(Cbp).dot(N1)
51  Ccov = N1.dot(Ccov).dot(N1)
52 
53  Ccov_filtered = filter_piston_TT(filename, Ccov)
54  Ctt = add_TT_model(filename, Ccov)
55  Ctt[:-2, :-2] = Ccov_filtered
56  Ctt = Ctt + Ctt.T
57  Caniso_filtered = filter_piston_TT(filename, Caniso)
58  tmp = add_TT_model(filename, Caniso)
59  tmp[:-2, :-2] = Caniso_filtered
60  Ctt += tmp
61  Cbp_filtered = filter_piston_TT(filename, Cbp)
62  tmp = add_TT_model(filename, Cbp)
63  tmp[:-2, :-2] = Cbp_filtered
64  Ctt += tmp
65  #contributors = ["noise","aliasing","non linearity","filtered modes"]
66  #cov_err = rexp.get_coverr_independence_contributors(filename,contributors)
67  P = f["P"][:]
68  cov_err = P.dot(Ctt).dot(P.T)
69  otftels, otf2s, psfs, gpu = gamora.psf_rec_Vii(filename, fitting=False,
70  cov=cov_err.astype(np.float32))
71  tac = time.time()
72  print("PSF estimated in ", tac - tic, " seconds")
73  t = f["tomography"][:]
74  b = f["bandwidth"][:]
75  tb = t + b
76  tb = tb.dot(tb.T) / float(tb.shape[1])
77  cov_err = P.dot(tb).dot(P.T)
78  otftel, otf2, psf, gpu = gamora.psf_rec_Vii(filename, fitting=False,
79  cov=cov_err.astype(np.float32))
80  if (plot):
81  Lambda_tar = f.attrs["target.Lambda"][0]
82  RASC = 180 / np.pi * 3600.
83  pixsize = Lambda_tar * 1e-6 / (
84  psf.shape[0] * f.attrs["tel_diam"] / f.attrs["pupdiam"]) * RASC
85  x = (np.arange(psf.shape[0]) - psf.shape[0] / 2) * pixsize / (
86  Lambda_tar * 1e-6 / f.attrs["tel_diam"] * RASC)
87  plt.figure()
88  plt.subplot(2, 1, 1)
89  plt.semilogy(x, psf[psf.shape[0] / 2, :], color="blue")
90  plt.semilogy(x, psfs[psf.shape[0] / 2, :], color="red")
91  plt.xlabel("X-axis angular distance [units of lambda/D]")
92  plt.ylabel("Normalized intensity")
93  plt.legend(["PSF exp", "PSF model"])
94 
95  #plt.semilogy(x,psf_compass[psf.shape[0]/2,:],color="red")
96  plt.legend(["PSF exp", "PSF model"])
97  plt.subplot(2, 1, 2)
98  plt.semilogy(x, psf[:, psf.shape[0] / 2], color="blue")
99  plt.semilogy(x, psfs[:, psf.shape[0] / 2], color="red")
100  plt.xlabel("Y-axis angular distance [units of lambda/D]")
101  plt.ylabel("Normalized intensity")
102 
103  #plt.semilogy(x,psf_compass[psf.shape[0]/2,:],color="red")
104  plt.legend(["PSF exp", "PSF model"])
105  '''
106  if(correction):
107  #plt.semilogy(x,psfc[psf.shape[0]/2,:],color="purple")
108  if(synth):
109  plt.semilogy(x,psfs[psf.shape[0]/2,:],color="black")
110  #plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS", "PSF corrected", "PSF synth"])
111  plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS", "PSF synth"])
112  else:
113  plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS", "PSF corrected"])
114  elif(synth):
115  plt.semilogy(x,psfs[psf.shape[0]/2,:],color="purple")
116  plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS", "PSF synth"])
117 
118  else:
119  plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS"])
120  '''
121 
122  f.close()
123  return psf_compass, psf, psfs
124 
125 
126 def filter_piston_TT(filename, C):
127  IF, T = rexp.get_IF(filename)
128  IF = IF.T
129  T = T.T
130  N = IF.shape[0]
131  n = IF.shape[1]
132 
133  delta = IF.T.dot(IF).toarray() / N
134 
135  # Tip-tilt + piston
136  Tp = np.ones((T.shape[0], T.shape[1] + 1))
137  Tp[:, :2] = T.copy() #.toarray()
138  deltaT = IF.T.dot(Tp) / N
139  # Tip tilt projection on the pzt dm
140  tau = np.linalg.inv(delta).dot(deltaT)
141 
142  # Famille generatrice sans tip tilt
143  G = np.identity(n)
144  tdt = tau.T.dot(delta).dot(tau)
145  subTT = tau.dot(np.linalg.inv(tdt)).dot(tau.T).dot(delta)
146  G -= subTT
147 
148  return G.T.dot(C).dot(G)
149 
150 
151 def filter_TT(filename, C):
152  IF, T = rexp.get_IF(filename)
153  IF = IF.T
154  T = T.T
155  N = IF.shape[0]
156  n = IF.shape[1]
157 
158  delta = IF.T.dot(IF).toarray() / N
159 
160  deltaT = IF.T.dot(T) / N
161  # Tip tilt projection on the pzt dm
162  tau = np.linalg.inv(delta).dot(deltaT)
163 
164  # Famille generatrice sans tip tilt
165  G = np.identity(n)
166  tdt = tau.T.dot(delta).dot(tau)
167  subTT = tau.dot(np.linalg.inv(tdt)).dot(tau.T).dot(delta)
168  G -= subTT
169 
170  return G.T.dot(C).dot(G)
171 
172 
174  f = h5py.File(filename, 'r')
175  Lambda_tar = f.attrs["target.Lambda"][0]
176  Lambda_wfs = f.attrs["wfs.Lambda"]
177  dt = f.attrs["ittime"]
178  gain = f.attrs["gain"]
179  wxpos = f.attrs["wfs.xpos"][0]
180  wypos = f.attrs["wfs.ypos"][0]
181  r0 = f.attrs["r0"] * (Lambda_tar / Lambda_wfs)**(6. / 5.)
182  RASC = 180. / np.pi * 3600.
183  xpos = f["dm.xpos"][:]
184  ypos = f["dm.ypos"][:]
185  p2m = f.attrs["tel_diam"] / f.attrs["pupdiam"]
186  pupshape = int(2**np.ceil(np.log2(f.attrs["pupdiam"]) + 1))
187  xactu = (xpos - pupshape / 2) * p2m
188  yactu = (ypos - pupshape / 2) * p2m
189  Ccov = np.zeros((xpos.size, xpos.size))
190  Caniso = np.zeros((xpos.size, xpos.size))
191  Cbp = np.zeros((xpos.size, xpos.size))
192  xx = np.tile(xactu, (xactu.shape[0], 1))
193  yy = np.tile(yactu, (yactu.shape[0], 1))
194  xij = xx - xx.T
195  yij = yy - yy.T
196 
197  for l in range(f.attrs["nscreens"]):
198  H = f.attrs["atm.alt"][l]
199  L0 = f.attrs["L0"][l]
200  speed = f.attrs["windspeed"][l]
201  theta = f.attrs["winddir"][l] * np.pi / 180.
202  frac = f.attrs["frac"][l]
203 
204  Htheta = np.linalg.norm([wxpos, wypos]) / RASC * H
205  vdt = speed * dt / gain
206  # Covariance matrices models on actuators space
207  M = np.zeros((xpos.size, xpos.size))
208  Mvdt = M.copy()
209  Mht = M.copy()
210  Mhvdt = M.copy()
211  angleht = np.arctan2(wypos, wxpos)
212  fc = xactu[1] - xactu[0]
213  #fc = 0.05
214 
215  M = np.linalg.norm([xij, yij], axis=0)
216  Mvdt = np.linalg.norm([xij - vdt * np.cos(theta), yij - vdt * np.sin(theta)],
217  axis=0)
218  Mht = np.linalg.norm(
219  [xij - Htheta * np.cos(angleht), yij - Htheta * np.sin(angleht)], axis=0)
220  Mhvdt = np.linalg.norm([
221  xij - vdt * np.cos(theta) - Htheta * np.cos(angleht),
222  yij - vdt * np.sin(theta) - Htheta * np.sin(angleht)
223  ], axis=0)
224  # for i in range(xpos.size):
225  # for j in range(xpos.size):
226  # Mvdt[i,j] = (np.sqrt((xactu[i]-(xactu[j]-vdt*np.cos(theta)))**2 + (yactu[i]-(yactu[j]-vdt*np.sin(theta)))**2))
227  # M[i,j] = (np.sqrt((xactu[i]-xactu[j])**2 + (yactu[i]-yactu[j])**2))
228  # Mht[i,j] = (np.sqrt((xactu[i]-(xactu[j]-Htheta*np.cos(angleht)))**2 + (yactu[i]-(yactu[j]-Htheta*np.sin(angleht)))**2))
229  # #Mhvdt[i,j] = (np.sqrt((xactu[i]-(xactu[j]+rho*np.cos(anglehvdt)))**2 + (yactu[i]-(yactu[j]+rho*np.sin(anglehvdt)))**2))
230  # Mhvdt[i,j] = (np.sqrt(((xactu[i]+vdt*np.cos(theta))-(xactu[j]-Htheta*np.cos(angleht)))**2 + ((yactu[i]+vdt*np.sin(theta))-(yactu[j]-Htheta*np.sin(angleht)))**2))
231 
232  Ccov += 0.5 * (Dphi.dphi_lowpass(Mhvdt,fc,L0,tabx,taby) - Dphi.dphi_lowpass(Mht,fc,L0,tabx,taby) \
233  - Dphi.dphi_lowpass(Mvdt,fc,L0,tabx,taby) + Dphi.dphi_lowpass(M,fc,L0,tabx,taby)) * (1./r0)**(5./3.) * frac
234 
235  Caniso += 0.5 * (Dphi.dphi_lowpass(Mht, fc, L0, tabx, taby) - Dphi.dphi_lowpass(
236  M, fc, L0, tabx, taby)) * (1. / r0)**(5. / 3.) * frac
237  Cbp += 0.5 * (Dphi.dphi_lowpass(Mvdt, fc, L0, tabx, taby) - Dphi.dphi_lowpass(
238  M, fc, L0, tabx, taby)) * (1. / r0)**(5. / 3.) * frac
239 
240  #Sp = (f.attrs["tel_diam"]/f.attrs["nxsub"])**2/2.
241  Sp = (Lambda_tar / (2 * np.pi))**2 #/3.45
242  f.close()
243  return (Caniso + Caniso.T) * Sp, (Cbp + Cbp.T) * Sp, Ccov * Sp
244 
245 
246 def add_TT_model(filename, Ccov):
247  C = np.zeros((Ccov.shape[0] + 2, Ccov.shape[0] + 2))
248  IF, T = rexp.get_IF(filename)
249  IF = IF.T
250  T = T.T
251  N = IF.shape[0]
252  deltaTT = T.T.dot(T) / N
253  deltaF = IF.T.dot(T) / N
254  pzt2tt = np.linalg.inv(deltaTT).dot(deltaF.T)
255 
256  CTT = Ccov - filter_TT(filename, Ccov)
257  C[-2:, -2:] = pzt2tt.dot(CTT).dot(pzt2tt.T)
258  C[:-2, :-2] = Ccov
259 
260  return C
261 
262 
263 def load_datas(files):
264  nmodes = (files[0])["P"][:].shape[0]
265  P = (files[0])["P"][:]
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  vartomo = np.zeros((nfiles, nmodes))
281  varbp = np.zeros((nfiles, nmodes))
282  vartot = np.zeros((nfiles, nmodes))
283  theta = np.zeros(nfiles)
284  speeds = np.zeros(nfiles)
285  gain = np.zeros(nfiles)
286  # data[:,0,i] = var(tomo+bp) for file #i
287  # data[:,1,i] = var(tomo) for file #i
288  # data[:,2,i] = var(bp) for file #i
289  # data[:,3,i] = var(tomo)+var(bp) for file #i
290  ind = 0
291  print("Loading data...")
292  for f in files:
293  vartot[ind, :] = rexp.variance(f, contributors) * ((2 * np.pi / Lambda_tar)**2)
294  vartomo[ind, :] = rexp.variance(f, ["tomography"]) * (
295  (2 * np.pi / Lambda_tar)**2)
296  varbp[ind, :] = rexp.variance(f, ["bandwidth"]) * ((2 * np.pi / Lambda_tar)**2)
297  theta[ind] = f.attrs["winddir"][0]
298  speeds[ind] = f.attrs["windspeed"][0]
299  gain[ind] = float('%.1f' % f.attrs["gain"][0])
300  ind += 1
301  print(ind, "/", len(files))
302 
303  covar = (vartot - (vartomo + varbp)) / 2.
304 
305  stot = np.sum(vartot, axis=1)
306  sbp = np.sum(varbp, axis=1)
307  stomo = np.sum(vartomo, axis=1)
308  scov = np.sum(covar, axis=1)
309 
310  return stot, sbp, stomo, scov, covar
311 
312 
313 def ensquare_PSF(filename, psf, N, display=False):
314  f = h5py.File(filename, 'r')
315  Lambda_tar = f.attrs["target.Lambda"][0]
316  RASC = 180 / np.pi * 3600.
317  pixsize = Lambda_tar * 1e-6 / (
318  psf.shape[0] * f.attrs["tel_diam"] / f.attrs["pupdiam"]) * RASC
319  x = (np.arange(psf.shape[0]) - psf.shape[0] / 2) * pixsize / (
320  Lambda_tar * 1e-6 / f.attrs["tel_diam"] * RASC)
321  w = int(N * (Lambda_tar * 1e-6 / f.attrs["tel_diam"] * RASC) / pixsize)
322  mid = psf.shape[0] / 2
323  psfe = psf[mid - w:mid + w, mid - w:mid + w]
324  if (display):
325  plt.matshow(np.log10(psfe))
326  xt = np.linspace(0, psfe.shape[0] - 1, 6).astype(np.int32)
327  yt = np.linspace(-N, N, 6).astype(np.int32)
328  plt.xticks(xt, yt)
329  plt.yticks(xt, yt)
330 
331  f.close()
332  return psf[mid - w:mid + w, mid - w:mid + w]
333 
334 
335 def cutsPSF(filename, psf, psfs):
336  f = h5py.File(filename, 'r')
337  Lambda_tar = f.attrs["target.Lambda"][0]
338  RASC = 180 / np.pi * 3600.
339  pixsize = Lambda_tar * 1e-6 / (
340  psf.shape[0] * f.attrs["tel_diam"] / f.attrs["pupdiam"]) * RASC
341  x = (np.arange(psf.shape[0]) - psf.shape[0] / 2) * pixsize / (
342  Lambda_tar * 1e-6 / f.attrs["tel_diam"] * RASC)
343  plt.figure()
344  plt.subplot(2, 1, 1)
345  plt.semilogy(x, psf[psf.shape[0] / 2, :], color="blue")
346  plt.semilogy(x, psfs[psf.shape[0] / 2, :], color="red")
347  plt.xlabel("X-axis angular distance [units of lambda/D]")
348  plt.ylabel("Normalized intensity")
349  plt.legend(["PSF exp", "PSF model"])
350  plt.xlim(-20, 20)
351  plt.ylim(1e-5, 1)
352  plt.subplot(2, 1, 2)
353  plt.semilogy(x, psf[:, psf.shape[0] / 2], color="blue")
354  plt.semilogy(x, psfs[:, psf.shape[0] / 2], color="red")
355  plt.xlabel("Y-axis angular distance [units of lambda/D]")
356  plt.ylabel("Normalized intensity")
357  plt.legend(["PSF exp", "PSF model"])
358  plt.xlim(-20, 20)
359  plt.ylim(1e-5, 1)
360  f.close()
361 
362 
363 def Hcor(f, Fe, g, dt):
364  p = 1j * 2 * np.pi * f
365  return np.abs(1 / (1 + g * Fe / p * np.exp(-dt * p)))**2
366 
367 
368 def Hretard(f, Fe, g, dt):
369  p = 1j * 2 * np.pi * f
370  return np.abs(1 - np.exp(-p * dt / g))**2
371 
372 
374  rfile = h5py.File(filename, 'r')
375  v = rfile.attrs["windspeed"][0]
376  dt = rfile.attrs["ittime"]
377  Fe = 1 / dt
378  g = rfile.attrs["gain"]
379  Lambda_tar = rfile.attrs["target.Lambda"][0]
380  Lambda_wfs = rfile.attrs["wfs.Lambda"][0]
381  r0 = rfile.attrs["r0"] * (Lambda_tar / Lambda_wfs)**(6. / 5.)
382  d = rfile.attrs["tel_diam"] / rfile.attrs["nxsub"]
383  fc = 0.314 * v / d
384  f = np.linspace(0.1, fc * 1.5, 1000)
385  H = Hcor(f, Fe, g, dt)
386  Hr = Hretard(f, Fe, g, dt)
387  plt.figure()
388  plt.plot(f, H)
389  plt.plot(f, Hr, color="red")
390  plt.plot([fc, fc], [H.min(), Hr.max()])
391  rfile.close()
392 
393 
394 datapath = '/home/fferreira/Data/correlation/'
395 filenames = glob.glob(datapath + 'roket_8m_1layer_dir*_cpu.h5')
396 files = []
397 for f in filenames:
398  files.append(h5py.File(f, 'r'))
399 
400 tabx, taby = Dphi.tabulateIj0()
401 
402 nfiles = len(filenames)
403 theta = np.zeros(nfiles)
404 speeds = np.zeros(nfiles)
405 gain = np.zeros(nfiles)
406 SRcompass = np.zeros(nfiles)
407 SRroket = np.zeros(nfiles)
408 SRi = np.zeros(nfiles)
409 fROKET = h5py.File('ROKETStudy.h5', 'r')
410 psfr = fROKET["psf"][:]
411 psfi = fROKET["psfi"][:]
412 nrjcompass = np.zeros(nfiles)
413 nrjroket = np.zeros(nfiles)
414 nrji = np.zeros(nfiles)
415 
416 ind = 0
417 for f in files:
418  theta[ind] = f.attrs["winddir"][0]
419  speeds[ind] = f.attrs["windspeed"][0]
420  gain[ind] = float('%.1f' % f.attrs["gain"][0])
421  SRcompass[ind] = f["psf"][:].max()
422  SRroket[ind] = psfr[:, :, ind].max()
423  SRi[ind] = psfi[:, :, ind].max()
424  nrjcompass[ind] = np.sum(
425  ensquare_PSF(filenames[ind], np.fft.fftshift(f["psf"][:]),
426  5)) / f["psf"][:].sum()
427  nrjroket[ind] = np.sum(ensquare_PSF(filenames[ind], psfr[:, :, ind],
428  5)) / psfr[:, :, ind].sum()
429  nrji[ind] = np.sum(ensquare_PSF(filenames[ind], psfi[:, :, ind],
430  5)) / psfi[:, :, ind].sum()
431  ind += 1
432 """
433 eSR = np.abs(SRroket-SRcompass) / SRcompass
434 eSRi = np.abs(SRi - SRcompass) / SRcompass
435 enrj = np.abs(nrjroket-nrjcompass) / nrjcompass
436 enrji = np.abs(nrji-nrjcompass) / nrjcompass
437 
438 plt.figure()
439 plt.scatter(SRcompass,SRroket,s=200)
440 plt.plot([SRcompass.min(),SRcompass.max()],[SRcompass.min(),SRcompass.max()],color="red")
441 plt.xlabel("COMPASS Strehl ratio")
442 plt.ylabel("ROKET Strehl ratio")
443 plt.figure()
444 plt.scatter(nrjcompass,nrjroket,s=200)
445 plt.plot([nrjcompass.min(),nrjcompass.max()],[nrjcompass.min(),nrjcompass.max()],color="red")
446 plt.xlabel("COMPASS PSF ensquared energy")
447 plt.ylabel("ROKET PSF ensquared energy")
448 
449 colors = ["blue","red","green","black","yellow"]
450 plt.figure()
451 indc = 0
452 for t in np.unique(theta):
453  ind = np.where(theta == t)
454  plt.scatter(SRcompass[ind],SRi[ind],s=200,color=colors[indc])
455  indc += 1
456 plt.legend(["0 deg","45 deg","90 deg","135 deg","180 deg"])
457 plt.plot([SRcompass.min(),SRcompass.max()],[SRcompass.min(),SRcompass.max()],color="red")
458 plt.xlabel("COMPASS Strehl ratio")
459 plt.ylabel("ROKET Strehl ratio")
460 
461 plt.figure()
462 indc = 0
463 for t in np.unique(theta):
464  ind = np.where(theta == t)
465  plt.scatter(nrjcompass[ind],nrji[ind],s=200,color=colors[indc])
466  indc += 1
467 plt.legend(["0 deg","45 deg","90 deg","135 deg","180 deg"])
468 plt.plot([nrjcompass.min(),nrjcompass.max()],[nrjcompass.min(),nrjcompass.max()],color="red")
469 plt.xlabel("COMPASS PSF ensquared energy")
470 plt.ylabel("ROKET PSF ensquared energy")
471 """
472 f = h5py.File('corStudy_Nact.h5', 'r')
473 psf = f["psf"][:]
474 psfs = f["psfs"][:]
475 nrj = f["nrj5"][:]
476 nrjs = f["nrj5s"][:]
477 SR = np.max(psf, axis=(0, 1))
478 SRs = np.max(psfs, axis=(0, 1))
479 
480 colors = ["blue", "red", "green"]
481 plt.figure()
482 k = 0
483 for g in np.unique(gain):
484  plt.subplot(2, 2, k + 1)
485  plt.title("g = %.1f" % (g))
486  for i in range(len(colors)):
487  c = colors[i]
488  v = np.unique(speeds)[i]
489  ind = np.where((gain == g) * (speeds == v))
490  plt.scatter(SR[ind], SRs[ind], color=c, s=200)
491  plt.legend(["10 m/s", "15 m/s", "20 m/s"], loc=2)
492  plt.xlabel("SR ROKET")
493  plt.ylabel("SR model")
494  plt.plot([SR.min(), SR.max()], [SR.min(), SR.max()], color="red")
495  k += 1
496 """
497 # Illustration du probleme
498 #psf_compass, psf, psfs = compute_and_compare_PSFs(filenames[13],plot=True)
499 # psf_compass = np.zeros((2048,2048,len(filenames)))
500 # psf = np.zeros((2048,2048,len(filenames)))
501 # psfi = np.zeros((2048,2048,len(filenames)))
502 # SR = np.zeros(len(filenames))
503 # SRi = np.zeros(len(filenames))
504 # SRcompass = np.zeros(len(filenames))
505 # nrj20 = np.zeros(len(filenames))
506 # nrj20s = np.zeros(len(filenames))
507 # nrj5 = np.zeros(len(filenames))
508 # nrj5i = np.zeros(len(filenames))
509 # nrj5compass = np.zeros(len(filenames))
510 #
511 # cc = 0
512 # for f in filenames:
513 # ff = h5py.File(f,'r')
514 # psf_compass[:,:,cc] = np.fft.fftshift(ff["psf"][:])
515 # psf[:,:,cc] = compute_psf(f)
516 # psfi[:,:,cc] = compute_psf_independence(f)
517 # #psf_compass, psf[:,:,cc], psfs[:,:,cc] = compute_and_compare_PSFs(f)
518 # SR[cc] = psf[:,:,cc].max()
519 # SRi[cc] = psfi[:,:,cc].max()
520 # SRcompass[cc] = psf_compass[:,:,cc].max()
521 # # nrj20[cc] = ensquare_PSF(f,psf[:,:,cc],20).sum()/psf[:,:,cc].sum()
522 # # nrj20s[cc] = ensquare_PSF(f,psfs[:,:,cc],20).sum()/psfs[:,:,cc].sum()
523 # nrj5[cc] = ensquare_PSF(f,psf[:,:,cc],5).sum()/psf[:,:,cc].sum()
524 # nrj5i[cc] = ensquare_PSF(f,psfi[:,:,cc],5).sum()/psfi[:,:,cc].sum()
525 # nrj5compass[cc] = ensquare_PSF(f,psf_compass[:,:,cc],5).sum()/psf_compass[:,:,cc].sum()
526 #
527 # cc +=1
528 # ff.close()
529 # print(cc)
530 #
531 # f = h5py.File("ROKETStudy.h5")
532 # f["psf"] = psf
533 # f["filenames"] = filenames
534 # f["psfi"] = psfi
535 # f["psf_compass"] = psf_compass
536 # f["SR"] = SR
537 # f["SRi"] = SRi
538 # f["SRcompass"] = SRcompass
539 # #f["nrj20"] = nrj20
540 # #f["nrj20s"] = nrj20s
541 # f["nrj5"] = nrj5
542 # f["nrj5i"] = nrj5i
543 # f["nrj5compass"] = nrj5compass
544 # f.close()
545 
546 
547 
548 
549 
550 
551 files = []
552 for f in filenames:
553  files.append(h5py.File(f,'r'))
554 
555 
556 # Datas
557 
558 nmodes = (files[0])["P"][:].shape[0]
559 P = (files[0])["P"][:]
560 xpos = files[0].attrs["wfs.xpos"][0]
561 ypos = files[0].attrs["wfs.ypos"][0]
562 contributors = ["tomography", "bandwidth"]
563 Lambda_tar = files[0].attrs["target.Lambda"][0]
564 Lambda_wfs = files[0].attrs["wfs.Lambda"][0]
565 L0 = files[0].attrs["L0"][0]
566 dt = files[0].attrs["ittime"]
567 H = files[0].attrs["atm.alt"][0]
568 RASC = 180/np.pi * 3600.
569 Htheta = np.linalg.norm([xpos,ypos])/RASC*H# np.sqrt(2)*4/RASC*H # Hardcoded for angular separation of sqrt(2)*4 arcsec
570 r0 = files[0].attrs["r0"] * (Lambda_tar/Lambda_wfs)**(6./5.)
571 nfiles = len(files)
572 vartomo = np.zeros((nfiles,nmodes))
573 varbp = np.zeros((nfiles,nmodes))
574 vartot = np.zeros((nfiles,nmodes))
575 theta = np.zeros(nfiles)
576 speeds = np.zeros(nfiles)
577 gain = np.zeros(nfiles)
578 
579 # Illustration du probleme
580 otftel, otf2, psf, gpu = gamora.psf_rec_Vii(filenames[11])
581 cov_err = rexp.get_coverr_independence(filenames[11])
582 otfteli, otf2i, psfi, gpu = gamora.psf_rec_Vii(filenames[11],covmodes=cov_err)
583 psf_compass = np.fft.fftshift(files[11]["psf"][:])
584 RASC = 180/np.pi*3600.
585 pixsize = Lambda_tar*1e-6 / (psf.shape[0] * 8./640) * RASC
586 x = (np.arange(psf.shape[0]) - psf.shape[0]/2) * pixsize / (Lambda_tar*1e-6/8. * RASC)
587 plt.semilogy(x,psf[psf.shape[0]/2,:])
588 plt.semilogy(x,psfi[psf.shape[0]/2,:],color="green")
589 plt.semilogy(x,psf_compass[psf.shape[0]/2,:],color="red")
590 plt.xlabel("Angular distance [units of lambda/D]")
591 plt.ylabel("Normalized intensity")
592 plt.legend(["PSF rec","PSF ind. assumption", "PSF COMPASS"])
593 
594 
595 # data[:,0,i] = var(tomo+bp) for file #i
596 # data[:,1,i] = var(tomo) for file #i
597 # data[:,2,i] = var(bp) for file #i
598 # data[:,3,i] = var(tomo)+var(bp) for file #i
599 ind = 0
600 print("Loading data...")
601 for f in files:
602  #vartot[ind,:] = rexp.variance(f, contributors) * ((2*np.pi/Lambda_tar)**2)
603  #vartomo[ind,:] = rexp.variance(f, ["tomography"]) * ((2*np.pi/Lambda_tar)**2)
604  #varbp[ind,:] = rexp.variance(f, ["bandwidth"]) * ((2*np.pi/Lambda_tar)**2)
605  theta[ind] = f.attrs["winddir"][0]
606  speeds[ind] = f.attrs["windspeed"][0]
607  gain[ind] = float('%.1f' % f.attrs["gain"][0])
608  ind += 1
609  print(ind,"/",len(files))
610 
611 covar = (vartot - (vartomo+varbp))/2.
612 
613 stot = np.sum(vartot,axis=1)
614 sbp = np.sum(varbp,axis=1)
615 stomo = np.sum(vartomo,axis=1)
616 scov = np.sum(covar,axis=1)
617 
618 # Model
619 
620 print("Building models...")
621 vdt = speeds*dt/gain
622 Htheta = np.ones(nfiles) * Htheta
623 gamma = np.arctan2(ypos,xpos) - theta*np.pi/180.
624 rho = np.sqrt(Htheta**2 + (vdt)**2 - 2*Htheta*vdt*np.cos(np.pi-gamma))
625 # Covariance matrices models on actuators space
626 xpos = files[11]["dm.xpos"][:]
627 ypos = files[11]["dm.ypos"][:]
628 p2m = files[11].attrs["tel_diam"] / files[11].attrs["pupdiam"]
629 pupshape = long(2 ** np.ceil(np.log2(files[11].attrs["pupdiam"]) + 1))
630 xactu = (xpos - pupshape/2) * p2m
631 yactu = (ypos - pupshape/2) * p2m
632 M = np.zeros((1304,1304))
633 Mvdt = M.copy()
634 Mht = M.copy()
635 Mhvdt = M.copy()
636 angleht = np.arctan2(files[11].attrs["wfs.ypos"][0],files[11].attrs["wfs.xpos"][0])
637 anglehvdt = gamma/2. - theta*np.pi/180.
638 thetar = theta*np.pi/180.
639 
640 for i in range(1304):
641  for j in range(1304):
642  Mvdt[i,j] = (np.sqrt((xactu[i]-(xactu[j]+vdt[11]*np.cos(thetar[11])))**2 + (yactu[i]-(yactu[j]+vdt[11]*np.sin(thetar[11])))**2))
643  M[i,j] = (np.sqrt((xactu[i]-xactu[j])**2 + (yactu[i]-yactu[j])**2))
644  Mht[i,j] = (np.sqrt((xactu[i]-(xactu[j]+Htheta[11]*np.cos(angleht)))**2 + (yactu[i]-(yactu[j]+Htheta[11]*np.sin(angleht)))**2))
645  #Mhvdt[i,j] = (np.sqrt((xactu[i]-(xactu[j]+rho[11]*np.cos(anglehvdt[11])))**2 + (yactu[i]-(yactu[j]+rho[11]*np.sin(anglehvdt[11])))**2))
646  Mhvdt[i,j] = (np.sqrt(((xactu[i]-vdt[11]*np.cos(thetar[11]))-(xactu[j]+Htheta[11]*np.cos(angleht)))**2 + ((yactu[i]-vdt[11]*np.sin(thetar[11]))-(yactu[j]+Htheta[11]*np.sin(angleht)))**2))
647 
648 Ccov = (Dphi.dphi_lowpass(Mhvdt,0.2,L0,tabx,taby) - Dphi.dphi_lowpass(Mht,0.2,L0,tabx,taby) \
649  - Dphi.dphi_lowpass(Mvdt,0.2,L0,tabx,taby) + Dphi.dphi_lowpass(M,0.2,L0,tabx,taby)) * (1/r0)**(5./3.)
650 
651 
652 mtomo = Dphi.dphi_lowpass(Htheta,0.2,L0, tabx, taby) * (1/r0)**(5./3.)
653 mbp = Dphi.dphi_lowpass(vdt ,0.2, L0, tabx, taby) * (1/r0)**(5./3.)
654 mtot = Dphi.dphi_lowpass(rho,0.2,L0,tabx,taby) * (1/r0)**(5./3.)
655 
656 # Piston correction
657 print("Computing piston correction...")
658 pup = gamora.get_pup(filenames[11])
659 r = np.zeros((8192,8192))
660 p2m = files[11].attrs["tel_diam"]/pup.shape[0]
661 Npts = files[11]["indx_pup"].size
662 for k in range(r.shape[0]):
663  for j in range(r.shape[0]):
664  r[k,j] = np.sqrt((k-r.shape[0]/2+0.5)**2+(j-r.shape[0]/2+0.5)**2) * p2m
665 
666 ipup = np.zeros((8192,8192))
667 ipup[3776:3776+640,3776:3776+640] = pup
668 dphi_map = Dphi.dphi_lowpass(r,0.2,L0,tabx,taby) * (1/r0)**(5./3.)
669 fpup = np.fft.fft2(ipup)#,s=[8192,8192])
670 fdphi = np.fft.fft2(dphi_map)#,s=[8192,8192])
671 fconv = fpup * fpup * fdphi
672 dconv = np.fft.ifft2(fconv).real / Npts / Npts
673 mini = np.where(dconv == dconv.min())
674 dutil = dconv[mini[0][0],mini[1][0]:]
675 #Avdt = dconv[mini[0]+(vdt/p2m).astype(np.int16),mini[1]] - dconv[mini]
676 Pbp = np.interp(vdt/p2m,np.arange(dutil.shape[0]),dutil) - dutil[0]
677 Ptomo = (np.interp(Htheta/gain/p2m,np.arange(dutil.shape[0]),dutil) - dutil[0])*gain**2
678 Ptot = np.interp(rho/p2m,np.arange(dutil.shape[0]),dutil) - dutil[0]
679 
680 mtomo -= Ptomo
681 mbp -= Pbp
682 mtot -= Ptot
683 mcov = (-mtomo - mbp + mtot)*0.5
684 
685 
686 # Correction on psf
687 m = (np.arange(nmodes)+1)**(-5/6.)
688 m /= m.sum()
689 m = m * (mcov[11] / (2*np.pi/Lambda_tar)**2)
690 
691 
692 cov_err2 = P.dot(cov_err).dot(P.T) + 2*np.diag(m)
693 otftelc, otf2c, psfc, gpu = gamora.psf_rec_Vii(filenames[11],cov=cov_err2.astype(np.float32))
694 plt.figure()
695 plt.semilogy(x,psf_compass[psf.shape[0]/2,:],color="red")
696 plt.semilogy(x,psfi[psf.shape[0]/2,:],color="green")
697 plt.semilogy(x,psfc[psf.shape[0]/2,:],color="blue")
698 plt.xlabel("Angular distance [units of lambda/D]")
699 plt.ylabel("Normalized intensity")
700 plt.legend([ "PSF COMPASS","PSF ind. assumption","PSF corrected"])
701 
702 
703 xpos = files[11]["dm.xpos"][:]
704 ypos = files[11]["dm.ypos"][:]
705 dm_dim = files[11]["dm_dim"].value
706 xpos -= (pupshape-dm_dim)/2
707 ypos -= (pupshape-dm_dim)/2
708 influ = np.load("influ.npy")
709 influ2 = np.zeros((dm_dim,dm_dim))
710 tmp = influ2.copy()
711 indx_pup = files[11]["indx_pup"][:]
712 pup = np.zeros((dm_dim,dm_dim)).flatten()
713 pup[indx_pup] = 1
714 pup = pup.reshape((dm_dim,dm_dim))
715 ind2 = np.where(pup)
716 influshape = influ.shape[0]
717 A = np.zeros((xpos.size,xpos.size))
718 rr = Htheta[11]
719 xx = np.cos(0*theta[11]*np.pi/180.)*rr/p2m
720 yy = np.sin(0*theta[11]*np.pi/180.)*rr/p2m
721 pup2 = pup.copy()*0.
722 pup2[(ind2[0]+xx).astype(np.int32),(ind2[1]+yy).astype(np.int32)] = 1.
723 
724 for i in range(xpos.size):
725  influ2 *=0
726  influ2[xpos[i]-influshape/2+1:xpos[i]+influshape/2+1,ypos[i]-influshape/2+1:ypos[i]+influshape/2+1] = influ
727  influ2 *= pup
728  for j in range(xpos.size):
729  if(tmp[xpos[j]-influshape/2+1+xx:xpos[j]+influshape/2+1+xx,ypos[j]-influshape/2+1+yy:ypos[j]+influshape/2+1+yy].shape == influ.shape):
730  tmp *=0
731  tmp[xpos[j]-influshape/2+1+xx:xpos[j]+influshape/2+1+xx,ypos[j]-influshape/2+1+yy:ypos[j]+influshape/2+1+yy] = influ
732  tmp *= pup2
733  A[i,j] = (influ2*tmp).sum()
734  else:
735  A[i,j] = 0.
736  print(i)
737 """
correlation_study.load_datas
def load_datas(files)
Definition: correlation_study.py:263
correlation_study.compute_psf_independence
def compute_psf_independence(filename)
Definition: correlation_study.py:31
correlation_study.ensquare_PSF
def ensquare_PSF(filename, psf, N, display=False)
Definition: correlation_study.py:313
correlation_study.compute_covariance_model
def compute_covariance_model(filename)
Definition: correlation_study.py:173
correlation_study.compute_and_compare_PSFs
def compute_and_compare_PSFs(filename, plot=False)
Definition: correlation_study.py:37
correlation_study.compareTransferFunctions
def compareTransferFunctions(filename)
Definition: correlation_study.py:373
correlation_study.cutsPSF
def cutsPSF(filename, psf, psfs)
Definition: correlation_study.py:335
correlation_study.compute_psf
def compute_psf(filename)
Definition: correlation_study.py:26
correlation_study.filter_TT
def filter_TT(filename, C)
Definition: correlation_study.py:151
correlation_study.Hcor
def Hcor(f, Fe, g, dt)
Definition: correlation_study.py:363
correlation_study.filter_piston_TT
def filter_piston_TT(filename, C)
Definition: correlation_study.py:126
correlation_study.Hretard
def Hretard(f, Fe, g, dt)
Definition: correlation_study.py:368
correlation_study.add_TT_model
def add_TT_model(filename, Ccov)
Definition: correlation_study.py:246