Beispiel #1
0
def test_sky_point_source():
    geom = WcsGeom.create(skydir=(2.4, 2.3), npix=(10, 10), binsz=0.3)
    model = PointSpatialModel(lon_0="2.5 deg", lat_0="2.5 deg", frame="icrs")

    assert model.evaluation_radius.unit == "deg"
    assert_allclose(model.evaluation_radius.value, 0)

    assert model.frame == "icrs"

    assert_allclose(model.position.ra.deg, 2.5)
    assert_allclose(model.position.dec.deg, 2.5)

    val = model.evaluate_geom(geom)
    assert val.unit == "sr-1"
    assert_allclose(np.sum(val * geom.solid_angle()), 1)
Beispiel #2
0
def test_compute_ts_map_psf(fermi_dataset):
    spatial_model = PointSpatialModel()
    spectral_model = PowerLawSpectralModel(amplitude="1e-22 cm-2 s-1 keV-1")
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model)

    estimator = TSMapEstimator(model=model,
                               kernel_width="1 deg",
                               selection_optional="all")
    result = estimator.run(fermi_dataset)

    assert_allclose(result["ts"].data[0, 29, 29], 835.140605, rtol=1e-2)
    assert_allclose(result["niter"].data[0, 29, 29], 7)
    assert_allclose(result["flux"].data[0, 29, 29], 1.351949e-09, rtol=1e-2)

    assert_allclose(result["flux_err"].data[0, 29, 29],
                    7.93751176e-11,
                    rtol=1e-2)
    assert_allclose(result["flux_errp"].data[0, 29, 29],
                    7.9376134e-11,
                    rtol=1e-2)
    assert_allclose(result["flux_errn"].data[0, 29, 29],
                    7.5180404579e-11,
                    rtol=1e-2)
    assert_allclose(result["flux_ul"].data[0, 29, 29],
                    1.63222157e-10,
                    rtol=1e-2)

    assert result["flux"].unit == u.Unit("cm-2s-1")
    assert result["flux_err"].unit == u.Unit("cm-2s-1")
    assert result["flux_ul"].unit == u.Unit("cm-2s-1")
Beispiel #3
0
def test_compute_ts_map_energy(fermi_dataset):
    spatial_model = PointSpatialModel()
    spectral_model = PowerLawSpectralModel(amplitude="1e-22 cm-2 s-1 keV-1")
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model)

    estimator = TSMapEstimator(
        model=model,
        kernel_width="0.6 deg",
        energy_edges=[10, 100, 1000] * u.GeV,
        sum_over_energy_groups=False,
    )

    result = estimator.run(fermi_dataset)

    assert_allclose(result["ts"].data[:, 29, 29], [804.86171, 16.988756],
                    rtol=1e-2)
    assert_allclose(result["flux"].data[:, 29, 29],
                    [1.233119e-09, 3.590694e-11],
                    rtol=1e-2)
    assert_allclose(result["flux_err"].data[:, 29, 29],
                    [7.382305e-11, 1.338985e-11],
                    rtol=1e-2)
    assert_allclose(result["niter"].data[:, 29, 29], [6, 6])

    energy_axis = result["ts"].geom.axes["energy"]
    assert_allclose(energy_axis.edges.to_value("GeV"), [10, 84.471641, 500],
                    rtol=1e-4)
Beispiel #4
0
def test_sky_point_source():
    # Test special case of point source. Regression test for GH 2367.

    energy_axis = MapAxis.from_edges(
        [1, 10], unit="TeV", name="energy_true", interp="log"
    )
    exposure = Map.create(
        skydir=(100, 70),
        npix=(4, 4),
        binsz=0.1,
        proj="AIT",
        unit="cm2 s",
        axes=[energy_axis],
    )
    exposure.data = np.ones_like(exposure.data)

    spatial_model = PointSpatialModel(
        lon_0=100.06 * u.deg, lat_0=70.03 * u.deg, frame="icrs"
    )
    # Create a spectral model with integral flux of 1 cm-2 s-1 in this energy band
    spectral_model = ConstantSpectralModel(const="1 cm-2 s-1 TeV-1")
    spectral_model.const.value /= spectral_model.integral(1 * u.TeV, 10 * u.TeV).value
    model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)
    evaluator = MapEvaluator(model=model, exposure=exposure)
    flux = evaluator.compute_flux().quantity.to_value("cm-2 s-1")[0]

    expected = [
        [0, 0, 0, 0],
        [0, 0.140, 0.058, 0.0],
        [0, 0.564, 0.236, 0],
        [0, 0, 0, 0],
    ]
    assert_allclose(flux, expected, atol=0.01)

    assert_allclose(flux.sum(), 1)
