Example #1
0
 def generate_user_dirs(self, pvname, value, **kwargs):
     if value==1:
         user = epics.caget('2xfmS1:user_string.VAL')
         beamline.setup_user_dirs(user)
     elif value==2:
         user = epics.caget('2xfmS1:user_string.VAL')
         beamline.setup_user_dirs_save_data_location(user)
Example #2
0
 def select_rois_to_save(self, roilist):
     """copy rois from MCA record to arrays to be saved
     by XSPress3"""
     roilist = list(roilist)
     if len(roilist) < 4: roilist.append((50, 4050))
     pref = self._prefix
     self._save_rois = []
     for iroi, roiname in enumerate(roilist):
         label = roiname
         if isinstance(roiname, tuple):
             lo, hi = roiname
             label = '[%i:%i]'  % (lo, hi)
         else:
             rname = roiname.lower().strip()
             lo, hi = 50, 4050
             for ix in range(MAX_ROIS):
                 nm = caget('%smca1.R%iNM' % (pref, ix))
                 if nm.lower().strip() == rname:
                     lo = caget('%smca1.R%iLO' % (pref, ix))
                     hi = caget('%smca1.R%iHI' % (pref, ix))
                     break
         self._save_rois.append(label)
         for imca in range(1, self.nmca+1):
             pv_lo = "%sC%i_MCA_ROI%i_LLM" % (pref, imca, iroi+1)
             pv_hi = "%sC%i_MCA_ROI%i_HLM" % (pref, imca, iroi+1)
             caput(pv_hi, hi)
             caput(pv_lo, lo)
Example #3
0
    def calculate_fly_ranges(self, **kwargs):
        # Min speed
        min_vel = epics.caget('2xfm:FlySetup:MinBaseVel.VAL')
        max_vel = epics.caget('2xfm:FlySetup:MaxVelocity.VAL')
        if min_vel == 0.0:
            return
        if max_vel == 0.0:
            return
        dwell = self.c_pvs[self.soft_prefix+'dwell.VAL'].get()/1e3
        step = abs(self.FscanH.PV('P1SI').get())
        width = abs(self.FscanH.PV('P1WD').get())
        npts = self.FscanH.PV('NPTS').get()

        if np.mod(step/0.0001, 1.0)>0.0:
            epics.caput('2xfmS1:warning1.VAL', 'Step size should be multiple of 100nm')
            epics.caput('2xfmS1:show_warning1.VAL', 1)
        else:
            epics.caput('2xfmS1:warning1.VAL', '')
            epics.caput('2xfmS1:show_warning1.VAL', 0)

        try:
            epics.caput(self.soft_prefix+'max_dwell.VAL', step/min_vel)
            epics.caput(self.soft_prefix+'min_dwell.VAL', step/max_vel)

            epics.caput(self.soft_prefix+'max_step.VAL', dwell/min_vel)
            epics.caput(self.soft_prefix+'min_step.VAL', 0.0001)

            epics.caput(self.soft_prefix+'max_width.VAL', npts*dwell/min_vel)
            epics.caput(self.soft_prefix+'min_width.VAL', npts*dwell/max_vel)
        except:
            raise
Example #4
0
def checkMcsData():
	c=epics.caget("zzz:MCSs0")
	for j in range(8):
		c = epics.caget("zzz:MCSs%d" % j)
		for i in range(len(c)-1):
			if c[i] != c[i+1]-1:
				print "input %d, i=%d, c[i]=%d, c[i+1]=%d" % (j, i, c[i], c[i+1])
Example #5
0
def find_max_intensity(readpv, drivepv, vals, minval=0.1):
    """find a max in an intensity while sweeping through an
    array of drive values,  around a current position, and
    move to the position with max intensity.

    Parameters
    ----------
    readpv:   PV for reading intensity
    drivepv:  PV for driving positions
    vals:     array of RELATIVE positions (from current value)
    minval:   minimum acceptable intensity [defualt = 0.1]

    Notes:
    -------
     1. PRIVATE method, not exposed in user-macros
     2. if the best intensity is below minval, the position is
        moved back to the original position.
     
    """
    _orig = _best = caget(drivepv)
    i0max = caget(readpv)
    for val in _orig+vals:
        caput(drivepv, val)
        sleep(0.1)
        i0 = caget(readpv)
        if i0 > i0max:
            i0max, _best = i0, val
        #endif
    #endfor
    if i0max < minval: _best = _orig
    caput(drivepv, _best)
    return i0max, _best
Example #6
0
 def update_time_remaining(self, **kwargs):
     try:
         if self.stepfly == 'step':
             dwell = epics.caget('2xfm:userTran1.P', timeout=0.1)
             n_pts = self.scan1.NPTS
             n_lines = self.scan2.NPTS
             c_line = self.scan2.CPT
             oh = cfg.time_estimate_overhead['step']
         elif self.stepfly == 'fly':
             dwell = epics.caget('2xfm:FlySetup:DwellTime.VAL', timeout=0.1)*1e-3
             n_pts = self.FscanH.NPTS
             n_lines = self.Fscan1.NPTS
             c_line = self.Fscan1.CPT
             oh = cfg.time_estimate_overhead['fly']
         if c_line>n_lines:
             c_line = n_lines
         time_per_line = oh[0]+dwell*n_pts*oh[1]
         time_per_image = oh[2]+time_per_line*(n_lines-c_line)*oh[3]
         epics.caput(self.soft_prefix+'hr_remaining.VAL', np.floor(time_per_image/3600.0), timeout=0.1)
         epics.caput(self.soft_prefix+'min_remaining.VAL', np.mod(time_per_image, 3600.0)/60.0, timeout=0.1)
     except TypeError:
         # Probably a caget timed out
         pass
     except AttributeError:
         raise
Example #7
0
def move_instrument(inst_name, position_name, wait=False,
                    prefix='13XRM:Inst:', timeout=60.0):
    """move an Epics Instrument to a named position

    Parameters
    ----------
    inst_name:      string, name of Epics Instrument
    position_name:  string, name of position for the Instrument
    wait:           True/False, whether to wait for move to complete (False)
    prefix:         string PV prefix used by Epics Instrument ('13XRM:Inst:')
    timeout:        time in seconds to give up waiting

    Examples
    --------
      move_instrument('Double H Mirror Stripes', 'platinum', wait=True)

    Notes
    ------
    This requires a working Epics Instrument program to be running.
    
    """

    'move an Epics Instrument to a named position'
    caput(prefix + 'InstName', inst_name)
    caput(prefix + 'PosName', position_name)
    sleep(0.25)
    if (caget(prefix + 'InstOK') == 1 and
        caget(prefix + 'PosOK') == 1):
        caput(prefix + 'Move', 1)
        if wait:
            moving, t0 = 1, clock()
            while moving:
                sleep(0.25)
                moving = ((1 == caget(prefix + 'Move')) or
                          (clock()-t0 > timeout))
