Esempio n. 1
0
    def _stage():

        _heater_status = yield from rd(mag6t.field.switch_heater)

        if _heater_status != 'On':
            # Click current ramp button
            yield from mv(mag6t.field.ramp_button, 1)

            # Wait for the supply current to match the magnet.
            target = yield from rd(mag6t.field.current)
            function = _difference_check(target, tolerance=0.01)
            yield from abs_set(signal,
                               mag6t.field.supply_current,
                               function,
                               wait=True)

            # Turn on persistance switch heater.
            yield from mv(mag6t.field.switch_heater, 'On')
            yield from sleep(2)

            # Wait for the heater to be on.
            function = _status_check(target=[3])
            yield from abs_set(signal,
                               mag6t.field.magnet_status,
                               function,
                               wait=True)

            # Click current ramp button
            yield from mv(mag6t.field.ramp_button, 1)
Esempio n. 2
0
def test_blackfly(RE, db, shutter, noise):
    for cycle in [
            None,
            cycler("blackfly_det_image", [np.ones(BLACKFLY_IMG_SIZE)])
    ]:
        det = det_factory(
            cycle=cycle,
            data_key="blackfly_det_image",
            shutter=shutter,
            noise=noise,
            size=BLACKFLY_IMG_SIZE,
        )
        RE.subscribe(db.insert, "all")
        RE(bs.abs_set(shctl1, XPD_SHUTTER_CONF["open"], wait=True))
        uid = RE(bp.count([det]))
        for name, doc in db.restream(db[-1], fill=True):
            if name == "event":
                db_img = doc["data"]["blackfly_det_image"]
                assert db_img.squeeze().shape == BLACKFLY_IMG_SIZE
        assert uid is not None
        if shutter:
            RE(bs.abs_set(shctl1, XPD_SHUTTER_CONF["close"], wait=True))
            uid = RE(bp.count([det]))
            for name, doc in db.restream(db[-1], fill=True):
                if name == "event":
                    db_img = doc["data"]["blackfly_det_image"]
                    assert db_img.squeeze().shape == BLACKFLY_IMG_SIZE
                    assert np.allclose(db_img, np.zeros_like(db_img))
            assert uid is not None
def inner_expo(exposure):
    """private function to configure pe1c with continuous acquisition mode
    cs studio configuration doesn't propagate to python level
    """
    yield from bps.abs_set(
        xpd_configuration["area_det"].cam.acquire_time,
        glbl["frame_acq_time"],
        wait=True,
    )
    print('l50')
    # compute number of frames
    acq_time = xpd_configuration["area_det"].cam.acquire_time.get()
    print('l53')
    # _check_mini_expo(exposure, acq_time)
    num_frame = np.ceil(exposure / acq_time)
    print('l56')
    computed_exposure = num_frame * acq_time
    yield from bps.abs_set(xpd_configuration["area_det"].images_per_set,
                           num_frame,
                           wait=True)
    print('l61')
    # print exposure time
    print("INFO: requested exposure time = {} - > computed exposure time"
          "= {}".format(exposure, computed_exposure))
    print('l67')
    return num_frame, acq_time, computed_exposure
Esempio n. 4
0
def test_dets_shutter(RE, db, name, fp):
    det = det_factory(cycle=build_image_cycle(fp), shutter=shctl1)
    RE.subscribe(db.insert, "all")
    uid = RE(bp.count([det]))
    cycle2 = build_image_cycle(fp)
    cg = cycle2()
    # With the shutter down
    RE(bs.abs_set(shctl1, XPD_SHUTTER_CONF["close"], wait=True))
    uid = RE(bp.count([det]))
    for name, doc in db.restream(db[-1], fill=True):
        if name == "event":
            assert_array_equal(
                doc["data"]["pe1_image"],
                np.zeros_like(doc["data"]["pe1_image"]),
            )
    assert uid is not None

    # With the shutter up
    RE(bs.abs_set(shctl1, XPD_SHUTTER_CONF["open"], wait=True))
    print('outside shutter id =', id(shctl1))
    print('outside shutter status =', shctl1.get())
    uid = RE(bp.count([det]))
    for name, doc in db.restream(db[-1], fill=True):
        if name == "event":
            assert_array_equal(doc["data"]["pe1_image"], next(cg)["pe1_image"])
    assert uid is not None
Esempio n. 5
0
def configure_area_det(det, md: Dict[str, Union[int, float]]):
    """
    Yield the message to configure the area detector with time per frame and number of frames per exposure
    according to the required exposure time. Update the metadata.

    Parameters
    ----------
    det
        The area detector.
    md
        A dictionary to configure the area detector. It is the output of calc_exposure.
        It contains the key value pairs:
        {
            'sp_time_per_frame': acq_time (float),
            'sp_num_frames': num_frame (int),
            'sp_requested_exposure': exposure (float),
            'sp_computed_exposure': computed_exposure (float)
        }

    Yields
    ------
    msg
        Message to configure the area detector.
    """
    acq_time = md.get('sp_time_per_frame')
    num_frame = md.get('sp_num_frames')

    yield from bps.abs_set(det.cam.acquire_time, acq_time, wait=True)
    if hasattr(det, "images_per_set"):
        yield from bps.abs_set(det.images_per_set, num_frame, wait=True)
Esempio n. 6
0
def test_sigint_three_hits(RE, hw):
    motor = hw.motor
    motor.delay = 0.3

    pid = os.getpid()

    def sim_kill(n=1):
        for j in range(n):
            print('KILL')
            os.kill(pid, signal.SIGINT)

    lp = RE.loop
    motor.loop = lp
    lp.call_later(.02, sim_kill, 3)
    lp.call_later(.02, sim_kill, 3)
    lp.call_later(.02, sim_kill, 3)
    start_time = ttime.time()
    with pytest.raises(RunEngineInterrupted):
        RE(
            finalize_wrapper(abs_set(motor, 1, wait=True),
                             abs_set(motor, 0, wait=True)))
    end_time = ttime.time()
    assert end_time - start_time < 0.2  # not enough time for motor to cleanup
    RE.abort()  # now cleanup
    done_cleanup_time = ttime.time()
    assert done_cleanup_time - end_time > 0.3
