def drive_s2():
    slog('drive s2 away to -50 and atrans to 0')
    sics.multiDrive({'s2': -50, 'atrans':0})
    s2.value = sics.getValue('s2').getFloatData()
    atrans.value = sics.getValue('atrans').getFloatData()
    sics.execute('s2 fixed 1')
    print 'Please check if s2 is fixed!'
Exemple #2
0
    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.')
Exemple #3
0
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')
Exemple #4
0
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')
Exemple #5
0
def startHistmem():
    slog('Starting histmem ...')

    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    sics.execute('histmem mode unlimited')
    time.sleep(1.0)
    sics.execute('histmem start')
def scan_temp_field_FW(fieldList, mode, preset, tempSettleTime = 1, fieldSettleTime = 1):
#    for wavelength in wavelengthList:
    sics.execute('setvolt ' + str(10))
    sleep(15)
    for i in xrange(len(fieldList)):
        pack = fieldList[i]
#        driveAtt(attList[i])
#        log('driving tc1_driveable=' +  str(pack[0]))
        
        value = str(pack[0])
        
        log(value)
#        sics.drive('tc1_driveable', value)
#        log('waiting for temperature to settle')
#        sleep(tempSettleTime)
        fields = pack[1]
        for j in xrange(len(fields)):
            
            log('driving magnet1_driveable=' + str(0))
            sics.drive('ma1_setpoint', 0)
            sics.drive('tc1_driveable', 50)
            log('waiting for temperature to settle')
            log('driving magnet1_driveable=' + str(225))
            sics.drive('ma1_setpoint', 225)
            sics.drive('tc1_driveable', value)
            log(value)
            log('waiting for temperature to settle')
            sleep(900)
            field = fields[j][0]
            log('driving magnet1_driveable=' + str(field))
            sics.drive('ma1_setpoint', field)
            log('waiting for field to settle')
            sleep(fieldSettleTime)
            
            e_fields = fields[j][1]
            for k in xrange(len(e_fields)):
                e_field = e_fields[k]
                log('drive electronic field to ' + str(e_field))
#                sics.execute('setvolt ' + str(500))
#                sleep(15)
#                sics.execute('setvolt ' + str(1000))
#                sleep(15)
#                sics.execute('setvolt ' + str(1500))
#                sleep(10)
#                sics.execute('setvolt ' + str(2000))
#                sleep(10)
#                sics.execute('setvolt ' + str(2500))
#               sleep(1)
                sics.execute('setvolt ' + str(e_field))
                
#                prep_transmission()
#                quokka.scan(scanMode.time, dataType.HISTOGRAM_XY, 120)
#                
#                prep_scattering()
                log('start counting')
                quokka.scan(mode, dataType.HISTOGRAM_XY, preset)
Exemple #7
0
def scan_en():
    aname = 'en'
    try:
        if DEBUGGING :
            aname = 'dummy_motor'
    except:
        pass
    axis_name.value = aname
    sicsext.call_back = __load_experiment_data__
    slog('scan ' + aname + ', ' + scan.value)
    sics.execute('s2 fixed 1')
    exec('sicsext.runbmonscan(\'' + aname + '\', ' + scan.value + ', 0, \'call_back()\')')
    time.sleep(2)
    fit_curve()
Exemple #8
0
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 drive_a1a2_0():
    if ei_old != Ei.value :
        slog('drive Ei ' + str(Ei.value))
        sics.execute('tasub update')
        time.sleep(1)
        try:
            sics.drive('ei', Ei.value)
        except:
            pass
        time.sleep(1)
        while str(sics.getDeviceController('ei').getStatus()) == 'RUNNING':
            time.sleep(0.5) 
    slog('drive a1 0 a2 0')
    sics.multiDrive({'a1' : 0, 'a2' : 0})
Exemple #10
0
def driveTesla(val, speed, wait_sec):
    sics.execute("oxfordseths on")
    time.sleep(35)
    sics.execute("oxfordsetrate " + str(speed))
    sics.execute("oxfordsetfield " + str(val))
    time.sleep(wait_sec)
    sics.execute("oxfordseths off")
    time.sleep(35)
Exemple #11
0
def driveTesla(val, speed, wait_sec):
    sics.execute('oxfordseths on')
    time.sleep(35)
    sics.execute('oxfordsetrate ' + str(speed))
    sics.execute('oxfordsetfield ' + str(val))
    time.sleep(wait_sec)
    sics.execute('oxfordseths off')
    time.sleep(35)