Beispiel #5
0
    def spatial_model(self, which="point"):
        """Spatial model (`~gammapy.modeling.models.SpatialModel`).

        * ``which="point"`` - `~gammapy.modeling.models.PointSpatialModel`
        * ``which="extended"`` - `~gammapy.modeling.models.DiskSpatialModel`.
          Only available for some sources. Raise ValueError if not available.
        """
        idx = self._get_idx(which)

        if idx == 0:
            model = PointSpatialModel(
                lon_0=self.data["glon"], lat_0=self.data["glat"], frame="galactic"
            )
        else:
            model = DiskSpatialModel(
                lon_0=self.data["glon"],
                lat_0=self.data["glat"],
                r_0=self.data[f"spec{idx}_radius"],
                frame="galactic",
            )

        lat_err = self.data["pos_err"].to("deg")
        lon_err = self.data["pos_err"].to("deg") / np.cos(self.data["glat"].to("rad"))
        model.parameters.set_error(lon_0=lon_err, lat_0=lat_err)

        return model
Beispiel #6
0
    def spatial_model(self):
        """Spatial model (`~gammapy.modeling.models.SpatialModel`)."""
        d = self.data
        ra = d["RAJ2000"]
        dec = d["DEJ2000"]

        if self.is_pointlike:
            model = PointSpatialModel(lon_0=ra, lat_0=dec, frame="icrs")
        else:
            de = self.data_extended
            morph_type = de["Model_Form"].strip()
            e = (1 - (de["Model_SemiMinor"] / de["Model_SemiMajor"]) ** 2.0) ** 0.5
            sigma = de["Model_SemiMajor"]
            phi = de["Model_PosAng"]
            if morph_type == "Disk":
                r_0 = de["Model_SemiMajor"]
                model = DiskSpatialModel(
                    lon_0=ra, lat_0=dec, r_0=r_0, e=e, phi=phi, frame="icrs"
                )
            elif morph_type in ["Map", "Ring", "2D Gaussian x2"]:
                filename = de["Spatial_Filename"].strip()
                path = make_path(
                    "$GAMMAPY_DATA/catalogs/fermi/LAT_extended_sources_8years/Templates/"
                )
                with warnings.catch_warnings():  # ignore FITS units warnings
                    warnings.simplefilter("ignore", FITSFixedWarning)
                    model = TemplateSpatialModel.read(path / filename)
            elif morph_type == "2D Gaussian":
                model = GaussianSpatialModel(
                    lon_0=ra, lat_0=dec, sigma=sigma, e=e, phi=phi, frame="icrs"
                )
            else:
                raise ValueError(f"Invalid spatial model: {morph_type!r}")
        self._set_spatial_errors(model)
        return model
Beispiel #7
0
def test_compute_flux_spatial():
    center = SkyCoord("0 deg", "0 deg", frame="galactic")
    region = CircleSkyRegion(center=center, radius=0.1 * u.deg)

    nbin = 2
    energy_axis_true = MapAxis.from_energy_bounds(".1 TeV",
                                                  "10 TeV",
                                                  nbin=nbin,
                                                  name="energy_true")

    spectral_model = ConstantSpectralModel()
    spatial_model = PointSpatialModel(lon_0=0 * u.deg,
                                      lat_0=0 * u.deg,
                                      frame="galactic")

    models = SkyModel(spectral_model=spectral_model,
                      spatial_model=spatial_model)
    model = Models(models)

    exposure_region = RegionNDMap.create(region,
                                         axes=[energy_axis_true],
                                         binsz_wcs="0.01deg")
    exposure_region.data += 1.0
    exposure_region.unit = "m2 s"

    geom = RegionGeom(region, axes=[energy_axis_true], binsz_wcs="0.01deg")
    psf = PSFKernel.from_gauss(geom.to_wcs_geom(), sigma="0.1 deg")

    evaluator = MapEvaluator(model=model[0], exposure=exposure_region, psf=psf)
    flux = evaluator.compute_flux_spatial()

    g = Gauss2DPDF(0.1)
    reference = g.containment_fraction(0.1)
    assert_allclose(flux.value, reference, rtol=0.003)
