コード例 #1
0
def test_set_source_invalid():

    s = Session()
    with pytest.raises(ArgumentErr) as ae:
        s.set_source('2 * made_up.foo')

    assert str(ae.value) == "invalid model expression: name 'made_up' is not defined"
コード例 #2
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_add_user_pars_modelname_not_a_model1():

    s = Session()
    with pytest.raises(ArgumentTypeErr) as exc:
        s.add_user_pars('not a model', ['x'])

    assert str(exc.value) == "'not a model' must be a user model"
コード例 #3
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_add_user_pars_modelname_not_a_string():

    s = Session()
    with pytest.raises(ArgumentTypeErr) as exc:
        s.add_user_pars(23, ['x'])

    assert str(exc.value) == "'model name' must be a string"
コード例 #4
0
def test_set_method(name, req):
    """We can set the method"""

    s = Session()
    s.set_method(name)
    ans = s.get_method()
    assert isinstance(ans, req)
コード例 #5
0
def test_set_stat(name, req):
    """We can set the statistic"""

    s = Session()
    s.set_stat(name)
    ans = s.get_stat()
    assert isinstance(ans, req)
コード例 #6
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_paramprompt_multi_parameter(caplog):
    """Check that paramprompt works with multiple parameters"""

    s = Session()
    s._add_model_types(sherpa.models.basic)

    cpt1 = s.create_model_component('const1d', 'bob')
    cpt2 = s.create_model_component('gauss1d', 'fred')

    s.paramprompt(True)
    assert len(caplog.records) == 0

    with SherpaVerbosity('INFO'):
        with patch("sys.stdin", StringIO("\n5,1,5\n\n-5, -5, 0")):
            s.set_source(bob + fred)

    assert len(caplog.records) == 0

    assert cpt1.c0.val == pytest.approx(1)
    assert cpt1.c0.min < -3e38
    assert cpt1.c0.max > 3e38

    assert cpt2.fwhm.val == pytest.approx(5)
    assert cpt2.fwhm.min == pytest.approx(1)
    assert cpt2.fwhm.max == pytest.approx(5)

    assert cpt2.pos.val == pytest.approx(0)
    assert cpt2.pos.min < -3e38
    assert cpt2.pos.max > 3e38

    assert cpt2.ampl.val == pytest.approx(-5)
    assert cpt2.ampl.min == pytest.approx(-5)
    assert cpt2.ampl.max == pytest.approx(0)
コード例 #7
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_paramprompt_eof(caplog):
    """What happens when we end early?"""

    s = Session()
    s._add_model_types(sherpa.models.basic)

    cpt1 = s.create_model_component('const1d', 'bob')
    cpt2 = s.create_model_component('gauss1d', 'fred')

    s.paramprompt(True)
    assert len(caplog.records) == 0

    with pytest.raises(EOFError):
        with SherpaVerbosity('INFO'):
            with patch("sys.stdin", StringIO("\n5,1,5\n2\n")):
                s.set_source(bob + fred)

    assert len(caplog.records) == 0

    assert cpt1.c0.val == pytest.approx(1)
    assert cpt1.c0.min < -3e38
    assert cpt1.c0.max > 3e38

    assert cpt2.fwhm.val == pytest.approx(5)
    assert cpt2.fwhm.min == pytest.approx(1)
    assert cpt2.fwhm.max == pytest.approx(5)

    assert cpt2.pos.val == pytest.approx(2)
    assert cpt2.pos.min < -3e38
    assert cpt2.pos.max > 3e38

    assert cpt2.ampl.val == pytest.approx(1)
    assert cpt2.ampl.min < -3e38
    assert cpt2.ampl.max > 3e38
コード例 #8
0
def test_delete_model_component_not_a_component():
    """Check correct error message for non-existent model"""

    s = Session()
    with pytest.raises(IdentifierErr,
                       match="model component 'tst' does not exist"):
        s.delete_model_component('tst')
コード例 #9
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_paramprompt_set_false(flag):
    """The default setting is False."""

    s = Session()
    s._paramprompt = True
    s.paramprompt(flag)
    assert not s._paramprompt
コード例 #10
0
def test_list_methods():
    """we have some methods"""

    s = Session()
    methods = s.list_methods()
    assert type(methods) == list
    assert len(methods) > 1  # do not check exact number
    assert 'levmar' in methods