def home_run():
    print 'Run Home routine for all slits ...'
    sics.execute('ps_left homerun 0')
    sics.execute('ps_left homerun 1')
    flag = False
    acc_time = 0
    while not flag and acc_time < 300:
        time.sleep(1)
        acc_time += 1
        val = float(sicsext.runCommand('pa_left homerun'))
        flag = val == 1
    if flag:
        print 'done'
        drive_slits()
    else:
        raise Exception, 'Time out running the Home routine.'
Exemple #13
0
def resetTrip(increase_att=True):
    slog('Reset trip')

    result = False
    if increase_att:
        # drive to higher attenuation
        att = getAtt()
        if att < max(ATT_VALUES):
            driveAtt(att + 30)
            result = True
        else:
            raise Exception('unable to increase attenuation in order to reset trip')

    # reset fast shutter
    sics.execute('hset /instrument/detector/reset_trip 1')
    sleep(20) # interruptable

    return result # only true if attenuation has been increased
Exemple #14
0
def driveTesla(value, speed, wait_sec):
    slog('Driving Tesla (value: %s, speed: %s) ...' % (value, speed))

    waitUntilSicsIs(ServerStatus.EAGER_TO_EXECUTE)

    sics.execute('oxfordseths on')
    sleep(35) # interruptable sleep
    sics.execute('oxfordsetrate %s' + speed)
    sics.execute('oxfordsetfield %s' + value)
    sleep(float(wait_sec))
    sics.execute('oxfordseths off')
    sleep(35)
Exemple #15
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()
Exemple #16
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()
Exemple #17
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')
Exemple #18
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')
Exemple #19
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")
Exemple #20
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()))
Exemple #21
0
def run_scan():
    dnv = device.value
    if dnv == None or dnv.strip() == '' :
        raise Exception('device name can\'t be empty')
    axis_name.value = dnv.strip()
    stv = start.value
    if stv == None or stv.strip() == '' :
        raise Exception('start position can\'t be empty')
    try:
        float(stv)
    except:
        raise Exception('start position must be a value')
    ssv = step_size.value
    if ssv == None or ssv.strip() == '' :
        raise Exception('step size can\'t be empty')
    try:
        float(ssv)
    except:
        raise Exception('step size must be a value')
    nsv = no_steps.value
    if nsv == None or nsv.strip() == '' :
        raise Exception('number of steps can\'t be empty')
    try:
        float(nsv)
    except:
        raise Exception('number of steps must be a value')
    mdv = mode.value
    if mdv == None or mdv.strip() == '' :
        raise Exception('count mode can\'t be empty')
    psv = preset.value
    if psv == None or psv.strip() == '' :
        raise Exception('preset can\'t be empty')
    
    cmd = 'bmonscan clear'
    print cmd
    sics.execute(cmd)
    time.sleep(0.1)
    cmd = 'bmonscan add ' + dnv + ' ' + stv + ' ' + ssv
    print cmd
    sics.execute(cmd)
    time.sleep(0.1)
    cmd = 'bmonscan run ' + nsv + ' ' + mdv + ' ' + psv
    print cmd
    sics.execute(cmd)
    time.sleep(0.1)
Exemple #22
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()))
Exemple #23
0
def initiate(info):
    # parameters
    title        = strOrDefault(info.experimentTitle, "Unknown")
    pnumber      = strOrDefault(info.proposalNumber, "0")
    users        = strOrDefault(info.users, "Unknown")
    emails       = strOrDefault(info.emails, "Unknown")
    phones       = strOrDefault(info.phones, "Unknown")
    sample_stage = str(info.sampleStage)

    # update sics
    sics.set('title', title)
    sics.execute('hset /experiment/experiment_identifier ' + pnumber)

    sics.set('user', users)
    sics.execute('hset /user/email "%s"' % emails)
    sics.execute('hset /user/phone "%s"' % phones)

    # clear environment drive scripts
    state.env_drive = dict()

    setSampleStage(sample_stage)
