def runTransmission(acqEntries, configSetting): for seqIndex in range(len(acqEntries)): acqEntry = acqEntries[seqIndex] sampleEntry = samples[acqEntry['sample']] # Click if runnable if isRunTransmission(acqEntry['runId']): # Set sample quokka.setSample(sampleEntry['position'], sampleEntry['name'], sampleEntry['description'], sampleEntry['thickness'], isDriveSampleStage()) # Set transmission flag sics.set('transmissionflag', 1) sleep(0.1) # Set attenuation # Acquire data mode = configSetting['transmissionMode'] preset = configSetting['transmissionPreset'] updateTransmissionRunState(acqEntry['runId'], True) log('Start transmission run on ' + sampleEntry['name'] + ' ...') dataFile = scan(mode, dataType.HISTOGRAM_XY, preset, getForcedScanValue(sampleEntry['type'])) # Update data file name updateTransmissionRunState(acqEntry['runId'], False) updateTransmissionDetails(acqEntry['runId'], dataFile[-14:-7], getLambdaValue(), getAttValue(), getL1Value(), getL2Value()) # Print instrument state sleep(0.2) quokka.printQuokkaSettings()
def selBsxz(beamstop, bx, bz): # Get command controller sicsController = sics.getSicsController() commandController = sicsController.findComponentController( '/commands/beamstops/selbsxz') # Configuring command properties sics.hset(commandController, '/bs', beamstop) sics.hset(commandController, '/bx', bx) sics.hset(commandController, '/bz', bz) cnt = 0 while cnt < 20: try: commandController.syncExecute() break except SicsExecutionException, e: em = str(e.getMessage()) if em.__contains__('Interrupted'): raise e log('retry selecting beam stop ' + str(beamstop)) time.sleep(1) while not sicsController.getServerStatus().equals( ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.3) cnt += 1
def driveFlipper(value): # Clear interrupt flag sics.getSicsController().clearInterrupt() # Set timeout to 120 sec timeout = 120 counter = 0 # Set flipper sics.set('/instrument/flipper/set_flip_on', value) log('Driving flipper to ' + str(value) + "...") while True: flipperValue = sics.getValue('/instrument/flipper/flip_on').getIntData() # Test if value is set if flipperValue == value: log('Flipper is set to ' + str(flipperValue)) return else: # Check timeout if counter >= timeout: raise Exception('Failed to set flipper to ' + str(value)) # Check interrupt if sics.getSicsController().isInterrupted() == 1: raise Exception('SICS has been interrupted') # Otherwise sleep for 1 sec counter += 1 time.sleep(1)
def driveToLoadPosition(): log('Driving sample holder to load position') # Find soft upper limit upperlimit = sics.getValue('/sample/sample_x/softupperlim').getFloatData() # Use the soft lower limit as the load position loadPosition = math.floor(upperlimit) sics.drive('samx', loadPosition)
def selBs(beamstop): # Get command controller sicsController = sics.getSicsController() commandController = sicsController.findComponentController('/commands/beamstops/selbsn') # Configuring command properties timeout = 10 count = 0 sics.hset(commandController, '/bs', beamstop) while sics.getValue('/commands/beamstops/selbsn/bs').getIntData() != beamstop: time.sleep(0.1) count += 0.1 if count > timeout: raise Exception("Time out on receiving feedback on beam stop selection") cnt = 0 while cnt < 20: try: commandController.syncExecute(); break except SicsExecutionException, e: em = str(e.getMessage()) if em.__contains__('Interrupted'): raise e log('retry selecting beam stop ' + str(beamstop)) time.sleep(1) while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.3) cnt += 1
def driveSample(position): log('Driving sample holder to position ' + str(position) + ' ...') cur = sics.getValue('sampleNum').getFloatData() if abs(cur - position) < 0.01: log('sampleNum is already at ' + str(position)) return sicsController = sics.getSicsController() controller = sicsController.findComponentController(devices['sampleNum']) # controller.drive(position) cnt = 0 while cnt < 20: try: controller.drive(position) break except SicsExecutionException, e: em = str(e.getMessage()) if em.__contains__('Interrupted'): raise e time.sleep(0.6) log(str(e)) log('retry driving sampleNum') time.sleep(1) while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.3) cnt += 1 sics.handleInterrupt() cur = sics.getValue('sampleNum').getFloatData() if abs(cur - position) < 0.01: log('sampleNum is already at ' + str(position)) return
def driveGuide(guideConfig): # Set configuration sics.set('/commands/optics/guide/configuration', guideConfig.key) log('Moving guide to ' + guideConfig.key) sicsController = SicsCore.getSicsController() commandController = sicsController.findComponentController('/commands/optics/guide') # Setting of configuration and starting a command are committed to SICS via different communication channels # In order to make those in sync, we need to wait for the configuration to be settled. time.sleep(0.1) # Start command now cnt = 0 while cnt < 20: try: commandController.syncExecute(); break except SicsExecutionException, e: em = str(e.getMessage()) if em.__contains__('Interrupted'): raise e log('retry moving guide to ' + str(guideConfig.key)) time.sleep(1) while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.3) cnt += 1
def printQuokkaSettings(): datafile = sics.getValue('datafilename').getStringData() if ((datafile.find('QKK') != -1) and (datafile.find('.nx.hdf') != -1)): runNumber = (datafile.split('QKK')[1].split('.nx.hdf'))[0] else: runNumber = datafile msg = '\n' msg += "***** Quokka Instrument Settings *****\n" msg += '\n' msg += " Last Run Number: " + runNumber + '\n' msg += " Sample Name: " + sics.getValue('samplename').getStringData() + '\n' msg += '\n' msg += " Attenuator: %.2f degree" % getAttValue() + '\n' msg += " Entrance Aperature: %.2f" % getEntRotApValue() + '\n' msg += "Guide Configuration: " + getGuideConfig() + '\n' try: msg += " Sample Position: " + str(getSamplePosition()) + '\n' except: msg += " Sample Position: ???\n" # print " Beam Stop 1: " + getBsPosition(1) # print " Beam Stop 2: " + getBsPosition(2) # print " Beam Stop 3: " + getBsPosition(3) # print " Beam Stop 4: " + getBsPosition(4) # print " Beam Stop 5: " + getBsPosition(5) msg += " Beam Stop X: %.2f" % getBsxValue() + '\n' msg += " Beam Stop Z: %.2f" % getBszValue() + '\n' msg += " Detector Position: %.2f" %getDetPosition() + '\n' msg += " Detector Offset: %.2f" % getDetOffsetValue() + '\n' msg += '\n' msg += "****************************************\n" log(msg)
def run(deviceId, value): sicsController = getSicsController() device = sicsController.findDeviceController(deviceId) device.setTargetValue(ComponentData.createData(value)) device.commitTargetValue(None) handleInterrupt() logger.log("Run " + device.getPath() + " OK")
def slog(text, f_err = False): global __MSW_CONTEXT__ if "__MSW_CONTEXT__" in globals(): if not f_err: line = log(text, __MSW_CONTEXT__.getWriter()) else: line = log(text, __MSW_CONTEXT__.getErrorWriter()) else: if not f_err: print text else: print >> sys.stderr, text line = text global __LOG_FILES__ if "__LOG_FILES__" in globals(): for file in __LOG_FILES__: try: file.write(line) file.flush() except Exception, e: print >> sys.stderr, e
def count(mode, dataType, preset, force='true', saveType=saveType.save): controllerPath = '/commands/scan/runscan' sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) sics.execute('hset ' + controllerPath + '/scan_variable ' + deviceName, 'scan') sics.execute('hset ' + controllerPath + '/scan_start 0', 'scan') sics.execute('hset ' + controllerPath + '/scan_stop 0', 'scan') sics.execute('hset ' + controllerPath + '/numpoints 1', 'scan') if (scanMode.key == 'monitor'): sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan') else: sics.execute('hset ' + controllerPath + '/mode ' + scanMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'scan') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'scan') sics.execute('hset ' + controllerPath + '/force ' + force, 'scan') # repeat until successful while True: time.sleep(1) while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) scanController.syncExecute() break # Get output filename filenameController = sicsController.findDeviceController('datafilename') savedFilename = filenameController.getValue().getStringData() log('Saved to ' + savedFilename) return savedFilename
def bs_att(bs_num, bs_angle, att_num): if bs_num < 3 or bs_num > 5 : raise Exception, 'beam stop number ' + str(bs_num) + ' is not supported' if att_num < 0 or att_num > 5 : raise Exception, 'att position number ' + str(att_num) + ' is not supported' cur_bs3 = bs3() cur_bs4 = bs4() cur_bs5 = bs5() cur_att = att_pos() # Check if the current configuration has all beamstops out of position and the # empty attenuator position selected. If this is the case, put an attenuator # in (which will engage the fast shutter while doing so). # Should not ever happen, but best to check. if (cur_bs3 < 63.0 or cur_bs3 > 67.0) and (cur_bs4 < 63.0 or cur_bs4 > 67.0) \ and (cur_bs5 < 63.0 or cur_bs5 > 67.0) and cur_att == 3: log('put attenuator to 5 first') att_pos(5) # This is nominally the BS in position for all beamstops # Inserts a given beamstop and then remove all others. Then moves the attenuator. if bs_angle >= 63.0 and bs_angle <= 67.0 : log('put bs' + str(bs_num) + ' in') if bs_num == 3: sics.drive('bs3', bs_angle) sics.drive('bs4', 0) sics.drive('bs5', 0) elif bs_num == 4: sics.drive('bs4', bs_angle) sics.drive('bs3', 0) sics.drive('bs5', 0) elif bs_num == 5: sics.drive('bs5', bs_angle) sics.drive('bs3', 0) sics.drive('bs4', 0) log('put attenuator to ' + str(att_num)) att_pos(att_num) # If you are driving an attenuator in, do this first, then move the beam stop elif (bs_angle < 63.0 or bs_angle > 67.0) and att_num != 3 : log('put attenuator to ' + str(att_num)) att_pos(att_num) log('put bs' + str(bs_num) + ' in') if bs_num == 3: sics.drive('bs3', bs_angle) sics.drive('bs4', 0) sics.drive('bs5', 0) elif bs_num == 4: sics.drive('bs4', bs_angle) sics.drive('bs3', 0) sics.drive('bs5', 0) elif bs_num == 5: sics.drive('bs5', bs_angle) sics.drive('bs3', 0) sics.drive('bs4', 0) else: # Do not let the BS_Att command drive to an unsafe configuration raise Exception, 'No valid beamstop or attenuator has been selected no movement of beamstop or attempted'
def stopHistmem(): sicsController = sics.getSicsController() histmemController = sicsController.findComponentController( '/commands/histogram/histmem') log('stopping histmem ...') sics.execute('histmem stop') time.sleep(0.5)
def driveGuide(guideConfig): # Set configuration if hasattr(guideConfig, 'key'): guideConfig = guideConfig.key sics.set('/commands/optics/guide/configuration', guideConfig) log('Moving guide to ' + guideConfig) sicsController = SicsCore.getSicsController() commandController = sicsController.findComponentController('/commands/optics/guide') # Setting of configuration and starting a command are committed to SICS via different communication channels # In order to make those in sync, we need to wait for the configuration to be settled. time.sleep(0.1) # Start command now cnt = 0 while cnt < 20: try: commandController.syncExecute(); break except SicsExecutionException, e: em = str(e.getMessage()) if em.__contains__('Interrupted'): raise e log('retry moving guide to ' + str(guideConfig)) time.sleep(1) while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.3) cnt += 1
def set(name, value): controller = getDeviceController(name) if (controller == None): raise SicsError('Device / Path ' + name + ' not found') else: controller.setTargetValue(ComponentData.createData(value)) controller.commitTargetValue(None) logger.log('Set ' + name + ' OK')
def startHistmem(): # sicsController = sics.getSicsController() # histmemController = sicsController.findComponentController('/commands/histogram/histmem') # sics.hset(histmemController, '/mode', 'unlimited') log('starting histmem...') sics.execute('histmem mode unlimited') time.sleep(1.0) sics.execute('histmem start')
def scan(scanMode, dataType, preset, force="true", saveType=saveType.save): controllerPath = "/commands/scan/runscan" sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) # Configuring scan properties # sics.hset(scanController, '/scan_variable', DEVICE_SAMX) # sics.hset(scanController, '/scan_start', getSampleHolderPosition()) # sics.hset(scanController, '/scan_stop', getSampleHolderPosition()) # sics.hset(scanController, '/numpoints', 1) # # Hack to fix monitor selection in scan # if (scanMode.key == 'monitor'): # sics.hset(scanController, '/mode', 'MONITOR_1') # else: # sics.hset(scanController, '/mode', scanMode.key) # sics.hset(scanController, '/preset', preset) # sics.hset(scanController, '/datatype', dataType.key) # sics.hset(scanController, '/savetype', saveType.key) # sics.hset(scanController, '/force', force) sics.execute("hset " + controllerPath + "/scan_variable dummy_motor", "scan") sics.execute("hset " + controllerPath + "/scan_start 0", "scan") sics.execute("hset " + controllerPath + "/scan_stop 0", "scan") sics.execute("hset " + controllerPath + "/numpoints 1", "scan") if scanMode.key == "monitor": sics.execute("hset " + controllerPath + "/mode MONITOR_1", "scan") else: sics.execute("hset " + controllerPath + "/mode " + scanMode.key, "scan") sics.execute("hset " + controllerPath + "/preset " + str(preset), "scan") sics.execute("hset " + controllerPath + "/datatype " + dataType.key, "scan") sics.execute("hset " + controllerPath + "/savetype " + saveType.key, "scan") sics.execute("hset " + controllerPath + "/force " + force, "scan") # repeat until successful while True: # Wait 1 sec to make the setting settle time.sleep(1) while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) # Synchronously run scan if not hasTripped(): log("starting scan") scanController.syncExecute() if not hasTripped(): break # successful acquisition resetTrip() # Get output filename filenameController = sicsController.findDeviceController("datafilename") savedFilename = filenameController.getValue().getStringData() log("Saved to " + savedFilename) return savedFilename
def scan(scanMode, dataType, preset, force='true', saveType=saveType.save): controllerPath = '/commands/scan/runscan' sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) # Configuring scan properties # sics.hset(scanController, '/scan_variable', DEVICE_SAMX) # sics.hset(scanController, '/scan_start', getSampleHolderPosition()) # sics.hset(scanController, '/scan_stop', getSampleHolderPosition()) sics.hset(scanController, '/numpoints', 1) # # Hack to fix monitor selection in scan # if (scanMode.key == 'monitor'): # sics.hset(scanController, '/mode', 'MONITOR_1') # else: # sics.hset(scanController, '/mode', scanMode.key) sics.hset(scanController, '/preset', preset) # sics.hset(scanController, '/datatype', dataType.key) # sics.hset(scanController, '/savetype', saveType.key) sics.hset(scanController, '/force', force) sics.execute('hset /instrument/dummy_motor 0', 'general') sics.execute('hset /instrument/dummy_motor 1', 'scan') sics.execute('hset ' + controllerPath + '/scan_variable dummy_motor', 'scan') sics.execute('hset ' + controllerPath + '/scan_start 0', 'scan') sics.execute('hset ' + controllerPath + '/scan_stop 0', 'scan') sics.execute('hset ' + controllerPath + '/numpoints 1', 'scan') if (scanMode.key == 'monitor'): sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan') else: sics.execute('hset ' + controllerPath + '/mode ' + scanMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'scan') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'scan') sics.execute('hset ' + controllerPath + '/force ' + force, 'scan') sics.execute('hset /instrument/dummy_motor 2', 'general') sics.execute('hset /instrument/dummy_motor 3', 'scan') # Wait 1 sec to make the setting settle time.sleep(2) # Synchronously run scan scanController.syncExecute() sics.execute('hset /instrument/dummy_motor 4', 'general') sics.execute('hset /instrument/dummy_motor 5', 'scan') # Get output filename filenameController = sicsController.findDeviceController('datafilename') savedFilename = filenameController.getValue().getStringData() log('Saved to ' + savedFilename) return savedFilename
def scan(scanMode, dataType, preset, force='true', saveType=saveType.save): controllerPath = '/commands/scan/runscan' sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) # Configuring scan properties # sics.hset(scanController, '/scan_variable', DEVICE_SAMX) # sics.hset(scanController, '/scan_start', getSampleHolderPosition()) # sics.hset(scanController, '/scan_stop', getSampleHolderPosition()) # sics.hset(scanController, '/numpoints', 1) # # Hack to fix monitor selection in scan # if (scanMode.key == 'monitor'): # sics.hset(scanController, '/mode', 'MONITOR_1') # else: # sics.hset(scanController, '/mode', scanMode.key) # sics.hset(scanController, '/preset', preset) # sics.hset(scanController, '/datatype', dataType.key) # sics.hset(scanController, '/savetype', saveType.key) # sics.hset(scanController, '/force', force) sics.execute('hset /instrument/dummy_motor 0', 'general') sics.execute('hset /instrument/dummy_motor 1', 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'general') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'general') sics.execute('hset ' + controllerPath + '/force ' + force, 'general') sics.execute('hset ' + controllerPath + '/scan_variable dummy_motor', 'scan') sics.execute('hset ' + controllerPath + '/scan_start 0', 'scan') sics.execute('hset ' + controllerPath + '/scan_stop 0', 'scan') sics.execute('hset ' + controllerPath + '/numpoints 1', 'scan') if (scanMode.key == 'monitor'): sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan') else: sics.execute('hset ' + controllerPath + '/mode ' + scanMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'scan') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'scan') sics.execute('hset ' + controllerPath + '/force ' + force, 'scan') sics.execute('hset /instrument/dummy_motor 2', 'general') sics.execute('hset /instrument/dummy_motor 3', 'scan') # Wait 1 sec to make the setting settle time.sleep(2) # Synchronously run scan scanController.syncExecute() sics.execute('hset /instrument/dummy_motor 4', 'general') sics.execute('hset /instrument/dummy_motor 5', 'scan') # Get output filename filenameController = sicsController.findDeviceController('datafilename') savedFilename = filenameController.getValue().getStringData() log('Saved to ' + savedFilename) return savedFilename
def curtaind(val = None): if not val is None : if not _is_within_precision_('curtaind', val, .1): dhv('DOWN') sics.drive('curtaind', val) dhv('UP') else: log('curtaind is already at ' + str(val) + ', skipped') return sics.get_raw_value('curtaind')
def scan(scanMode, dataType, preset, force='true', saveType=saveType.save): controllerPath = '/commands/scan/runscan' sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) # Configuring scan properties # sics.hset(scanController, '/scan_variable', DEVICE_SAMX) # sics.hset(scanController, '/scan_start', getSampleHolderPosition()) # sics.hset(scanController, '/scan_stop', getSampleHolderPosition()) # sics.hset(scanController, '/numpoints', 1) # # Hack to fix monitor selection in scan # if (scanMode.key == 'monitor'): # sics.hset(scanController, '/mode', 'MONITOR_1') # else: # sics.hset(scanController, '/mode', scanMode.key) # sics.hset(scanController, '/preset', preset) # sics.hset(scanController, '/datatype', dataType.key) # sics.hset(scanController, '/savetype', saveType.key) # sics.hset(scanController, '/force', force) sics.execute('hset ' + controllerPath + '/scan_variable dummy_motor', 'scan') sics.execute('hset ' + controllerPath + '/scan_start 0', 'scan') sics.execute('hset ' + controllerPath + '/scan_stop 0', 'scan') sics.execute('hset ' + controllerPath + '/numpoints 1', 'scan') if (scanMode.key == 'monitor'): sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan') else: sics.execute('hset ' + controllerPath + '/mode ' + scanMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'scan') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'scan') sics.execute('hset ' + controllerPath + '/force ' + force, 'scan') # repeat until successful while True: # Wait 1 sec to make the setting settle time.sleep(1) while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) # Synchronously run scan if not hasTripped(): log("starting scan") scanController.syncExecute() if not hasTripped(): break; # successful acquisition resetTrip() # Get output filename filenameController = sicsController.findDeviceController('datafilename') savedFilename = filenameController.getValue().getStringData() log('Saved to ' + savedFilename) return savedFilename
def curtaind(val=None): if not val is None: if not _is_within_precision_('curtaind', val, .1): dhv('DOWN') sics.drive('curtaind', val) dhv('UP') else: log('curtaind is already at ' + str(val) + ', skipped') return sics.get_raw_value('curtaind')
def driveAtt(value): """ Do something very hard """ while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.2) log("Driving attenuator to " + str(value) + " degree ...") time.sleep(0.2) sics.drive("att", value) log("Attenuator is now at " + str(getAttValue()) + " degree")
def driveAtt(value): """ Do something very hard """ while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.2) log('Driving attenuator to ' + str(value) + ' degree ...') time.sleep(0.2) sics.drive('att', value) log('Attenuator is now at ' + str(getAttValue()) + ' degree')
def driveHistmem(hmMode, preset): sicsController = sics.getSicsController() histmemController = sicsController.findComponentController('/commands/histogram/histmem') sics.hset(histmemController, '/mode', hmMode.key) sics.hset(histmemController, '/preset', preset) sics.hset(histmemController, '/cmd', 'start') log('Start histmem ...') histmemController.syncExecute() time.sleep(0.8) log('Histmem stopped')
def driveHistmem(hmMode, preset): sicsController = sics.getSicsController() histmemController = sicsController.findComponentController( '/commands/histogram/histmem') sics.hset(histmemController, '/mode', hmMode.key) sics.hset(histmemController, '/preset', preset) sics.hset(histmemController, '/cmd', 'start') log('Start histmem ...') histmemController.syncExecute() time.sleep(0.8) log('Histmem stopped')
def runscan(type, scan_variable, scan_start, scan_increment, NP, mode, preset, channel): # Initialisation clearInterrupt() sicsController = getSicsController() scanController = sicsController.findComponentController('/commands/scan/' + type) hset(scanController, '/scan_variable', scan_variable) hset(scanController, '/scan_start', scan_start) hset(scanController, '/scan_increment', scan_increment) hset(scanController, '/NP', NP) hset(scanController, '/mode', mode) hset(scanController, '/preset', preset) hset(scanController, '/channel', channel) # Monitor status while (scanController.getCommandStatus().equals(CommandStatus.BUSY)): # Don't do anything before scan is ready time.sleep(0.1) # Run scan logger.log('Scan started') scanController.asyncExecute() # Monitor initial status change timeOut = False counter = 0 while (scanController.getStatusDirtyFlag() == False): time.sleep(0.1) counter += 0.1 if (counter >= 1): timeOut = True logger.log('Time out on running scan') break # Enter into normal sequence if (timeOut == False): scanpoint = -1 scanPointController = sicsController.findComponentController( scanController, '/feedback/scanpoint') countsController = sicsController.findComponentController( scanController, '/feedback/counts') logger.log(' NP ' + '\t' + ' Counts') while (scanController.getCommandStatus().equals(CommandStatus.BUSY)): currentPoint = scanPointController.getValue().getIntData() if ((scanpoint == -1 and currentPoint == 0) or (scanpoint != -1 and currentPoint != scanpoint)): scanpoint = currentPoint logger.log( '%4d \t %d' % (scanpoint, countsController.getValue().getIntData())) time.sleep(0.1) logger.log('Scan completed') handleInterrupt()
def driveToLoadPosition(): log("Driving sample holder to load position") # Find soft upper limit upperlimit = sics.getValue("/sample/sample_x/softupperlim").getFloatData() hardlimit = sics.getValue("/sample/sample_x/hardupperlim").getFloatData() softzero = sics.getValue("/sample/sample_x/softzero").getFloatData() if upperlimit > hardlimit - softzero: upperlimit = hardlimit - softzero # Use the soft lower limit as the load position loadPosition = math.floor(upperlimit) sics.drive("samx", loadPosition)
def driveHistmem(hmMode, preset): controllerPath = "/commands/histogram/histmem" sicsController = sics.getSicsController() histmemController = sicsController.findComponentController(controllerPath) sics.execute("hset " + controllerPath + "/mode " + hmMode.key, "scan") sics.execute("hset " + controllerPath + "/preset " + str(preset), "scan") sics.execute("hset " + controllerPath + "/cmd start", "scan") log("Start histmem ...") time.sleep(0.5) histmemController.syncExecute() time.sleep(0.8) log("Histmem stopped")
def driveHistmem(hmMode, preset): controllerPath = '/commands/histogram/histmem' sicsController = sics.getSicsController() histmemController = sicsController.findComponentController(controllerPath) sics.execute('hset ' + controllerPath + '/mode ' + hmMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/cmd start', 'scan') log('Start histmem ...') time.sleep(0.5) histmemController.syncExecute() time.sleep(0.8) log('Histmem stopped')
def driveGuide(guideConfig): # Set configuration sics.set('/commands/optics/guide/configuration', guideConfig.key) log('Moving guide to ' + guideConfig.key) sicsController = SicsCore.getSicsController() commandController = sicsController.findComponentController('/commands/optics/guide') # Setting of configuration and starting a command are committed to SICS via different communication channels # In order to make those in sync, we need to wait for the configuration to be settled. time.sleep(0.1) # Start command now commandController.syncExecute(); log('Guide is moved to ' + getGuideConfig())
def get_raw_feedback(comm): global __time_out__ __count__ = 0 comm_str = str(comm) while __count__ < __time_out__: try: item = run_command(comm_str, True) return str(item) except: __count__ += 0.2 time.sleep(0.2) logger.log('time out in running ' + comm_str) return None
def run_command_timeout(cmd, use_full_feedback=False, timeout=None): logger.log('using timeout command') call_back = __SICS_Callback__(use_full_feedback) SicsCore.getDefaultProxy().send(cmd, call_back) acc_time = 0 while call_back.__status__ is None and (timeout is None or acc_time < timeout): # while call_back.__status__ is None: time.sleep(0.2) acc_time += 0.2 if call_back.__status__ is None: raise Exception, 'time out in running the command' return call_back.__status__
def driveGuide(guideConfig): # Set configuration sics.set('/commands/optics/guide/configuration', guideConfig.key) log('Moving guide to ' + guideConfig.key) sicsController = SicsCore.getSicsController() commandController = sicsController.findComponentController( '/commands/optics/guide') # Setting of configuration and starting a command are committed to SICS via different communication channels # In order to make those in sync, we need to wait for the configuration to be settled. time.sleep(0.1) # Start command now commandController.syncExecute() log('Guide is moved to ' + getGuideConfig())
def check_nvs_lambda(self, val): timeout = 600 interval = 2 count = 0 while count < timeout : try: cur = sics.get_raw_value('nvs_lambda') if sics.isInterrupt(): break # pre = sics.get_raw_value('nvs_lambda precision') pre = 0.1 if abs(cur - val) < pre: log('wavelength is ' + str(cur)) return True else: try: time.sleep(interval) count += interval except KeyboardInterrupt as ei: log('Interrupted') raise Exception, 'interrupted' break; except: try: time.sleep(interval) count += interval except KeyboardInterrupt as ei: log('Interrupted') raise Exception, 'interrupted' break; if sics.isInterrupt(): sics.clearInterrupt() raise Exception, 'interrupted' sics.execute('stopexe nvs_lambda') log('WARNING: timeout in driving nvs_lambda, but choose to continue.')
def setSafeAttenuation(startingAttenuation=330): local_rate = 0 global_rate = 0 previousLocalRate = 0 previousGlobalRate = 0 startLevel = attenuationLevels.index(startingAttenuation) # Hack: need to reset and run histmem log('set safe attenuation...') # loop from the safe range of attenuation for level in xrange(startLevel, len(attenuationLevels)): # drive the attenuator driveAtt(attenuationLevels[level]) # count bin rate local_rate, global_rate = determineAveragedRates(max_samples=5, log_success=False) log('local rate = ' + str(local_rate)) log('global rate = ' + str(global_rate)) # Too much (check both local and global rate) if ((local_rate > local_rateSafe) or (global_rate > global_rateSafe)): if (level > 0): # [GUMTREE-378] Ensure SICS is ready after count while not sics.getSicsController().getServerStatus().equals( ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) # Brings it back to one step driveAtt(attenuationLevels[level - 1]) local_rate = previousLocalRate global_rate = previousGlobalRate break # Within tolerance elif (local_rate >= local_rateSafe / 2) or (global_rate >= global_rateSafe / 2): log('exit loop') break previousLocalRate = local_rate previousGlobalRate = global_rate # Ensure SICS is ready after count while not sics.getSicsController().getServerStatus().equals( ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) # Print info at the end log('Attenuation is set to ' + str(getAttValue()) + ' degree with bin rate ' + str(local_rate))
def scan10(sample_position, collect_time, sample_name = None): global __sampleMap__, __sampleNum__ if sample_position < 1 or sample_position > 10: raise Exception, 'Invalid sample position, scan not run. Choose a position between 1 and 10 inclusive.' else: if not sample_name is None: sics.execute('samplename ' + str(sample_name), 'scan') cur_samx = __sampleMap__[__sampleNum__][sample_position] # cur_samx = samx() time.sleep(1) log("Collection time set to " + str(collect_time) + " seconds") # sics.execute('histmem mode time') # sics.execute('histmem preset ' + str(collect_time)) # time.sleep(1) log("Data collection for sample " + sample_name + " started") # sics.execute("histmem start") # sicsController = sics.getSicsController() # while not sicsController.getServerStatus().equals(ServerStatus.COUNTING): # time.sleep(0.3) # while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): # time.sleep(0.3) # time.sleep(1) # sics.execute('newfile HISTOGRAM_XYT') # time.sleep(1) # log("Saving data") # sics.execute('save') scan('samx', cur_samx, cur_samx, 1, scanMode.time, dataType.HISTOGRAM_XYT, collect_time) time.sleep(2) log(sics.get_base_filename() + ' updated') log("Scan completed") if not sample_name is None: sics.execute('samplename {}', 'scan')
def scan10(sample_position, collect_time, sample_name=None): global __sampleMap__, __sampleNum__ if sample_position < 1 or sample_position > 10: raise Exception, 'Invalid sample position, scan not run. Choose a position between 1 and 10 inclusive.' else: if not sample_name is None: sics.execute('samplename ' + str(sample_name), 'scan') cur_samx = __sampleMap__[__sampleNum__][sample_position] # cur_samx = samx() time.sleep(1) log("Collection time set to " + str(collect_time) + " seconds") # sics.execute('histmem mode time') # sics.execute('histmem preset ' + str(collect_time)) # time.sleep(1) log("Data collection for sample " + sample_name + " started") # sics.execute("histmem start") # sicsController = sics.getSicsController() # while not sicsController.getServerStatus().equals(ServerStatus.COUNTING): # time.sleep(0.3) # while not sicsController.getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): # time.sleep(0.3) # time.sleep(1) # sics.execute('newfile HISTOGRAM_XYT') # time.sleep(1) # log("Saving data") # sics.execute('save') scan('samx', cur_samx, cur_samx, 1, scanMode.time, dataType.HISTOGRAM_XYT, collect_time) time.sleep(2) log(sics.get_base_filename() + ' updated') log("Scan completed") if not sample_name is None: sics.execute('samplename {}', 'scan')
def resetTrip(): #print >> sys.stderr, '!!! detector tripped !!!' log('!!! detector tripped !!!') # drive to higher attenuation if getAttValue() < 330: log('adjusting attenuation') driveAtt(getAttValue() + 30) # reset fast shutter # raise Exception('detector tripped - reset not supported') sics.execute('hset ' + reset_trip + ' 1') time.sleep(20)
def test_logger(self): # Setup writer stringWriter = StringWriter() pyFileWriter = PyFileWriter(stringWriter) oldWriter = sys.stdout sys.stdout = pyFileWriter # Run logger.log('123') output = stringWriter.toString() sys.stdout = oldWriter # Assert self.assertTrue(output.index('123') > 0)
def scan(deviceName, start, stop, numpoints, scanMode, dataType, preset, force='true', saveType=saveType.save): controllerPath = '/commands/scan/runscan' sicsController = sics.getSicsController() scanController = sicsController.findComponentController(controllerPath) sics.execute('hset ' + controllerPath + '/scan_variable ' + deviceName, 'scan') sics.execute('hset ' + controllerPath + '/scan_start ' + str(start), 'scan') sics.execute('hset ' + controllerPath + '/scan_stop ' + str(stop), 'scan') sics.execute('hset ' + controllerPath + '/numpoints ' + str(numpoints), 'scan') if (scanMode.key == 'monitor'): sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan') else: sics.execute('hset ' + controllerPath + '/mode ' + scanMode.key, 'scan') sics.execute('hset ' + controllerPath + '/preset ' + str(preset), 'scan') sics.execute('hset ' + controllerPath + '/datatype ' + dataType.key, 'scan') sics.execute('hset ' + controllerPath + '/savetype ' + saveType.key, 'scan') sics.execute('hset ' + controllerPath + '/force ' + force, 'scan') # repeat until successful while True: time.sleep(1) while not sics.getSicsController().getServerStatus().equals( ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) scanController.syncExecute() break # Get output filename filenameController = sicsController.findDeviceController('datafilename') savedFilename = filenameController.getValue().getStringData() log('Saved to ' + savedFilename) return savedFilename
def driveBs(ids, action): # Wrap input as list if type(ids) != type([]): ids = [ids] # Loop thru each beam stop for id in ids: if action.key == 'up': log('Driving bs' + str(id) + ' up ...') bsList[id - 1].up() log('bs' + str(id) + ' is now in ' + getBsPosition(id)) elif action.key == 'down': log('Driving bs' + str(id) + ' down ...') bsList[id - 1].down() log('bs' + str(id) + ' is now in ' + getBsPosition(id)) else: log('Cannot driving bs' + str(id) + ' to ' + str(action))
def __setattr__(self, name, value): if name == 'att' and value != 330 and not value is None: log('att can not be changed; use 330 instead') return if name == 'bs' and not value is None: if value < 1 or value > 6: self.clear() raise Exception, 'beamstop selection must be an integer from 1 to 6' if name == 'guide': if hasattr(value, 'key'): value = value.key if not ConfigSystem._property_list.__contains__(name): raise Exception, 'property not allowed: ' + str(name) self.__dict__[name] = value if name != '__is_dirty__' and value != None: self.__dict__['__is_dirty__'] = True
def driveBs(ids, action): # Wrap input as list if type(ids) != type([]): ids = [ids] # Loop thru each beam stop for id in ids: if action.key == "up": log("Driving bs" + str(id) + " up ...") bsList[id - 1].up() log("bs" + str(id) + " is now in " + getBsPosition(id)) elif action.key == "down": log("Driving bs" + str(id) + " down ...") bsList[id - 1].down() log("bs" + str(id) + " is now in " + getBsPosition(id)) else: log("Cannot driving bs" + str(id) + " to " + str(action))
def driveSafeAttenuation(override=False, startingAttenuation=330): if override: # Use traditional method setSafeAttenuation(startingAttenuation) else: # Find safe attenuation value att = findSafeAttenuation(startingAttenuation) if att is not None: while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE): time.sleep(0.1) driveAtt(att) time.sleep(3) while hasTripped(): resetTrip() local_rate, global_rate = determineAveragedRates(max_samples=3, log_success=False) log('local rate = ' + str(local_rate)) log('global rate = ' + str(global_rate))