Example #8
0
def collect_data(center_offset, collection_time, angle, time_offset=5.0, theta_offset=0.0, back_rotation_time=10.0):
    # move beamstop down:
    caput("13IDD:Unidig2Bo5", 0)

    #get old position
    old_theta = caget('13IDD:m95.RBV')
    old_x = caget('13IDD:m93.RBV')
    old_z = caget('13IDD:m94.RBV')

    # create parameters for trajectory scan
    rotation_time = collection_time + time_offset
    rotation_angle = float(rotation_time) / float(collection_time) * angle

    # create the timer for data_collection
    t = Timer(time_offset / 2.0, start_detector, args=(collection_time,))
    t.start()

    print 'SOLLER: rotation trajectory START'
    perform_rotation_trajectory(center_offset, rotation_time, rotation_angle, theta_offset=theta_offset)
    print 'SOLLER: rotation trajectory FINISHED'

    print 'SOLLER: moving to original position'
    print ' --performing backwards trajectory'
    perform_rotation_trajectory(center_offset, back_rotation_time, -rotation_angle)

    time.sleep(0.5)
    print ' --moving motors to starting position'
    caput('13IDD:m94.VAL', old_z, wait=False)
    caput('13IDD:m93.VAL', old_x, wait=False)
    caput('13IDD:m95.VAL', old_theta, wait=True)
    print 'SOLLER: movement FINISHED'
Example #9
0
    def estimate_collection_time(self, epics_config):
        total_time = 0
        det_x_speed = caget(epics_config['detector_position_x'] + '.VELO')
        det_z_speed = caget(epics_config['detector_position_z'] + '.VELO')
        det_x_pos = caget(epics_config['detector_position_x'])
        det_z_pos = caget(epics_config['detector_position_z'])

        for exp_ind, experiment in enumerate(self.model.experiment_setups):
            exp_collection = False
            for sample_point in self.model.sample_points:
                if sample_point.perform_wide_scan_for_setup[exp_ind]:
                    exposure_time = abs(experiment.omega_end - experiment.omega_start) / experiment.omega_step * \
                                    experiment.time_per_step
                    total_time += exposure_time
                    exp_collection = True
                if sample_point.perform_step_scan_for_setup[exp_ind]:
                    print("Performing step scan for {}, with setup {}".format(sample_point, experiment))
                    number_of_steps = abs(experiment.omega_end - experiment.omega_start) / experiment.omega_step
                    exposure_time = number_of_steps * (4 + experiment.time_per_step)
                    total_time += exposure_time
                    exp_collection = True
                if exp_collection:
                    det_x_move_time = abs(experiment.detector_pos_x - det_x_pos) / float(det_x_speed)
                    det_y_move_time = abs(experiment.detector_pos_z - det_z_pos) / float(det_z_speed)
                    total_time += det_x_move_time + det_y_move_time
                    det_x_pos = experiment.detector_pos_x
                    det_z_pos = experiment.detector_pos_z
        return total_time
Example #10
0
def DICLiveImage(det, HutchLetter=None, expTime=None):
    if HutchLetter is None:
        print "hutch letter missing."
        print "e: 1-id-e"
        HutchLetter = raw_input("enter hutch letter : ")

    ## LIGHT CONTROL
    if HutchLetter is "e":
        # DIODE FOR OVERHEAD LIGHTS
        pvname = "1ide1:IPC1:ch3"
        #        while mac1id.IsLightOn(pvname):
        #            spec.sleep(0.5)

        # PULIZZI LIGHT SWITCH
        pv_indicator = "1ide1:IPC1:ch3"
        pv_on_switch = "1ide1:IPC1:on_ch3.PROC"
        pv_off_switch = "1ide1:IPC1:off_ch3.PROC"
        if ep.caget(pv_indicator) is False:
            print "pulizzi dic light is off"
            while ep.caget(pv_indicator) is False:
                ep.caput(pv_on_switch, 1)
                spec.sleep(0.25)
            print "pulizzi dic light is on"
    else:
        print "no photo diodes / dic lights implemented"

    AD.AD_set(det, "image_mode", 2)
    AD.AD_set(det, "autosave", 0)
    AD.AD_set(det, "acquire_time", expTime)
    print "python console control returned"
    print "press STOP button to finish live dic feed"
    AD.AD_set(det, "acquire", 1)
Example #11
0
def _UpDnCntrTest():
	epics.caput("zzz:SG:sseq1.PROC","0", wait=True, timeout=1000000.0)
	time.sleep(1.5)
	divBy = []
	divBy.append(epics.caget("zzz:SG:UpDnCntr-1_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-2_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-3_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-4_PRESET"))
	cnt = []
	cnt.append(epics.caget("zzz:SG:UpCntr-1_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-2_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-3_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-4_COUNTS"))
	#cntClock = epics.caget("zzz:SG:DnCntr-1_COUNTS")  # doesn't exist yet
	cts = epics.caget("zzz:reg1_RB8")
	preset = epics.caget("zzz:SG:DnCntr-1_PRESET")
	cntClock = preset - cts
	success = True
	diff = -1
	for i in range(4):
		d = abs(cntClock/divBy[i] - cnt[i])
		if d > 1:
			success = 0
			if d > diff:
				diff = d

	if success:
		print "UpDnCntrTest: Passed"
	else:
		print "UpDnCntrTest: Failed: max diff=", diff
		#print "cntClock=", cntClock, "cnt=", cnt, "divBy=", divBy
	return success
Example #12
0
    def move(self, motor, position, timeout):
        """
        Move motor to position. We use put_callback
        and check final position is within RDBD.
        """
    
        try:
            caput(motor, position, wait=True, timeout=timeout)
        except:
            e = sys.exc_info()
            print str(e)
            print "ERROR: caput failed."
            print (motor + " pos:" + str(position) + " timeout:" + str(timeout))
            return self.__g.FAIL
        
        rdbd = motor + ".RDBD"
        rbv = motor + ".RBV"

        final_pos = caget(rbv)
        deadband = caget(rdbd)

        success = True

        if ((final_pos < position-deadband) or (final_pos > position+deadband)):
            print "ERROR: final_pos out of deadband."
            print (motor + " " + str(position) + " " + str(timeout) + " " 
                   + str(final_pos) + " " + str(deadband))
            success = False

        if (success):
            return self.postMoveCheck(motor)
        else:
            self.postMoveCheck(motor)
            return self.__g.FAIL
