def test_rank_models(): RE = RunEngine() #Create accurate fit motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) det = Reader('det', {'centroid': lambda: 5 * motor.read()['motor']['value'] + 2}) fit1 = LinearFit('centroid', 'motor', update_every=None, name='Accurate') RE(scan([det], motor, -1, 1, 50), fit1) #Create inaccurate fit det2 = Reader( 'det', {'centroid': lambda: 25 * motor.read()['motor']['value'] + 2}) fit2 = LinearFit('centroid', 'motor', update_every=None, name='Inaccurate') RE(scan([det2], motor, -1, 1, 50), fit2) #Create inaccurate fit det3 = Reader( 'det', {'centroid': lambda: 12 * motor.read()['motor']['value'] + 2}) fit3 = LinearFit('centroid', 'motor', update_every=None, name='Midly Inaccurate') RE(scan([det3], motor, -1, 1, 50), fit3) #Rank models ranking = rank_models([fit2, fit1, fit3], target=22, x=4) assert ranking[0] == fit1 assert ranking[1] == fit3 assert ranking[2] == fit2
def test_linear_fit(): #Create RunEngine RE = RunEngine() #Excepted values of fit expected = {'slope': 5, 'intercept': 2} #Create simulated devices motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) det = Reader('det', {'centroid': lambda: 5 * motor.read()['motor']['value'] + 2}) #Assemble fitting callback cb = LinearFit('centroid', 'motor', update_every=None) #Scan through variables RE(scan([det], motor, -1, 1, 50), cb) #Check accuracy of fit for k, v in expected.items(): assert np.allclose(cb.result.values[k], v, atol=1e-6) #Check we create an accurate estimate assert np.allclose(cb.eval(x=10), 52, atol=1e-5) assert np.allclose(cb.eval(motor=10), 52, atol=1e-5) assert np.allclose(cb.backsolve(52)['x'], 10, atol=1e-5)
def test_colliding_streams(fresh_RE): RE = fresh_RE motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) motor1 = Mover('motor1', {'motor1': lambda x: x}, {'x': 0}) collector = {'primary': [], 'baseline': []} descs = {} def local_cb(name, doc): if name == 'descriptor': descs[doc['uid']] = doc['name'] elif name == 'event': collector[descs[doc['descriptor']]].append(doc) RE( bp.baseline_wrapper( bp.outer_product_scan([motor], motor, -1, 1, 5, motor1, -5, 5, 7, True), [motor, motor1]), local_cb) assert len(collector['primary']) == 35 assert len(collector['baseline']) == 2 assert list(range(1, 36)) == [e['seq_num'] for e in collector['primary']] assert list(range(1, 3)) == [e['seq_num'] for e in collector['baseline']]
def test_slit_scan_area_compare(RE): fake_slits = Mover( "slits", OrderedDict([ ('xwidth', (lambda x, y: x)), ('ywidth', (lambda x, y: y)), ]), { 'x': 0, 'y': 0 }) fake_yag = Reader( 'fake_yag', { 'xwidth': (lambda: fake_slits.read()['xwidth']['value']), 'ywidth': (lambda: fake_slits.read()['ywidth']['value']), }) # collector callbacks aggregate data from 'yield from' in the given lists xwidths = [] ywidths = [] measuredxwidths = collector("xwidth", xwidths) measuredywidths = collector("ywidth", ywidths) #test two basic positions RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 1.0, 1.0, 2)), subs={'event': [measuredxwidths, measuredywidths]}) RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 1.1, 1.5, 2)), subs={'event': [measuredxwidths, measuredywidths]}) # excpect error if both measurements <= 0 with pytest.raises(ValueError): RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 0.0, 0.0, 2)), subs={'event': [measuredxwidths, measuredywidths]}) # expect error if one measurement <= 0 with pytest.raises(ValueError): RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 1.1, 0.0, 2)), subs={'event': [measuredxwidths, measuredywidths]}) logger.debug(xwidths) logger.debug(ywidths) assert xwidths == [ 1.0, 1.0, 1.1, 1.1, 0.0, 0.0, 1.1, 1.1, ] assert ywidths == [ 1.0, 1.0, 1.5, 1.5, 0.0, 0.0, 0.0, 0.0, ]
def test_walk_to_pixel(RE, one_bounce_system): logger.debug("test_walk_to_pixel") _, mot, det = one_bounce_system ########################## # Test on simple devices # ########################## simple_motor = Mover('motor', {'motor' : lambda x : x}, {'x' :0}) simple_det = Reader('det', {'det' : lambda : 5*simple_motor.read()['motor']['value'] + 2}) #Naive step plan = run_wrapper(walk_to_pixel(simple_det, simple_motor, 200, 0, first_step=1e-6, tolerance=10, average=None, target_fields=['det', 'motor'], max_steps=3)) RE(plan) assert np.isclose(simple_det.read()['det']['value'], 200, atol=1) simple_motor.set(0.) #Gradient simple_motor = Mover('motor', {'motor' : lambda x : x}, {'x' :0}) simple_det = Reader('det', {'det' : lambda : 5*simple_motor.read()['motor']['value'] + 2}) plan = run_wrapper(walk_to_pixel(simple_det, simple_motor, 200, 0, gradient=1.6842e+06, tolerance=10, average=None, target_fields=['det', 'motor'], max_steps=3)) RE(plan) assert np.isclose(simple_det.read()['det']['value'], 200, atol=1) ########################## # Test on full model # ########################## #Naive step plan = run_wrapper(walk_to_pixel(det, mot, 200, 0, first_step=1e-6, tolerance=10, average=None, target_fields=['detector_stats2_centroid_x', 'pitch'], max_steps=3)) RE(plan) assert np.isclose(det.read()[det.name + '_detector_stats2_centroid_x']['value'], 200, atol=1) mot.set(0.) #Gradient plan = run_wrapper(walk_to_pixel(det, mot, 200, 0, gradient=1.6842e+06, tolerance=10, average=None, target_fields=['detector_stats2_centroid_x', 'pitch'], max_steps=3)) RE(plan) assert np.isclose(det.read()[det.name + '_detector_stats2_centroid_x']['value'], 200, atol=10)
def _make_unrewindable_suspender_marker(): class UnReplayableSynGauss(SynGauss): def pause(self): raise NoReplayAllowed() motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) def test_plan(motor, det): yield Msg('set', motor, 0) yield Msg('trigger', det) yield Msg('sleep', None, 1) yield Msg('set', motor, 0) yield Msg('trigger', det) inps = [] inps.append((test_plan, motor, UnReplayableSynGauss('det', motor, 'motor', center=0, Imax=1), ['set', 'trigger', 'sleep', 'wait_for', 'set', 'trigger'])) inps.append( (test_plan, motor, SynGauss('det', motor, 'motor', center=0, Imax=1), [ 'set', 'trigger', 'sleep', 'wait_for', 'set', 'trigger', 'sleep', 'set', 'trigger' ])) return pytest.mark.parametrize('plan,motor,det,msg_seq', inps)
def fiducialized_yag(): #Instantiate fake slits object fake_slits = Mover( "slits", OrderedDict([ ('xwidth', (lambda xwidth: xwidth)), #('ywidth',(lambda xwidth,ywidth:ywidth)), #('ywidth',(lambda xwidth:xwidth)), ]), #{'xwidth':0,'ywidth':0} #{'xwidth':0,'ywidth':0} {'xwidth': 0}) #Pretend our beam is 0.3 from the slit center def aperatured_centroid(slits=fake_slits): #Beam is unblocked if slits.read()['xwidth']['value'] > 0.5: #and slits.read()['ywidth']['value'] > 0.5): #return 0.3 return 0.3 #Beam is fully blocked return 0.0 #Instantiate fake detector object fake_yag = Reader('det', {'centroid': aperatured_centroid}) return fake_slits, fake_yag
def test_relative_spiral(fresh_RE): motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) motor1 = Mover('motor1', {'motor1': lambda x: x}, {'x': 0}) motor2 = Mover('motor2', {'motor2': lambda x: x}, {'x': 0}) det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1) start_x = 1.0 start_y = 1.0 motor1.set(start_x) motor2.set(start_y) scan = RelativeSpiralScan([det], motor1, motor2, 1.0, 1.0, 0.1, 1.0, 0.0) approx_multi_traj_checker(fresh_RE, scan, _get_spiral_data(start_x, start_y), decimal=2)
def motor_det(request): motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1, exposure_time=0) return motor, det
def test_wa(): motor = Mover( 'motor', OrderedDict([('motor', lambda x: x), ('motor_setpoint', lambda x: x)]), {'x': 0}) ip = FakeIPython({'motor': motor}) sm = BlueskyMagics(ip) # Test an empty list. sm.wa('') sm.positioners.extend([motor]) sm.wa('') # Make motor support more attributes. motor.limits = (-1, 1) sm.wa('') motor.user_offset = SimpleNamespace(get=lambda: 0) sm.wa('[motor]')
def test_absolute_spiral(fresh_RE): motor = Mover('motor', {'motor': lambda x: x}, {'x': 0}) motor1 = Mover('motor1', {'motor1': lambda x: x}, {'x': 0}) motor2 = Mover('motor2', {'motor2': lambda x: x}, {'x': 0}) det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1) motor1.set(1.0) motor2.set(1.0) scan = SpiralScan([det], motor1, motor2, 0.0, 0.0, 1.0, 1.0, 0.1, 1.0, 0.0) approx_multi_traj_checker(fresh_RE, scan, _get_spiral_data(0.0, 0.0), decimal=2) scan = SpiralScan([det], motor1, motor2, 0.5, 0.5, 1.0, 1.0, 0.1, 1.0, 0.0) approx_multi_traj_checker(fresh_RE, scan, _get_spiral_data(0.5, 0.5), decimal=2)
def test_mv_progress(fresh_RE): RE = fresh_RE RE.waiting_hook = ProgressBarManager() motor1 = Mover('motor1', OrderedDict([('motor1', lambda x: x), ('motor1_setpoint', lambda x: x)]), {'x': 0}) motor2 = Mover('motor2', OrderedDict([('motor2', lambda x: x), ('motor2_setpoint', lambda x: x)]), {'x': 0}) assert RE.waiting_hook.delay_draw == 0.2 # moving time > delay_draw motor1._fake_sleep = 0.5 motor1._fake_sleep = 0.5 RE(mv(motor1, 0, motor2, 0)) # moving time < delay_draw motor1._fake_sleep = 0.01 motor1._fake_sleep = 0.01 RE(mv(motor1, 0, motor2, 0))
def test_multi_fit(): #Create RunEngine RE = RunEngine() #Excepted values of fit expected = {'x0': 5, 'x1': 4, 'x2': 3} #Create simulated devices m1 = Mover('m1', {'m1': lambda x: x}, {'x': 0}) m2 = Mover('m2', {'m2': lambda x: x}, {'x': 0}) det = Reader( 'det', { 'centroid': lambda: 5 + 4 * m1.read()['m1']['value'] + 3 * m2.read()['m2'][ 'value'] }) #Assemble fitting callback cb = MultiPitchFit('centroid', ('m1', 'm2'), update_every=None) #Scan through variables RE(outer_product_scan([det], m1, -1, 1, 10, m2, -1, 1, 10, False), cb) #Check accuracy of fit print(cb.result.fit_report()) for k, v in expected.items(): assert np.allclose(cb.result.values[k], v, atol=1e-6) #Check we create an accurate estimate assert np.allclose(cb.eval(a0=5, a1=10), 55, atol=1e-5) assert np.allclose(cb.backsolve(55, a1=10)['a0'], 5, atol=1e-5) assert np.allclose(cb.backsolve(55, a0=5)['a1'], 10, atol=1e-5)
def test_fitwalk(RE): #Create simulated devices motor = Mover('motor', {'motor' : lambda x : x}, {'x' :0}) det = Reader('det', {'centroid' : lambda : 5*motor.read()['motor']['value'] + 2}) #Assemble linear fitting callback linear = LinearFit('centroid', 'motor', average=1) #Assemble parabolic fitting callback parabola = ParabolicFit('centroid', 'motor', average=1) #Create plan walk = fitwalk([det], motor, [parabola, linear], 89.4, average=1, tolerance = 0.5) #Call with RunEngine RE(run_wrapper(walk)) #Check we hit our target assert np.isclose(det.read()['centroid']['value'], 89.4, 0.5)
def test_relative_set(fresh_RE): motor = Mover('a', {'a': lambda x: x}, {'x': 0}) motor.set(5) msgs = [] def accumulator(msg): msgs.append(msg) fresh_RE.msg_hook = accumulator def plan(): yield from (m for m in [Msg('set', motor, 8)]) fresh_RE(relative_set_wrapper(plan())) expected = [Msg('set', motor, 13)] for msg in msgs: msg.kwargs.pop('group', None) assert msgs == expected
from bluesky import RunEngine from bluesky.examples import motor, det, Mover from bluesky.spec_api import ascan from bluesky.global_state import gs from bluesky.utils import install_qt_kicker INSTALL = True if INSTALL: install_qt_kicker() INSTALL = False RE = RunEngine({'proposal_id': 'test'}) det.exposure_time = .3 sample_plate = Mover('sample', ['sample']) gs.BASELINE_DEVICES = [sample_plate] gs.DETS = [det] gs.PLOT_Y = 'det' sample_list = ['a', 'b', 'c'] sample_ranges = { 'a': { 'start': -5, 'finish': -1 }, 'b': { 'start': -1, 'finish': 1 }, 'c': {
from bluesky.examples import Mover, SynGauss, Syn2DGauss import bluesky.simple_scans as bss import bluesky.spec_api as bsa import bluesky.callbacks from bluesky.standard_config import gs import bluesky.qt_kicker # motors theta = Mover('theta', ['theta']) gamma = Mover('gamma', ['gamma']) # synthetic detectors coupled to one motor theta_det = SynGauss('theta_det', theta, 'theta', center=0, Imax=1, sigma=1) gamma_det = SynGauss('gamma_det', gamma, 'gamma', center=0, Imax=1, sigma=1) # synthetic detector coupled to two detectors tgd = Syn2DGauss('theta_gamma_det', theta, 'theta', gamma, 'gamma', center=(0, 0), Imax=1) # set up the default detectors gs.DETS = [theta_det, gamma_det, tgd] ysteps = 25 xsteps = 20 # hook up the live raster callback
import matplotlib.pyplot as plt from bluesky import RunEngine from bluesky.scans import AdaptiveAscan from bluesky.examples import Mover, SynGauss from bluesky.callbacks import LivePlot, LiveTable from bluesky.tests.utils import setup_test_run_engine #plt.ion() RE = setup_test_run_engine() motor = Mover('motor', ['pos']) det = SynGauss('det', motor, 'pos', center=0, Imax=1, sigma=1) #fig, ax = plt.subplots() #ax.set_xlim([-15, 5]) #ax.set_ylim([0, 2]) # Point the function to our axes above, and specify what to plot. #my_plotter = LivePlot('det', 'pos') table = LiveTable(['det', 'pos']) ad_scan = AdaptiveAscan([det], 'det', motor, -15, 5, .01, 1, .05, True) RE(ad_scan, subscriptions={'all': [table]}) #, my_plotter})
import matplotlib.pyplot as plt from bluesky import RunEngine from bluesky.examples import Reader, Mover from bluesky.plans import scan from bluesky.callbacks import LiveTable, CallbackBase from bluesky.utils import install_qt_kicker import tomopy import numpy as np L = 64 obj = tomopy.lena(L) det = Reader('det', {'image': lambda: tomopy.project(obj, angle.read()['angle']['value'])}) angle = Mover('angle', {'angle': lambda x: x}, {'x': 0}) angle._fake_sleep = 0.01 RE = RunEngine({}) install_qt_kicker() t = LiveTable([angle]) class LiveRecon(CallbackBase): SMALL = 1e-6 def __init__(self, name, x, y, ax=None, **recon_kwargs): if ax is None: import matplotlib.pyplot as plt ax = plt.gca() ax.set_title('Reconstruction using Tomopy') ax.set_xlabel('x')