def setSubdirectory(dirname): '''create a new sub-directory for data collection that follows''' Finder.find("GDAMetadata").setMetadataValue("subdirectory", dirname) try: os.mkdir(pwd()) except: pass
def visit(self, new_visit = None): if new_visit: Finder.getInstance().find("GDAMetadata").setMetadataValue("visit", new_visit) Finder.getInstance().find("GDAMetadata").setMetadataValue("defaultVisit", new_visit) if not os.path.exists(self.getVisitDirectory()): print "!!! Warning !!! The directory '%s' does NOT exist! (pointing to it anyway though)" %self.getVisitDirectory() self.setDetectorDirectories() return Finder.getInstance().find("GDAMetadata").getMetadataValue("visit")
def __init__(self, stageName): self.name=stageName self.calibrant_file_name=None self.stage_x=Finder.getInstance().find(stageName+"x") self.stage_y=Finder.getInstance().find(stageName+"y") self.stage_rot=Finder.getInstance().find(stageName+"rot") self.lookup_table = readLookupTable(LocalProperties.get("gda.function.lookupTable.dir")+os.path.sep+"lde_stages_home_positions.txt") self.samples=[] self.calibration_required=True self.pixium=Finder.getInstance().find('pixium_hdf')
def setSubdirectory(dirname): '''create a new sub-directory under current data directory for data collection that follows''' if os.sep not in dirname: subdirectory = getSubdirectory() if subdirectory: dirname = str(subdirectory) + os.sep + str(dirname) Finder.find("GDAMetadata").setMetadataValue("subdirectory", dirname) try: os.mkdir(pwd()) except: exceptionType, exception = sys.exc_info()[:2] print "Error Type: ", exceptionType print "Error value: ", exception
def visit(self, new_visit=None): if new_visit: Finder.getInstance().find("GDAMetadata").setMetadataValue( "visit", new_visit) Finder.getInstance().find("GDAMetadata").setMetadataValue( "defaultVisit", new_visit) if not os.path.exists(self.getVisitDirectory()): print "!!! Warning !!! The directory '%s' does NOT exist! (pointing to it anyway though)" % self.getVisitDirectory( ) self.setDetectorDirectories() return Finder.getInstance().find("GDAMetadata").getMetadataValue( "visit")
def reconnect(self): try: #have to close the old one if it's not broken self.leem_com.sendCmdNoReply("clo") except DeviceException: pass #we expect this new_com = SocketBidiAsciiCommunicator() new_com.setAddress( self.leem_com.address ) new_com.setPort( self.leem_com.port ) new_com.setCmdTerm( self.leem_com.cmdTerm ) new_com.setReplyTerm( self.leem_com.replyTerm ) new_finder_map = {"leem2000_com" : new_com} Finder.find("leem2000_objects").setMap(new_finder_map) self.leem_com = new_com
def setDof(self, dof): if dof in MOTORS.keys(): self.motor = Finder.find(MOTORS[dof]) else: raise ValueError("No Motor found Error") self.dof = dof self.backupMotor()
def analyserpathscan_v1(scannables, path, *args): ''' perform a single region analyser data collection at each point on the specified path, and produce a single scan data files recording scannables' poistions and metadata, and analyser data for the active region defined in your sequence definition file under ew4001 node. implementation details: This function pre-process sequence file to set up Region Position Provider for scannable 'regions' ready for data collection using analyser 'ew4001', then delegate the scan process to 'pathscan'. ''' newargs = [] i = 0 while i < len(args): arg = args[i] newargs.append(arg) i = i + 1 if isinstance(arg, RegionScannable): controller = Finder.find("SequenceFileObserver") xmldir = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + "xml" + os.sep filename = xmldir + args[i] if (OsUtil.isWindows()): FilenameUtil.setPrefix("D:") filename = FilenameUtil.convertSeparator(filename) controller.update(controller, SequenceFileChangeEvent(filename)) sleep(1.0) while (InterfaceProvider.getScanStatusHolder().getScanStatus() == JythonStatus.PAUSED): sleep(1.0) newargs.append(RegionPositionProvider(filename)) #newargs.append( arg ) # to read the actual position i = i + 1 pathscan(scannables, path, newargs)
def getUserOptionsManager(): manager = Finder.getInstance().findSingleton(UserOptionsManager) if not manager: manager = UserOptionsManager() manager.configure() return manager
def __init__(self): self.ccWaveFormHead = CAClient(pvWaveFormHead) self.ccSubArraySize = CAClient(pvSubArraySize) self.ccSubArrayIndex = CAClient(pvSubArrayIndex) self.ccUpdate = CAClient(pvUpdate) self.ccCh01 = CAClient(pvCh01) self.ccCh02 = CAClient(pvCh02) self.ccCh03 = CAClient(pvCh03) self.ccCh04 = CAClient(pvCh04) self.ccCh05 = CAClient(pvCh05) self.ccCh06 = CAClient(pvCh06) self.ccWaveFormHead.configure() self.ccSubArraySize.configure() self.ccSubArrayIndex.configure() self.ccUpdate.configure() self.ccCh01.configure() self.ccCh02.configure() self.ccCh03.configure() self.ccCh04.configure() self.ccCh05.configure() self.ccCh06.configure() self.length = 0 self.head = 0 self.dataSetCh01 = dnp.zeros([maxLength]) self.dataSetCh01.setName("Channel 1") self.js = Finder.find("command_server")
def __init__(self, name): self.setName(name) self.setInputNames([name]) self.setExtraNames([]) # self.Units=[strUnit]; self.setLevel(7) self.uview = Finder.find("uview")
def __init__(self, name, roi): self.setName(name) self.setInputNames([]) self.setExtraNames([name]) # self.Units=[strUnit]; self.setLevel(7) self.roi = Finder.find(roi)
def Assemble(self): nameList=Finder.getInstance().listAllNames('Scannable') nameList=['ab__a', 'ab__b', 'xyz__x', 'xyz__y', 'xyz__z', 'blarghh'] # Filter out those containing __ groupComponentList=[] for name in nameList: if name.__contains__('__'): groupComponentList.append(name) # Create a dictionary with one key for each group, each key pointing to a list of component strings" groupDict={} for name in groupComponentList: group, component = name.split('__') if not(groupDict.has_key(group)): groupDict[group]=[] groupDict[group].append(component) # Create the group scannables and pass back as list (STUB) toReturn = [] groupNameList = groupDict.keys() for groupName in groupNameList: tmp=groupName for componentName in groupDict[groupName]: tmp += "." + componentName toReturn += [tmp] return toReturn
def setProperty(propertyName, propertyValue): LocalProperties.set(propertyName, propertyValue) eventAdmin=Finder.getInstance().find("eventadmin") if eventAdmin is None: print "Cannot find 'eventAdmin' on the GDA server. Please create a Spring bean using 'Scriptcontroller' Java class" else: eventAdmin.update(propertyName, propertyValue)
def __init__(self, name, tfg, fg, adc, pe, detector): self.name=name self.tfg=tfg self.fg=fg self.adc=adc self.pedata=pe self.detector=detector self.fastshutter=Finder.getInstance().find("fastshutter") self.numGates=1 self.numCycles=1 self.numFrames=1 self.livetime=0.0 self.deadtime=0.0 self.boundaryFrequency=0.1 self.func = 2 self.bncycle=1 self.freq=0.1 self.adcStreamerCompleted=True self.gateDetectorCompleted=True self.numDefinedSequency=1 self.filename="" self.directory="" self.scanNumber=0 self.preConditioning=True self.startCycleNumber=0 self.startSeqNumber=0
def doCalibration(self, calibrant='Si', calibrant_x=0, calibrant_y=0, calibrant_exposure=1.0): if self.calibration_required: mycalibrant=Finder.getInstance().find("calibrant_name") mycalibrant.moveTo(calibrant) dummyScannable=DummyScannable("dummyScannable") #additional_plugin_list = pixium.getAdditionalPluginList()[0] #Detector calibration if self.calibration_required: self.stage_x.moveTo(calibrant_x) self.stage_y.moveTo(calibrant_y) scan([dummyScannable, 1, 1, 1, self.pixium, calibrant_exposure]) #TODO GDA .nxs file, not EPICS h5 file scan_data_point_provider = InterfaceProvider.getScanDataPointProvider() self.calibrant_file_name = scan_data_point_provider.getLastScanDataPoint().getCurrentFilename() #calibrant_file_name = additional_plugin_list.getFullFileName() #do detector calibration on cluster serevrs builder = OSCommandRunnerBuilder.defaults() builder=builder.command([LocalProperties.get("org.opengda.lde.pixium.data.reduction.script","/dls_sw/apps/i11-scripts/bin/LDE-RunFromGDAAtEndOfScan.sh")]) builder=builder.keepOutput(True) builder = builder.inputFilename(self.calibrant_file_name) builder = builder.outputFilename(os.path.splitext(self.calibrant_file_name)[0]+"_output.log") builder=builder.noTimeout() builder.build() self.calibration_required=False
def analyserscan_v1(*args): starttime = time.ctime() if PRINTTIME: print "=== Scan started: " + starttime newargs = [] i = 0 while i < len(args): arg = args[i] newargs.append(arg) i = i + 1 if isinstance(arg, RegionScannable): controller = Finder.find("SequenceFileObserver") xmldir = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + "xml" + os.sep filename = xmldir + args[i] if (OsUtil.isWindows()): FilenameUtil.setPrefix("D:") filename = FilenameUtil.convertSeparator(filename) controller.update(controller, SequenceFileChangeEvent(filename)) sleep(1.0) while (InterfaceProvider.getScanStatusHolder().getScanStatus() == JythonStatus.PAUSED): sleep(1.0) newargs.append(RegionPositionProvider(filename)) #newargs.append( arg ) # to read the actual position i = i + 1 scan(newargs) if PRINTTIME: print("=== Scan ended: " + time.ctime() + ". Elapsed time: %.0f seconds" % (time.time() - starttime))
def setTerminalLogger(self, newLoggerName="gda_terminal.log"): tlPath = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() tlFile = os.path.join(tlPath, newLoggerName) tlpp = Finder.find("terminallog_path_provider") tlpp.setTemplate(str(tlFile))
def __init__(self, name, rootPV, channelList, extraChannelList=[], elementCounter="iddFastScanElementCounter"): self.numberOfChannels=len(channelList); self.setupEpics(rootPV); self.setName(name); self.setInputNames(["pIndex"]); self.setLevel(7); en=[]; of=["%5.0f"]; for c in channelList + extraChannelList: en.append( str(c) ); of.append("%20.12f"); self.setExtraNames(en); self.setOutputFormat(of); self.timeout=30; self.defaultSize = 100; self.low = 0; self.high = 1000; self.keyChannel=None; # self.fastScanElementCounter = None; self.fastScanElementCounter = Finder.find(elementCounter); self.reset();
def Assemble(self): nameList = Finder.getInstance().listAllNames('Scannable') nameList = ['ab__a', 'ab__b', 'xyz__x', 'xyz__y', 'xyz__z', 'blarghh'] # Filter out those containing __ groupComponentList = [] for name in nameList: if name.__contains__('__'): groupComponentList.append(name) # Create a dictionary with one key for each group, each key pointing to a list of component strings" groupDict = {} for name in groupComponentList: group, component = name.split('__') if not (groupDict.has_key(group)): groupDict[group] = [] groupDict[group].append(component) # Create the group scannables and pass back as list (STUB) toReturn = [] groupNameList = groupDict.keys() for groupName in groupNameList: tmp = groupName for componentName in groupDict[groupName]: tmp += "." + componentName toReturn += [tmp] return toReturn
def meta_rm(farg, *vargs): """ Command to remove items to be put into the scan metadata. """ metashop=Finder.getInstance().find("metashop") if metashop == None: return metashop.remove([farg]+list(vargs))
def meta_add( farg, *vargs): """ Command to add a scannable to the items to be put into the scan metadata """ metashop=Finder.getInstance().find("metashop") if metashop == None: return metashop.add([farg]+list(vargs))
def meta_rm(farg, *vargs): """ Command to remove items to be put into the scan metadata. """ metashop = Finder.getInstance().find("metashop") if metashop == None: return metashop.remove([farg] + list(vargs))
def meta_add(farg, *vargs): """ Command to add a scannable to the items to be put into the scan metadata """ metashop = Finder.getInstance().find("metashop") if metashop == None: return metashop.add([farg] + list(vargs))
def __init__(self, name, scannableX, scannableY, deviceFun): '''constructor parameters: name: Name of the new device scannableX: Name of the scannable on X-axis (for example: "energy") scannableY: Name of the scannable on Y-axis (for example: "mac15") deviceFun: Name of the function to calculate the new position based on scannableX and scannableY positions''' self.setName(name) self.setInputNames([name]) #self.Units=[strUnit] #self.setOutputFormat([strFormat]) #self.setLevel(8); self.x1 = 0.0 self.x2 = 0.0 self.y = 0.0 self.refObj1 = Finder.find(scannableX) self.refObj2 = Finder.find(scannableY) self.deviceFun = deviceFun
def __init__(self, name, scannableX, scannableY, deviceFun): """constructor parameters: name: Name of the new device scannableX: Name of the scannable on X-axis (for example: "energy") scannableY: Name of the scannable on Y-axis (for example: "mac15") deviceFun: Name of the function to calculate the new position based on scannableX and scannableY positions""" self.setName(name) self.setInputNames([name]) # self.Units=[strUnit] # self.setOutputFormat([strFormat]) # self.setLevel(8); self.x1 = 0.0 self.x2 = 0.0 self.y = 0.0 self.refObj1 = Finder.getInstance().find(scannableX) self.refObj2 = Finder.getInstance().find(scannableY) self.deviceFun = deviceFun
def __init__(self, name): self.setName(name) self.setInputNames([name]) self.setExtraNames([]) self.setOutputFormat(["%5.5g"]) my_pgm_energy = Finder.find("pgm_energy") self.currentposition = (float)(my_pgm_energy.getPosition( )) # this template scannable represents a single number self.iambusy = 0 # flag to hold the status of the scannable
def __init__(self): self.comms_started=False try: self.leem_com=(Finder.find("leem2000_objects")).get("leem2000_com") self.leem_com.setReplyTerm('\0') self.leem_com.setCmdTerm('\0') except: exceptionType, exception, traceback=sys.exc_info(); handle_messages.log(None, "Error getting leem2000_com from leem2000_objects", exceptionType, exception, traceback, True)
def getDataDir(self): opc = ObservablePathConstructor() opc.setName("opc") opc.setTemplate("${gda.data}/$year$/$visit$/$subdirectory$") opc.setGdaMetadata(Finder.find("GDAMetadata")) opc.configure() dataDir = opc.getPath() return dataDir
def __init__(self, name, index): self.setName(name) self.setInputNames([]) self.setExtraNames([name]) # self.Units=[strUnit]; self.setLevel(7) self.peem = Finder.find("leem") self.index = index self.value = 0
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 _createHeaderStringForScannables(self, fmt='%s=%s\n'): s = "" metascannables = Finder.getInstance().find("metashop").getMetaScannables() \ if self.readFromNexus else self.scannables_to_read for scn in metascannables: pairs = self._createNamePositionPairs(scn) for key, value in pairs: s += fmt % (key, value) return s
def reloadLookupTables(): """reloads all lookup tables on the ObjectServer""" controller = None prefix = "reloadLookupTables:" update(controller, prefix, " - started.") converters = Finder.listFindablesOfType(IReloadableQuantitiesConverter) for converter in converters: update(controller, prefix, "..." + converter.getName() ) converter.reloadConverter() update(controller, prefix, " - completed")
def runExperiment(self): print "I am now running the experiment using parameters in the bean",str(self.bean),"..." time.sleep(2) print "...and now the experiment is over." scriptController = Finder.getInstance().find("MyExperimentScriptController") if scriptController != None: print "Broadcasting experiment complete message..." scriptController.update("MyExperiment Script", "Experiment Complete!")
def runExperiment(self): print "I am now running the experiment using parameters in the bean", str( self.bean), "..." time.sleep(2) print "...and now the experiment is over." scriptController = Finder.find("MyExperimentScriptController") if scriptController != None: print "Broadcasting experiment complete message..." scriptController.update("MyExperiment Script", "Experiment Complete!")
def initialise_zpz_osa_function(): # Set the parameters of the linear function that combines ZonePlateZ & OSA Z motion # # Assuming the current positions of the motors are correct, we always want the OSA to move an equal # and opposite distance to the zone plate. zpz_osa_function = Finder.find('zpz_osa_coupling_function') zpz_osa_function.setSlopeDividend(Quantities.getQuantity('-1 mm')) zpz_osa_function.setSlopeDivisor(Quantities.getQuantity('1 mm')) zpz_osa_function.setInterception(Quantities.getQuantity('0 mm')) print(u'zpz_osa_function: {}'.format(zpz_osa_function))
def reloadLookupTables(): """reloads all lookup tables on the ObjectServer""" controller = None prefix = "reloadLookupTables:" update(controller, prefix, " - started.") finder = Finder.getInstance() converters = finder.listAllObjects("IReloadableQuantitiesConverter") for converter in converters: update(controller, prefix, "..." + converter.getName() ) converter.reloadConverter() update(controller, prefix, " - completed")
def __init__(self, name, lowLimit, highLimit, refObj, delay): self.setName(name); self.setInputNames([name]); self.setExtraNames([name]); #self.Units=[strUnit] #self.setOutputFormat([strFormat]) self.setLevel(5); self.value = 0.0; self.lowLimit = lowLimit; self.highLimit = highLimit; self.refObj = Finder.find(refObj); self.delay = delay;
def analyserpathscan(*args): ''' perform single/multiple regions analyser data collection at each point on the specified path, and produce a single scan file recording all scannables' poistions and metadata, along with analyser scan data under region's name as NXdetector node. implementation details: This function pre-process sequence file to set up analyser 'ew4000' ready for data collection. It creates scannable group to support point-to-point concurrent scan. ''' starttime = time.ctime() if PRINTTIME: print "=== Scan started: " + starttime newargs = [] i = 0 while i < len(args): arg = args[i] if type(arg) == TupleType: if allElementsAreScannable(arg): scannableGroup = ScannableGroup("pathgroup") for each in arg: scannableGroup.addGroupMember(each) newargs.append(scannableGroup) elif allElementsAreListOfNumber(arg): newargs.append(arg) else: raise TypeError, "Only tuple of scannables and tuple of list of numbers are supported." else: newargs.append(arg) i = i + 1 if isinstance(arg, EW4000): controller = Finder.find("SequenceFileObserver") xmldir = InterfaceProvider.getPathConstructor( ).createFromDefaultProperty() + "xml" + os.sep filename = xmldir + args[i] if (OsUtil.isWindows()): FilenameUtil.setPrefix("D:") filename = FilenameUtil.convertSeparator(filename) controller.update(controller, SequenceFileChangeEvent(filename)) sleep(2.0) jythonServerStatus = InterfaceProvider.getJythonServerStatusProvider( ).getJythonServerStatus() while (jythonServerStatus.isScriptOrScanPaused()): sleep(1.0) arg.setSequenceFilename(filename) sequence = arg.loadSequenceData(filename) if isinstance(arg.getCollectionStrategy(), EW4000CollectionStrategy): arg.getCollectionStrategy().setSequence(sequence) i = i + 1 scan(newargs) if PRINTTIME: print("=== Scan ended: " + time.ctime() + ". Elapsed time: %.0f seconds" % (time.time() - starttime))
def writefile(scannable1Name, scannable2Name, filepath): """ add a line with 2 column for calibration scannable1 versus scannable2 """ Scannable1 = Finder.find("photoDiode1") Scannable1Position = Scannable1.getPosition() print "Scannable1Position", Scannable1Position values = [] f = open(filepath) lines = f.readlines() f.close()
def __init__(self, name, refCA): self.setName(name) self.setInputNames([name + "_sum"]) self.setExtraNames([name + "_average"]) # self.Units=[strUnit]; self.setLevel(7) self.sum = 0 self.average = 0 self.total = 1 #default number of counts # self.refCA = globals()[refCA]; self.refCA = Finder.find(refCA)
def __init__(self, name, lutObj='energytable', objType=0, rootNameSpace={}): '''Constructor - Only succeed if it find the lookup table, otherwise raise exception.''' self.finder=Finder.getInstance() self.lut=self.finder.find(lutObj) if self.lut==None: raise Exception, "Can not find the Lookup Table object" self.rootNameSpace=rootNameSpace self.scannableNames=self.lut.getScannableNames() self._busy=0 self.scannables=[self.rootNameSpace[x] for x in self.scannableNames] self.setName(name) self.setLevel(3) self.objType=objType self.inputNames=['energy']
def jobs(): """ Print a string showing the threads running in the command server. Only shows the live threads. """ command_server = Finder.getInstance().find(Jython.SERVER_NAME) logger.debug("jobs() called") s = "%-10s %-12s %-8s %-11s %s\n" % ('DATE', 'TIME', 'TYPE', 'INTERRUPTED', 'COMMAND') thread_infos = command_server.getCommandThreadInfo() for t in thread_infos: date = t.getDate() time = t.getTime() thread_type = t.getCommandThreadType() cmd = t.getCommand(); intrpt = ' X ' if t.isInterrupted() else '' s += "%(date)-10s %(time)-12s %(thread_type)-8s %(intrpt)-11s %(cmd)s\n" % locals() print s
def reload_tables(logInfo=True): """reloads all lookup tables on the ObjectServer""" ok = True controller = None prefix = "reload_tables:" if( logInfo ): handle_messages.log(controller, prefix + " - started") finder = Finder.getInstance() converters = finder.listAllObjects("IReloadableQuantitiesConverter") for converter in converters: try: if( logInfo ): handle_messages.log(controller, prefix + "..." + converter.getName() ) converter.reloadConverter() except: type1, exception, traceback = sys.exc_info() handle_messages.log(controller, prefix + " - ", type1, exception, traceback, False) ok = False if( logInfo ): handle_messages.log(controller, prefix + " - completed") if( not ok): print "reload_tables completed with error" return ok
def __init__(self, name): self.tfg = Finder.getInstance().find("tfg") self.daserver = Finder.getInstance().find("daserver") # to support showArmed status self.tfg.setShowArmed(True)
from gda.data import PathConstructor from gda.factory import Finder import sys import gda.device.scannable.DummyScannable from gda.configuration.properties import LocalProperties import subprocess from gda.device import Scannable from gda.jython.commands.GeneralCommands import ls_names, vararg_alias from time import sleep from gda.jython.commands import GeneralCommands from gda.epics import CAClient from epics_scripts.pv_scannable_utils import caputStringAsWaveform # set up a nice method for getting the latest file path i11NumTracker = NumTracker("i11"); finder = Finder.getInstance() ca=CAClient() def wd(): dir = PathConstructor.createFromDefaultProperty() return dir # function to find the last file path def pwd(): dir = PathConstructor.createFromDefaultProperty() filenumber = i11NumTracker.getCurrentFileNumber(); return os.path.join(dir, str(filenumber))
def meta_clear_alldynamical(): metashop = Finder.getInstance().find("metashop") if metashop is None: return metashop.clearDynamicScannableMetadata() return metashop.list(False)
def ls(self): metascannables = Finder.getInstance().find("metashop").getMetaScannables() \ if self.readFromNexus else self.scannables_to_read # meta_ls and meta_ll enforce their own formatting, so return their # list of metadata scannables in our format. return ' '.join([scn.name for scn in metascannables])
def pescan(self, frequency=0.1,exposure=0.5,amplitude=5.0,numPoints=40, function=2, bncycle=1): self.directory=PathConstructor.createFromDefaultProperty() self.scanNumber=scanNumTracker.incrementNumber() self.filename=self.directory+(str(self.scanNumber)) print self.filename if self.adc.getMode()=="Gate": self.setupADC2() elif self.adc.getMode()=="Trigger": self.configADC(200, self.adcClockRate(frequency)) self.calculateExperimentParameters(frequency, exposure, numPoints) self.setupFG(freq=frequency,amp=amplitude,bncycle=self.numGates, func=function) # must in following order if self.isSampleConditioning(): self.sampleConditioning(func=6, bncycle=1) self.configTFG(frequency) self.setupDataCapturer(self.filename, self.numGates) print "open fast shutter %d" % time() self.fastshutter.moveTo("OPEN") try: if frequency <= self.boundaryFrequency: for i in range(self.numCycles): GeneralCommands.pause() self.pedata.reset() self.pedata.setCollectionNumber(i) print "\ncollecting %d frames, %d gates per frame, Scan number %d, Collection number %d" % (self.numFrames*self.numDefinedSequency, self.numGates, self.scanNumber, i) Thread(target=self.gateDetector, name="MythenGatedCollection", args=(self.numFrames, self.numGates, self.scanNumber, i), kwargs={}).start() sleep(1) #self.startDetector(frequency, self.scanNumber, i) if self.adc.getMode()=="Trigger": print "enable adc sampling" self.adc.enable() #elif self.adc.getMode()=="Continuous": self.startPEDataStreamer(self.filename+"_pe_"+str(i)+".h5", 1/frequency+TIME_FUDGE_FACTOR_IN_SECONDS) self.tfg.start() sleep(1/frequency+GDAPROCESSTIME) else: finder=Finder.getInstance() print "\nPlease start PSD collection from Mythen QT client ..." print " 1. select 'Gated' option in the 'Runs' box first" print " 2. then set 'Acquisition time' to %d, 'Repetitions' to %d" % (self.numGates, self.numFrames * self.numDefinedSequency*self.numCycles) print " 3. set 'Output Directory' to subdirector %s under 'processing' directory, 'File name root' to %d, 'Start index' to %d" % (finder.find("GDAMetadata").getMetadataValue("subdirectory"), self.scanNumber, 0) target = requestInput("Is PSD ready, Yes or No?") print str(target) if str(target)!="Yes": raise "Exiting program" for j in range(self.startCycleNumber,self.numCycles): self.pedata.reset() self.pedata.setCollectionNumber(j) #self.startDetector(frequency, self.scanNumber, j) for i in range(self.startSeqNumber, self.numDefinedSequency): GeneralCommands.pause() sleep(4.0) self.tfg.config_cycle_for_seq(i, self.numGates, 1) sleep(4.0) if self.adc.getMode()=="Trigger": print "enable adc sampling" self.adc.enable() #elif self.adc.getMode()=="Continuous": self.startPEDataStreamer(self.filename+"_pe_"+str(i)+".h5", 1/frequency*self.numGates+TIME_FUDGE_FACTOR_IN_SECONDS) self.tfg.start() sleep(1/frequency*self.numGates+GDAPROCESSTIME) except: self.stop() raise finally: print "close fast shutter %d" % time() self.fastshutter.moveTo("CLOSE") self.pedata.removeMonitors() print "collection completed at %d" % time()
"""Utility script to help manage BSL file conversion""" from gda.configuration.properties import LocalProperties from gda.factory import Finder from gda.observable import IObserver from uk.ac.diamond.daq.persistence.jythonshelf import LocalParameters from gda.data.metadata import GDAMetadataProvider BSL_CONVERSION_CONFIGURED = 'gda.scan.processing.bsl.configured' RUNNER = Finder.getInstance().find('bslConversion') class BslConversionUpdater(IObserver): def update(self, source, arg): print 'Visit changed to ' + str(arg) restore() if not LocalProperties.contains(BSL_CONVERSION_CONFIGURED): LocalProperties.set(BSL_CONVERSION_CONFIGURED, 'True') for meta in GDAMetadataProvider.getInstance().getMetadataEntries(): if meta.name == 'visit': break if meta: meta.addIObserver(BslConversionUpdater()) CONFIGURATION_FILE = 'bslUsers' DEFAULT = False STORE = LocalParameters.getXMLConfiguration(CONFIGURATION_FILE) def isConvertingOn(): """Check whether new files will be converted automatically"""
def setTitle(title): """ Command to set the title that is recorded in the scan file """ Finder.getInstance().find("GDAMetadata").setMetadataValue("title", title)
def getMeta(self): return Finder.getInstance().find("metashop").getMetaScannables() \ if self.readFromNexus else self.scannables_to_read
def _meta_ls(): """ Command to list the items to be put into the scan metadata. """ metashop=Finder.getInstance().find("metashop") return metashop.list(False)
def _meta_ll(): """ Command to list the items to be put into the scan metadata. The value of the items will also be listed """ metashop=Finder.getInstance().find("metashop") return metashop.list(True)
def testMCA(): beamline = Finder.getInstance().find("Beamline") return plotY("Point","Counts",beamline.getValue(ReturnType.DBR_NATIVE,"","-EA-DET-01:MCA-01:mca3"))
''' Created on 10 Oct 2014 @author: fy65 ''' from gda.device import Detector from gda.device.scannable import DummyScannable from gda.factory import Finder from gda.jython.commands.ScannableCommands import scan ds1=DummyScannable("ds1") NDR=0 CAL=1 calName=Finder.getInstance().find("calibrantName") dr=Finder.getInstance().find("datareduction") def ldescan(*args): MUSTADDDATAREDUCTIONATEND=False newargs=[] i=0 #processing 1st argument if (args[i] == NDR): i=1 if (isinstance(args[i], Detector)) : newargs.append(ds1) # @UndefinedVariable newargs.append(1.0) newargs.append(1.0) newargs.append(1.0) while i<len(args): newargs.append(args[i]) i=i+1
def getTitle(): """ Command to get the title that is recorded in the scan file """ return Finder.getInstance().find("GDAMetadata").getMetadataValue("title")