def test_live_fit_plot(RE, hw): try: import lmfit except ImportError: raise pytest.skip('requires lmfit') def gaussian(x, A, sigma, x0): return A * np.exp(-(x - x0)**2 / (2 * sigma**2)) model = lmfit.Model(gaussian) init_guess = { 'A': 2, 'sigma': lmfit.Parameter('sigma', 3, min=0), 'x0': -0.2 } livefit = LiveFit(model, 'det', {'x': 'motor'}, init_guess, update_every=50) lfplot = LiveFitPlot(livefit, color='r') lplot = LivePlot('det', 'motor', ax=plt.gca(), marker='o', ls='none') RE(scan([hw.det], hw.motor, -1, 1, 50), [lplot, lfplot]) expected = {'A': 1, 'sigma': 1, 'x0': 0} for k, v in expected.items(): assert np.allclose(livefit.result.values[k], v, atol=1e-6)
def my_plan(): motor = hw.motor det = hw.det motor.delay = 1 plan = bp.scan([det], motor, -5, 5, 25) plan = subs_wrapper(bp.scan([det], motor, -5, 5, 25), LivePlot(det.name, motor.name)) return (yield from plan)
def test_live_plotter(RE, hw): RE.ignore_callback_exceptions = False try: import matplotlib.pyplot as plt del plt except ImportError as ie: pytest.skip("Skipping live plot test because matplotlib is not installed." "Error was: {}".format(ie)) my_plotter = LivePlot('det', 'motor') assert RE.state == 'idle' RE(stepscan(hw.det, hw.motor), {'all': my_plotter}) assert RE.state == 'idle' xlen = len(my_plotter.x_data) assert xlen > 0 ylen = len(my_plotter.y_data) assert xlen == ylen RE.ignore_callback_exceptions = True
import numpy as np import lmfit from bluesky.plans import scan from ophyd.sim import motor, noisy_det from bluesky.callbacks import LiveFit from bluesky.callbacks.mpl_plotting import LivePlot, LiveFitPlot from bluesky import RunEngine RE = RunEngine({}) def gaussian(x, A, sigma, x0): return A * np.exp(-(x - x0)**2 / (2 * sigma**2)) model = lmfit.Model(gaussian) init_guess = {'A': 2, 'sigma': lmfit.Parameter('sigma', 3, min=0), 'x0': -0.2} import matplotlib.pyplot as plt fig, ax = plt.subplots() lf = LiveFit(model, 'noisy_det', {'x': 'motor'}, init_guess) lfp = LiveFitPlot(lf, ax=ax, color='r') lp = LivePlot('noisy_det', 'motor', ax=ax, marker='o', linestyle='none') RE(scan([noisy_det], motor, -1, 1, 50), [lfp, lp]) plt.draw()
from bluesky import RunEngine from bluesky.plans import scan from ophyd.sim import det, motor from bluesky.callbacks.mpl_plotting import LivePlot RE = RunEngine({}) RE(scan([det], motor, -5, 5, 30), LivePlot('det', 'motor', marker='x', markersize=10, color='red'))
from bluesky import RunEngine from bluesky.plans import scan from ophyd.sim import det, motor from bluesky.callbacks.mpl_plotting import LivePlot RE = RunEngine({}) RE(scan([det], motor, -5, 5, 30), LivePlot('det', 'motor'))
def rocking_curve(start=-0.10, stop=0.10, nsteps=101, choice="peak"): """Perform a relative scan of the DCM 2nd crystal pitch around the current position to find the peak of the crystal rocking curve. Begin by opening the hutch slits to 3 mm. At the end, move to the position of maximum intensity on I0, then return to the hutch slits to their original height. Input: start: (float) starting position relative to current [-0.1] end: (float) ending position relative to current [0.1] nsteps: (int) number of steps [101] choice: (string) 'peak', fit' or 'com' (center of mass) ['peak'] If choice is fit, the fit is performed using the SkewedGaussianModel from lmfit, which works pretty well for this measurement at BMM. The line shape is a bit skewed due to the convolution with the slightly misaligned entrance slits. """ # Cache the data here as it is collected so we can examine it here and use # it to make decisions. src = SingleRunCache() @subs_decorator(LivePlot("I0", pitch.name, ax=plt.gca())) @subs_decorator(src.callback) def scan_dcm_pitch(): line1 = "%s, %s, %.3f, %.3f, %d -- starting at %.3f\n" % ( pitch.name, "I0", start, stop, nsteps, pitch.readback.get(), ) uid = yield from rel_scan([I0], pitch, start, stop, nsteps) # The data that we just acquired has been cached in memory by src. # Access it as a pandas DataFrame so that we can conveniently do some # math on it. run = src.retrieve() t = run.primary.read().to_dataframe() if choice.lower() == "com": signal = numpy.array(t["I0"]) position = com(signal) top = t['pitch'].iloc[position] elif choice.lower() == "fit": signal = numpy.array(t["I0"]) pitch_ = numpy.array(t["pitch"]) mod = SkewedGaussianModel() pars = mod.guess(signal, x=pitch_) out = mod.fit(signal, pars, x=pitch_) print(out.fit_report(min_correl=0)) out.plot() top = out.params["center"].value else: signal = t['I0'] position = peak(signal) top = t[pitch.name][position] print( "rocking curve scan: %s\tuid = %s, scan_id = %d" % (line1, uid, run.metadata["start"]["scan_id"]) ) print(f"Found and moved to peak at {top:.3} via method {choice}") yield from mv(pitch, top) yield from scan_dcm_pitch()