コード例 #11
0
def test_get_method_invalid():
    """Errors out with invalid argument"""

    s = Session()
    with pytest.raises(ArgumentTypeErr) as exc:
        s.get_method(opt.MonCar)

    assert str(exc.value) == "'name' must be a string"
コード例 #12
0
def test_get_stat_invalid():
    """Errors out with invalid argument"""

    s = Session()
    with pytest.raises(ArgumentTypeErr) as exc:
        s.get_stat(stats.Cash)

    assert str(exc.value) == "'name' must be a string"
コード例 #13
0
def test_set_stat_invalid():
    """Errors out with invalid argument"""

    s = Session()
    with pytest.raises(ArgumentTypeErr) as exc:
        s.set_stat(sherpa.models.basic.Const1D)

    assert str(exc.value) == "'stat' must be a statistic name or object"
コード例 #14
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_delete_model_component_not_a_component():
    """Check correct error message for non-exitant model"""

    s = Session()
    with pytest.raises(IdentifierErr) as te:
        s.delete_model_component('tst')

    assert str(te.value) == "model component 'tst' does not exist"
コード例 #15
0
def test_get_functions():
    """Limited check of get_functions"""

    s = Session()
    fns = s.get_functions()
    assert type(fns) == list
    assert len(fns) > 1
    assert all([type(f) == str for f in fns])
    assert 'load_data' in fns
コード例 #16
0
ファイル: test_data.py プロジェクト: nplee/sherpa
def test_regression_346(Session):
    session = Session()
    x = numpy.arange(-5, 5.1)
    old_y = x * x + 23.2
    y = numpy.ma.masked_array(old_y, mask=old_y < 35)
    e = numpy.ones(x.size)
    session.load_arrays("mydata", x, y, e)
    filtered_y = session.get_dep("mydata", filter=True)
    assert numpy.allclose(filtered_y, [48.2, 39.2, 39.2, 48.2])
コード例 #17
0
def test_list_iter_methods():
    """we have some iteration methods"""

    s = Session()
    methods = s.list_iter_methods()
    assert type(methods) == list
    assert len(methods) > 1  # do not check exact number
    assert 'none' in methods
    assert 'sigmarej' in methods
コード例 #18
0
def test_list_functions():
    """Limited check of list_functions"""

    s = Session()
    store = StringIO()
    s.list_functions(outfile=store)
    txt = store.getvalue()
    fns = txt.split('\n')
    assert len(fns) > 1
    assert 'calc_stat' in fns
コード例 #19
0
def test_models_all():
    """We can get a list of all models"""

    s = Session()
    s._add_model_types(sherpa.models.basic)

    models = s.list_models()
    assert type(models) == list
    assert len(models) > 1
    assert all([type(m) == str for m in models])
コード例 #20
0
ファイル: test_session.py プロジェクト: wmclaugh/sherpa
def test_paramprompt_single_parameter_check_invalid_max_out_of_bound(caplog):
    """Note this creates two warnings"""

    s = Session()
    s._add_model_types(sherpa.models.basic)

    s.paramprompt(True)
    assert len(caplog.records) == 0

    with SherpaVerbosity('INFO'):
        with patch("sys.stdin", StringIO(",,typo\n,,-200")):
            s.set_source("scale1d.bob")

    assert len(caplog.records) == 2
    lname, lvl, msg = caplog.record_tuples[0]
    assert lname == "sherpa.ui.utils"
    assert lvl == logging.INFO
    assert msg == "Please provide a float value; could not convert string to float: 'typo'"

    lname, lvl, msg = caplog.record_tuples[1]
    assert lname == "sherpa.models.parameter"
    assert lvl == logging.WARN
    assert msg == "parameter bob.c0 greater than new maximum; bob.c0 reset to -200"

    mdl = s.get_model_component('bob')
    assert mdl.c0.val == pytest.approx(-200)
    assert mdl.c0.min < -3e38
    assert mdl.c0.max == pytest.approx(-200)
コード例 #21
0
def test_models_all_xspec():
    """Check all models are returned"""

    import sherpa.astro.xspec

    s = Session()
    s._add_model_types(sherpa.models.basic)
    s._add_model_types(sherpa.astro.xspec)

    # Actually, it's not guaranteed that these models are disjoint
    # but they are at the moment.
    #
    mall = s.list_models('all')
    m1d = s.list_models('1d')
    m2d = s.list_models('2d')
    mxs = s.list_models('xspec')

    nall = len(mall)
    assert nall == len(m1d) + len(m2d) + len(mxs)

    mall = set(mall)
    assert nall == len(mall)

    mcomb = set(m1d).union(set(m2d)).union(set(mxs))
    assert nall == len(mcomb)
