Ejemplo n.º 1
0
 def reference_model_default(self):
     """Reference model default (`SkyModel`) """
     return SkyModel(PowerLawSpectralModel(index=2))
Ejemplo n.º 2
0
def data_prep():
    data_store = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1/")
    OBS_ID = 23523
    obs_ids = OBS_ID * np.ones(N_OBS)
    observations = data_store.get_observations(obs_ids)
    target_position = SkyCoord(ra=83.63, dec=22.01, unit="deg", frame="icrs")
    on_region_radius = Angle("0.11 deg")
    on_region = CircleSkyRegion(center=target_position,
                                radius=on_region_radius)

    exclusion_region = CircleSkyRegion(
        center=SkyCoord(183.604, -8.708, unit="deg", frame="galactic"),
        radius=0.5 * u.deg,
    )

    skydir = target_position.galactic
    exclusion_mask = Map.create(npix=(150, 150),
                                binsz=0.05,
                                skydir=skydir,
                                proj="TAN",
                                frame="galactic")

    mask = exclusion_mask.geom.region_mask([exclusion_region], inside=False)
    exclusion_mask.data = mask

    e_reco = MapAxis.from_bounds(0.1, 40, nbin=40, interp="log",
                                 unit="TeV").edges
    e_true = MapAxis.from_bounds(0.05, 100, nbin=200, interp="log",
                                 unit="TeV").edges

    empty = SpectrumDatasetOnOff.create(
        region=on_region,
        e_reco=e_reco,
        e_true=e_true,
    )

    dataset_maker = SpectrumDatasetMaker(containment_correction=True,
                                         selection=["counts", "aeff", "edisp"])
    bkg_maker = ReflectedRegionsBackgroundMaker(exclusion_mask=exclusion_mask)
    safe_mask_masker = SafeMaskMaker(methods=["aeff-max"], aeff_percent=10)

    spectral_model = PowerLawSpectralModel(index=2,
                                           amplitude=2e-11 *
                                           u.Unit("cm-2 s-1 TeV-1"),
                                           reference=1 * u.TeV)
    spatial_model = PointSpatialModel(lon_0=target_position.ra,
                                      lat_0=target_position.dec,
                                      frame="icrs")
    spatial_model.lon_0.frozen = True
    spatial_model.lat_0.frozen = True

    sky_model = SkyModel(spatial_model=spatial_model,
                         spectral_model=spectral_model,
                         name="")

    # Data preparation
    datasets = []

    for idx, observation in enumerate(observations):
        dataset = empty.copy(name=f"dataset{idx}")
        dataset = dataset_maker.run(dataset=dataset, observation=observation)
        dataset_on_off = bkg_maker.run(dataset, observation)
        dataset_on_off = safe_mask_masker.run(dataset_on_off, observation)
        dataset_on_off.models = sky_model
        datasets.append(dataset_on_off)

    return Datasets(datasets)
