예제 #1
0
def get_spectrum(filename, data_id="1"):
    ui.load_data(id=data_id, filename=filename)
    d = ui.get_data(data_id)
    arf = d.get_arf()
    rmf = d.get_rmf()

    return d, arf, rmf
예제 #2
0
def load_data(ui, make_data_path):
    """
    Load dataset before every test.
    """
    ui.load_data(make_data_path("3c273.pi"))
    ui.set_source("powlaw1d.p")
    ui.set_bkg_model("const1d.c")
    ui.fit()
예제 #3
0
def load_data(ui, make_data_path):
    """
    Load dataset before every test.
    """
    ui.load_data(make_data_path("3c273.pi"))
    ui.set_source("powlaw1d.p")
    ui.set_bkg_model("const1d.c")
    ui.fit()
예제 #4
0
def fit_sherpa():
    sh.load_data(obs_path)

    sh.set_source("powlaw1d.model")
    model.ref = 1e9  # 1 TeV = 1e9 keV
    model.ampl = 1.23e-20  # in cm**-2 s**-1 keV**-1
    model.gamma = 2.8

    sh.set_stat("cash")
    sh.notice(energy_range[0].to("keV").value, energy_range[1].to("keV").value)
    sh.fit()
    print(sh.get_fit_results())
예제 #5
0
파일: utils.py 프로젝트: evantey14/nustar
def setup(imgfile, emapfile):
    shp.load_data(imgfile)

    shp.load_table_model('emap', emapfile)
    shp.freeze(emap.ampl)

    # we're using an on axis psf provided in 
    # /packages/CALDB/data/nustar/fpm/bcf/psf/
    shp.load_psf('psf', 'nuA2dpsf20100101v003_onaxis.fits')
    shp.set_psf(psf)
    psf.center = (500.0, 500.0)
    psf.size = (200, 200)
예제 #6
0
    def run_hspec_fit(self, model, thres_low, thres_high):
        """Run the gammapy.hspec fit

        Parameters
        ----------
        model : str
            Sherpa model
        thres_high : `~gammapy.spectrum.Energy`
            Upper threshold of the spectral fit
        thres_low : `~gammapy.spectrum.Energy`
            Lower threshold of the spectral fit
        """

        log.info("Starting HSPEC")
        import sherpa.astro.ui as sau
        from ..hspec import wstat
        from sherpa.models import PowLaw1D

        if model == 'PL':
            p1 = PowLaw1D('p1')
            p1.gamma = 2.2
            p1.ref = 1e9
            p1.ampl = 6e-19
        else:
            raise ValueError('Desired Model is not defined')

        thres = thres_low.to('keV').value
        emax = thres_high.to('keV').value

        sau.freeze(p1.ref)
        sau.set_conf_opt("max_rstat", 100)

        list_data = []
        for obs in self.observations:
            datid = obs.phafile.parts[-1][7:12]
            sau.load_data(datid, str(obs.phafile))
            sau.notice_id(datid, thres, emax)
            sau.set_source(datid, p1)
            list_data.append(datid)
        wstat.wfit(list_data)
        sau.covar()
        fit_val = sau.get_covar_results()
        fit_attrs = ('parnames', 'parvals', 'parmins', 'parmaxes')
        fit = dict((attr, getattr(fit_val, attr)) for attr in fit_attrs)
        fit = self.apply_containment(fit)
        sau.clean()
        self.fit = fit
