Example #1
0
def test_sky_model_init():
    with pytest.raises(ValueError) as excinfo:
        spatial_model = SkyGaussian("0 deg", "0 deg", "0.1 deg")
        _ = SkyModel(spectral_model=1234, spatial_model=spatial_model)

    assert "Spectral model" in str(excinfo.value)

    with pytest.raises(ValueError) as excinfo:
        _ = SkyModel(spectral_model=PowerLaw(), spatial_model=1234)

    assert "Spatial model" in str(excinfo.value)
Example #2
0
def get_npred_map():
    position = SkyCoord(0.0, 0.0, frame="galactic", unit="deg")
    energy_axis = MapAxis.from_bounds(1,
                                      100,
                                      nbin=30,
                                      unit="TeV",
                                      name="energy",
                                      interp="log")

    exposure = Map.create(
        binsz=0.02,
        map_type="wcs",
        skydir=position,
        width="5 deg",
        axes=[energy_axis],
        coordsys="GAL",
        unit="cm2 s",
    )

    spatial_model = SkyGaussian("0 deg", "0 deg", sigma="0.2 deg")
    spectral_model = PowerLaw(amplitude="1e-11 cm-2 s-1 TeV-1")
    skymodel = SkyModel(spatial_model=spatial_model,
                        spectral_model=spectral_model)

    exposure.data = 1e14 * np.ones(exposure.data.shape)
    evaluator = MapEvaluator(model=skymodel, exposure=exposure)

    npred = evaluator.compute_npred()
    return npred
Example #3
0
def simulate_map_dataset(random_state=0):
    irfs = load_cta_irfs(
        "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
    )

    skydir = SkyCoord("0 deg", "0 deg", frame="galactic")
    edges = np.logspace(-1, 2, 15) * u.TeV
    energy_axis = MapAxis.from_edges(edges=edges, name="energy")

    geom = WcsGeom.create(skydir=skydir,
                          width=(4, 4),
                          binsz=0.1,
                          axes=[energy_axis],
                          coordsys="GAL")

    gauss = SkyGaussian("0 deg", "0 deg", "0.4 deg", frame="galactic")
    pwl = PowerLaw(amplitude="1e-11 cm-2 s-1 TeV-1")
    skymodel = SkyModel(spatial_model=gauss, spectral_model=pwl, name="source")
    dataset = simulate_dataset(
        skymodel=skymodel,
        geom=geom,
        pointing=skydir,
        irfs=irfs,
        random_state=random_state,
    )
    return dataset
Example #4
0
def sky_model():
    spatial_model = SkyGaussian(lon_0="0.2 deg",
                                lat_0="0.1 deg",
                                sigma="0.2 deg")
    spectral_model = PowerLaw(index=3,
                              amplitude="1e-11 cm-2 s-1 TeV-1",
                              reference="1 TeV")
    return SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)
Example #5
0
    def calc_bk(self, lon0, lat0, sig, amp):
        """
            returns the computed b_k and the diffuse model template.
        """
        # Define sky model to fit the data
        ind = 2.0

        spatial_model = SkyGaussian(lon_0=lon0, lat_0=lat0, sigma=sig)
        spectral_model = PowerLaw(index=ind, amplitude=amp, reference="1 TeV")
        model = SkyModel(spatial_model=spatial_model,
                         spectral_model=spectral_model)

        # For simulations, we can have the same npred map

        b_k = []
        Sk_list = []

        for count, bkg, exp in zip(self.count_list, self.background_list,
                                   self.exposure_list):

            evaluator = MapEvaluator(model=model, exposure=exp)
            npred = evaluator.compute_npred()
            geom = exp.geom
            diffuse_map = WcsNDMap(geom, npred)  #This is Sk
            Bk = bkg.data
            Sk = diffuse_map.data
            Nk = count.data

            not_has_exposure = ~(exp.data > 0)
            not_has_bkg = ~(Bk > 0)

            S_B = np.divide(Sk, Bk)
            S_B[not_has_exposure] = 0.0
            S_B[not_has_bkg] = 0.0

            #Sk is nan for large sep.. to be investigated. temp soln
            #if np.isnan(np.sum(S_B)):
            #    S_B=np.zeros(S_B.shape)

            delta = np.power(np.sum(Nk) / np.sum(Bk),
                             2.0) - 4.0 * np.sum(S_B) / np.sum(Bk)
            #print(np.sum(Nk),np.sum(Bk),np.sum(Sk),np.sum(S_B), delta)
            #print("delta is %f for obs no %s",delta,k)
            #bk1=(np.sum(Nk)/np.sum(Bk) - np.sqrt(delta))/2.0
            bk2 = (np.sum(Nk) / np.sum(Bk) + np.sqrt(delta)) / 2.0
            b_k.append(bk2)
            Sk_list.append(diffuse_map)

        return Sk_list, b_k