Exemple #24
0
def findSafeAttenuation(startingAttenuation):
    # Sample at 90 (was 150) and 60 (was 120)
    attenuation1 = 120
    attenuation2 =  90
    # Safety margin (ratio)
    safety_margin = 1.02 # 2%
    
    # First sampling
    while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation1)
        
    local_rate1, global_rate1 = determineAveragedRates()
    thickness1 = thicknessTable[attenuation1]
    
    log('local rate1 = ' + str(local_rate1))
    log('global rate1 = ' + str(global_rate1))
    
    # Second sampling
    while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation2)
        
    local_rate2, global_rate2 = determineAveragedRates()
    thickness2 = thicknessTable[attenuation2]
    
    log('local rate2 = ' + str(local_rate2))
    log('global rate2 = ' + str(global_rate2))
    
    # check that at least local or global rate is sufficient
    if (local_rate2 <= local_rate1 * safety_margin) and (global_rate2 <= global_rate1 * safety_margin):
        log('insufficient statistics - safe attenuation routine is used')
        sics.execute('histmem mode time')
        if (local_rate2 <= local_rateSafe) and (global_rate2 <= global_rateSafe):
            setSafeAttenuation(attenuation2)
            return None # to tell caller that attenuation value is set
        elif (local_rate1 <= local_rateSafe) and (global_rate1 <= global_rateSafe):
            setSafeAttenuation(attenuation1)
            return None # to tell caller that attenuation value is set
        else:
            setSafeAttenuation(startingAttenuation)
            return None # to tell caller that attenuation value is set

    # find safe thickness
    if local_rate2 > local_rate1 * safety_margin:
        local_ratio  = math.log(local_rate2 / local_rate1) / (thickness1 - thickness2)
        local_offset = math.log(local_rate1 / local_rateSafe) / local_ratio
        if local_offset < 0:
            local_thicknessSafe = thickness1 + local_offset
        else:
            local_thicknessSafe = thickness1
        log('local ratio = ' + str(local_ratio))
    else:
        local_thicknessSafe = 0
    
    if global_rate2 > global_rate1 * safety_margin:
        global_ratio  = math.log(global_rate2 / global_rate1) / (thickness1 - thickness2)
        global_offset = math.log(global_rate1 / global_rateSafe) / global_ratio
        if global_offset < 0:
            global_thicknessSafe = thickness1 + global_offset
        else:
            global_thicknessSafe = thickness1
        log('global ratio = ' + str(global_ratio))
    else:
        global_thicknessSafe = 0

    # final safe thickness
    thicknessSafe = max([0, local_thicknessSafe, global_thicknessSafe])
    log('safe thickness = ' + str(thicknessSafe))
    
    # find corresponding attenuation angle
    suggestedAttAngle = 330
    for item in thicknessTable.items():
        attAngle  = item[0]
        thickness = item[1]
        if (thicknessSafe <= thickness) and (suggestedAttAngle > attAngle):
            suggestedAttAngle = attAngle
    
    log('suggested attenutaion angle = ' + str(suggestedAttAngle))
    return suggestedAttAngle
Exemple #25
0
def stopHistmem():
    sicsController = sics.getSicsController()
    histmemController = sicsController.findComponentController('/commands/histogram/histmem')
    log('stopping histmem ...')
    sics.execute('histmem stop')
Exemple #26
0
def publishFinishTime(time):
    sics.execute('hset /experiment/gumtree_time_estimate %i' % time, 'status')
Exemple #27
0
def stopHistmem():
    sicsController = sics.getSicsController()
    histmemController = sicsController.findComponentController("/commands/histogram/histmem")
    log("stopping histmem ...")
    sics.execute("histmem stop")
    time.sleep(0.5)
