コード例 #1
0
def test_match_condition_success_no_stop(RE, mot_and_sig):
    logger.debug("test_match_condition_success_no_stop")
    mot, sig = mot_and_sig
    mot.delay = 0

    # Delay has no purpose if we aren't going to stop

    def condition(x):
        if 5 < x < 7:
            return True
        elif 10 < x < 16:
            return True
        return False

    RE(run_wrapper(match_condition(sig, condition, mot, 20, has_stop=False)))
    assert 12 < mot.position < 14
    # Motor should end in the middle of the largest True region

    mot.move(0, wait=True)

    def condition(x):
        return 10 < x < 16

    RE(run_wrapper(match_condition(sig, condition, mot, 20, has_stop=False)))
    assert 12 < mot.position < 14

    mot.move(0, wait=True)

    def condition(x):
        return x > 10

    RE(run_wrapper(match_condition(sig, condition, mot, 20, has_stop=False)))
    assert 14 < mot.position < 16
コード例 #2
0
def test_fiducialize(RE, fiducialized_yag):
    logger.debug('test_fiducialize')

    fake_slits, fake_yag = fiducialized_yag

    center = []
    measuredcenter = collector("det", center)

    # Run plan with sufficiently large max_width
    RE(
        run_wrapper(
            fiducialize(fake_slits,
                        fake_yag,
                        start=0.1,
                        step_size=1.0,
                        centroid='det',
                        samples=1)), {'event': [measuredcenter]})

    # First shot is blocked second is not
    assert center == [0.0, 0.3]

    # Run plan with insufficiently large max_width
    with pytest.raises(BeamNotFoundError):
        RE(
            run_wrapper(
                fiducialize(fake_slits,
                            fake_yag,
                            start=0.1,
                            step_size=1.0,
                            max_width=0.25,
                            centroid='det',
                            samples=1)))
