Example #1
0
 def insert_take_dark(msg):
     now = time.time()
     nonlocal need_dark
     qualified_dark_uid = _validate_dark(expire_time=glbl.dk_window)
     # FIXME: should we do "or" or "and"?
     if (not need_dark) and (not qualified_dark_uid):
         need_dark = True
     if need_dark \
             and (not qualified_dark_uid) \
             and msg.command == 'open_run' \
             and ('dark_frame' not in msg.kwargs):
         # We are about to start a new 'run' (e.g., a count or a scan).
         # Insert a dark frame run first.
         need_dark = False
         # Annoying detail: the detector was probably already staged.
         # Unstage it (if it wasn't staged, nothing will happen) and
         # then take_dark() and then re-stage it.
         return bp.pchain(bp.unstage(glbl.area_det), take_dark(),
                          bp.stage(glbl.area_det), bp.single_gen(msg),
                          bp.abs_set(glbl.shutter, 60, wait=True)), None
     elif msg.command == 'open_run' and 'dark_frame' not in msg.kwargs:
         return bp.pchain(bp.single_gen(msg),
                          bp.abs_set(glbl.shutter, 60, wait=True)), None
     else:
         # do nothing if (not need_dark)
         return None, None
Example #2
0
 def insert_take_dark(msg):
     now = time.time()
     nonlocal need_dark
     qualified_dark_uid = _validate_dark(expire_time=glbl.dk_window)
     # FIXME: should we do "or" or "and"?
     if (not need_dark) and (not qualified_dark_uid):
         need_dark = True
     if need_dark \
             and (not qualified_dark_uid) \
             and msg.command == 'open_run' \
             and ('dark_frame' not in msg.kwargs):
         # We are about to start a new 'run' (e.g., a count or a scan).
         # Insert a dark frame run first.
         need_dark = False
         # Annoying detail: the detector was probably already staged.
         # Unstage it (if it wasn't staged, nothing will happen) and
         # then take_dark() and then re-stage it. 
         return bp.pchain(bp.unstage(glbl.area_det),
                          take_dark(),
                          bp.stage(glbl.area_det),
                          bp.single_gen(msg),
                          bp.abs_set(glbl.shutter, 60, wait=True)), None
     elif msg.command == 'open_run' and 'dark_frame' not in msg.kwargs:
         return bp.pchain(bp.single_gen(msg),
                          bp.abs_set(glbl.shutter, 60, wait=True)), None
     else:
         # do nothing if (not need_dark)
         return None, None
Example #3
0
    def test_mutator(msg):
        nonlocal _mut_active
        if _mut_active:
            _mut_active = False

            return (pchain(echo_plan(num=2, command=cmd2), single_message_gen(msg)), bad_tail())
        return None, None
Example #4
0
def test_steps(comment=''):
    flyers = [pb9.enc1, pba2.adc6, pba2.adc7]
    plan = bp.relative_scan([hhm.theta, pb9.enc1, pba2.adc6, pba2.adc7],
                            hhm.theta, -0.1, 0.1, 5)
    plan = bp.fly_during_wrapper(plan, flyers)
    plan = bp.pchain(plan)
    yield from plan
Example #5
0
    def test_mutator(msg):
        nonlocal _mut_active
        if _mut_active:
            _mut_active = False

            return (pchain(echo_plan(num=2, command=cmd2),
                           single_message_gen(msg)), bad_tail())
        return None, None
Example #6
0
    def test_mutator(msg):
        nonlocal _mut_active
        if _mut_active:
            _mut_active = False

            return (pchain(echo_plan(num=pre_count, command=pre_cmd),
                           single_message_gen(msg)),
                    echo_plan(num=post_count, command=post_cmd))
        return None, None
Example #7
0
    def test_mutator(msg):
        nonlocal _mut_active
        if _mut_active:
            _mut_active = False

            return (pchain(echo_plan(num=pre_count, command=pre_cmd),
                            single_message_gen(msg)),
                    echo_plan(num=post_count, command=post_cmd))
        return None, None
Example #8
0
 def insert_set(msg):
     obj = msg.obj
     if obj is not None and obj not in devices_seen:
         devices_seen.add(obj)
         if hasattr(obj, 'count_time'):
             # TODO Do this with a 'read' Msg once reads can be
             # marked as belonging to a different event stream (or no
             # event stream.
             original_times[obj] = obj.count_time.get()
             # TODO do this with configure
             return pchain(mv(obj.count_time, time), single_gen(msg)), None
     return None, None
