Example #1
0
    def test_dhv1(self, key):
        # Test drive
        startingValue = getDhv1Value()
        precision = 20
        log("Test drive dhv1 to " + key + " ...")
        sics.getSicsController().clearInterrupt()
        sics.execute("dhv1 " + key)
        # Wait for 6 sec
        time.sleep(6)
        hasInterrupted = sics.getSicsController().isInterrupted() == 1
        # Stop test drive
        log("Stopping test drive")
        sics.execute("INT1712 3")
        time.sleep(1)
        currentValue = getDhv1Value()
        # Don't go any further if someone has interrrupted the test drive
        if hasInterrupted:
            #            log('Test drive was interrupted')
            raise Exception, "dhv1 " + key + " interrupted"
        #            print ('currentValue: ' + str(currentValue) + ', startingValue: ' +  str(startingValue));
        # Test if the current value is within the precision (more than half of voltage step size, which is about half of 30V)
        if (startingValue + precision >= currentValue) and (startingValue - precision <= currentValue):
            log("Dhv1 needs to be reset")
            sics.execute("dhv1 reset")
            time.sleep(1)

        # Actual drive
        sics.getSicsController().clearInterrupt()
Example #2
0
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
Example #3
0
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)
Example #4
0
def driveDet(position, offset):
    # Tolerance: 5mm and 1mm
    precision = 5
    offsetPrecision = 1
    shouldDrive = (position > getDetPosition() + precision) or (
        position < getDetPosition() - precision)
    shouldDrive = (shouldDrive) or (
        (offset > getDetOffsetValue() + offsetPrecision) or
        (offset < getDetOffsetValue() - offsetPrecision))
    # Drive det only if we needed to
    if shouldDrive:
        driveDhv1(action.down)
        log('Driving detector to ' + str(position) + ' mm ...')
        while not sics.getSicsController().getServerStatus().equals(
                ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
        sics.drive('det', position)
        while not sics.getSicsController().getServerStatus().equals(
                ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
        log('Driving detector offset to ' + str(position) + ' mm ...')
        driveDetOffset(offset)
        while not sics.getSicsController().getServerStatus().equals(
                ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
    # Always set voltage up regardless if it is in position or not
    driveDhv1(action.up)
    log('Detector is now at ' + str(getDetPosition()) + 'mm with offset ' +
        str(getDetOffsetValue()) + 'mm')
Example #5
0
    def test_dhv1(self, key):
        # Test drive
        startingValue = getDhv1()
        precision = 20
        log('Test drive dhv1 to ' + key + ' ...')
        sics.getSicsController().clearInterrupt()
        sics.execute('dhv1 ' + key)
        # Wait for 6 sec
        time.sleep(6)
        hasInterrupted = sics.getSicsController().isInterrupted() == 1
        # Stop test drive
        log('Stopping test drive')
        sics.execute('INT1712 3')
        time.sleep(1)
        currentValue = getDhv1()
        # Don't go any further if someone has interrrupted the test drive
        if hasInterrupted:
            #            log('Test drive was interrupted')
            raise Exception, 'dhv1 ' + key + ' interrupted'
#            print ('currentValue: ' + str(currentValue) + ', startingValue: ' +  str(startingValue));
# Test if the current value is within the precision (more than half of voltage step size, which is about half of 30V)
        if (startingValue + precision >=
                currentValue) and (startingValue - precision <= currentValue):
            log('Dhv1 needs to be reset')
            sics.execute('dhv1 reset')
            time.sleep(1)

        # Actual drive
        sics.getSicsController().clearInterrupt()
Example #6
0
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)
Example #7
0
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
Example #8
0
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
Example #9
0
def waitUntilSicsIs(status, dt=0.2):
    repeat = True
    while repeat:
        sics.handleInterrupt()

        while not sics.getSicsController().getServerStatus().equals(status):
            time.sleep(dt)

        time.sleep(dt)
        repeat = not sics.getSicsController().getServerStatus().equals(status)

    sics.handleInterrupt()
Example #10
0
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))
Example #11
0
File: bilby.py Project: nxi/gumtree
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
Example #12
0
def run_action(act):
    act.set_running_status()
    try:
        exec(act.command)
        act.set_done_status()