コード例 #22
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_paramprompt_function():
    """Does paramprompt toggle the state setting?"""

    s = Session()
    assert not s._paramprompt

    s.paramprompt(True)
    assert s._paramprompt

    s.paramprompt(False)
    assert not s._paramprompt
コード例 #23
0
def test_error_estimate_not_run(name):
    """Can not rn the error estimate if data is not set up"""

    s = Session()
    s.set_default_id('bob')
    func = getattr(s, name)

    with pytest.raises(IdentifierErr) as exc:
        func()

    assert str(exc.value) == "data set bob has not been set"
コード例 #24
0
ファイル: test_data.py プロジェクト: nplee/sherpa
def test_data_dep_masked_numpyarray_nomask_ui(data_for_load_arrays, Session):
    session, args, data = data_for_load_arrays
    session = Session()
    posy = POS_Y_ARRAY[type(data)]
    args = list(args)
    args[posy] = numpy.ma.array(args[posy])
    session.load_arrays(*args)
    new_data = session.get_data(data.name)
    # Sherpa's way of saying "mask is not set"
    assert new_data.mask is True
    assert len(new_data.get_dep(filter=True)) == len(args[posy].flatten())
コード例 #25
0
def test_data_indeperr_masked_numpyarray_ui(arrpos, data_for_load_arrays, Session):
    session, args, data = data_for_load_arrays
    session = Session()
    i = arrpos[type(data)]
    mask = numpy.random.rand(*(args[i].shape)) > 0.5
    args = list(args)
    args[1] = numpy.ma.array(args[i], mask=mask)
    with pytest.warns(UserWarning, match="for dependent variables only"):
        session.load_arrays(*args)
    new_data = session.get_data(data.name)
    assert len(new_data.get_dep(filter=True)) == len(args[i])
コード例 #26
0
ファイル: test_data.py プロジェクト: nplee/sherpa
def test_data_dep_masked_numpyarray_ui(data_for_load_arrays, Session):
    session, args, data = data_for_load_arrays
    session = Session()
    posy = POS_Y_ARRAY[type(data)]
    mask = numpy.random.rand(*(args[posy].shape)) > 0.5
    args = list(args)
    args[posy] = numpy.ma.array(args[posy], mask=mask)
    session.load_arrays(*args)
    new_data = session.get_data(data.name)
    assert new_data.mask.shape == mask.shape
    assert numpy.all(new_data.mask == ~mask)
    assert len(new_data.get_dep(filter=True)) == (~mask).sum()
コード例 #27
0
def test_list_ids():
    session = Session()
    session.load_arrays(1, TEST, TEST)
    session.load_arrays("1", TEST, TEST2)

    # order of 1 and "1" is not determined
    assert {1, "1"} == set(session.list_data_ids())
    assert_array_equal(TEST2, session.get_data('1').get_dep())
    assert_array_equal(TEST, session.get_data(1).get_dep())
コード例 #28
0
def test_list_ids():
    session = Session()
    session.load_arrays(1, [1, 2, 3], [1, 2, 3])
    session.load_arrays("1", [1, 2, 3], [4, 5, 6])

    # order of 1 and "1" is not determined
    assert {1, "1"} == set(session.list_data_ids())
    assert_array_equal([4, 5, 6], session.get_data('1').get_dep())
    assert_array_equal([1, 2, 3], session.get_data(1).get_dep())
コード例 #29
0
def test_add_user_pars_modelname_not_a_model2():
    """Use an actual model, but not a user model"""

    s = Session()
    s._add_model_types(sherpa.models.basic)
    s.create_model_component('scale1d', 'foo')
    with pytest.raises(ArgumentTypeErr) as exc:
        s.add_user_pars('foo', ['x'])

    assert str(exc.value) == "'foo' must be a user model"

    # remove the foo symbol from the global table
    s.clean()