Beispiel #8
0
    def spatial_model(self):
        """Spatial model (`~gammapy.modeling.models.SpatialModel`)."""
        d = self.data
        ra = d["RAJ2000"]
        dec = d["DEJ2000"]

        if self.is_pointlike:
            model = PointSpatialModel(lon_0=ra, lat_0=dec, frame="icrs")
        else:
            de = self.data_extended
            morph_type = de["Model_Form"].strip()
            e = (1 - (de["Model_SemiMinor"] / de["Model_SemiMajor"]) ** 2.0) ** 0.5
            sigma = de["Model_SemiMajor"]
            phi = de["Model_PosAng"]
            if morph_type in ["Disk", "Elliptical Disk"]:
                r_0 = de["Model_SemiMajor"]
                model = DiskSpatialModel(
                    lon_0=ra, lat_0=dec, r_0=r_0, e=e, phi=phi, frame="icrs"
                )
            elif morph_type in ["Map", "Ring", "2D Gaussian x2"]:
                filename = de["Spatial_Filename"].strip()
                path = make_path(
                    "$GAMMAPY_DATA/catalogs/fermi/Extended_archive_v15/Templates/"
                )
                return TemplateSpatialModel.read(path / filename)
            elif morph_type in ["2D Gaussian", "Elliptical 2D Gaussian"]:
                model = GaussianSpatialModel(
                    lon_0=ra, lat_0=dec, sigma=sigma, e=e, phi=phi, frame="icrs"
                )
            else:
                raise ValueError(f"Invalid spatial model: {morph_type!r}")

        self._set_spatial_errors(model)
        return model
    def fit_start_model(self) -> Models:
        ra = self.source_pos_radec["ra"]
        dec = self.source_pos_radec["dec"]

        spatial_model_fit = PointSpatialModel(lon_0=ra, lat_0=dec)

        spatial_model_fit.lon_0.frozen = False
        spatial_model_fit.lat_0.frozen = False

        spatial_model_fit.lon_0.min = spatial_model_fit.lon_0.value - 0.1
        spatial_model_fit.lon_0.max = spatial_model_fit.lon_0.value + 0.1
        spatial_model_fit.lat_0.min = spatial_model_fit.lat_0.value - 0.1
        spatial_model_fit.lat_0.max = spatial_model_fit.lat_0.value + 0.1

        spectral_model_ecpl_fit = ExpCutoffPowerLawSpectralModel(
            index=2.0,
            amplitude="1.3e-12 cm-2 s-1 TeV-1",
            reference="1 TeV",
            lambda_="0.1 TeV-1",
            alpha=1.0)

        spectral_model_ecpl_fit.amplitude.min = 1e-17
        spectral_model_ecpl_fit.amplitude.max = 1e-5
        spectral_model_ecpl_fit.index.min = 0.0
        spectral_model_ecpl_fit.index.max = 4.0
        spectral_model_ecpl_fit.lambda_.min = -1.0
        spectral_model_ecpl_fit.lambda_.max = 1.0
        spectral_model_ecpl_fit.reference.frozen = True
        spectral_model_ecpl_fit.alpha.frozen = True
        spectral_model_ecpl_fit.lambda_.frozen = False

        return Models(
            SkyModel(spatial_model=spatial_model_fit,
                     spectral_model=spectral_model_ecpl_fit,
                     name="fitstartmodel"))
    def true_model(self) -> SkyModel:
        def ecpl_model(amplitude):
            return ExpCutoffPowerLawSpectralModel(index=self.index_true,
                                                  amplitude=amplitude /
                                                  (u.cm**2 * u.s * u.TeV),
                                                  reference=1 * u.TeV,
                                                  lambda_=self.lambda_true,
                                                  alpha=1.0)

        def flux_difference_at_reference(x):
            diff_norm = self.normalization_true.value
            flux = ecpl_model(x)(energy=1 * u.TeV)
            return flux.value - diff_norm

        amplitude = fsolve(flux_difference_at_reference,
                           self.normalization_true.value)[0]

        spectral_model_sim = ExpCutoffPowerLawSpectralModel(
            index=self.index_true,
            amplitude=amplitude / (u.cm**2 * u.s * u.TeV),
            lambda_=self.lambda_true,
            reference=1 * u.TeV)

        ra = self.source_pos_radec["ra"]
        dec = self.source_pos_radec["dec"]

        spatial_model_sim = PointSpatialModel(lon_0=ra, lat_0=dec)

        return SkyModel(spatial_model=spatial_model_sim,
                        spectral_model=spectral_model_sim,
                        name="source")
