Beispiel #1
0
    def test_set_coord_bad_coord(self):
        from sherpa.utils.err import IdentifierErr, DataErr

        # Test Case #1: if the list of ids is empty, raise
        # IdentifierErr['nodatasets']
        caught = False
        try:
            ui.set_coord('image')
        except IdentifierErr:
            caught = True
        if not caught:
            self.fail("Test Case #1: IdentifierErr Exception not caught")

        # Test Case #2: check the user expected behavior. The call
        # set_coord("sky") will result in the error message
        # DataErr: unknown coordinates: 'sky'\n \
        # Valid coordinates: logical, image, physical, world, wcs
        ui.load_image(self.img)

        caught = False
        try:
            ui.set_coord("sky")
        except DataErr as e:
            okmsg = "unknown coordinates: 'sky'\nValid options: logical, image, physical, world, wcs"
            self.assertEqual(okmsg, e.message)
            caught = True
        if not caught:
            self.fail("Test Case #2: DataErr Exception not caught")
    def test_set_coord_bad_coord(self):
        from sherpa.utils.err import IdentifierErr, DataErr

        # Test Case #1: if the list of ids is empty, raise
        # IdentifierErr['nodatasets']
        caught = False
        try:
            ui.set_coord('image')
        except IdentifierErr:
            caught = True
        if not caught:
            self.fail("Test Case #1: IdentifierErr Exception not caught")

        # Test Case #2: check the user expected behavior. The call
        # set_coord("sky") will result in the error message
        # DataErr: unknown coordinates: 'sky'\n \
        # Valid coordinates: logical, image, physical, world, wcs
        ui.load_image(self.img)

        caught = False
        try:
            ui.set_coord("sky")
        except DataErr as e:
            okmsg = "unknown coordinates: 'sky'\nValid options: " + \
                    "logical, image, physical, world, wcs"
            self.assertEqual(okmsg, e.message)
            caught = True
        if not caught:
            self.fail("Test Case #2: DataErr Exception not caught")
Beispiel #3
0
def basic_img(make_data_path):
    """Create a basic image data set/setup"""

    ui.set_default_id(2)
    ui.load_image(make_data_path('img.fits'))
    ui.set_source(ui.gauss2d.gmdl)
    ui.guess()
def test_image_with_id(make_data_path, clean_astro_ui):
    """Call load_image with an identifier"""

    img = make_data_path('img.fits')

    assert ui.list_data_ids() == []
    ui.load_image('ix', img)
    assert ui.list_data_ids() == ['ix']

    d = ui.get_data('ix')
    assert isinstance(d, ui.DataIMG)
    assert d.name.endswith('img.fits')
def test_image_12578_set_coord_bad_coord(make_data_path, clean_astro_ui):

    img = make_data_path('img.fits')

    # Test Case #1: if the list of ids is empty, raise
    # IdentifierErr['nodatasets']
    #
    with pytest.raises(IdentifierErr):
        ui.set_coord('image')

    # Test Case #2: check the user expected behavior. The call
    # set_coord("sky") will result in the error message
    # DataErr: unknown coordinates: 'sky'\n \
    # Valid coordinates: logical, image, physical, world, wcs
    #
    ui.load_image(img)

    with pytest.raises(DataErr) as exc:
        ui.set_coord("sky")

    okmsg = "unknown coordinates: 'sky'\nValid options: " + \
            "logical, image, physical, world, wcs"
    assert okmsg in str(exc.value)
Beispiel #6
0
"""Fit gamma-ray images with Sherpa.
"""
import sherpa.astro.ui as ui
from kapteyn import wcs, positions
try:
    from astropy.io import fits
except:
    import pyfits as fits

filename = 'skymap_ex.fits'
nomposstr = '05h34m31.94s 22d00m52.2s'
header = fits.getheader(filename)
proj = wcs.Projection(header)
xc, yc = float(header['NAXIS1']) / 2., float(header['NAXIS2']) / 2.
ui.load_image(filename)
ui.notice2d('circle({0}, {1}, {2})'.format(xc, yc, float(header['NAXIS2']) / 4.))
ui.set_source(ui.gauss2d.g1 + ui.gauss2d.g2)
g1.xpos = xc
g1.ypos = yc
g2.fwhm = g1.fwhm = 3.
ui.link(g2.xpos, g1.xpos)
ui.link(g2.ypos, g1.ypos)
g2.ampl = 50.
g1.ampl = 50.
ui.guess()
ui.fit()
ui.image_fit()
ui.covar()
conf = ui.get_covar_results()
conf_dict = dict([(n,(v, l, h)) for n,v,l,h in
                   zip(conf.parnames, conf.parvals, conf.parmins, conf.parmaxes)])