Example #6
0
def test_simulate():
    irfs = load_cta_irfs(
        "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
    )

    # Define sky model to simulate the data
    spatial_model = SkyGaussian(lon_0="0 deg", lat_0="0 deg", sigma="0.2 deg")
    spectral_model = PowerLaw(index=2,
                              amplitude="1e-11 cm-2 s-1 TeV-1",
                              reference="1 TeV")
    sky_model_simu = SkyModel(spatial_model=spatial_model,
                              spectral_model=spectral_model)

    # Define map geometry
    axis = MapAxis.from_edges(np.logspace(-1, 1.0, 20),
                              unit="TeV",
                              name="energy",
                              interp="log")
    geom = WcsGeom.create(skydir=(0, 0),
                          binsz=0.025,
                          width=(1, 1),
                          coordsys="GAL",
                          axes=[axis])

    # Define some observation parameters
    pointing = SkyCoord(0 * u.deg, 0 * u.deg, frame="galactic")

    dataset = simulate_dataset(sky_model_simu,
                               geom,
                               pointing,
                               irfs,
                               livetime=10 * u.h,
                               random_state=42)

    assert isinstance(dataset, MapDataset)
    assert isinstance(dataset.model, SkyModels)

    assert dataset.counts.data.dtype is np.dtype("int")
    assert_allclose(dataset.counts.data[5, 20, 20], 5)
    assert_allclose(dataset.exposure.data[5, 20, 20], 16122681639.856329)
    assert_allclose(dataset.background_model.map.data[5, 20, 20],
                    0.976554,
                    rtol=1e-5)
    assert_allclose(dataset.psf.data[5, 32, 32], 0.044402823)
    assert_allclose(dataset.edisp.data.data[10, 10], 0.662208, rtol=1e-5)
Example #7
0
def make_example_2():
    spatial = SkyGaussian("0 deg", "0 deg", "1 deg")
    model = SkyModel(spatial, PowerLaw())
    models = SkyModels([model])
    models.to_yaml(DATA_PATH / "example2.yaml")
Example #8
0
 def sky_model(self):
     """Source sky model (`~gammapy.cube.models.SkyModel`)."""
     spatial_model = self.spatial_model
     spectral_model = self.spectral_model
     return SkyModel(spatial_model, spectral_model, name=self.name)
Example #9
0
irfs = load_cta_irfs(
    "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits")

# In[ ]:

# Define sky model to simulate the data
spatial_model = SkyGaussian(lon_0="0 deg", lat_0="0 deg", sigma="0.2 deg")

spectral_model = ExponentialCutoffPowerLaw(
    index=2,
    amplitude="3e-12 cm-2 s-1 TeV-1",
    reference="1 TeV",
    lambda_="0.05 TeV-1",
)

sky_model_simu = SkyModel(spatial_model=spatial_model,
                          spectral_model=spectral_model)
print(sky_model_simu)

# In[ ]:

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1, 2, 30),
                          unit="TeV",
                          name="energy",
                          interp="log")
geom = WcsGeom.create(skydir=(0, 0),
                      binsz=0.05,
                      width=(2, 2),
                      coordsys="GAL",
                      axes=[axis])
Example #10
0
# ## Simulate

# In[ ]:

filename = (
    "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits")
irfs = load_cta_irfs(filename)

# In[ ]:

# Define sky model to simulate the data
spatial_model = SkyGaussian(lon_0="0.2 deg", lat_0="0.1 deg", sigma="0.3 deg")
spectral_model = PowerLaw(index=3,
                          amplitude="1e-11 cm-2 s-1 TeV-1",
                          reference="1 TeV")
sky_model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model)
print(sky_model)

# In[ ]:

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10),
                          unit="TeV",
                          name="energy",
                          interp="log")
geom = WcsGeom.create(skydir=(0, 0),
                      binsz=0.02,
                      width=(5, 4),
                      coordsys="GAL",
                      axes=[axis])