def configure_cam_detector(detector: tp.Any, acquire_time: float,
                           images_per_set: int) -> tp.Generator:
    """Configure the acquire_time of the cam opponent in detector and the images_per_set of the detector."""
    print("acquire_time -> {}; images_per_set -> {}; exposure -> {}".format(
        acquire_time, images_per_set, acquire_time * images_per_set))
    yield from bps.abs_set(detector.cam.acquire_time, acquire_time, wait=True)
    yield from bps.abs_set(detector.images_per_set, images_per_set, wait=True)
Esempio n. 8
0
def test_sigint_three_hits(RE, hw):
    motor = hw.motor
    motor.delay = 0.3

    pid = os.getpid()

    def sim_kill(n=1):
        for j in range(n):
            print('KILL')
            os.kill(pid, signal.SIGINT)

    lp = RE.loop
    motor.loop = lp
    lp.call_later(.02, sim_kill, 3)
    lp.call_later(.02, sim_kill, 3)
    lp.call_later(.02, sim_kill, 3)
    start_time = ttime.time()
    with pytest.raises(RunEngineInterrupted):
        RE(finalize_wrapper(abs_set(motor, 1, wait=True),
                            abs_set(motor, 0, wait=True)))
    end_time = ttime.time()
    assert end_time - start_time < 0.2  # not enough time for motor to cleanup
    RE.abort()  # now cleanup
    done_cleanup_time = ttime.time()
    assert done_cleanup_time - end_time > 0.3
Esempio n. 9
0
def MED(init_gas, other_gas, minT, maxT, num_steps, num_steady, num_trans, num_loops=2):
    """
    1. Start flowing the initial gas.
    2. Scan the temperature from minT to maxT in `num_steps` evenly-spaced steps.
    3. Hold temperature at maxT and take  `num_steady` images.
    4. Repeat (2) and (3) `num_loops` times.
    5. Switch the gas to `other_gas` and take `num_trans` acquisitions.
    6. Switch it back and take another `num_trans` acquisitions.

    Example
    -------
    Set the gasses. They can be in any other, nothing to do with
    the order they are used in the plan.
    >>> gas.gas_list = ['O2', 'CO2']

    Optionally, preview the plan.
    >>> print_summary(MED('O2', 'C02', 200, 300, 21, 20, 60))

    Execute it.
    >>> RE(MED('O2', 'C02', 200, 300, 21, 20, 60))

    """
    # Step 1
    yield from abs_set(gas, init_gas)
    # Steps 2 and 3 in a loop.
    for _ in range(num_loops):
        yield from subs_wrapper(scan([pe1, gas.current_gas], eurotherm, minT, maxT, num_steps),
                            LiveTable([eurotherm, gas.current_gas]))
        yield from subs_wrapper(count([pe1], num_steady), LiveTable([]))
    # Step 4
    yield from abs_set(gas, other_gas)
    yield from subs_wrapper(count([pe1], num_steady), LiveTable([]))
    # Step 6
    yield from abs_set(gas, init_gas)
    yield from subs_wrapper(count([pe1], num_steady), LiveTable([]))
Esempio n. 10
0
def fix_epu():
    # move the energy setpoint to where the energy really is
    yield from bps.abs_set(pgm.energy, pgm.energy.position, wait=True)
    # set the interpolator to look at what it was looking at before
    # the scan.  This should be the energy set point.
    yield from bps.abs_set(epu1.flt.input_pv, 'XF:23ID2-OP{Mono}Enrgy-SP CP MS', wait=True)
    yield from bps.abs_set(epu1.flt.output_deadband, 0, wait=True)
Esempio n. 11
0
def fly_scan(E0, mono_speed, device_dict, parent):
    # Initial settings
    flyer = device_dict['energyFlyer']

    parent.subscribe_callback()
    parent.toLog("A new fly scan is started!", color='blue')

    # Set to fly scan speed
    yield from bps.abs_set(flyer.fly_motor_speed, mono_speed)

    # Do fly scan
    yield from bpp.monitor_during_wrapper(bp.fly([flyer]), [
        device_dict['ENC_fly_counter'], device_dict['I0_fly_counter'],
        device_dict['It_fly_counter'], device_dict['If_fly_counter'],
        device_dict['Ir_fly_counter']
    ])

    # Set to normal speed
    yield from bps.abs_set(flyer.fly_motor_speed, parent._orig_mono_speed)

    # Move to E0
    yield from stop_and_mv(dcm, E0)

    parent.unsubscribe_callback()

    # Decrease remaining scan-number
    num_scan = int(parent.control.number_of_scan_edit.value())
    if num_scan > 1:
        _submit(parent.control.number_of_scan_edit.setValue, num_scan - 1)

        cooling_time = parent.control.flyControl.flyCoolTime.value()
        parent.toLog(
            "Cooling dcm. The next scan starts after {} seconds.".format(
                cooling_time))
        yield from bps.sleep(cooling_time)
Esempio n. 12
0
 def clean_up():
     # move the energy setpoint to where the energy really is
     yield from bps.abs_set(pgm.energy, pgm.energy.position, wait=True)
     # set the interpolator to look at what it was looking at before
     # the scan.  This should be the energy set point.
     yield from bps.abs_set(epu1.flt.input_pv, old_link, wait=True)
     yield from bps.abs_set(epu1.flt.output_deadband, old_db, wait=True)