Beispiel #7
0
"""Fit gamma-ray images with Sherpa."""
import sherpa.astro.ui as ui
from kapteyn import wcs, positions
try:
    from astropy.io import fits
except:
    import pyfits as fits

filename = 'skymap_ex.fits'
nomposstr = '05h34m31.94s 22d00m52.2s'
header = fits.getheader(filename)
proj = wcs.Projection(header)
xc, yc = float(header['NAXIS1']) / 2., float(header['NAXIS2']) / 2.
ui.load_image(filename)
ui.notice2d('circle({0}, {1}, {2})'.format(xc, yc,
                                           float(header['NAXIS2']) / 4.))
ui.set_source(ui.gauss2d.g1 + ui.gauss2d.g2)
g1.xpos = xc
g1.ypos = yc
g2.fwhm = g1.fwhm = 3.
ui.link(g2.xpos, g1.xpos)
ui.link(g2.ypos, g1.ypos)
g2.ampl = 50.
g1.ampl = 50.
ui.guess()
ui.fit()
ui.image_fit()
ui.covar()
conf = ui.get_covar_results()
conf_dict = dict([(n, (v, l, h)) for n, v, l, h in zip(
    conf.parnames, conf.parvals, conf.parmins, conf.parmaxes)])
Beispiel #8
0

# ### Read the maps and store them in a sherpa model
# 
# We now have the prepared files which sherpa can read. 
# This part of the notebook shows how to do image analysis using sherpa

# In[ ]:


import sherpa.astro.ui as sh

sh.set_stat("cash")
sh.set_method("simplex")

sh.load_image("analysis_3d/counts_2D.fits")
sh.set_coord("logical")

sh.load_table_model("expo", "analysis_3d/exposure_2D.fits")
sh.load_table_model("bkg", "analysis_3d/background_2D.fits")
sh.load_psf("psf", "analysis_3d/psf_2D.fits")


# In principle one might first want to fit the background amplitude. However the background estimation method already yields the correct normalization, so we freeze the background amplitude to unity instead of adjusting it. The (smoothed) residuals from this background model are then computed and shown.

# In[ ]:


sh.set_full_model(bkg)
bkg.ampl = 1
sh.freeze(bkg)
Beispiel #9
0
ax_sed, ax_resid = total_result.plot(fig_kwargs=dict(figsize=(8, 8)),
                                     point_kwargs=dict(color='blue',
                                                       label='Measured'),
                                     **opts)

spec_true.plot(ax=ax_sed, label='True', color='magenta', **opts)
ax_sed.legend()

# # Sherpa Morphological fit

# In[53]:

import sherpa.astro.ui as sh
sh.set_stat("cash")
sh.set_method("simplex")
sh.load_image('../datasets/images/MSH15-52_counts.fits.gz')
sh.set_coord("logical")

sh.load_table_model("expo", "../datasets/images/MSH15-52_exposure.fits.gz")
sh.load_table_model("bkg", "../datasets/images/MSH15-52_background.fits.gz")
sh.load_psf("psf", "../datasets/images/MSH15-52_psf.fits.gz")

# In[54]:

sh.set_full_model(bkg)
bkg.ampl = 1
sh.freeze(bkg)

