Beispiel #1
0
def test_user_model_create_pars_names(clean_ui):

    mname = "test_model"
    ui.load_user_model(um_line, mname)

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 1

    # add user pars doesn't change the existing instance, you have
    # to "get" the new version to see the change
    #
    ui.add_user_pars(mname, ['X1', 'x'])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'X1'
    assert p0.val == pytest.approx(0.0)
    assert p0.units == ''
    assert not p0.frozen
    assert p0.min == pytest.approx(-1 * hugeval)
    assert p0.max == pytest.approx(hugeval)

    assert p1.name == 'x'
    assert p1.val == pytest.approx(0.0)
    assert p1.units == ''
    assert not p1.frozen
    assert p1.min == pytest.approx(-1 * hugeval)
    assert p1.max == pytest.approx(hugeval)
Beispiel #2
0
def test_user_model_create_pars_names():

    mname = "test_model"
    ui.load_user_model(um_line, mname)

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 1

    # add user pars doesn't change the existing instance, you have
    # to "get" the new version to see the change
    #
    ui.add_user_pars(mname, ['X1', 'x'])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'X1'
    assert p0.val == pytest.approx(0.0)
    assert p0.units == ''
    assert not p0.frozen
    assert p0.min == pytest.approx(-1 * hugeval)
    assert p0.max == pytest.approx(hugeval)

    assert p1.name == 'x'
    assert p1.val == pytest.approx(0.0)
    assert p1.units == ''
    assert not p1.frozen
    assert p1.min == pytest.approx(-1 * hugeval)
    assert p1.max == pytest.approx(hugeval)
Beispiel #3
0
def test_does_user_model_get_cleaned(clean_ui):
    """Do user models get removed from the session by clean?"""

    mname = "test_model"
    with pytest.raises(IdentifierErr):
        ui.get_model_component(mname)

    ui.load_user_model(um_line, mname)
    mdl = ui.get_model_component(mname)
    assert mdl.name == "usermodel.{}".format(mname)
    assert isinstance(mdl, sherpa.models.basic.UserModel)

    ui.clean()

    with pytest.raises(IdentifierErr):
        ui.get_model_component(mname)
Beispiel #4
0
def test_user_model_create_pars_full(clean_ui):

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ['pAr1', '_p'], [23.2, 3.1e2],
                     parunits=['', 'cm^2 s'],
                     parfrozen=[True, False],
                     parmins=[0, -100],
                     parmaxs=[100, 1e5])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'pAr1'
    assert p0.val == pytest.approx(23.2)
    assert p0.units == ''
    assert p0.frozen
    assert p0.min == pytest.approx(0)
    assert p0.max == pytest.approx(100)

    assert p1.name == '_p'
    assert p1.val == pytest.approx(3.1e2)
    assert p1.units == 'cm^2 s'
    assert not p1.frozen
    assert p1.min == pytest.approx(-100)
    assert p1.max == pytest.approx(1e5)
Beispiel #5
0
def test_user_model_create_pars_full():

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ['pAr1', '_p'], [23.2, 3.1e2],
                     parunits=['', 'cm^2 s'],
                     parfrozen=[True, False],
                     parmins=[0, -100],
                     parmaxs=[100, 1e5])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'pAr1'
    assert p0.val == pytest.approx(23.2)
    assert p0.units == ''
    assert p0.frozen
    assert p0.min == pytest.approx(0)
    assert p0.max == pytest.approx(100)

    assert p1.name == '_p'
    assert p1.val == pytest.approx(3.1e2)
    assert p1.units == 'cm^2 s'
    assert not p1.frozen
    assert p1.min == pytest.approx(-100)
    assert p1.max == pytest.approx(1e5)
Beispiel #6
0
def example_model():
    """Create an example model."""

    ui.create_model_component('const1d', 'cpt')
    cpt = ui.get_model_component('cpt')
    cpt.c0 = 35
    return cpt
Beispiel #7
0
def test_does_user_model_get_cleaned():
    """Do user models get removed from the session by clean?"""

    mname = "test_model"
    with pytest.raises(IdentifierErr):
        ui.get_model_component(mname)

    ui.load_user_model(um_line, mname)
    mdl = ui.get_model_component(mname)
    assert mdl.name == "usermodel.{}".format(mname)
    assert isinstance(mdl, sherpa.models.basic.UserModel)

    ui.clean()

    with pytest.raises(IdentifierErr):
        ui.get_model_component(mname)