コード例 #30
0
ファイル: test_data.py プロジェクト: nplee/sherpa
def test_load_arrays_no_errors(data_no_errors):
    from sherpa.astro.ui.utils import Session
    session = Session()
    data = data_no_errors
    data_class = data.__class__
    data_args = DATA_NO_ERRORS_ARGS
    args = data_args + (data_class, )
    session.load_arrays(*args)
    new_data = session.get_data(data.name)
    assert new_data is not data
    # DATA-NOTE: Do we need an equality operator for data classes? These tests are very partial
    # Note that when they are created with load_arrays they seem to lose the name, which becomes the ID
    numpy.testing.assert_array_equal(new_data.get_indep(), data.get_indep())
    numpy.testing.assert_array_equal(new_data.get_dep(), data.get_dep())
コード例 #31
0
def test_set_log_clean():
    """Cleaning the session resets the plot preferences."""

    # relies on the tests in test_set_log
    session = Session()
    session.set_xlog()
    session.set_ylog()

    session.clean()
    assert not session.get_data_plot_prefs()['xlog']
    assert not session.get_data_plot_prefs()['ylog']
コード例 #32
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_list_ids():
    session = Session()
    session.load_arrays(1, TEST, TEST)
    session.load_arrays("1", TEST, TEST2)

    # order of 1 and "1" is not determined
    assert {1, "1"} == set(session.list_data_ids())
    assert_array_equal(TEST2, session.get_data('1').get_dep())
    assert_array_equal(TEST, session.get_data(1).get_dep())
コード例 #33
0
ファイル: basic_session.py プロジェクト: DougBurke/sherpa
from sherpa.ui.utils import Session
import sherpa.models.basic

x = [100, 200, 300, 400]
y = [10, 12, 9, 13]

s = Session()
s._add_model_types(sherpa.models.basic)

s.load_arrays(1, x, y)

print("# list_data_ids")
print(s.list_data_ids())

print("# get_data()")
print(repr(s.get_data()))

print("# get_data()")
print(s.get_data())

print("# get_stat_name/get_method_name")
print(s.get_stat_name())
print(s.get_method_name())

s.set_stat('cash')
s.set_method('simplex')

s.set_source('const1d.mdl')

print("# mdl")
print(mdl)
コード例 #34
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_paramprompt():
    """Does paramprompt work?"""

    s = Session()
    assert s.list_model_ids() == []
    assert s.list_model_components() == []

    # Add in some models
    import sherpa.models.basic
    s._add_model_types(sherpa.models.basic)
    assert s.list_models() != []

    s.create_model_component('const1d', 'm1')
    assert s.list_model_ids() == []

    expected = ['m1']
    assert s.list_model_components() == expected

    # Now there are multiple components do not rely on any ordering
    # provided by list_model_components()
    #
    s.paramprompt(True)

    # paramprompt doesn't affect create_model_component (as shown
    # by the fact that we don't have to mock stdin)
    #
    s.create_model_component('const1d', 'm2')
    assert s.list_model_ids() == []
    expected = set(expected)
    expected.add('m2')
    assert set(s.list_model_components()) == expected

    # it does affect set_model
    #
    # pytest errors out if you try to read from stdin in a test, so
    # try to work around this here using
    # https://stackoverflow.com/questions/13238566/python-equivalent-of-input-using-sys-stdin
    # An alternative would be just to check that the error is
    # raised, and the text, but then we don't get to test the
    # behaviour of the paramprompt code.
    #
    with patch("sys.stdin", StringIO(u"2.1")):
        s.set_model('const1d.mx')

    assert s.list_model_ids() == [1]
    expected.add('mx')
    assert set(s.list_model_components()) == expected

    mx = s.get_model_component('mx')
    assert mx.c0.val == pytest.approx(2.1)

    with patch("sys.stdin", StringIO(u"2.1e-3 , 2.0e-3, 1.2e-2")):
        s.set_model('x', 'const1d.my')

    assert set(s.list_model_ids()) == set([1, 'x'])
    expected.add('my')
    assert set(s.list_model_components()) == expected

    my = s.get_model_component('my')
    assert my.c0.val == pytest.approx(2.1e-3)
    assert my.c0.min == pytest.approx(2.0e-3)
    assert my.c0.max == pytest.approx(1.2e-2)

    with patch("sys.stdin", StringIO(u"2.1e-3 ,, 1.2e-2")):
        s.set_model(2, 'const1d.mz')

    assert set(s.list_model_ids()) == set([1, 2, 'x'])
    expected.add('mz')
    assert set(s.list_model_components()) == expected

    mz = s.get_model_component('mz')
    assert mz.c0.val == pytest.approx(2.1e-3)
    assert mz.c0.min == pytest.approx(- parameter.hugeval)
    assert mz.c0.max == pytest.approx(1.2e-2)

    with patch("sys.stdin", StringIO(u"-12.1,-12.1")):
        s.set_model('const1d.f1')

    assert set(s.list_model_ids()) == set([1, 2, 'x'])
    expected.add('f1')
    assert set(s.list_model_components()) == expected

    f1 = s.get_model_component('f1')
    assert f1.c0.val == pytest.approx(-12.1)
    assert f1.c0.min == pytest.approx(-12.1)
    assert f1.c0.max == pytest.approx(parameter.hugeval)

    with patch("sys.stdin", StringIO(u" ,-12.1")):
        s.set_model('const1d.f2')

    # stop checking list_model_ids
    expected.add('f2')
    assert set(s.list_model_components()) == expected

    f2 = s.get_model_component('f2')
    assert f2.c0.val == pytest.approx(1.0)
    assert f2.c0.min == pytest.approx(-12.1)
    assert f2.c0.max == pytest.approx(parameter.hugeval)

    with patch("sys.stdin", StringIO(u" ,")):
        s.set_model('const1d.f3')

    f3 = s.get_model_component('f3')
    assert f3.c0.val == pytest.approx(1.0)
    assert f3.c0.min == pytest.approx(- parameter.hugeval)
    assert f3.c0.max == pytest.approx(parameter.hugeval)

    with patch("sys.stdin", StringIO(u" ,, ")):
        s.set_model('const1d.f4')

    f4 = s.get_model_component('f4')
    assert f4.c0.val == pytest.approx(1.0)
    assert f4.c0.min == pytest.approx(- parameter.hugeval)
    assert f4.c0.max == pytest.approx(parameter.hugeval)