예제 #7
0
def image_model_sherpa(exposure,
                       psf,
                       sources,
                       model_image,
                       overwrite):
    """Compute source model image with Sherpa.

    Inputs:

    * Source list (JSON file)
    * PSF (JSON file)
    * Exposure image (FITS file)

    Outputs:

    * Source model flux image (FITS file)
    * Source model excess image (FITS file)
    """
    import sherpa.astro.ui as sau
    from ..image.models.psf import Sherpa
    from ..image.models.utils import read_json

    log.info('Reading exposure: {0}'.format(exposure))
    # Note: We don't really need the exposure as data,
    # but this is a simple way to init the dataspace to the correct shape
    sau.load_data(exposure)
    sau.load_table_model('exposure', exposure)

    log.info('Reading PSF: {0}'.format(psf))
    Sherpa(psf).set()

    log.info('Reading sources: {0}'.format(sources))
    read_json(sources, sau.set_source)

    name = sau.get_source().name
    full_model = 'exposure * psf({})'.format(name)
    sau.set_full_model(full_model)

    log.info('Computing and writing model_image: {0}'.format(model_image))
    sau.save_model(model_image, clobber=overwrite)
    sau.clean()
    sau.delete_psf()
예제 #8
0
def test_eqwith_err(make_data_path, restore_xspec_settings):

    def check(a0, a1, a2):
        assert a0 == approx(0.16443033244310976, rel=1e-3)
        assert a1 == approx(0.09205564216156815, rel=1e-3)
        assert a2 == approx(0.23933118287470895, rel=1e-3)

    ui.set_method('neldermead')
    ui.set_stat('cstat')
    ui.set_xsabund('angr')
    ui.set_xsxsect('bcmc')

    ui.load_data(make_data_path('12845.pi'))
    ui.notice(0.5, 7)

    ui.set_model("xsphabs.gal*xszphabs.zabs*(powlaw1d.p1+xszgauss.g1)")
    ui.set_par(gal.nh, 0.08)
    ui.freeze(gal)

    ui.set_par(zabs.redshift, 0.518)
    ui.set_par(g1.redshift, 0.518)
    ui.set_par(g1.Sigma, 0.01)
    ui.freeze(g1.Sigma)
    ui.set_par(g1.LineE, min=6.0, max=7.0)

    ui.fit()

    numpy.random.seed(12345)
    result = ui.eqwidth(p1, p1 + g1, error=True, niter=100)
    check(result[0], result[1], result[2])
    params = result[3]

    numpy.random.seed(12345)
    result = ui.eqwidth(p1, p1 + g1, error=True, params=params, niter=100)
    check(result[0], result[1], result[2])

    parvals = ui.get_fit_results().parvals
    assert parvals[0] == approx(0.6111340686157877, rel=1.0e-3)
    assert parvals[1] == approx(1.6409785803466297, rel=1.0e-3)
    assert parvals[2] == approx(8.960926761312153e-05, rel=1.0e-3)
    assert parvals[3] == approx(6.620017726014523, rel=1.0e-3)
    assert parvals[4] == approx(1.9279114810359657e-06, rel=1.0e-3)
예제 #9
0
def test_eqwith_err(make_data_path, restore_xspec_settings):

    def check(a0, a1, a2):
        assert a0 == pytest.approx(0.16443033244310976, rel=1e-3)
        assert a1 == pytest.approx(0.09205564216156815, rel=1e-3)
        assert a2 == pytest.approx(0.23933118287470895, rel=1e-3)

    ui.set_method('neldermead')
    ui.set_stat('cstat')
    ui.set_xsabund('angr')
    ui.set_xsxsect('bcmc')

    ui.load_data(make_data_path('12845.pi'))
    ui.notice(0.5, 7)

    ui.set_model("xsphabs.gal*xszphabs.zabs*(powlaw1d.p1+xszgauss.g1)")
    ui.set_par(gal.nh, 0.08)
    ui.freeze(gal)

    ui.set_par(zabs.redshift, 0.518)
    ui.set_par(g1.redshift, 0.518)
    ui.set_par(g1.Sigma, 0.01)
    ui.freeze(g1.Sigma)
    ui.set_par(g1.LineE, min=6.0, max=7.0)

    ui.fit()

    np.random.seed(12345)
    result = ui.eqwidth(p1, p1 + g1, error=True, niter=100)
    check(result[0], result[1], result[2])
    params = result[3]

    np.random.seed(12345)
    result = ui.eqwidth(p1, p1 + g1, error=True, params=params, niter=100)
    check(result[0], result[1], result[2])

    parvals = ui.get_fit_results().parvals
    assert parvals[0] == pytest.approx(0.6111340686157877, rel=1.0e-3)
    assert parvals[1] == pytest.approx(1.6409785803466297, rel=1.0e-3)
    assert parvals[2] == pytest.approx(8.960926761312153e-05, rel=1.0e-3)
    assert parvals[3] == pytest.approx(6.620017726014523, rel=1.0e-3)
    assert parvals[4] == pytest.approx(1.9279114810359657e-06, rel=1.0e-3)