Esempio n. 13
0
def recover_mirrors():
    m2_xu, m2_xd, m2_yu, m2_ydo, m2_ydi = user_ns['m2_xu'], user_ns['m2_xd'], user_ns['m2_yu'], user_ns['m2_ydo'], user_ns['m2_ydi']
    m3_xu, m3_xd, m3_yu, m3_ydo, m3_ydi = user_ns['m3_xu'], user_ns['m3_xd'], user_ns['m3_yu'], user_ns['m3_ydo'], user_ns['m3_ydi']
    yield from abs_set(m2_yu.home_signal,  1)
    yield from abs_set(m2_xu.home_signal,  1)
    yield from abs_set(m3_yu.home_signal,  1)
    yield from abs_set(m3_xu.home_signal,  1)
    yield from sleep(1.0)
    print('Begin homing lateral and vertical motors in M2 and M3:\n')
    hvalues = (m2_yu.hocpl.get(), m2_ydo.hocpl.get(), m2_ydi.hocpl.get(), m2_xu.hocpl.get(), m2_xd.hocpl.get(),
               m3_yu.hocpl.get(), m3_ydo.hocpl.get(), m3_ydi.hocpl.get(), m3_xu.hocpl.get(), m3_xd.hocpl.get())
    while any(v == 0 for v in hvalues):
        hvalues = (m2_yu.hocpl.get(), m2_ydo.hocpl.get(), m2_ydi.hocpl.get(), m2_xu.hocpl.get(), m2_xd.hocpl.get(),
                   m3_yu.hocpl.get(), m3_ydo.hocpl.get(), m3_ydi.hocpl.get(), m3_xu.hocpl.get(), m3_xd.hocpl.get())
        strings = ['m2_yu', 'm2_ydo', 'm2_ydi', 'm2_xu', 'm2_xd', 'm3_yu', 'm3_ydo', 'm3_ydi', 'm3_xu', 'm3_xd',]
        for i,v in enumerate(hvalues):
            strings[i] = go_msg(strings[i]) if hvalues[i] == 1 else error_msg(strings[i])
        print('  '.join(strings), end='\r')
        yield from sleep(1.0)
    print('\n')
    yield from mv(m2_yu,  MODEDATA['m2_yu']['E'],
                  m2_ydo, MODEDATA['m2_ydo']['E'],
                  m2_ydi, MODEDATA['m2_ydi']['E'],
                  m2_xu,  MODEDATA['m2_xu']['E'],
                  m2_xd,  MODEDATA['m2_xd']['E'],
                  m3_yu,  MODEDATA['m3_yu']['E'],
                  m3_ydo, MODEDATA['m3_ydo']['E'],
                  m3_ydi, MODEDATA['m3_ydi']['E'],
                  m3_xu,  MODEDATA['m3_xu']['E'],
                  m3_xd,  MODEDATA['m3_xd']['E'])
Esempio n. 14
0
def set_integration_plan(time=0.5):
    '''
    set integration times for electrometers and Struck from a plan
    '''
    yield from abs_set(user_ns['vor'].auto_count_time, time, wait=True)
    yield from abs_set(user_ns['quadem1'].averaging_time, time, wait=True)
    yield from abs_set(user_ns['dualio'].averaging_time, time, wait=True)
Esempio n. 15
0
def _configure_area_det(exposure):
    """private function to configure pe1c with continuous acquisition mode"""
    det = xpd_configuration["area_det"]
    # cs studio configuration doesn't propagate to python level

    yield from bps.abs_set(det.cam.acquire_time, glbl["frame_acq_time"])
    acq_time = det.cam.acquire_time.get()
    _check_mini_expo(exposure, acq_time)
    if hasattr(det, "images_per_set"):
        # compute number of frames
        num_frame = np.ceil(exposure / acq_time)
        yield from bps.abs_set(det.images_per_set, num_frame)
    else:
        # The dexela detector does not support `images_per_set` so we just
        # use whatever the user asks for as the thing
        # TODO: maybe put in warnings if the exposure is too long?
        num_frame = 1
    computed_exposure = num_frame * acq_time

    # print exposure time
    print(
        "INFO: requested exposure time = {} - > computed exposure time"
        "= {}".format(exposure, computed_exposure)
    )
    return num_frame, acq_time, computed_exposure
Esempio n. 16
0
 def clean_up():
     # move the energy setpoint to where the energy really is
     yield from bps.abs_set(pgm.energy, pgm.energy.position, wait=True)
     # set the interpolator to look at what it was looking at before
     # the scan.  This should be the energy set point.
     yield from bps.abs_set(epu1.flt.input_pv, old_link, wait=True)
     yield from bps.abs_set(epu1.flt.output_deadband, old_db, wait=True)
Esempio n. 17
0
def tune_plan(step=0):
    '''
    Tune 2nd crystal pitch from a plan.  Argument is a value for the step, so a relative motion.
    '''
    yield from abs_set(dcm_pitch.kill_cmd, 1, wait=True)
    yield from mvr(dcm_pitch, step)
    yield from sleep(1.0)
    yield from abs_set(dcm_pitch.kill_cmd, 1, wait=True)
Esempio n. 18
0
 def cleanup_plan():
     yield from mv(user_ns['slits3'].vsize, slit_height)
     yield from abs_set(user_ns['_locked_dwell_time'], 0.5, wait=True)
     yield from sleep(1.0)
     yield from abs_set(motor.kill_cmd, 1, wait=True)
     yield from sleep(1.0)
     yield from user_ns['dcm'].kill_plan()
     yield from resting_state_plan()
Esempio n. 19
0
def slit_scan_fiducialize(slits,
                          yag,
                          x_width=0.01,
                          y_width=0.01,
                          samples=10,
                          filters=None,
                          centroid='detector_stats2_centroid_y'):
    """
    Assists beam alignment by setting the slits to a w,h and checking,
    returning the centroid position.

    Parameters
    ----------
    slits : pcdsdevices.slits.Slits
        Ophyd slits object from pcdsdevices.slits.Slits

    yag : pcdsdevices.pim.PIM
        Detector to fidicuialize. This plan assumes the detector is stated and
        inserted

    x_width : float
        x dimensions of the gap in the slits. EGU: mm

    y_width : float
        y dimensions of the gap in the slits. EGU: mm

    samples : int
        Returned measurements are averages over multiple samples. samples arg
        determines the number of samples to average over for returned data

    filters : dict, optional
        Key, callable pairs of event keys and single input functions that
        evaluate to True or False. For more infromation see
        :meth:`.apply_filters`

    centroid : str, optional
        Key to gather centroid information

    Returns
    -------
    float
        return centroid position in pixel space, single axis
    """
    # Set slits and imager, wait together
    group = str(uuid.uuid4())
    yield from abs_set(yag, "IN", group=group)
    yield from abs_set(slits, x_width, group=group)
    yield from plan_wait(group=group)

    #Collect data from yags
    yag_measurements = yield from measure_average([yag],
                                                  num=samples,
                                                  filters=filters)

    #Extract centroid positions from yag_measurments dict
    centroid = yag_measurements[field_prepend(centroid, yag)]

    return centroid