data = sh.get_data_image().y - sh.get_model_image().y
resid = SkyImage(data=data, wcs=ref_image.wcs)
Beispiel #10
0
    def simulate_null_images(img_file: str,
                             psf_file: str,
                             n_null_sims: int,
                             no_core: bool = False,
                             mcmciter: int = 5000,
                             **kwargs) -> None:
        """
        Simulates a specified number of baseline images for a given input observation and a psf file

        :param img_file: Path to the input image file
        :param psf_file: Path to the psf image file
        :param n_null_sims: Number of baseline replicates to be simulated
        :param no_core: Setting this to True will only generate baseline replicates with a flat background while the default value includes a point source at the location of the core
        :param mcmciter: The number of MCMC samples to draw for simulating the baselines
        """
        print("Creating the null file")
        clean()
        set_stat("cstat")
        set_method("simplex")
        load_image(img_file)
        load_psf("mypsf", psf_file)
        set_psf(mypsf)

        if no_core:
            set_model(const2d.c0)
            set_par(c0.c0, min=0)
        else:
            set_model(gauss2d.q1 + const2d.c0)
            set_par(c0.c0, min=0)
            # set_par(q1.fwhm,max=0.5)
            guess(q1)
        fit()
        results = get_fit_results()
        save("core_source_fit.save", clobber=True)
        save_source("null_q1_c1.fits", clobber=True)
        covar()

        if no_core:
            for i in range(n_null_sims):
                fake()
                save_image("sim_null_{}.fits".format(i), clobber=True)
            clean()
            return

        normgauss1d.g1
        g1.pos = q1.fwhm
        g1.fwhm = get_covar_results().parmaxes[0]

        # check if there is a valid upper bound.
        print(get_covar_results())
        if (get_covar_results().parmaxes[0] is None
                or get_covar_results().parmins[1] is None
                or get_covar_results().parmins[0] is None):
            for i in range(n_null_sims):
                fake()
                save_image("sim_null_{}.fits".format(i), clobber=True)
            clean()
            return
        # if not go for the regular
        set_prior(q1.fwhm, g1)
        set_sampler_opt("defaultprior", False)
        set_sampler_opt("priorshape", [True, False, False, False, False])
        set_sampler_opt("originalscale", [True, True, True, True, True])
        if mcmciter < n_null_sims * 100:
            mcmciter = n_null_sims * 100

        # the following code throws an error sometimes #bug
        try:
            stats, accept, params = get_draws(1, niter=mcmciter)
        except:
            params = [np.repeat(q1.fwhm.val, mcmciter)]

        # print('Simulating the null files')
        for i in range(n_null_sims):
            set_par(q1.fwhm, params[0][(i + 1) * 100 - 1])
            fake()
            save_image("sim_null_{}.fits".format(i), clobber=True)
        save_all(outfile="lira_input_baseline_sim.log", clobber=True)
        clean()
Beispiel #11
0
# You may see a Warning concerning XSPEC
# As we will note use Xspec spectral models this warning is not important
import sherpa.astro.ui as sh


# In[2]:


# Read the fits file to load them in a sherpa model
hdr = fits.getheader("G300-0_test_counts.fits")
wcs = WCS(hdr)

sh.set_stat("cash")
sh.set_method("simplex")
sh.load_image("G300-0_test_counts.fits")
sh.set_coord("logical")

sh.load_table_model("expo", "G300-0_test_exposure.fits")
sh.load_table_model("bkg", "G300-0_test_background.fits")
sh.load_psf("psf", "G300-0_test_psf.fits")


# In principle one might first want to fit the background amplitude. However the background estimation method already yields the correct normalization, so we freeze the background amplitude to unity instead of adjusting it. The (smoothed) residuals from this background model are then computed and shown.

# In[3]:


sh.set_full_model(bkg)
bkg.ampl = 1
sh.freeze(bkg)
from gammapy.maps import Map, WcsNDMap, WcsGeom
import os

# Warnings about XSPEC or DS9 can be ignored here
import sherpa.astro.ui as sh

# In[ ]:

# Read the fits file to load them in a sherpa model
filecounts = os.environ["GAMMAPY_DATA"] + "/sherpaCTA/G300-0_test_counts.fits"
hdr = fits.getheader(filecounts)
wcs = WCS(hdr)

sh.set_stat("cash")
sh.set_method("simplex")
sh.load_image(filecounts)
sh.set_coord("logical")

fileexp = os.environ["GAMMAPY_DATA"] + "/sherpaCTA/G300-0_test_exposure.fits"
filebkg = os.environ["GAMMAPY_DATA"] + "/sherpaCTA/G300-0_test_background.fits"
filepsf = os.environ["GAMMAPY_DATA"] + "/sherpaCTA/G300-0_test_psf.fits"
sh.load_table_model("expo", fileexp)
sh.load_table_model("bkg", filebkg)
sh.load_psf("psf", filepsf)

# In principle one might first want to fit the background amplitude. However the background estimation method already yields the correct normalization, so we freeze the background amplitude to unity instead of adjusting it. The (smoothed) residuals from this background model are then computed and shown.

# In[ ]:

sh.set_full_model(bkg)
bkg.ampl = 1