Beispiel #1
0
def test_random_state_gauss1d():
    """With given random state, the output value should stay the same.
    Test performs on 1D gaussian.
    """
    dlist = []
    motor = SynAxis(name='motor')
    for i in range(2):
        s = np.random.RandomState(0)
        noisy_det = SynGauss('noisy_det', motor, 'motor', center=0, Imax=1,
                             noise='uniform', sigma=1, noise_multiplier=0.1,
                             random_state=s)
        noisy_det.trigger()
        d = noisy_det.read()['noisy_det']['value']
        dlist.append(d)
    assert dlist[0] == dlist[1]

    # Without random state, output will be different.
    dlist.clear()
    for i in range(2):
        noisy_det = SynGauss('noisy_det', motor, 'motor', center=0, Imax=1,
                             noise='uniform', sigma=1, noise_multiplier=0.1)
        noisy_det.trigger()
        d = noisy_det.read()['noisy_det']['value']
        dlist.append(d)
    assert dlist[0] != dlist[1]
def _make_unrewindable_suspender_marker():
    from ophyd.sim import SynGauss, SynAxis

    class UnReplayableSynGauss(SynGauss):
        def pause(self):
            raise NoReplayAllowed()

    motor = SynAxis(name='motor')

    def test_plan(motor, det):
        yield Msg('set', motor, 0)
        yield Msg('trigger', det)
        yield Msg('sleep', None, 1)
        yield Msg('set', motor, 0)
        yield Msg('trigger', det)

    inps = []
    inps.append(
        (test_plan, motor,
         UnReplayableSynGauss('det', motor, 'motor', center=0, Imax=1), [
             'set', 'trigger', 'sleep', 'rewindable', 'wait_for', 'rewindable',
             'set', 'trigger'
         ]))

    inps.append(
        (test_plan, motor, SynGauss('det', motor, 'motor', center=0, Imax=1), [
            'set', 'trigger', 'sleep', 'rewindable', 'wait_for', 'rewindable',
            'set', 'trigger', 'sleep', 'set', 'trigger'
        ]))

    return pytest.mark.parametrize('plan,motor,det,msg_seq', inps)
def test_timeout(RE):
    from ophyd.positioner import SoftPositioner
    from ophyd.sim import SynGauss
    from ophyd import StatusBase

    mot = SoftPositioner(name='mot')
    mot.set(0)
    det = SynGauss('det', mot, 'mot', 0, 3)

    def kickoff():
        # This process should take a total of 5 seconds, but it will be
        # interrupted after 0.1 seconds via the timeout keyword passed to
        # ramp_plan below.
        yield Msg('null')
        for j in range(100):
            RE.loop.call_later(.05 * j, lambda j=j: mot.set(j))

        return StatusBase()

    def inner_plan():
        yield from trigger_and_read([det])

    g = ramp_plan(kickoff(), mot, inner_plan, period=.01, timeout=.1)

    start = time.time()
    with pytest.raises(RampFail):
        RE(g)
    stop = time.time()
    elapsed = stop - start

    # This test has a tendency to randomly fail, so we're giving it plenty of
    # time to run. 4, though much greater than 0.1, is still less than 5.
    assert .1 < elapsed < 4
Beispiel #4
0
def _make_single(ignore):
    if ignore:
        pytest.skip()
    motor = SynAxis(name="motor", labels={"motors"})
    det = SynGauss("det",
                   motor,
                   "motor",
                   center=0,
                   Imax=1,
                   sigma=1,
                   labels={"detectors"})
    return [det]
Beispiel #5
0
def make_db(self):
        mydb = mysql.connector.connect(
        host="localhost",
        user="******",
        passwd="ep513140",
        database="motordb",
        )
        cursor = mydb.cursor(buffered=True)
        cursor.execute("USE motordb")
        motor = StatusAxis(name = 'testMotor')
        motor.prefix = 'prefix'
        det = SynGauss('det', motor, 'testMotor', center=0, Imax=1, sigma=1)
        det.kind = 'hinted'
        wh = waitingHook()
        mydb.commit()
        RE = RunEngine()
        RE.waiting_hook = wh
        RE(scan([], motor, 1, 3, 3))
        time.sleep(2)
        mydb.commit()
        return mydb