Example #9
0
def test_get_events_filtering_field(db, RE):
    RE.subscribe('all', db.mds.insert)
    uid, = RE(count([det], num=7))
    h = db[uid]
    assert len(list(db.get_events(h, fields=['det']))) == 7

    with pytest.raises(ValueError):
        list(db.get_events(h, fields=['not_a_field']))

    uids = RE(pchain(count([det1], num=7), count([det2], num=3)))
    headers = db[uids]

    assert len(list(db.get_events(headers, fields=['det1']))) == 7
    assert len(list(db.get_events(headers, fields=['det2']))) == 3
Example #10
0
def test_flyers():
    # one flyer
    D = DiagnosticPreprocessor(flyers=[flyer1])
    original = list(count([det]))
    processed = list(D(count([det])))
    # should add kickoff, wait, complete, wait, collect
    assert len(processed) == 5 + len(original)

    # two flyers
    D.flyers.append(flyer2)
    processed = list(D(count([det])))
    # should add 2 * (kickoff, complete, collect) + 2 * (wait)
    assert len(processed) == 8 + len(original)

    # two flyers applied to a plan with two consecutive runs
    original = list(list(count([det])) + list(count([det])))
    processed = list(D(pchain(count([det]), count([det]))))
    assert len(processed) == 16 + len(original)
Example #11
0
def test_baseline():
    # one baseline detector
    D = DiagnosticPreprocessor(baseline=[det2])
    original = list(count([det]))
    processed = list(D(count([det])))
    # should add 2X (trigger, wait, create, read, save)
    assert len(processed) == 10 + len(original)

    # two baseline detectors
    D.baseline.append(det3)
    processed = list(D(count([det])))
    # should add 2X (trigger, triger, wait, create, read, read, save)
    assert len(processed) == 14 + len(original)

    # two baseline detectors applied to a plan with two consecutive runs
    original = list(list(count([det])) + list(count([det])))
    processed = list(D(pchain(count([det]), count([det]))))
    assert len(processed) == 28 + len(original)
Example #12
0
def test_monitors():
    # no-op
    D = DiagnosticPreprocessor()
    original = list(count([det]))
    processed = list(D(count([det])))
    assert len(processed) == len(original)

    # one monitor
    D.monitors.append(det2)
    original = list(count([det]))
    processed = list(D(count([det])))
    assert len(processed) == 2 + len(original)

    # two monitors
    D.monitors.append(det3)
    processed = list(D(count([det])))
    assert len(processed) == 4 + len(original)

    # two monitors applied a plan with consecutive runs
    original = list(list(count([det])) + list(count([det])))
    processed = list(D(pchain(count([det]), count([det]))))
    assert len(processed) == 8 + len(original)
Example #13
0
def tune(detectors, motor, start, stop, num, comment='', **metadata):
    """
    Example
    -------
    >>> RE(tune([pba2.adc7],-2, 2, 5, ''), LivePlot('pba2_adc7_volt', 'hhm_pitch'))
    """

    flyers = detectors  #[pba2.adc6, pba2.adc7]
    # Start with a step scan.
    plan = bp.relative_scan(flyers,
                            motor,
                            start,
                            stop,
                            num,
                            md={'comment': comment})
    plan = bp.fly_during_wrapper(plan, flyers)

    #for flyer in flyers:
    #    yield from bp.stage(flyer)

    plan = bp.pchain(plan)
    yield from plan
Example #14
0
def hhm_theta_scan(start,
                   stop,
                   num,
                   flyers=[pb9.enc1, pba2.adc6, pba2.adc7],
                   comment='',
                   **metadata):
    """
    Example
    -------
    >>> RE(hhm_theta_scan(-0.1, 0.1, 2, [pb4.di, xia]))
    """
    def inner():
        md = {'plan_args': {}, 'plan_name': 'step scan', 'comment': comment}
        md.update(**metadata)
        yield from bp.open_run(md=md)

    # Start with a step scan.
    plan = bp.relative_scan([hhm_en.energy],
                            hhm_en.energy,
                            start,
                            stop,
                            num,
                            md={'comment': comment})
    # Wrap it in a fly scan with the Pizza Box.
    plan = bp.fly_during_wrapper(plan, flyers)
    # Working around a bug in fly_during_wrapper, stage and unstage the pizza box manually.

    for flyer in flyers:
        yield from bp.stage(flyer)
    yield from bp.stage(hhm)

    plan = bp.pchain(plan)
    #plan = bp.pchain(bp.stage(pb9.enc1), bp.stage(pba2.adc6), bp.stage(pba2.adc7),
    #                 plan,
    #                 bp.unstage(pb9.enc1), bp.unstage(pba2.adc6), bp.unstage(pba2.adc7))
    yield from plan
