-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreach_inj_opt.py
365 lines (289 loc) · 14.1 KB
/
reach_inj_opt.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
### Injection optimization for the REACH module on SCExAO
### Author : Sebastien Vievard
import pygame, sys
from pygame.locals import *
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from astropy.io import fits
import struct
import os
from PIL import Image
import time
import math as m
import copy
import datetime
from astropy.io import fits as pf
import subprocess
import os,sys
# from xaosim.scexao_shmlib import shm
from pyMilk.interfacing.isio_shmlib import SHM as shm
home = os.getenv('HOME')
sys.path.append(home+'/src/lib/python/')
sys.path.append(home+'/Documents/sebviev/Bench_tests/')
import conex_tt as conex_tt
import conex3 as conex
con = conex.conex()
from tqdm import tqdm
import imageio
from scipy import optimize
from scipy.optimize import curve_fit
plt.ion()
class reach_inj(object):
def __init__(self):###############################################################################################
self.flux=shm("ird_flux_val")
## Conex for Theta
self.conex_id_theta="/dev/serial/by-id/usb-Newport_CONEX-AGP_A64MV6OB-if00-port0"
## Connex for Phi
self.conex_id_phi="/dev/serial/by-id/usb-Newport_CONEX-AGP_A6WMSQ3G-if00-port0"
## Conex for pcfi_len --> focus of the fiber
self.conexidz="/dev/serial/by-id/usb-Newport_CONEX-AGP_A606QDT0-if00-port0u"
## Tip/Tilt mount adress
self.adress_TT = "http://133.40.163.196:50002"
## NOTE : For TT, max values +/- 0.75
## NOTE : move(x,y) --> X = theta, Y = Phi
def save_info(self,info, save_name):######################################################################################
import json
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Write JSON file
with io.open(save_name, 'w', encoding='utf8') as outfile:
str_ = json.dumps(info,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
def spiral(self,a):##############################################################################################
sp = np.zeros((a**2,2))
switch = np.zeros(a**2)
x = y = 0
dx = 0
dy = -1
for i in range(a**2):
sp[i,:] = np.array([x,y], dtype=float)/(a-1)*2
if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
switch[i] = True
dx, dy = -dy, dx
else:
switch[i] = False
x, y = x+dx, y+dy
return sp,switch
def show_optim(self,res_opt,ird_channel_opt,Target):######################################################################################
plt.figure()
plt.subplot(4,2,1)
idplt=1
cmin=np.min(self.res_optim)
cmax=np.max(self.res_optim[:,:,ird_channel_opt])
for id in range(8):
plt.subplot(4,2,idplt)
plt.imshow(self.res_optim[:,:,id],origin='lower')
plt.ylabel('#'+str(id+1))
# plt.clim([cmin,cmax])
idplt+=1
self.date=datetime.datetime.today().strftime('%Y-%m-%d')
self.clock=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
path_save='/home/scexao/Documents/sebviev/REACH_injection/data/Optim_maps/'+self.date+'/'+self.clock+'_'+Target+'/'
if not os.path.exists(path_save):
os.makedirs(path_save)
#plt.savefig(path_save+'optim_result.png',orientation='landscape')
for i in range(8):
# plt.imsave(path_save+'optim_'+self.clock+'_'+str(i+1)+'.pdf', self.res_optim[:,:,i])
hdu=fits.PrimaryHDU(self.res_optim[:,:,i])
hdu.writeto(path_save+'optim_'+self.clock+'_'+str(i+1)+'.fits')
def optimization_slow(self,phi0=0., theta0=0., window_mas=0.05, npt=5, n_raw=1, ird_channel_opt=0, Target='Name_of_Target'):######################
#############################
# Unit conversion #
#############################
step_mas = window_mas/(npt-1)
sp, switch = self.spiral(npt)
sp = sp*(window_mas/2.)
xi,yi = 0,0
self.res_optim_raw = np.zeros((npt, npt, n_raw, 8))
self.res_optim = np.zeros((npt, npt, 8))
indphi0 = int(npt//2.)
indtheta0 = int(npt//2.)
self.map_phi = np.zeros((npt,npt))
self.map_theta = np.zeros((npt,npt))
#step2mas = 5300
#mas2step = 1/5300
step2mas = 1
mas2step = 1
#############################
# First position #
#############################
# con.open(self.conex_id_phi)
# con.move(phi0, "", False)
conex_tt.move(theta0,phi0,address=self.adress_TT)
time.sleep(0.2)
# con.close()
# con.open(self.conex_id_theta)
# con.move(theta0, "", False)
# time.sleep(0.1)
# con.close()
cnt = 0
cnt1 = 0
#print('Position: x:',phi0,'y:',theta0)
self.map_phi[indphi0,indtheta0] = phi0
self.map_theta[indphi0,indtheta0] = theta0
for r in range(n_raw):
while (cnt1 <= cnt):
cnt1 = self.flux.get_counter()
cnt = cnt1
self.res_optim_raw[indphi0,indtheta0,r,:] = (self.flux.get_data(True, True, timeout = 1.))#[:,0]
#time.sleep(0.002)
self.res_optim[indphi0,indtheta0,:] = np.mean(self.res_optim_raw[indphi0,indtheta0,:,:],axis=0)
#print(self.res_optim[int(indphi0)-1,int(indtheta0)-1])
#print('Index: x:',np.ceil(indphi0-1),'y:',np.ceil(indtheta0-1))
#############################
# Start spiral movement #
#############################
for i in tqdm(range(1,npt**2)):
# for i in range(1,npt**2):
xi = phi0+sp[i,0]*mas2step
yi = theta0+sp[i,1]*mas2step
#print('Position: x:',xi,'y:',yi)
indphi = indphi0+int(sp[i,0]/(window_mas/2.)*(npt//2.))
indtheta = indtheta0+int(sp[i,1]/(window_mas/2.)*(npt//2.))
self.map_phi[indphi,indtheta] = xi
self.map_theta[indphi,indtheta] = yi
#print('Index: x:',np.ceil(indphi-1),'y:',np.ceil(indtheta-1))
if i==1:
# con.open(self.conex_id_phi)
axis = "x"
# con.move(xi, "", False)
conex_tt.move(yi,xi,address=self.adress_TT)
#print(i, axis, xi-phi0, yi-theta0)
if i > 1:
if switch[i-1]:
# con.close()
if axis == "y":
# con.open(self.conex_id_phi)
axis = "x"
else:
# con.open(self.conex_id_theta)
axis = "y"
if axis == "x":
# con.move(xi, "", False)
conex_tt.move(yi,xi,address=self.adress_TT)
else:
conex_tt.move(yi,xi,address=self.adress_TT)
# con.move(yi, "", False)
time.sleep(0.2)
#############################
# Take Flux values #
#############################
cnt = 0
cnt1 = 0
for r in range(n_raw):
while (cnt1 <= cnt):
cnt1 = self.flux.get_counter()
cnt = cnt1
self.res_optim_raw[indphi,indtheta,r,:] = (self.flux.get_data(True, True, timeout = 1.))#[:,0]
#time.sleep(0.002)
self.res_optim[indphi,indtheta,:] = np.mean(self.res_optim_raw[indphi,indtheta,:,:],axis=0)
#print(self.res_optim[int(indphi)-1,int(indtheta)-1])
#############################
# Show/save Optimization #
#############################
self.show_optim(self.res_optim,ird_channel_opt,Target)
#############################
# Extract optimal pos #
#############################
indphi_opt, indtheta_opt = self.process_optim_map(self.res_optim[:,:,ird_channel_opt], Target, window_mas, np.around(step_mas,decimals=2))
phi_opt = phi0 -(indphi0 -indphi_opt) *step_mas
theta_opt = theta0-(indtheta0-indtheta_opt)*step_mas
print('Optimal process position in phi:',phi_opt, 'in theta:',theta_opt)
if phi_opt < np.around(np.min(self.map_phi),decimals=4) or phi_opt > np.around(np.max(self.map_phi),decimals=4):
indphi_opt, indtheta_opt = np.unravel_index(self.res_optim[:,:,ird_channel_opt].argmax(),(npt,npt))
phi_opt = self.map_phi[indphi_opt, indtheta_opt]
print('Warning : Phi optimal value out of the box')
if theta_opt < np.around(np.min(self.map_theta),decimals=4) or theta_opt > np.around(np.max(self.map_theta),decimals=4):
indphi_opt, indtheta_opt = np.unravel_index(self.res_optim[:,:,ird_channel_opt].argmax(),(npt,npt))
theta_opt = self.map_theta[indphi_opt, indtheta_opt]
print('Warning : Theta optimal value out of the box')
#scan_mas=(((np.max(self.map_phi)-np.min(self.map_phi))*1e3)/10.)*53
#step_mas=(((self.map_phi[1,0]-self.map_phi[0,0])*1e3)/10.)*53
scan_mas = 1
step_mas = 1
print('Scan in x from ',np.around(np.min(self.map_phi),decimals=4),'to',np.around(np.max(self.map_phi),decimals=4), '--', np.around(scan_mas,decimals=0),'mas')
print('Scan in y from ',np.around(np.min(self.map_theta),decimals=4),'to',np.around(np.max(self.map_theta),decimals=4))
print('Step:',np.around((self.map_phi[1,0]-self.map_phi[0,0])*1e3,decimals=1),'um', '--', np.around(step_mas,decimals=0),'mas' )
print('Optimal position in phi:',np.around(phi_opt, decimals = 6), 'in theta:',np.around(theta_opt, decimals=6))
#############################
# Move to optimal pos #
#############################
conex_tt.move(theta_opt,phi_opt,address=self.adress_TT)
# con.open(self.conex_id_phi)
# con.move(phi_opt, "", False)
# con.close()
# con.open(self.conex_id_theta)
# con.move(theta_opt, "", False)
# con.close()
#############################
# Save info optim #
#############################
info={'Target' : Target,
'phi init' : phi0,
'theta init' : theta0,
'Windows size (mas)' : window_mas,
'Step size (mas)' : step_mas,
'Number frames' : n_raw,
'phi optimal' : phi_opt,
'theta optimal' : theta_opt,
}
#date=datetime.datetime.today().strftime('%Y-%m-%d')
#clock=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
self.save_info(info, '/home/scexao/Documents/sebviev/REACH_injection/data/Optim_maps/'+self.date+'/'+self.clock+'_'+Target+'/info_'+self.clock+'_'+Target+'.txt')
return(theta_opt,phi_opt) #SEB, I added this line for my code -Julien
def process_optim_map(self, data, Target, window_mas, step_mas):######################################################################################
def gaussian(height, center_x, center_y, width_x, width_y):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
return lambda x,y: height*np.exp(
-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)
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(np.abs((np.arange(col.size)-y)**2*col).sum()/col.sum())
row = data[int(x), :]
width_y = np.sqrt(np.abs((np.arange(row.size)-x)**2*row).sum()/row.sum())
height = data.max()
return height, x, y, width_x, width_y
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(*p)(*np.indices(data.shape)) -
data)
p, success = optimize.leastsq(errorfunction, params)
return p
image=data
plt.figure()
plt.imshow(image,origin='lower')
params=fitgaussian(image)
fit=gaussian(*params)
plt.contour(fit(*np.indices(image.shape)), cmap=plt.cm.copper)
ax=plt.gca()
(height,x,y,width_x,width_y)=params
#print('(%.1f,%.1f)'%(x,y))
plt.gca().set_title('Optimization map - '+Target)#+'- Scan='+str(window_mas)+'mas Step='+str(step_mas)+'mas')
plt.text(0.95,0.05,"""
Center:(%.1f,%.1f)
Width_x:%.1f
Width_y:%.1f"""%(x,y,width_x,width_y),fontsize=10,horizontalalignment='right',verticalalignment='bottom',transform=ax.transAxes,color='w')
path_save='/home/scexao/Documents/sebviev/REACH_injection/data/Optim_maps/'+self.date+'/'+self.clock+'_'+Target+'/'
plt.savefig(path_save+Target+'_processed.png')
return x,y
##### Main of test #####
#### First you initialize the object by giving it a name you will use. Here I am going to call it "ird"
r_inj=reach_inj()