def test(): loggers = ('ophyd.controls.cas', ) config.setup_loggers(loggers) logger = config.logger session = config.session server = session.cas motor_record = config.motor_recs[0] mrec = EpicsMotor(motor_record) logger.info('--> PV Positioner, using put completion and a DONE pv') # PV positioner, put completion, done pv pos = PVPositioner(mrec.field_pv('VAL'), readback=mrec.field_pv('RBV'), done=mrec.field_pv('MOVN'), done_val=0, stop=mrec.field_pv('STOP'), stop_val=1, put_complete=True, limits=(-2, 2), egu='unknown', ) def updated(value=None, **kwargs): print('Updated to: %s' % value) cas_motor = CasMotor('m1', pos, server=server) print(cas_motor.severity) record_name = cas_motor.full_pvname for i in range(2): epics.caput(record_name, i, wait=True) print(pos.position) return cas_motor
def test(): loggers = ('ophyd.controls.signal', 'ophyd.controls.positioner', 'ophyd.session', ) config.setup_loggers(loggers) fm = config.fake_motors[0] if 0: pos0 = PVPositioner(fm['setpoint'], readback=fm['readback'], act=fm['actuate'], act_val=1, stop=fm['stop'], stop_val=1, done=fm['moving'], done_val=1, put_complete=False, ) else: motor_record = config.motor_recs[0] pos0 = EpicsMotor(motor_record) det = [EpicsSignal(pv, rw=False) for pv in config.fake_sensors] # pos0_traj = [0, 0.1, 0.2] pos0_traj = np.linspace(0, 1, 5) traj, data = simple_scan(motors=[pos0], trajectories=[pos0_traj], triggers=[], detectors=det, dwell_time=1.0) print(traj, data)
def test(): loggers = ('ophyd.controls.areadetector', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger det1 = config.sim_areadetector[0] det1_prefix = det1['prefix'] det1_cam = det1['cam'] # Instantiate a plugin directly img1 = ImagePlugin(det1_prefix, suffix='image1:') img = img1.image plt.imshow(img, cmap=plt.cm.gray) logger.debug('Image shape=%s dtype=%s' % (img.shape, img.dtype)) logger.debug('Image pixels=%s dtype=%s' % (img1.array_pixels, img1.data_type.value)) plt.show() # Or reference that plugin from the detector instance ad = AreaDetector(det1_prefix, cam=det1_cam, images=['image1:', ]) img = ad.image1.image plt.imshow(img, cmap=plt.cm.gray) plt.show()
def test(): loggers = ('ophyd.controls.cas', ) config.setup_loggers(loggers) session = config.session server = session.cas def updated(value=None, **kwargs): print('Updated to: %s' % value) python_pv = CasPV(config.server_pvnames[0], 123.0, server=server) # full_pvname includes the server prefix pvname = python_pv.full_pvname signal = EpicsSignal(pvname) signal.subscribe(updated) time.sleep(0.1) for i in range(10): python_pv.value = i time.sleep(0.05)
def test(): global logger def callback(sub_type=None, timestamp=None, value=None, **kwargs): logger.info('[callback] [%s] (type=%s) value=%s' % (timestamp, sub_type, value)) def done_moving(**kwargs): logger.info('Done moving %s' % (kwargs, )) loggers = ('ophyd.controls.signal', 'ophyd.controls.positioner', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger fm = config.fake_motors[0] # ensure we start at 0 for this simple test epics.caput(fm['setpoint'], 0) epics.caput(fm['actuate'], 1) time.sleep(2) if 0: pos = PVPositioner(fm['setpoint'], readback=fm['readback'], act=fm['actuate'], act_val=1, stop=fm['stop'], stop_val=1, done=fm['moving'], done_val=1, put_complete=False, ) pos.subscribe(callback, event_type=pos.SUB_DONE) pos.subscribe(callback, event_type=pos.SUB_READBACK) logger.info('---- test #1 ----') logger.info('--> move to 1') pos.move(1) logger.info('--> move to 0') pos.move(0) logger.info('---- test #2 ----') logger.info('--> move to 1') pos.move(1, wait=False) time.sleep(0.5) logger.info('--> stop') pos.stop() logger.info('--> sleep') time.sleep(1) logger.info('--> move to 0') pos.move(0, wait=False, moved_cb=done_moving) logger.info('--> post-move request, moving=%s' % pos.moving) time.sleep(2) # m2.move(1) put_complete_test()
def test(): loggers = ('ophyd.controls.signal', 'ophyd.controls.scaler', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger sca = scaler.EpicsScaler(config.scalers[0]) sca.preset_time = 5.2 logger.info('Counting in One-Shot mode for %f s...' % sca.preset_time) sca.start() logger.info('Sleeping...') time.sleep(3) logger.info('Done sleeping. Stopping counter...') sca.stop() logger.info('Set mode to AutoCount') sca.count_mode = ScalerMode.AUTO_COUNT sca.start() logger.info('Begin auto-counting (aka "background counting")...') time.sleep(2) logger.info('Set mode to OneShot') sca.count_mode = ScalerMode.ONE_SHOT time.sleep(1) logger.info('Stopping (aborting) auto-counting.') sca.stop() logger.info('read() all channels in one-shot mode...') vals = sca.read() logger.info(vals) channels = (1,3,5,6) logger.info('read() selected channels %s in one-shot mode...' % list(channels)) vals = sca.read(channels) logger.info(vals)
def test(): def callback(sub_type=None, timestamp=None, value=None, **kwargs): logger.info('[callback] [%s] (type=%s) value=%s' % (timestamp, sub_type, value)) # Test that the monitor dispatcher works (you cannot use channel access in # callbacks without it) logger.info('[callback] caget=%s' % rw_signal.get()) loggers = ('ophyd.controls.signal', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger motor_record = config.motor_recs[0] val = record_field(motor_record, 'VAL') rbv = record_field(motor_record, 'RBV') rw_signal = EpicsSignal(rbv, write_pv=val) # put_complete=True) rw_signal.subscribe(callback, event_type=rw_signal.SUB_VALUE) rw_signal.subscribe(callback, event_type=rw_signal.SUB_SETPOINT) rw_signal.value = 2 time.sleep(1.) rw_signal.value = 1 time.sleep(1.) # You can also create a Python Signal: sig = Signal(name='testing', value=10) logger.info('Python signal: %s' % sig) # Even one with a separate setpoint/readback value: sig = Signal(name='testing', value=10, setpoint=2, separate_readback=True) logger.info('Python signal: %s' % sig)
def test(): def log_values(obj): port_name = obj.port_name.value for attr, signal in sorted(obj.signals.items()): name = "%s.%s" % (port_name, attr) logger.debug('(epics) %s %s=%s' % (name, signal.pvname, signal.value)) loggers = ('ophyd.controls.areadetector', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger det1 = config.sim_areadetector[0] det1_prefix = det1['prefix'] det1_cam = det1['cam'] for type_, suffix_list in config.ad_plugins.items(): if type_ == 'overlay': continue for suffix in suffix_list: plugin = get_areadetector_plugin(det1_prefix, suffix) # Note: the below will print out every EpicsSignal attribute for # every plugin, image, etc. and will take a while: if 0: log_values(plugin) if 0: dump_pvnames(plugin) if type_ != 'file': break det = SimDetector(det1_prefix, cam=det1_cam) det.image_mode = 'Single' det.image1.enable = 'Enable' det.array_callbacks = 'Enable' img = det.read() print('Image: %s' % img) det.tiff1.file_template = '%s%s_%3.3d.tif' logger.debug('template value=%s' % det.tiff1.file_template.value) logger.debug('full filename=%s' % det.tiff1.full_file_name.value) log_values(det) # det.acquire = 1 # logger.info('Acquired filename(s): {}'.format(det.tiff1.get_filenames())) logger.debug('acquire = %d' % det.acquire.value) image1_suffix = config.ad_plugins['image'][0] img1 = ImagePlugin(det1_prefix, suffix=image1_suffix) # or: img1 = det.image1 # log_all(img1) logger.debug('nd_array_port = %s' % img1.nd_array_port.value) # ensure EPICS_CA_MAX_ARRAY_BYTES set properly... if 1: img1.array_data.value proc1_suffix = config.ad_plugins['proc'][0] proc1 = ProcessPlugin(det1_prefix, suffix=proc1_suffix) # or: proc1 = det.proc1 # Signal group allows setting value as a list: logger.debug('fc=%s' % proc1.fc.value) proc1.fc = [1, 2, 3, 4] time.sleep(0.1) logger.debug('fc=%s from %s' % (proc1.fc.value, proc1.fc.pvname)) # But they can be accessed individually as well logger.debug('(fc1=%s, fc2=%s, fc3=%s, fc4=%s)' % (proc1._fc1.value, proc1._fc2.value, proc1._fc3.value, proc1._fc4.value)) # Reset them to the default values proc1.fc = [1, -1, 0, 1] time.sleep(0.1) logger.debug('reset to fc=%s' % proc1.fc.value) # if using IPython, try the following: # In [0]: run areadetector.py # # In [1]: help(proc1) overlay_suffix, over_start, over_count = config.ad_plugins['overlay'][0] over1 = OverlayPlugin(det1_prefix, suffix=overlay_suffix, count=over_count, first_overlay=over_start) logger.debug('Overlay1:1 blue=%s' % over1.overlays[0].blue) return proc1, over1
def test(): loggers = ('ophyd.utils.hkl', ) config.setup_loggers(loggers) logger = config.logger logger.info('Diffractometer types: %s' % ', '.join(diffractometer_types)) logger.info('') logger.info('---- calck6c ----') k6c = CalcK6C(engine='hkl') # or equivalently: # k6c = CalcRecip('K6C', engine='hkl') logger.info(k6c.engines) logger.info(k6c['mu']) logger.info(k6c[k6c.physical_axis_names[0]].limits) # geometry holds physical motor information logger.info('physical axes (depends on diffr. type): {}'.format(k6c.physical_axis_names)) # engine holds pseudo motor information logger.info('pseudo axes (depends on engine): {}'.format(k6c.pseudo_axis_names)) logger.info('engine parameters: {}'.format(k6c.parameters)) logger.info('hkl 1, 1, 1 corresponds to real motor positions: {}'.format(list(k6c([1, 0.99, 1])))) logger.info('') logger.info('---- k6c.sample ----') sample = k6c.sample refl = sample.add_reflection(1, 1, 1) sample.remove_reflection(refl) sample.clear_reflections() lim = (0.0, 20.0) k6c['mu'].limits = lim logger.info('mu limits: {}'.format(k6c['mu'].limits)) assert(k6c['mu'].limits == lim) k6c['h'] = 1.0 k6c['mu'] = 0.55 logger.info('pseudo={} physical={}'.format(dict(k6c.engine.pseudo_axes), dict(k6c.physical_axes))) sample.add_reflection(1, 1, 1) sample.add_reflection(1, 0, 1) sample.add_reflection(1, 0, 0) logger.info(sample.reflection_measured_angles) logger.info(sample.reflection_theoretical_angles) logger.info(sample.reflections) k6c.sample.name = 'main_sample' sample2 = k6c.new_sample('sample2') try: k6c.new_sample('sample2') except ValueError: pass else: sample2 raise Exception k6c.sample = 'main_sample' logger.info('') logger.info('---- k6c matrix, lattice, engines ----') sample.U = [[1, 1, 1], [1, 0, 0], [1, 1, 0]] logger.info('U=%s' % sample.U) # sample.UB = [[1, 1, 1], [1, 0, 0], [1, 1, 0]] logger.info('UB=%s' % sample.UB) logger.info('ux, uy, uz=%s, %s, %s' % (sample.ux, sample.uy, sample.uz)) logger.info('lattice=%s reciprocal=%s' % (sample.lattice, sample.reciprocal)) logger.info('main_sample=%s' % sample) # logger.info(k6c) logger.info('') logger.info('current engine is: {}'.format(k6c.engine)) logger.info('available engines:') for engine, info in k6c.engines.items(): logger.info('-> {}: {}'.format(engine, info)) # TODO compute_UB affects sample state? # logger.info('computed ub=%s' % sample.compute_UB([1, 1, 1], [1, 0, 1])) logger.info('wavelength is %s nm (energy=%s keV)' % (k6c.wavelength, k6c.energy)) logger.info('hkl mode is %s (can be: %s)' % (k6c.engine.mode, k6c.engine.modes)) logger.info('* single position') list(k6c([0, 1, 0])) logger.info('* 10 positions between two hkls') for solutions in k6c([0, 1, 0], [0, 1, 0.1], n=10): logger.info('choosing {} of {} solutions'.format(solutions[0], len(solutions))) logger.info('* 3 specific hkls') list(k6c([[0, 1, 0], [0, 1, 0.01], [0, 1, 0.02]])) q2_recip = CalcRecip('K6C', engine='q2') logger.info('q is {}'.format(q2_recip['q'])) logger.info('alpha is {}'.format(q2_recip['alpha'])) assert(len(list(q2_recip([[1, 2], ]))) == 1) assert(len(list(q2_recip([[1, 2], [3, 4]]))) == 2) assert(len(list(q2_recip([1, 2], [3, 4], n=20))) == 21) logger.info('') logger.info('---- calce4ch ----') e4ch = CalcE4CH() logger.info('e4ch axes: {} {}'.format(e4ch.pseudo_axis_names, e4ch.physical_axis_names)) logger.info('') logger.info('---- diffractometer ----') class MyE4CH(E4CH): h = Cpt(PseudoSingle, '') k = Cpt(PseudoSingle, '') l = Cpt(PseudoSingle, '') omega = Cpt(FakeMotor, '') chi = Cpt(FakeMotor, '') phi = Cpt(FakeMotor, '') tth = Cpt(FakeMotor, '') diffr = MyE4CH('', name='my_e4ch', energy=8.0, ) # this will run the callbacks to force a readback pseudo position # calculation: (not normally used, since they should be tied to real # motors) for i, pos in enumerate(diffr.real_positioners): pos._set_position(0.1 * (i + 1)) calc = diffr.calc sample = calc.sample sample.add_reflection(1, 1, 1) def show_pos(): print('pseudo positioners', diffr.pseudo_positioners) _pseudos = [(pos.name, pos.position) for pos in diffr.pseudo_positioners] _reals = [(pos.name, pos.position) for pos in diffr.real_positioners] logger.info('pseudo positioner is at {}'.format(_pseudos)) logger.info('real positioners: {}'.format(_reals)) show_pos() logger.info('') diffr.move((1, 0, 1), wait=True) diffr.energy = 10.0 diffr.move((1, 0, 1), wait=True) logger.info('') show_pos() sample = diffr.calc.sample logger.info(diffr.calc) return k6c, diffr
import time import config from ophyd import scaler from ophyd.utils import enum ScalerMode = enum(ONE_SHOT=0, AUTO_COUNT=1) loggers = ( 'ophyd.signal', 'ophyd.scaler', ) config.setup_loggers(loggers) logger = config.logger sca = scaler.EpicsScaler(config.scalers[0]) sca.preset_time.put(5.2, wait=True) logger.info('Counting in One-Shot mode for %f s...', sca.preset_time.get()) sca.trigger() logger.info('Sleeping...') time.sleep(3) logger.info('Done sleeping. Stopping counter...') sca.count.put(0) logger.info('Set mode to AutoCount') sca.count_mode.put(ScalerMode.AUTO_COUNT, wait=True) sca.trigger() logger.info('Begin auto-counting (aka "background counting")...')
import time import config from ophyd import scaler from ophyd.utils import enum ScalerMode = enum(ONE_SHOT=0, AUTO_COUNT=1) loggers = ('ophyd.signal', 'ophyd.scaler', ) config.setup_loggers(loggers) logger = config.logger sca = scaler.EpicsScaler(config.scalers[0]) sca.preset_time.put(5.2, wait=True) logger.info('Counting in One-Shot mode for %f s...', sca.preset_time.get()) sca.trigger() logger.info('Sleeping...') time.sleep(3) logger.info('Done sleeping. Stopping counter...') sca.count.put(0) logger.info('Set mode to AutoCount') sca.count_mode.put(ScalerMode.AUTO_COUNT, wait=True) sca.trigger() logger.info('Begin auto-counting (aka "background counting")...')
def test(): def callback(sub_type=None, timestamp=None, value=None, **kwargs): logger.info('[callback] [%s] (type=%s) value=%s' % (timestamp, sub_type, value)) def done_moving(**kwargs): logger.info('Done moving %s' % (kwargs, )) loggers = ('ophyd.controls.signal', 'ophyd.controls.positioner', 'ophyd.session', ) config.setup_loggers(loggers) logger = config.logger motor_record = config.motor_recs[0] m1 = EpicsMotor(motor_record) # m2 = EpicsMotor('MLL:bad_record') m1.subscribe(callback, event_type=m1.SUB_DONE) m1.subscribe(callback, event_type=m1.SUB_READBACK) # print(m1.user_readback.read()) # print(m1.read()) logger.info('---- test #1 ----') logger.info('--> move to 1') m1.move(1) logger.info('--> move to 0') m1.move(0) logger.info('---- test #2 ----') logger.info('--> move to 1') m1.move(1, wait=False) time.sleep(0.2) logger.info('--> stop') m1.stop() logger.info('--> sleep') time.sleep(1) logger.info('--> move to 0') m1.move(0, wait=False, moved_cb=done_moving) time.sleep(2) logger.debug('limits are: {}'.format(m1.limits)) low_lim, high_lim = m1.low_limit, m1.high_limit try: m1.move(high_lim + 1) except LimitError as ex: logger.debug('Failed move, as expected (%s)' % ex) else: raise ValueError('Move should have failed') try: m1.move(low_lim - 1) # LimitError is a ValueError, so either can be caught except ValueError as ex: logger.debug('Failed move, as expected (%s)' % ex) else: raise ValueError('Move should have failed') try: m1.check_value(low_lim - 1) except ValueError as ex: logger.debug('Failed check_value, as expected (%s)' % ex) else: raise ValueError('check_value should have failed') logger.info('--> move to 0') stat = m1.move(2, wait=False) while not stat.done: logger.info('--> moving... %s error=%s' % (stat, stat.error)) time.sleep(0.1) logger.debug(m1.get(as_string=True)) logger.debug(m1.setpoint_ts) logger.debug(m1.timestamp) logger.debug(m1.pvname) logger.debug(m1.setpoint_pvname) fmt = '%%.%df' % m1.precision logger.debug('precision formatting: %s '% fmt) string_pos = fmt % m1.position logger.debug('final position: %s' % string_pos)