Beispiel #6
0
def get_1d_det():
    """Create a new 1d detector

    Returns
    -------
    SynGauss object
    """
    motor = get_motor()
    detname = 'det1d_' + unique_name()
    det = SynGauss(detname, motor, motor.name, center=random.random() - 0.5,
                   Imax=random.random() * 10, sigma=random.random() * 5)
    all_objects.add(det)
    return det
Beispiel #7
0
def class_db(request):
        print("here")
        mydb = mysql.connector.connect(
        host=os.environ['MYSQL_HOST'],
        user=os.environ['MYSQL_USER'],
        passwd=os.environ['MYSQL_PASSWORD'],
        database=os.environ['MYSQL_DB'],
        )
        cursor = mydb.cursor(buffered=True)
        
        motor = StatusAxis(name = 'testMotor')
        motor.prefix = 'prefix'
        det = SynGauss('det', motor, 'testMotor', center=0, Imax=1, sigma=1)
        det.kind = 'hinted'
        wh = waitingHook()
        mydb.commit()
        RE = RunEngine()
        RE.waiting_hook = wh
        RE(scan([], motor, 1, 3, 3))
        time.sleep(2)
        mydb.commit()
        request.cls.db =  mydb
Beispiel #8
0
def test_glue(db, RE):
    from databroker.glue import read_header
    from glue.qglue import parse_data
    import bluesky.plans as bp
    from ophyd.sim import SynAxis, SynGauss
    motor = SynAxis(name='motor')
    det = SynGauss('det',
                   motor,
                   'motor',
                   center=0,
                   Imax=1,
                   noise='uniform',
                   sigma=1,
                   noise_multiplier=0.1)
    RE.subscribe(db.insert)
    RE(bp.scan([det], motor, -5, 5, 10))

    d = read_header(db[-1])
    g = parse_data(d[0], 'test')[0].to_dataframe()
def test_ramp(RE):
    from ophyd.positioner import SoftPositioner
    from ophyd import StatusBase
    from ophyd.sim import SynGauss

    tt = SoftPositioner(name='mot')
    tt.set(0)
    dd = SynGauss('det', tt, 'mot', 0, 3)

    st = StatusBase()

    def kickoff():
        yield Msg('null')
        for j, v in enumerate(np.linspace(-5, 5, 10)):
            RE.loop.call_later(.1 * j, lambda v=v: tt.set(v))
        RE.loop.call_later(1.2, st._finished)
        return st

    def inner_plan():
        yield from trigger_and_read([dd])

    g = ramp_plan(kickoff(), tt, inner_plan, period=0.08)
    db = DocCollector()
    RE.subscribe(db.insert)
    rs = RE(g)
    if RE.call_returns_result:
        uid = rs.run_start_uids[0]
    else:
        uid = rs[0]
    assert db.start[0]['uid'] == uid
    assert len(db.descriptor[uid]) == 2
    descs = {d['name']: d for d in db.descriptor[uid]}

    assert set(descs) == set(['primary', 'mot_monitor'])

    primary_events = db.event[descs['primary']['uid']]
    assert len(primary_events) > 11

    monitor_events = db.event[descs['mot_monitor']['uid']]
    # the 10 from the updates, 1 from 'run at subscription time'
    assert len(monitor_events) == 11
Beispiel #10
0
def test_peak_statistics_compare_chx(RE):
    """This test focuses on gaussian function with noise.
    """
    s = np.random.RandomState(1)
    noisy_det_fix = SynGauss('noisy_det_fix',
                             motor,
                             'motor',
                             center=0,
                             Imax=1,
                             noise='uniform',
                             sigma=1,
                             noise_multiplier=0.1,
                             random_state=s)
    x = 'motor'
    y = 'noisy_det_fix'
    ps = PeakStats(x, y)
    RE.subscribe(ps)

    RE(scan([noisy_det_fix], motor, -5, 5, 100))
    ps_chx = get_ps(ps.x_data, ps.y_data)

    assert np.allclose(ps.cen, ps_chx['cen'], atol=1e-6)
    assert np.allclose(ps.com, ps_chx['com'], atol=1e-6)
    assert np.allclose(ps.fwhm, ps_chx['fwhm'], atol=1e-6)