Beispiel #8
0
def test_user_model1d_eval_fail():
    """This is expected to fail as the number of pars does not match."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    mdl = ui.get_model_component(mname)
    with pytest.raises(IndexError):
        mdl([2.3, 5.4, 8.7])
Beispiel #9
0
def test_user_model1d_eval_fail(clean_ui):
    """This is expected to fail as the number of pars does not match."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    mdl = ui.get_model_component(mname)
    with pytest.raises(IndexError):
        mdl([2.3, 5.4, 8.7])
Beispiel #10
0
 def test_psf_model2d(self):
     ui.dataspace1d(1, 10)
     for model in self.models1d:
         try:
             ui.load_psf("psf1d", model + ".mdl")
             ui.set_psf("psf1d")
             mdl = ui.get_model_component("mdl")
             self.assert_((numpy.array(mdl.get_center()) == numpy.array([4])).all())
         except:
             print model
             raise
Beispiel #11
0
 def test_psf_model2d(self):
     ui.dataspace2d([216, 261])
     for model in self.models2d:
         try:
             ui.load_psf("psf2d", model + ".mdl")
             ui.set_psf("psf2d")
             mdl = ui.get_model_component("mdl")
             self.assert_((numpy.array(mdl.get_center()) == numpy.array([108, 130])).all())
         except:
             print model
             raise
Beispiel #12
0
 def test_psf_model2d(self):
     ui.dataspace2d([216, 261])
     for model in self.models2d:
         try:
             ui.load_psf('psf2d', model + '.mdl')
             ui.set_psf('psf2d')
             mdl = ui.get_model_component('mdl')
             self.assertTrue((numpy.array(mdl.get_center()) ==
                              numpy.array([108, 130])).all())
         except:
             print(model)
             raise
Beispiel #13
0
 def test_psf_model2d(self):
     ui.dataspace2d([216,261])
     for model in self.models2d:
         try:
             ui.load_psf('psf2d', model+'.mdl')
             ui.set_psf('psf2d')
             mdl = ui.get_model_component('mdl')
             self.assertTrue((numpy.array(mdl.get_center()) ==
                              numpy.array([108,130])).all())
         except:
             print model
             raise
Beispiel #14
0
 def test_psf_model1d(self):
     ui.dataspace1d(1, 10)
     for model in self.models1d:
         try:
             ui.load_psf('psf1d', model + '.mdl')
             ui.set_psf('psf1d')
             mdl = ui.get_model_component('mdl')
             self.assertTrue(
                 (numpy.array(mdl.get_center()) == numpy.array([4])).all())
         except:
             print(model)
             raise
Beispiel #15
0
 def test_psf_model1d(self):
     ui.dataspace1d(1, 10)
     for model in self.models1d:
         try:
             ui.load_psf('psf1d', model+'.mdl')
             ui.set_psf('psf1d')
             mdl = ui.get_model_component('mdl')
             self.assertTrue((numpy.array(mdl.get_center()) ==
                              numpy.array([4])).all())
         except:
             print model
             raise