Exemple #28
0
def findSafeAttenuation(startingAttenuation):
    # Sample at 90 (was 150) and 60 (was 120)
    attenuation1 = 180
    attenuation2 = 150
    # Safety margin (ratio)
    safety_margin = 1.02  # 2%

    # First sampling
    while not sics.getSicsController().getServerStatus().equals(
            ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation1)

    local_rate1, total_rate1 = determineAveragedRates()
    thickness1 = thicknessTable[attenuation1]

    log('local rate1 = ' + str(local_rate1))
    log('total rate1 = ' + str(total_rate1))

    # Second sampling
    while not sics.getSicsController().getServerStatus().equals(
            ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation2)

    local_rate2, total_rate2 = determineAveragedRates()
    thickness2 = thicknessTable[attenuation2]

    log('local rate2 = ' + str(local_rate2))
    log('total rate2 = ' + str(total_rate2))

    # check that at least local or total rate is sufficient
    if (local_rate2 <= local_rate1 * safety_margin) and (
            total_rate2 <= total_rate1 * safety_margin):
        log('insufficient statistics - safe attenuation routine is used')
        sics.execute('histmem mode time')
        if (local_rate2 <= local_rateSafe) and (total_rate2 <= total_rateSafe):
            setSafeAttenuation(attenuation2)
            return None, attenuation1  # to tell caller that attenuation value is set
        elif (local_rate1 <= local_rateSafe) and (total_rate1 <=
                                                  total_rateSafe):
            setSafeAttenuation(attenuation1)
            return None, attenuation1  # to tell caller that attenuation value is set
        else:
            setSafeAttenuation(startingAttenuation)
            return None, startingAttenuation  # to tell caller that attenuation value is set

    # find safe thickness
    if local_rate2 > local_rate1 * safety_margin:
        local_ratio = math.log(
            local_rate2 / local_rate1) / (thickness1 - thickness2)
        local_offset = math.log(local_rate1 / local_rateSafe) / local_ratio
        if local_offset < 0:
            local_thicknessSafe = thickness1 + local_offset
        else:
            local_thicknessSafe = thickness1
        log('local ratio = ' + str(local_ratio))
    else:
        local_thicknessSafe = 0

    if total_rate2 > total_rate1 * safety_margin:
        total_ratio = math.log(
            total_rate2 / total_rate1) / (thickness1 - thickness2)
        total_offset = math.log(total_rate1 / total_rateSafe) / total_ratio
        if total_offset < 0:
            total_thicknessSafe = thickness1 + total_offset
        else:
            total_thicknessSafe = thickness1
        log('total ratio = ' + str(total_ratio))
    else:
        total_thicknessSafe = 0

    # final safe thickness
    thicknessSafe = max([0, local_thicknessSafe, total_thicknessSafe])
    log('safe thickness = ' + str(thicknessSafe))

    # find corresponding attenuation angle
    suggestedAttAngle = 330
    for item in thicknessTable.items():
        attAngle = item[0]
        thickness = item[1]
        if (thicknessSafe <= thickness) and (suggestedAttAngle > attAngle):
            suggestedAttAngle = attAngle

    log('suggested attenutaion angle = ' + str(suggestedAttAngle))
    return suggestedAttAngle, attenuation1
Exemple #29
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
# The type can be string, int, float, bool, file.
cact = Act('', 'The alignment is finished.')

G1 = Group('Devices Status')
m1 = Par('float', sics.getValue('m1').getFloatData())
m2 = Par('float', sics.getValue('m2').getFloatData())
s1 = Par('float', sics.getValue('s1').getFloatData())
s2 = Par('float', sics.getValue('s2').getFloatData())
a1 = Par('float', sics.getValue('a1').getFloatData())
a2 = Par('float', sics.getValue('a2').getFloatData())
Ei = Par('float', sics.getValue('ei').getFloatData())
Ef = Par('float', sics.getValue('ef').getFloatData())
En = Par('float', sics.getValue('en').getFloatData())

G1.add(m1, m2, s1, s2, a1, a2, Ei, Ef, En)
sics.execute('s2 fixed -1')
    
pact = Act('previous_step()', '<- Previous Step')
def previous_step():
    load_script(previous_file)
    
#    load_script()

def fit_curve():
    global Plot1
    ds = Plot1.ds
    if ds is None or len(ds) == 0:
        slog('Error: no curve to fit in Plot1.')
        return
    for d in ds:
        if d.title == 'fitting':
Exemple #31
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
Exemple #32
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
Exemple #33
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
Exemple #34
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
Exemple #35
0
def scan(mode, preset):
    controllerPath = '/commands/scan/runscan'

    if mode == ACQUISITION_MODE.unlimited:
        sics.execute('hset ' + controllerPath + '/mode unlimited', 'scan')
    elif mode == ACQUISITION_MODE.time:
        sics.execute('hset ' + controllerPath + '/mode time', 'scan')
    elif mode == ACQUISITION_MODE.counts:
        sics.execute('hset ' + controllerPath + '/mode counts', 'scan')
    elif mode == ACQUISITION_MODE.bm_counts:
        sics.execute('hset ' + controllerPath + '/mode MONITOR_1', 'scan')
    else:
        raise Exception('unsupported scan mode: ' + mode)

    # set preset
    if preset is not None:
        sics.execute('hset ' + controllerPath + '/preset %s' % preset, 'scan')
    elif mode != ACQUISITION_MODE.unlimited:
        raise Exception('preset is required for mode: ' + mode)

    # ensure that ba is disabled
    sics.execute('histmem ba disable', 'scan')

    syncScan(controllerPath)