Esempio n. 20
0
def fix_epu():
    # move the energy setpoint to where the energy really is
    yield from bps.abs_set(pgm.energy, pgm.energy.position, wait=True)
    # set the interpolator to look at what it was looking at before
    # the scan.  This should be the energy set point.
    yield from bps.abs_set(epu1.flt.input_pv,
                           'XF:23ID2-OP{Mono}Enrgy-SP CP MS',
                           wait=True)
    yield from bps.abs_set(epu1.flt.output_deadband, 0, wait=True)
Esempio n. 21
0
def tweak_bct(step):
    dm3_bct = user_ns['dm3_bct']
    if step is None:
        step = 0
    yield from abs_set(dm3_bct.kill_cmd,1, wait=True)
    print('Moving from %.4f to %.4f' % (dm3_bct.user_readback.get(), dm3_bct.user_readback.get() + step))
    yield from mvr(dm3_bct, step)
    time.sleep(3.0)
    yield from abs_set(dm3_bct.kill_cmd,1, wait=True)
Esempio n. 22
0
def multi_edge(*, edge_list=None):
    if edge_list is None:
        edge_list = list(EDGE_MAP)
#    edge_list = sorted(edge_list, key=lambda k: EDGE_MAP[k]['start'])
    cy = cycler('edge', edge_list)
    for inp in cy:
       yield from XAS_edge_scan(**inp)
    yield from bps.abs_set(valve_diag3_close, 1)
    yield from bps.abs_set(valve_mir3_close, 1)
Esempio n. 23
0
def multi_sample_edge(*, edge_list=None, sample_list=None):
    if sample_list is None:
        sample_list = list(SAMPLE_MAP)
    if edge_list is None:
        edge_list = list(EDGE_MAP)
#    edge_list = sorted(edge_list, key=lambda k: EDGE_MAP[k]['start'])
    cy = cycler('edge', edge_list) * cycler('sample_name', sample_list)
    for inp in cy:
        if pass_filter(**inp):
            yield from edge_ascan(**inp)
    yield from bps.abs_set(valve_diag3_close, 1)
    yield from bps.abs_set(valve_mir3_close, 1)
def move_m3(target=5):
    alpha = 9002  # distance M3 to Be window
    beta = 9637  # distance M3 to xafs_yu
    gamma = 10792  # distance M3 to xafs_ydo/xafs_ydi

    #bnot = 46.11                # BCT position in mode D/E
    #unot = 132                  # xafs_yu position in mode D/E
    #dnot = 132                  # xafs_ydo/xafs_ydi position in mode D/E
    bnot = 29.57  # BCT position in mode D/E
    unot = 111.6  # xafs_yu position in mode D/E
    dnot = 109.9  # xafs_ydo/xafs_ydi position in mode D/E

    thetanot = 0  # angle in mR of M3 in mode A
    #thetanot = 3.5             # angle in mR of M3 in mode D/E

    theta = target - thetanot

    #correction = 0.8 * tan(theta/1000) / tan(1.5/1000)
    correction = 0.0 * tan(theta / 1000) / tan(1.5 / 1000)

    bct = bnot - alpha * tan((2 * theta) / 1000) + correction - 0.6
    upstr = unot - beta * tan((2 * theta) / 1000) + correction
    dnstr = dnot - gamma * tan((2 * theta) / 1000) + correction

    print(
        '\nThe M3 target is %.2f mRad relative to the beam incident on M3\n' %
        target)
    print('Move M3 pitch to %.2f mRad' % (thetanot - theta))
    print('\t BCT:          %.2f' % bct)
    print('\t xafs_yu:      %.2f' % upstr)
    print('\t xafs_yd:      %.2f' % dnstr)
    print('\t (correction): %.2f' % correction)
    print('')

    action = input("Begin moving motors> [Y/n then Enter] ")
    if action.lower() == 'q' or action.lower() == 'n':
        yield from null()
        return

    RE.msg_hook = None
    BMM_log_info(
        'Moving mirror 3: target = %.2f, M3 pitch = %.2f\nBCT -> %.2f, yu -> %.2f, yd -> %.2f, correction = %.2f'
        % (target, thetanot - theta, bct, upstr, dnstr, correction))

    yield from abs_set(dm3_bct.kill_cmd, 1, wait=True)  # and after

    yield from mv(m3.pitch, thetanot - theta, dm3_bct, bct, xafs_table.yu,
                  upstr, xafs_table.ydo, dnstr, xafs_table.ydi, dnstr)

    yield from sleep(2.0)
    yield from abs_set(dm3_bct.kill_cmd, 1, wait=True)  # and after
    RE.msg_hook = BMM_msg_hook
    BMM_log_info(motor_status())
Esempio n. 25
0
 def count_dets(_dets, _full_md):
     _count_plan = bp.count(_dets, md=_full_md)
     _count_plan = bpp.subs_wrapper(_count_plan, LiveTable(_dets))
     _count_plan = bpp.finalize_wrapper(
         _count_plan,
         bps.abs_set(xpd_configuration['shutter'],
                     XPD_SHUTTER_CONF['close'],
                     wait=True))
     yield from bps.abs_set(xpd_configuration['shutter'],
                            XPD_SHUTTER_CONF['open'],
                            wait=True)
     yield from _count_plan
