Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
def test_descriptor_layout_from_monitor(fresh_RE):
    collector = []
    det = Reader('det', {k: lambda: i
                         for i, k in enumerate('abcd')},
                 read_attrs=list('ab'),
                 conf_attrs=list('cd'))

    def collect(name, doc):
        if name == 'descriptor':
            collector.append(doc)

    fresh_RE([
        Msg('open_run'),
        Msg('monitor', det, name=det.name),
        Msg('unmonitor', det),
        Msg('close_run')
    ], collect)

    descriptor, = collector
    assert descriptor['object_keys'] == {det.name: list(det.describe().keys())}
    assert descriptor['data_keys'] == det.describe()
    conf = descriptor['configuration'][det.name]
    assert conf['data_keys'] == det.describe_configuration()
    vals = {key: val['value'] for key, val in det.read_configuration().items()}
    timestamps = {
        key: val['timestamp']
        for key, val in det.read_configuration().items()
    }
    assert conf['data'] == vals
    assert conf['timestamps'].keys() == timestamps.keys()
    for val in conf['timestamps'].values():
        assert type(val) is float  # can't check actual value; time has passed
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
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,
    ]
Ejemplo n.º 7
0
def test_measure(RE):
    #Simplest implementation
    plan = run_wrapper(measure([det,motor], num=5, delay=0.01))

    #Fake callback storage
    shots = list()
    cb    = collector('det', shots)

    #Run simple
    RE(plan, subs={'event' : cb})
    assert shots == [1.0, 1.0, 1.0, 1.0, 1.0]


    #Create counting detector
    index = 0
    def count():
        nonlocal index
        index += 1
        return index

    counter = Reader('det', {'intensity' : count})

    #Filtered implementation
    plan = run_wrapper(measure([counter],
                       filters = {'intensity' : lambda x : x > 2},
                       #num=5, delay=[0.01, 0.02, 0.03, 0.04]))
                        num=5))
    #Fake callback storage
    shots = list()
    cb    = collector('intensity', shots)

    #Run filtered
    RE(plan, subs={'event' : cb})
    assert shots == [1, 3, 4, 5, 6, 7] #2 is skipped, because read is called
                                       #by `describe`, which is called by RE
                                       #after first read

    # Make sure an exception is raised when we fail too many filter checks
    counter = Reader('det', {'intensity' : count})
    plan = run_wrapper(measure([counter],
                       filters = {'intensity' : lambda x : False},
                        num=500))
    with pytest.raises(FilterCountError):
        RE(plan)
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
def test_broker_base_no_unpack(fresh_RE, db):
    class BrokerChecker(BrokerCallbackBase):
        def __init__(self, field, *, db=None):
            super().__init__(field, db=db)

        def event(self, doc):
            super().event(doc)
            assert isinstance(doc['data'][self.fields[0]], np.ndarray)

    RE = fresh_RE
    bc = BrokerChecker(('img', ), db=db)
    db.fs.register_handler('RWFS_NPY', ReaderWithRegistryHandler)
    det = Reader('det', {'img': lambda: np.array(np.ones((10, 10)))})
    RE.subscribe(bc)
    RE(count([det]))
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
        sigma = 0.1
        I = A * np.exp(-(pos - x0)**2 / (2 * sigma**2)) + 10.0

        return np.random.poisson(I)

    def fake_detector_response_edge():
        pos = armz.user_readback.value
        A = 1000.0
        x0 = -17.0
        sigma = 0.05
        I = A / (1 + np.exp(-(pos - x0) / (-sigma))) + 10.0

        return np.random.poisson(I)

    #det = Reader( 'det', {'intensity': lambda: 1.0*( (DETx.user_readback.value - (-40.0))**2 )/(2.*(0.1)**2) } )
    det = Reader('intensity', {'intensity': fake_detector_response_edge})
    detselect(det)
    #detselect(det, suffix='')

    #fit_scan(DETx, 1, 3, detector_suffix='')
    #fit_scan(armz, [-5,0], 5, detector_suffix='')


class MotorWait(CallbackBase):
    def __init__(self, motor, wait_time):

        self.motor = motor
        self.wait_time = wait_time

    def start(self, doc):
        self.settle_time_original = self.motor.settle_time
Ejemplo n.º 12
0
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')