Beispiel #11
0
    def __init__(self,
                 model=None,
                 kernel_width="0.2 deg",
                 downsampling_factor=None,
                 n_sigma=1,
                 n_sigma_ul=2,
                 threshold=None,
                 rtol=0.01,
                 selection_optional="all",
                 n_jobs=None):
        self.kernel_width = Angle(kernel_width)

        if model is None:
            model = SkyModel(spectral_model=PowerLawSpectralModel(),
                             spatial_model=PointSpatialModel(),
                             name="ts-kernel")

        self.model = model
        self.downsampling_factor = downsampling_factor
        self.n_sigma = n_sigma
        self.n_sigma_ul = n_sigma_ul
        self.threshold = threshold
        self.rtol = rtol
        self.n_jobs = n_jobs

        self.selection_optional = selection_optional
        self._flux_estimator = BrentqFluxEstimator(
            rtol=self.rtol,
            n_sigma=self.n_sigma,
            n_sigma_ul=self.n_sigma_ul,
            selection_optional=selection_optional,
            ts_threshold=threshold)
Beispiel #12
0
def test_contributes_region_mask():
    axis = MapAxis.from_edges(np.logspace(-1, 1, 3), unit=u.TeV, name="energy")
    geom = RegionGeom.create("galactic;circle(0, 0, 0.2)",
                             axes=[axis],
                             binsz_wcs="0.05 deg")

    mask = Map.from_geom(geom, unit="", dtype="bool")
    mask.data[...] = True

    spatial_model1 = GaussianSpatialModel(lon_0="0.2 deg",
                                          lat_0="0 deg",
                                          sigma="0.1 deg",
                                          frame="galactic")
    spatial_model2 = PointSpatialModel(lon_0="0.3 deg",
                                       lat_0="0.3 deg",
                                       frame="galactic")

    model1 = SkyModel(
        spatial_model=spatial_model1,
        spectral_model=PowerLawSpectralModel(),
        name="source-1",
    )
    model2 = SkyModel(
        spatial_model=spatial_model2,
        spectral_model=PowerLawSpectralModel(),
        name="source-2",
    )
    assert model1.contributes(mask, margin=0 * u.deg)
    assert not model2.contributes(mask, margin=0 * u.deg)
    assert model2.contributes(mask, margin=0.3 * u.deg)
Beispiel #13
0
def test_npred_psf_after_edisp():
    energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=3)
    energy_axis_true = MapAxis.from_energy_bounds(
        "0.8 TeV", "15 TeV", nbin=6, name="energy_true"
    )

    geom = WcsGeom.create(width=4 * u.deg, binsz=0.02, axes=[energy_axis])
    dataset = MapDataset.create(geom=geom, energy_axis_true=energy_axis_true)
    dataset.background.data += 1
    dataset.exposure.data += 1e12
    dataset.mask_safe.data += True
    dataset.psf = PSFMap.from_gauss(
        energy_axis_true=energy_axis_true, sigma=0.2 * u.deg
    )

    model = SkyModel(
        spectral_model=PowerLawSpectralModel(),
        spatial_model=PointSpatialModel(),
        name="test-model",
    )

    model.apply_irf["psf_after_edisp"] = True

    bkg_model = FoVBackgroundModel(dataset_name=dataset.name)
    dataset.models = [bkg_model, model]

    npred = dataset.npred()
    assert_allclose(npred.data.sum(), 129553.858658)