Ejemplo n.º 3
0
    def run_region(self, kr, lon, lat, radius):
        #    TODO: for now we have to read/create the allsky maps each in each job
        #    because we can't pickle <functools._lru_cache_wrapper object
        #    send this back to init when fixed

        log.info(f"ROI {kr}: loading data")

        # exposure
        exposure_hpx = Map.read(
            "$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_exposure_cube_hpx.fits.gz")
        exposure_hpx.unit = "cm2 s"

        # iem
        iem_filepath = BASE_PATH / "data" / "gll_iem_v06_extrapolated.fits"
        iem_fermi_extra = Map.read(iem_filepath)
        # norm=1.1, tilt=0.03 see paper appendix A
        model_iem = SkyModel(
            PowerLawNormSpectralModel(norm=1.1, tilt=0.03),
            TemplateSpatialModel(iem_fermi_extra, normalize=False),
            name="iem_extrapolated",
        )

        # ROI
        roi_time = time()
        ROI_pos = SkyCoord(lon, lat, frame="galactic", unit="deg")
        width = 2 * (radius + self.psf_margin)

        # Counts
        counts = Map.create(
            skydir=ROI_pos,
            width=width,
            proj="CAR",
            frame="galactic",
            binsz=1 / 8.0,
            axes=[self.energy_axis],
            dtype=float,
        )
        counts.fill_by_coord({
            "skycoord": self.events.radec,
            "energy": self.events.energy
        })

        axis = MapAxis.from_nodes(counts.geom.axes[0].center,
                                  name="energy_true",
                                  unit="GeV",
                                  interp="log")
        wcs = counts.geom.wcs
        geom = WcsGeom(wcs=wcs, npix=counts.geom.npix, axes=[axis])
        coords = geom.get_coord()
        # expo
        data = exposure_hpx.interp_by_coord(coords)
        exposure = WcsNDMap(geom, data, unit=exposure_hpx.unit, dtype=float)

        # read PSF
        psf_kernel = PSFKernel.from_table_psf(self.psf,
                                              geom,
                                              max_radius=self.psf_margin *
                                              u.deg)

        # Energy Dispersion
        e_true = exposure.geom.axes[0].edges
        e_reco = counts.geom.axes[0].edges
        edisp = EDispKernel.from_diagonal_response(e_true=e_true,
                                                   e_reco=e_reco)

        # fit mask
        if coords["lon"].min() < 90 * u.deg and coords["lon"].max(
        ) > 270 * u.deg:
            coords["lon"][coords["lon"].value > 180] -= 360 * u.deg
        mask = (
            (coords["lon"] >= coords["lon"].min() + self.psf_margin * u.deg)
            & (coords["lon"] <= coords["lon"].max() - self.psf_margin * u.deg)
            & (coords["lat"] >= coords["lat"].min() + self.psf_margin * u.deg)
            & (coords["lat"] <= coords["lat"].max() - self.psf_margin * u.deg))
        mask_fermi = WcsNDMap(counts.geom, mask)

        log.info(f"ROI {kr}: pre-computing diffuse")

        # IEM
        eval_iem = MapEvaluator(model=model_iem,
                                exposure=exposure,
                                psf=psf_kernel,
                                edisp=edisp)
        bkg_iem = eval_iem.compute_npred()

        # ISO
        eval_iso = MapEvaluator(model=self.model_iso,
                                exposure=exposure,
                                edisp=edisp)
        bkg_iso = eval_iso.compute_npred()

        # merge iem and iso, only one local normalization is fitted
        dataset_name = "3FHL_ROI_num" + str(kr)
        background_total = bkg_iem + bkg_iso
        background_model = BackgroundModel(background_total,
                                           name="bkg_iem+iso",
                                           datasets_names=[dataset_name])
        background_model.parameters["norm"].min = 0.0

        # Sources model
        in_roi = self.FHL3.positions.galactic.contained_by(wcs)
        FHL3_roi = []
        for ks in range(len(self.FHL3.table)):
            if in_roi[ks] == True:
                model = self.FHL3[ks].sky_model()
                model.spatial_model.parameters.freeze_all()  # freeze spatial
                model.spectral_model.parameters["amplitude"].min = 0.0
                if isinstance(model.spectral_model, PowerLawSpectralModel):
                    model.spectral_model.parameters["index"].min = 0.1
                    model.spectral_model.parameters["index"].max = 10.0
                else:
                    model.spectral_model.parameters["alpha"].min = 0.1
                    model.spectral_model.parameters["alpha"].max = 10.0

                FHL3_roi.append(model)
        model_total = Models([background_model] + FHL3_roi)

        # Dataset
        dataset = MapDataset(
            models=model_total,
            counts=counts,
            exposure=exposure,
            psf=psf_kernel,
            edisp=edisp,
            mask_fit=mask_fermi,
            name=dataset_name,
        )
        cat_stat = dataset.stat_sum()
        datasets = Datasets([dataset])

        log.info(f"ROI {kr}: running fit")
        fit = Fit(datasets)
        results = fit.run(**self.optimize_opts)
        print("ROI_num", str(kr), "\n", results)
        fit_stat = datasets.stat_sum()

        if results.message != "Optimization failed.":
            datasets.write(path=Path(self.resdir),
                           prefix=dataset.name,
                           overwrite=True)
            np.savez(
                self.resdir / f"3FHL_ROI_num{kr}_fit_infos.npz",
                message=results.message,
                stat=[cat_stat, fit_stat],
            )

            exec_time = time() - roi_time
            print("ROI", kr, " time (s): ", exec_time)

            log.info(f"ROI {kr}: running flux points")
            for model in FHL3_roi:
                if (self.FHL3[model.name].data["ROI_num"] == kr
                        and self.FHL3[model.name].data["Signif_Avg"] >=
                        self.sig_cut):
                    flux_points = FluxPointsEstimator(
                        e_edges=self.El_flux,
                        source=model.name,
                        n_sigma_ul=2,
                    ).run(datasets=datasets)
                    filename = self.resdir / f"{model.name}_flux_points.fits"
                    flux_points.write(filename, overwrite=True)

            exec_time = time() - roi_time - exec_time
            print("ROI", kr, " Flux points time (s): ", exec_time)
Ejemplo n.º 4
0
# In[ ]:

model_diffuse = SkyDiffuseCube(diffuse_galactic, name="diffuse")
eval_diffuse = MapEvaluator(model=model_diffuse,
                            exposure=exposure,
                            psf=psf_kernel,
                            edisp=edisp)

background_gal = eval_diffuse.compute_npred()

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

# In[ ]:

model_iso = SkyModel(ConstantSpatialModel(), diffuse_iso, name="diffuse-iso")

eval_iso = MapEvaluator(model=model_iso, exposure=exposure, edisp=edisp)

background_iso = eval_iso.compute_npred()

background_iso.sum_over_axes().plot(add_cbar=True)
print("Background counts from isotropic diffuse: ", background_iso.data.sum())

# In[ ]:

background_total = background_iso + background_gal

# ## Excess and flux
#
# Let's compute an excess and flux image, by subtracting the background, and summing over the energy axis.
Ejemplo n.º 5
0
def make_example_2():
    spatial = GaussianSpatialModel(lon_0="0 deg", lat_0="0 deg", sigma="1 deg")
    model = SkyModel(PowerLawSpectralModel(), spatial)
    models = Models([model])
    models.write(DATA_PATH / "example2.yaml")
Ejemplo n.º 6
0
plt.plot(lons, profile / profile.max(), alpha=0.5)
plt.xlabel("Radius (deg)")
plt.ylabel("Profile (A.U.)")

edge_min, edge_max = r_0 * (1 - edge_width / 2.), r_0 * (1 + edge_width / 2.)
with quantity_support():
    plt.vlines([edge_min, edge_max], 0, 1, linestyles=["--"], color="k")
    plt.annotate("", xy=(edge_min, 0.5), xytext=(edge_min + r_0 * edge_width, 0.5),
                 arrowprops=dict(arrowstyle="<->", lw=2))
    plt.text(0.2, 0.53, "Edge width", ha="center", size=12)
    margin = 0.02 * u.deg
    plt.hlines([0.95], edge_min - margin, edge_min + margin, linestyles=["-"], color="k")
    plt.text(edge_min + margin, 0.95, "95%", size=12, va="center")
    plt.hlines([0.05], edge_max - margin, edge_max + margin, linestyles=["-"], color="k")
    plt.text(edge_max - margin, 0.05, "5%", size=12, va="center", ha="right")
    plt.show()

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

pwl = PowerLawSpectralModel()
gauss = DiskSpatialModel()

model = SkyModel(spectral_model=pwl, spatial_model=gauss, name="pwl-disk-model")
models = Models([model])

print(models.to_yaml())

Ejemplo n.º 7
0
def test_sky_model_create():
    m = SkyModel.create("pl", "point", name="my-source")
    assert isinstance(m.spatial_model, PointSpatialModel)
    assert isinstance(m.spectral_model, PowerLawSpectralModel)
    assert m.name == "my-source"
.. _LightCurve-temporal-model:

LightCurve Temporal Model
=========================

This model parametrises a lightCurve time model.


"""

from gammapy.modeling.models import LightCurveTemplateTemporalModel, SkyModel, Models
from astropy.time import Time

time_range = [Time("59100", format="mjd"), Time("59365", format="mjd")]
path = "$GAMMAPY_DATA/tests/models/light_curve/lightcrv_PKSB1222+216.fits"
light_curve_model = LightCurveTemplateTemporalModel.read(path)
light_curve_model.plot(time_range)

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:
from gammapy.modeling.models import PowerLawSpectralModel

model = SkyModel(spectral_model=PowerLawSpectralModel(),
                 temporal_model=light_curve_model,
                 name="light_curve_model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 9
0
# %%
# Example plot
# ------------
# Here is an example plot of the model:

from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import Models, SkyModel, SmoothBrokenPowerLawSpectralModel

energy_range = [0.1, 100] * u.TeV
model = SmoothBrokenPowerLawSpectralModel(
    index1=1.5,
    index2=2.5,
    amplitude="1e-12 TeV-1 cm-2 s-1",
    ebreak="1 TeV",
    reference="1 TeV",
    beta=1,
)
model.plot(energy_range)
plt.grid(which="both")

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model, name="smooth-broken-power-law-model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 10
0
    \phi(E) = \frac{N_0}{\sigma \sqrt{2\pi}}  \exp{ \frac{- \left( E-\bar{E} \right)^2 }{2 \sigma^2} }

"""

# %%
# Example plot
# ------------
# Here is an example plot of the model:

from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import GaussianSpectralModel, Models, SkyModel

energy_range = [0.1, 100] * u.TeV
model = GaussianSpectralModel(norm="1e-2 cm-2 s-1",
                              mean=2 * u.TeV,
                              sigma=0.2 * u.TeV)
model.plot(energy_range)
plt.grid(which="both")
plt.ylim(1e-24, 1e-1)

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model, name="gaussian-model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 11
0
# Define the source model - Use a pointsource + integrated power law model to directly get flux

spatial_model = PointSpatialModel(lon_0=target_position.ra,
                                  lat_0=target_position.dec,
                                  frame="icrs")