コード例 #3
0
def test_slit_scan_area_compare(RE):
    pre = 'fakeslits'
    fake_slits = FakeSlits(name=pre)

    class FakeYag(Device):
        xwidth = Cmp(SynSignal,
                     func=lambda: fake_slits.read()[pre + '_xwidth']['value'])
        ywidth = Cmp(SynSignal,
                     func=lambda: fake_slits.read()[pre + '_ywidth']['value'])

        def trigger(self):
            xstat = self.xwidth.trigger()
            ystat = self.ywidth.trigger()
            return xstat & ystat

    fake_yag = FakeYag(name='fakeyag')

    # collector callbacks aggregate data from 'yield from' in the given lists
    xwidths = []
    ywidths = []
    measuredxwidths = collector("fakeyag_xwidth", xwidths)
    measuredywidths = collector("fakeyag_ywidth", ywidths)

    # test two basic positions
    RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 1.0, 1.0, 2)),
       {'event': [measuredxwidths, measuredywidths]})
    RE(run_wrapper(slit_scan_area_comp(fake_slits, fake_yag, 1.1, 1.5, 2)),
       {'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)),
           {'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)),
           {'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,
    ]
コード例 #4
0
def test_slit_scan_fiducialize(RE, fiducialized_yag):
    logger.debug('test_slit_scan_fiducialize')

    fake_slits, fake_yag = fiducialized_yag

    center = []
    measuredcenter = collector("det", center)

    # Run plan with wide slits
    RE(
        run_wrapper(
            slit_scan_fiducialize(fake_slits,
                                  fake_yag,
                                  x_width=1.0,
                                  y_width=1.0,
                                  centroid='det',
                                  samples=1)), {'event': [measuredcenter]})

    assert center == [0.3]

    center = []
    measuredcenter = collector("det", center)

    # Run plan with narrow slits
    RE(
        run_wrapper(
            slit_scan_fiducialize(fake_slits,
                                  fake_yag,
                                  centroid='det',
                                  samples=1)), {'event': [measuredcenter]})

    assert center == [0.0]
コード例 #5
0
ファイル: test_plans.py プロジェクト: slactjohnson/pswalker
def test_measure_average(RE, one_bounce_system):
    logger.debug("test_measure_average")
    _, mot, det = one_bounce_system

    centroids = []
    readbacks = []
    col_c = collector(det.name + '_detector_stats2_centroid_x', centroids)
    col_r = collector(mot.name + '_sim_alpha',    readbacks)

    RE(run_wrapper(measure_average([det, mot], delay=0.1, num=5)),
       {'event': [col_c, col_r]})

    assert centroids == [250., 250., 250., 250., 250.]
    assert readbacks == [0., 0., 0., 0., 0.]

    centroids.clear()
    readbacks.clear()

    # Run with array of delays
    RE(run_wrapper(measure_average([det, mot], delay=[0.1], num=2)),
       {'event': [col_c, col_r]})

    assert centroids == [250., 250.]
    assert readbacks == [0., 0.]

    # Invalid delay settings
    with pytest.raises(ValueError):
        RE(run_wrapper(measure_average([det, mot], delay=[0.1], num=3)))
コード例 #6
0
def test_iterwalk_raises_RuntimeError_on_motion_timeout(
        RE, lcls_two_bounce_system):
    logger.debug("test_iterwalk_raises_RuntimeError_on_motion_timeout")
    s, m1, m2, y1, y2 = lcls_two_bounce_system

    # Center pixels of yag
    center_pix = [y1.size[0] / 2] * 2
    goal = [p + 300 for p in center_pix]

    # Define a bad set command
    def bad_set(yag, cmd=None, **kwargs):
        logger.info("{0}Setting Attributes. (BAD)".format(yag.log_pref))
        logger.debug("{0}Setting: CMD:{1}, {2} (BAD)".format(
            yag.log_pref, cmd, kwargs))
        return Status(done=True, success=False)

    # Patch yag set command
    y1.set = lambda cmd, **kwargs: bad_set(y1, cmd, **kwargs)

    plan = run_wrapper(
        iterwalk([y1, y2], [m1, m2],
                 goal,
                 starts=None,
                 first_steps=1,
                 gradients=None,
                 detector_fields='detector_stats2_centroid_x',
                 motor_fields='sim_alpha',
                 tolerances=TOL,
                 system=None,
                 averages=1,
                 overshoot=0,
                 max_walks=5,
                 timeout=None))
    # Check a RunTimError is raised
    with pytest.raises(RuntimeError):
        RE(plan)

    # Reload system
    s, m1, m2, y1, y2 = lcls_two_bounce_system
    # Patch yag set command
    y2.set = lambda cmd, **kwargs: bad_set(y2, cmd, **kwargs)

    plan = run_wrapper(
        iterwalk([y1, y2], [m1, m2],
                 goal,
                 starts=None,
                 first_steps=1e-6,
                 gradients=None,
                 detector_fields='detector_stats2_centroid_x',
                 motor_fields='sim_alpha',
                 tolerances=TOL,
                 system=None,
                 averages=1,
                 overshoot=0,
                 max_walks=5,
                 timeout=None))
    # Check a RunTimError is raised
    with pytest.raises(RuntimeError):
        RE(plan)
コード例 #7
0
ファイル: test_plans.py プロジェクト: slactjohnson/pswalker
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 = SynAxis(name='motor')
    simple_det = SynSignal(name='det',
                           func=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 = SynAxis(name='motor')
    simple_det = SynSignal(name='det',
                           func=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
    cent = 'detector_stats2_centroid_x'
    plan = run_wrapper(walk_to_pixel(det, mot, 200, 0, first_step=1e-6,
                                     tolerance=10, average=None,
                                     target_fields=[cent, 'sim_alpha'],
                                     max_steps=3))
    RE(plan)
    assert np.isclose(det.read()[det.name + "_" + cent]['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=[cent, 'sim_alpha'],
                                     max_steps=3))
    RE(plan)
    assert np.isclose(det.read()[det.name + "_" + cent]['value'], 200, atol=10)
コード例 #8
0
ファイル: test_plans.py プロジェクト: pcdshub/amo
def test_x348_scan(fresh_RE):
    #m1 = SynAxis(name="m1")
    #m2 = SynAxis(name="m2")
    #seq = SynSequencer('', name='sequencer')
    pal = McgrainPalette(name='test_palette',
                         N=10,
                         M=5,
                         chip_spacing=0,
                         chip_dims=[10])

    pal._accept_calibration(start_pt=np.array([0, 0, 0]),
                            n_pt=np.array([pal.N - 1, 0, 0]),
                            m_pt=np.array([0, pal.M - 1, 0]))

    seq = SimSequencer('', name='sequencer')

    seq._cb_sleep = 0

    def test_plan():
        yield from x348_scan(pal, seq, 0, 7, .1)
        assert pal.x_motor.position == 1.0
        assert pal.y_motor.position == 3.0
        assert seq.play_control.get() == 1

    # Send all metadata/data captured to the BestEffortCallback.
    fresh_RE(run_wrapper(test_plan()))
コード例 #9
0
def test_homs_fiducialize(RE, fiducialized_yag_set):
    fset = fiducialized_yag_set

    slit_set, yag_set = list(zip(*fset))
    yag_set = [
        PIM("TEST"),
        PIM("TEST"),
        PIM("TEST"),
    ]
    center = []
    measuredcenter = collector("TST:TEST_detector_stats2_centroid_y", center)
    state = []
    measuredstate = collector("TST:TEST_states", state)
    RE(
        run_wrapper(
            homs_fiducialize(slit_set,
                             yag_set,
                             x_width=.6,
                             y_width=.6,
                             samples=2,
                             centroid='detector_stats2_centroid_y')),
        {'event': [measuredcenter, measuredstate]})

    for x in yag_set:
        assert x.read()['TST:TEST_states']['value'] == 'OUT', "yag not removed"

    for index, _ in enumerate(center):
        assert center[index] == 0.0, 'measurment incorrect'
コード例 #10
0
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
    fresh_RE(run_wrapper(test_plan()))

    # get the expected and current positions
    expected_positions = [
        ipos if m in return_devices else fpos
        for m, ipos, fpos in zip(motors, initial_positions, final_positions)
    ]
    current_positions = [mot.position for mot in motors]

    # Assert they are the same
    assert current_positions == expected_positions
コード例 #11
0
ファイル: test_plans_scans.py プロジェクト: ZryletTC/hxrsnd
def test_centroid_scan_returns_correct_columns(fresh_RE, mot_fields,
                                               det_fields, system_attrs):
    # Simulated camera
    camera = SynCamera(m1, m2, delay, name="camera")

    # Create the plan

    def test_plan():
        steps = 2  # Start and stop position
        delay_scan = (yield from centroid_scan(camera,
                                               delay,
                                               -1,
                                               1,
                                               steps,
                                               detector_fields=det_fields,
                                               motor_fields=mot_fields,
                                               system=system_attrs[0],
                                               system_fields=system_attrs[1]))

        expected_length = (len(as_list(mot_fields)) or 1) \
            + len(as_list(det_fields)) \
            + len(as_list(system_attrs[1]))
        # Check the number of columns based in the inputs
        assert delay_scan.shape[1] == expected_length

        expected_columns = as_list(mot_fields or delay.name) \
            + as_list(system_attrs[1]) \
            + ["_".join([camera.name, fld]) for fld in as_list(
                det_fields)]
        # Check the columns are all what we expect them to be
        assert (delay_scan.columns == expected_columns).all()

    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #12
0
def test_match_condition_fail_no_stop(RE, mot_and_sig):
    logger.debug("test_match_condition_fail_no_stop")
    mot, sig = mot_and_sig
    mot.delay = 0
    RE(run_wrapper(match_condition(sig, lambda x: x > 50, mot, 40,
                                   has_stop=False)))
    assert mot.position == 40
コード例 #13
0
def test_scan_vars(RE, daq):
    logger.debug('test_scan_vars')

    daq.configure(events=120)

    scan_vars = ScanVars('TST', name='tst', RE=RE)
    scan_vars.enable()

    check = CheckVals(scan_vars)
    RE.subscribe(check)

    check.plan = 'scan'
    RE(
        scan([det1, det2], motor1, 0, 10, motor2, 20, 0, motor3, 0, 1, motor,
             0, 1, 11))

    check.plan = 'count'
    RE(count([det1, det2], 11))

    def custom(detector):
        for i in range(3):
            yield from create()
            yield from read(detector)
            yield from save()

    check.plan = 'custom'
    daq.configure(duration=4)
    RE(stage_wrapper(run_wrapper(custom(det1)), [det1]))

    scan_vars.disable()

    # Last, let's force an otherwise uncaught error to cover the catch-all
    # try-except block to make sure the log message doesn't error
    scan_vars.start({'motors': 4})
コード例 #14
0
def test_calibration_scan(fresh_RE, weights):
    camera = SynCamera(m1, m2, delay, name="camera")
    centroids = [camera.centroid_x, camera.centroid_y]
    calib_motors = [m1, m2]
    for cent, weight in zip(centroids, weights):
        cent.weights = [weight, cent.weights[1]]

    def test_plan():
        # Perform the scan
        df_calib, df_scan, _, _ = yield from calib.calibration_scan(
            camera, ['camera_centroid_x', 'camera_centroid_y'],
            delay,
            None, [m1, m2],
            None,
            -1,
            1,
            5,
            tolerance=0)

        # Expected positions of the centroids are the first positions
        expected_centroids = df_scan[[c.name for c in centroids]].iloc[0]

        for i in range(len(df_scan)):
            # Move to the scan position for the main motor
            delay.set(df_calib[delay.name].iloc[i])

            for cmotor, exp_cent, cent in zip(calib_motors, expected_centroids,
                                              centroids):
                # Move to the abosolute corrected position
                cmotor.set(df_calib[cmotor.name + "_post"].iloc[i])
                # Check the centroids are where they should be
                assert np.isclose(cent.get(), exp_cent, rtol=rtol)

    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #15
0
def test_CalibMotor_move_compensation(fresh_RE, get_calib_motor):
    # Define all the needed variables
    motor = get_calib_motor
    calib_motors = motor.calib_motors
    camera = SynCamera(*motor.calib_motors, motor, name="camera")
    centroids = [camera.centroid_x, camera.centroid_y]
    start, stop, steps = -1, 1, 5

    # Create the plan
    def test_plan():
        # Perform the calibration
        df_scan = (yield from
                   centroid_scan(camera,
                                 motor,
                                 start,
                                 stop,
                                 steps,
                                 motor_fields=motor.motor_fields,
                                 detector_fields=motor.detector_fields))

        # Expected positions of the centroids are the first positions
        df_centroids = df_scan[[c.name for c in centroids]]
        assert (df_centroids == df_centroids.iloc[0]).all().all()

    # Calibrate the motors
    motor.calibrate(start,
                    stop,
                    steps,
                    RE=fresh_RE,
                    detector=camera,
                    average=1,
                    tolerance=0,
                    confirm_overwrite=False)
    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #16
0
def test_detector_scaling_walk_start_positions_are_valid(fresh_RE):
    camera = SynCamera(m1, m2, delay, name="camera")
    m1.set(0)
    m2.set(0)
    delay.set(0)
    calib_motors = [m1, m2]

    def test_plan():
        # Get the current positions of the calib motors
        expected_positions = [
            test_df_scan[m.name + "_pre"][-1] for m in calib_motors
        ]
        # Perform the walk
        _, start = yield from calib.detector_scaling_walk(test_df_scan,
                                                          camera,
                                                          calib_motors,
                                                          tolerance=0,
                                                          system=delay)

        # Make sure we dont have any bad values
        assert np.nan not in start and np.inf not in start
        # Make sure we are get the expected positions of the motors
        assert np.isclose(start, expected_positions, rtol=rtol).all()

    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #17
0
def test_detector_scaling_walk_scale_values_are_valid(fresh_RE, weights):
    camera = SynCamera(m1, m2, delay, name="camera")
    centroids = [camera.centroid_x, camera.centroid_y]
    calib_motors = [m1, m2]
    for cent, weight in zip(centroids, weights):
        cent.weights = [weight, cent.weights[1]]

    def test_plan():
        df_scan = yield from calib.calibration_centroid_scan(
            camera,
            delay, [m1, m2],
            -1,
            1,
            5,
            detector_fields=['camera_centroid_x', 'camera_centroid_y'])

        # Get the expected scales if we do the walk
        expected_scales = [1 / cent.weights[0] for cent in centroids]
        # Perform the walk
        scales, _ = yield from calib.detector_scaling_walk(df_scan,
                                                           camera,
                                                           calib_motors,
                                                           tolerance=0,
                                                           system=delay)

        # Make sure we dont have any bad values
        assert np.nan not in scales and np.inf not in scales
        # Make sure we are get the expected positions of the motors
        assert np.isclose(scales, expected_scales, rtol=rtol).all()

    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #18
0
def test_iterwalk(RE, lcls_two_bounce_system, goal1, goal2, first_steps,
                  gradients, tolerances, overshoot, max_walks, tol_scaling):
    logger.debug(
        "test_iterwalk with goal1=%s, goal2=%s, first_steps=%s, " +
        "gradients=%s, tolerances=%s, overshoot=%.2f, max_walks=%s", goal1,
        goal2, first_steps, gradients, tolerances, overshoot, max_walks)
    s, m1, m2, y1, y2 = lcls_two_bounce_system

    goal1 += y1.size[0] / 2
    goal2 += y2.size[0] / 2

    goal = [goal1, goal2]

    plan = run_wrapper(
        iterwalk([y1, y2], [m1, m2],
                 goal,
                 starts=None,
                 first_steps=first_steps,
                 gradients=gradients,
                 detector_fields='detector_stats2_centroid_x',
                 motor_fields='sim_alpha',
                 tolerances=tolerances,
                 system=[m1, m2, y1, y2],
                 averages=1,
                 overshoot=overshoot,
                 max_walks=max_walks,
                 timeout=None,
                 tol_scaling=tol_scaling))
    RE(plan)
    assert np.isclose(y1.read()[y1.name +
                                '_detector_stats2_centroid_x']['value'],
                      goal[0],
                      atol=tolerances)
    assert np.isclose(y2.read()[y2.name +
                                '_detector_stats2_centroid_x']['value'],
                      goal[1],
                      atol=tolerances)

    # Make sure we actually read all the groups as we went
    m1_reads = 0
    m2_reads = 0
    y1_reads = 0
    y2_reads = 0
    saves = 0
    for msg in RE.msg_hook.msgs:
        if msg.command == 'read':
            if msg.obj == m1:
                m1_reads += 1
            if msg.obj == m2:
                m2_reads += 1
            if msg.obj == y1:
                y1_reads += 1
            if msg.obj == y2:
                y2_reads += 1
        if msg.command == 'save':
            saves += 1
    assert saves > 0
    assert all(
        map(lambda x: x == saves, [m1_reads, m2_reads, y1_reads, y2_reads]))
コード例 #19
0
def macro_sweep_test(target):
    logging.info(
        'macro_sweep_test initiated with target {:0.4f}'.format(target))
    RE = RunEngine({})
    bec = BestEffortCallback()
    RE.subscribe(bec)
    RE.waiting_hook = ProgressBarManager()
    RE(run_wrapper(rel_smooth_sweep_test(tst_23, target)))
コード例 #20
0
def test_recover_threshold_timeout_failure(RE, mot_and_sig):
    logger.debug("test_recover_threshold_timeout_failure")
    mot, sig = mot_and_sig
    # Make the motor slower to guarantee a timeout
    mot.n_steps = 5000
    RE(run_wrapper(recover_threshold(sig, 50, mot, +1, timeout=0.1)))
    pos = mot.position
    assert not 49 < pos < 51
    assert mot.position not in (100, -100)
コード例 #21
0
ファイル: test_plans.py プロジェクト: slactjohnson/pswalker
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, {'event': cb})
    assert shots == [1.0, 1.0, 1.0, 1.0, 1.0]

    # Create counting detector
    index = -1

    def count():
        nonlocal index
        index += 1
        return index

    counter = SynSignal(name='intensity',
                        func=count)

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

    # Run filtered
    RE(plan, {'event': cb})
    assert shots == [1, 2, 3, 4, 5, 6, 7]

    # Make sure an exception is raised when we fail too many filter checks
    plan = run_wrapper(measure([counter],
                       filters={'intensity': lambda x: False},
                       num=500))
    with pytest.raises(FilterCountError):
        RE(plan)
コード例 #22
0
ファイル: test_plans.py プロジェクト: slactjohnson/pswalker
def test_measure_centroid(RE, one_bounce_system):
    logger.debug("test_measure_centroid")

    _, mot, det = one_bounce_system
    centroids = []
    key_ext = 'detector_stats2_centroid_x'
    col_c = collector(det.name + "_" + key_ext, centroids)

    RE(run_wrapper(measure_centroid(det, average=5,
                                    target_field=key_ext)),
       {'event': [col_c]})
    assert centroids == [250., 250., 250., 250., 250.]
コード例 #23
0
def test_iterwalk_raises_RuntimeError_on_failed_walk_to_pixel(
        RE, lcls_two_bounce_system):
    logger.debug("test_iterwalk_raises_RuntimeError_on_failed_walk_to_pixel")
    s, m1, m2, y1, y2 = lcls_two_bounce_system

    # Center pixels of yag
    center_pix = [y1.size[0] / 2] * 2
    goal = [p + 300 for p in center_pix]

    # Define a bad set command
    def bad_set(mirror, cmd=None, **kwargs):
        logger.info("{0}Setting Attributes. (BAD)".format(mirror.log_pref))
        logger.debug("{0}Setting: CMD:{1}, {2} (BAD)".format(
            mirror.log_pref, cmd, kwargs))
        err = 0.1
        if cmd in ("IN", "OUT"):
            pass  # If these were removable we'd implement it here
        elif cmd is not None:
            # Here is where we move the pitch motor if a value is set
            cmd += err
            mirror.sim_pitch = cmd
            return mirror.pitch.set(cmd)
        mirror.sim_x = kwargs.get('x', mirror.sim_x)
        mirror.sim_z = kwargs.get('z', mirror.sim_z)
        mirror.sim_pitch = kwargs.get('pitch', mirror.sim_pitch)
        for motor in mirror.motors:
            motor_params = motor.read()
            for key in kwargs.keys():
                if key in motor_params:
                    # Add error term to sets
                    motor.set(kwargs[key] + err)
        return Status(done=True, success=True)

    # Patch yag set command
    m1.set = lambda cmd, **kwargs: bad_set(m1, cmd, **kwargs)

    plan = run_wrapper(
        iterwalk([y1, y2], [m1, m2],
                 goal,
                 starts=None,
                 first_steps=1e-6,
                 gradients=None,
                 detector_fields='sim_x',
                 motor_fields='sim_alpha',
                 tolerances=TOL,
                 system=None,
                 averages=1,
                 overshoot=0,
                 max_walks=5,
                 timeout=None))
    # Check a RunTimError is raised
    with pytest.raises(RuntimeError):
        RE(plan)
コード例 #24
0
ファイル: test_plans.py プロジェクト: slactjohnson/pswalker
def test_fitwalk(RE):
    # Create simulated devices
    motor = SynAxis(name='motor')
    det = SynSignal(name='centroid',
                    func=lambda: 5*motor.read()['motor']['value'] + 2)

    linear = LinearFit('centroid', 'motor', average=1)
    parabola = ParabolicFit('centroid', 'motor', average=1)
    walk = fitwalk([det], motor, [parabola, linear], 89.4,
                   average=1, tolerance=0.5)
    RE(run_wrapper(walk))

    assert np.isclose(det.read()['centroid']['value'], 89.4, 0.5)
コード例 #25
0
ファイル: test_plans.py プロジェクト: pcdshub/sxr
def test_mcgrain_scan(fresh_RE):
    m1 = SynAxis(name="m1")
    m2 = SynAxis(name="m2")
    seq = SynSequencer('', name='sequencer')

    def test_plan():
        yield from mcgrain_scan(m1, m2, seq, 0, 5, 6, 5)
        assert m1.position == 5.0
        assert m2.position == 30
        assert seq.state_control.get() == 1

    # Send all metadata/data captured to the BestEffortCallback.
    fresh_RE(run_wrapper(test_plan()))
コード例 #26
0
ファイル: macros.py プロジェクト: pcdshub/sxr
def macro_RSXS_smooth_sweep(stroke_height,
                            stroke_spacing,
                            n_strokes,
                            both_directions=True):
    """
    macro_RSXS_smooth_sweep

    This method wraps up the bluesky/ophyd codeand allows users to drive
    the LU20 experiment with minimal code overhead. It contains the following
    bluesky plan.

    This bluesky plan moves a 2-axis actuator across multiple traversals of a
    sample. The plan traverses the entirety of the stroke_height (y-axis) and
    after each traversal, steps in the x-axis by the stroke_spacing.It may be
    configured to scan in only a single direction and shutter the beam for the
    opposite direction. This removes the shutter at the beginning of the plan
    and reinserts it at the end. At the end of the plan, the sample is moved to
    its original y-axis position but with an x-axis posiiton ready for the next
    run. For more details about the path, see the documentation of the
    xy_sequencer, the method that generates the sample's path. 

    Parameters 
    ----------
    stroke_height : float
        Vertical distance (y-axs) of each stroke.

    stroke_spacing : float
        Horizontal distance between individual strokes.
    
    n_strokes : int
        Number of strokes to complete.

    both_directions : bool, optional
        Defaults to True. If this value is true the beam will be scanned across
        the sample while moving in both vertical directions. If false, the beam
        is only scanned in a single direction.
    """

    RE = RunEngine({})
    bec = BestEffortCallback()
    RE.subscribe(bec)
    RE.waiting_hook = ProgressBarManager()
    RE(
        run_wrapper(
            rel_smooth_sweep(mot_x=rsxs_sample_x,
                             mot_y=rsxs_sample_y,
                             shutter=shutter,
                             stroke_height=stroke_height,
                             stroke_spacing=stroke_spacing,
                             n_strokes=n_strokes,
                             both_directions=both_directions)))
コード例 #27
0
def test_euclidean_distance(fresh_RE):
    camera = SynCamera(m1, m2, delay, name="camera")

    # Define the distance plan that makes the assertion
    def test_plan():
        distance = yield from euclidean_distance(camera,
                                                 ['centroid_x', 'centroid_y'],
                                                 [1, 1])
        assert np.isclose(distance, math.sqrt(2))

    # Wrap the plan
    plan = run_wrapper(test_plan())
    # And now run it
    fresh_RE(plan)
コード例 #28
0
ファイル: test_run_engine.py プロジェクト: NSLS-II/bluesky
def test_nonrewindable_detector(RE, hw, start_state, msg_seq):
    class FakeSig:
        def get(self):
            return False

    hw.det.rewindable = FakeSig()

    RE.rewindable = start_state
    m_col = MsgCollector()
    RE.msg_hook = m_col

    RE(run_wrapper(trigger_and_read([hw.motor, hw.det])))

    assert [m.command for m in m_col.msgs] == msg_seq
コード例 #29
0
def test_nonrewindable_detector(RE, hw, start_state, msg_seq):
    class FakeSig:
        def get(self):
            return False

    hw.det.rewindable = FakeSig()

    RE.rewindable = start_state
    m_col = MsgCollector()
    RE.msg_hook = m_col

    RE(run_wrapper(trigger_and_read([hw.motor, hw.det])))

    assert [m.command for m in m_col.msgs] == msg_seq
コード例 #30
0
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)
コード例 #31
0
def test_calibration_centroid_scan_df_is_valid(fresh_RE):
    camera = SynCamera(m1, m2, delay, name="camera")

    def test_plan():
        df = yield from calib.calibration_centroid_scan(
            camera,
            delay, [m1, m2],
            -1,
            1,
            5,
            detector_fields=['camera_centroid_x', 'camera_centroid_y'])
        assert True not in df.isnull().values

    # Run the plan
    fresh_RE(run_wrapper(test_plan()))
コード例 #32
0
ファイル: test_callbacks.py プロジェクト: xpdAcq/xpdAn
def test_interrupted_with_callbacks(RE, int_meth, stop_num, msg_num):

    docs = defaultdict(list)

    def collector_cb(name, doc):
        nonlocal docs
        docs[name].append(doc)

    RE.msg_hook = MsgCollector()

    with pytest.raises(RunEngineInterrupted):
        RE(subs_wrapper(run_wrapper(pause()), {"all": collector_cb}))
    getattr(RE, int_meth)()

    assert len(docs["start"]) == 1
    assert len(docs["event"]) == 0
    assert len(docs["descriptor"]) == 0
    assert len(docs["stop"]) == stop_num
    assert len(RE.msg_hook.msgs) == msg_num