Beispiel #14
0
def data_prep():
    data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps/")
    OBS_ID = 110380
    obs_ids = OBS_ID * np.ones(N_OBS)
    observations = data_store.get_observations(obs_ids)

    energy_axis = MapAxis.from_bounds(0.1,
                                      10,
                                      nbin=10,
                                      unit="TeV",
                                      name="energy",
                                      interp="log")
    geom = WcsGeom.create(
        skydir=(0, 0),
        binsz=0.02,
        width=(10, 8),
        frame="galactic",
        proj="CAR",
        axes=[energy_axis],
    )

    energy_axis_true = MapAxis.from_bounds(0.05,
                                           20,
                                           nbin=30,
                                           unit="TeV",
                                           name="energy_true",
                                           interp="log")

    offset_max = 4 * u.deg
    maker = MapDatasetMaker()
    safe_mask_maker = SafeMaskMaker(methods=["offset-max"],
                                    offset_max=offset_max)
    stacked = MapDataset.create(geom=geom, energy_axis_true=energy_axis_true)

    spatial_model = PointSpatialModel(lon_0="-0.05 deg",
                                      lat_0="-0.05 deg",
                                      frame="galactic")
    spectral_model = ExpCutoffPowerLawSpectralModel(
        index=2,
        amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1.0 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="gc-source")

    datasets = Datasets([])
    for idx, obs in enumerate(observations):
        cutout = stacked.cutout(obs.pointing_radec,
                                width=2 * offset_max,
                                name=f"dataset{idx}")
        dataset = maker.run(cutout, obs)
        dataset = safe_mask_maker.run(dataset, obs)
        dataset.models = [model, FoVBackgroundModel(dataset_name=dataset.name)]
        datasets.append(dataset)
    return datasets
Beispiel #15
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", coordsys="GAL"
    )

    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

    dataset_maker = SpectrumDatasetMaker(
        region=on_region, e_reco=e_reco, e_true=e_true, containment_correction=True
    )
    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 ind, observation in enumerate(observations):
        dataset = dataset_maker.run(observation, selection=["counts", "aeff", "edisp"])
        dataset_on_off = bkg_maker.run(dataset, observation)
        dataset_on_off = safe_mask_masker.run(dataset_on_off, observation)
        dataset_on_off.name = f"dataset{ind}"
        dataset_on_off.models = sky_model
        datasets.append(dataset_on_off)

    return Datasets(datasets)
Beispiel #16
0
def define_model_pointlike(model):
    spatial_model = PointSpatialModel(lon_0=model.spatial_model.lon_0,
                                      lat_0=model.spatial_model.lat_0,
                                      frame=model.spatial_model.frame)
    spectral_model = model.spectral_model.copy()

    sky_model = SkyModel(spatial_model=spatial_model,
                         spectral_model=spectral_model,
                         name=f"{model.name}_point")
    return sky_model
def fit_estimator(dataset):
    spatial_model = PointSpatialModel()
    spectral_model = PowerLawSpectralModel(index=2)
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model)
    estimator = TSMapEstimator(model,
                               kernel_width="1 deg",
                               energy_edges=[10, 30, 300] * u.GeV)
    images = estimator.run(dataset)
    return images
Beispiel #18
0
    def __init__(self):
        """
        This initializes a default GRB.

        Returns
        -------
        None.

        """
        self.name = 'dummy'
        self.z = 0

        # GRB properties - Dummy default values
        self.radec = SkyCoord(100 * u.degree, -15 * u.degree, frame='icrs')
        self.Eiso = 0. * u.erg
        self.Epeak = 0. * u.keV
        self.t90 = 0. * u.s
        self.G0H = 0. * u.dimensionless_unscaled
        self.G0W = 0. * u.dimensionless_unscaled
        self.FluxPeak = 0. * u.erg
        self.gamma_le = 0. * u.dimensionless_unscaled
        self.gamma_he = 0. * u.dimensionless_unscaled

        # GRB detection positions
        self.site_keys = ["North", "South"]  # Put it somewhere else !
        self.site = {"North": 'Roque de los Muchachos', "South": 'Paranal'}

        # GRB alert received
        self.t_trig = Time('2000-01-01 02:00:00', scale='utc')

        # Afterglow Flux table - Flux at a series of points
        self.Eval = [0] * u.GeV
        self.tval = [0] * u.s
        self.fluxval = [0] * u.Unit("1 / (cm2 GeV s)")
        self.spec_afterglow = []  # Interpolated, non attenuated

        # Prompt energy spectrum
        self.prompt = False  # Default : no prompt
        self.id90 = -1
        self.E_prompt = [0] * u.GeV
        self.flux_prompt = [0] * u.Unit("1 / (cm2 GeV s)")
        self.spec_prompt = None  # One Interpolated, non attenuated E-spectrum

        # Visibility (requires GRB points interval)
        self.vis = {
            "North": Visibility(self, "North"),
            "South": Visibility(self, "South")
        }
        # GRB cumulated attenuated spectra and spatial model
        self.spectra = []  # Gammapy models (one per t slice)
        self.spatial = PointSpatialModel(lon_0=0 * u.deg, lat_0=0 * u.deg)

        return