Exemple #36
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()
Exemple #37
0
    def drive(self):
        if self.__is_dirty__:
            driveAtt(330)
        else:
            return
        try:
            sics.clearInterrupt()
            log('starting configuration')
            if self.need_drive_det():

                ########### below code drop dhv1 and select beam stop together ###########
                precision = 20
                safe_voltage = 800
                working_voltage = 2100
                startingValue = getDhv1()
                if startingValue > safe_voltage:
                    self.test_dhv1('down')
                    startingValue = getDhv1()
                    log('Driving dhv1 to down ...')
                    sics.execute('dhv1 down')
                    time.sleep(1)

                if not self.bs is None:
                    selBs(self.bs)

                if startingValue > safe_voltage:
                    time_count = 0
                    time_out = 30
                    while getDhv1() == startingValue and time_count < time_out:
                        time.sleep(0.5)
                        time_count += 0.5
                    if getDhv1() == startingValue:
                        raise Exception, 'failed to start dropping dhv1'
                    time_count = 0
                    time_out = 600
                    while getDhv1() > safe_voltage and time_count < time_out:
                        time.sleep(0.5)
                        time_count += 0.5
                    if getDhv1() > safe_voltage:
                        raise Exception, 'time out dropping dhv1'
                    log('dhv1 is now down')

                ########### below drive det and other motors ###########
                self.multi_drive()

                ########### below code raise dhv1 and drive guide together ###########
                self.test_dhv1('up')
                startingValue = getDhv1()
                log('Driving dhv1 to up ...')
                sics.execute('dhv1 up')
                time.sleep(1)
                if self.need_drive_guide():
                    driveGuide(self.guide)
                time_count = 0
                time_out = 30
                while getDhv1() == startingValue and time_count < time_out:
                    time.sleep(0.5)
                    time_count += 0.5
                if getDhv1() == startingValue:
                    raise Exception, 'failed to start raising dhv1'
                time_count = 0
                time_out = 600
                while getDhv1() < working_voltage and time_count < time_out:
                    time.sleep(0.5)
                    time_count += 0.5
                if getDhv1() < working_voltage:
                    raise Exception, 'time out raising dhv1'
                log('dhv1 is now up')

                self.multi_set()
            else:
                if not self.bs is None:
                    selBs(self.bs)
                if self.need_drive_guide():
                    driveGuide(self.guide)
                self.multi_drive()
                self.multi_set()
        finally:
            self.clear()
        while sics.getStatus() != 'EAGER TO EXECUTE':
            time.sleep(0.3)
        sics.handleInterrupt()
        log('configuration is finished')
Exemple #38
0
def stopHistmem():
    sicsController = sics.getSicsController()
    histmemController = sicsController.findComponentController('/commands/histogram/histmem')
    log('stopping histmem ...')
    sics.execute('histmem stop')
    time.sleep(0.5)