Example #13
0
def check_alarm(base_pv, stat_field='STAT', severity_field='SEVR',
                reason_field=None, reason_pv=None,
                min_severity=errors.SEV_MINOR):
    """
    Raise an exception if an alarm is set
    """
    stat_pv = '%s.%s' % (base_pv, stat_field)
    severity_pv = '%s.%s' % (base_pv, severity_field)
    if reason_field is not None:
        reason_pv = '%s.%s' % (base_pv, reason_field)
    reason = None

    severity = epics.caget(severity_pv)

    if severity >= min_severity:
        try:
            error_class = errors.severity_error_class[severity]
        except KeyError:
            pass
        else:
            severity = epics.caget(severity_pv, as_string=True)
            alarm = epics.caget(stat_pv, as_string=True)
            if reason_pv is not None:
                reason = epics.caget(reason_pv, as_string=True)

            message = 'Alarm status %s [severity %s]' % (alarm, severity)
            if reason is not None:
                message = '%s: %s' % (message, reason)

            raise error_class(message)

    return True
def test1(i):
	e = expressions[i]
	epics.caput(calc,e[0], wait=True)
	#time.sleep(5)
	rtry = epics.caget(result)
	atry = epics.caget(aresult)
	if (e[1]):
		r = eval(e[1])
		print "\n", e[0], "-->", e[1]
	else:
		r = eval(e[0])
		print "\n", e[0]
	if ((type(r) == type(1.0)) or (type(r) == type(1))):
		if (abs(r - rtry) < small):
			print "OK\t", "rtry=",rtry, ", r=",r
			return(0)
		else:
			print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
			return(1)
	elif (type(r) == type(True)):
		if ((abs(rtry) < small) == (r == False)):
			print "OK\t", "rtry=",rtry, ", r=",r
			return(0)
		else:
			print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
			return(1)
	else:
		print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
		return(1)
Example #15
0
def feed_data(config, logger, *args):
    """
    This function is called by an client to start the process. It parses configuration and gets needed process
    variables. It stores necessary values in the globals object.
    After all initial settings are completed, the method awaits for the area detector to start acquireing by polling
    the PV. When the area detective is active it starts processing.

    Parameters
    ----------
    config : str
        a configuration file

    logger : Logger
        a Logger instance, recommended to use the same logger for feed and consuming process

    *args : list
        a list of process specific arguments

    Returns
    -------
    None
    """

    no_frames, detector, detector_basic, detector_image = parse_config(config)
    acquire_pv, counter_pv, data_pv, sizex_pv, sizey_pv = get_pvs(detector, detector_basic, detector_image)
    globals.no_frames = no_frames
    test = True
    while test:
        globals.sizex = caget (sizex_pv)
        globals.sizey = caget (sizey_pv)
        ack =  caget(acquire_pv)
        if ack == 1:
            test = False
            start_processes(counter_pv, data_pv, logger, *args)
    def test_TC_1322(self):
        if (self.msta & MSTA_BIT_HOMED):
            tc_no = "TC-1322-low-limit-switch"
            print '%s' % tc_no
            old_high_limit = epics.caget(self.m1 + '.HLM')
            old_low_limit = epics.caget(self.m1 + '.LLM')
            epics.caput(self.m1 + '.STOP', 1)
            #Go away from limit switch
            moveUserPosition(self.m1, tc_no, self.per30_UserPosition, self.moving_velocity, self.acceleration)
            #switch off the soft limits. Depending on the postion
            # low or high must be set to 0 first
            if epics.caget(self.m1 + '.RBV') > 0:
                epics.caput(self.m1 + '.LLM', 0.0)
                epics.caput(self.m1 + '.HLM', 0.0)
            else:
                epics.caput(self.m1 + '.HLM', 0.0)
                epics.caput(self.m1 + '.LLM', 0.0)

            epics.caput(self.m1 + '.JOGR', 1, wait=True)
            # Get values, check them later
            lvio = int(epics.caget(self.m1 + '.LVIO'))
            mstaE = int(epics.caget(self.m1 + '.MSTA'))
            #Go away from limit switch
            moveUserPosition(self.m1, tc_no, old_high_limit, self.moving_velocity, self.acceleration)
            print '%s msta=%x lvio=%d' % (tc_no, mstaE, lvio)

            epics.caput(self.m1 + '.LLM', old_low_limit)
            epics.caput(self.m1 + '.HLM', old_high_limit)

            #self.assertEqual(0, lvio, 'LVIO == 0')
            self.assertEqual(0, mstaE & MSTA_BIT_PROBLEM,    'No Error MSTA.Problem at PLUS_LS')
            self.assertNotEqual(0, mstaE & MSTA_BIT_MINUS_LS,   'Minus hard limit switch not active')
            self.assertEqual(0, mstaE & MSTA_BIT_PLUS_LS, 'Plus hard limit switch active')
Example #17
0
def _test():
    group = MotorGroup()
    group.add_motor("m1", "IOC:m1", "0.5 * pseudo1")
    group.add_motor("m2", "IOC:m2", "0.6 * pseudo1")
    group.add_motor("pseudo1", "ECLI:test", "2.0 * m1")
    # group.check_equations()

    from . import PVManager
    import epics

    manager = PVManager("ECLI:")
    manager.run()

    group.set_record("m1", epics.Motor("IOC:m1"))
    group.set_record("m2", epics.Motor("IOC:m2"))
    pseudo = PseudoMotor(manager, group, "pseudo1", "test")

    group.start()

    pseudo.update_readback()
    print("calculated rbv is", epics.caget("ECLI:test.RBV"))

    print(epics.caget("ECLI:test.VAL"), pseudo)
    import time

    try:
        time.sleep(60)
    except KeyboardInterrupt:
        pass

    print("Move done")

    print("pseudo rbv", epics.caget("ECLI:test.RBV"))
    print("m1 rbv", epics.caget("IOC:m1.RBV"))
    print("m2 rbv", epics.caget("IOC:m2.RBV"))
Example #18
0
 def caget(self):
     ''' pvConnect if not connected ! '''
     if self.pvConnected != False :
         self.x = epics.caget(self.xPvName)
         self.y = epics.caget(self.yPvName)
     else:
         self.pvConnect()
     self.emit_dataChanged()
