예제 #1
0
def setup_imgdata_model():
    """Use a model for the PSF"""

    # Fake an image
    #
    x1, x0 = np.mgrid[0:8, 0:10]
    ymod = 10 + 100 / ((x0 - 5.5)**2 + (x1 - 3.5)**2)

    x0 = x0.flatten()
    x1 = x1.flatten()
    y = ymod.flatten()

    y = y.astype(int)  # convert to integers

    ui.load_arrays(1, x0, x1, y, (8, 10), ui.DataIMG)

    pmodel = ui.create_model_component('gauss2d', 'pmodel')
    pmodel.xpos = 0
    pmodel.ypos = 0
    pmodel.fwhm = 3

    ui.load_psf('psf', pmodel)
    psf.size = [10, 10]  # not sure if this is useful but leave in
    psf.center = [5, 4]
    ui.set_psf(psf)

    setup_imgdata_source()
예제 #2
0
def test_psf_model2d(model, clean_astro_ui):
    ui.dataspace2d([216, 261])
    ui.load_psf('psf2d', model + '.mdl')
    ui.set_psf('psf2d')
    mdl = ui.get_model_component('mdl')
    assert (numpy.array(mdl.get_center()) ==
            numpy.array([108, 130])).all()
예제 #3
0
 def set(self):
     """Set the PSF for Sherpa."""
     import sherpa.astro.ui as sau
     from ..scripts.image_fit import read_json
     read_json(self.pars, sau.set_model)
     sau.load_psf('psf', sau.get_model())
     self.center_psf()
     sau.set_psf('psf')
예제 #4
0
파일: psf.py 프로젝트: mwcraig/gammapy
 def set(self):
     """Set the PSF for Sherpa."""
     import sherpa.astro.ui as sau
     # from morphology.utils import read_json
     read_json(self.pars, sau.set_model)
     sau.load_psf('psf', sau.get_model())
     sau.set_psf('psf')
     self.center_psf()
예제 #5
0
 def set(self):
     """Set the PSF for Sherpa."""
     import sherpa.astro.ui as sau
     # from gammapy.image.models.utils import read_json
     read_json(self.pars, sau.set_model)
     sau.load_psf('psf', sau.get_model())
     self.center_psf()
     sau.set_psf('psf')
예제 #6
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
예제 #7
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.assert_((numpy.array(mdl.get_center()) == numpy.array([4])).all())
         except:
             print model
             raise
예제 #8
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
예제 #9
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
예제 #10
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
예제 #11
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
예제 #12
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)
예제 #13
0
def setup_imgdata_file(tmp_path, recwarn):
    """Use a model for the PSF"""

    # Fake an image
    #
    x1, x0 = np.mgrid[0:8, 0:10]
    ymod = 10 + 100 / ((x0 - 5.5)**2 + (x1 - 3.5)**2)

    x0 = x0.flatten()
    x1 = x1.flatten()
    y = ymod.flatten()

    y = y.astype(int)  # convert to integers

    ui.load_arrays(1, x0, x1, y, (8, 10), ui.DataIMG)

    # Sherpa can confuse astropy if you send in pathlib objects so
    # convert to the raw filesystem path.
    #
    fname = tmp_path / "psf.fits"
    infile = str(fname)
    fake_psf_image(infile)

    ui.load_psf('psf', infile)
    psf.size = [10, 8]
    psf.center = [5, 4]

    # Just check where the warning comes from (pytest.warns didn't
    # seem to remove the warning so it still triggered the general
    # "check no warning" fixture, so use recwarn like this).
    #
    assert len(recwarn) == 0
    ui.set_psf(psf)
    assert len(recwarn) == 1

    setup_imgdata_source()

    assert len(recwarn) == 1
    w = recwarn.pop()
    assert issubclass(w.category, UserWarning)

    wmsg = 'PSF Image does not have a pixel size. Sherpa ' + \
        'will assume the pixel size is the same as the data'
    assert str(w.message) == wmsg
예제 #14
0
def test_psf_pars_are_frozen(clean_astro_ui):
    "bug #12503"
    ui.create_model_component("beta2d", "p1")
    p1 = ui.get_model_component("p1")
    ui.load_psf('psf', p1)
    assert p1.thawedpars == []
예제 #15
0
def test_psf_model1d(model, center, clean_astro_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() == (center, )
예제 #16
0
# 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)

data = sh.get_data_image().y -  sh.get_model_image().y
resid = SkyImage(data=data, wcs=wcs)

resid_table = []  # Keep residual images in a list to show them later
예제 #17
0
# 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)


# In[ ]:

예제 #18
0
 def test_psf_pars_are_frozen(self):
     ui.create_model_component("beta2d", "p1")
     p1 = ui.get_model_component("p1")
     ui.load_psf('psf', p1)
     self.assertEqual([], p1.thawedpars)
예제 #19
0
 def test_psf_pars_are_frozen(self):
     ui.create_model_component("beta2d", "p1")
     p1 = ui.get_model_component("p1")
     ui.load_psf('psf', p1)
     self.assertEqual([], p1.thawedpars)
# 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
sh.freeze(bkg)

resid = Map.read(filecounts)
resid.data = sh.get_data_image().y - sh.get_model_image().y
resid_smooth = resid.smooth(width=6)
resid_smooth.plot()

# ### Find and fit the brightest source
예제 #21
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()
예제 #22
0
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)

resid_table = []  #Keep residual images in a list to show them later
resid_smo6 = resid.smooth(radius=6)
resid_smo6.plot(vmax=5, add_cbar=True)
resid_table.append(resid_smo6)
예제 #23
0
 def test_psf_pars_are_frozen(self):
     ui.load_psf('psf', ui.beta2d.p1)
     self.assertEqual([], p1.thawedpars)
예제 #24
0
 def test_psf_pars_are_frozen(self):
     ui.load_psf("psf", ui.beta2d.p1)
     self.assertEqual([], p1.thawedpars)