예제 #10
0
def sherpa_model_image(exposure, psf, sources, model_image, overwrite):
    """Compute source model image with Sherpa.

    Inputs:

    * Source list (JSON file)
    * PSF (JSON file)
    * Exposure image (FITS file)

    Outputs:

    * Source model flux image (FITS file)
    * Source model excess image (FITS file)
    """
    import logging
    logging.basicConfig(level=logging.DEBUG,
                        format='%(levelname)s - %(message)s')
    import sherpa.astro.ui as sau  # @UnresolvedImport
    from ..morphology.psf import Sherpa
    from ..morphology.utils import read_json

    logging.info('Reading exposure: {0}'.format(exposure))
    # Note: We don't really need the exposure as data,
    # but this is a simple way to init the dataspace to the correct shape
    sau.load_data(exposure)
    sau.load_table_model('exposure', exposure)

    logging.info('Reading PSF: {0}'.format(psf))
    Sherpa(psf).set()

    logging.info('Reading sources: {0}'.format(sources))
    read_json(sources, sau.set_source)

    name = sau.get_source().name
    full_model = 'exposure * psf({})'.format(name)
    sau.set_full_model(full_model)

    logging.info('Computing and writing model_image: {0}'.format(model_image))
    sau.save_model(model_image, clobber=overwrite)
예제 #11
0
    def _run_hspec_fit(self):
        """Run the gammapy.hspec fit
        """

        log.info("Starting HSPEC")
        import sherpa.astro.ui as sau
        from ..hspec import wstat

        sau.set_conf_opt("max_rstat", 100)

        thres_lo = self.energy_threshold_low.to('keV').value
        thres_hi = self.energy_threshold_high.to('keV').value
        sau.freeze(self.model.ref)

        list_data = []
        for pha in self.pha:
            datid = pha.parts[-1][7:12]
            sau.load_data(datid, str(pha))
            sau.notice_id(datid, thres_lo, thres_hi)
            sau.set_source(datid, self.model)
            list_data.append(datid)

        wstat.wfit(list_data)