#    except Exception, e:
#        raise e
    except:
        if sics.getSicsController() != None: 
            act.set_interrupt_status()
        act.set_error_status()
        traceback.print_exc(file = sys.stdout)
        raise Exception, 'Error in running <' + act.text + '>'
    if sics.getSicsController() != None:
        sics.handleInterrupt()
Example #13
0
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
Example #14
0
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
Example #15
0
def stopHistmem():
    sicsController = sics.getSicsController()
    histmemController = sicsController.findComponentController(
        '/commands/histogram/histmem')
    log('stopping histmem ...')
    sics.execute('histmem stop')
    time.sleep(0.5)
Example #16
0
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
Example #17
0
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
Example #18
0
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
Example #19
0
def driveDhv1(action):
    # Don't drive if it is already in position
    startingValue = getDhv1Value()
    if (action.key == 'up'
            and startingValue >= 2350.0) or (action.key == 'down'
                                             and startingValue == 0.0):
        log('dhv1 is now at ' + str(startingValue) + ', no action is required')
        return

    # Test drive
    log('Test drive dhv1 to ' + action.key + ' ...')
    sics.getSicsController().clearInterrupt()
    sics.execute('dhv1 ' + action.key)
    # Wait for 6 sec
    time.sleep(6)
    hasInterrupted = sics.getSicsController().isInterrupted() == 1
    # Stop test drive
    log('Stopping test drive')
    sics.execute('INT1712 3')
    time.sleep(1)
    currentValue = getDhv1Value()
    # Don't go any further if someone has interrrupted the test drive
    if hasInterrupted:
        #        log('Test drive was interrupted')
        raise Exception


#    print ('currentValue: ' + str(currentValue) + ', startingValue: ' +  str(startingValue));
# Test if the current value is within the precision (more than half of voltage step size, which is about half of 30V)
    precision = 20
    if (startingValue + precision >=
            currentValue) and (startingValue - precision <= currentValue):
        log('Dhv1 needs to be reset')
        sics.execute('dhv1 reset')
        time.sleep(1)

    # Actual drive
    sics.getSicsController().clearInterrupt()
    log('Driving dhv1 to ' + action.key + ' ...')
    if action.key == 'up':
        dhv1.up()
    elif action.key == 'down':
        dhv1.down()
    elif action.key == 'reset':
        dhv1.reset()
    log('dhv1 is now at ' + str(getDhv1Value()))
Example #20
0
def checkedDrive(motor, value, useController=False):
    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    if useController:
        controller = sics.getSicsController().findComponentController(motor)
        controller.drive(value)
    else:
        sics.drive(motor, value)
Example #21
0
 def getter():
     if useController:
         controller = sics.getSicsController().findComponentController(path)
         return controller.getValue().getIntData()
     elif useRaw:
         return int(sics.get_raw_value(path))
     else:
         return sics.getValue(path).getIntData()
Example #22
0
def checkedDrive(motor, value, useController=False):
    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    if useController:
        controller = sics.getSicsController().findComponentController(motor)
        controller.drive(value)
    else:
        sics.drive(motor, value)
Example #23
0
 def getter():
     if useController:
         controller = sics.getSicsController().findComponentController(path)
         return controller.getValue().getStringData()
     elif useRaw:
         return str(sics.get_raw_value(path))
     else:
         return sics.getValue(path).getStringData()
Example #24
0
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
Example #25
0
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))
Example #26
0
def run_action(act):
    act.set_running_status()
    try:
        exec(act.command)
        act.set_done_status()
    except Exception, e:
        if sics.getSicsController() != None:
            act.set_interrupt_status()
        raise Exception, e.message
Example #27
0
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
Example #28
0
def run_action(act):
    act.set_running_status()
    try:
        exec(act.command)
        act.set_done_status()


