def test_synaxis_timestamps(): from ophyd.status import wait import time def time_getter(m): return {k: v['timestamp'] for k, v in m.read().items()} def tester(m, orig_time): new_time = time_getter(m) assert orig_time != new_time return new_time motor = SynAxis(name='motor1') motor.delay = .01 orig_time = time_getter(motor) wait(motor.set(3)) orig_time = tester(motor, orig_time) wait(motor.setpoint.set(4)) orig_time = tester(motor, orig_time) motor.setpoint.put(3) time.sleep(2*motor.delay) orig_time = tester(motor, orig_time)
def test_synaxis_subcribe(): hits = dict.fromkeys(['r', 's', 'a'], 0) vals = dict.fromkeys(['r', 's', 'a'], None) def p1(tar, value): hits[tar] += 1 vals[tar] = value motor = SynAxis(name='motor1') # prime the cb cache so these run an subscription motor.set(0) motor.subscribe(lambda *, value, _tar='a', **kwargs: p1(_tar, value)) motor.readback.subscribe(lambda *, value, _tar='r', **kwargs: p1(_tar, value)) motor.setpoint.subscribe(lambda *, value, _tar='s', **kwargs: p1(_tar, value)) assert vals['r'] == motor.readback.get() assert vals['a'] == motor.readback.get() assert vals['s'] == motor.setpoint.get() assert all(v == 1 for v in hits.values()) motor.set(1) assert vals['r'] == motor.readback.get() assert vals['a'] == motor.readback.get() assert vals['s'] == motor.setpoint.get() assert all(v == 2 for v in hits.values())
dcm_x.llm.put(0) dcm_x.velocity.put(0.6) dcm_x._limits = (0, 68) ## this is about as fast as this motor can go, 1.25 results in a following error dcm_para.velocity.put(0.4) dcm_para.hvel_sp.put(0.4) dcm_perp.velocity.put(0.2) dcm_perp.hvel_sp.put(0.2) #dcm_para.llm.put(12.3) #dcm_para.hlm.put(158.5) dcm_perp.llm.put(1.39) dcm_perp.hlm.put(26.5) if dcm_x.user_readback.get() > 10: dcm.set_crystal('311') else: dcm.set_crystal('111') else: dcm_bragg = SynAxis(name='dcm_bragg') dcm_pitch = SynAxis(name='dcm_pitch') dcm_roll = SynAxis(name='dcm_roll') dcm_perp = SynAxis(name='dcm_perp') dcm_para = SynAxis(name='dcm_para') dcm_x = SynAxis(name='dcm_x') dcm_y = SynAxis(name='dcm_y') dcmlist = [dcm_bragg, dcm_pitch, dcm_roll, dcm_perp, dcm_para, dcm_x, dcm_y] mcs8_motors.extend(dcmlist)
if rv is not None: logging.error('%s' % rv) RE = RunEngine({}) # cpo thinks this is more for printout of each step from bluesky.callbacks.best_effort import BestEffortCallback bec = BestEffortCallback() # Send all metadata/data captured to the BestEffortCallback. RE.subscribe(bec) from ophyd.sim import motor1, SynAxis from bluesky.plans import scan step_value = SynAxis(name='step_value') # instantiate DaqScan object mydaq = DaqScan(control, daqState=daqState, args=args) dets = [mydaq] # just one in this case, but it could be more than one # configure DaqScan object with a set of motors mydaq.configure(motors=[motor1, step_value]) # Scan motor1 from -10 to 10 and step_value from 0 to 14, stopping # at 15 equally-spaced points along the way and reading dets. RE(scan(dets, motor1, -10, 10, step_value, 0, 14, 15)) mydaq.push_socket.send_string('shutdown') #shutdown the daq thread mydaq.comm_thread.join()
import logging import pytest from bluesky.plan_stubs import rel_set from bluesky.preprocessors import run_wrapper from ophyd.sim import SynAxis from ..plans.preprocessors import return_to_start logger = logging.getLogger(__name__) m1 = SynAxis(name="m1") m2 = SynAxis(name="m2") motors = [m1, m2] @pytest.mark.parametrize("return_devices", [[], [m1], [m1, m2]]) def test_return_to_start_returns_motors_correctly(fresh_RE, return_devices): # Grab the initial positions initial_positions = [mot.position for mot in motors] final_positions = [] # Create the plan @return_to_start(*return_devices) def test_plan(): for mot in motors: yield from rel_set(mot, 1) # Grab the final positions final_positions.append(mot.position) # Run the plan
def get_calib_motor(request): m1 = SynAxis(name="m1") m2 = SynAxis(name="m2") return CalibTest("test", m1=m1, m2=m2)
from ophyd.sim import det1, noisy_det from ophyd.device import Device, Component as Cpt from ophyd.signal import EpicsSignalRO, AttributeSignal import pcdsdevices """ Creates a RunEngine, and uses BestEffortCallback for nice visualizations during the scan """ RE = RunEngine() bec = BestEffortCallback() RE.subscribe(bec) install_qt_kicker() # Create the motor x = SynAxis(name='x') def basic_event_builder(*args, **kwargs): """ Pass any number of pandas Series and return an event built pandas DataFrame. Kwargs can be used to name the columns of the returned DataFrame. """ data_table = dict() [data_table.setdefault(col, args[col]) for col in range(len(args))] [data_table.setdefault(col, kwargs[col]) for col in kwargs] full_frame = pd.DataFrame(data_table) return full_frame.dropna()
def motor(): return SynAxis(name='motor')
import numpy as np from hutch_python.utils import safe_load from ophyd.sim import SynAxis # Test axes that may come in handy with safe_load('Virtual Motors'): virtual_motor_1 = SynAxis(name='Virtual Motor 1') virtual_motor_2 = SynAxis(name='Virtual Motor 2') virtual_motor_3 = SynAxis(name='Virtual Motor 3')
import logging import numpy as np from bluesky.preprocessors import run_wrapper from ophyd.sim import SynAxis from .conftest import Diode from ..plans.alignment import maximize_lorentz, rocking_curve logger = logging.getLogger(__name__) crystal = SynAxis(name='angle') def test_lorentz_maximize(fresh_RE): # Simulated diode readout diode = Diode('intensity', crystal, 'angle', 10.0, noise_multiplier=None) # Create plan to maximize the signal plan = run_wrapper(maximize_lorentz(diode, crystal, 'intensity', step_size=0.2, bounds=(9., 11.), position_field='angle', initial_guess = {'center' : 8.})) # Run the plan fresh_RE(plan) # Trigger an update diode.trigger() #Check that we were within 10% assert np.isclose(diode.read()['intensity']['value'], 1.0, 0.1) def test_rocking_curve(fresh_RE): # Simulated diode readout
parser = argparse.ArgumentParser(description='Spatial overlap of timetool') parser.add_argument('--sim', action='store_true', default=False, help='Do a simulated scan') args = parser.parse_args() # Interactive matplotlib mode plt.ion() # Create a RunEngine RE = RunEngine() # Use BestEffortCallback for nice vizualizations during scans bec = BestEffortCallback() # Install our notebook kicker to have plots update during a scan install_nb_kicker() if args.sim: # Create our motors x_motor = SynAxis(name='x') y_motor = SynAxis(name='y') #Defines relationships between centroids and motors x_centroid = SynSignal(func=partial(centroid_from_motor_cross, x_motor,y_motor, noise_scale = 1), name='x_syn') y_centroid = SynSignal(func=partial(centroid_from_motor_cross, y_motor,x_motor), name='y_syn') print('Running Simulated Scan') else: #The Newport motors x_motor = Newport('XPP:LAS:MMN:13', name = 'real_x') y_motor = Newport('XPP:LAS:MMN:14', name = 'real_y') #Readback from actual beamline devices x_centroid = EpicsSignalRO('XPP:OPAL1K:01:Stats2:CentroidX_RBV', name = 'x_readback') y_centroid = EpicsSignalRO('XPP:OPAL1K:01:Stats2:CentroidY_RBV', name = 'y_readback') print('Running Real Scan') #Executes the plan
from ophyd import Component from ophyd.sim import SynAxis, SynSignal, Device cs700 = SynAxis(name='cs700', value=300.) cs700.readback.name = 'temperature' shctl1 = SynAxis(name='shctl1', value=0) shctl1.readback.name = 'rad' class SimFilterBank(Device): """Simulated filter bank with only the first filter in by default""" flt1 = Component(SynSignal, func=lambda: 'In') flt2 = Component(SynSignal, func=lambda: 'Out') flt3 = Component(SynSignal, func=lambda: 'Out') flt4 = Component(SynSignal, func=lambda: 'Out') fb = SimFilterBank(name='fb')
def linear(): motor = SynAxis(name='motor') # Make our linear detector sig = SynSignal(func=lambda: 4 * motor.position, name='det') return (sig, motor)
def inverted_gauss(): motor = SynAxis(name='motor') # Make our inverted detector sig = SynGauss('det', motor, 'motor', center=0, Imax=-1, sigma=1) return (sig, motor)
import logging import pytest from numpy import linspace import pandas as pd from bluesky.preprocessors import run_wrapper from ophyd.sim import SynAxis from .conftest import SynCamera from ..plans.scans import centroid_scan from ..utils import as_list logger = logging.getLogger(__name__) m1 = SynAxis(name="m1") m2 = SynAxis(name="m2") delay = SynAxis(name="delay") def test_centroid_scan_returns_df(fresh_RE): # Simulated camera camera = SynCamera(m1, m2, delay, name="camera") # Create the plan def test_plan(): delay_scan = (yield from centroid_scan( camera, delay, -1, 1, 3,
start=start) config = dev.read_configuration() # Assert the extra values are in the cofiguration assert config['scan']['value'] is scan assert config['scale']['value'] == scale assert config['start']['value'] == start @pytest.mark.parametrize( "calib", [None, pd.DataFrame(columns=['a']), pd.DataFrame(columns=['a', 'b'])]) @pytest.mark.parametrize( "motors", [None, [SynAxis(name='a')], [SynAxis(name='a'), SynAxis(name='b')]]) def test_CalibMotor_has_calib_correctly_indicates_there_is_a_valid_calibration( calib, motors): dev = CalibMotor("TST", name="test") # Force replace the underlying calibration to use the inputs dev._calib['calib']['value'] = calib dev._calib['motors']['value'] = motors # There must be both a calibration and motors, and they are the same length expected_logic = bool((calib is not None and motors) and (len(calib.columns) == len(motors))) assert dev.has_calib == expected_logic def test_CalibMotor_calibration_returns_correct_parameters():
# obj = tomopy.checkerboard(L) # obj = tomopy.baboon(L) # obj = tomopy.lena(L) class TomoDet(Device): image = Cpt(Signal) def trigger(self): super().trigger() self.image.put(tomopy.project(obj, angle.read()['angle']['value'])) return NullStatus() det = TomoDet(name='det') angle = SynAxis(name='angle') RE = RunEngine({}) # Do this if running the example interactively; # skip it when building the documentation. import os if 'BUILDING_DOCS' not in os.environ: from bluesky.utils import install_qt_kicker # for notebooks, qt -> nb install_qt_kicker() plt.ion() angle._fake_sleep = 0.001 # simulate slow motor movement class LiveRecon(CallbackBase): SMALL = 1e-6
if rv is not None: logging.error('%s' % rv) RE = RunEngine({}) # cpo thinks this is more for printout of each step from bluesky.callbacks.best_effort import BestEffortCallback bec = BestEffortCallback() # Send all metadata/data captured to the BestEffortCallback. RE.subscribe(bec) from ophyd.sim import motor1, SynAxis from bluesky.plans import scan step_value = SynAxis(name=ControlDef.STEP_VALUE) # instantiate BlueskyScan object mydaq = BlueskyScan(control, daqState=daqState, args=args) dets = [mydaq] # just one in this case, but it could be more than one # configure BlueskyScan object with a set of motors mydaq.configure(motors=[motor1, step_value]) # Scan motor1 from -10 to 10 and step_value from 0 to 14, stopping # at 15 equally-spaced points along the way and reading dets. RE(scan(dets, motor1, -10, 10, step_value, 0, 14, 15)) mydaq.push_socket.send_string('shutdown') #shutdown the daq thread mydaq.comm_thread.join()
def descriptor(self, doc): if doc["name"] != self._stream: return if len(self._descriptors): self._descriptors.add(doc["uid"]) else: super().descriptor(doc) lt = BatchLiveTable( ["ctrl_Ti", "ctrl_temp", "ctrl_anneal_time", "ctrl_thickness", "x", "y"]) y = SynAxis(name="y") x = SynAxis(name="x") RE = RunEngine() RE.subscribe(lt) recommender = SequenceRecommender([[30, 340, 450, 1], [35, 340, 450, 1], [48, 400, 3600, 1], [35, 400, 450, 0]]) cb, queue = recommender_factory( recommender, ["ctrl_Ti", "ctrl_temp", "ctrl_annealing_time", "ctrl_thickness"], ["x"], ) pair = single_strip_set_transform_factory(single_data)
m.move = m.set @property def position(self): return self.motor.position def move(self, position, *args, **kwargs): # Perform the calibration move status = self.motor.set(position, *args, *kwargs) if self.has_calib and self.use_calib: status = status & self._calib_compensate(position) return status # Simulated Crystal motor that goes where you tell it crystal = SynAxis(name='angle') m1 = SynAxis(name="m1") m2 = SynAxis(name="m2") delay = SynAxis(name="delay") # Create a fixture to automatically instantiate logging setup @pytest.fixture(scope='session', autouse=True) def set_level(pytestconfig): # Read user input logging level log_level = getattr(logging, pytestconfig.getoption('--log'), None) # Report invalid logging level if not isinstance(log_level, int): raise ValueError("Invalid log level : {}".format(log_level))
def test_synaxis_describe(): bs = pytest.importorskip('bluesky') import bluesky.plans as bp motor1 = SynAxis(name='motor1') RE = bs.RunEngine() RE(bp.scan([], motor1, -5, 5, 5))