Beispiel #19
0
def define_model_3d(target_position):
    spatial_model = PointSpatialModel(lon_0=target_position.ra,
                                      lat_0=target_position.dec,
                                      frame="icrs")
    spectral_model = PowerLawSpectralModel(
        index=3.4,
        amplitude=2e-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="pks2155")
    return sky_model
Beispiel #20
0
def test_spatial_model_plot():
    model = PointSpatialModel()
    model.covariance = np.diag([0.01, 0.01])

    with mpl_plot_check():
        ax = model.plot()

    with mpl_plot_check():
        model.plot_error(ax=ax)
Beispiel #21
0
def data_prep():
    data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps/")
    OBS_ID = 110380
    obs_ids = OBS_ID * np.ones(N_OBS)
    observations = data_store.get_observations(obs_ids)

    energy_axis = MapAxis.from_bounds(0.1,
                                      10,
                                      nbin=10,
                                      unit="TeV",
                                      name="energy",
                                      interp="log")
    geom = WcsGeom.create(
        skydir=(0, 0),
        binsz=0.02,
        width=(10, 8),
        coordsys="GAL",
        proj="CAR",
        axes=[energy_axis],
    )

    src_pos = SkyCoord(0, 0, unit="deg", frame="galactic")
    offset_max = 4 * u.deg
    maker = MapDatasetMaker()
    safe_mask_maker = SafeMaskMaker(methods=["offset-max"],
                                    offset_max=offset_max)
    stacked = MapDataset.create(geom=geom)

    spatial_model = PointSpatialModel(lon_0="-0.05 deg",
                                      lat_0="-0.05 deg",
                                      frame="galactic")
    spectral_model = ExpCutoffPowerLawSpectralModel(
        index=2,
        amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1.0 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="gc-source")

    datasets = []
    for i, obs in enumerate(observations):
        dataset = maker.run(stacked, obs)
        dataset = safe_mask_maker.run(dataset, obs)
        dataset.models = model
        dataset.name = f"dataset{i}"
        datasets.append(dataset)
    return Datasets(datasets)
Beispiel #22
0
    def spatial_model(self):
        """Spatial model (`~gammapy.modeling.models.SpatialModel`).

        One of the following models (given by ``Spatial_Model`` in the catalog):

        - ``Point-Like`` or has a size upper limit : `~gammapy.modeling.models.PointSpatialModel`
        - ``Gaussian``: `~gammapy.modeling.models.GaussianSpatialModel`
        - ``2-Gaussian`` or ``3-Gaussian``: composite model (using ``+`` with Gaussians)
        - ``Shell``: `~gammapy.modeling.models.ShellSpatialModel`
        """
        d = self.data
        glon = d["GLON"]
        glat = d["GLAT"]

        spatial_type = self.spatial_model_type

        if self.is_pointlike:
            model = PointSpatialModel(lon_0=glon, lat_0=glat, frame="galactic")
        elif spatial_type == "gaussian":
            model = GaussianSpatialModel(lon_0=glon,
                                         lat_0=glat,
                                         sigma=d["Size"],
                                         frame="galactic")
            model.parameters.set_error(lon_0=d["GLON_Err"],
                                       lat_0=d["GLAT_Err"],
                                       sigma=d["Size_Err"])
        elif spatial_type in {"2-gaussian", "3-gaussian"}:
            raise ValueError(
                "For Gaussian or Multi-Gaussian models, use sky_model()!")
        elif spatial_type == "shell":
            # HGPS contains no information on shell width
            # Here we assume a 5% shell width for all shells.
            r_out = d["Size"]
            radius = 0.95 * r_out
            width = r_out - radius
            model = ShellSpatialModel(lon_0=glon,
                                      lat_0=glat,
                                      width=width,
                                      radius=radius,
                                      frame="galactic")
            model.parameters.set_error(lon_0=d["GLON_Err"],
                                       lat_0=d["GLAT_Err"],
                                       radius=d["Size_Err"])
        else:
            raise ValueError(f"Invalid spatial_type: {spatial_type}")

        return model
