def saveSRSData(self, energy, pol, fileList): srsHeader=[" &SRS\n", " SRSRUN=null,SRSDAT=null,SRSTIM=null,\n", " SRSSTN='null',SRSPRJ='null ',SRSEXP='null ',\n", " SRSTLE=' ',\n", " SRSCN1=' ',SRSCN2=' ',SRSCN3=' ',\n", " &END\n"]; try: runs=NumTracker("tmp") currentNum = runs.getCurrentFileNumber() #currentNum = runs.incrementNumber() path = InterfaceProvider.getPathConstructor().createFromProperty("gda.data.scan.datawriter.datadir") fileName = path + "/" + str(currentNum) + ".dat" # print fileName fh=open(fileName, 'w'); #SRS Header for i in range(len(srsHeader)): fh.write(srsHeader[i]); titleLine='%(v1)s \t %(v2)s \t %(v3)s \n' %{'v1': self.energyDevice.getName(), 'v2': self.polarisationDevice.getName(), 'v3': self.detector.getName()}; fh.write(titleLine); nf=len(fileList); for n in range(nf): #print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i]; newLine='%(v1).8f \t %(v2)s \t %(v3)s \n' %{'v1': energy[n], 'v2': pol[n], 'v3': fileList[n]}; fh.write(newLine); fh.close(); print "Scan complete. File saved in " + fileName; except: print "ERROR: Could not save data into file."
def __init__(self, filespec=None, dir=None): self.format = LocalProperties.get( "gda.data.scan.datawriter.dataFormat") if dir != None and dir != "None": self.dir = dir else: self.dir = PathConstructor.createFromDefaultProperty() self.beamline = GDAMetadataProvider.getInstance().getMetadataValue( "instrument", LocalProperties.GDA_INSTRUMENT, "tmp") if (self.format == "NexusDataWriter"): #really should use scanFileName prefix rather than forcing to beamline- self.prefix = LocalProperties.get("gda.data.filePrefix", self.beamline + "-") self.ext = "nxs" if filespec == None: filespec = "%d" % NumTracker(self.beamline).currentFileNumber else: self.prefix = "" self.ext = "dat" if filespec == None: filespec = "%d" % NumTracker().currentFileNumber filespec = filespec.__str__() self.filename = self.tryFiles([ filespec, self.dir + "/" + filespec, self.prefix + filespec + "." + self.ext, self.dir + "/" + self.prefix + filespec + "." + self.ext, self.dir + "/" + filespec + "." + self.ext ]) if (self.filename == None): raise Exception("no file found for %s" % filespec)
def __init__(self, name, panelName, detector): self.setName(name); self.setInputNames([name]); self.setExtraNames([]); # self.Units=[strUnit]; self.setLevel(7); self.panel = panelName; self.detector = detector; self.scanNumberTracker = NumTracker("tmp"); self.fileName=None; self.data = ScanFileHolder() self.exposureTime = 0 self.logScale = False; self.alive=True; # To setup the image folder according to I06 requirement self.scanImageDirectory(); self.fastMode=False; self.protection=True; # self.protectCamera(); self.verbose = False
def lastscan(extension="tmp"): nt = NumTracker(extension) lastSRSFileName = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + File.separator + str( nt.getCurrentFileNumber()) + ".dat" del nt return lastSRSFileName
def saveSRSData(self, numberOfPoints): srsHeader = [ " &SRS\n", " SRSRUN=null,SRSDAT=null,SRSTIM=null,\n", " SRSSTN='null',SRSPRJ='null ',SRSEXP='null ',\n", " SRSTLE=' ',\n", " SRSCN1=' ',SRSCN2=' ',SRSCN3=' ',\n", " &END\n" ] try: runs = NumTracker("tmp") nextNum = runs.getCurrentFileNumber() #nextNum = runs.incrementNumber() path = InterfaceProvider.getPathConstructor().createFromProperty( "gda.data.scan.datawriter.datadir") fileName = path + "/" + str(nextNum + 1) + ".dat" print fileName fh = open(fileName, 'w') #SRS Header for i in range(len(srsHeader)): fh.write(srsHeader[i]) titleLine = '%(v1)s \t %(v2)s \t %(v3)s \t %(v4)s \t %(v5)s \t %(v6)s \n' % { 'v1': 'PGM Energy', 'v2': 'ID GAP Energy', 'v3': 'Channel 1', 'v4': 'Channel 2', 'v5': 'Channel 3', 'v6': 'Channel 4' } fh.write(titleLine) arrayEnergyPGM = self.energyPGM.cagetArrayDouble() arrayEnergyIDGAP = self.energyIDGAP.cagetArrayDouble() arrayChannel01 = self.channel01.cagetArrayDouble() arrayChannel02 = self.channel02.cagetArrayDouble() arrayChannel03 = self.channel03.cagetArrayDouble() arrayChannel04 = self.channel04.cagetArrayDouble() for i in range(numberOfPoints): if arrayEnergyPGM[i] < self.se: continue if arrayEnergyPGM[i] > self.ee: continue #print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i]; newLine = '%(v1).8f \t %(v2).8f \t %(v3).8f \t %(v4).8f \t %(v5).8f \t %(v6).8f \n' % { 'v1': arrayEnergyPGM[i], 'v2': arrayEnergyIDGAP[i], 'v3': arrayChannel01[i], 'v4': arrayChannel02[i], 'v5': arrayChannel03[i], 'v6': arrayChannel04[i] } fh.write(newLine) fh.close() runs.incrementNumber() except: print "ERROR: Could not save data into file."
def __init__(self, name, datasetProcessor, scanClass, *args): self.name = name self.inputNames = [] self.extraNames = ['scan'] + list(datasetProcessor.labelList) self.outputFormat = ['%i']+['%f']*len(datasetProcessor.labelList) self.datasetProcessorName = datasetProcessor.name self.scan = scanClass([ScanDataProcessor([datasetProcessor])]) self.numTracker = NumTracker('scanbase_numtrack') self.args = tuple(args)
def prepare(self, trackerName='xmd', pathPrefix='xmd_'): #To setup the new directory for images self.detector.scanImageDirectory(); #To create a new xmcd folder based on xmcd run number #get current scan number nt = NumTracker(trackerName); r=nt.getCurrentFileNumber(); subDir=pathPrefix + str(r); targetDir = self.createPrecessingDir(subDir); #increase the scan number for next run nt.incrementNumber(); return targetDir;
def getSrsFileName(self, scanNumber=None, srsPath=None): if scanNumber is None: nt = NumTracker("tmp") sn = nt.getCurrentFileNumber() else: sn = scanNumber if srsPath is None: srsPath = InterfaceProvider.getPathConstructor( ).createFromProperty("gda.data.scan.datawriter.datadir") srsFileName = srsPath + File.separator + str(sn) + ".dat" # print "srs file name is: " + srsFileName; return srsFileName
def setNewImagePath(self): """Set file path and name based on current scan run number""" next_num = NumTracker("tmp").getCurrentFileNumber() base_path = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + File.separator sub_dir = "%d_%s" % (next_num, self.pathPostfix) new_image_path = os.path.join(base_path, sub_dir) if not os.path.exists(new_image_path): #print("Path does not exist. Create new one.") os.makedirs(new_image_path) self.resetImageNumber() if not os.path.isdir(new_image_path): print("Invalid path") return self.filePath = new_image_path #print("Image file path set to " + self.filePath) nd_file = self.detector.getNdFile() nd_file.setFilePath(self.filePath) nd_file.setFileName(self.filePrefix) nd_file.setFileTemplate(self.fileFormat) nd_file.setAutoIncrement(True) nd_file.setAutoSave(True) nd_file.setFileFormat(0) #Magic file format depending on the file extension return self.filePath
def __init__(self, name, xAxisName, yAxisName, extraAxisNameList=[], metaAxisNameList=[]): self.setName(name) self.setInputNames(["scanNumber"]) self.srsPath = None self.xAxis = xAxisName self.yAxis = yAxisName self.extraAxis = extraAxisNameList self.metaAxis = metaAxisNameList self.setNewOutputFormat() # self.dataHolder=ScanFileHolder(); self.dataHolder = None self.index = long(NumTracker("tmp").getCurrentFileNumber()) self.yMax = None self.pos = None self.xVal = None self.centroid = None self.extraValues = []
def postCapture(self): if not self.save: return; runs=NumTracker(self.name); nextNum = NumTracker(self.name).getCurrentFileNumber() + 1; self.fileName = os.path.join(self.filePath, self.filePrefix+str(nextNum)+".png"); # print "New File name is: ----------->" + self.fileName; #My Own PNG file writer # self.saveImageFile(self.fileName); #PNG file writer from GDA Analysis package self.data.save(PNGSaver(self.fileName)); runs.incrementNumber();
def __init__(self, detectorList=None): # EXAFS PANEL CODE self.scannableNamesVector = Vector() self.scannableNamesVector.add("dcm_mono") self.detectorNamesVector = Vector() self.detectorNamesVector.add("counterTimer01") self.detectorNamesVector.add("counterTimer02") self.controller = Finder.find("ExafsController") self.mcontroller = Finder.find("MicroFocusController") self.title = "TITLE" self.condition1 = "CONDITION1" self.condition2 = "CONDITION2" self.condition3 = "CONDITION3" # Script code self.das = Finder.find("daserver") self.ionchambers = SlaveCounterTimer() self.converter = Finder.find("auto_mDeg_idGap_mm_converter") self.windowValues = [[0, 4095]] * 9 self.windowName = 'ALL' self.ionchamberData = [] self.mcaList = [] self.scalarList = [] self.runs = NumTracker("tmp") self.runprefix = 'i18exafs' self.runext = '.dat' self.fileno = self.runs.getCurrentFileNumber() + 1 self.runs.incrementNumber() self.datadir = InterfaceProvider.getPathConstructor( ).createFromProperty("gda.data.scan.datawriter.datadir") self.datafilename = self.datadir + '/' + str(self.fileno) + self.runext if (detectorList != None): self.detectorMask = detectorList else: self.detectorMask = [1, 1, 1, 1, 1, 1, 1, 1, 1] self.mcadir = self.datadir + '/mca/' + str(self.fileno) + '/' self.mcarootname = self.mcadir + str(self.fileno) if not os.path.isdir(self.mcadir): os.mkdir(self.mcadir) self.tag = 1 self.facade = JythonServerFacade.getInstance() self.scanList = [] self.noOfRepeats = 1 self.noOfPoints = 0
def writeDataToFile(self, data=[]): filenumber = NumTracker("i10").getCurrentFileNumber(); waveformfilename=str(InterfaceProvider.getPathConstructor().createFromDefaultProperty())+"/"+ str("i10-")+str(filenumber)+"-"+str(self.getName())+"_"+str(self.pointNumber)+".dat" print waveformfilename datafile=open(waveformfilename, 'w') for value in data: datafile.write(str(value)+'\n') datafile.flush() datafile.close() return waveformfilename
def __init__(self, name): self.name = name self.detectorModel = None self.detectorInfo = None self.exposureTime = 0 self.exposurePeriod = 1 self.status = PilatusInfo.DETECTOR_STATUS_STANDBY self.filePath = None self.filePrefix = 'pilatusImage' self.fileFormat = "%s%s%d.tif" self.numImages = 1 self.gain = 0 self.thresholdEnergy = 5000 self.runs = NumTracker(self.filePrefix) self.fileNumber = self.runs.getCurrentFileNumber()
def postCapture(self): if not self.save: return runs = NumTracker(self.name) nextNum = runs.getCurrentFileNumber() + 1 fn = "%s%05d.png" % (self.filePrefix, nextNum) self.fileName = os.path.join(self.filePath, fn) # print "Dubug: Saving file started"; t0 = time() #My Own PNG file writer # self.saveImageFile(self.fileName); #PNG file writer from GDA Analysis package dnp.io.save(self.fileName, self.dataset, autoscale=False) # print "Dubug: Saving file finished within %d seconds" %(time()-t0); runs.incrementNumber()
def setNewImagePath(self): """Set file path and name based on current scan run number""" nextNum = NumTracker("tmp").getCurrentFileNumber() basePath = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + File.separator subDir = "%d_%s" % (nextNum, self.pathPostfix) newImagePath = os.path.join(basePath, subDir) if not os.path.exists(newImagePath): #print "Path does not exist. Create new one." os.makedirs(newImagePath) self.imageNumber = 0 #To reset the image number if not os.path.isdir(newImagePath): print "Invalid path" return self.filePath = newImagePath #print "Image file path set to " + self.filePath; return self.filePath
def writeDataToFile(self, data=[]): path = str(InterfaceProvider.getPathConstructor(). createFromDefaultProperty()) + "/anritsu/" if not os.path.exists(path): os.makedirs(path) filenumber = NumTracker("i10").getCurrentFileNumber() filename = "i10-%06d-%s_%04d.dat" % (filenumber, self.getName(), self.pointNum) print "writing file: " + path + filename datafile = open(path + filename, 'w') data = dnp.array(data, dtype=dnp.float) data = dnp.transpose(data) datafile.write(" &END\n") datafile.write("freq\ts12\ts21\ts11\ts22" '\n') for line in data: s = "".join("%10.5g\t" % x for x in line[0]) datafile.write(s + '\n') datafile.flush() datafile.close() return path + filename
class ScannableScan(PseudoDevice): def __init__(self, name, datasetProcessor, scanClass, *args): self.name = name self.inputNames = [] self.extraNames = ['scan'] + list(datasetProcessor.labelList) self.outputFormat = ['%i']+['%f']*len(datasetProcessor.labelList) self.datasetProcessorName = datasetProcessor.name self.scan = scanClass([ScanDataProcessor([datasetProcessor])]) self.numTracker = NumTracker('scanbase_numtrack') self.args = tuple(args) def asynchronousMoveTo(self): raise Exception("Not supported") def isBusy(self): return False# getPosition is blocking def getPosition(self): if ScannableCommands.isPosCommandIsInTheProcessOfListingAllScannables(): raise Exception(self.name + " is not readout while the pos commands samples all Scannables") scan_result = self.scan(*self.args) try: sdpr = scan_result[self.datasetProcessorName] except TypeError: print "***" print "scan_result:", scan_result print "***" raise result = [int(self.numTracker.getCurrentFileNumber())] for label in self.extraNames[1:]: result.append(sdpr.result[label]) return result
class UViewDetectorClass(DetectorBase): DETECTOR_STATUS_IDLE, DETECTOR_STATUS_BUSY, DETECTOR_STATUS_PAUSED, DETECTOR_STATUS_STANDBY, DETECTOR_STATUS_FAULT, DETECTOR_STATUS_MONITORING = range(6); ImageFileLoaders={ 'TIF' : TIFFImageLoader, 'TIFF': TIFFImageLoader, 'JPG' : JPEGLoader, 'JPEG': JPEGLoader, 'PNG' : PNGLoader }; def __init__(self, name, panelName, detector): self.setName(name); self.setInputNames([name]); self.setExtraNames([]); # self.Units=[strUnit]; self.setLevel(7); self.panel = panelName; self.detector = detector; self.scanNumberTracker = NumTracker("tmp"); self.fileName=None; self.data = ScanFileHolder() self.exposureTime = 0 self.logScale = False; self.alive=True; # To setup the image folder according to I06 requirement self.scanImageDirectory(); self.fastMode=False; self.protection=True; # self.protectCamera(); self.verbose = False #DetectorBase Implementation def getPosition(self): return self.readout(); def asynchronousMoveTo(self,newPos): self.setCollectionTime(newPos); self.collectData(); def getCollectionTime(self): self.exposureTime=self.detector.getCollectionTime(); return self.exposureTime; def setCollectionTime(self, newExpos): self.exposureTime = newExpos; self.detector.setCollectionTime(self.exposureTime); def collectData(self): #self.detector.setCollectionTime(self.exposureTime) self.detector.collectData(); return; def prepareForCollection(self): #To put camera in the "camera mode" self.detector.setCameraInProgress(False); self.detector.prepareForCollection(); def endCollection(self): # self.detector.endCollection(); if self.protection: self.protectCamera(); return; def readout(self): self.fileName = self.detector.readout(); if self.alive: self.display(); return self.fileName; def getStatus(self): return self.detector.getStatus(); def createsOwnFiles(self): return True; def toString(self): self.getPosition(); return "Latest image file: " + self.getFullFileName(); def isBusy(self): return self.detector.getStatus() == Detector.BUSY ## Extra Implementation def setFileFormat(self, fileExt, contents=2): ''' fileExtension: dat: Raw data uncompressed png: PNG compressed tiff: TIFF compressed bmp: BMP uncompressed jpg: JPG compressed tif: TIFF uncompressed imagecontents: 0: RGB 8+8+8 bits x,y,z, as seen on screen 1: RGB 8+8+8 bits,x,y raw, z as seen on screen 2: RAW 16 bits graylevel x, y, z raw data ''' self.detector.setFileFormat(fileExt, contents); def setImageAverage(self, averageParameter): ''' averageParameter: -1: Sliding average. Current does NOT work! 0: No average 1 ~ 99: Number of frames to be averaged ''' self.detector.setImageAverageNumber(averageParameter); def getImageAverage(self): iv=self.detector.getImageAverageNumber(); return iv; def protectCamera(self): #self.detector.setCollectionTime(0.1); self.detector.setCameraInProgress(True); if self.verbose: print "Camera is set to 'Recorder Mode' for protection."; return; def setAlive(self, newAlive=True): self.alive = newAlive; def setLogScale(self, newLogScale=True): self.logScale = newLogScale; def setPanel(self, newPanelName): self.panel = newPanelName; def getDetectorInfo(self): return self.detectorInfo; def singleFastShot(self, newExpos=None): if newExpos is not None: # New exposure time given self.exposureTime = newExpos; self.setCollectionTime(newExpos); return self.detector.shotSingleImage(); def singleShot(self, newExpos=None): """Shot single image with given exposure time"""; #To put camera in the "camera mode" self.detector.setCameraInProgress(False); if self.getStatus() != Detector.IDLE: print 'Camera not available, please try later'; return; if newExpos is not None: # New exposure time given self.exposureTime = newExpos; self.setCollectionTime(self.exposureTime); self.detector.setCameraSequentialMode(True); #self.setNumOfImages(1); self.collectData(); sleep(self.exposureTime); while self.getStatus() != Detector.IDLE: sleep(self.exposureTime/10.0); if self.protection: self.protectCamera(); return self.readout(); def multiShot(self, numberOfImages, newExpos=None, newDir=True): """Shot multiple images with given exposure time"""; #To put camera in the "camera mode" self.detector.setCameraInProgress(False); if self.getStatus() != Detector.IDLE: print 'Camera not available, please try later'; return; if newExpos is not None: # New exposure time given self.exposureTime = newExpos; self.setCollectionTime(self.exposureTime); if newDir: self.newImageDirectory(); self.scanImageDirectory(); else: self.detector.setCameraSequentialMode(True); temp=self.alive; self.alive=False;#To turn off the display if self.fastMode: fn=self.multiFastShot(numberOfImages); else: fn=self.multiSafeShot(numberOfImages); self.alive=temp; #To restoru the display setting if self.protection: self.protectCamera(); return fn; def multiSafeShot(self, numberOfImages): fn=[]; #self.setNumOfImages(numberOfImages); for n in range(numberOfImages): self.collectData(); sleep(self.exposureTime); while self.getStatus() != Detector.IDLE: sleep(self.exposureTime/10.0); fn.append( self.readout() ); return fn; def multiFastShot(self, numberOfImages): fn=[]; #To take the first image self.collectData() sleep(self.exposureTime + 0.15); i=0; while i<numberOfImages-1: self.collectData();#To trigger a new acquisition t0=time.time(); fn.append( self.readout() );#To save the previous picture t1=time.time(); td=t1-t0; if td < self.exposureTime+0.15:#To wait the exposure time, plus a 150ms delay? sleep(self.exposureTime+0.15-td); i+=1; fn.append( self.readout() );#To save the last previous triggered picture return fn; def display(self,file=None): if file==None: file = self.getFullFileName() fileLoader = UViewDetectorClass.ImageFileLoaders[os.path.splitext(file)[-1].split('.')[-1].upper()]; self.data.load( fileLoader(file) ); dataset = self.data.getAxis(0); if self.panel: if self.logScale: RCPPlotter.imagePlot(self.panel, DatasetUtils.lognorm(dataset)); #For RCP GUI else: RCPPlotter.imagePlot(self.panel, dataset); #For RCP GUI else: print "No panel set to display" raise Exception("No panel_name set in %s. Set this or set %s.setAlive(False)" % (self.name,self.name)); def setNumOfImages(self, number): # self.detector.setNumOfImages(number); return; def getNumOfImages(self): return 1 # return self.detector.getNumOfImages(); # To use the directory with scan number to save image, like what scan command does. def scanImageDirectory(self): #increase the scan number for one self.scanNumberTracker.incrementNumber(); self.prepareForCollection(); # To create a new directory following the PEEM image directory rules def newImageDirectory(self, newDir=None): if newDir is not None: self.detector.setImageDir(newDir); self.detector.prepare(); def getFullFileName(self): """Returns file path of the LAST CREATED image""" return self.fileName;
#2. Unbounded way print lang.String.startsWith(myStr, "Z"); #jarrays import jarray x=jarray.zeros(200,"i"); print x; import java.lang.Math y=java.lang.Math.sqrt(256); print y; #=================GDA Track Number (Scan Number)============================================= from gda.data import NumTracker nt = NumTracker("tmp") #get current scan number nt.getCurrentFileNumber() #set new scan number #nt.setFileNumber(2000) del nt #=====================Using EPICS caget() and caput to access PVs ========================================= from gda.epics import CAClient #Create the Client epicsClient = CAClient()
''' Created on 29 Jan 2014 @author: fy65 ''' from time import sleep from gda.configuration.properties import LocalProperties from gda.data import NumTracker scanNumTracker=NumTracker(LocalProperties.get(LocalProperties.GDA_BEAMLINE_NAME)) scanNumTracker.incrementNumber() EXPOSURETIME=120 #seconds TARGETCOUNT=100000 ONEMINUTECOUNT=1000 DELTAMIN=-15.0 DELTAMAX=77.0 scancount=0 Tolerance=0.1 NUMBEROFSCANS=TARGETCOUNT/ONEMINUTECOUNT*60/EXPOSURETIME print "Number of scans to do: %d, total time taken: %f" % (NUMBEROFSCANS, NUMBEROFSCANS*EXPOSURETIME) mythen.configure() # @UndefinedVariable mythen.atScanStart() # @UndefinedVariable mythen.setCollectionTime(EXPOSURETIME+10) # @UndefinedVariable delta.moveTo(DELTAMIN) # @UndefinedVariable delta.setSpeed((DELTAMAX-DELTAMIN)/(EXPOSURETIME)) # @UndefinedVariable target=DELTAMAX for i in range(NUMBEROFSCANS): sleep(5) if scancount % 2==0: target=DELTAMAX else:
Created on 26 Sep 2012 @author: fy65 ''' from gda.device.detector import DetectorBase from gda.device import Detector from gda.epics import CAClient from gov.aps.jca.event import MonitorListener from threading import Timer import scisoftpy as dnp from gda.data import NumTracker from gda.jython import InterfaceProvider import os import array i09NumTracker = NumTracker("i09"); def nextDataFile(): '''query the absolute path of the next working file''' curdir = InterfaceProvider.getPathConstructor().createFromDefaultProperty() filenumber = i09NumTracker.incrementNumber(); return os.path.join(curdir,str(filenumber)+".txt") class StripChart(MonitorListener): ''' plot y dataset against x dataset for a fixed length, new data added push oldest data out in the datasets. ''' def __init__(self, xpv, ypv, controlpv, numberofpointstoplot=1000,save=False): ''' Constructor '''
class PilatusOverSocket(Pilatus, SingleSessionSocketDeviceClass): terminators = '\n\x15\x18' def __init__(self, name): Pilatus.__init__(self, name) self.detectorInfo = 'Pilatus Over Socket' self.setFilePrefix('pilatusImage') serverHost = 'localhost' serverPort = 41234 # super(SockteDeviceClass, self).__init__(self, serverHost, serverPort); SingleSessionSocketDeviceClass.__init__(self, serverHost, serverPort) def turnOn(self): self.status = PilatusInfo.DETECTOR_STATUS_IDLE self.connect() def turnOff(self): self.send("exit ") self.disconnect() def getNumOfImages(self): reply = self.sendAndReply('nimages') # The reply should be something like: '15 OK N images (frames) set to: 1' print reply rlist = reply.split(' ', 9) if rlist[1] == 'OK': self.numImages = int(rlist[7].rstrip( PilatusOverSocket.terminators)) else: print "Get detector information failed." return self.numImages def setNumOfImages(self, number): self.numImages = number self.sendAndReply('nimages ' + str(number)) return self.numImages def setFilePath(self, newFilePath): """Set file path""" self.filePath = newFilePath self.sendAndReply('imgpath ' + newFilePath) def getFilePath(self): if self.filePath != None: return self.filePath reply = self.sendAndReply('imgpath ') print reply # The reply should be something like: '10 OK' /home/det/p2_det/images/' rlist = reply.split(' ', 3) if rlist[1] == 'OK': self.filePath = rlist[2].rstrip(PilatusOverSocket.terminators) else: print "Get detector information failed." return self.filePath def setFilePrefix(self, filePrefix): self.filePrefix = filePrefix self.runs = NumTracker(self.filePrefix) self.fileNumber = self.runs.getCurrentFileNumber() def getFileNumberOld(self): """Restore the pickled file number for persistence""" try: inStream = file(self.filePath + 'simPilatusFileNumber.txt', 'rb') self.fileNumber = pickle.load(inStream) inStream.close() except IOError: print "No previous pickled file numbers. Create new one" self.fileNumber = 0 return self.fileNumber def saveFileNumberOld(self): """Save the file number for persistence""" outStream = file(self.filePath + 'simPilatusFileNumber.txt', 'wb') try: #Pickle the file number and dump to a file stream pickle.dump(self.fileNumber, outStream) outStream.close() except IOError: print "Can not preserve file numbers." # Palitus Detector Interface Implementation def getCollectionTime(self): reply = self.sendAndReply("exptime") # The reply should be something like: '15 OK Exposure time set to: 2.000000 sec.' print reply rlist = reply.split(' ', 9) if rlist[1] == 'OK': self.exposureTime = float(rlist[8]) else: print "Get detector information failed." return self.exposureTime def setCollectionTime(self, newExpos): reply = self.sendAndReply("exptime " + str(newExpos)) print reply rlist = reply.split(' ', 9) if rlist[1] == 'OK': self.exposureTime = float(rlist[8]) else: print "Set detector information failed." return self.exposureTime def collectData(self): # newFileName = self.filePrefix + "%04.0f" % self.fileNumber + self.fileFormat[-4:] newFileName = self.getNextFullFileName() self.status = PilatusInfo.DETECTOR_STATUS_BUSY try: reply01 = self.sendAndReply('exposure ' + newFileName) reply02 = self.receive() print reply01 print reply02 self.runs.incrementNumber() except SocketError, msg: print 'Socket Connection Error: ' + str(msg) self.status = PilatusInfo.DETECTOR_STATUS_IDLE return
def getScanNumber(): nt = NumTracker("tmp") scanNumber = nt.getCurrentFileNumber() del nt return scanNumber
class Pilatus(object): def __init__(self, name): self.name = name self.detectorModel = None self.detectorInfo = None self.exposureTime = 0 self.exposurePeriod = 1 self.status = PilatusInfo.DETECTOR_STATUS_STANDBY self.filePath = None self.filePrefix = 'pilatusImage' self.fileFormat = "%s%s%d.tif" self.numImages = 1 self.gain = 0 self.thresholdEnergy = 5000 self.runs = NumTracker(self.filePrefix) self.fileNumber = self.runs.getCurrentFileNumber() def turnOn(self): self.status = PilatusInfo.DETECTOR_STATUS_IDLE def turnOff(self): self.status = PilatusInfo.DETECTOR_STATUS_STANDBY def setThreshold(self, newGain, newThresholdEnergy): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def getThreshold(self): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def setExposurePeriod(self, newExpp): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def getExposurePeriod(self): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") def start(self): return def getDetectorInfo(self): return self.detectorInfo def setNumOfImages(self, number): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def getNumOfImages(self): return self.numImages def setFilePath(self, newFilePath): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def getFilePath(self): return self.filePath def setFilePrefix(self, filePrefix): self.filePrefix = filePrefix # self.runs=NumTracker(self.filePrefix); # self.fileNumber = self.runs.getCurrentFileNumber(); def getFilePrefix(self): return self.filePrefix def getFileNumber(self): self.fileNumber = self.runs.getCurrentFileNumber() return self.fileNumber def getFileFromat(self): return self.fileFormat def getFullFileName(self): """Returns file path of the LAST CREATED image""" self.fileNumber = self.getFileNumber() fileName = self.filePrefix + "%04.0f" % ( self.fileNumber) + self.fileFormat[-4:] return os.path.join(self.filePath, fileName) def getCurrentFullFileName(self): """Returns file path of the next image to be created""" self.fileNumber = self.getFileNumber() return self.filePath + self.filePrefix + "%04.0f" % ( self.fileNumber + 1) + self.fileFormat[-4:] def getNextFullFileName(self): return self.getCurrentFullFileName() def getMultipleFullFileNames(self): """Returns a list of image names from multiple shot""" self.fileNumber = self.getFileNumber() names = [] for i in range(self.numImages): names.append(self.filePath + self.filePrefix + "%04.0f" % (self.fileNumber) + "_%05.0f" % (i) + self.fileFormat[-4:]) return names # Palitus Detector Interface Implementation def getCollectionTime(self): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def setCollectionTime(self, newExpos): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def collectData(self): raise NotImplementedError( "This is an abstract method that must be implemented by subclass.") return def readout(self): return self.getFullFileName() def getStatus(self): return self.status
from gda.factory import Finder import os import sys print "-" * 100 print "commands for directory/file operations: " print " >>>pwd - return the current data directory" print " >>>lwf - return the full path of the last working data file" print " >>>nwf - return the full path of the next working data file" print " >>>nfn - return the next data file number to be collected" print " >>>setSubdirectory('test') - change data directory to a sub-directory named 'test', created first if not exist" print " >>>getSubdirectory() - return the current sub-directory setting if exist" print "Please note: users can only create sub-directory within their permitted visit data directory via GDA, not themselves." # set up a nice method for getting the latest file path numTracker = NumTracker("i10") # function to find the working directory def pwd(): '''return the current working directory''' cwd = InterfaceProvider.getPathConstructor().createFromDefaultProperty() return cwd # function to find the last working file path def lwf(): '''return the last working file path''' cwd = InterfaceProvider.getPathConstructor().createFromDefaultProperty() filenumber = numTracker.getCurrentFileNumber() return os.path.join(cwd, str(filenumber))
def setFilePrefix(self, filePrefix): self.filePrefix = filePrefix self.runs = NumTracker(self.filePrefix) self.fileNumber = self.runs.getCurrentFileNumber()
from gda.factory import Finder import os import sys print "-" * 100 print "commands for directory/file operations: " print " >>>pwd - return the current data directory" print " >>>lwf - return the full path of the last working data file" print " >>>nwf - return the full path of the next working data file" print " >>>nfn - return the next data file number to be collected" print " >>>setSubdirectory('test') - change data directory to a sub-directory named 'test', created first if not exist" print " >>>getSubdirectory() - return the current sub-directory setting if exist" print "Please note: users can only create sub-directory within their permitted visit data directory via GDA, not themselves." # set up a nice method for getting the latest file path numTracker = NumTracker("i05") # function to find the working directory def pwd(): '''return the current working directory''' cwd = InterfaceProvider.getPathConstructor().createFromDefaultProperty() return cwd # function to find the last working file path def lwf(): '''return the last working file path''' cwd = InterfaceProvider.getPathConstructor().createFromDefaultProperty() filenumber = numTracker.getCurrentFileNumber() return os.path.join(cwd, str(filenumber))
def getScanNumber(self): nt = NumTracker("tmp") #get current scan number return int(nt.getCurrentFileNumber())
class I18ExafsScanClass(ScriptBase): def __init__(self, detectorList=None): # EXAFS PANEL CODE self.scannableNamesVector = Vector() self.scannableNamesVector.add("dcm_mono") self.detectorNamesVector = Vector() self.detectorNamesVector.add("counterTimer01") self.detectorNamesVector.add("counterTimer02") self.controller = Finder.find("ExafsController") self.mcontroller = Finder.find("MicroFocusController") self.title = "TITLE" self.condition1 = "CONDITION1" self.condition2 = "CONDITION2" self.condition3 = "CONDITION3" # Script code self.das = Finder.find("daserver") self.ionchambers = SlaveCounterTimer() self.converter = Finder.find("auto_mDeg_idGap_mm_converter") self.windowValues = [[0, 4095]] * 9 self.windowName = 'ALL' self.ionchamberData = [] self.mcaList = [] self.scalarList = [] self.runs = NumTracker("tmp") self.runprefix = 'i18exafs' self.runext = '.dat' self.fileno = self.runs.getCurrentFileNumber() + 1 self.runs.incrementNumber() self.datadir = InterfaceProvider.getPathConstructor( ).createFromProperty("gda.data.scan.datawriter.datadir") self.datafilename = self.datadir + '/' + str(self.fileno) + self.runext if (detectorList != None): self.detectorMask = detectorList else: self.detectorMask = [1, 1, 1, 1, 1, 1, 1, 1, 1] self.mcadir = self.datadir + '/mca/' + str(self.fileno) + '/' self.mcarootname = self.mcadir + str(self.fileno) if not os.path.isdir(self.mcadir): os.mkdir(self.mcadir) self.tag = 1 self.facade = JythonServerFacade.getInstance() self.scanList = [] self.noOfRepeats = 1 self.noOfPoints = 0 def addAngleScan(self, start, end, step, collectionTime): self.noOfPoints = self.noOfPoints + int((end - start) / step) self.scanList.append(['a', start, end, step, collectionTime]) def addKScan(self, start, end, step, kStartTime, kEndTime, kWeighting, edgeEnergy, twoD): self.noOfPoints = self.noOfPoints + int((end - start) / step) self.scanList.append([ 'k', start, end, step, kStartTime, kEndTime, kWeighting, edgeEnergy, twoD ]) def setNoOfRepeats(self, repeats): self.noOfRepeats = repeats def startScan(self): # # Send repeat and point information to the GUI # then start the scan # self.setupGUI() for i in range(self.noOfRepeats): if (i > 0): self.incrementFilename() for j in range(len(self.scanList)): if (self.scanList[j][0] == 'a'): self.anglescan(self.scanList[j][1], self.scanList[j][2], self.scanList[j][3], self.scanList[j][4]) elif (self.scanList[j][0] == 'k'): self.kscan(self.scanList[j][1],self.scanList[j][2],\ self.scanList[j][3],self.scanList[j][4],self.scanList[j][5],self.scanList[j][6],self.scanList[j][7],self.scanList[j][8]) self.incrementGUIRepeat() def setupGUI(self): scandata = Vector() # Type of scan scandata.add("FluScan") # No of Repeats # No of Points scandata.add(self.noOfPoints) scandata.add(self.noOfRepeats) self.controller.update(None, scandata) self.mcontroller.update(None, scandata) def incrementGUIRepeat(self): scandata = Vector() # Type of scan scandata.add("ScanComplete") self.controller.update(None, scandata) self.mcontroller.update(None, scandata) # ======================================== # Read in a window to be used on the mca files # ======================================== def setWindows(self, filename, desiredWindow): infile = open(filename, 'r') tmpwindowValues = [[0, 4095]] * 9 tmpwindowName = '' while infile: # Read in the line file a = infile.readline() n = len(a) if n == 0: break temp = a.split('\t') tmpwindowName = temp[0].strip().replace(' ', '') if (tmpwindowName.lower().find(desiredWindow.lower()) >= 0): for j in range(len(temp) - 1): index = j + 1 mytemp = temp[index].strip().replace('[', '').replace( ']', '').split(',') mytemp = [int(mytemp[0]), int(mytemp[1])] tmpwindowValues[j] = mytemp print 'window values chosen :', j, tmpwindowValues[j] self.windowValues = tmpwindowValues self.windowName = tmpwindowName if (self.windowName == 'ALL'): print '======================' print '========WARNING========' print 'No window has been found or set' print '======WARNING==========' print '======================' #================================================== # Performs an angle scan in step mode # ================================================== def anglescan(self, start, end, step, collectionTime): i = 0 self.createFile() # create some empty lists self.mcaList = [] self.ionchamberData = [] self.scalarList = [] # find no of points difference = end - start if (difference < 0 and step > 0): step = -step npoints = int(difference / step) # start position currentpos = start print 'Clearing and Preparing Detector' # set collection time self.prepareDetectorForCollection(npoints, collectionTime / 1000.0) # Set the collection time self.ionchambers.setCollectionTime(collectionTime) # loop over npoints print 'Starting angle scan' print 'Bragg Energy Time I0 It Idrain' self.checkForAngleInterrupt(0, start, end, step, collectionTime) #print 'w1',w for i in range(npoints): #print 'w1',w self.checkForAnglePause(i, start, end, step, collectionTime) # Check beam is running while (BeamMonitor.beamOn() == 0): self.checkForAngleInterrupt(i, start, end, step, collectionTime) print 'Beam lost : Pausing until resumed' try: sleep(60) except: self.interrupted = 1 self.checkForAngleInterrupt(i, start, end, step, collectionTime) #print 'w2',w # Move mono to start position self.checkForAngleInterrupt(i, start, end, step, collectionTime) #print 'w3',w try: #print 'w4',w comboDCM_d.moveTo(currentpos) comboDCM_d.waitWhileBusy() self.converter.disableAutoConversion() #ScannableBase.waitForScannable(comboDCM) #print 'w5',w except: self.interrupted = 1 self.converter.enableAutoConversion() self.checkForAngleInterrupt(i, start, end, step, collectionTime) # Ready the ion chambers #print 'w5',w self.ionchambers.clearAndPrepare() #print 'w6',w self.checkForAngleInterrupt(i, start, end, step, collectionTime) # tfg starts paused so tell it to continue self.das.sendCommand("tfg cont") self.checkForAngleInterrupt(i, start, end, step, collectionTime) self.das.sendCommand("tfg wait timebar") self.checkForAngleInterrupt(i, start, end, step, collectionTime) # read out the ion chambers #print 'w7',w while (self.ionchambers.isBusy() >= 1): self.checkForAngleInterrupt(i, start, end, step, collectionTime) try: sleep(0.05) except: self.interrupted = 1 pass #print 'w8',w self.ionchamberData.append(self.ionchambers.collectData()) # print out some progress self.checkForAngleInterrupt(i, start, end, step, collectionTime) #print currentpos,comboDCM.calcEnergy(currentpos/1000.0),collectionTime,self.ionchamberData[i][0],self.ionchamberData[i][1],self.ionchamberData[i][2] print currentpos, comboDCM_eV.getPosition( ), collectionTime, self.ionchamberData[i][0], self.ionchamberData[ i][1], self.ionchamberData[i][2] # Move the mono #print 'w9',w currentpos = currentpos + step # stop detector self.stopDetector() # write out the data self.writeSummary(npoints, start, end, step, collectionTime) self.converter.enableAutoConversion() self.tag = self.tag + 1 print 'Finished angle scan' #================================================== # Performs a kscan in step mode # ================================================== def kscan(self, start, end, step, kStartTime, kEndTime, kWeighting, edgeEnergy, twoD): i = 0 #try: self.createFile() self.mcaList = [] self.ionchamberData = [] self.scalarList = [] # check that step is negative when moving downwards to stop difference = end - start if (difference < 0 and step > 0): step = -step npoints = int(difference / step) currentpos = start # prepare detector for collection print 'Clearing and Preparing Detector' self.prepareDetectorForKScan(start, step, end, kWeighting, kEndTime, kStartTime) print 'Starting k scan' print 'Bragg Energy Time I0 It Idrain' self.checkForKScanInterrupt(0, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) for i in range(npoints): # Check for pause! self.checkForKScanPause(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) # Check beam is running while (BeamMonitor.beamOn() == 0): print 'Beam lost : Pausing until resumed' self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) try: sleep(60) except: self.interrupted = 1 mdegPosition = self.mDegForK(currentpos, edgeEnergy, twoD) secTime = self.timeForK(currentpos, start, end, kWeighting, kEndTime, kStartTime) self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) # Set the collection time self.ionchambers.setCollectionTime(secTime) # Move mono to start position try: comboDCM_d.moveTo(mdegPosition) #comboDCM.waitWhileBusy() self.converter.disableAutoConversion() #ScannableBase.waitForScannable(comboDCM) except: self.interrupted = 1 self.converter.enableAutoConversion() self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) # Ready the ion chambers self.ionchambers.clearAndPrepare() self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) # tfg starts paused so tell it to continue self.das.sendCommand("tfg cont") self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) self.das.sendCommand("tfg wait timebar") self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) while (self.ionchambers.isBusy() >= 1): self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) try: sleep(0.05) except: self.interrupted = 1 pass self.ionchamberData.append(self.ionchambers.collectData()) self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) #print mdegPosition,comboDCM.calcEnergy(mdegPosition/1000.0),secTime,self.ionchamberData[i][0],self.ionchamberData[i][1],self.ionchamberData[i][2] print mdegPosition, comboDCM_eV.getPosition( ), secTime, self.ionchamberData[i][0], self.ionchamberData[i][ 1], self.ionchamberData[i][2] # Move the mono currentpos = currentpos + step # write out at end self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) self.stopDetector() self.checkForKScanInterrupt(i, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) self.converter.enableAutoConversion() self.writeKScanSummary(npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) self.tag = self.tag + 1 print 'Finished k scan' #================================================== # Disables, Clears and enables the detector # Sets up tfg for a given noOfFrames and collectionTime # pausing in the dead frame and dead port=1 for adc triggering # and finally starts the tfg which means it sits waiting for a software based continue command #================================================== def prepareDetectorForCollection(self, noOfFrames, collectionTime): self.das.sendCommand("disable 0") self.das.sendCommand("clear 0") self.das.sendCommand("enable 0") self.das.sendCommand("tfg init") command = "tfg setup-groups cycles 1 \n%d 0.01 %f 0 1 1 0 \n-1 0 0 0 0 0 0 " % ( noOfFrames, collectionTime) self.das.sendCommand(command) self.das.sendCommand("tfg start") #================================================== # Disables, Clears and enables the detector # Sets up tfg for a set of possibly variable length time frames # and finally starts the tfg which means it sits waiting for a software based continue command #================================================== def prepareDetectorForKScan(self, start, step, end, kWeighting, kEndTime, kStartTime): self.das.sendCommand("disable 0") self.das.sendCommand("clear 0") self.das.sendCommand("enable 0") self.das.sendCommand("tfg init") self.das.sendCommand("tfg auto-cont 0") command = self.getTFGCommandForKScan(start, step, end, kWeighting, kEndTime, kStartTime) self.das.sendCommand(command) self.das.sendCommand("tfg start") #================================================== # Stop the tfg and disable the detector #================================================== def stopDetector(self): self.das.sendCommand("tfg init") self.das.sendCommand("disable 0") #================================================== # Write the detector data to files #================================================== def writeDetectorFile(self, npoints): for i in range(npoints): name = "%s_scan_%d_index_%d.dat" % (self.mcarootname, self.tag, i) sname = "%s_scan_%d_index_%d_scalar.dat" % (self.mcarootname, self.tag, i) print 'Writing scan point', i, 'to', name self.mcaList.append(name) self.scalarList.append(sname) command = "read 0 0 %d 4096 9 1 from 0 to-local-file \"%s\" raw intel" % ( i, name) self.das.sendCommand(command) command = "read 0 0 %d 9 2 1 from 1 to-local-file \"%s\" raw intel" % ( i, sname) self.das.sendCommand(command) #================================================== # Write the data to a file #================================================== def writeSummary(self, npoints, start, end, step, collectionTime): self.writeDetectorFile(npoints) # lets window this mofo fid = open(self.datafilename, 'a') current = start for i in range(npoints): windowedData = [0.0] * 9 print 'Reading and windowing:', self.mcaList[i] frameData = Xspress2Utilities.interpretDataFile(self.mcaList[i], 0) totalw = 0.0 for j in range(9): sumgrades = frameData[j] windowedData[j] = windowedData[j] + self.windowData( sumgrades, self.windowValues[j][0], self.windowValues[j][1]) for j in range(9): if (self.detectorMask[j] == 1): totalw = totalw + windowedData[j] # # now read scalar data # scalarData = [] for j in range(2): scalarData.append(range(9)) fis = FileInputStream(self.scalarList[i]) dis = DataInputStream(fis) scalerBytes = jarray.zeros(18 * 4, 'b') dis.read(scalerBytes, 0, 18 * 4) fis.close() offset = 0 for j in range(2): for l in range(0, 36, 4): scalarData[j][l/4]= (0x000000FF & scalerBytes[offset+l+0]) +\ ((0x000000FF & scalerBytes[offset+l+1])<<8)+\ ((0x000000FF & scalerBytes[offset+l+2])<<16)+((0x000000FF & scalerBytes[offset+l+3])<<24) offset = offset + 36 liveTime = collectionTime / 1000.0 corrCounts = self.getCorrectedCounts(scalarData[0], scalarData[1], liveTime) measuredCounts = scalarData[0] relinCounts = self.reLinearizeCounts(corrCounts) factor = [] for j in range(len(relinCounts)): if (relinCounts[j] == 0 or measuredCounts[j] == 0): val = 1 factor.append(1.0) else: val = (relinCounts[j] / measuredCounts[j]) factor.append(val * liveTime) correctWindows = [] corrWindTot = 0.0 for j in range(9): correctW = float(windowedData[j]) * factor[j] corrWindTot = corrWindTot + correctW correctWindows.append(correctW) #print >>fid,current,comboDCM.calcEnergy(current/1000.0),collectionTime,self.ionchamberData[i][0],\ # self.ionchamberData[i][1],self.ionchamberData[i][2],str(windowedData[0:]).strip('[]').replace(',',''), \ # totalw,str(correctWindows[0:]).strip('[]').replace(',',''),corrWindTot print >>fid,current,comboDCM_eV.getPosition(),collectionTime,self.ionchamberData[i][0],\ self.ionchamberData[i][1],self.ionchamberData[i][2],str(windowedData[0:]).strip('[]').replace(',',''), \ totalw,str(correctWindows[0:]).strip('[]').replace(',',''),corrWindTot # pdq added for plotting current = current + step # SDP Stuff detectorVector = Vector() detectorVector.add(self.ionchamberData[i]) detectorVector.add(windowedData) positionVector = Vector() positionVector.add(str(current)) #sdp = ScanDataPoint("scan name",self.scannableNamesVector,self.detectorNamesVector,positionVector,detectorVector,"Panel Name","I18 Custom SDP","Header String",self.datafilename) sdp = ScanDataPoint("Exafs FluAngleScan", self.scannableNamesVector, self.detectorNamesVector, None, None, None, None, positionVector, detectorVector, None, "Panel Name", "I18 Custom SDP", "Header String", self.datafilename, 0) self.controller.update(None, sdp) self.mcontroller.update(None, sdp) fid.close() #================================================== # Write the data to a file #================================================== def writeKScanSummary(self, npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting): self.writeDetectorFile(npoints) current = start # lets window this mofo fid = open(self.datafilename, 'a') current = start for i in range(npoints): windowedData = [0.0] * 9 print 'Reading and windowing:', self.mcaList[i] frameData = Xspress2Utilities.interpretDataFile( self.mcaList[i].strip(), 0) totalw = 0.0 for j in range(9): sumgrades = frameData[j] windowedData[j] = windowedData[j] + self.windowData( sumgrades, self.windowValues[j][0], self.windowValues[j][1]) for j in range(9): totalw = totalw + windowedData[j] # # now read scalar data # scalarData = [] for j in range(2): scalarData.append(range(9)) fis = FileInputStream(self.scalarList[i]) dis = DataInputStream(fis) scalerBytes = jarray.zeros(18 * 4, 'b') dis.read(scalerBytes, 0, 18 * 4) fis.close() offset = 0 for j in range(2): for l in range(0, 36, 4): scalarData[j][l / 4] = ( 0x000000FF & scalerBytes[offset + l + 0] ) + ((0x000000FF & scalerBytes[offset + l + 1]) << 8) + ( (0x000000FF & scalerBytes[offset + l + 2]) << 16) + ( (0x000000FF & scalerBytes[offset + l + 3]) << 24) offset = offset + 36 secTime = self.timeForK(current, start, end, kWeighting, kEndTime, kStartTime) liveTime = secTime / 1000.0 corrCounts = self.getCorrectedCounts(scalarData[0], scalarData[1], liveTime) measuredCounts = scalarData[0] relinCounts = self.reLinearizeCounts(corrCounts) factor = [] for j in range(len(relinCounts)): if (relinCounts[j] == 0 or measuredCounts[j] == 0): val = 1 factor.append(1.0) else: val = (relinCounts[j] / measuredCounts[j]) factor.append(val * liveTime) correctWindows = [] corrWindTot = 0.0 for j in range(9): correctW = float(windowedData[j]) * factor[j] corrWindTot = corrWindTot + correctW correctWindows.append(correctW) #print>>fid,self.mDegForK(current,edgeEnergy,twoD),comboDCM.calcEnergy(self.mDegForK(current,edgeEnergy,twoD)/1000.0),\ # secTime,self.ionchamberData[i][0],self.ionchamberData[i][1],self.ionchamberData[i][2],str(windowedData[0:]).strip('[]').replace(',',''), \ # totalw,str(correctWindows[0:]).strip('[]').replace(',',''),corrWindTot print>>fid,self.mDegForK(current,edgeEnergy,twoD),comboDCM.calcEnergy(self.mDegForK(current,edgeEnergy,twoD)/1000.0),\ secTime,self.ionchamberData[i][0],self.ionchamberData[i][1],self.ionchamberData[i][2],str(windowedData[0:]).strip('[]').replace(',',''), \ totalw,str(correctWindows[0:]).strip('[]').replace(',',''),corrWindTot current = current + step # SDP Stuff detectorVector = Vector() detectorVector.add(self.ionchamberData[i]) detectorVector.add(windowedData[0:]) positionVector = Vector() positionVector.add(str(self.mDegForK(current, edgeEnergy, twoD))) #sdp = ScanDataPoint("scan name",self.scannableNamesVector,self.detectorNamesVector,positionVector,detectorVector,"Panel Name","I18 Custom SDP","Header String",self.datafilename) sdp = ScanDataPoint("Exafs FluKScan", self.scannableNamesVector, self.detectorNamesVector, None, None, None, None, positionVector, detectorVector, None, "Panel Name", "I18 Custom SDP", "Header String", self.datafilename, 0) self.controller.update(None, sdp) self.mcontroller.update(None, sdp) fid.close() #================================================== # Window an mca contained in data between two values, start and end #================================================== def windowData(self, data, start, end): sum = 0.0 for i in range(start, end): sum = sum + data[i] return sum #================================================== # mDegForK converts k value (in inverse angstroms) to mDeg by using the java # Converter class. #================================================== def mDegForK(self, k, edgeEnergy, twoD): return gda.gui.exafs.Converter.convert( k, gda.gui.exafs.Converter.PERANGSTROM, gda.gui.exafs.Converter.MDEG, edgeEnergy, twoD) #================================================== # timeForK calculates the appropriate counting time for a particular k value # ================================================== def timeForK(self, k, start, end, kWeighting, kEndTime, kStartTime): a = Math.pow(k - start, kWeighting) b = Math.pow(end - start, kWeighting) c = (kEndTime - kStartTime) time = kStartTime + (a * c) / b # round to nearest 10milliseconds as this is all the ion chambers can collect in time = Math.round(time / 1.0) * 1.0 return time #================================================== # # Produces the tfg setup-groups used for kscans # In kscans you may want a time increase from start to finish # This method produces a series of individual tfg time frames for each time step in the scan #================================================== def getTFGCommandForKScan(self, start, step, end, kWeighting, kEndTime, kStartTime): difference = end - start if (difference < 0 and step > 0): step = -step npoints = int(difference / step) currentpos = start tfglist = "tfg setup-groups cycles 1 \n" for j in range(npoints + 1): secTime = self.timeForK(currentpos, start, end, kWeighting, kEndTime, kStartTime) tfglist = tfglist + "1 0.01 %f 0 1 1 0 \n" % (secTime / 1000.0) currentpos = currentpos + step tfglist = tfglist + "-1 0 0 0 0 0 0 " return tfglist #================================================== # # Creates the file used for the EXAFS # #================================================== def createFile(self): if (os.path.exists(self.datafilename) == 0): fid = open(self.datafilename, 'w') df = SimpleDateFormat('hh.mm.dd.MM.yyyy') today = df.format(Date()) print "Writing data to file:" + self.datafilename print "Writing mca file to:" + self.mcadir # write datetime line = " I18_EXAFS_RUN=" + str(self.fileno) + " " + today print >> fid, line print >> fid, self.title print >> fid, self.condition1 print >> fid, self.condition2 print >> fid, self.condition3 print >> fid, 'Sample X=', MicroFocusSampleX.getPosition( ), 'Sample Y=', MicroFocusSampleY.getPosition() print >> fid, 'comboDCM energy time I0 It drain flu1 flu2 flu3 flu4 flu5 flu6 flu7 flu8 flu9 flutot' fid.close() #================================================== # # Checks to see if an angle scan has been interrupted # #================================================== def checkForAngleInterrupt(self, npoints, start, end, step, collectionTime): #if(self.facade.getScanStatus()==0 and self.facade.getScriptStatus()==0): if (self.interrupted): print 'Stopping angle scan:Writing out data taken' # write the data we have so far and return self.stopDetector() self.writeSummary(npoints, start, end, step, collectionTime) self.interrupted = Boolean(0) self.paused = Boolean(0) JythonServerFacade.getInstance().setScriptStatus(JythonStatus.IDLE) scandata = Vector() scandata.add("STOP") self.controller.update(None, scandata) self.mcontroller.update(None, scandata) print 'Now the nasty bit: throw an exception to stop running' raise lang.InterruptedException() raise lang.InterruptedException() #================================================== # # Checks to see if an angle scan has been paused # #================================================== def checkForAnglePause(self, npoints, start, end, step, collectionTime): if (self.paused): JythonServerFacade.getInstance().setScriptStatus( JythonStatus.PAUSED) while (self.paused): try: print 'Angle Scan paused - Awaiting resume' java.lang.Thread.sleep(10000) except lang.InterruptedException: self.checkForAngleInterrupt(npoints, start, end, step, collectionTime) #================================================== # # Checks to see if an angle scan has been paused # #================================================== def checkForKScanInterrupt(self, npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting): #if(self.facade.getScanStatus()==0 and self.facade.getScriptStatus()==0): if (self.interrupted): print 'Stopping k scan:Writing out data taken' # write the data we have so far and return self.stopDetector() self.writeKScanSummary(npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) self.interrupted = Boolean(0) self.paused = Boolean(0) JythonServerFacade.getInstance().setScriptStatus(JythonStatus.IDLE) scandata = Vector() scandata.add("STOP") self.controller.update(None, scandata) self.mcontroller.update(None, scandata) print 'Now the nasty bit: throw an exception to stop running' raise lang.InterruptedException() #================================================== # # Checks to see if an angle scan has been paused # #================================================== def checkForKScanPause(self, npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting): if (self.paused): JythonServerFacade.getInstance().setScriptStatus( JythonStatus.PAUSED) while (self.paused): try: print 'K Scan Scan paused - Awaiting resume' java.lang.Thread.sleep(10000) except lang.InterruptedException: self.checkForKScanInterrupt(npoints, start, end, step, edgeEnergy, twoD, kStartTime, kEndTime, kWeighting) #================================================== # To set the resolution binning used by xspress # Usage # setResMode(0) .. all grades processed # setResMode(1) .. variable all grades summed into 1 grade # setResMode(1,8) variable all grades from 0-7 put in one grade and 8-15 in next grade #================================================== def setResMode(self, mode, map=None): if (mode == 0): command = "xspress2 set-resmode \"xsp1\" 0 0" self.das.sendCommand(command) else: if (map == None or map < 0 or map > 15): command = "xspress2 set-resmode \"xsp1\" 1 0" else: command = "xspress2 set-resmode \"xsp1\" 1 %d" % (map) self.das.sendCommand(command) #================================================== # # To set the header info used in the script # #================================================== def setHeaderInfo(self, title, condition1, condition2, condition3): self.title = title self.condition1 = condition1 self.condition2 = condition2 self.condition3 = condition3 #================================================== # # Get corrected counts # #================================================== def getCorrectedCounts(self, countData, resetData, liveTime): realCounts = [] for i in range(len(countData)): realCounts.append(countData[i] * (1.0 / (liveTime - ((12.5e-9) * resetData[i])))) return realCounts #================================================== # # Get corrected counts # #================================================== def reLinearizeCounts(self, corrCounts): process_times = [ 3.4e-07, 3.8e-07, 3.7e-07, 3.0e-07, 3.4e-07, 3.5e-07, 3.3e-07, 3.0e-07, 3.3e-07 ] realCounts = [] for i in range(len(process_times)): a = process_times[i] * corrCounts[i] aa = a * a eqn1 = (-10.0 + 27.0 * a + 5.196152423 * sqrt(4 - 20.0 * a + 27.0 * aa))**(1.0 / 3.0) eqn2 = (1.0 / (3.0 * process_times[i])) eqn3 = eqn2 * eqn1 - 2 * eqn2 / eqn1 + 2 * eqn2 realCounts.append(eqn3) return realCounts #================================================== # # Read in a scalar data file and return array # #================================================== def readScalarDataFile(self, scalarfile): scalarData = [] for j in range(2): scalerData.append(range(9)) fis = FileInputStream(self.scalarList[i]) dis = DataInputStream(fis) scalerBytes = jarray.zeros(18 * 4, 'b') dis.read(scalerBytes, 0, 18 * 4) fis.close() offset = 0 for j in range(2): for l in range(0, 36, 4): scalarData[j][ l / 4] = (0x000000FF & scalerBytes[offset + l + 0]) + ( (0x000000FF & scalerBytes[offset + l + 1]) << 8 ) + ((0x000000FF & scalerBytes[offset + l + 2]) << 16) + ( (0x000000FF & scalerBytes[offset + l + 3]) << 24) offset = offset + 36 fis.close() return scalarData # # In a scan you create a new scan object for each scan # You can reuse the i18exafs scan # This simply increments the file no.s etc. # def incrementFilename(self): self.fileno = self.runs.getCurrentFileNumber() + 1 self.runs.incrementNumber() self.datadir = InterfaceProvider.getPathConstructor( ).createFromProperty("gda.data.scan.datawriter.datadir") self.datafilename = self.datadir + '/' + str(self.fileno) + self.runext self.mcadir = self.datadir + '/mca/' + str(self.fileno) + '/' self.mcarootname = self.mcadir + str(self.fileno) if not os.path.isdir(self.mcadir): os.mkdir(self.mcadir) self.tag = 1 self.interrupted = Boolean(0)
scansReturnToOriginalPositions = 0 print _epicsScriptLibraryDir = PropertyUtils.getExistingDirFromLocalProperties( "gda.install.git.loc" ) + "/gda-epics.git/uk.ac.gda.epics/scripts" + System.getProperty( "file.separator") sys.path.append(_epicsScriptLibraryDir) ############################################################################### ### Generic Functions ### ############################################################################### print "-----------------------------------------------------------------------------------------------------------------" print "create directory operation commands: " i09_2NumTracker = NumTracker("i09") print " pwd : present working directory;" # function to find the working directory def pwd(): '''return the current working directory''' curdir = InterfaceProvider.getPathConstructor().createFromDefaultProperty() return curdir alias("pwd") print " lwf : last working file path;" # function to find the last working file path