Example #19
0
 def test_caget(self):
     write('Simple Test of caget() function\n')
     pvs = (pvnames.double_pv, pvnames.enum_pv, pvnames.str_pv)
     for p in pvs:
         val = caget(p)
         self.assertIsNot(val, None)
     sval = caget(pvnames.str_pv)
     self.assertEqual(sval, 'ao')
Example #20
0
 def caget(self):
     ''' pvConnect if not connected ! '''
     if self._pvConnected != False :
         self.dataContainer.x = epics.caget(self.dataContainer.xPvName)
         self.dataContainer.y = epics.caget(self.dataContainer.yPvName)
     else:
         self.pvConnect()
     self.update()
Example #21
0
 def check_conditions():
     if int(caget('13IDD:m24.RBV')) > -105:
         return False
     elif int(caget('13IDD:m23.RBV')) > -105:
         return False
     elif int(caget('13IDD:m67.RBV')) > -65:
         return False
     return True
Example #22
0
 def get_current_sample_position():
     try:
         x = float("{:.4g}".format(caget(epics_config['sample_position_x'])))
         y = float("{:.4g}".format(caget(epics_config['sample_position_y'])))
         z = float("{:.4g}".format(caget(epics_config['sample_position_z'])))
     except epics.ca.ChannelAccessException:
         x = y = z = 0
     return x, y, z
Example #23
0
    def check_filepath_exists(self):
        cur_epics_filepath = caget(epics_config['detector_file'] + ':FilePath', as_string=True)
        print self.filepath
        caput(epics_config['detector_file'] + ':FilePath', self.filepath, wait=True)
        exists = caget(epics_config['detector_file'] + ':FilePathExists_RBV')

        caput(epics_config['detector_file'] + ':FilePath', cur_epics_filepath)
        return exists == 1
Example #24
0
    def take_standards(self, pvname, value, **kwargs):
        if value==1:
            old_comment = epics.caget('2xfm:userStringCalc10.CC')
            epics.caput('2xfm:userStringCalc10.CC', 'axo_std')
            self.sample.x.move(0, wait=True)
            self.sample.y.move(-2.7, wait=True)

            # Step scan
            epics.caput(self.soft_prefix+'stepfly.VAL', 0)
            epics.caput(self.soft_prefix+'scan_axes_select.VAL',0)
            epics.caput(self.ioc_prefix+'userTran1.P', 1)

            self.scan1.P1WD = 0.06
            self.scan1.NPTS = 61
            self.scan2.P1WD = 0.02
            self.scan2.NPTS = 3

            done = False
            epics.caput('2xfm:scanPause.VAL', 0)
            fn_root = epics.caget('2xfm:saveData_fileSystem')
            fn_subdir = epics.caget('2xfm:saveData_subDir')
            fn_basename = epics.caget('2xfm:saveData_baseName')
            std_mda_num = epics.caget('2xfm:saveData_scanNumber')
            time.sleep(1.0)
            fp_str = os.path.join(fn_root.replace('//xfm0/xfm0-data', '/mnt/xfm0'), fn_subdir)
            print('Starting step scan...')
            self.scan2.EXSC = 1
            time.sleep(10.0)
            while not done:
                time.sleep(5.0)
                done = self.scan2.BUSY==0
            # Make a copy of the mda file and name it "axo_std.mda"
            try:
                shutil.copy(os.path.join(fp_str, fn_basename+'{:04d}.mda'.format(std_mda_num)), os.path.join(fp_str, 'axo_std.mda'))
            except IOError:
                print('Could not create axo_std.mda')
            print('Step scan done.')

            # Fly Scan
            epics.caput(self.soft_prefix+'stepfly.VAL', 1)
            epics.caput(self.ioc_prefix+'FlySetup:DwellTime.VAL', 30)

            self.FscanH.P1WD = 0.06
            self.FscanH.NPTS = 86
            self.Fscan1.P1WD = 0.02
            self.Fscan1.NPTS = 29

            done = False
            epics.caput('2xfm:FscanPause.VAL', 0)
            print('Starting fly scan...')
            self.Fscan1.EXSC = 1
            time.sleep(10.0)
            while not done:
                time.sleep(5.0)
                done = self.Fscan1.BUSY==0
            print('Step fly done.')

            epics.caput('2xfm:userStringCalc10.CC',old_comment)
Example #25
0
    def maps_process_now(self, pvname, value, **kwargs):
        if value==1:
            user = epics.caget('2xfmS1:user_string.VAL')
            run = epics.caget('2xfmS1:run_string.VAL')

            fn_livejob = '/mnt/xfm0/data/2ide/{run:s}/{user:s}/livejob_{run:s}_2ide_{user:s}.txt'.format(**{'user':user, 'run':run})

            if os.path.isfile(fn_livejob):
                shutil.move(fn_livejob, '/mnt/xfm0/data/jobs')
def moveUserPosition(motor, tc_no, destination, velocity, acceleration):
    time_to_wait = 30
    if velocity > 0:
        distance = math.fabs(epics.caget(motor + '.RBV') - destination)
        time_to_wait += distance / velocity + 2 * acceleration
    print '%s: moveUserPosition Start destination=%f' % (tc_no, destination) 
    epics.caput(motor + '.VAL', destination, wait=True)
    msta = int(epics.caget(motor + '.MSTA'))
    rbv =  epics.caget(motor + '.RBV')
    print '%s: moveUserPosition End msta=%x %s rbv=%f' % (tc_no, msta, getMSTAtext(msta), rbv)
Example #27
0
 def get_filename_info():
     path = caget(epics_config['detector_file'] + ':FilePath', as_string=True)
     print(path)
     filename = caget(epics_config['detector_file'] + ':FileName', as_string=True)
     file_number = caget(epics_config['detector_file'] + ':FileNumber')
     if path is None:
         path = ''
         filename = 'test'
         file_number = 0
     return path, filename, file_number
Example #28
0
def _dnCntrTest():
	epics.caput(prefix+"SG:sseq1.PROC","0", wait=True, timeout=1000000.0)
	time.sleep(1.5)
	divBy = []
	divBy.append(epics.caget(prefix+"SG:DnCntr-1_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-2_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-3_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-4_PRESET"))
	cnt = []
	cnt.append(epics.caget(prefix+"SG:UpCntr-1_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-2_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-3_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-4_COUNTS"))
	cntClock = epics.caget(prefix+"SG:UpDnCntr-1_COUNTS")

	success = True
	diff = -1
	for i in range(4):
		d = abs(cntClock/divBy[i] - cnt[i])
		if d > 1:
			success = 0
			if d > diff:
				diff = d

	if success:
		print "dnCntrTest: Passed"
	else:
		print "dnCntrTest: Failed: max diff=", diff
		print "cntClock=", cntClock, "cnt=", cnt, "divBy=", divBy
	return success