#    except Exception, e:
#        raise e
    except:
        if sics.getSicsController() != None:
            act.set_interrupt_status()
        act.set_error_status()
        traceback.print_exc(file=sys.stdout)
        raise Exception, 'Error in running <' + act.text + '>'
    if not act.no_interrupt_check == 'True':
        if sics.getSicsController() != None:
            sics.handleInterrupt()
Example #29
0
 def getter():
     if useController:
         controller = sics.getSicsController().findComponentController(path)
         if refresh:
             controller.getValue(True)
         return controller.getValue().getFloatData()
     elif useRaw:
         return float(sics.get_raw_value(path))
     else:
         return sics.getValue(path, refresh).getFloatData()
Example #30
0
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")
Example #31
0
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')
Example #32
0
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')
Example #33
0
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')
Example #34
0
def driveToSamplePosition(position):
    if state.sample_stage == SAMPLE_STAGE.fixed:
        slog('fixed sample stage cannot be driven to %s' % position)
        return

    # drive to position
    slog('Driving sample holder to position %s ...' % position)

    if state.sample_stage == SAMPLE_STAGE.manual:
        checkedDrive('samx', position)
        return

    if state.sample_stage != SAMPLE_STAGE.lookup:
        raise Exception('unexpected sample stage configuration')

    sicsController = sics.getSicsController()
    controller = sicsController.findComponentController('/sample/sampleNum')

    counter = 0
    position = int(position)
    tolerance = 0.1
    while True:
        try:
            counter += 1

            waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)
            sics.handleInterrupt()

            controller.drive(position)
            sics.handleInterrupt()

            break

        except (Exception, SicsExecutionException) as e:
            if isInterruptException(e) or (counter >= 20):
                raise

            if abs(controller.getValue(True).getFloatData() -
                   position) <= tolerance:
                break

            slog('Retry driving sampleNum')
            time.sleep(1)

    # wait until
    for counter in xrange(10):
        if abs(controller.getValue(True).getFloatData() -
               position) > tolerance:
            time.sleep(0.1)
        else:
            break

    slog('Position of sample holder: %s' %
         controller.getValue(True).getFloatData())
Example #35
0
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')
Example #36
0
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)
Example #37
0
def driveDhv1(action):
    # Don't drive if it is already in position
    startingValue = getDhv1Value()
    if (action.key == 'up' and startingValue >= 2350.0) or (action.key == 'down' and startingValue == 0.0):
        log('dhv1 is now at ' + str(startingValue) + ', no action is required')
        return
    
    # Test drive
    log('Test drive dhv1 to ' + action.key + ' ...')
    sics.getSicsController().clearInterrupt()
    sics.execute('dhv1 ' + action.key)
    # Wait for 6 sec
    time.sleep(6)
    hasInterrupted = sics.getSicsController().isInterrupted() == 1
    # Stop test drive
    log('Stopping test drive')
    sics.execute('INT1712 3')
    time.sleep(1)
    currentValue = getDhv1Value()
    # Don't go any further if someone has interrrupted the test drive
    if hasInterrupted:
#        log('Test drive was interrupted')
        raise Exception
#    print ('currentValue: ' + str(currentValue) + ', startingValue: ' +  str(startingValue));
    # Test if the current value is within the precision (more than half of voltage step size, which is about half of 30V)
    precision = 20
    if (startingValue + precision >= currentValue) and (startingValue - precision <= currentValue):
        log('Dhv1 needs to be reset')
        sics.execute('dhv1 reset')
        time.sleep(1)
    
    # Actual drive
    sics.getSicsController().clearInterrupt()
    log('Driving dhv1 to ' + action.key + ' ...')
    if action.key == 'up':
        dhv1.up()
    elif action.key == 'down':
        dhv1.down()
    elif action.key == 'reset':
        dhv1.reset()
    log('dhv1 is now at ' + str(getDhv1Value()))