def nano_y_scan_and_fly(*args, extra_dets=None, **kwargs):
    kwargs.setdefault('xmotor', nano_stage.sy)
    kwargs.setdefault('ymotor', nano_stage.sx)
    kwargs.setdefault('flying_zebra', nano_flying_zebra)
    yield from abs_set(nano_flying_zebra.fast_axis, 'NANOVER')
    yield from abs_set(nano_flying_zebra.slow_axis, 'NANOHOR')

    _xs = kwargs.pop('xs', xs)
    if extra_dets is None:
        extra_dets = []
    dets = [_xs] + extra_dets
    yield from scan_and_fly_base(dets, *args, **kwargs)
    def inner():
        # Prepare Camera
        yield from bps.mv(cam.acquire, 0)  # Stop camera...
        yield from bps.sleep(.5)  # ...and wait for the pipeline to empty.
        yield from bps.mv(
            cam.trigger_mode,
            "Sync In 1",  # External Trigger
            cam.array_counter,
            0,
        )

        if use_roi4:
            yield from bps.mv(cam.min_x, roi.min_xyz.min_x.get(), cam.min_y,
                              roi.min_xyz.min_y.get(), cam.size.size_x,
                              roi.size.x.get(), cam.size.size_y,
                              roi.size.y.get())

        # Prepare TIFF Plugin
        yield from bps.mv(tiff.file_write_mode, "Stream", tiff.num_capture,
                          steps, tiff.auto_save, 1, tiff.auto_increment, 1,
                          tiff.file_path, folder, tiff.file_name, filename,
                          tiff.file_template, "%s%s_%d.tif", tiff.file_number,
                          1, tiff.enable, 1)

        yield from bps.abs_set(tiff.capture, 1)

        yield from bps.abs_set(cam.acquire, 1)  # wait=False

        # Move to the starting positions
        yield from bps.mv(
            gonio.py,
            start_y - slack_y,
            gonio.pz,
            start_z - slack_z,
        )

        # Set velocity for the scan
        yield from bps.mv(gonio.py.velocity, speed_y, gonio.pz.velocity,
                          speed_z)

        # Arm Zebra
        yield from bps.abs_set(zebra.pos_capt.arm.arm, 1)

        # Wait Zebra armed
        while not zebra2.download_status.get():
            time.sleep(0.1)

        # Go
        yield from bps.mv(gonio.py, end_y + slack_y, gonio.pz, end_z + slack_z)

        yield from bps.abs_set(tiff.capture, 0)

        print(f"{cam.array_counter.get()} images captured")
Esempio n. 28
0
def multi_sample_edge(*, edge_list=None, sample_list=None):
    if sample_list is None:
        sample_list = list(SAMPLE_MAP)
    if edge_list is None:
        edge_list = list(EDGE_MAP)
#    edge_list = sorted(edge_list, key=lambda k: EDGE_MAP[k]['start'])
    cy = cycler('edge', edge_list) * cycler('sample_name', sample_list)
    for inp in cy:
        if pass_filter(**inp):
            yield from edge_ascan(**inp)
    yield from bps.abs_set(valve_diag3_close, 1)
    yield from bps.abs_set(valve_mir3_close, 1)
def move_m2(target=3.5):
    alpha = 10907  # distance M2 to Be window
    beta = 11542  # distance M2 to xafs_yu
    gamma = 12697  # distance M2 to xafs_ydo/xafs_ydi

    bnot = 50.2  # BCT position in mode A
    unot = 136 - 0.83  # xafs_yu position in mode A
    dnot = 136 - 0.92  # xafs_ydo/xafs_ydi position in mode D/E
    #bnot = 35.14                # BCT position in mode A
    #unot = 120.04                  # xafs_yu position in mode A
    #dnot = 117.96                  # xafs_ydo/xafs_ydi position in mode D/E

    thetanot = 3.5  # angle in mR of M2 in mode A
    #thetanot = 4.428              # angle in mR of M2 in mode A

    theta = target - thetanot

    correction = 0  # 0.8 * tan(theta/1000) / tan(1.5/1000)

    bct = bnot - alpha * tan((2 * theta) / 1000) + correction + 1.218
    upstr = unot - beta * tan((2 * theta) / 1000) + correction
    dnstr = dnot - gamma * tan((2 * theta) / 1000) + correction

    print(
        '\nThe M2 target is %.2f mRad relative to the beam incident on M2\n' %
        target)
    print('Move M2 pitch to %.2f mRad' % (thetanot - theta))
    print('\t BCT:          %.2f' % bct)
    print('\t xafs_yu:      %.2f' % upstr)
    print('\t xafs_yd:      %.2f' % dnstr)
    print('\t (correction): %.2f' % correction)
    print('')

    action = input("Begin moving motors? [Y/n then Enter] ")
    if action.lower() == 'q' or action.lower() == 'n':
        yield from null()
        return

    RE.msg_hook = None
    BMM_log_info(
        'Moving mirror 2: target = %.2f, M2 pitch = %.2f\nBCT -> %.2f, yu -> %.2f, yd -> %.2f, correction = %.2f'
        % (target, thetanot - theta, bct, upstr, dnstr, correction))

    yield from abs_set(dm3_bct.kill_cmd, 1, wait=True)

    yield from mv(m2.pitch, thetanot - theta, dm3_bct, bct, xafs_table.yu,
                  upstr, xafs_table.ydo, dnstr, xafs_table.ydi, dnstr)

    yield from sleep(2.0)
    yield from abs_set(dm3_bct.kill_cmd, 1, wait=True)  # and after
    RE.msg_hook = BMM_msg_hook
    BMM_log_info(motor_status())
Esempio n. 30
0
        def move_to_start_fly():
            "See http://nsls-ii.github.io/bluesky/plans.html#the-per-step-hook"
            # row_str = short_uid('row')
            # yield from abs_set(xmotor, row_start, group=row_str)
            # yield from one_1d_step([temp_nanoKB], motor, step)
            # yield from bps.wait(group=row_str)

            row_str = short_uid('row')
            yield from bps.checkpoint()
            yield from bps.abs_set(xmotor, row_start, group=row_str)
            yield from bps.abs_set(motor, step, group=row_str)
            yield from bps.wait(group=row_str)
            yield from bps.trigger_and_read([temp_nanoKB, motor])