Example #29
0
def AD_done(detsyms,wait=True):
    """Test and optionally wait for the detector(s) have completed data collection

    :param object detsyms: An area detector variable (or name as a string), as defined in
      :func:`DefineAreaDetector`. Alternately, a list of area detectors variable or names
      (as strings) can be supplied.
    :param bool wait: If False test and return immediately; if True (default), return
      after the ``state`` command (if defined) indicates the data collection is done
      for each detector.

    :returns: True if all detector(s) are done; False is wait is False and any detectors are
      not done; or None if after 30 seconds, any detector is not complete
    """
    # is the detector specified as a string? 
    if isinstance(detsyms,str): detsyms = tuple((detsyms,))
    # is there a list of detectors?
    try:
        symList = tuple(detsyms)
    except TypeError:
        symList = tuple((detsyms,))
    alldone = True
    sleeptime = 0.0
    for sym in symList:
        detObj = globals().get(sym)
        if detObj is None: detObj = sym
        if not isinstance(detObj,_ADobject):
            raise spec.specException('AD_done error: detsyms '+str(sym)+' is not defined in DefineAreaDetector')
        # get cmdObj of correct type for the current detector ==============================
        for cmdObj in CommandDict['state']:
            if cmdObj.detectortype is None: break #  this a generic command
            if cmdObj.detectortype == detObj.detectortype: break # matches selected device
        else:
            continue
        if cmdObj.readstr == "": continue
        if cmdObj.useImagePrefix:
            PV = detObj.imageprefix + cmdObj.readstr
        else:
            PV = detObj.controlprefix + cmdObj.readstr
        if not (EPICS and spec.UseEPICS()): # in simulation
            print("Confirming detector "+detObj.symbol+" is done with collection")
            continue
        else:
            val = ep.caget(PV)
            if val == 0: continue # detector has completed
            if not wait: return False
            # detector is not done and a wait is requested
            while val != 0:
                if sleeptime > 30.0:
                    print('AD_done wait exceeded count*frames+30 seconds for'+detObj.symbol+', continuing with script')
                    return
                spec.sleep(0.1)
                sleeptime += 0.1
                val = ep.caget(PV)
    # all detector(s) have signed off as done
    return True
 def connect_epics(self):
     curr = self.current_rois
     iroi = 0
     pref = "%smca1.R" % self.prefix
     for i in range(self.nrois):
         nm = caget("%s%iNM" % (pref, i))
         hi = caget("%s%iHI" % (pref, i))
         if len(nm.strip()) > 0 and hi > 0:
             self.wids[i][0].SetLabel('  %s ' % nm)
             self.wids[i][1].SetValue(nm.lower() in curr)
             self.wids[i][1].Enable()
Example #31
0
def caput_lf(pv, value, wait=True):
    t0 = time.time()
    caput(pv, value, wait=wait)

    while time.time() - t0 < 20.0:
        time.sleep(0.02)
        if caget(lf_PVs['lf_detector_state'],
                 as_string=True) == lf_values['lf_detector_idle']:
            return True
    return False
Example #32
0
def cmdscanrel(pv, min, max, step, value):
    center=caget(pv)
    runs=loop((center-min),(center+max), step)
    for r in runs:
        print(str(datetime.datetime.now()) + " ...Rel Scanning " + pv + " at " + str(r))
        caput('BL5:SMS:RunInfo:RunTitle',"Scanrel_" + pv + "_" + str(r))
        caput(pv,r)
        caput('BL5:CS:RunControl:Start', 1)
        Wait('BL5:Det:PCharge:C', value, comparison='increase by')
        caput('BL5:CS:RunControl:Stop', 1)
Example #33
0
def caput_pil(pv, value, wait=True):
    t0 = time.time()
    caput(pv, value, wait=wait)

    while time.time() - t0 < 20.0:
        time.sleep(0.02)
        if detector_values['status_message_ok'] in caget(
                detector_pvs['status_message'], as_string=True):
            return True
    return False
Example #34
0
def ListObjectiveValue(RecordList,ArmList):
	rms = []
# put ArmList
	for num in range(len(RecordList)):
		caput(ArmList[num],1)
	for num in range(len(RecordList)):
		while(1):
			if caget(ArmList[num]) != 1:
				break
# get Value
	for num in range(len(RecordList)):
		val = []
		str = caget(RecordList[num])
		for i in range(0,2,1):
			val.append((str[i]/1000)*(str[i]/1000))
#			print(str[i])
		rms.append(math.sqrt(sum(val)))
#		print rms[num]
	return sum(rms)
 def statusBarColor(self, statusbar):
     green = QColor(0, 255, 0)
     red = QColor(255, 54, 14)
     Value = caget(self.Test_PV)
     if Value == 1.0:
         statusbar.brush.setColor(green)
         statusbar.update()
     else:
         statusbar.brush.setColor(red)
         statusbar.update()
    def test_TC_404(self):
        tc_no = "TC-404-JOGR"
        print '%s' % tc_no
        motor = self.motor
        if (self.msta & self.lib.MSTA_BIT_HOMED):
            accl = float(epics.caget(motor + '.ACCL'))
            jvel = float(epics.caget(motor + '.JVEL'))
            saved_JAR = float(epics.caget(motor + '.JAR'))
            used_JAR = jvel / (accl + 2.0)
            epics.caput(motor + '.JAR', used_JAR)
            epics.caput(motor + '.JOGR', 1, wait=True)
            resacc = self.getAcceleration(motor, tc_no)
            expacc = used_JAR
            epics.caput(motor + '.JAR', saved_JAR)
            print '%s JAR=%f expacc=%f resacc=%f' % (tc_no, used_JAR, expacc,
                                                     resacc)

            assert self.lib.calcAlmostEqual(self.motor, tc_no, expacc, resacc,
                                            2)
Example #37
0
def caput_check(name, value):
    t0 = time.time()

    while caget(name) != value:
        caput(name, value)
        poll(evt=1.e-5, iot=0.01)
        if time.time() - t0 > 10:
            print "did not set"
            return False
    return True