Example #38
0
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')
Example #39
0
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")
Example #40
0
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')
Example #41
0
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)
Example #42
0
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)
    
    # Synchronously run command
    commandController.syncExecute()
Example #43
0
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)

    # Synchronously run command
    commandController.syncExecute()
Example #44
0
def driveDet(position, offset):
    # Tolerance: 5mm and 1mm
    precision = 5
    offsetPrecision = 1
    shouldDrive = (position > getDetPosition() + precision) or (position < getDetPosition() - precision)
    shouldDrive = (shouldDrive) or ((offset > getDetOffsetValue() + offsetPrecision) or (offset < getDetOffsetValue() - offsetPrecision))
    # Drive det only if we needed to
    if shouldDrive:
        driveDhv1(action.down)
        log('Driving detector to ' + str(position) + ' mm ...')
        while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
        sics.drive('det', position)
        while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
        log('Driving detector offset to ' + str(position) + ' mm ...')
        driveDetOffset(offset)
        while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
            time.sleep(0.1)
    # Always set voltage up regardless if it is in position or not
    driveDhv1(action.up)
    log('Detector is now at ' + str(getDetPosition()) + 'mm with offset ' + str(getDetOffsetValue()) + 'mm')
Example #45
0
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")
    # Synchronously run command
    commandController.syncExecute()
Example #46
0
def waitUntilSicsIs(status, dt=0.2):
    controller = sics.getSicsController()
    timeout = 5
    while True:
        sics.handleInterrupt()

        count = 0
        while not controller.getServerStatus().equals(status) and count < timeout:
            time.sleep(dt)
            count += dt
        
        if controller.getServerStatus().equals(status):
            break
        else:
            controller.refreshServerStatus()

    sics.handleInterrupt()
Example #47
0
def driveGuide(value):
    if value not in GUIDE_CONFIG:
        slog('[WARNING] unknown guide configuration: ' + value)

    # set target configuration
    sics.set('/commands/optics/guide/configuration', value)

    if getGuideConfig() == value:
        slog('Guide was already moved to %s (no action is required)' % value)
        return

    slog('Moving guide to ' + value)

    sicsController = sics.getSicsController()
    controller = 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 settle
    time.sleep(0.5)

    counter = 0
    while True:
        try:
            counter += 1

            waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)
            sics.handleInterrupt()

            timeout = datetime.now() + timedelta(minutes=5)
            controller.syncExecute()

            while (getGuideConfig() != value) and (datetime.now() < timeout):
                sleep(0.5)

            break

        except (Exception, SicsExecutionException) as e:
            if isInterruptException(e) or (counter >= 20):
                raise

            slog(str(e), f_err=True)
            slog('Retry moving guide')
            time.sleep(1)

    slog('Guide is moved to ' + getGuideConfig())
Example #48
0
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))
Example #49
0
def driveToLoadPosition():
    if state.sample_stage == SAMPLE_STAGE.fixed:
        slog('fixed sample stage cannot be driven to load position')
        return

    slog('Driving sample holder to load position ...')
    samx = sics.getSicsController().findDeviceController('samx')

    tolerance     = samx.getChildController('/precision').getValue().getFloatData()
    soft_zero     = samx.getChildController('/softzero').getValue().getFloatData()
    soft_upperlim = samx.getChildController('/softupperlim').getValue().getFloatData()
    hard_upperlim = samx.getChildController('/hardupperlim').getValue().getFloatData()

    if soft_upperlim > hard_upperlim - soft_zero:
        soft_upperlim = hard_upperlim - soft_zero

    checkedDrive('samx', soft_upperlim - tolerance)

    slog('Sample holder is now at load position')
Example #50
0
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")
    # Synchronously run command
    commandController.syncExecute()
