import struct import os, select import drive_piezo import analog_output home = os.getenv('HOME') sys.path.append(home + "/src/lib/python/") from scexao_shm import shm plt.ion() dev = "/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_AH01JW35-if00-port0" Piezo_volt = drive_piezo.PIEZO(dev) # connecting to Piezo actuators shm_volt = shm("/tmp/ppiezo.im.shm") # create shared memory file for Piezo fd = os.open("/tmp/ppiezo.im.shm", os.O_RDWR) # reading Piezo shared memory buf = mmap.mmap(fd, 0, mmap.MAP_SHARED) delay = 0.004 # Reading and writing Piezo actuators #----------------------------------------- def read_piezo(): x = aoutput.read_piezox() y = aoutput.read_piezoy()
def ident_model(x, fsamp, maxpeaks, sharp_threshold, vibrange, freq_ex, novib, condition, display, mk, it2): # ident_model - turbulence and vibration identification procedure. # PURPOSE: # This function computes and returns models for turbulence and vibration # peaks made of one AR2 + measurement noise for turbulence, and a sum of n # AR2 signals for vibrations # INPUTS: # x: Time sequence to analyse. # fsamp: sampling frequency # maxpeaks: maximum number of identified vibrations # sharp_threshold: minimum sharpness of the vibrations # vibrange: frequency range for the vibration identification # freq_ex: Frequency ranges to exclude from the identification # novib: boolean telling if there are no vibrations to identify # condition: boolean to constrain a1 and a2 to a1+a2=1 # display: boolean to display plots along the estimation process. # ifig: figure number for the display # OUTPUTS: # model: identified vibration model. Structure with the following # fields: # nvib: number of identified sharp components. # aivib: array containing the a1 and a2 components for each # identified sharp component. # cvvib: array containing the sigma for each identified # sharp component. # vibrations: Structure made of the the following fields: # fv: central frequency of the identified # component. # k: dampening coefficient of the identified # component. # sigma2vib: energy of the identified component. # npoints: number of points of the time sequence # fsamp: sampling frequency. # modelturb: identified turbulence model # noise_level: identified noise level npoints = len(x) #%%%%%%%%%% A. Turbulence+noise identification %%%%%%%%%% #%%%%%%%%%% 1. time sequence study %%%%%%%%%% x -= np.mean(x) window = np.hanning(npoints) window /= np.mean(window) #x *= window fftx = nfft.fft(x)/npoints res = calc_psd(x) psdx = res.psd tabfreq = make_ramp(0, fsamp/2, npoints//2) xr = np.array([fsamp/npoints, fsamp/2]) concplot = np.zeros((9,npoints//2)) # noise level: average value of psdx for frequencies between vibrange(3) # and fsamp/2 indnoise = np.where(tabfreq >= vibrange[2]) noise_level = np.mean(psdx[indnoise]) # AR100 fit of x print 'starting ar20 fit' arcoef_x, mse_x = ts_to_ar(x, 20) # corresponding PSD res = arcoeff_to_psd(-arcoef_x, mse_x, npoints, fsamp, 0, 1) est_psd_x = res.psd #%%%%%%%%%% 2. Vibrating peaks clipping %%%%%%%%%% # indices of tabfreq corresponding to medium frequencies, ie between # vibrange(1) and vibrange (2) indvib = np.where((tabfreq >= vibrange[0]) & (tabfreq <= vibrange[1])) rangevib = np.array([np.min(indvib), np.max(indvib)]) val1 = est_psd_x[rangevib[0]] val2 = est_psd_x[rangevib[1]] # slope in log scale a = np.log(val2/val1)/m.log(rangevib[1]/rangevib[0]) # offset b = np.log(val2)-a*m.log(rangevib[1]) # linear (in log log) spectrum model in the central zone prolong = np.exp(b)*indvib**a spectrum_lin = cp.deepcopy(psdx) spectrum_lin[indvib] = np.abs(prolong+noise_level-val2) spectrum_lin[indnoise] = noise_level est_psd_lin = np.concatenate((spectrum_lin, spectrum_lin[::-1])) # est_psd_lin is the linear gauge spectrum, We consider that the part of # psdx higher than 2*est_psd_lin correspond to vibrations so we clip it. # The clipping is performed on fftx instead of its squared modulus: absfft_novib = np.minimum(np.abs(fftx), np.sqrt(4*est_psd_lin)) absfft_novib = absfft_novib-m.sqrt(noise_level) # the phaser is: fftx_phaser = fftx/abs(fftx) # we gather the two: fft_novib = fftx_phaser*absfft_novib # the corresponding time sequence is obtained by: serie_novib = nfft.ifft(fft_novib)*npoints serie_novib = serie_novib[1:npoints-1] #%%%%%%%%%% 3. AR20 fit on the clipped time sequence %%%%%%%%%% arcoeff_novib, mse_novib = ts_to_ar(serie_novib, 20) # corresponding PSD res = arcoeff_to_psd(-arcoeff_novib, mse_novib, npoints, fsamp, 0, 1) est_psd_novib = res.psd #%%%%%%%%%% 4. Fitting an AR2+noise to this AR20+noise %%%%%%%%%% print 'starting arn_to_ar2' modelturb = arn_to_ar2(arcoeff_novib, mse_novib, noise_level, npoints, fsamp, vibrange[2], condition) print 'Turbulence model: AR coefficients and noise level' print modelturb.aiturb print noise_level #%%%%%%%%%% B. Vibration identification %%%%%%%%%% if novib == 0: # PSD corresponding to modelturb+noise res = arcoeff_to_psd(-modelturb.aiturb, modelturb.cvturb, npoints, fsamp) psdfit = res.psd+noise_level psdsim = psdfit[:] # residual psdres = abs(psdx-psdfit) data = Datapsd(psdres, psdx, psdfit, npoints, fsamp) # initialization indw = indvib[:] ctabfreq = tabfreq[:] cdata = cp.deepcopy(data) #if display == 1: # plt.ion() # plt.figure() # plt.loglog(tabfreq[1:], cdata.psdtot[1:], label='Data') # plt.plot(tabfreq[1:], est_psd_x[1:npoints//2], label='AR100') # plt.plot(tabfreq[1:], est_psd_lin[1:npoints//2], label='lin') # plt.plot(tabfreq[1:], (np.abs(fft_novib[1:npoints//2]))**2, label = 'novib') # plt.plot(tabfreq[1:], est_psd_novib[1:npoints//2], label='AR20') # plt.plot(tabfreq[1:], psdfit[1:npoints//2], label='AR2') # #axis([xr, 1, 2], 'auto y') # plt.xlabel('frequency [Hz]') # plt.ylabel('PSD [um^2/Hz]') i = 0 docontinue = 1 countsharp = 0 n_ex = len(freq_ex) # estimation loop while docontinue == 1: cest = find_vibs(cdata, ctabfreq, indw) if abs(sum(abs(cdata.psdres)/abs(psdsim)/npoints*2)-1) <= 1e-6: docontinue = 0 print 'Model error:' print sum(cest.vib_psd/psdfit) else: if countsharp == maxpeaks: docontinue = 0 #'itmax' else: if i == 0: tab_est = cp.deepcopy(cest) else: print tab_est.vib_fv.shape print cest.vib_fv.shape tab_est.vib_fv = np.concatenate((tab_est.vib_fv, cest.vib_fv)) tab_est.vib_k = np.concatenate((tab_est.vib_k, cest.vib_k)) tab_est.vib_sigma2 = np.concatenate((tab_est.vib_sigma2, cest.vib_sigma2)) tab_est.vib_np = np.concatenate((tab_est.vib_np, cest.vib_np)) tab_est.vib_fsamp = np.concatenate((tab_est.vib_fsamp, cest.vib_fsamp)) if len(tab_est.vib_psd.shape) == 1: tab_est.vib_psd = tab_est.vib_psd.reshape((npoints//2,1)) tab_est.vib_psd = np.concatenate((tab_est.vib_psd, cest.vib_psd.reshape((npoints//2,1))), axis=1) if n_ex > 0: indfreq = np.where((tab_est.vib_fv < freq_ex[0]) | (tab_est.vib_fv > freq_ex[n_ex-1])) countfreq = len(indfreq) if n_ex >= 4: for i in range(n_ex/2-1): indfreqtemp = np.where((tab_est.vib_fv > freq_ex[2*i+1]) & (tab_est.vib_fv < freq_ex[2*i+2])) counttemp = len(indfreqtemp) if countfreq == 0: if counttemp == 0: indfreq = -1 else: indfreq = indfreqtemp[:] else: if counttemp != 0: indfreq = np.concactenate((indfreq, indfreqtemp)) countfreq += counttemp if countfreq == 0: indsmooth = -1 count = 0 indsharp = -1 countsharp = 0 else: indsmooth = np.where(tab_est.vib_k >= sharp_threshold) count = len(indsmooth) indsharptemp = np.where(tab_est.vib_k[indfreq] < sharp_threshold) countsharp = len(indsharptemp) indsharp = indfreq[indsharptemp] else: indsmooth = np.where(tab_est.vib_k >= sharp_threshold) count = len(indsmooth) indsharp = np.squeeze(np.where(tab_est.vib_k < sharp_threshold)) countsharp = np.size(indsharp) if display == 1: if i == 0: #plt.ion() #fig = plt.figure(1) #graph = fig.add_subplot(211+mk) #graph.clear() #graph.loglog(tabfreq[1:], cdata.psdtot[1:], label='Data') #if mk: # plt.xlabel('Frequency [Hz]') #plt.ylabel('PSD [mas^2/Hz]') if countsharp >= 1: psdsim = psdfit+tab_est.vib_psd #plotsim, = plt.plot(tabfreq, psdsim, color='r', label='Model w/ turbulence and vibrations') #graph.plot(tabfreq, psdfit, color='c', label = 'Model w/ turbulence') #plt.legend(loc=3) else: if countsharp == 1: psdsim = psdfit+tab_est.vib_psd[:, indsharp] #plotsim, = graph.plot(tabfreq, psdsim, color='r', label='Model w/ turbulence and vibrations') elif countsharp > 1: psdsim = psdfit+np.sum(tab_est.vib_psd[:, indsharp], axis=1) #plotsim.set_ydata(psdsim) #plt.draw() #if mk == 1: #plt.savefig("./Figures/identmodelPSD_"+str(it2)+".eps", clobber=True) if i ==0: if not os.path.isfile("/tmp/LQG_identplot.im.shm"): os.system("creashmim LQG_identplot %d %d" % (npoints//2,9)) concplotshm = shm("/tmp/LQG_identplot.im.shm", verbose = False) concplot = concplotshm.get_data() concplot[0,:] = tabfreq concplot[4*mk+1:4*mk+5,:] = np.vstack((cdata.psdtot, est_psd_novib[0:npoints//2], psdfit, psdsim)) concplotshm.set_data(concplot.astype(np.float32)) cdata = Datapsd(abs(cdata.psdres-cest.vib_psd), cdata.psdtot, abs(cdata.psdfit+cest.vib_psd), npoints, fsamp) print 'Estimated residual and vib. parameters (f, k):' print [sum(psdx/psdsim*noise_level), cest.vib_fv[0], cest.vib_k[0]] i += 1 # Output computation #if count > 0: #'smooth components:' #temp = struct2cell(tab_est_vib); #size(temp) #temp(indsmooth, :) if countsharp > 0: # 'sharp components:' vib_ai = np.zeros([countsharp, 2]) vib_sigma2 = tab_est.vib_sigma2[indsharp] vib_fv = tab_est.vib_fv[indsharp] vib_k = tab_est.vib_k[indsharp] print 'vib. frequencies:' print vib_fv print 'vib. damping coefficient:' print vib_k print 'vib. variance:' print vib_sigma2 if countsharp == 1: vib_ai[0, :] = kfs_to_ar(tab_est.vib_k[indsharp], tab_est.vib_fv[indsharp], tab_est.vib_fsamp[indsharp]) else: for j in range(countsharp): #tab_est_vib(indsharp(j)) vib_ai[j, :] = kfs_to_ar(tab_est.vib_k[indsharp[j]], tab_est.vib_fv[indsharp[j]], tab_est.vib_fsamp[indsharp[j]]) nvib = countsharp else: nvib = 0 vib_ai = 0 vib_sigma2 = 0 vib_fv = 0 vib_k = 0 aiturb = modelturb.aiturb cvturb = modelturb.cvturb kf = modelturb.kf return Returnmodel(aiturb, cvturb, kf, nvib, vib_ai, vib_sigma2, vib_fv, vib_k, psdsim, noise_level)
import numpy as np from astropy.io import fits as pf from PIL import Image import time import os import sys home = os.getenv('HOME') sys.path.append(home + '/src/lib/python/') from scexao_shm import shm cam = shm("/tmp/pbimage.im.shm") ndark = 1000 while (True): temp = np.squeeze(cam.get_data( True, True, timeout=1.).astype(float)) #dimensions 1,y,x darkcube = np.zeros(np.append(ndark, np.shape(temp))) for idark in range(ndark): darkcube[idark, :, :] = np.squeeze( cam.get_data(True, True, timeout=1.).astype(float)) dark = np.median(darkcube, axis=0) newXImSize = np.shape(dark)[1] newYImSize = np.shape(dark)[0] fname = home+"/pizzabox/SCExAO/pbserver.main/saphcamdarks/"+\ time.strftime("%Y%m%d%H%M%S")+'_'+str(newXImSize)+'_'+str(newYImSize)+'.fits' pf.writeto(fname, dark, clobber=True) print "Wrote", fname time.sleep(600)
from scexao_shm import shm delay=0.5 relative=False aoname="/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_AH01JW35-if00-port0" pygame.init() TIMER_EVENT = pygame.USEREVENT+1 pygame.time.set_timer(TIMER_EVENT, 10) timer_count = 0 MAX_TIMER_COUNT = 1000 time_step=np.zeros((1000,1)) shm_NominalVolt = shm("/tmp/pyrTT.im.shm") # create shared memory file for Piezo def read_NominalVolts(): x0 = shm_NominalVolt.get_data()[0,0] y0 = shm_NominalVolt.get_data()[0,1] #x0 = -5.2 #y0 = -5.7 return (x0, y0) def on_timer_event(): global last_time global timer_count new_time = time.time() [x0,y0] = read_NominalVolts()
from pyqtgraph.Qt import QtCore, QtGui import numpy as np import pyqtgraph as pg import pyqtgraph.ptime as ptime import time import os,sys home = os.getenv('HOME') sys.path.append(home+'/src/lib/python/') from scexao_shm import shm args = sys.argv[1:] if args == []: print "no shared memory provided" else: imshm = shm("/tmp/"+args[0]+".im.shm") # ------------------------------------------------------------------ # another short hand to convert numpy array into image for display # ------------------------------------------------------------------ def arr2im(arr, vmin=0., vmax=10000.0, pwr=1.0): arr2 = arr.astype('float')**pwr #mmin,mmax = arr2.min(), arr2.max() #mmax = np.percentile(arr2, 99) #arr2 -= mmin #arr2 /= (mmax-mmin) #test = mycmap(arr2) return(arr2)
print("==========\n") print("Key a: Change amplitude") print("Key t: Change integration time") print("Key n: Change number of points") print("Key q: Turn off the DM circle and put channel 7 to zero") def shutdown(thread): thread.ev_quit.set() # ------------------------------------------------------------------ # access to shared memory structures # ------------------------------------------------------------------ disp7 = shm('/tmp/dmdisp7.im.shm', False) # read channel 7 disp = shm('/tmp/dmdisp.im.shm', False) volt = shm('/tmp/dmvolt.im.shm', False) #--------------Functions that read the shared memory array, modify the array # ---as per user input and writes it back to the shared memory def DM_circ(ampl, tint, nbstep): ''' ---------------------------------------- calculate tip tilt phaseramp DM displacement map: - ampl : amplitude in um - tint : time interval in us - NBstep : set number of points in a circle ---------------------------------------- ''' global phase
from spkl_tools import * from img_tools import * from scexao_shm import shm plt.ion() utcnow = datetime.datetime.utcnow # ------------------------------------------------------------------ # global variables # ------------------------------------------------------------------ # ------------------------------------------------------------------ # access to shared memory structures # ------------------------------------------------------------------ res = shm('/tmp/aol2_DMmode_cmd1.im.shm', False) # read mode residuals com = shm('/tmp/aol2_DMmode_cmd.im.shm', False) # read mode commands class myGUI: # -------------------------------------------------------------- live_plot = False # ------------------------------- def pgquit(self, widget): self.live_plot = False print("The program has ended normally.") mygtk.gui_quit() # -------------------------------