Example #11
0
def sky_model():
    spatial_model = SkyGaussian(lon_0="3 deg", lat_0="4 deg", sigma="3 deg")
    spectral_model = PowerLaw(index=2,
                              amplitude="1e-11 cm-2 s-1 TeV-1",
                              reference="1 TeV")
    return SkyModel(spatial_model, spectral_model, name="source-1")
Example #12
0
# In[ ]:


model = SkyDiffuseCube(diffuse_galactic)

evaluator = MapEvaluator(model=model, exposure=exposure, psf=psf_kernel)

background_gal = counts.copy(data=evaluator.compute_npred())
background_gal.sum_over_axes().plot()
print("Background counts from Galactic diffuse: ", background_gal.data.sum())


# In[ ]:


model = SkyModel(SkyDiffuseConstant(), diffuse_iso)

evaluator = MapEvaluator(model=model, exposure=exposure, psf=psf_kernel)

background_iso = counts.copy(data=evaluator.compute_npred())
background_iso.sum_over_axes().plot()
print("Background counts from isotropic diffuse: ", background_iso.data.sum())


# In[ ]:


background = background_gal.copy()
background.data += background_iso.data

Example #13
0
spatial_model_1 = SkyGaussian(
    lon_0=lon_0_1 * u.deg, lat_0=lat_0_1 * u.deg, sigma="0.3 deg"
)
spatial_model_2 = SkyGaussian(
    lon_0=lon_0_2 * u.deg, lat_0=lat_0_2 * u.deg, sigma="0.2 deg"
)

spectral_model_1 = PowerLaw(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)

spectral_model_2 = PowerLaw(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)

sky_model_1 = SkyModel(spatial_model=spatial_model_1, spectral_model=spectral_model_1)

sky_model_2 = SkyModel(spatial_model=spatial_model_2, spectral_model=spectral_model_2)

compound_model = sky_model_1 + sky_model_2

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10), unit="TeV")
geom = WcsGeom.create(
    skydir=(0, 0), binsz=0.02, width=(2, 2), coordsys="GAL", axes=[axis]
)


# Define some observation parameters
# we are not simulating many pointings / observations
pointing = SkyCoord(0.2, 0.5, unit="deg", frame="galactic")
Example #14
0
mask = Map.from_geom(maps["counts"].geom)

coords = mask.geom.get_coord()
mask.data = coords["energy"] > 0.3

# ### Model fit
#
# No we are ready for the actual likelihood fit. We first define the model as a combination of a point source with a powerlaw:

# In[ ]:

spatial_model = SkyPointSource(lon_0="0.01 deg", lat_0="0.01 deg")
spectral_model = PowerLaw(index=2.2,
                          amplitude="3e-12 cm-2 s-1 TeV-1",
                          reference="1 TeV")
model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)

# Often, it is useful to fit the normalisation (and also the tilt) of the background. To do so, we have to define the background as a model. In this example, we will keep the tilt fixed and the norm free.

# In[ ]:

background_model = BackgroundModel(maps["background"], norm=1.1, tilt=0.0)
background_model.parameters["norm"].frozen = False
background_model.parameters["tilt"].frozen = True

# Now we set up the `MapDataset` object by passing the prepared maps, IRFs as well as the model:

# In[ ]:

dataset = MapDataset(
    model=model,
Example #15
0
# In[ ]:

coords = maps["counts"].geom.get_coord()
mask = coords["energy"] > 0.3

# ### Model fit
#
# No we are ready for the actual likelihood fit. We first define the model as a combination of a point source with a powerlaw:

# In[ ]:

spatial_model = SkyPointSource(lon_0="0.01 deg", lat_0="0.01 deg")
spectral_model = PowerLaw(index=2.2,
                          amplitude="3e-12 cm-2 s-1 TeV-1",
                          reference="1 TeV")
model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)

# Often, it is useful to fit the normalisation (and also the tilt) of the background. To do so, we have to define the background as a model. In this example, we will keep the tilt fixed and the norm free.

# In[ ]:

background_model = BackgroundModel(maps["background"], norm=1.1, tilt=0.0)
background_model.parameters["norm"].frozen = False
background_model.parameters["tilt"].frozen = True

# Now we set up the `MapDataset` object by passing the prepared maps, IRFs as well as the model:

# In[ ]:

dataset = MapDataset(
    model=model,