Example #51
0
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))
Example #52
0
def syncScan(controllerPath):
    # configuring scan properties
    sics.execute('hset ' + controllerPath + '/datatype ' + 'HISTOGRAM_XY', 'scan')
    sics.execute('hset ' + controllerPath + '/savetype ' + 'save'        , 'scan')
    sics.execute('hset ' + controllerPath + '/force '    + 'true'        , 'scan')

    # dummy 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')

    # wait to make the settings settle
    time.sleep(1)
    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    # synchronously run scan
    sicsController = sics.getSicsController()
    scanController = sicsController.findComponentController(controllerPath)
    scanController.syncExecute()
Example #53
0
def driveToLoadPosition():
    if state.sample_stage == SAMPLE_STAGE.fixed:
        slog('fixed sample stage cannot be driven to load position')
        return

    slog('Driving sample holder to load position ...')
    samx = sics.getSicsController().findDeviceController('samx')

    tolerance = samx.getChildController('/precision').getValue().getFloatData()
    soft_zero = samx.getChildController('/softzero').getValue().getFloatData()
    soft_upperlim = samx.getChildController(
        '/softupperlim').getValue().getFloatData()
    hard_upperlim = samx.getChildController(
        '/hardupperlim').getValue().getFloatData()

    if soft_upperlim > hard_upperlim - soft_zero:
        soft_upperlim = hard_upperlim - soft_zero

    checkedDrive('samx', soft_upperlim - tolerance)

    slog('Sample holder is now at load position')
Example #54
0
def syncScan(controllerPath):
    # configuring scan properties
    sics.execute('hset ' + controllerPath + '/datatype ' + 'HISTOGRAM_XY',
                 'scan')
    sics.execute('hset ' + controllerPath + '/savetype ' + 'save', 'scan')
    sics.execute('hset ' + controllerPath + '/force ' + 'true', 'scan')

    # dummy 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')

    # wait to make the settings settle
    time.sleep(1)
    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    # synchronously run scan
    sicsController = sics.getSicsController()
    scanController = sicsController.findComponentController(controllerPath)
    scanController.syncExecute()
Example #55
0
def selBsHelper(beamstop, bx, bz, controller):
    # get command controller
    sicsController = sics.getSicsController()
    commandController = sicsController.findComponentController(controller)

    # configuring command properties
    if bx is not None:
        sics.hset(commandController, '/bx', bx)
    if bz is not None:
        sics.hset(commandController, '/bz', bz)

    sics.hset(commandController, '/bs', beamstop)

    count = 0
    while getIntData(controller + '/bs') != beamstop:
        time.sleep(0.1)
        count += 1
        if count > 100:
            raise Exception('Time out on receiving feedback on beam stop selection')

    count = 0
    while True:
        try:
            count += 1
            slog('run beamstop selecting command ...')
            commandController.syncExecute()
            break

        except (Exception, SicsExecutionException) as e:
            if isInterruptException(e) or (count >= 20):
                raise

            slog('Retry selecting beam stop %s' % beamstop)
            time.sleep(1)
            waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    slog('beam stop is %s' % beamstop)
Example #56
0
def driveGuide(value):
    if value not in GUIDE_CONFIG:
        slog('[WARNING] unknown guide configuration: ' + value)

    # set target configuration
    sics.set('/commands/optics/guide/configuration', value)

    slog('Moving guide to ' + value)

    sicsController = sics.getSicsController()
    controller = 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 settle
    time.sleep(0.5)

    counter = 0
    while True:
        try:
            counter += 1

            waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)
            sics.handleInterrupt()

            controller.syncExecute()
            sics.handleInterrupt()
            break

        except (Exception, SicsExecutionException) as e:
            if isInterruptException(e) or (counter >= 20):
                raise

            slog('Retry moving guide')
            time.sleep(1)

    slog('Guide is moved to ' + getGuideConfig())