def fautomated_repeated_scan_busy(busy_name='7bmb1:busy5'):
    '''Performs a repeated scan.
    '''
    repeated_scan_busy_PV = epics.PV('7bmb1:busy4')
    counter = 0
    try:
        while True:
            if repeated_scan_busy_PV.value == 1:
                num_repeats = int(epics.caget('7bmb1:var:int1'))
                sec_between_pts = float(epics.caget('7bmb1:var:float6'))
                for i in range(num_repeats):
                    if repeated_scan_busy_PV.value == 0:
                        break
                    print("In the repeat loop on scan #{:3d}".format(i))
                    #Monitor for good beam
                    while epics.caget(
                            "S:SRcurrentAI.VAL") < 30.0 or epics.caget(
                                'PA:07BM:STA_A_BEAMREADY_PL.VAL') < 0.5:
                        print("Waiting for the beam to come back up.")
                        time.sleep(5.0)
                    fopen_A_shutter()
                    #Start the scan
                    epics.caput(busy_name, 'Busy')
                    time.sleep(1.0)
                    for __ in range(int(sec_between_pts)):
                        #Check to make sure we haven't clicked "Done" on repeated_scan_busy to abort this.
                        print("Waiting for the next scan.")
                        if repeated_scan_busy_PV.value == 0:
                            print("Scan aborted!")
                            break
                        time.sleep(1.0)
                repeated_scan_busy_PV.value = 0
                time.sleep(0.5)
            if counter == 100:
                print "Looking for repeated scan busy at time " + time.strftime(
                    '%H:%M:%S', time.localtime())
                counter = 0
            else:
                counter += 1
            time.sleep(0.01)
    finally:
        print("Problem in repeated scan loop.")
        fclose_A_shutter()
Example #39
0
    def __init__(self, pv_file, model=None):

        caget('vlaser@test:energy_pulse')

        super(SyncedSimCAServer, self).__init__(pv_file, model)

        pvdefs = parse_pv_file(pv_file)
        #self.monitor_pv_list = pvdefs['monitor']
        #print(self.monitor_pv_list)

        #assert 'input' in pvdefs, 'User supplied pv definitions must contain "input" pvs.'

        print('Setting monitors...')
        self.monitors = {
            mpv: PV(mpv, auto_monitor=True)
            for mpv in pvdefs['monitor']
        }
        for pv in self.monitors:
            print(pv, self.monitors[pv])
Example #40
0
def copyMotorSettings(fromMotor="18IDd:m1", toMotor="18IDd:m2"):
	motorFields = [".MRES", ".ERES", ".RRES", ".SREV", ".DIR", ".DHLM", ".DLLM", ".TWV",  
	".VBAS", ".VELO", ".ACCL", ".BDST", ".BVEL", ".BACC", ".RDBD", ".DESC",
	".EGU", ".RTRY", ".UEIP", ".URIP", ".DLY", ".RDBL", ".PREC", ".DISA",
	".DISP", ".FOFF", ".OFF", ".FRAC", ".OMSL", ".JVEL", ".JAR", ".VMAX",
	".PCOF", ".ICOF", ".DCOF", ".HVEL", ".NTM", ".NTMF", ".INIT", ".PREM",
	".POST", ".FLNK", ".RMOD"]
	for field in motorFields:
		val = epics.caget(fromMotor+field)
		epics.caput(toMotor+field, val)
Example #41
0
def writeData(header_list, numChannels, data):
    reloadFolder()
    scanNum = epics.caget(pv['Scan Number']) - 1
    scan = write.scan(scanNum)

    coordHeader = {}
    for i, key in enumerate(pv):
        if i > 2:
            coordHeader.update({key: epics.caget(pv[key])})
    coord = write.coordinate(scan, coordHeader)
    for ch in range(numChannels):
        if useChannels[ch] == '1':
            channelHeader = {
                'SerialNumber': header_list[0].SerialNumber,
                'SamplePeriod': header_list[0].SamplePeriod * .125,
                'InputRange': input_range[ch]
            }
            write.channel(coord, ch, data[ch], channelHeader)
    scan.close()
Example #42
0
 def motorReady(self, label, mtolerance):
     self.logger('%s: Checking whether motors are ready.\n'%(self.getCurrentTime()))
     ready = 0
     rules = [0] * len(label)
     while not ready:
         self.logger('%s: Motors not in position\n'%(self.getCurrentTime()))
         for i, l_ in enumerate(label):
             caput(self.pvs['%s_Rqs'%(l_)], caget(self.pvs['%s_Rqs'%(l_)]))
             time.sleep(1)
             pos_diff = abs(caget(self.pvs['%s_Rqs'%(l_)]) - caget(self.pvs['%s_Act'%(l_)]))
             rules[i] = (pos_diff < mtolerance[i])
             if rules[i]:
                 self.logger('%s: %s motor is in position with value'\
                             '%.2f um\n'%(self.getCurrentTime(), l_, caget(self.pvs['%s_Rqs'%(l_)])))
         
         if all(rules):
             ready = 1
                 
     self.logger('%s: Motors Ready \n'%(self.getCurrentTime()))
Example #43
0
def flyscan(motor='yyy:m1',start=0.0,end=3.14,npts=100,dwell=.2,scaler='yyy:scaler1'):
	recordDate = "Sun Mar  1 21:28:45 2015"
	# save prev speed
	oldSpeed = epics.caget(motor+".VELO")
	maxSpeed = epics.caget(motor+".VMAX")
	baseSpeed = epics.caget(motor+".VBAS")
	accelTime = epics.caget(motor+".ACCL")
	if maxSpeed == 0: maxSpeed = oldSpeed

	# send motor to start at normal speed
	epics.caput(motor+".VAL",start, wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.R1PV",motor+".RBV", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.P1PV",motor+".VAL", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.P1SP",start, wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.P1EP",end, wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.NPTS",npts, wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.T1PV",scaler+".CNT", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.D01PV",scaler+".S1", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.D02PV",scaler+".S2", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.P1SM","FLY", wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.P1AR","ABSOLUTE", wait=True, timeout=1000000.0)
	epics.caput(scaler+".TP",dwell, wait=True, timeout=1000000.0)
	#epics.caput("18IDd:scan1.PASM","STAY", wait=True, timeout=1000000.0)

	# calc speed including accelTime and baseSpeed
	totalTime = npts*dwell
	totalDist = abs(end-start)
	if totalTime > 2*accelTime:
		speed = (totalDist - accelTime*baseSpeed) / (totalTime - accelTime)
	else:
		speed = 2*totalDist/totalTime - baseSpeed

	if speed <= baseSpeed:
		print "desired speed=%f less than base speed %f" % (speed, baseSpeed)
		speed = baseSpeed+.01
	if speed > maxSpeed:
		print "desired speed=%f greater than max speed %f" %(speed, maxSpeed)
		speed = maxSpeed

	#print "speed=%f" % speed
	epics.caput(motor+".VELO",speed, wait=True, timeout=1000000.0)
	epics.caput("18IDd:scan1.EXSC","1", wait=True, timeout=1000000.0)
	epics.caput(motor+".VELO",oldSpeed, wait=True, timeout=1000000.0)