spectral_model = PowerLawSpectralModel(
    index=2.6,
    amplitude=2.0e-11 * u.Unit("1 / (cm2 s TeV)"),
    reference=1 * u.TeV,
)
spectral_model.parameters["index"].frozen = False

sky_model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="")
sky_model.parameters["lon_0"].frozen = True
sky_model.parameters["lat_0"].frozen = True

# ### Make the map datasets
#
# The following function is in charge of the MapDataset production. It will later be fully covered in the data reduction chain

# In[ ]:


# psf_kernel and MapMaker for each segment
def make_map_dataset(observations,
                     target_pos,
                     geom,
Ejemplo n.º 12
0
from astropy import units as u
from astropy.time import Time
import matplotlib.pyplot as plt
from gammapy.modeling.models import (
    Models,
    PowerLawSpectralModel,
    PowerLawTemporalModel,
    SkyModel,
)

time_range = [Time.now(), Time.now() + 2 * u.d]
pl_model = PowerLawTemporalModel(alpha=-2.0,
                                 t_ref=(time_range[0].mjd - 0.1) * u.d)
pl_model.plot(time_range)
plt.grid(which="both")
plt.yscale("log")

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(
    spectral_model=PowerLawSpectralModel(),
    temporal_model=pl_model,
    name="powerlaw-model",
)
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 13
0
    lon_0=lon_0_1 * u.deg, lat_0=lat_0_1 * u.deg, sigma="0.3 deg", frame="galactic"
)
spatial_model_2 = GaussianSpatialModel(
    lon_0=lon_0_2 * u.deg, lat_0=lat_0_2 * u.deg, sigma="0.2 deg", frame="galactic"
)

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

spectral_model_2 = PowerLawSpectralModel(
    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, name="source-1"
)

sky_model_2 = SkyModel(
    spatial_model=spatial_model_2, spectral_model=spectral_model_2, name="source-2"
)

models = sky_model_1 + sky_model_2

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

Ejemplo n.º 14
0
    def from_maps(cls,
                  maps,
                  sed_type=None,
                  reference_model=None,
                  gti=None,
                  meta=None):
        """Create FluxMaps from a dictionary of maps.

        Parameters
        ----------
        maps : `Maps`
            Maps object containing the input maps.
        sed_type : str
            SED type of the input maps. Default is `Likelihood`
        reference_model : `~gammapy.modeling.models.SkyModel`, optional
            Reference model to use for conversions. Default in None.
            If None, a model consisting of a point source with a power
            law spectrum of index 2 is assumed.
        gti : `~gammapy.data.GTI`
            Maps GTI information. Default is None.
        meta : `dict`
            Meta dict.

        Returns
        -------
        flux_maps : `~gammapy.estimators.FluxMaps`
            Flux maps object.
        """
        if sed_type is None:
            sed_type = cls._guess_sed_type(maps.keys())

        if sed_type is None:
            raise ValueError("Specifying the sed type is required")

        cls._validate_data(data=maps, sed_type=sed_type)

        if sed_type == "likelihood":
            return cls(data=maps,
                       reference_model=reference_model,
                       gti=gti,
                       meta=meta)

        if reference_model is None:
            log.warning(
                "No reference model set for FluxMaps. Assuming point source with E^-2 spectrum."
            )
            reference_model = cls.reference_model_default
        elif isinstance(reference_model, SpectralModel):
            reference_model = SkyModel(reference_model)

        map_ref = maps[sed_type]
        energy_axis = map_ref.geom.axes["energy"]

        with np.errstate(invalid="ignore", divide="ignore"):
            fluxes = reference_model.spectral_model.reference_fluxes(
                energy_axis=energy_axis)

        # TODO: handle reshaping in MapAxis
        factor = fluxes[f"ref_{sed_type}"].to(map_ref.unit)[cls._expand_slice]

        data = dict()
        data["norm"] = map_ref / factor

        for key in OPTIONAL_QUANTITIES[sed_type]:
            if key in maps:
                norm_type = key.replace(sed_type, "norm")
                data[norm_type] = maps[key] / factor

        # We add the remaining maps
        for key in OPTIONAL_QUANTITIES_COMMON:
            if key in maps:
                data[key] = maps[key]

        return cls(data=data,
                   reference_model=reference_model,
                   gti=gti,
                   meta=meta)
Ejemplo n.º 15
0
# ------------
# Here is an example plot of the model:

from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import (
    Models,
    PiecewiseNormSpectralModel,
    PowerLawSpectralModel,
    SkyModel,
)