Example #57
0
def selBsHelper(beamstop, bx, bz, controller):
    # get command controller
    sicsController = sics.getSicsController()
    commandController = sicsController.findComponentController(controller)

    # configuring command properties
    if bx is not None:
        sics.hset(commandController, '/bx', bx)
    if bz is not None:
        sics.hset(commandController, '/bz', bz)

    sics.hset(commandController, '/bs', beamstop)

    count = 0
    while getIntData(controller + '/bs') != beamstop:
        time.sleep(0.1)
        count += 1
        if count > 100:
            raise Exception(
                'Time out on receiving feedback on beam stop selection')

    count = 0
    while True:
        try:
            count += 1
            commandController.syncExecute()
            break

        except (Exception, SicsExecutionException) as e:
            if isInterruptException(e) or (count >= 20):
                raise

            slog('Retry selecting beam stop %s' % beamstop)
            time.sleep(1)
            waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    slog('beam stop is %s' % beamstop)
Example #58
0
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
Example #59
0
def startScan(configModel):
    ''' setup '''

    scanVariable = configModel.scanVariable
    crystal = configModel.crystal
    mode = configModel.mode

    MainDeadTime = 1.08E-6
    TransDeadTime = 1.08E-6

    if 'Si111' in crystal:
        empLevel = 0.3
        bkgLevel = 0.277
        dOmega = 2.3E-6
        gDQv = 0.0586
        gDQh = 0

        wavelength = 4.74
        TransmissionTube = 10
        TransBackground = 0  # counts per second

    elif 'Si311' in crystal:
        empLevel = 0.34
        bkgLevel = 0.333
        dOmega = 4.6E-7
        gDQv = 0.117
        gDQh = 0

        wavelength = 2.37
        TransmissionTube = 9
        TransBackground = 0  # counts per second

    else:
        print 'selected crystal is invalid'
        return
    ''' angles '''

    scan = configModel.scan

    scan_angleMin = builtin_min(scan['angles'])
    scan_angleMax = builtin_max(scan['angles'])

    if ('m1om' in scanVariable) or ('m2om' in scanVariable):
        tolerance = 2

        approved = False
        if 'Si111' in crystal:
            if (180 - tolerance <= scan_angleMin) and (scan_angleMax <=
                                                       180 + tolerance):
                approved = True

        elif 'Si311' in crystal:
            if (0 - tolerance <= scan_angleMin) and (scan_angleMax <=
                                                     0 + tolerance):
                approved = True

        if not approved:
            print 'angle out of range'
            return
    ''' execution '''

    sics.execute('hset user/name ' + configModel.user_name)
    sics.execute('hset user/email ' + configModel.user_email)

    sics.execute('hset sample/name ' + configModel.sample_name)
    sics.execute('hset sample/description ' + configModel.sample_description)
    sics.execute('hset sample/thickness %g' % configModel.sample_thickness)

    sics.execute('hset experiment/bkgLevel %g' % bkgLevel)
    sics.execute('hset experiment/empLevel %g' % empLevel)

    sics.execute('hset instrument/detector/MainDeadTime %g' % MainDeadTime)
    sics.execute('hset instrument/detector/TransDeadTime %g' % TransDeadTime)
    sics.execute('hset instrument/detector/TransBackground %g' %
                 TransBackground)
    sics.execute('hset instrument/detector/TransmissionTube %i' %
                 TransmissionTube)

    sics.execute('hset instrument/crystal/dOmega %g' % dOmega)
    sics.execute('hset instrument/crystal/gDQv %g' % gDQv)
    sics.execute('hset instrument/crystal/gDQh %g' % gDQh)
    sics.execute('hset instrument/crystal/wavelength %g' % wavelength)
    sics.execute('hset instrument/crystal/scan_variable ' + scanVariable)

    sicsController = sics.getSicsController()

    # slits
    def getSlitValues(gap, offset, a0, b0, aOpen, bOpen):

        if gap == 'fully opened':
            return (aOpen, bOpen)

        if gap == 'fully closed':
            gap = -5.0
            offset = 0.0

        a = a0 + 0.5 * float(gap) + float(offset)
        b = b0 - 0.5 * float(gap) + float(offset)

        return (a, b)

    ss1vg = configModel.ss1vg
    ss1vo = configModel.ss1vo
    ss1hg = configModel.ss1hg
    ss1ho = configModel.ss1ho

    ss2vg = configModel.ss2vg
    ss2vo = configModel.ss2vo
    ss2hg = configModel.ss2hg
    ss2ho = configModel.ss2ho

    (ss1u, ss1d) = getSlitValues(ss1vg, ss1vo, ss1u0, ss1d0, 35.8, -38.8)
    (ss1r, ss1l) = getSlitValues(ss1hg, ss1ho, ss1r0, ss1l0, 57.0, -58.0)

    (ss2u, ss2d) = getSlitValues(ss2vg, ss2vo, ss2u0, ss2d0, 37.0, -39.5)
    (ss2r, ss2l) = getSlitValues(ss2hg, ss2ho, ss2r0, ss2l0, 35.0, -35.0)

    # apply slits
    run = {}
    run['ss1u'] = ss1u
    run['ss1d'] = ss1d
    run['ss1r'] = ss1r
    run['ss1l'] = ss1l

    run['ss2u'] = ss2u
    run['ss2d'] = ss2d
    run['ss2r'] = ss2r
    run['ss2l'] = ss2l

    sics.multiDrive(run)

    time.sleep(2)
    while not sicsController.getServerStatus().equals(
            ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    '''
    sics.execute('run ss1u %.2f' % ss1u)
    sics.execute('run ss1d %.2f' % ss1d)
    sics.execute('run ss1r %.2f' % ss1r)
    sics.execute('run ss1l %.2f' % ss1l)
    
    sics.execute('run ss2u %.2f' % ss2u)
    sics.execute('run ss2d %.2f' % ss2d)
    sics.execute('run ss2r %.2f' % ss2r)
    sics.execute('run ss2l %.2f' % ss2l)
    '''

    # load sample positions
    sam_positions = str(configModel.sam_position)

    if (len(sam_positions) == 0) or (sam_positions == 'fixed'):
        samz_list = [None]
    else:
        samz_list = []

        pos2samz = {}
        pos2samz['1'] = 33.5
        pos2samz['2'] = 178.5
        pos2samz['3'] = 323.5
        pos2samz['4'] = 468.5
        pos2samz['5'] = 613.5

        pos2samz['1 top'] = 17.4
        pos2samz['1 bottom'] = 77.7
        pos2samz['2 top'] = 163.5
        pos2samz['2 bottom'] = 223.1
        pos2samz['3 top'] = 308.0
        pos2samz['3 bottom'] = 368.1
        pos2samz['4 top'] = 454.1
        pos2samz['4 bottom'] = 513.6
        pos2samz['5 top'] = 598.2
        pos2samz['5 bottom'] = 658.0

        samz_list.append(pos2samz[sam_positions])
        '''
        for range in filter(None, sam_positions.split(',')):
            rangeItems = range.split('-')
            if ('' in rangeItems) or (len(rangeItems) < 1) or (len(rangeItems) > 2):
                raise Exception('format in "Sample Position" is incorrect')
            
            if len(rangeItems) == 1:
                samz_list.append(pos2samz[int(rangeItems[0])])
            else:
                for i in xrange(int(rangeItems[0]), int(rangeItems[1])+1):
                    samz_list.append(pos2samz[i])
                    
        if len(samz_list) == 0:
            samz_list = [0.0]
            
        '''

    for samz in samz_list:

        sics.execute('histmem stop')
        time.sleep(3)
        sics.execute('histmem mode time')

        if samz is not None:
            print 'run samz %.2f' % samz
            sics.execute('run samz %.2f' % samz)
            # sics.execute('prun samz 2' % samz) !!!
            time.sleep(1)
            while not sicsController.getServerStatus().equals(
                    ServerStatus.EAGER_TO_EXECUTE):
                time.sleep(0.1)

        sics.execute('newfile HISTOGRAM_XYT')
        #sics.execute('autosave 60') # 60 seconds
        time.sleep(1)

        # start/stop hmm
        if mode == 'count_roi':
            sics.execute('histmem preset %i' % 1)
            time.sleep(1)
            sics.execute('histmem start')
            time.sleep(5)
            while not sicsController.getServerStatus().equals(
                    ServerStatus.EAGER_TO_EXECUTE):
                time.sleep(0.1)
            sics.execute('histmem stop')

        print 'frames:', len(scan['angles'])
        for frame_index in xrange(len(scan['angles'])):
            angle = scan['angles'][frame_index]
            preset = scan['presets'][frame_index]
            maxTime = scan['maxTimes'][frame_index]

            print 'run %s %.6f' % (scanVariable, angle)
            sics.execute('run %s %.6f' % (scanVariable, angle))
            time.sleep(10)
            while not sicsController.getServerStatus().equals(
                    ServerStatus.EAGER_TO_EXECUTE):
                time.sleep(0.1)
            print 'run done'

            time.sleep(1)
            print 'histmem start'
            while True:
                if mode == 'count_roi':
                    sics.execute('histmem preset %i' % maxTime)
                else:
                    sics.execute('histmem preset %i' % preset)

                time.sleep(5)
                sics.execute('histmem start')
                time.sleep(5)

                if mode == 'count_roi':
                    print 'count_roi'

                    time.sleep(configModel.min_time)

                    count_roi = 0
                    while not sicsController.getServerStatus().equals(
                            ServerStatus.EAGER_TO_EXECUTE):
                        try:
                            count_roi = int(
                                sicsext.runCommand(
                                    'hmm configure num_events_filled_to_count_roi'
                                ))
                            print count_roi

                            if count_roi > preset:
                                print count_roi
                                print 'reached desired count_roi'
                                sics.execute('histmem pause')
                                time.sleep(1)
                                break
                        except:
                            pass

                        time.sleep(0.5)

                    break

                else:
                    while not sicsController.getServerStatus().equals(
                            ServerStatus.EAGER_TO_EXECUTE):
                        time.sleep(0.1)

                    valid = False
                    for i in xrange(10):
                        time.sleep(1)
                        detector_time = sics.getValue(
                            '/instrument/detector/time').getFloatData()

                        valid = (detector_time >= preset - 1) or (
                            detector_time >= preset * 0.90)
                        if valid:
                            break

                    print 'detector_time:', detector_time

                    if valid:
                        break
                    else:
                        print 'scan was invalid and needs to be repeated'

            #sics.execute('histmem stop')
            sics.execute('save %i' % frame_index)
            frame_index += 1
            print 'histmem done'

        sics.execute('newfile clear')
        #sics.execute('autosave 0') # disable autosave

        # Get output filename
        filenameController = sicsController.findDeviceController(
            'datafilename')
        savedFilename = filenameController.getValue().getStringData()
        print 'saved:', savedFilename

    print 'done'
    print
Example #60
0
    ds = Plot3.ds
    if ds is None:
        nds = instance([1], init = peak_pos.value)
    else:
        ds0 = ds[0]
        nds = append(ds0, peak_pos.value)
    nds.var[:] = 0
    Plot3.set_dataset(nds)
    Plot3.x_label = ''
    Plot3.y_label = axis_name.value
    Plot3.title = 'Peak Positions'
    rlist = copy(peak_at.options)
    rlist.append(len(rlist))
    peak_at.options = rlist

filenameNode = sics.getSicsController().findComponentController('/experiment/file_name')
saveCountNode = sics.getSicsController().findComponentController('/experiment/save_count')
scanpoint_node = sics.getSicsController().findComponentController('/commands/scan/bmonscan/feedback/scanpoint')
scan_variable_node = sics.getSicsController().findComponentController('/commands/scan/bmonscan/scan_variable')
#saveCount = int(saveCountNode.getValue().getIntData())
dataSourceViewer = __register__.getDataSourceViewer()

#class __SaveListener__(DynamicControllerListenerAdapter):
#    
#    def __init__(self):
#        pass
#    
#    def valueChanged(self, controller, newValue):
#        pass
#
#__cur_point__ = -1