Beispiel #16
0
def test_user_model1d_fit():
    """Check can use in a fit."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ["slope", "intercept"],
                     parvals = [1.0, 1.0])

    mdl = ui.get_model_component(mname)

    x = numpy.asarray([-2.4, 2.3, 5.4, 8.7, 12.3])

    # Set up the data to be scattered around y = -0.2 x + 2.8
    # Pick the deltas so that they sum to 0 (except for central
    # point)
    #
    slope = -0.2
    intercept = 2.8

    dy = numpy.asarray([0.1, -0.2, 0.14, -0.1, 0.2])
    ydata = x * slope + intercept + dy

    ui.load_arrays(1, x, ydata)

    ui.set_source(mname)
    ui.ignore(5.0, 6.0)  # drop the central bin

    ui.set_stat('leastsq')
    ui.set_method('simplex')
    ui.fit()

    fres = ui.get_fit_results()
    assert fres.succeeded
    assert fres.parnames == ('test_model.slope', 'test_model.intercept')
    assert fres.numpoints == 4
    assert fres.dof == 2

    # Tolerance has been adjusted to get the tests to pass on my
    # machine. It's really just to check that the values have chanegd
    # from their default values.
    #
    assert fres.parvals[0] == pytest.approx(slope, abs=0.01)
    assert fres.parvals[1] == pytest.approx(intercept, abs=0.05)

    # Thse should be the same values, so no need to use pytest.approx
    # (unless there's some internal translation between types done
    # somewhere?).
    #
    assert mdl.slope.val == fres.parvals[0]
    assert mdl.intercept.val == fres.parvals[1]
Beispiel #17
0
def test_user_model_create_pars_default(clean_ui):

    mname = "test_model"
    ui.load_user_model(um_line, mname)

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 1
    par = mdl.pars[0]
    assert par.name == "ampl"
    assert par.val == pytest.approx(1.0)
    assert not par.frozen
    assert par.units == ''
    assert par.min == pytest.approx(-1 * hugeval)
    assert par.max == pytest.approx(hugeval)
Beispiel #18
0
def test_user_model1d_fit():
    """Check can use in a fit."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ["slope", "intercept"],
                     parvals = [1.0, 1.0])

    mdl = ui.get_model_component(mname)

    x = numpy.asarray([-2.4, 2.3, 5.4, 8.7, 12.3])

    # Set up the data to be scattered around y = -0.2 x + 2.8
    # Pick the deltas so that they sum to 0 (except for central
    # point)
    #
    slope = -0.2
    intercept = 2.8

    dy = numpy.asarray([0.1, -0.2, 0.14, -0.1, 0.2])
    ydata = x * slope + intercept + dy

    ui.load_arrays(1, x, ydata)

    ui.set_source(mname)
    ui.ignore(5.0, 6.0)  # drop the central bin

    ui.set_stat('leastsq')
    ui.set_method('simplex')
    ui.fit()

    fres = ui.get_fit_results()
    assert fres.succeeded
    assert fres.parnames == ('test_model.slope', 'test_model.intercept')
    assert fres.numpoints == 4
    assert fres.dof == 2

    # Tolerance has been adjusted to get the tests to pass on my
    # machine. It's really just to check that the values have chanegd
    # from their default values.
    #
    assert fres.parvals[0] == pytest.approx(slope, abs=0.01)
    assert fres.parvals[1] == pytest.approx(intercept, abs=0.05)

    # Thse should be the same values, so no need to use pytest.approx
    # (unless there's some internal translation between types done
    # somewhere?).
    #
    assert mdl.slope.val == fres.parvals[0]
    assert mdl.intercept.val == fres.parvals[1]
Beispiel #19
0
def test_user_model_create_pars_default():

    mname = "test_model"
    ui.load_user_model(um_line, mname)

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 1
    par = mdl.pars[0]
    assert par.name == "ampl"
    assert par.val == pytest.approx(1.0)
    assert not par.frozen
    assert par.units == ''
    assert par.min == pytest.approx(-1 * hugeval)
    assert par.max == pytest.approx(hugeval)
Beispiel #20
0
def test_user_model_change_par(clean_ui):

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ['xXx', 'Y2'])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'xXx'
    assert p1.name == 'Y2'
    assert p0.val == pytest.approx(0.0)
    assert p1.val == pytest.approx(0.0)

    # Use the user-supplied names:
    #
    mdl.xXx = 2.0
    assert p0.val == pytest.approx(2.0)

    mdl.Y2 = 3.0
    assert p1.val == pytest.approx(3.0)

    # Now all lower case
    #
    mdl.xxx = 4.0
    assert p0.val == pytest.approx(4.0)

    mdl.y2 = 12.0
    assert p1.val == pytest.approx(12.0)

    # Try with the set_par function
    #
    ui.set_par('test_model.xxx', 12.2)
    assert p0.val == pytest.approx(12.2)

    ui.set_par('test_model.y2', 14.0, frozen=True)
    assert p1.val == pytest.approx(14.0)
    assert p1.frozen

    ui.clean()
