ctrl = controlCorba.controlClient(controlName=prefix + "Control", debug=0) y = raw_input("Do you want to do pixel calibration? y/n") if y == "y": y = raw_input( "Do you want to do dark map calibration? If so, please turn of light sources. y/n" ) if y == "y": n = raw_input("Number of frames to average?") n = int(n) ctrl.set("bgImage", None) ctrl.set("flatField", None) ctrl.set("darkNoise", None) ctrl.set("thresholdType", 0) dark = ctrl.AverageImage(n, whole=1) ctrl.set("darkNoise", dark) FITS.Write(dark, "darkNoise.fits") y = raw_input( "Do you want to do flat field calibration? If so, please illuminate with a flat field. y/n" ) if y == "y": n = raw_input("Number of frames to average?") n = int(n) ctrl.set("bgImage", None) ctrl.set("flatField", None) ctrl.set("thresholdType", 0) ff = ctrl.AverageImage(n, whole=1) ctrl.set("flatField", ff) FITS.Write(ff, "flatField.fits") y = raw_input( "Do you want to do a background image calibration? If so, please turn off light sources and get your background ready. y/n" )
for j in range(nsubx[k]): indx=nsubapsCum[k]+i*nsubx[k]+j n=(subapLocation[indx,1])*npxlx[k] ##use full row. pxlCnt[indx]=n #pxlCnt[-3:]=npxls#not necessary, but means the RTC reads in all of the pixels... so that the display shows whole image #create a reconstruction matrix rmx=numpy.random.normal(0,1.,(nacts,ncents)).astype("f")#FITS.Read("rmxRTC.fits")[1].transpose().astype("f") print("rmx: %s"%str(rmx.shape)) #Parameters passed to the dynamic libraries upon loading. These will vary depending on what library is in use. fname="camfileimg.fits" if not os.path.exists("camfileimg.fits"): img=numpy.random.normal(10,1,(3,npxly[0],npxlx[0])).astype(numpy.int16) FITS.Write(img,fname) while len(fname)%4!=0:#zero pad to it fits into 32bit int array fname+="\0" cameraParams=numpy.fromstring(fname,dtype="i") slopeParams=None mirrorParams=numpy.zeros((5,),"i") mirrorParams[0]=1000#timeout/ms mirrorParams[1]=1#port mirrorParams[2]=1#thread affinity el size mirrorParams[4]=-1#thread affinity mirrorParams[3]=1#thread prioirty #Now populate the control structure - this is what gets used.
tmp[:, ny[i] / 2 - 1:npxly[i]:ny[i], nx[i] / 2 - 1:npxlx[i]:nx[i]] = 100 tmp[:, ny[i] / 2:npxly[i]:ny[i], nx[i] / 2 - 1:npxlx[i]:nx[i]] = 100 tmp[:, ny[i] / 2 - 1:npxly[i]:ny[i], nx[i] / 2:npxlx[i]:nx[i]] = 100 tmp[:, ny[i] / 2:npxly[i]:ny[i], nx[i] / 2:npxlx[i]:nx[i]] = 100 tmp *= fftmp tmp += bgtmp corrImg = correlationPSF[indx:indx + npxlx[i] * npxly[i]] corrImg.shape = npxly[i], npxlx[i] corrImg[ny[i] / 2 - 1:npxly[i]:ny[i], nx[i] / 2 - 1:npxlx[i]:nx[i]] = 1 corrImg[ny[i] / 2:npxly[i]:ny[i], nx[i] / 2 - 1:npxlx[i]:nx[i]] = 1 corrImg[ny[i] / 2 - 1:npxly[i]:ny[i], nx[i] / 2:npxlx[i]:nx[i]] = 1 corrImg[ny[i] / 2:npxly[i]:ny[i], nx[i] / 2:npxlx[i]:nx[i]] = 1 indx += npxlx[i] * npxly[i] FITS.Write(camimg, "camImage.fits") #file used when reading from file, subapLocation = numpy.zeros((nsubaps, 6), "i") nsubaps = nsuby * nsubx #cumulative subap nsubapsCum = numpy.zeros((ncam + 1, ), numpy.int32) ncentsCum = numpy.zeros((ncam + 1, ), numpy.int32) for i in range(ncam): nsubapsCum[i + 1] = nsubapsCum[i] + nsubaps[i] ncentsCum[ i + 1] = ncentsCum[i] + subapFlag[nsubapsCum[i]:nsubapsCum[i + 1]].sum() * 2 kalmanPhaseSize = nacts #assume single layer turbulence... HinfT = numpy.random.random((ncents, kalmanPhaseSize * 3)).astype("f") - 0.5 kalmanHinfDM = numpy.random.random( (kalmanPhaseSize * 3, kalmanPhaseSize)).astype("f") - 0.5 Atur = numpy.random.random(
import sys import numpy import darc import FITS rcond=float(sys.argv[1]) pmx=FITS.Read("pmx.fits")[1]#This contains high order DM and TT. rmx=-numpy.linalg.pinv(pmx,rcond).T#separating out the TT from rest would be better - but I'm too lazy... FITS.Write(rmx,"rmx%g.fits"%rcond) d=darc.Control("main") d.Set("rmx",rmx) print "Saved rmx%g.fits and set in darc"%rcond
import FITS import sys import time file="tmp.fits" if len(sys.argv)>1: file=sys.argv[1] #Create the corba client c=controlCorba.controlClient() def set(name,val,com="",swap=1,check=1): c.obj.Set(controlCorba.sdata(name),controlCorba.encode([val]),controlCorba.sdata(com),swap,check) #time.sleep(0.01) set("fakeCCDImage",FITS.Read("shimage.fits")[1][0]) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file) set("thresholdAlgorithm",2) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file,writeMode="a") set("thresholdAlgorithm",0) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file,writeMode="a") set("thresholdValue",0) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file,writeMode="a") set("thresholdAlgorithm",1) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file,writeMode="a") set("thresholdAlgorithm",2) FITS.Write(controlCorba.decode(c.obj.AverageCentroids(1)),file,writeMode="a")
def save(self, fname): """Save the buffer (so that it can be loaded with loadBuf)""" FITS.Write(self.arr, fname)
def pokeSine(self,nFrames,pokeVal=1000.,dmNo=0,baseFreq=5,nrec=2,fname="sinePoke.fits",fno=-20,order=None,nRepeats=1,repeatIfErr=10): """nFrames - number of iterations over which to poke. baseFreq - minimum number of sine waves to fit within nFrames. nrec - number of cycles to record (for averaging purposes) fno - number of frames to allow for sync purposes. Make this more negative for faster systems (or closer to zero for simulation!). order - if None, will increase the freq of neighbouring actuators in a linear fashion. Otherwise, can be the index order in which this should be done. nRepeats - number of times to repeat the recording, with an offset added to the frequency of each actuator each time (so that different dynamics can be explored). repeatIfErr - number of times to repeat if an error is obtained, before giving up. If -ve, will repeat indefinitely Use processSine() function below to process this data... """ if order is not None: raise Exception("order not yet implemented - sorry!") d=darc.Control(self.prefix) nslopes=d.Get("subapFlag").sum()*2 nacts=d.Get("nacts")#self.nactList[dmNo] actOrig=d.Get("actuators") FITS.Write(actOrig,"tmpActOrig.fits") print("Writing original actuators to tmpActOrig.fits") pokeArr=numpy.zeros((nFrames,nacts),numpy.float32) nactDm=self.nactList[dmNo] offset=sum(self.nactList[:dmNo]) writeMode="w" freqOffset=0. dataList=[] errList=[] extraHeader=["POKEVAL = %d"%pokeVal,"NFRAMES = %d"%nFrames,"DMNUMBER= %d"%dmNo,"BASEFREQ= %d"%baseFreq,"NRECORD = %d"%nrec] for rpt in range(nRepeats): err=0 pokeArr[:]=actOrig for i in range(nactDm): freq=baseFreq+(freqOffset+i)%nactDm pokeArr[:,offset+i]+=numpy.sin(numpy.arange(nFrames)/float(nFrames)*2.*numpy.pi*freq)*pokeVal d.Set("actuators",pokeArr) time.sleep(1.) takeData=repeatIfErr if takeData==0: takeData=1 while takeData: err=0 data=d.GetStreamBlock(["rtcActuatorBuf","rtcCentBuf"],nFrames*nrec,asArray=1,fno=fno) #check the data is okay. for key in ["rtcCentBuf","rtcActuatorBuf"]: f=data[key][2] if not numpy.alltrue((f[1:]-f[:-1])==1): print "Cycle %d: Some frames missing from %s"%(rpt,key) err=1 if not numpy.alltrue(data["rtcCentBuf"][2]==data["rtcActuatorBuf"][2]): allframenumbersequal=0 print "Cycle %d: actuator and slope frame numbers don't agree"%rpt err=1 allframetimesequal=1 for key in ["rtcCentBuf","rtcActuatorBuf"]: ftime=data[key][1] fdiff=ftime[1:]-ftime[:-1] if not numpy.alltrue(fdiff<=numpy.median(fdiff)*3): allframetimesequal=0 err=1 print "Cycle %d: Not all frame times within 3x median frame time"%rpt if err==0:#got data okay takeData=0 elif takeData>1: print "Error in data - repeating acquisition (another %d times to try)"%takeData takeData-=1 elif takeData==1: takeData=0 if repeatIfErr==0: print "Error in data - continuing anyway" else: print "Error in data - cannot acquire (is your network fast enough? Is the frame rate too high?)" else: print "Error in data - repeating acquisition (will continue until successful...!)" if repeatIfErr!=0 and err!=0: raise Exception("Unable to capture data") #subtract the actuator offset (midrange) data["rtcActuatorBuf"][0]=data["rtcActuatorBuf"][0]-actOrig dataList.append(data) if fname is not None: FITS.Write(data["rtcCentBuf"][0],fname,writeMode=writeMode,extraHeader=extraHeader) writeMode="a" extraHeader=None FITS.Write(data["rtcCentBuf"][1],fname,writeMode="a")#times FITS.Write(data["rtcCentBuf"][2],fname,writeMode="a")#frameno FITS.Write(data["rtcActuatorBuf"][0],fname,writeMode="a") FITS.Write(data["rtcActuatorBuf"][1],fname,writeMode="a") FITS.Write(data["rtcActuatorBuf"][2],fname,writeMode="a") errList.append(err) freqOffset+=nactDm//nRepeats d.Set("actuators",actOrig) return dataList,errList
import sys import numpy import darc import FITS nfr = 10 if len(sys.argv) > 1: nfr = int(sys.argv[1]) print "Have you set into calibration mode?" d = darc.Control("main") d.Set("refCentroids", None) refslopes = d.SumData("rtcCentBuf", nfr)[0] / nfr d.Set("refCentroids", refslopes) FITS.Write(refslopes, "refslopes.fits") print "Saved refslopes.fits and set in darc"
dm.pokeSine(2000, pokeVal=pokeVal, nrec=2, dmNo=1, fname=fname, fno=-300, nRepeats=2, repeatIfErr=repeatIfErr) return fname, dm if __name__ == "__main__": rcond = 0.1 thresh = 0.25 if len(sys.argv) > 1: rcond = float(sys.argv[1]) if len(sys.argv) > 2: #1 for simulation, 1000 for bench. amp = float(sys.argv[2]) if len(sys.argv) > 3: #0 for simulation, 0.25 for bench thresh = float(sys.argv[3]) fname, dm = doSinePokeGTC(pokeVal=amp) #dm=calibrate.DMInteraction([373,2],"") # fname="pokeSineBench180705_121816.fits" # fname="pokeSineBench180705_160328.fits" rmx, pmxList, rmxList = dm.processSine(fname, rcond=rcond, stdThresh=thresh) rname = "rmx_%f_%s" % (rcond, fname) FITS.Write(rmx, rname) print "Written %s" % rname
if rmx.shape[1] != gainmx.shape[0]: transpose = 1 rmx = rmx.T gainmx = numpy.dot(rmx, gainmx) if transpose: gainmx = gainmx.T return gainmx if __name__ == "__main__": import sys import FITS if len(sys.argv) < 5: print( "Usage: %s globalGain [modal,gain,list] output.fits slopeToZernMx.fits optionalRmx" % sys.argv[0]) sys.exit(0) gain = sys.argv[1] modalGainList = eval(sys.argv[2]) outMx = sys.argv[3] slopeToZernMx = FITS.Read(sys.argv[4])[1] if slopeToZernMx[0].std() == 0: #first row all zeros - probably piston print("Stripping piston from %s" % sys.argv[4]) slopeToZernMx = slopeToZernMx[1:] rmx = None if len(sys.argv) > 5: rmx = FITS.Read(sys.argv[5])[1] gmx = computeModalGainMx(gain, modalGainList, slopeToZernMx, rmx) FITS.Write(gmx, outMx)
pokeval = 10. if len(sys.argv) > 2: pokeval = float(sys.argv[2]) print "Have you set into calibration mode and taken reference slopes?" d = darc.Control("main") rmx = d.Get("rmx") nacts, nslopes = rmx.shape pmx = numpy.zeros(rmx.shape, numpy.float32) d.Set("addActuators", 0) actuators = numpy.zeros((nacts, ), numpy.float32) actuators[:2] = 32768 #the tip-tilt mirror. for i in range(nacts): print "Poking %d" % i actuators[i] = pokeval if i < 2: actuators[i] += 32768 d.Set("actuators", actuators) time.sleep(1.5) sl = d.SumData("rtcCentBuf", nfr)[0] / nfr / pokeval pmx[i] = sl actuators[i] = 0 if i < 2: actuators[i] = 32768 d.Set("actuators", actuators) FITS.Write(pmx, "pmx.fits") rmx = -numpy.linalg.pinv(pmx, 0.1).T FITS.Write(rmx, "rmx.fits") d.Set("rmx", rmx) print "Saved pmx.fits, rmx.fits and set rmx into darc"
def tofits(self, fname, ffrom=None, fto=None, tfrom=None, tto=None): curshape = None curdtype = None fheader = None nentries = 0 tlist = [] flist = [] ffits = open(fname, "w") firstHeader = 1 while 1: hdr = self.fd.read(self.info.size * self.info.itemsize) if hdr == "": break elif len(hdr) < self.info.size * self.info.itemsize: print "Didn't read all of header" break info = numpy.fromstring(hdr, numpy.int32) fno = int(info[1]) ftime = float(info[2:4].view("d")) databytes = info[0] - (self.info.size - 1) * self.info.itemsize fok = tok = 0 if (ffrom == None or fno >= ffrom) and (fto == None or fno <= fto): #print fno fok = 1 if (tfrom == None or ftime >= tfrom) and (tto == None or ftime <= tto): tok = 1 if fok == 1 and tok == 1: frame = self.fd.read(databytes) if len(frame) != databytes: print "Didn't read all of frame" break frame = numpy.fromstring(frame, chr(info[4])) #can it be put into the existing HDU? If not, finalise current, and start a new one. if curshape != databytes or curdtype != chr(info[4]): #end the current HDU FITS.End(ffits) #Update FITS header if fheader != None: FITS.updateLastAxis(None, nentries, fheader) del (fheader) #fheader.close() fheader = None #now write the frame number and time. ffits.close() if firstHeader == 0: FITS.Write(numpy.array(flist).astype("i"), fname, writeMode="a", doByteSwap=self.doByteSwap) FITS.Write(numpy.array(tlist), fname, writeMode="a", doByteSwap=self.doByteSwap) ffits = open(fname, "a+") FITS.WriteHeader(ffits, [ 1, databytes / numpy.zeros( (1, ), chr(info[4])).itemsize ], chr(info[4]), firstHeader=firstHeader, doByteSwap=self.doByteSwap) ffits.flush() firstHeader = 0 fheader = numpy.memmap(fname, dtype="c", mode="r+", offset=ffits.tell() - 2880) flist = [] tlist = [] nentries = 0 curshape = databytes curdtype = chr(info[4]) #now write the data if self.doByteSwap and numpy.little_endian: ffits.write(frame.byteswap().data) else: ffits.write(frame) flist.append(fno) tlist.append(ftime) nentries += 1 else: #skip the data self.fd.seek(databytes - 1, 1) if self.rd.read(1) == "": print "Didn't read all of the frame" break #now finalise the file. FITS.End(ffits) if fheader is not None: FITS.updateLastAxis(None, nentries, fheader) #fheader.close() del (fheader) fheader = None #now write the frame number and time. ffits.close() FITS.Write(numpy.array(flist).astype("i"), fname, writeMode="a", doByteSwap=self.doByteSwap) FITS.Write(numpy.array(tlist), fname, writeMode="a", doByteSwap=self.doByteSwap)
#darc, the Durham Adaptive optics Real-time Controller. #Copyright (C) 2010 Alastair Basden. #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU Affero General Public License as #published by the Free Software Foundation, either version 3 of the #License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU Affero General Public License for more details. #You should have received a copy of the GNU Affero General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. import controlCorba import FITS #Create the corba client c=controlCorba.controlClient() def set(name,val,com="",swap=1,check=1): c.obj.Set(controlCorba.sdata(name),controlCorba.encode([val]),controlCorba.sdata(com),swap,check) #Acquire a calibrated image, averaged over 10 frames data=c.obj.AverageImage(10,0) #Decode and reshape the return data=controlCorba.decode(data) data.shape=128,128 FITS.Write(data,"tmp.fits")