def data_prep():
    data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps/")
    OBS_ID = 110380
    obs_ids = OBS_ID * np.ones(N_OBS)
    observations = data_store.get_observations(obs_ids)

    energy_axis = MapAxis.from_bounds(0.1,
                                      10,
                                      nbin=10,
                                      unit="TeV",
                                      name="energy",
                                      interp="log")

    geom = WcsGeom.create(
        skydir=(0, 0),
        binsz=0.05,
        width=(10, 8),
        frame="galactic",
        proj="CAR",
        axes=[energy_axis],
    )

    stacked = MapDataset.create(geom, name="stacked_ds")
    maker = MapDatasetMaker()
    safe_mask_maker = SafeMaskMaker(methods=["offset-max"], offset_max="4 deg")
    for obs in observations:
        dataset = maker.run(stacked, obs)
        dataset = safe_mask_maker.run(dataset, obs)
        stacked.stack(dataset)

    spatial_model = PointSpatialModel(lon_0="0.01 deg",
                                      lat_0="0.01 deg",
                                      frame="galactic")
    spectral_model = ExpCutoffPowerLawSpectralModel(
        index=2,
        amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1.0 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="gc-source")

    stacked.models.append(model)
    return Datasets([stacked])
Beispiel #24
0
    def spatial_model(self):
        """Source spatial model (`~gammapy.modeling.models.SpatialModel`).

        TODO: add parameter errors!
        """
        d = self.data
        morph_type = d["morph_type"]

        glon = d["glon"]
        glat = d["glat"]

        if morph_type == "point":
            model = PointSpatialModel(lon_0=glon, lat_0=glat, frame="galactic")
        elif morph_type == "gauss":
            # TODO: add infos back once model support elongation
            # pars['x_stddev'] = d['morph_sigma']
            # pars['y_stddev'] = d['morph_sigma']
            # if not np.isnan(d['morph_sigma2']):
            #     pars['y_stddev'] = d['morph_sigma2']
            # if not np.isnan(d['morph_pa']):
            #     # TODO: handle reference frame for rotation angle
            #     pars['theta'] = Angle(d['morph_pa'], 'deg').rad
            model = GaussianSpatialModel(
                lon_0=glon, lat_0=glat, sigma=d["morph_sigma"], frame="galactic"
            )
        elif morph_type == "shell":
            model = ShellSpatialModel(
                lon_0=glon,
                lat_0=glat,
                # TODO: probably we shouldn't guess a shell width here!
                radius=0.8 * d["morph_sigma"],
                width=0.2 * d["morph_sigma"],
                frame="galactic",
            )
        elif morph_type == "none":
            return None
        else:
            raise ValueError(f"Invalid morph_type: {morph_type!r}")

        lat_err = self.data["pos_err"].to("deg")
        lon_err = self.data["pos_err"].to("deg") / np.cos(self.data["glat"].to("rad"))
        model.parameters.set_error(lon_0=lon_err, lat_0=lat_err)
        # TODO: check if pos_err is really 1sigma
        return model
Beispiel #25
0
    def __init__(
        self,
        model=None,
        kernel_width=None,
        downsampling_factor=None,
        n_sigma=1,
        n_sigma_ul=2,
        threshold=None,
        rtol=0.01,
        selection_optional=None,
        energy_edges=None,
        sum_over_energy_groups=True,
        n_jobs=None,
    ):
        if kernel_width is not None:
            kernel_width = Angle(kernel_width)

        self.kernel_width = kernel_width

        if model is None:
            model = SkyModel(
                spectral_model=PowerLawSpectralModel(),
                spatial_model=PointSpatialModel(),
                name="ts-kernel",
            )

        self.model = model
        self.downsampling_factor = downsampling_factor
        self.n_sigma = n_sigma
        self.n_sigma_ul = n_sigma_ul
        self.threshold = threshold
        self.rtol = rtol
        self.n_jobs = n_jobs
        self.sum_over_energy_groups = sum_over_energy_groups

        self.selection_optional = selection_optional
        self.energy_edges = energy_edges
        self._flux_estimator = BrentqFluxEstimator(
            rtol=self.rtol,
            n_sigma=self.n_sigma,
            n_sigma_ul=self.n_sigma_ul,
            selection_optional=selection_optional,
            ts_threshold=threshold,
        )