Beispiel #11
0
def inverted_gauss():
    motor = SynAxis(name='motor')
    # Make our inverted detector
    sig = SynGauss('det', motor, 'motor', center=0, Imax=-1, sigma=1)
    return (sig, motor)
Beispiel #12
0
def alignRSXS(iterations = 3, alignCriteria = None, theta_kws = None, 
			  x_kws = None, SimAlign = False, verbose = False):     
	"""
	alignRSXS:
		-sets up detector and motor objects
		-sets up summary plots
		-calls up multiScan
		
	Parameters
    ----------
    iterations 		: integer number of iterations to perform [unless alignment
					  criteria is not None and met]. Default value is 3,
	alignCriteria	: dict of criteria for ending alignment
					  Default value is None,
	theta_kws 		: dict for arguments to be passed to theta-alignment -- most
					  important is det4offset 
					  Default value is None,
	x_kws 			: dict for arguments to be passed to x-alignment
					  Default value is None
	SimAlign		: boolean for simulated run (not implemented for full loop
					  only for individual x, theta loops via the keyword args)
	verbose 		: boolean for showing alignment process using LiveTable
					  callbacks. Default value is False
    
	"""
	
	asd.sequence = []
	asd.x0 = []
	asd.theta5 = []

	if alignCriteria is None:
		alignCriteria = {}  #TODO meant as way of introducing variable number of 
							#steps for alignment process, where the number of 
							#iterations would based off of the change between 
							#iterations
	if x_kws is None:
		x_kws = {}
	if theta_kws is None:
		theta_kws = {}

	detX_name = 'ca4det_ca_value'
	detTh_name = detX_name 
	mX_name = 'motorX'
	mTh_name = 'motorTh'
	mTTh_name = 'motorTTh'

	#setup ophyd objects
	if not SimAlign:
		motorX = EpicsMotor('29idd:m1', name = mX_name)
		motorTh = EpicsMotor('29idd:m7', name = mTh_name)
		motorTTh = EpicsMotor('29idHydra:m1', name = mTTh_name)
		
		detX = CurAmp('29idd:ca4:', name = 'ca4det', read_attrs = ['ca_value'])
		detTh = detX		
	else:
		motorX = SynAxis(name = mX_name)
		motorTh = SynAxis(name = mTh_name)
		motorTTh = SynAxis(name = mTTh_name)

		try:
			thAlignRange = theta_kws['alignRange'] 
		except:
			thAlignRange = def_thAlignRange 

		simCenter = (thAlignRange[1]-thAlignRange[0])*np.random.random() + \
					thAlignRange[0]
		try:
			xAlignRange = x_kws['alignRange'] 
		except:
			xAlignRange = def_xAlignRange 

		simX0 = (xAlignRange[1]-xAlignRange[0])/3*(1+np.random.random()) + \
					xAlignRange[0]

		detX = SynErfGauss(detX_name, motorX, mX_name, 
						  Imax=0.024, wid=0.20, x0 = simX0,
						  noise='uniform', noise_multiplier=0.0005)
						  
		detTh = SynGauss(detTh_name, motorTh, mTh_name, 
						   center=simCenter, Imax=1, sigma=.03, 
						   noise='uniform', noise_multiplier=0.05)
		
	#setup plots

	fig1, ax = plt.subplots() 	# x-alignment plot
	fig2, bx = plt.subplots() 	# theta-alignment plot
	fig3, cx1 = plt.subplots() 	# summary plot
	fig3.suptitle('Alignment summary')
	cx2 = cx1.twinx()

	#start run engine

	RE = RunEngine({})
	RE(multiScan(detX, detX_name, detTh, detTh_name, 
				 motorX, mX_name, motorTh, mTh_name, motorTTh, mTTh_name,
				 iterations = iterations, alignCriteria = alignCriteria, 
				 theta_kws = theta_kws, x_kws = x_kws, 
				 sumPlot = fig3, sumAxes = [cx1, cx2], xPlot = ax, thPlot = bx,
				 SimAlign = SimAlign, verbose = verbose))