def fast_shutter_wrapper(plan):
    if gs.USE_FAST_SHUTTER:
        plan = bsp.pchain(bsp.abs_set(fast_shutter.output, FastShutter.OPEN_SHUTTER, settle_time=FastShutter.SETTLE_TIME), plan)
        plan = bsp.finalize_wrapper(plan, bsp.abs_set(fast_shutter.output, FastShutter.CLOSE_SHUTTER, settle_time=FastShutter.SETTLE_TIME))
    return (yield from plan)
Example #16
0
def test_get_events_multiple_headers(db, RE):
    RE.subscribe('all', db.mds.insert)
    headers = db[RE(pchain(count([det]), count([det])))]
    assert len(list(db.get_events(headers))) == 2
Example #17
0
def test_uid_list_multiple_headers(db, RE):
    RE.subscribe('all', db.mds.insert)
    uids = RE(pchain(count([det]), count([det])))
    headers = db[uids]
    assert uids == [h['start']['uid'] for h in headers]
Example #18
0
    def __call__(self, sample, plan, subs=None, *,
                 verify_write=False, dark_strategy=periodic_dark,
                 raise_if_interrupted=False, **metadata_kw):
        # The CustomizedRunEngine knows about a Beamtime object, and it
        # interprets integers for 'sample' as indexes into the Beamtime's
        # lists of Samples from all its Experiments.

        # deprecated from v0.5 release
        #if getattr(glbl, 'collection', None) is None:
        #    raise RuntimeError("No collection has been linked to current "
        #                       "experiment yet.\nPlease do\n"
        #                       ">>> open_collection(<collection_name>)\n"
        #                       "before you run any prun")

        if isinstance(sample, int):
            try:
                sample = self.beamtime.samples[sample]
            except IndexError:
                print("WARNING: hmm, there is no sample with index `{}`"
                      ", please do `bt.list()` to check if it exists yet"
                      .format(sample))
                return
        # If a plan is given as a string, look in up in the global registry.
        if isinstance(plan, int):
            try:
                plan = self.beamtime.scanplans[plan]
            except IndexError:
                print("WARNING: hmm, there is no scanplan with index `{}`"
                      ", please do `bt.list()` to check if it exists yet"
                      .format(plan))
                return
        # If the plan is an xpdAcq 'ScanPlan', make the actual plan.
        if isinstance(plan, ScanPlan):
            plan = plan.factory()
        _subs = normalize_subs_input(subs)
        if verify_write:
            _subs.update({'stop': verify_files_saved})
        # No keys in metadata_kw are allows to collide with sample keys.
        if set(sample) & set(metadata_kw):
            raise ValueError("These keys in metadata_kw are illegal "
                             "because they are always in sample: "
                             "{}".format(set(sample) & set(metadata_kw)))
        if self._beamtime.get('bt_wavelength') is None:
            print("WARNING: there is no wavelength information in current"
                  "beamtime object, scan will keep going....")
        metadata_kw.update(sample)
        sh = glbl.shutter
        # force to open shutter before scan and close it after
        if glbl.shutter_control:
            plan = bp.pchain(bp.abs_set(sh, 1), plan, bp.abs_set(sh, 0))
        # Alter the plan to incorporate dark frames.
        if glbl.auto_dark:
            plan = dark_strategy(plan)
            plan = bp.msg_mutator(plan, _inject_qualified_dark_frame_uid)
        # Load calibration file
        if glbl.auto_load_calib:
            plan = bp.msg_mutator(plan, _inject_calibration_md)
        # Execute
        super().__call__(plan, subs,
                         raise_if_interrupted=raise_if_interrupted,
                         **metadata_kw)

        # deprecated from v0.5 release
        # insert collection
        #_insert_collection(glbl.collection_name, glbl.collection,
        #                   self._run_start_uids)

        return self._run_start_uids