コード例 #35
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_list_model_ids():
    """Does list_model_ids work?"""

    # This issue was found when developing the paramprompt test.
    s = Session()

    import sherpa.models.basic
    s._add_model_types(sherpa.models.basic)

    assert s.list_model_ids() == []

    s.set_model('ma', 'const1d.mdla')
    assert s.list_model_ids() == ['ma']

    s.set_model('mb', 'const1d.mdla')
    assert set(s.list_model_ids()) == set(['ma', 'mb'])

    s.set_model('const1d.mdla')
    assert set(s.list_model_ids()) == set([1, 'ma', 'mb'])
コード例 #36
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_set_log():
    session = Session()
    assert not session.get_data_plot_prefs()['xlog']
    assert not session.get_data_plot_prefs()['ylog']
    session.set_xlog()
    assert session.get_data_plot_prefs()['xlog']
    session.set_ylog()
    assert session.get_data_plot_prefs()['ylog']
    session.set_xlinear()
    assert not session.get_data_plot_prefs()['xlog']
    session.set_ylinear()
    assert not session.get_data_plot_prefs()['ylog']
コード例 #37
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_save_restore(tmpdir):
    outfile = tmpdir.join("sherpa.save")
    session = Session()
    session.load_arrays(1, TEST, TEST2)
    session.save(str(outfile), clobber=True)
    session.clean()
    assert set() == set(session.list_data_ids())

    session.restore(str(outfile))
    assert {1, } == set(session.list_data_ids())
    assert_array_equal(TEST, session.get_data(1).get_indep()[0])
    assert_array_equal(TEST2, session.get_data(1).get_dep())
コード例 #38
0
ファイル: test_session.py プロジェクト: DougBurke/sherpa
def test_default_models():
    """There are no models available by default"""

    s = Session()
    assert s.list_models() == []
コード例 #39
0
def test_309(make_data_path):

    idval = 'bug309'

    # have values near unity for the data
    ynorm = 1e9

    session = Session()

    dname = make_data_path('load_template_with_interpolation-bb_data.dat')

    session.load_data(idval, dname)
    session.get_data(idval).y *= ynorm

    indexname = 'bb_index.dat'
    datadir = make_data_path('')

    # Need to load the data from the same directory as the index
    basedir = os.getcwd()
    os.chdir(datadir)
    try:
        session.load_template_model('bbtemp', indexname)
    finally:
        os.chdir(basedir)

    bbtemp = session.get_model_component('bbtemp')
    session.set_source(idval, bbtemp * ynorm)

    session.set_method('gridsearch')
    session.set_method_opt('sequence', None)
    session.fit(idval)