Beispiel #21
0
def test_user_model_change_par():

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ['xXx', 'Y2'])

    mdl = ui.get_model_component(mname)
    assert len(mdl.pars) == 2
    p0 = mdl.pars[0]
    p1 = mdl.pars[1]

    assert p0.name == 'xXx'
    assert p1.name == 'Y2'
    assert p0.val == pytest.approx(0.0)
    assert p1.val == pytest.approx(0.0)

    # Use the user-supplied names:
    #
    mdl.xXx = 2.0
    assert p0.val == pytest.approx(2.0)

    mdl.Y2 = 3.0
    assert p1.val == pytest.approx(3.0)

    # Now all lower case
    #
    mdl.xxx = 4.0
    assert p0.val == pytest.approx(4.0)

    mdl.y2 = 12.0
    assert p1.val == pytest.approx(12.0)

    # Try with the set_par function
    #
    ui.set_par('test_model.xxx', 12.2)
    assert p0.val == pytest.approx(12.2)

    ui.set_par('test_model.y2', 14.0, frozen=True)
    assert p1.val == pytest.approx(14.0)
    assert p1.frozen

    ui.clean()
Beispiel #22
0
def test_user_model1d_eval():
    """Simple evaluation check for 1D case."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ["slope", "intercept"])

    m = 2.1
    c = -4.8

    mdl = ui.get_model_component(mname)
    mdl.slope = m
    mdl.intercept = c

    x = numpy.asarray([2.3, 5.4, 8.7])
    y = mdl(x)

    yexp = x * m + c

    # This check require pytest >= 3.2.0
    #
    assert y == pytest.approx(yexp)
Beispiel #23
0
def test_user_model1d_eval(clean_ui):
    """Simple evaluation check for 1D case."""

    mname = "test_model"
    ui.load_user_model(um_line, mname)
    ui.add_user_pars(mname, ["slope", "intercept"])

    m = 2.1
    c = -4.8

    mdl = ui.get_model_component(mname)
    mdl.slope = m
    mdl.intercept = c

    x = np.asarray([2.3, 5.4, 8.7])
    y = mdl(x)

    yexp = x * m + c

    # This check require pytest >= 3.2.0
    #
    assert y == pytest.approx(yexp)
#axplot = {}
#ftype = 'obc_bad'
for ftype in failures:

    fail_mask = failures[ftype]
    data_id = figmap[ftype]
    ui.set_method('simplex')

    ui.load_user_model(lim_line, '%s_mod' % ftype)
    ui.add_user_pars('%s_mod' % ftype, ['m', 'b'])
    ui.set_model(data_id, '%s_mod' % ftype)

    ui.load_arrays(data_id, times, failures[ftype])

    fmod = ui.get_model_component('%s_mod' % ftype)

    fmod.b.min = 0
    fmod.b.max = 1
    fmod.m.min = 0
    fmod.m.max = 0.5
    fmod.b.val = 1e-7

    ui.load_user_stat("loglike", llh, my_err)
    ui.set_stat(loglike)
    # the tricky part here is that the "model" is the probability polynomial
    # we've defined evaluated at the data x values.
    # the model and the data are passed to the user stat/ llh
    # function as it is minimized.
    ui.fit(data_id)
    myfit = ui.get_fit_results()
Beispiel #25
0
def test_psf_model2d(model):
    ui.dataspace2d([216, 261])
    ui.load_psf('psf2d', model + '.mdl')
    ui.set_psf('psf2d')
    mdl = ui.get_model_component('mdl')
    assert mdl.get_center() == (108.0, 130.0)
 def scaled_warm_frac(pars, x):
     scaled = pars[1] + warm_frac * pars[0]
     return scaled
 data_id = 1
 ui.set_method('simplex')
 ui.set_stat('chi2datavar')
 #ui.set_stat('leastsq')
 #ui.load_user_stat("chi2custom", my_chi2, my_err)
 #ui.set_stat(chi2custom)
 ui.load_user_model(scaled_warm_frac, 'model')
 ui.add_user_pars('model', ['scale', 'offset'])
 ui.set_model(data_id, 'model')
 ui.load_arrays(data_id,
                np.array(times),
                np.array(bad_frac))
 fmod = ui.get_model_component('model')
 fmod.scale.min = 1e-9
 fmod.offset.val = 0
 ui.freeze(fmod.offset)
 max_err = np.max([err_high, err_low], axis=0)
 ui.set_staterror(data_id, max_err)
 ui.fit(data_id)
 f = ui.get_fit_results()
 scale = f.rstat ** .5
 ui.set_staterror(data_id, max_err * scale)
 ui.fit()
 f = ui.get_fit_results()
 if f.rstat > 3:
     raise ValueError
 ui.confidence()
 conf = ui.get_confidence_results()
#ftype = 'obc_bad'
for ftype in failures:

    fail_mask = failures[ftype]
    data_id = figmap[ftype]
    ui.set_method('simplex')

    ui.load_user_model(lim_line, '%s_mod' % ftype)
    ui.add_user_pars('%s_mod' % ftype, ['m', 'b'])
    ui.set_model(data_id, '%s_mod' % ftype)

    ui.load_arrays(data_id,
                   times,
                   failures[ftype])

    fmod = ui.get_model_component('%s_mod' % ftype)

    fmod.b.min = 0
    fmod.b.max = 1
    fmod.m.min = 0
    fmod.m.max = 0.5
    fmod.b.val=1e-7


    ui.load_user_stat("loglike", llh, my_err)
    ui.set_stat(loglike)
    # the tricky part here is that the "model" is the probability polynomial
    # we've defined evaluated at the data x values.
    # the model and the data are passed to the user stat/ llh
    # function as it is minimized.
    ui.fit(data_id)
Beispiel #28
0
def change_model(idval):
    """Change the example model values (created by setup_model)"""

    cpt = ui.get_model_component('cpt')
    cpt.c0 = 41
Beispiel #29
0
from matplotlib import pyplot as plt
import numpy as np

from sherpa import ui

x1 = np.arange(-5.0, 30, 0.5)

x2 = np.arange(1.0, 29.0, 0.2)

ui.load_arrays(1, x1, x1 * 0, ui.Data1D)
ui.load_arrays(2, x2, x2 * 0, ui.Data1D)

ui.set_source(1, ui.box1d.box)
box = ui.get_model_component('box')
ui.set_source(2, box)

box.xlow = 10.0
box.xhi = 20.0

# Copy all the objects just to make sure
g1 = ui.gauss1d('g1')
g1.fwhm = 3.0

g2 = ui.gauss1d('g2')
g2.fwhm = 3.0

ui.load_psf('psf1', g1)
ui.load_psf('psf2', g2)

ui.set_psf(1, 'psf1')
ui.set_psf(2, 'psf2')
Beispiel #30
0
            def scaled_warm_frac(pars, x):
                scaled = pars[1] + warm_frac * pars[0]
                return scaled

            data_id = 1
            ui.set_method("simplex")
            ui.set_stat("chi2datavar")
            # ui.set_stat('leastsq')
            # ui.load_user_stat("chi2custom", my_chi2, my_err)
            # ui.set_stat(chi2custom)
            ui.load_user_model(scaled_warm_frac, "model")
            ui.add_user_pars("model", ["scale", "offset"])
            ui.set_model(data_id, "model")
            ui.load_arrays(data_id, np.array(times), np.array(bad_frac))
            fmod = ui.get_model_component("model")
            fmod.scale.min = 1e-9
            max_err = np.max([data[range_type][mag][ok]["err_high"], data[range_type][mag][ok]["err_low"]], axis=0)
            ui.set_staterror(data_id, max_err)
            ui.fit(data_id)
            f = ui.get_fit_results()
            scale = f.rstat ** 0.5
            ui.set_staterror(data_id, max_err * scale)
            ui.fit()
            f = ui.get_fit_results()
            if f.rstat > 3:
                raise ValueError
            ui.confidence()
            conf = ui.get_confidence_results()
            fit_info[range_type][mag][limit] = dict(fit=str(f), conf=str(conf), fmod=fmod, fit_orig=f, conf_orig=conf)
Beispiel #31
0
def test_psf_model1d(model, clean_ui):
    ui.dataspace1d(1, 10)
    ui.load_psf('psf1d', model + '.mdl')
    ui.set_psf('psf1d')
    mdl = ui.get_model_component('mdl')
    assert mdl.get_center() == (4.0, )
# coding: utf-8

import sherpa.ui as ui

ui.load_data("default_interp", "load_template_with_interpolation-bb_data.dat")
ui.load_template_model('bb1', "bb_index.dat")
ui.set_model("default_interp", bb1)
ui.set_method('gridsearch')
ui.set_method_opt('sequence', ui.get_model_component('bb1').parvals)
ui.fit("default_interp")
# coding: utf-8

import sherpa.ui as ui

ui.load_data("default_interp", "bb_data.dat")
ui.load_template_model('bb1', "bb_index.dat")
ui.set_model("default_interp", bb1)
ui.set_method('gridsearch')
ui.set_method_opt('sequence', ui.get_model_component('bb1').parvals)
ui.fit("default_interp")