energy_range = [0.1, 100] * u.TeV
model = PiecewiseNormSpectralModel(
    energy=[0.1, 1, 3, 10, 30, 100] * u.TeV,
    norms=[1, 3, 8, 10, 8, 2],
)
model.plot(energy_range, flux_unit="")
plt.grid(which="both")

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = model * PowerLawSpectralModel()
model = SkyModel(spectral_model=model, name="piecewise-norm-model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 16
0
def data_prep():
    data_store = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1/")
    OBS_ID = 23523
    obs_ids = OBS_ID * np.ones(N_OBS)
    observations = data_store.get_observations(obs_ids)

    time_intervals = [(obs.tstart, obs.tstop) for obs in observations]
    target_position = SkyCoord(ra=83.63308, dec=22.01450, unit="deg")

    emin, emax = [0.7, 10] * u.TeV
    energy_axis = MapAxis.from_bounds(emin.value,
                                      emax.value,
                                      10,
                                      unit="TeV",
                                      name="energy",
                                      interp="log")
    geom = WcsGeom.create(
        skydir=target_position,
        binsz=0.02,
        width=(2, 2),
        coordsys="CEL",
        proj="CAR",
        axes=[energy_axis],
    )

    energy_axis_true = MapAxis.from_bounds(0.1,
                                           20,
                                           20,
                                           unit="TeV",
                                           name="energy",
                                           interp="log")
    offset_max = 2 * u.deg

    datasets = []

    maker = MapDatasetMaker(offset_max=offset_max)
    safe_mask_maker = SafeMaskMaker(methods=["offset-max"],
                                    offset_max=offset_max)

    for time_interval in time_intervals:
        observations = observations.select_time(time_interval)

        # Proceed with further analysis only if there are observations
        # in the selected time window
        if len(observations) == 0:
            log.warning(f"No observations in time interval: {time_interval}")
            continue

        stacked = MapDataset.create(geom=geom,
                                    energy_axis_true=energy_axis_true)

        for obs in observations:
            dataset = maker.run(stacked, obs)
            dataset = safe_mask_maker.run(dataset, obs)
            stacked.stack(dataset)

        stacked.edisp = stacked.edisp.get_energy_dispersion(
            position=target_position, e_reco=energy_axis.edges)

        stacked.psf = stacked.psf.get_psf_kernel(position=target_position,
                                                 geom=stacked.exposure.geom,
                                                 max_radius="0.3 deg")

        datasets.append(stacked)

    spatial_model = PointSpatialModel(lon_0=target_position.ra,
                                      lat_0=target_position.dec,
                                      frame="icrs")
    spatial_model.lon_0.frozen = True
    spatial_model.lat_0.frozen = True

    spectral_model = PowerLawSpectralModel(index=2.6,
                                           amplitude=2.0e-11 *
                                           u.Unit("1 / (cm2 s TeV)"),
                                           reference=1 * u.TeV)
    spectral_model.index.frozen = False

    sky_model = SkyModel(spatial_model=spatial_model,
                         spectral_model=spectral_model,
                         name="")

    for dataset in datasets:
        model = sky_model.copy(name="crab")
        dataset.model = model

    return datasets
Ejemplo n.º 17
0
"""

# %%
# Example plot
# ------------
# Here is an example plot of the model:

from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import ExpCutoffPowerLawSpectralModel, Models, SkyModel

energy_range = [0.1, 100] * u.TeV
model = ExpCutoffPowerLawSpectralModel(
    amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
    index=2,
    lambda_=0.1 * u.Unit("TeV-1"),
    reference=1 * u.TeV,
)
model.plot(energy_range)
plt.grid(which="both")

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model, name="exp-cutoff-power-law-model")
models = Models([model])

print(models.to_yaml())
mDM = 40000 * u.Unit("GeV")
channel = "b"
xsection = 1e-26 * u.Unit("cm3 s-1")
redshift = 0
RATIO = 2.71

# **Define 3D Sky Model**
DarkMatterAnnihilationSpectralModel.THERMAL_RELIC_CROSS_SECTION = xsection
flux_model = DarkMatterAnnihilationSpectralModel(mass=mDM,
                                                 channel=channel,
                                                 jfactor=JFAC)

spatial_model = TemplateSpatialModel.read(jfactor_filename)

sky_model = SkyModel(spatial_model=spatial_model,
                     spectral_model=flux_model,
                     name="model-simu")

bkg_model = FoVBackgroundModel(dataset_name="dataset-simu")

models = Models([sky_model, bkg_model])

# ## Declare observation values

pointing = src_pos
livetime = 100 * u.hour
offset = 2.0 * u.deg
#offset = 0.5 * u.deg

# Create an in-memory observation
obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
Ejemplo n.º 19
0
from astropy import units as u
from astropy.time import Time
import matplotlib.pyplot as plt
# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:
from gammapy.modeling.models import (
    ExpDecayTemporalModel,
    Models,
    PowerLawSpectralModel,
    SkyModel,
)

t0 = "5 h"
t_ref = Time("2020-10-01")
time_range = [t_ref, t_ref + 1 * u.d]
expdecay_model = ExpDecayTemporalModel(t_ref=t_ref.mjd * u.d, t0=t0)
expdecay_model.plot(time_range)
plt.grid(which="both")

model = SkyModel(
    spectral_model=PowerLawSpectralModel(),
    temporal_model=expdecay_model,
    name="expdecay_model",
)
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 20
0
    def make_prof(self, sp_datasets):
        """ Utility to make the profile in each region

        Parameters
        ----------
        sp_datasets : `~gammapy.datasets.MapDatasets` of `~gammapy.datasets.SpectrumDataset` or \
        `~gammapy.datasets.SpectrumDatasetOnOff`
            the dataset to use for profile extraction

        Returns
        --------
        results : list of dictionary
            the list of results (list of keys: x_min, x_ref, x_max, alpha, counts, background, excess, ts, sqrt_ts, \
            err, errn, errp, ul, exposure, solid_angle)
        """
        results = []

        distance = self._get_projected_distance()

        for index, spds in enumerate(sp_datasets):
            old_model = None
            if spds.models is not None:
                old_model = spds.models
            spds.models = SkyModel(spectral_model=self.spectrum)
            e_reco = spds.counts.geom.axes["energy"].edges

            # ToDo: When the function to_spectrum_dataset will manage the masks, use the following line
            # mask = spds.mask if spds.mask is not None else slice(None)
            mask = slice(None)
            if isinstance(spds, SpectrumDatasetOnOff):
                stats = WStatCountsStatistic(
                    spds.counts.data[mask][:, 0, 0],
                    spds.counts_off.data[mask][:, 0, 0],
                    spds.alpha.data[mask][:, 0, 0],
                )

            else:
                stats = CashCountsStatistic(
                    spds.counts.data[mask][:, 0, 0],
                    spds.background_model.evaluate().data[mask][:, 0, 0],
                )

            result = {
                "x_min": distance.edges[index],
                "x_max": distance.edges[index + 1],
                "x_ref": distance.center[index],
                "energy_edge": e_reco,
            }
            if isinstance(spds, SpectrumDatasetOnOff):
                result["alpha"] = stats.alpha
            result.update(
                {
                    "counts": stats.n_on,
                    "background": stats.background,
                    "excess": stats.excess,
                }
            )

            result["ts"] = stats.delta_ts
            result["sqrt_ts"] = stats.significance

            result["err"] = stats.error * self.n_sigma

            if "errn-errp" in self.selection_optional:
                result["errn"] = stats.compute_errn(self.n_sigma)
                result["errp"] = stats.compute_errp(self.n_sigma)

            if "ul" in self.selection_optional:
                result["ul"] = stats.compute_upper_limit(self.n_sigma_ul)

            npred = spds.npred().data[mask][:, 0, 0]
            e_reco_lo = e_reco[:-1]
            e_reco_hi = e_reco[1:]
            flux = (
                stats.excess
                / npred
                * spds.models[0].spectral_model.integral(e_reco_lo, e_reco_hi).value
            )
            result["flux"] = flux

            result["flux_err"] = stats.error / stats.excess * flux

            if "errn-errp" in self.selection_optional:
                result["flux_errn"] = np.abs(result["errn"]) / stats.excess * flux
                result["flux_errp"] = result["errp"] / stats.excess * flux

            if "ul" in self.selection_optional:
                result["flux_ul"] = result["ul"] / stats.excess * flux

            solid_angle = spds.counts.geom.solid_angle()
            result["solid_angle"] = (
                np.full(result["counts"].shape, solid_angle.to_value("sr")) * u.sr
            )

            results.append(result)
            if old_model is not None:
                spds.models = old_model

        return results
Ejemplo n.º 21
0
# ------------
# Here is an example plot of the model:

from astropy import units as u
from astropy.time import Time
import matplotlib.pyplot as plt
# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:
from gammapy.modeling.models import (
    ConstantTemporalModel,
    Models,
    PowerLawSpectralModel,
    SkyModel,
)

time_range = [Time.now(), Time.now() + 1 * u.d]
constant_model = ConstantTemporalModel(const=1)
constant_model.plot(time_range)
plt.grid(which="both")

model = SkyModel(
    spectral_model=PowerLawSpectralModel(),
    temporal_model=constant_model,
    name="constant-model",
)
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 22
0
from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import (
    Models,
    SkyModel,
    SuperExpCutoffPowerLaw4FGLSpectralModel,
)

energy_range = [0.1, 100] * u.TeV
model = SuperExpCutoffPowerLaw4FGLSpectralModel(
    index_1=1,
    index_2=2,
    amplitude="1e-12 TeV-1 cm-2 s-1",
    reference="1 TeV",
    expfactor=1e-2,
)
model.plot(energy_range)
plt.grid(which="both")
plt.ylim(1e-24, 1e-10)

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model,
                 name="super-exp-cutoff-power-law-4fgl-model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 23
0
    def test_plot_fit(self):
        dataset = self.dataset.copy()
        dataset.models = SkyModel(spectral_model=PowerLawSpectralModel())

        with mpl_plot_check():
            dataset.plot_fit()
Ejemplo n.º 24
0
def reference_model():
    return SkyModel(spatial_model=PointSpatialModel(),
                    spectral_model=PowerLawSpectralModel(index=2))
Ejemplo n.º 25
0
def make_datasets_example():
    # Define which data to use and print some information

    energy_axis = MapAxis.from_edges(
        np.logspace(-1.0, 1.0, 4), unit="TeV", name="energy", interp="log"
    )
    geom0 = WcsGeom.create(
        skydir=(0, 0),
        binsz=0.1,
        width=(1, 1),
        frame="galactic",
        proj="CAR",
        axes=[energy_axis],
    )
    geom1 = WcsGeom.create(
        skydir=(1, 0),
        binsz=0.1,
        width=(1, 1),
        frame="galactic",
        proj="CAR",
        axes=[energy_axis],
    )
    geoms = [geom0, geom1]

    sources_coords = [(0, 0), (0.9, 0.1)]
    names = ["gc", "g09"]
    models = []

    for idx, (lon, lat) in enumerate(sources_coords):
        spatial_model = PointSpatialModel(
            lon_0=lon * u.deg, lat_0=lat * u.deg, frame="galactic"
        )
        spectral_model = ExpCutoffPowerLawSpectralModel(
            index=2 * u.Unit(""),
            amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
            reference=1.0 * u.TeV,
            lambda_=0.1 / u.TeV,
        )
        model_ecpl = SkyModel(
            spatial_model=spatial_model, spectral_model=spectral_model, name=names[idx]
        )
        models.append(model_ecpl)

    # test to link a spectral parameter
    params0 = models[0].spectral_model.parameters
    params1 = models[1].spectral_model.parameters
    params0.link("reference", params1["reference"])
    # update the sky model
    models[0].parameters.link("reference", params1["reference"])

    obs_ids = [110380, 111140, 111159]
    data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps/")

    diffuse_model = SkyDiffuseCube.read(
        "$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits"
    )

    datasets_list = []
    for idx, geom in enumerate(geoms):
        observations = data_store.get_observations(obs_ids)

        stacked = MapDataset.create(geom=geom)
        stacked.background_model.name = "background_irf_" + names[idx]

        maker = MapDatasetMaker(offset_max=4.0 * u.deg)

        for obs in observations:
            dataset = maker.run(stacked, obs)
            stacked.stack(dataset)

        stacked.psf = stacked.psf.get_psf_kernel(
            position=geom.center_skydir, geom=geom, max_radius="0.3 deg"
        )

        stacked.name = names[idx]
        stacked.models = models[idx] + diffuse_model
        datasets_list.append(stacked)

    datasets = Datasets(datasets_list)

    dataset0 = datasets[0]
    print("dataset0")
    print("counts sum : ", dataset0.counts.data.sum())
    print("expo sum : ", dataset0.exposure.data.sum())
    print("bkg0 sum : ", dataset0.background_model.evaluate().data.sum())

    datasets.write("$GAMMAPY_DATA/tests/models", prefix="gc_example_", overwrite=True)
Ejemplo n.º 26
0
def logpar_reference_model():
    logpar = LogParabolaSpectralModel(amplitude="2e-12 cm-2s-1TeV-1",
                                      alpha=1.5,
                                      beta=0.5)
    return SkyModel(spatial_model=PointSpatialModel(), spectral_model=logpar)
Ejemplo n.º 27
0
def test_fov_bkg_maker_with_source_model(obs_dataset, exclusion_mask, caplog):

    test_dataset = obs_dataset.copy(name="test-fov")

    # crab model
    spatial_model = PointSpatialModel(lon_0="83.619deg",
                                      lat_0="22.024deg",
                                      frame="icrs")
    spectral_model = PowerLawSpectralModel(
        index=2.6, amplitude="4.5906e-11 cm-2 s-1 TeV-1", reference="1 TeV")
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="test-source")

    bkg_model = FoVBackgroundModel(dataset_name="test-fov")
    test_dataset.models = [model, bkg_model]

    # pre-fit both source and background to get reference model
    Fit().run(test_dataset)
    bkg_model_spec = test_dataset.models[
        f"{test_dataset.name}-bkg"].spectral_model
    norm_ref = 0.897
    assert not bkg_model_spec.norm.frozen
    assert_allclose(bkg_model_spec.norm.value, norm_ref, rtol=1e-4)
    assert_allclose(bkg_model_spec.tilt.value, 0.0, rtol=1e-4)

    # apply scale method with pre-fitted source model and no exclusion_mask
    bkg_model_spec.norm.value = 1
    fov_bkg_maker = FoVBackgroundMaker(method="scale", exclusion_mask=None)
    dataset = fov_bkg_maker.run(test_dataset)

    bkg_model_spec = test_dataset.models[f"{dataset.name}-bkg"].spectral_model
    assert_allclose(bkg_model_spec.norm.value, norm_ref, rtol=1e-4)
    assert_allclose(bkg_model_spec.tilt.value, 0.0, rtol=1e-4)

    # apply fit method with pre-fitted source model and no exlusion mask
    bkg_model_spec.norm.value = 1
    fov_bkg_maker = FoVBackgroundMaker(method="fit", exclusion_mask=None)
    dataset = fov_bkg_maker.run(test_dataset)

    bkg_model_spec = test_dataset.models[f"{dataset.name}-bkg"].spectral_model
    assert_allclose(bkg_model_spec.norm.value, norm_ref, rtol=1e-4)
    assert_allclose(bkg_model_spec.tilt.value, 0.0, rtol=1e-4)

    # apply scale method with pre-fitted source model and exclusion_mask
    bkg_model_spec.norm.value = 1
    fov_bkg_maker = FoVBackgroundMaker(method="scale",
                                       exclusion_mask=exclusion_mask)
    dataset = fov_bkg_maker.run(test_dataset)

    bkg_model_spec = test_dataset.models[f"{dataset.name}-bkg"].spectral_model
    assert_allclose(bkg_model_spec.norm.value, 0.830779, rtol=1e-4)
    assert_allclose(bkg_model_spec.tilt.value, 0.0, rtol=1e-4)

    # apply fit method with pre-fitted source model and exlusion mask
    bkg_model_spec.norm.value = 1
    fov_bkg_maker = FoVBackgroundMaker(method="fit",
                                       exclusion_mask=exclusion_mask)
    dataset = fov_bkg_maker.run(test_dataset)

    bkg_model_spec = test_dataset.models[f"{dataset.name}-bkg"].spectral_model
    assert_allclose(bkg_model_spec.norm.value, 0.830779, rtol=1e-4)
    assert_allclose(bkg_model_spec.tilt.value, 0.0, rtol=1e-4)

    # Here we check that source parameters are correctly thawed after fit.
    assert not dataset.models.parameters["index"].frozen
    assert not dataset.models.parameters["lon_0"].frozen

    # test
    model.spectral_model.amplitude.value *= 1e5
    fov_bkg_maker = FoVBackgroundMaker(method="scale")
    dataset = fov_bkg_maker.run(test_dataset)
    assert "WARNING" in [_.levelname for _ in caplog.records]
    message1 = "FoVBackgroundMaker failed. Negative residuals counts for test-fov. Setting mask to False."
    assert message1 in [_.message for _ in caplog.records]
Ejemplo n.º 28
0
# Spectral model corresponding to PKS 2155-304 (quiescent state)
index = 3.53
amplitude = 1.81 * 1e-12 * u.Unit("cm-2 s-1 TeV-1")
reference = 1 * u.TeV
pwl = PowerLawSpectralModel(index=index,
                            amplitude=amplitude,
                            reference=reference)

# The power-law model is multiplied by the EBL norm spectral model
redshift = 0.117
absorption = EBLAbsorptionNormSpectralModel.read_builtin("dominguez",
                                                         redshift=redshift)

model = pwl * absorption

energy_bounds = [0.1, 100] * u.TeV
plt.figure()
model.plot(energy_bounds)
plt.grid(which="both")
plt.ylim(1e-24, 1e-8)

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model, name="absorbed-model")
models = Models([model])

print(models.to_yaml())
Ejemplo n.º 29
0
 def sky_model(self):
     """Source sky model (`~gammapy.modeling.models.SkyModel`)."""
     spatial_model = self.spatial_model
     spectral_model = self.spectral_model
     return SkyModel(spatial_model, spectral_model, name=self.name)
Ejemplo n.º 30
0
=======================

This model takes a constant value along the spectral range.

    .. math:: \phi(E) = k
"""

# %%
# Example plot
# ------------
# Here is an example plot of the model:

from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import ConstantSpectralModel, Models, SkyModel

energy_range = [0.1, 100] * u.TeV
model = ConstantSpectralModel(const="1 / (cm2 s TeV)")
model.plot(energy_range)
plt.grid(which="both")

# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:

model = SkyModel(spectral_model=model, name="constant-model")
models = Models([model])

print(models.to_yaml())