Beispiel #13
0
"""
lesson 5 : get motor and scaler from ophyd simulators
"""

__all__ = [
    'motor',
    'noisy',
]

from ...session_logs import logger
logger.info(__file__)

import numpy as np
from ophyd.sim import motor, SynGauss

noisy = SynGauss(
    'noisy',
    motor,
    'motor',
    # center somewhere between -1 and 1
    center=2 * (np.random.random() - 0.5),
    # randomize these parameters
    Imax=100000 + 20000 * (np.random.random() - 0.5),
    noise='poisson',
    sigma=0.016 + 0.015 * (np.random.random() - 0.5),
    noise_multiplier=0.1 + 0.02 * (np.random.random() - 0.5),
    labels={'detectors'})

motor.precision = 5
noisy.precision = 0
Beispiel #14
0
    pass


class TunableEpicsMotor(EpicsMotor, AxisTunerMixin):
    pass


def myaxis_pretune_hook():
    # set the counting time for *this* tune
    mydet.exposure_time = 0.02  # can't yield this one


myaxis = TunableSynAxis(name="myaxis")
mydet = SynGauss('mydet',
                 myaxis,
                 'myaxis',
                 center=0.21,
                 Imax=0.98e5,
                 sigma=0.127)
myaxis.tuner = TuneAxis([mydet], myaxis)
myaxis.tuner.width = 2
myaxis.tuner.num = 81

m1 = TunableEpicsMotor('prj:m1', name='m1')
spvoigt = SynPseudoVoigt('spvoigt',
                         m1,
                         'm1',
                         center=-1.5 + 0.5 * np.random.uniform(),
                         eta=0.2 + 0.5 * np.random.uniform(),
                         sigma=0.001 + 0.05 * np.random.uniform(),
                         scale=0.95e5,
                         bkg=0.01 * np.random.uniform())
Beispiel #15
0
# take_pre_data=True, timeout=None, period=None, md=None)
from databroker import Broker
from bluesky.plans import ramp_plan
from bluesky.plan_stubs import trigger_and_read
from bluesky import Msg
from bluesky.utils import RampFail
import numpy as np
import time

from ophyd.positioner import SoftPositioner
from ophyd import StatusBase
from ophyd.sim import SynGauss

tt = SoftPositioner(name='mot')
tt.set(0)
dd = SynGauss('det', tt, 'mot', 0, 3)

st = StatusBase()


def kickoff():
    yield Msg('null')
    for j, v in enumerate(np.linspace(-2, 2, 10)):
        RE.loop.call_later(.1 * j, lambda v=v: tt.set(v))
    RE.loop.call_later(1.2, st._finished)
    return st


def inner_plan():
    print(tt.position)
    yield from trigger_and_read([dd])
Beispiel #16
0
from bluesky import RunEngine
from bluesky.plans import scan
from bluesky.callbacks.best_effort import BestEffortCallback
from ophyd.sim import SynGauss

from status import StatusAxis

# Create simulated devices
motor = StatusAxis(name='motor')
det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1)
det.kind = 'hinted'
motor.prefix = 'fake:Prefix'
# Create our RunEngine
RE = RunEngine()
RE.subscribe(BestEffortCallback())
Beispiel #17
0
import bluesky.utils as bu
from ophyd.sim import motor, SynGauss
from bluesky import RunEngine

# Do this if running the example interactively;
# skip it when building the documentation.
import os
if 'BUILDING_DOCS' not in os.environ:
    from bluesky.utils import install_qt_kicker  # for notebooks, qt -> nb
    install_qt_kicker()
    plt.ion()

noisy_det = SynGauss('noisy_det',
                     motor,
                     'motor',
                     center=0,
                     Imax=100,
                     noise='poisson',
                     sigma=1)

RE = RunEngine({})


def errorbar(lmfit_result, param_name):
    # width of 95% conf interfal:
    ci = lmfit_result.conf_interval()
    return ci[param_name][-2][1] - ci[param_name][1][1]


def gaussian(x, A, sigma, x0):
    return A * np.exp(-(x - x0)**2 / (2 * sigma**2))