Beispiel #26
0
def fake_dataset():
    axis = MapAxis.from_energy_bounds(0.1, 10, 5, unit="TeV", name="energy")
    axis_true = MapAxis.from_energy_bounds(0.05, 20, 10, unit="TeV", name="energy_true")

    geom = WcsGeom.create(npix=50, binsz=0.02, axes=[axis])
    dataset = MapDataset.create(geom)
    dataset.psf = PSFMap.from_gauss(axis_true, sigma="0.05 deg")
    dataset.mask_safe += np.ones(dataset.data_shape, dtype=bool)
    dataset.background += 1
    dataset.exposure += 1e12 * u.cm ** 2 * u.s

    spatial_model = PointSpatialModel()
    spectral_model = PowerLawSpectralModel(amplitude="1e-10 cm-2s-1TeV-1", index=2)
    model = SkyModel(
        spatial_model=spatial_model, spectral_model=spectral_model, name="source"
    )
    dataset.models = [model]
    dataset.fake(random_state=42)
    return dataset
Beispiel #27
0
def models(backgrounds):
    spatial_model = GaussianSpatialModel(
        lon_0="3 deg", lat_0="4 deg", sigma="3 deg", frame="galactic"
    )
    spectral_model = PowerLawSpectralModel(
        index=2, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
    )
    model1 = SkyModel(
        spatial_model=spatial_model, spectral_model=spectral_model, name="source-1",
    )

    model2 = model1.copy(name="source-2")
    model2.datasets_names = ["dataset-1"]
    model3 = model1.copy(name="source-3")
    model3.datasets_names = "dataset-2"
    model3.spatial_model = PointSpatialModel(frame="galactic")
    model3.parameters.freeze_all()
    models = Models([model1, model2, model3] + backgrounds)
    return models
Beispiel #28
0
def data_fit(stacked):
    # Data fitting

    spatial_model = PointSpatialModel(
        lon_0="0.01 deg", lat_0="0.01 deg", frame="galactic"
    )
    spectral_model = ExpCutoffPowerLawSpectralModel(
        index=2,
        amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1.0 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    model = SkyModel(
        spatial_model=spatial_model, spectral_model=spectral_model, name="gc-source"
    )

    stacked.model = model

    fit = Fit([stacked])
    result = fit.run(optimize_opts={"print_level": 1})
def read():

    datasets = []
    spatial_model = PointSpatialModel(lon_0="-0.05 deg",
                                      lat_0="-0.05 deg",
                                      frame="galactic")
    spectral_model = ExpCutoffPowerLawSpectralModel(
        index=2,
        amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1.0 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    model = SkyModel(spatial_model=spatial_model,
                     spectral_model=spectral_model,
                     name="gc-source")
    for ind in range(N_OBS):
        dataset = MapDataset.read(f"dataset-{ind}.fits")
        dataset.model = model
        datasets.append(dataset)

    return datasets
Beispiel #30
0
    def spatial_model(self):
        """Source spatial model (`~gammapy.modeling.models.SpatialModel`).

        TODO: add parameter errors!
        """
        d = self.data
        morph_type = d["morph_type"]

        glon = d["glon"]
        glat = d["glat"]

        if morph_type == "point":
            return PointSpatialModel(lon_0=glon, lat_0=glat, frame="galactic")
        elif morph_type == "gauss":
            # TODO: add infos back once model support elongation
            # pars['x_stddev'] = d['morph_sigma']
            # pars['y_stddev'] = d['morph_sigma']
            # if not np.isnan(d['morph_sigma2']):
            #     pars['y_stddev'] = d['morph_sigma2']
            # if not np.isnan(d['morph_pa']):
            #     # TODO: handle reference frame for rotation angle
            #     pars['theta'] = Angle(d['morph_pa'], 'deg').rad
            return GaussianSpatialModel(lon_0=glon,
                                        lat_0=glat,
                                        sigma=d["morph_sigma"],
                                        frame="galactic")
        elif morph_type == "shell":
            return ShellSpatialModel(
                lon_0=glon,
                lat_0=glat,
                # TODO: probably we shouldn't guess a shell width here!
                radius=0.8 * d["morph_sigma"],
                width=0.2 * d["morph_sigma"],
                frame="galactic",
            )
        elif morph_type == "none":
            raise NoDataAvailableError(
                f"No spatial model available: {self.name}")
        else:
            raise NotImplementedError(f"Unknown spatial model: {morph_type!r}")