Esempio n. 31
0
def _shutter_step(detectors, motor, step):
    """ customized step to ensure shutter is open before
    reading at each motor point and close shutter after reading
    """
    yield from bps.checkpoint()
    yield from bps.abs_set(motor, step, wait=True)
    yield from bps.abs_set(
        xpd_configuration["shutter"], XPD_SHUTTER_CONF["open"], wait=True
    )
    yield from bps.sleep(glbl['shutter_sleep'])
    yield from bps.trigger_and_read(list(detectors) + [motor])
    yield from bps.abs_set(
        xpd_configuration["shutter"], XPD_SHUTTER_CONF["close"], wait=True
    )
Esempio n. 32
0
    def setup_dc(self, enable, period, off_time, verify=True):
        enable = 1 if enable else 0
        period = int(period)
        off_time = int(off_time)
        wait_group = 'anc_set_dc'

        yield from bps.abs_set(self.dc_period, period,
                               group=wait_group)
        yield from bps.abs_set(self.dc_off_time, off_time,
                               group=wait_group)
        yield from bps.abs_set(self.dc_enable, enable,
                               group=wait_group)
        if verify:
            yield from bps.wait(group=wait_group)
Esempio n. 33
0
def fast_shutter_wrapper(plan):
    update_metadata()

    if USE_FAST_SHUTTER:
        plan = bpp.pchain(
            bps.abs_set(fast_shutter.output,
                        FastShutter.OPEN_SHUTTER,
                        settle_time=FastShutter.SETTLE_TIME), plan)
        plan = bpp.finalize_wrapper(
            plan,
            bps.abs_set(fast_shutter.output,
                        FastShutter.CLOSE_SHUTTER,
                        settle_time=FastShutter.SETTLE_TIME))

    return (yield from plan)
Esempio n. 34
0
def close_shutter_stub():
    """simple function to return a generator that yields messages to
    close the shutter"""
    yield from bps.abs_set(
        xpd_configuration["shutter"], XPD_SHUTTER_CONF["close"], wait=True
    )
    yield from bps.checkpoint()
Esempio n. 35
0
    def go_plan():
        ret = (yield from bps.abs_set(pgm.fly.fly_start, 1))

        st = StatusBase()
        enum_map = pgm.fly.scan_status.describe()[
            pgm.fly.scan_status.name]['enum_strs']

        def _done_cb(value, old_value, **kwargs):
            print(f'Old value {old_value} -> new value {value}')
            print(
                f'Old value type {type(old_value)} -> new value {type(value)}')
            try:
                old_value = enum_map[int(old_value)]
            except (TypeError, ValueError):
                ...
            try:
                value = enum_map[int(value)]
            except (TypeError, ValueError):
                ...
            if old_value != value and value == 'Ready':
                st._finished()
                pgm.fly.scan_status.clear_sub(_done_cb)

        if ret is not None:
            pgm.fly.scan_status.subscribe(_done_cb, run=False)
        else:
            st._finished()
            print('SIM MODE')

        return st
Esempio n. 36
0
def change_epu_flt_link(new_target):
    v = (yield from bps.read(epu1.flt.input_pv))
    if v is None:
        return
    n = epu1.flt.input_pv.name
    cur_pv = v[n]['value']
    pts = cur_pv.split(' ', maxsplit=1)
    new_pv = ' '.join([new_target] + pts[1:])
    yield from bps.abs_set(epu1.flt.input_pv, new_pv)
Esempio n. 37
0
 def move():
     yield from checkpoint()
     grp = short_uid("set")
     for motor, pos in step.items():
         if pos == pos_cache[motor]:
             # This step does not move this motor.
             continue
         yield from abs_set(motor, pos, group=grp)
         pos_cache[motor] = pos
     yield from wait(group=grp)
Esempio n. 38
0
def _epu_ramp(dets, start, stop):
    def go_plan():
        return (yield from bps.abs_set(epu1.gap, stop, wait=False))

    def inner_plan():
        yield from trigger_and_read(dets)

    yield from bps.abs_set(epu1.gap, start, wait=True)

    return (yield from (ramp_plan(go_plan(), pgm.energy,
                                  inner_plan, period=None, md=md)))
Esempio n. 39
0
def _ct_dark_cleanup(oldnumim, gain_bit_dict, gain_state,
                     dark_sh_dict, dark_shutter_state):
    print('\nReturning to intial conditions (pre-count).')
    yield from bps.abs_set(fccd.cam.num_images, oldnumim, wait=True)

    yield from bps.mv(fccd.cam.fcric_gain, gain_state)
    yield from bps.mv(inout, dark_sh_dict.get(dark_shutter_state))
    yield from bps.sleep(fccd.cam.acquire_period.value)

    print('\tTotal images per trigger are NOW:\t {}'.format(
        fccd.cam.num_images.setpoint))
    print('\tFCCD FCRIC gain value is NOW:\t\t {}\n\n'.format(
        gain_bit_dict.get(fccd.cam.fcric_gain.value)))
Esempio n. 40
0
def open_all_valves(valve_list):
    '''Open all the listed valves

    Parameters
    ----------
    valve_list : sequence
        The valves to open

    '''
    for v in valve_list:
        yield from bps.abs_set(v, 1, group='valve_set')
    yield from bps.wait('valve_set')
    # sleep might not be needed
    yield from bps.sleep(2)
Esempio n. 41
0
    def go_plan():
        ret = (yield from bps.abs_set(pgm.fly.fly_start, 1))

        st = StatusBase()
        enum_map = pgm.fly.scan_status.describe()[pgm.fly.scan_status.name]['enum_strs']
        def _done_cb(value, old_value, **kwargs):
            old_value = enum_map[int(old_value)]
            value = enum_map[int(value)]
            if old_value != value and value == 'Ready':
                st._finished()
                pgm.fly.scan_status.clear_sub(_done_cb)

        if ret is not None:
            pgm.fly.scan_status.subscribe(_done_cb, run=False)
        else:
            st._finished()
            print('SIM MODE')

        return st