Exemple #39
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
Exemple #40
0
def findSafeAttenuation(startingAttenuation):
    # Sample at 90 (was 150) and 60 (was 120)
    attenuation1 = 120
    attenuation2 =  90
    # Safety margin (ratio)
    safety_margin = 1.02 # 2%
    
    # First sampling
    while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation1)
        
    local_rate1, global_rate1 = determineAveragedRates()
    thickness1 = thicknessTable[attenuation1]

    if hasTripped():
        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))
        return None # to tell caller that attenuation value is set
    
    log('local rate1 = ' + str(local_rate1))
    log('global rate1 = ' + str(global_rate1))
    
    # Second sampling
    while not sics.getSicsController().getServerStatus().equals(ServerStatus.EAGER_TO_EXECUTE):
        time.sleep(0.1)
    driveAtt(attenuation2)
        
    local_rate2, global_rate2 = determineAveragedRates()
    thickness2 = thicknessTable[attenuation2]

    if hasTripped():
        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))
        return None # to tell caller that attenuation value is set
    
    log('local rate2 = ' + str(local_rate2))
    log('global rate2 = ' + str(global_rate2))
    
    # check that at least local or global rate is sufficient
    if (local_rate2 <= local_rate1 * safety_margin) and (global_rate2 <= global_rate1 * safety_margin):
        log('insufficient statistics - safe attenuation routine is used')
        sics.execute('histmem mode time')
        if (local_rate2 <= local_rateSafe) and (global_rate2 <= global_rateSafe):
            setSafeAttenuation(attenuation2)
            return None # to tell caller that attenuation value is set
        elif (local_rate1 <= local_rateSafe) and (global_rate1 <= global_rateSafe):
            setSafeAttenuation(attenuation1)
            return None # to tell caller that attenuation value is set
        else:
            setSafeAttenuation(startingAttenuation)
            return None # to tell caller that attenuation value is set

    # find safe thickness
    if local_rate2 > local_rate1 * safety_margin:
        local_ratio  = math.log(local_rate2 / local_rate1) / (thickness1 - thickness2)
        local_offset = math.log(local_rate1 / local_rateSafe) / local_ratio
        if local_offset < 0:
            local_thicknessSafe = thickness1 + local_offset * 0.90 # 90% for safety
        else:
            local_thicknessSafe = thickness1
        log('local ratio = ' + str(local_ratio))
    else:
        local_thicknessSafe = 0
    
    if global_rate2 > global_rate1 * safety_margin:
        global_ratio  = math.log(global_rate2 / global_rate1) / (thickness1 - thickness2)
        global_offset = math.log(global_rate1 / global_rateSafe) / global_ratio
        if global_offset < 0:
            global_thicknessSafe = thickness1 + global_offset * 0.90 # 90% for safety
        else:
            global_thicknessSafe = thickness1
        log('global ratio = ' + str(global_ratio))
    else:
        global_thicknessSafe = 0

    # final safe thickness
    thicknessSafe = max([0, local_thicknessSafe, global_thicknessSafe])
    log('safe thickness = ' + str(thicknessSafe))
    
    # find corresponding attenuation angle
    suggestedAttAngle = 330
    for item in thicknessTable.items():
        attAngle  = item[0]
        thickness = item[1]
        if (thicknessSafe <= thickness) and (suggestedAttAngle > attAngle):
            suggestedAttAngle = attAngle

    # try to improve attenuation if possible
    if suggestedAttAngle > 0:
        setSafeAttenuation(suggestedAttAngle)
        return None # to tell caller that attenuation value is set

    log('suggested attenutaion angle = ' + str(suggestedAttAngle))
    return suggestedAttAngle
Exemple #41
0
def scanBA(min_time, max_time, counts, bm_counts):
    def getIntOrDefault(value, default):
        if value is not None:
            return int(value)
        else:
            return default

    controllerPath = '/commands/scan/runscan'

    sics.execute('hset ' + controllerPath + '/mode unlimited', 'scan')

    # always reset the ba properties before setting up new values
    sics.execute('histmem ba reset', 'scan')

    sics.execute('histmem ba roi total', 'scan')
    sics.execute('histmem ba monitor 1', 'scan')

    sics.execute('histmem ba mintime %i' % getIntOrDefault(min_time, 0),
                 'scan')
    sics.execute('histmem ba maxtime %i' % getIntOrDefault(max_time, -1),
                 'scan')
    sics.execute('histmem ba maxdetcount %i' % getIntOrDefault(counts, -1),
                 'scan')
    sics.execute('histmem ba maxbmcount %i' % getIntOrDefault(bm_counts, -1),
                 'scan')

    try:
        sics.execute('histmem ba enable', 'scan')
        syncScan(controllerPath)

    finally:
        # ensure that ba is disabled afterwards
        sics.execute('histmem ba disable', 'scan')
Exemple #42
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
Exemple #43
0
def drive_Ei():
    sics.execute('tasub outofplane 0')
    slog('fix s1, s2, a1 and a2')
    sics.execute('s1 fixed 1')
    sics.execute('s2 fixed 1')
    sics.execute('a1 fixed 1')
    sics.execute('a2 fixed 1')
    sics.drive('sgl', 0)
    sics.drive('sgu', 0)
    sics.execute('sgl fixed 1')
    sics.execute('sgu fixed 1')
    slog('drive Ei ' + str(Ei.value))
    sics.execute('tasub update')
    time.sleep(1)
    try:
        sics.drive('ei', Ei.value)
    except:
        pass
    time.sleep(1)
    while str(sics.getDeviceController('ei').getStatus()) == 'RUNNING':
        time.sleep(0.5) 
    m2.value = sicsext.getStableValue('m2').getFloatData()
    m1.value = m2.value / 2
    scan.value = str(math.ceil((m1.value - 2) * 1000) / 1000) + ', 0.1, 41, \'timer\', 1'
    sics.execute('tasub update')
    slog('unfix sgu, sgl, s1, s2, a1 and a2')
    sics.execute('s2 fixed -1')
    sics.execute('s1 fixed -1')
    sics.execute('a1 fixed -1')
    sics.execute('a2 fixed -1')
    sics.execute('sgl fixed -1')
    sics.execute('sgu fixed -1')