Example #44
0
def PWR_read_CalSys(pv_set,var,inf_flag='inf',ofs_flag='noofs',avg='noavg'):
	if(var.startswith('RFIn')):
		RFIn=int(var[4:])
		if(RFIn<1 or RFIn>15):
			raise ValueError('Channel '+str(RFIn)+' does not exist')
	else:
		raise ValueError('Channel '+var+' does not exist')


	pwr_pv=pv_set[RFIn-1]
	if(avg=='noavg'):
		pwr=pwr_pv.get()
		if (pwr<-42 and inf_flag!='noinf'):
			return -np.inf
		if(ofs_flag=='ofs'):
			ofs=ep.caget('RA-RaBO01:RF-LLRFCalSys:OFSdB'+str(RFIn)+'-Mon')
			return pwr+ofs
		return pwr
	else:
		try:
			avg_size=int(avg)
		except ValueError:
			raise ValueError('Avg parameter is not an integer')
		global val
		global measurements
		clean_val()
		val.append(pwr_pv.get())
		measurements=1
		timeout=1.5*avg_size
		pwr_pv.add_callback(GEN_PV_average)
		start_time=time.perf_counter()
		while measurements<avg_size and time.perf_counter()-start_time<timeout:
			pass
		pwr_pv.clear_callbacks()
		if(measurements<avg_size):
			logging.warning(var+' PWR read timeout:'+str(measurements)+' measurements taken')
		avg=sum(val)/len(val)
		if(avg<-42 and inf_flag!='noinf'):
			return -np.inf
		if(ofs_flag=='ofs'):
			ofs=ep.caget('RA-RaBO01:RF-LLRFCalSys:OFSdB'+str(RFIn)+'-Mon')
			return avg+ofs
		return avg
Example #45
0
    def waitForMirror(self, statusPV, lockPV, mirror, desiredPosition):
        self.printMessage('Checking ' + mirror + ' Mirror Position for ' +
                          desiredPosition + '...')

        while not caget(statusPV):
            QApplication.processEvents()
            sleep(1)
        self.printMessage('Detected ' + mirror + ' Mirror in ' +
                          desiredPosition + ' Position')
        caput(lockPV, '0')
Example #46
0
 def update_detectors(self):
     # TODO check first if a scan is running!
     self.active_detectors.clear()
     for i in range(1, self.NUM_DETECTORS + 1):
         nv_branch = 'D%2.2iNV' % i
         if caget(self.trunk + nv_branch) == 0:
             pv_key = 'D%2.2iPV' % i
             new_trunk, new_branch = os.path.splitext(
                 self.dnnpv[pv_key].value)
             record = caget(new_trunk + '.RTYP')
             if record == 'scaler':
                 if new_branch != '.T':
                     name_branch = new_branch.replace('S', 'NM')
                 else:
                     print new_branch
                     name_branch = 'Elapsed Time'
             elif record == 'transform':
                 name_branch = new_branch[:1] + 'CMT' + new_branch[1:]
             elif record == 'mca':
                 name_branch = new_branch + 'NM'
             else:
                 name_branch = None
             if name_branch:
                 if name_branch == 'Elapsed Time':
                     name = name_branch
                 else:
                     name = caget(new_trunk + name_branch)
                     if name == '':
                         name = new_trunk + new_branch
             else:
                 name = new_trunk + new_branch
             print name
             # TODO send name out to GUI labels
             det_key = pv_key.replace('P', 'C')
             self.active_detectors[det_key] = np.zeros(self.MAX_NUM_POINTS)
         else:
             name = ''
         if not type(name) == str:
             name = str(name)
         cb_key = 'D%2.2iCB' % i
         eye.dnncb[cb_key].setText(name)
     print self.active_detectors
Example #47
0
 def check_state(self, adned, state):
     """
     Verify that the ADnED state is what it should be.
     """
     _detector_state = adned + ":DetectorState_RBV"
     detector_state = caget(_detector_state)
     if (detector_state != state):
         print "ERROR: ADnED state is: " + str(detector_state) + " and it should be: " + str(state)
         return self.__g.FAIL
     
     return self.__g.SUCCESS
Example #48
0
    def verify(self, adned, value):
        """

    ling
        Verify that adned record == value.
        """
        if (caget(adned) != value):
            msg = " ERROR: " + adned + " not equal to " + str(value)
            raise Exception(__name__ + msg)

        return self.__g.SUCCESS
Example #49
0
def turbo():
    current_T = cryostream.T.get()
    tb = caget("XF:28ID1-ES:1{Env:01}Cmd:Turbo-Cmd")
    if current_T <= turbo_T and tb == 0:
        caput("XF:28ID1-ES:1{Env:01}Cmd:Turbo-Cmd", 1)
        time.sleep(2)
        caput("XF:28ID1-ES:1{Env:01}Cmd-Cmd", 20)
    if current_T >= turbo_T and tb == 1:
        caput("XF:28ID1-ES:1{Env:01}Cmd:Turbo-Cmd", 0)
        time.sleep(2)
        caput("XF:28ID1-ES:1{Env:01}Cmd-Cmd", 20)
    def test_TC_100(self):
        motor = self.motor
        tc_no = "TC-100"
        print '%s Home the motor' % tc_no
        msta = int(epics.caget(motor + '.MSTA'))
        if (msta & self.lib.MSTA_BIT_PLUS_LS):
            epics.caput(motor + '.HOMR', 1)
        else:
            epics.caput(motor + '.HOMF', 1)
        time_to_wait = 30
        if self.range_postion > 0 and self.homing_velocity > 0:
            time_to_wait = 1 + self.range_postion / self.homing_velocity + 2 * self.acceleration

        # Homing velocity not implemented, wait longer
        time_to_wait = 180
        done = self.lib.waitForStartAndDone(motor, tc_no, time_to_wait)

        msta = int(epics.caget(motor + '.MSTA'))
        self.assertEqual(True, done, 'done = True')
        self.assertNotEqual(0, msta & self.lib.MSTA_BIT_HOMED, 'MSTA.homed (Axis has been homed)')