Esempio n. 42
0
def multi_part_ascan(DETS, motor1, steps, motor2, asc_p):
    for d in steps:
        yield from bps.abs_set(motor1, d, wait=True)
        yield from bp.scan(DETS, motor2, *asc_p)
Esempio n. 43
0
def edge_ascan(sample_name, edge, md=None):
    '''Run a multi-edge nexafs scan for single sample and edge

    Parameters
    ----------
    sample_name : str
        Base sample name

    sample_position : float
        Postion of sample on manipulator arm

    edge : str
        Key into EDGE_MAP


    '''
    if md is None:
        md = {}
    local_md = {'plan_name': 'edge_ascan'}
    local_md['edge'] = edge
    md = ChainMap(md, local_md)

    e_scan_params = EDGE_MAP[edge]
    # TODO configure the vortex
    det_settings = DET_SETTINGS[edge]
    sample_props = SAMPLE_MAP[sample_name]
#    sample_props = list(sample_manager.find(name=sample_name))
    local_md.update(sample_props)

    # init_group = 'ME_INIT_' + str(uuid.uuid4())
    yield from bps.abs_set(ioxas_x, sample_props['pos'], wait=True)
#    yield from bps.mov(appes_x, sample_props['pos_x'])
#    yield from bps.mov(appes_y, sample_props['pos_y'])
    yield from bps.abs_set(feedback, 0, wait=True)
    yield from bps.abs_set(pgm_energy, e_scan_params['start'], wait=True)
    yield from bps.abs_set(epu1table, e_scan_params['epu_table'], wait=True)
    yield from bps.abs_set(epu1offset, e_scan_params['epu1offset'], wait=True)
    yield from bps.sleep(15)
    yield from bps.abs_set(m1b1_fp, 100)
    yield from bps.abs_set(feedback, 1, wait=True)
    yield from bps.sleep(5)
    yield from bps.abs_set(feedback, 0, wait=True)
    yield from bps.abs_set(vortex_x, det_settings['vortex_pos'], wait=True)
    yield from bps.abs_set(sample_sclr_gain, det_settings['samplegain'], wait=True)
    yield from bps.abs_set(sample_sclr_decade, det_settings['sampledecade'], wait=True)
    yield from bps.abs_set(aumesh_sclr_gain, det_settings['aumeshgain'], wait=True)
    yield from bps.abs_set(aumesh_sclr_decade, det_settings['aumeshdecade'], wait=True)
    yield from bps.abs_set(sclr_time, det_settings['sclr_time'], wait=True)

 #   yield from open_all_valves(all_valves)
    # yield from bp.wait(init_group)

# TODO make this an ohypd obj!!!!!!
    #caput('XF:23IDA-PPS:2{PSh}Cmd:Opn-Cmd',1)
#   yield from bp.sleep(2)
    # TODO make this an ohypd obj!!!!!!
    # TODO ask stuart
    #caput('XF:23IDA-OP:2{Mir:1A-Ax:FPit}Mtr_POS_SP',50)
    yield from bps.sleep(5)

#    yield from bps.configure(vortex, VORTEX_SETTINGS[edge])
#    yield from bps.sleep(2)
    yield from bps.abs_set(vortex.mca.rois.roi4.lo_chan, det_settings['vortex_low'], wait=True)
    yield from bps.abs_set(vortex.mca.rois.roi4.hi_chan, det_settings['vortex_high'], wait=True)
    yield from bps.abs_set(vortex.mca.preset_real_time, det_settings['vortex_time'], wait=True)

#    lp_list = []
#    for n in ['sclr_ch4', 'vortex_mca_rois_roi4_count']:
#        fig = plt.figure(edge + ': ' + n)
#        lp = bs.callbacks.LivePlot(n, 'pgm_energy_readback', fig=fig)
#        lp_list.append(lp)

#    class norm_plot(bs.callbacks.LivePlot):
#        def event(self,doc):
#            try:
#                doc.data['norm_intensity'] = doc.data['sclr_ch4']/doc.data['sclr_ch3']
#            except KeyError:
#                pass
#            super().event(doc)

#    for n in ['sclr_ch4']:
#        fig = plt.figure(edge + ': ' + n)
#        lp = bs.callbacks.LivePlot(n, 'pgm_energy_readback', fig=fig)
#        lp = norm_plot('norm_intensity', 'pgm_energy_readback', fig=fig)
#        lp_list.append(lp)
    dets = [sclr, vortex, norm_ch4, ring_curr]
    for channel in ['mca.rois.roi2.count','mca.rois.roi3.count','mca.rois.roi4.count']:
            getattr(vortex, channel).kind = 'hinted'
    for channel in ['mca.rois.roi2.count','mca.rois.roi3.count']:
            getattr(vortex, channel).kind = 'normal'
    for channel in ['channels.chan3','channels.chan4']:
        getattr(sclr, channel).kind = 'hinted'
    for channel in ['channels.chan2']:
        getattr(sclr, channel).kind = 'normal'
    
    scan_kwargs = {'start': e_scan_params['stop'],
                   'stop': e_scan_params['start'],
                   'velocity': e_scan_params['velocity'],
                   'deadband': e_scan_params['deadband'],
                   'md': md}
    ret = []
    for j in range(e_scan_params['scan_count']):
        tmp_pos = sample_props['pos'] + (j-((e_scan_params['scan_count']-1)/2))*e_scan_params['intervals']