Exemple #44
0
    def drive(self):
        if self.__is_dirty__:
            driveAtt(330)
        else:
            return
        try:
            sics.clearInterrupt()
            log("starting configuration")
            if self.need_drive_det():

                ########### below code drop dhv1 and select beam stop together ###########
                precision = 20
                startingValue = getDhv1Value()
                if startingValue > precision:
                    self.test_dhv1("down")
                    startingValue = getDhv1Value()
                    log("Driving dhv1 to down ...")
                    sics.execute("dhv1 down")
                    time.sleep(1)

                if not self.bs is None:
                    selBs(self.bs)

                if startingValue > precision:
                    time_count = 0
                    time_out = 6
                    while getDhv1Value() == startingValue and time_count < time_out:
                        time.sleep(0.5)
                        time_count += 0.5
                    if getDhv1Value() == startingValue:
                        raise Exception, "failed to start dropping dhv1"
                    time_count = 0
                    time_out = 300
                    while getDhv1Value() > precision and time_count < time_out:
                        time.sleep(0.5)
                        time_count += 0.5
                    if getDhv1Value() > precision:
                        raise Exception, "time out dropping dhv1"
                    log("dhv1 is now down")

                ########### below drive det and other motors ###########
                self.multi_drive()

                ########### below code raise dhv1 and drive guide together ###########
                self.test_dhv1("up")
                startingValue = getDhv1Value()
                log("Driving dhv1 to up ...")
                sics.execute("dhv1 up")
                time.sleep(1)
                if self.need_drive_guide():
                    driveGuide(self.guide)
                time_count = 0
                time_out = 6
                while getDhv1Value() == startingValue and time_count < time_out:
                    time.sleep(0.5)
                    time_count += 0.5
                if getDhv1Value() == startingValue:
                    raise Exception, "failed to start raising dhv1"
                time_count = 0
                time_out = 300
                while getDhv1Value() < 2350.0 - precision and time_count < time_out:
                    time.sleep(0.5)
                    time_count += 0.5
                if getDhv1Value() < 2350.0 - precision:
                    raise Exception, "time out raising dhv1"
                log("dhv1 is now up")

                self.multi_set()
            else:
                if not self.bs is None:
                    selBs(self.bs)
                if self.need_drive_guide():
                    driveGuide(self.guide)
                self.multi_drive()
                self.multi_set()
        finally:
            self.clear()
        while sics.getStatus() != "EAGER TO EXECUTE":
            time.sleep(0.3)
        sics.handleInterrupt()
        log("configuration is finished")
import time
from gumpy.nexus.fitting import Fitting, GAUSSIAN_FITTING
from gumpy.commons import sics
# Script control setup area
# script info
__script__.title = 'Alignment Finished'
__script__.version = ''

previous_file = 'auto_8_scan_en.py'

# Use below example to create parameters.
# The type can be string, int, float, bool, file.
cact = Act('', 'The alignment is finished.')

G1 = Group('Devices Status')
sics.execute('tasub update')
sics.getDeviceController('ei').getValue(True)
sics.getDeviceController('ef').getValue(True)
sics.getDeviceController('en').getValue(True)
m1 = Par('float', sics.getValue('m1').getFloatData())
m2 = Par('float', sics.getValue('m2').getFloatData())
s1 = Par('float', sics.getValue('s1').getFloatData())
s2 = Par('float', sics.getValue('s2').getFloatData())
a1 = Par('float', sics.getValue('a1').getFloatData())
a2 = Par('float', sics.getValue('a2').getFloatData())
Ei = Par('float', sics.getValue('ei').getFloatData())
Ef = Par('float', sics.getValue('ef').getFloatData())
En = Par('float', sics.getValue('en').getFloatData())

G1.add(m1, m2, s1, s2, a1, a2, Ei, Ef, En)
sics.execute('s2 fixed -1')
Exemple #46
0
def stopHistmem():
    slog('Stopping histmem ...')

    sics.execute('histmem stop')
    time.sleep(0.5)