Example #51
0
    def __init__(self, title, pvname, scale, start, end, nsteps):

        self.pv = PV(pvname,auto_monitor=True)
         
        self.scale= float(scale)

        start=float(start)
        end=float(end)
        
        self.slider = Slider(title=title, value=scale*caget(pvname), start=start, end=end, step=(end-start)/nsteps)
        self.slider.on_change('value', self.set_pv_from_slider)
Example #52
0
    def check_sample_point_distances(self, pos_x, pos_y, pos_z):
        cur_x = float(epics.caget(self.hor_motor_name + '.RBV',
                                  as_string=True))
        cur_y = float(epics.caget(self.ver_motor_name + '.RBV',
                                  as_string=True))
        cur_z = float(
            epics.caget(self.focus_motor_name + '.RBV', as_string=True))

        largest_distance = np.sqrt((float(pos_x) - cur_x)**2 +
                                   (float(pos_y) - cur_y)**2 +
                                   (float(pos_z) - cur_z)**2)

        if largest_distance > 0.2:
            reply = self.show_continue_abort_message_box(
                'Current and image positions are far away from each other. Are you sure, you want to move?'
            )
            if reply == QtWidgets.QMessageBox.Abort:
                return False

        return True
Example #53
0
 def epicswarning(self, widget1, widget2, prefix, flg):
     # widget1 = input, widget2 = warning sign, prefix = epics motor name, flg = on/off
     num0 = widget1.text()
     time.sleep(0.02)
     try:
         num1 = float(num0)
         HLM = epics.caget(prefix + '.HLM')
         LLM = epics.caget(prefix + '.LLM')
         if num1 > HLM:
             widget2.setText('high lim')
             return flg * 0
         elif num1 < LLM:
             widget2.setText('low lim')
             return flg * 0
         else:
             widget2.setText('')
             return flg
     except:
         widget2.setText('not num')
         return flg * 0
def test_with_caget_nomonitor():
    pv = PV(mypv, auto_monitor=True, callback=lambda **args:...)
    pv.wait_for_connection()

    # check that the PV is connected and  data is received
    assert pv.connected is True
    assert pv.get() is not None

    # use caget to get data from the same PV
    assert caget(mypv, use_monitor=False) is not None

    # disconnect PV object
    pv.disconnect()

    # check that the PV is disconnected and doesn't receive data
    assert pv.connected is False
    assert pv.get() is None

    # check that you can still use caget to get data from the same PV
    assert caget(mypv, use_monitor=False) is not None
Example #55
0
 def waitForMipZero(self, motor, tc_no, wait_for_MipZero):
     while wait_for_MipZero > -10.0:  # Extra long wait
         wait_for_MipZero -= polltime
         mip = int(epics.caget(motor + '.MIP', use_monitor=False))
         print '%s: wait_for_MipZero=%f mip=%s (%x)' % (
             tc_no, wait_for_MipZero, self.getMIPtext(mip), mip)
         if not mip:
             return True
         time.sleep(polltime)
         wait_for_MipZero -= polltime
     return False
    def __init__(self, title, pvname, scale, start, end, step):

        self.pvname = pvname
        self.scale = scale

        self.slider = Slider(title=title,
                             value=scale * caget(pvname),
                             start=start,
                             end=end,
                             step=step)
        self.slider.on_change('value', self.set_pv_from_slider)
Example #57
0
def read_cam_positions():
    global CAM_ANGLE_DEG
    global CAM_ANGLE_RAD
    #    CAM_ANGLE_DEG = [caget(PV_CALL_PREFIX % {"cam": cam, "suffix": "MOTOR.RBV"}) for cam in CAM_PVS]
    CAM_ANGLE_DEG = [
        caget(PV_CALL_PREFIX % {
            "cam": cam,
            "suffix": "READDEG"
        }) for cam in CAM_PVS
    ]
    CAM_ANGLE_RAD = map(lambda value: value * np.pi / 180, CAM_ANGLE_DEG)
Example #58
0
def get_record_by_name(record_name, *, timeout=1.0, **kwargs):
    if '.' in record_name:
        record_name = record_name.split('.')[0]

    rtyp_pvname = '{}.RTYP'.format(record_name)
    record_type = epics.caget(rtyp_pvname, timeout=timeout)
    if record_type is None:
        raise TimeoutError('Timed out requesting record type')

    record_class = get_record_class(record_type)
    return record_class(record_name, **kwargs)
 def test_TC_1232(self):
     motor = self.motor
     if (self.msta & self.lib.MSTA_BIT_HOMED):
         tc_no = "TC-1232-90-percent-UserPosition"
         print '%s' % tc_no
         destination = self.per90_UserPosition
         res = self.lib.move(motor, destination, 60)
         UserPosition = epics.caget(motor + '.RBV', use_monitor=False)
         print '%s postion=%f per90_UserPosition=%f' % (
             tc_no, UserPosition, self.per90_UserPosition)
         self.assertEqual(res, self.__g.SUCCESS, 'move returned SUCCESS')
Example #60
0
def test(LearningRate, obj_record_list, arm_list, tbt_list):
    """Optimize 
	Input : objective record name list
	Output: non
	"""
    Rate = LearningRate
    x = []
    y = []
    grad = []
    knob = []
    tmp = []
    tmp2 = []
    for i in range(len(obj_record_list)):
        grad.append(Gradient(obj_record_list[i], arm_list, tbt_list))
        knob.append(caget(obj_record_list[i], timeout=5))
    tmp = knob
    tmp2 = knob
    #	print grad,knob,tmp
    k = 0
    sum = 0
    sum2 = 0  # prev
    sum3 = 0  # follow
    for i in range(10):
        # 		if i==0:
        # 			for k in range(5):
        # 				sum += obj.List_Value(arm_list,tbt_list)
        # 			prev = sum
        # 			follw = prev
        if i >= 1 and prev < follw:
            for j in range(len(obj_record_list)):
                #				tmp[j] = knob[j] - (LearningRate-Rate)*grad[j]
                caput(obj_record_list[j], tmp2[j])
            break

        sum2 = 0
        for k in range(8):
            sum2 += obj.List_Value(arm_list, tbt_list)
        prev = sum2

        for j in range(len(obj_record_list)):
            tmp[j] = knob[j] - LearningRate * grad[j]
        for j in range(len(obj_record_list)):
            caput(obj_record_list[j], tmp[j])
        tmp2 = tmp
        sum3 = 0
        for k in range(8):
            sum3 += obj.List_Value(arm_list, tbt_list)
        follw = sum3
        #		x.append(LearningRate)
        #		y.append(follw/100000)
        print tmp, LearningRate, follw
        LearningRate += Rate

    print "optimized =", tmp, LearningRate, follw