Example #1
0
def test_set_log_does_not_change_other_sessions():
    """The plot preferences in different sessions are distinct.
    """

    session1 = Session()
    session2 = Session()
    session1.set_xlog()
    session2.set_ylog()

    assert session1.get_data_plot_prefs()['xlog']
    assert not session1.get_data_plot_prefs()['ylog']
    assert not session2.get_data_plot_prefs()['xlog']
    assert session2.get_data_plot_prefs()['ylog']
Example #2
0
def test_paramprompt_single_parameter_check_invalid_max(caplog):

    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("-2,,typo\n-200,,-2")):
            s.set_source("scale1d.bob")

    assert len(caplog.records) == 1
    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'"

    mdl = s.get_model_component('bob')
    assert mdl.c0.val == pytest.approx(-200)
    assert mdl.c0.min < -3e38
    assert mdl.c0.max == pytest.approx(-2)

    # remove the bob symbol from the global table
    s.clean()
Example #3
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"
Example #4
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')
Example #5
0
def test_paramprompt_single_parameter_check_too_many_commas(caplog):
    """Check we tell users there was a problem"""

    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(",,,,\n12")):
            s.set_source("scale1d.bob")

    assert len(caplog.records) == 1
    lname, lvl, msg = caplog.record_tuples[0]
    assert lname == "sherpa.ui.utils"
    assert lvl == logging.INFO
    assert msg == "Error: Please provide a comma-separated list of floats; e.g. val,min,max"

    mdl = s.get_model_component('bob')
    assert mdl.c0.val == pytest.approx(12)
    assert mdl.c0.min < -3e38
    assert mdl.c0.max > 3e38

    # remove the bob symbol from the global table
    s.clean()
Example #6
0
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)
def test_get_default_id():
    """Does the default id react correctly?"""
    s = Session()
    assert s.get_default_id() == 1

    s.set_default_id('alpha')
    assert s.get_default_id() == 'alpha'
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)
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)
Example #10
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)
Example #11
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)
Example #12
0
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
Example #13
0
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"
Example #14
0
def test_get_error_estimator(name, req):
    """Can we get the error estimator?"""

    s = Session()
    func = getattr(s, 'get_{}'.format(name))
    ans = func()
    assert isinstance(ans, req)
Example #15
0
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"
Example #16
0
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)
Example #17
0
def test_paramprompt_set_false(flag):
    """The default setting is False."""

    s = Session()
    s._paramprompt = True
    s.paramprompt(flag)
    assert not s._paramprompt
Example #18
0
def test_issue_16():
    """Check one of the examples from #16"""

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

    s.dataspace1d(0.01, 11, 0.01, id=1)
    s.dataspace1d(2, 5, 0.1, id="tst")
    s.set_source(1, 'powlaw1d.pl1')
    s.set_source('tst', 'powlaw1d.pltst')

    assert s.list_data_ids() == [1, 'tst']
    assert s.list_model_ids() == [1, 'tst']
    assert s.list_model_components() == ['pl1', 'pltst']

    s.delete_model(id='tst')
    s.delete_model_component("pltst")
    s.delete_data(id='tst')

    assert s.list_data_ids() == [1]
    assert s.list_model_ids() == [1]
    assert s.list_model_components() == ['pl1']

    s.delete_model(id=1)
    s.delete_model_component("pl1")
    s.delete_data(id=1)

    assert s.list_data_ids() == []
    assert s.list_model_ids() == []
    assert s.list_model_components() == []
Example #19
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"
Example #20
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
Example #21
0
def data_for_load_arrays(request):
    data_class = request.param
    from sherpa.astro.ui.utils import Session
    session = Session()
    data_args = INSTANCE_ARGS[data_class]
    args = data_args + (data_class, )
    data = data_class(*data_args)
    return session, args, data
Example #22
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"
Example #23
0
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"
Example #24
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"
Example #25
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
Example #26
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
Example #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())
Example #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())
Example #29
0
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])
Example #30
0
def test_error_estimate_not_set(name, fullname):
    """Error out if the error estimate is not set"""

    s = Session()
    func = getattr(s, 'get_{}_results'.format(name))

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

    assert str(exc.value) == "{} has not been performed".format(fullname)