#        yield from bps.mov(appes_y, tmp_pos)
        yield from bps.mov(ioxas_x, tmp_pos)
        yield from bps.abs_set(pgm_energy, e_scan_params['stop'], wait=True)
        yield from open_all_valves(all_valves)
        res = yield from bpp.subs_wrapper(E_ramp(dets, **scan_kwargs), {'stop': save_csv})
        yield from bps.abs_set(valve_diag3_close, 1, wait=True)
        yield from bps.abs_set(valve_mir3_close, 1, wait=True)
        yield from bps.sleep(5)
        if res is None:
            res = []
        ret.extend(res)
        if not ret:
            return ret


    # hdr = db[ret[0]]
    # redo_count = how_many_more_times_to_take_data(hdr)
    # for j in range(redo_count):
    #     res = yield from bpp.subs_wrapper(ascan(*scan_args, md=md), lp)
    #     ret.extend(res)


    # new_count_time = compute_new_count_time(hdr, old_count_time)
    # if new_count_time != old_count_time:
    #     yield from bps.configure(vortex, {'count_time': new_count_time})
    #     res = yield from bpp.subs_wrapper(ascan(*scan_args, md=md), lp)
    #     ret.extend(res)

    return ret
Esempio n. 44
0
def ct_dark(numim=None, detectors=None, gain_std=0):
    """Collect dark images for fccd and add metadata tag for dark and gain.

The pre-count shutter & gain states preserved.

    Parameters
    -----------
    numim: int

        Number of images to be measured. If different from current
        setting, the number of images will revert back to the original
        after the scan is complete.

    detectors: list
        List of detectors to be recorded.
        Default = [fccd]

    gain_std: int
        List of detectors to be recorded.
        Default = 0   (which is 'Auto' or x8, the most sensitive gain)

    Returns
    -------

    """
    if detectors is None:
        detectors = [fccd]

    try:
        # TODO figureout kwargs and self to mkae up to line 44 a
        # single definition
        oldnumim = fccd.cam.num_images.value

        # Printing info
        print(
            '\nStarting procedure to acquire darks '
            '{:3.3}Hz or {:3.3f}s.\n'.format(
                1/fccd.cam.acquire_time.value, fccd.cam.acquire_time.value))

        print('\tCurrent number of images = {}.\n'.format(
            fccd.cam.num_images.value))

        yield from bps.sleep(.3)

        if numim is not None:
            print('\tSetting to {} images.\n'.format(numim))
            yield from bps.abs_set(fccd.cam.num_images, numim, wait=True)

        dark_shutter_state = inout.status.value
        dark_sh_dict = {'Inserted': 'In', 'Not Inserted': 'Out'}
        gain_state = fccd.cam.fcric_gain.value
        gain_bit_dict = {0: 'auto', 1: 'x2', 2: 'x1'}

        yield from bps.mv(inout, 'In')
        # This has to be 2 until we can selectively remove dark images
        # get_fastccd_images()
        yield from bps.sleep(fccd.cam.acquire_period.value*2.01)
        # SET TO 1 TO ARM FOR NEXT EVENT so that the FastCCD1 is
        # already bkg subt
        yield from bps.mv(fccd.fccd1.capture_bgnd, 1)

        # take darks
        yield from _ct_dark(detectors, gain_std, gain_bit_dict)

        # Putting things back
        yield from _ct_dark_cleanup(oldnumim, gain_bit_dict,
                                    gain_state, dark_sh_dict,
                                    dark_shutter_state)

    except Exception:
        yield from _ct_dark_cleanup(oldnumim, gain_bit_dict, gain_state,
                                    dark_sh_dict, dark_shutter_state)
        raise
    except KeyboardInterrupt:
        yield from _ct_dark_cleanup(oldnumim, gain_bit_dict,
                                    gain_state, dark_sh_dict,
                                    dark_shutter_state)
        raise
Esempio n. 45
0
 def go_plan():
     return (yield from bps.abs_set(epu1.gap, stop, wait=False))
Esempio n. 46
0
def _run_E_ramp(dets, start, stop, velocity, deadband, *, md=None):
    if md is None:
        md = {}

    md = ChainMap(md, {'plan_args': {'dets': list(map(repr, dets)),
                                     'start': start,
                                     'stop': stop,
                                     'velocity': velocity,
                                     'deadband': deadband},
                       'plan_name': 'E_ramp',
                       'motors': [pgm.energy.name]})
    # put the energy at the starting value
    yield from bps.abs_set(pgm.energy, start, wait=True)

    yield from bps.abs_set(pgm.fly.start_sig, start, wait=True)
    yield from bps.abs_set(pgm.fly.stop_sig, stop, wait=True)
    yield from bps.abs_set(pgm.fly.velocity, velocity, wait=True)

    # TODO do this with stage
    old_db = epu1.flt.output_deadband.get()
    yield from bps.abs_set(epu1.flt.output_deadband, deadband)

    # get the old vlaue
    v = (yield from bps.read(epu1.flt.input_pv))
    if v is None:
        old_link = ''
    else:
        n = epu1.flt.input_pv.name
        old_link = v[n]['value']

    # define a clean up plan
    def clean_up():
        # move the energy setpoint to where the energy really is
        yield from bps.abs_set(pgm.energy, pgm.energy.position, wait=True)
        # set the interpolator to look at what it was looking at before
        # the scan.  This should be the energy set point.
        yield from bps.abs_set(epu1.flt.input_pv, old_link, wait=True)
        yield from bps.abs_set(epu1.flt.output_deadband, old_db, wait=True)

    # change to track the readout energy
    yield from change_epu_flt_link(pgm_energy.readback.pvname)

    def go_plan():
        ret = (yield from bps.abs_set(pgm.fly.fly_start, 1))

        st = StatusBase()
        enum_map = pgm.fly.scan_status.describe()[pgm.fly.scan_status.name]['enum_strs']
        def _done_cb(value, old_value, **kwargs):
            old_value = enum_map[int(old_value)]
            value = enum_map[int(value)]
            if old_value != value and value == 'Ready':
                st._finished()
                pgm.fly.scan_status.clear_sub(_done_cb)

        if ret is not None:
            pgm.fly.scan_status.subscribe(_done_cb, run=False)
        else:
            st._finished()
            print('SIM MODE')

        return st

    def inner_plan():
        yield from trigger_and_read(dets)

    print(md)
    rp = ramp_plan(go_plan(), pgm.energy,
                   inner_plan, period=None, md=md)

    return (yield from bpp.finalize_wrapper(rp, clean_up()))