예제 #12
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Compute results with Sherpa"""

import numpy as np
import sherpa.astro.ui as sau

sau.load_data('counts.fits.gz')
sau.set_source('normgauss2d.source + const2d.background')
sau.set_stat('cstat')
# Ask for high-precision results
sau.set_method_opt('ftol', 1e-20)
sau.set_covar_opt('eps', 1e-20)

# Set start parameters close to simulation values to make the fit converge
sau.set_par('source.xpos', 101)
sau.set_par('source.ypos', 101)
sau.set_par('source.ampl', 1.1e3)
sau.set_par('source.fwhm', 10)
sau.set_par('background.c0', 1.1)

# Run fit and covariance estimation
# Results are automatically printed to the screen
sau.fit()
sau.covar()

# Sherpa uses fwhm instead of sigma as extension parameter ... need to convert
# http://cxc.harvard.edu/sherpa/ahelp/gauss2d.html
fwhm_to_sigma = 1. / np.sqrt(8 * np.log(2))
cov = sau.get_covar_results()
sigma = fwhm_to_sigma * cov.parvals[0]
sigma_err = fwhm_to_sigma * cov.parmaxes[0]
def test_save_image_dataimg_fits_wcs(writer, make_data_path, tmp_path):
    """Does save_image work for a FITS image with WCS

    We also check the input file, is read in, for fun.

    dmlist reports that this file has

    Block    1: EVENTS_IMAGE                   Image      Int2(316x313)

    Physical Axis Transforms for Image Block EVENTS_IMAGE

    Group# Axis#
       1   1,2    sky(x) = (+2986.8401) +(+1.0)* ((#1)-(+0.50))
                     (y)   (+4362.6602)  (+1.0)  ((#2) (+0.50))

    World Coordinate Axis Transforms for Image Block EVENTS_IMAGE

    Group# Axis#
       1   1,2    EQPOS(RA ) = (+149.8853)[deg] +TAN[(-0.000136667)* (sky(x)-(+4096.50))]
                       (DEC)   (+2.6079  )           (+0.000136667)  (   (y) (+4096.50))

    """

    from sherpa.astro.io import read_image
    from sherpa.astro.io.meta import Meta
    from sherpa.astro.io.wcs import WCS

    # It looks like we don't write out the header info, at least for
    # pyfits. Probably a bug.
    #
    def check_data(d, header=True):
        assert isinstance(d, ui.DataIMG)
        assert d.shape == (313, 316)
        assert d.y.shape == (313 * 316, )
        assert d.y.sum() == 965
        assert d.y.max() == 3

        hdr = d.header
        assert isinstance(hdr, Meta)
        if header:
            assert hdr['OBJECT'] == 'CSC'
            assert hdr['ONTIME'] == pytest.approx(18220.799932122)
            assert hdr['TSTOP'] == pytest.approx(280770182.77747)

        assert isinstance(d.sky, WCS)
        assert d.sky.name == 'physical'
        assert d.sky.type == 'LINEAR'
        assert d.sky.crval == pytest.approx([2986.84008789, 4362.66015625])
        assert d.sky.crpix == pytest.approx([0.5, 0.5])
        assert d.sky.cdelt == pytest.approx([1, 1])

        assert isinstance(d.eqpos, WCS)
        assert d.eqpos.name == 'world'
        assert d.eqpos.type == 'WCS'
        assert d.eqpos.epoch == pytest.approx(2000)
        assert d.eqpos.equinox == pytest.approx(2000)
        assert d.eqpos.crval == pytest.approx([149.88533198, 2.60794887])
        assert d.eqpos.crpix == pytest.approx([4096.5, 4096.5])
        assert d.eqpos.cdelt * 3600 == pytest.approx([-0.492, 0.492])

    infile = make_data_path('acisf08478_000N001_r0043_regevt3_srcimg.fits')
    ui.load_data(2, infile)

    dorig = ui.get_data(2)
    check_data(dorig)

    out = tmp_path / "data.dat"
    outfile = str(out)
    writer(2, outfile, ascii=False)

    ans = read_image(outfile)
    check_data(ans, header=False)
예제 #14
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Compute results with Sherpa"""
from __future__ import print_function, division
# __doctest_skip__
__doctest_skip__ = ['*']
import numpy as np
import sherpa.astro.ui as sau

sau.load_data('counts.fits.gz')
sau.set_source('normgauss2d.source + const2d.background')
sau.set_stat('cstat')
# Ask for high-precision results
sau.set_method_opt('ftol', 1e-20)
sau.set_covar_opt('eps', 1e-20)

# Set start parameters close to simulation values to make the fit converge
sau.set_par('source.xpos', 101)
sau.set_par('source.ypos', 101)
sau.set_par('source.ampl', 1.1e3)
sau.set_par('source.fwhm', 10)
sau.set_par('background.c0', 1.1)

# Run fit and covariance estimation
# Results are automatically printed to the screen
sau.fit()
sau.covar()

# Sherpa uses fwhm instead of sigma as extension parameter ... need to convert
# http://cxc.harvard.edu/sherpa/ahelp/gauss2d.html
fwhm_to_sigma = 1. / np.sqrt(8 * np.log(2))
cov = sau.get_covar_results()
예제 #15
0
파일: test_spatial.py 프로젝트: eblur/soxs
def test_beta_model():
    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    r_c = 20.0
    beta = 1.0

    exp_time = Quantity(500.0, "ks")

    e = spec.generate_energies(exp_time, area, prng=prng)

    beta_src = BetaModel(ra0, dec0, r_c, beta, e.size, prng=prng)

    write_photon_list("beta",
                      "beta",
                      e.flux,
                      beta_src.ra,
                      beta_src.dec,
                      e,
                      overwrite=True)

    instrument_simulator("beta_simput.fits",
                         "beta_evt.fits",
                         exp_time,
                         "hdxi", [ra0, dec0],
                         ptsrc_bkgnd=False,
                         instr_bkgnd=False,
                         foreground=False,
                         prng=prng)

    inst = get_instrument_from_registry("hdxi")
    arf = AuxiliaryResponseFile(inst["arf"])
    cspec = ConvolvedSpectrum(spec, arf)
    ph_flux = cspec.get_flux_in_band(0.5, 7.0)[0].value
    S0 = 3.0 * ph_flux / (2.0 * np.pi * r_c * r_c)

    write_radial_profile("beta_evt.fits",
                         "beta_evt_profile.fits", [ra0, dec0],
                         0.0,
                         100.0,
                         200,
                         ctr_type="celestial",
                         emin=0.5,
                         emax=7.0,
                         overwrite=True)

    load_data(1, "beta_evt_profile.fits", 3,
              ["RMID", "SUR_BRI", "SUR_BRI_ERR"])
    set_stat("chi2")
    set_method("levmar")
    set_source("beta1d.src")
    src.beta = 1.0
    src.r0 = 10.0
    src.ampl = 0.8 * S0
    freeze(src.xpos)

    fit()
    set_covar_opt("sigma", 1.645)
    covar()
    res = get_covar_results()

    assert np.abs(res.parvals[0] - r_c) < res.parmaxes[0]
    assert np.abs(res.parvals[1] - beta) < res.parmaxes[1]
    assert np.abs(res.parvals[2] - S0) < res.parmaxes[2]

    os.chdir(curdir)
    shutil.rmtree(tmpdir)
예제 #16
0
    def test_chi2(self):

        # Case 1: first ds has no error, second has, chi2-derived (chi2gehrels)
        # statistic. I expect stat.name to be chi2gehrels for ds1, chi2 for
        # ds2, chi2gehrels for ds1,2
        ui.load_data(1, self.data)
        ui.load_data(2, self.data, use_errors=True)

        ui.set_source(1, "gauss1d.g1")
        ui.set_source(2, "gauss1d.g1")

        ui.set_stat("chi2gehrels")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2gehrels', stat1)
        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2gehrels', stat12)

        # Case 2: first ds has errors, second has not, chi2-derived
        # (chi2gehrels) statistic. I expect stat.name to be chi2 for ds1,
        # chi2gehrels for ds2, chi2gehrels for ds1,2
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2gehrels', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2gehrels', stat12)

        # Case 3: both datasets have errors, chi2-derived (chi2gehrels)
        # statistic. I expect stat.name to be chi2 for all of them.
        ui.load_data(2, self.data, use_errors=True)
        ui.load_data(1, self.data, use_errors=True)

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2', stat12)

        # Case 4: first ds has errors, second has not, LeastSq statistic
        # I expect stat.name to be leastsq for all of them.
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("leastsq")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('leastsq', stat2)
        self.assertEqual('leastsq', stat1)
        self.assertEqual('leastsq', stat12)

        # Case 5: both ds have errors, LeastSq statistic
        # I expect stat.name to be leastsq for all of them.
        ui.load_data(2, self.data, use_errors=True)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("leastsq")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('leastsq', stat2)
        self.assertEqual('leastsq', stat1)
        self.assertEqual('leastsq', stat12)

        # Case 6: first ds has errors, second has not, CStat statistic
        # I expect stat.name to be cstat for all of them.
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("cstat")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('cstat', stat2)
        self.assertEqual('cstat', stat1)
        self.assertEqual('cstat', stat12)

        # Case7: select chi2 as statistic. One of the ds does not provide
        # errors. I expect sherpa to raise a StatErr exception.
        ui.set_stat('chi2')

        caught = False

        from sherpa.utils.err import StatErr
        try:
            ui.get_stat_info()
        except StatErr:
            caught = True

        self.assertTrue(caught, msg='StatErr was not caught')

        # Case8: select chi2 as statistic. Both datasets provide errors
        # I expect stat to be 'chi2'
        ui.load_data(2, self.data, use_errors=True)
        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2', stat12)
예제 #17
0
파일: test_spatial.py 프로젝트: eblur/soxs
def test_beta_model_flux():
    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    r_c = 20.0
    beta = 1.0

    prng = 34

    e = spec.generate_energies(exp_time, area, prng=prng)

    beta_src = BetaModel(ra0, dec0, r_c, beta, e.size, prng=prng)

    write_photon_list("beta",
                      "beta",
                      e.flux,
                      beta_src.ra,
                      beta_src.dec,
                      e,
                      overwrite=True)

    instrument_simulator("beta_simput.fits",
                         "beta_evt.fits",
                         exp_time,
                         "acisi_cy0", [ra0, dec0],
                         ptsrc_bkgnd=False,
                         instr_bkgnd=False,
                         foreground=False,
                         roll_angle=37.0,
                         prng=prng)

    ph_flux = spec.get_flux_in_band(0.5, 7.0)[0].value
    S0 = 3.0 * ph_flux / (2.0 * np.pi * r_c * r_c)

    wspec = spec.new_spec_from_band(0.5, 7.0)

    make_exposure_map("beta_evt.fits",
                      "beta_expmap.fits",
                      wspec.emid.value,
                      weights=wspec.flux.value,
                      overwrite=True)

    write_radial_profile("beta_evt.fits",
                         "beta_evt_profile.fits", [ra0, dec0],
                         0.0,
                         100.0,
                         200,
                         ctr_type="celestial",
                         emin=0.5,
                         emax=7.0,
                         expmap_file="beta_expmap.fits",
                         overwrite=True)

    load_data(1, "beta_evt_profile.fits", 3,
              ["RMID", "SUR_FLUX", "SUR_FLUX_ERR"])
    set_stat("chi2")
    set_method("levmar")
    set_source("beta1d.src")
    src.beta = 1.0
    src.r0 = 10.0
    src.ampl = 0.8 * S0
    freeze(src.xpos)

    fit()
    set_covar_opt("sigma", 1.645)
    covar()
    res = get_covar_results()

    assert np.abs(res.parvals[0] - r_c) < res.parmaxes[0]
    assert np.abs(res.parvals[1] - beta) < res.parmaxes[1]
    assert np.abs(res.parvals[2] - S0) < res.parmaxes[2]

    os.chdir(curdir)
    shutil.rmtree(tmpdir)
예제 #18
0
def test_chi2(make_data_path, clean_astro_ui):
    "bugs #11400, #13297, #12365"

    data = make_data_path('3c273.pi')

    # Case 1: first ds has no error, second has, chi2-derived (chi2gehrels)
    # statistic. I expect stat.name to be chi2gehrels for ds1, chi2 for
    # ds2, chi2gehrels for ds1,2
    ui.load_data(1, data)
    ui.load_data(2, data, use_errors=True)

    ui.set_source(1, "gauss1d.g1")
    ui.set_source(2, "gauss1d.g1")

    ui.set_stat("chi2gehrels")

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'chi2gehrels'
    assert stat2 == 'chi2'
    assert stat12 == 'chi2gehrels'

    # Case 2: first ds has errors, second has not, chi2-derived
    # (chi2gehrels) statistic. I expect stat.name to be chi2 for ds1,
    # chi2gehrels for ds2, chi2gehrels for ds1,2
    ui.load_data(2, data)
    ui.load_data(1, data, use_errors=True)

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'chi2'
    assert stat2 == 'chi2gehrels'
    assert stat12 == 'chi2gehrels'

    # Case 3: both datasets have errors, chi2-derived (chi2gehrels)
    # statistic. I expect stat.name to be chi2 for all of them.
    ui.load_data(2, data, use_errors=True)
    ui.load_data(1, data, use_errors=True)

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'chi2'
    assert stat2 == 'chi2'
    assert stat12 == 'chi2'

    # Case 4: first ds has errors, second has not, LeastSq statistic
    # I expect stat.name to be leastsq for all of them.
    ui.load_data(2, data)
    ui.load_data(1, data, use_errors=True)

    ui.set_stat("leastsq")

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'leastsq'
    assert stat2 == 'leastsq'
    assert stat12 == 'leastsq'

    # Case 5: both ds have errors, LeastSq statistic
    # I expect stat.name to be leastsq for all of them.
    ui.load_data(2, data, use_errors=True)
    ui.load_data(1, data, use_errors=True)

    ui.set_stat("leastsq")

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'leastsq'
    assert stat2 == 'leastsq'
    assert stat12 == 'leastsq'

    # Case 6: first ds has errors, second has not, CStat statistic
    # I expect stat.name to be cstat for all of them.
    ui.load_data(2, data)
    ui.load_data(1, data, use_errors=True)

    ui.set_stat("cstat")

    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'cstat'
    assert stat2 == 'cstat'
    assert stat12 == 'cstat'

    # Case7: select chi2 as statistic. One of the ds does not provide
    # errors. I expect sherpa to raise a StatErr exception.
    ui.set_stat('chi2')

    with pytest.raises(StatErr):
        ui.get_stat_info()

    # Case8: select chi2 as statistic. Both datasets provide errors
    # I expect stat to be 'chi2'
    ui.load_data(2, data, use_errors=True)
    si = ui.get_stat_info()

    stat1 = si[0].statname
    stat2 = si[1].statname
    stat12 = si[2].statname

    assert stat1 == 'chi2'
    assert stat2 == 'chi2'
    assert stat12 == 'chi2'
예제 #19
0
파일: test_spatial.py 프로젝트: eblur/soxs
def test_annulus():

    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    r_in = 10.0
    r_out = 30.0

    e = spec.generate_energies(exp_time, area, prng=prng)

    ann_src = AnnulusModel(ra0, dec0, r_in, r_out, e.size, prng=prng)

    write_photon_list("ann",
                      "ann",
                      e.flux,
                      ann_src.ra,
                      ann_src.dec,
                      e,
                      overwrite=True)

    instrument_simulator("ann_simput.fits",
                         "ann_evt.fits",
                         exp_time,
                         "hdxi", [ra0, dec0],
                         ptsrc_bkgnd=False,
                         instr_bkgnd=False,
                         foreground=False,
                         prng=prng)

    inst = get_instrument_from_registry("hdxi")
    arf = AuxiliaryResponseFile(inst["arf"])
    cspec = ConvolvedSpectrum(spec, arf)
    ph_flux = cspec.get_flux_in_band(0.5, 7.0)[0].value
    S0 = ph_flux / (np.pi * (r_out**2 - r_in**2))

    write_radial_profile("ann_evt.fits",
                         "ann_evt_profile.fits", [ra0, dec0],
                         1.1 * r_in,
                         0.9 * r_out,
                         100,
                         ctr_type="celestial",
                         emin=0.5,
                         emax=7.0,
                         overwrite=True)

    load_data(1, "ann_evt_profile.fits", 3, ["RMID", "SUR_BRI", "SUR_BRI_ERR"])
    set_stat("chi2")
    set_method("levmar")
    set_source("const1d.src")
    src.c0 = 0.8 * S0

    fit()
    set_covar_opt("sigma", 1.645)
    covar()
    res = get_covar_results()

    assert np.abs(res.parvals[0] - S0) < res.parmaxes[0]

    os.chdir(curdir)
    shutil.rmtree(tmpdir)
예제 #20
0
    def test_chi2(self):

        # Case 1: first ds has no error, second has, chi2-derived (chi2gehrels)
        # statistic. I expect stat.name to be chi2gehrels for ds1, chi2 for
        # ds2, chi2gehrels for ds1,2
        ui.load_data(1, self.data)
        ui.load_data(2, self.data, use_errors=True)

        ui.set_source(1, "gauss1d.g1")
        ui.set_source(2, "gauss1d.g1")

        ui.set_stat("chi2gehrels")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2gehrels', stat1)
        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2gehrels', stat12)

        # Case 2: first ds has errors, second has not, chi2-derived
        # (chi2gehrels) statistic. I expect stat.name to be chi2 for ds1,
        # chi2gehrels for ds2, chi2gehrels for ds1,2
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2gehrels', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2gehrels', stat12)

        # Case 3: both datasets have errors, chi2-derived (chi2gehrels)
        # statistic. I expect stat.name to be chi2 for all of them.
        ui.load_data(2, self.data, use_errors=True)
        ui.load_data(1, self.data, use_errors=True)

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2', stat12)

        # Case 4: first ds has errors, second has not, LeastSq statistic
        # I expect stat.name to be leastsq for all of them.
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("leastsq")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('leastsq', stat2)
        self.assertEqual('leastsq', stat1)
        self.assertEqual('leastsq', stat12)

        # Case 5: both ds have errors, LeastSq statistic
        # I expect stat.name to be leastsq for all of them.
        ui.load_data(2, self.data, use_errors=True)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("leastsq")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('leastsq', stat2)
        self.assertEqual('leastsq', stat1)
        self.assertEqual('leastsq', stat12)

        # Case 6: first ds has errors, second has not, CStat statistic
        # I expect stat.name to be cstat for all of them.
        ui.load_data(2, self.data)
        ui.load_data(1, self.data, use_errors=True)

        ui.set_stat("cstat")

        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('cstat', stat2)
        self.assertEqual('cstat', stat1)
        self.assertEqual('cstat', stat12)

        # Case7: select chi2 as statistic. One of the ds does not provide
        # errors. I expect sherpa to raise a StatErr exception.
        ui.set_stat('chi2')

        caught = False

        from sherpa.utils.err import StatErr
        try:
            ui.get_stat_info()
        except StatErr:
            caught = True

        self.assertTrue(caught, msg='StatErr was not caught')

        # Case8: select chi2 as statistic. Both datasets provide errors
        # I expect stat to be 'chi2'
        ui.load_data(2, self.data, use_errors=True)
        si = ui.get_stat_info()

        stat1 = si[0].statname
        stat2 = si[1].statname
        stat12 = si[2].statname

        self.assertEqual('chi2', stat2)
        self.assertEqual('chi2', stat1)
        self.assertEqual('chi2', stat12)
예제 #21
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Compute results with Sherpa"""
from __future__ import print_function, division
import numpy as np
import sherpa.astro.ui as sau

sau.load_data("counts.fits.gz")
sau.set_source("normgauss2d.source + const2d.background")
sau.set_stat("cstat")
# Ask for high-precision results
sau.set_method_opt("ftol", 1e-20)
sau.set_covar_opt("eps", 1e-20)

# Set start parameters close to simulation values to make the fit converge
sau.set_par("source.xpos", 101)
sau.set_par("source.ypos", 101)
sau.set_par("source.ampl", 1.1e3)
sau.set_par("source.fwhm", 10)
sau.set_par("background.c0", 1.1)

# Run fit and covariance estimation
# Results are automatically printed to the screen
sau.fit()
sau.covar()

# Sherpa uses fwhm instead of sigma as extension parameter ... need to convert
# http://cxc.harvard.edu/sherpa/ahelp/gauss2d.html
fwhm_to_sigma = 1.0 / np.sqrt(8 * np.log(2))
cov = sau.get_covar_results()
sigma = fwhm_to_sigma * cov.parvals[0]
sigma_err = fwhm_to_sigma * cov.parmaxes[0]