COMPASS  5.0.0
End-to-end AO simulation tool using GPU acceleration
misc/correlations/script_roket.py
1 """
2 Created on Tue Jul 12 09:28:23 2016
3 
4 @author: fferreira
5 """
6 
7 import cProfile
8 import pstats as ps
9 
10 import sys, os
11 import numpy as np
12 import carmaWrap as ch
13 import shesha as ao
14 import time
15 import matplotlib.pyplot as plt
16 plt.ion()
17 import hdf5_util as h5u
18 import pandas
19 from scipy.sparse import csr_matrix
20 
21 
28 c = ch.carmaWrap_context(devices=np.array([6, 7], dtype=np.int32))
29 
30 
31 def init_config(config):
32  if (hasattr(config, "simul_name")):
33  if (config.simul_name is None):
34  simul_name = ""
35  else:
36  simul_name = config.simul_name
37  else:
38  simul_name = ""
39  print("simul name is", simul_name)
40 
41  matricesToLoad = {}
42  if (simul_name == b""):
43  clean = 1
44  else:
45  clean = 0
46  param_dict = h5u.params_dictionary(config)
47  matricesToLoad = h5u.checkMatricesDataBase(os.environ["SHESHA_ROOT"] + "/data/",
48  config, param_dict)
49  #initialisation:
50  # context
51  #c=ch.carmaWrap_context(device)
52  c = ch.carmaWrap_context(devices=np.array([6, 7], dtype=np.int32))
53  #c.set_active_device(device)
54 
55  # wfs
56  print("->wfs")
57  wfs, tel = ao.wfs_init(config.p_wfss, config.p_atmos, config.p_tel, config.p_geom,
58  config.p_target, config.p_loop, config.p_dms)
59 
60  # atmos
61  print("->atmos")
62  atm = ao.atmos_init(c, config.p_atmos, config.p_tel, config.p_geom, config.p_loop,
63  config.p_wfss, wfs, config.p_target, rank=0, clean=clean,
64  load=matricesToLoad)
65 
66  # dm
67  print("->dm")
68  dms = ao.dm_init(config.p_dms, config.p_wfss, wfs, config.p_geom, config.p_tel)
69 
70  # target
71  print("->target")
72  tar = ao.target_init(c, tel, config.p_target, config.p_atmos, config.p_geom,
73  config.p_tel, config.p_dms)
74 
75  print("->rtc")
76  # rtc
77  rtc = ao.rtc_init(tel, wfs, config.p_wfss, dms, config.p_dms, config.p_geom,
78  config.p_rtc, config.p_atmos, atm, config.p_tel, config.p_loop,
79  clean=clean, simul_name=simul_name, load=matricesToLoad)
80 
81  if not clean:
82  h5u.validDataBase(os.environ["SHESHA_ROOT"] + "/data/", matricesToLoad)
83 
84  print("====================")
85  print("init done")
86  print("====================")
87  print("objects initialzed on GPU:")
88  print("--------------------------------------------------------")
89  print(atm)
90  print(wfs)
91  print(dms)
92  print(tar)
93  print(rtc)
94 
95  print("----------------------------------------------------")
96  print("iter# | SE SR image | LE SR image | Fitting | LE SR phase var")
97  print("----------------------------------------------------")
98 
99  error_flag = True in [w.roket for w in config.p_wfss]
100 
101  return atm, wfs, tel, dms, tar, rtc
102 
103 
104 
111 def loop(n):
112  """
113  Performs the main AO loop for n interations. First, initialize buffers
114  for error breakdown computations. Then, at the end of each iteration, just
115  before applying the new DM shape, calls the error_breakdown function.
116 
117  :param n: (int) : number of iterations
118 
119  :return:
120  com : (np.array((n,nactus))) : full command buffer
121 
122  noise_com : (np.array((n,nactus))) : noise contribution for error breakdown
123 
124  alias_wfs_com : (np.array((n,nactus))) : aliasing estimation in the WFS direction
125 
126  tomo_com : (np.array((n,nactus))) : tomography error estimation
127 
128  H_com : (np.array((n,nactus))) : Filtered modes contribution for error breakdown
129 
130  trunc_com : (np.array((n,nactus))) : Truncature and sampling error of WFS
131 
132  bp_com : (np.array((n,nactus))) : Bandwidth error estimation on target
133 
134  mod_com : (np.array((n,nactus))) : Commanded modes expressed on the actuators
135 
136  fit : (float) : fitting (mean variance of the residual target phase after projection)
137 
138  SR : (float) : final strehl ratio returned by the simulation
139  """
140  if (error_flag):
141  # Initialize buffers for error breakdown
142  nactu = rtc.get_command(0).size
143  nslopes = rtc.get_centroids(0).size
144  com = np.zeros((n, nactu), dtype=np.float32)
145  noise_com = np.zeros((n, nactu), dtype=np.float32)
146  alias_wfs_com = np.copy(noise_com)
147  wf_com = np.copy(noise_com)
148  tomo_com = np.copy(noise_com)
149  trunc_com = np.copy(noise_com)
150  H_com = np.copy(noise_com)
151  mod_com = np.copy(noise_com)
152  bp_com = np.copy(noise_com)
153  fit = np.zeros(n)
154  # covm = np.zeros((nslopes,nslopes))
155  # covv = np.zeros((nactu,nactu))
156 
157  t0 = time.time()
158  for i in range(-10, n):
159  atm.move_atmos()
160 
161  if (config.p_controllers[0].type == b"geo"):
162  for t in range(config.p_target.ntargets):
163  tar.atmos_trace(t, atm, tel)
164  rtc.docontrol_geo(0, dms, tar, 0)
165  rtc.applycontrol(0, dms)
166  tar.dmtrace(0, dms)
167  else:
168  for t in range(config.p_target.ntargets):
169  tar.atmos_trace(t, atm, tel)
170  tar.dmtrace(t, dms)
171  for w in range(len(config.p_wfss)):
172  wfs.sensors_trace(w, "all", tel, atm, dms)
173  wfs.sensors_compimg(w)
174  rtc.docentroids(0)
175  rtc.docontrol(0)
176  #m = np.reshape(rtc.get_centroids(0),(nslopes,1))
177  #v = np.reshape(rtc.get_command(0),(nactu,1))
178  if (error_flag and i > -1):
179  #compute the error breakdown for this iteration
180  #covm += m.dot(m.T)
181  #covv += v.dot(v.T)
182  roket.computeBreakdown()
183  rtc.applycontrol(0, dms)
184 
185  if ((i + 1) % 100 == 0 and i > -1):
186  strehltmp = tar.get_strehl(0)
187  print(i + 1, "\t", strehltmp[0], "\t", strehltmp[1], "\t",
188  np.exp(-strehltmp[2]), "\t", np.exp(-strehltmp[3]))
189  t1 = time.time()
190  print(" loop execution time:", t1 - t0, " (", n, "iterations), ", (t1 - t0) / n,
191  "(mean) ", n / (t1 - t0), "Hz")
192  if (error_flag):
193  #Returns the error breakdown
194  SR2 = np.exp(-tar.get_strehl(0, comp_strehl=False)[3])
195  SR = tar.get_strehl(0, comp_strehl=False)[1]
196  #bp_com[-1,:] = bp_com[-2,:]
197  #SR = tar.get_strehl(0,comp_strehl=False)[1]
198  return SR, SR2
199 
200 
201 def preloop(n):
202  """
203  Performs the main AO loop for n interations. First, initialize buffers
204  for error breakdown computations. Then, at the end of each iteration, just
205  before applying the new DM shape, calls the error_breakdown function.
206 
207  :param n: (int) : number of iterations
208 
209  :return:
210  com : (np.array((n,nactus))) : full command buffer
211 
212  noise_com : (np.array((n,nactus))) : noise contribution for error breakdown
213 
214  alias_wfs_com : (np.array((n,nactus))) : aliasing estimation in the WFS direction
215 
216  tomo_com : (np.array((n,nactus))) : tomography error estimation
217 
218  H_com : (np.array((n,nactus))) : Filtered modes contribution for error breakdown
219 
220  trunc_com : (np.array((n,nactus))) : Truncature and sampling error of WFS
221 
222  bp_com : (np.array((n,nactus))) : Bandwidth error estimation on target
223 
224  mod_com : (np.array((n,nactus))) : Commanded modes expressed on the actuators
225 
226  fit : (float) : fitting (mean variance of the residual target phase after projection)
227 
228  SR : (float) : final strehl ratio returned by the simulation
229  """
230  for i in range(0, n):
231  atm.move_atmos()
232 
233  if (config.p_controllers[0].type == b"geo"):
234  for t in range(config.p_target.ntargets):
235  tar.atmos_trace(t, atm, tel)
236  rtc.docontrol_geo(0, dms, tar, 0)
237  rtc.applycontrol(0, dms)
238  else:
239  for t in range(config.p_target.ntargets):
240  tar.atmos_trace(t, atm, tel)
241  for w in range(len(config.p_wfss)):
242  wfs.sensors_trace(w, "all", tel, atm, dms)
243  wfs.sensors_compimg(w)
244  rtc.docentroids(0)
245  rtc.docontrol(0)
246 
247  rtc.applycontrol(0, dms)
248 
249 
250 
257  IF = rtc.get_IFsparse(1).T
258  N = IF.shape[0]
259  n = IF.shape[1]
260  #T = IF[:,-2:].copy()
261  T = rtc.get_IFtt(1)
262  #IF = IF[:,:n-2]
263  n = IF.shape[1]
264 
265  delta = IF.T.dot(IF).toarray() / N
266 
267  # Tip-tilt + piston
268  Tp = np.ones((T.shape[0], T.shape[1] + 1))
269  Tp[:, :2] = T.copy() #.toarray()
270  deltaT = IF.T.dot(Tp) / N
271  # Tip tilt projection on the pzt dm
272  tau = np.linalg.inv(delta).dot(deltaT)
273 
274  # Famille generatrice sans tip tilt
275  G = np.identity(n)
276  tdt = tau.T.dot(delta).dot(tau)
277  subTT = tau.dot(np.linalg.inv(tdt)).dot(tau.T).dot(delta)
278  G -= subTT
279 
280  # Base orthonormee sans TT
281  gdg = G.T.dot(delta).dot(G)
282  U, s, V = np.linalg.svd(gdg)
283  U = U[:, :U.shape[1] - 3]
284  s = s[:s.size - 3]
285  L = np.identity(s.size) / np.sqrt(s)
286  B = G.dot(U).dot(L)
287 
288  # Rajout du TT
289  TT = T.T.dot(T) / N #.toarray()/N
290  Btt = np.zeros((n + 2, n - 1))
291  Btt[:B.shape[0], :B.shape[1]] = B
292  mini = 1. / np.sqrt(TT)
293  mini[0, 1] = 0
294  mini[1, 0] = 0
295  Btt[n:, n - 3:] = mini
296 
297  # Calcul du projecteur actus-->modes
298  delta = np.zeros((n + T.shape[1], n + T.shape[1]))
299  #IF = rtc.get_IFsparse(1).T
300  delta[:-2, :-2] = IF.T.dot(IF).toarray() / N
301  delta[-2:, -2:] = T.T.dot(T) / N
302  P = Btt.T.dot(delta)
303 
304  return Btt.astype(np.float32), P.astype(np.float32)
305 
306 
307 def compute_cmatWithBtt(Btt, nfilt):
308  D = rtc.get_imat(0)
309  #D = ao.imat_geom(wfs,config.p_wfss,config.p_controllers[0],dms,config.p_dms,meth=0)
310  # Filtering on Btt modes
311  Btt_filt = np.zeros((Btt.shape[0], Btt.shape[1] - nfilt))
312  Btt_filt[:, :Btt_filt.shape[1] - 2] = Btt[:, :Btt.shape[1] - (nfilt + 2)]
313  Btt_filt[:, Btt_filt.shape[1] - 2:] = Btt[:, Btt.shape[1] - 2:]
314 
315  # Modal interaction basis
316  Dm = D.dot(Btt_filt)
317  # Direct inversion
318  Dmp = np.linalg.inv(Dm.T.dot(Dm)).dot(Dm.T)
319  # Command matrix
320  cmat = Btt_filt.dot(Dmp)
321 
322  return Dm.astype(np.float32), cmat.astype(np.float32)
323 
324 
325 def compute_cmatWithBtt2(Btt, nfilt):
326  D = rtc.get_imat(0)
327 
328  # Modal interaction basis
329  Dm = D.dot(Btt)
330  # Filtering on modal imat
331  DmtDm = Dm.T.dot(Dm)
332  U, s, V = np.linalg.svd(DmtDm)
333  s = 1. / s
334  s[s.shape[0] - nfilt - 2:s.shape[0] - 2] = 0.
335  DmtDm1 = U.dot(np.diag(s)).dot(U.T)
336  Dmp = DmtDm1.dot(Dm.T)
337  # Command matrix
338  cmat = Btt.dot(Dmp)
339 
340  return Dm.astype(np.float32), cmat.astype(np.float32)
341 
342 
343 
350 
351 
352 def cov_cor(P, noise, trunc, alias, H, bp, tomo):
353  cov = np.zeros((6, 6))
354  bufdict = {
355  "0": noise.T,
356  "1": trunc.T,
357  "2": alias.T,
358  "3": H.T,
359  "4": bp.T,
360  "5": tomo.T
361  }
362  for i in range(cov.shape[0]):
363  for j in range(cov.shape[1]):
364  if (j >= i):
365  tmpi = P.dot(bufdict[str(i)])
366  tmpj = P.dot(bufdict[str(j)])
367  cov[i, j] = np.sum(
368  np.mean(tmpi * tmpj, axis=1) -
369  np.mean(tmpi, axis=1) * np.mean(tmpj, axis=1))
370  else:
371  cov[i, j] = cov[j, i]
372 
373  s = np.reshape(np.diag(cov), (cov.shape[0], 1))
374  sst = np.dot(s, s.T)
375  cor = cov / np.sqrt(sst)
376 
377  return cov, cor
378 
379 
380 
386 
387 
388 def save_it(filename):
389  IF = rtc.get_IFsparse(1)
390  TT = rtc.get_IFtt(1)
391  noise_com = roket.getContributor("noise")
392  trunc_com = roket.getContributor("nonlinear")
393  alias_wfs_com = roket.getContributor("aliasing")
394  H_com = roket.getContributor("filtered")
395  bp_com = roket.getContributor("bandwidth")
396  tomo_com = roket.getContributor("tomo")
397  fit = roket.getContributor("fitting")
398 
399  tmp = (config.p_geom._ipupil.shape[0] -
400  (config.p_dms[0]._n2 - config.p_dms[0]._n1 + 1)) / 2
401  tmp_e0 = config.p_geom._ipupil.shape[0] - tmp
402  tmp_e1 = config.p_geom._ipupil.shape[1] - tmp
403  pup = config.p_geom._ipupil[tmp:tmp_e0, tmp:tmp_e1]
404  indx_pup = np.where(pup.flatten() > 0)[0].astype(np.int32)
405  dm_dim = config.p_dms[0]._n2 - config.p_dms[0]._n1 + 1
406  cov, cor = cov_cor(P, noise_com, trunc_com, alias_wfs_com, H_com, bp_com, tomo_com)
407  psf = tar.get_image(0, "le", fluxNorm=False)
408  psfortho = roket.get_tar_imageortho()
409  covv = roket.get_covv()
410  covm = roket.get_covm()
411 
412  fname = "/home/fferreira/Data/" + filename
413  pdict = {
414  "noise": noise_com.T,
415  "aliasing": alias_wfs_com.T,
416  "tomography": tomo_com.T,
417  "filtered modes": H_com.T,
418  "non linearity": trunc_com.T,
419  "bandwidth": bp_com.T,
420  "P": P,
421  "Btt": Btt,
422  "IF.data": IF.data,
423  "IF.indices": IF.indices,
424  "IF.indptr": IF.indptr,
425  "TT": TT,
426  "dm_dim": dm_dim,
427  "indx_pup": indx_pup,
428  "fitting": fit,
429  "SR": SR,
430  "SR2": SR2,
431  "cov": cov,
432  "cor": cor,
433  "psfortho": psfortho,
434  "covm": covm,
435  "covv": covv
436  }
437  h5u.save_h5(fname, "psf", config, psf)
438  #h5u.writeHdf5SingleDataset(fname,com.T,datasetName="com")
439  for k in list(pdict.keys()):
440  h5u.save_hdf5(fname, k, pdict[k])
441 
442 
443 
450 param_file = "/home/fferreira/compass/trunk/shesha/data/par/par4roket/correlation_study/roket_8m_1layer.py"
451 error_flag = True
452 if (param_file.split('.')[-1] == b"py"):
453  filename = param_file.split('/')[-1]
454  param_path = param_file.split(filename)[0]
455  sys.path.insert(0, param_path)
456  exec("import %s as config" % filename.split(".py")[0])
457  #sys.path.remove(param_path)
458 nfiltered = 20
459 niters = config.p_loop.niter
460 
461 winddirs = [0, 45, 90, 135, 180]
462 windspeeds = [5., 10., 15., 20.]
463 
464 d = float(sys.argv[1])
465 s = float(sys.argv[2])
466 g = float(sys.argv[3])
467 
468 savename = "roket_8m_1layer_dir%d_speed%d_g%d.h5" % (d, s, g * 10)
469 config.p_atmos.set_winddir([d])
470 config.p_atmos.set_windspeed([s])
471 config.p_controllers[0].set_gain(g)
472 
473 atm, wfs, tel, dms, tar, rtc = init_config(config)
474 #config.p_loop.set_niter(niters)
475 Btt, P = compute_btt()
476 rtc.load_Btt(1, Btt.dot(Btt.T))
477 Dm, cmat = compute_cmatWithBtt(Btt, nfiltered)
478 rtc.set_cmat(0, cmat)
479 R = rtc.get_cmat(0)
480 imat = rtc.get_imat(0)
481 RD = np.dot(R, imat).astype(np.float32)
482 gRD = (np.identity(RD.shape[0]) - config.p_controllers[0].gain * RD).astype(np.float32)
483 roket = ao.roket_init(rtc, wfs, tar, dms, tel, atm, 0, 1, Btt.shape[0], Btt.shape[1],
484  nfiltered, niters, Btt, P, gRD, RD)
485 preloop(1000)
486 SR, SR2 = loop(niters)
487 
488 save_it(savename)
script_roket.save_it
def save_it(filename)
Definition: misc/correlations/script_roket.py:388
script_roket.compute_btt
def compute_btt()
Definition: misc/correlations/script_roket.py:256
script_roket.cov_cor
def cov_cor(P, noise, trunc, alias, H, bp, tomo)
Definition: misc/correlations/script_roket.py:352
script_roket.compute_cmatWithBtt2
def compute_cmatWithBtt2(Btt, nfilt)
Definition: misc/correlations/script_roket.py:325
script_roket.compute_cmatWithBtt
def compute_cmatWithBtt(Btt, nfilt)
Definition: misc/correlations/script_roket.py:307
script_roket.loop
def loop(n)
Definition: misc/correlations/script_roket.py:139
script_roket.init_config
def init_config(config)
Definition: misc/correlations/script_roket.py:31
script_roket.preloop
def preloop(n)
Definition: misc/correlations/script_roket.py:229