Пример #1
0
    def sample_coord(self, map_coord, random_state=0):
        """Apply the energy dispersion corrections on the coordinates of a set of simulated events.

        Parameters
        ----------
        map_coord : `~gammapy.maps.MapCoord` object.
            Sequence of coordinates and energies of sampled events.
        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}
            Defines random number generator initialisation.
            Passed to `~gammapy.utils.random.get_random_state`.

        Returns
        -------
        `~gammapy.maps.MapCoord`.
            Sequence of Edisp-corrected coordinates of the input map_coord map.
        """
        random_state = get_random_state(random_state)
        migra_axis = self.edisp_map.geom.get_axis_by_name("migra")

        coord = {
            "skycoord": map_coord.skycoord.reshape(-1, 1),
            "energy_true": map_coord["energy_true"].reshape(-1, 1),
            "migra": migra_axis.center,
        }

        pdf_edisp = self.edisp_map.interp_by_coord(coord)

        sample_edisp = InverseCDFSampler(pdf_edisp, axis=1, random_state=random_state)
        pix_edisp = sample_edisp.sample_axis()
        migra = migra_axis.pix_to_coord(pix_edisp)

        energy_reco = map_coord["energy_true"] * migra

        return MapCoord.create({"skycoord": map_coord.skycoord, "energy": energy_reco})
Пример #2
0
def test_wcsndmap_set_get_by_coord(npix, binsz, frame, proj, skydir, axes):
    geom = WcsGeom.create(
        npix=npix, binsz=binsz, skydir=skydir, proj=proj, frame=frame, axes=axes
    )
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    m.set_by_coord(coords, coords[0])
    assert_allclose(coords[0].value, m.get_by_coord(coords))

    # Test with SkyCoords
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    skydir = coords.skycoord
    skydir_cel = skydir.transform_to("icrs")
    skydir_gal = skydir.transform_to("galactic")

    m.set_by_coord((skydir_gal,) + tuple(coords[2:]), coords[0])
    assert_allclose(coords[0].value, m.get_by_coord(coords))
    assert_allclose(
        m.get_by_coord((skydir_cel,) + tuple(coords[2:])),
        m.get_by_coord((skydir_gal,) + tuple(coords[2:])),
    )

    # Test with MapCoord
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    coords_dict = dict(lon=coords[0], lat=coords[1])
    if axes:
        for i, ax in enumerate(axes):
            coords_dict[ax.name] = coords[i + 2]
    map_coords = MapCoord.create(coords_dict, frame=frame)
    m.set_by_coord(map_coords, coords[0])
    assert_allclose(coords[0].value, m.get_by_coord(map_coords))
Пример #3
0
    def sample_psf(self, psf_map, events):
        """Sample psf map.

        Parameters
        ----------
        psf_map : `~gammapy.irf.PSFMap`
            PSF map.
        events : `~gammapy.data.EventList`
            Event list.

        Returns
        -------
        events : `~gammapy.data.EventList`
            Event list with reconstructed position columns.
        """
        coord = MapCoord(
            {
                "lon": events.table["RA_TRUE"].quantity,
                "lat": events.table["DEC_TRUE"].quantity,
                "energy_true": events.table["ENERGY_TRUE"].quantity,
            },
            frame="icrs",
        )

        coords_reco = psf_map.sample_coord(coord, self.random_state)
        events.table["RA"] = coords_reco["lon"] * u.deg
        events.table["DEC"] = coords_reco["lat"] * u.deg
        return events
Пример #4
0
    def sample_edisp(self, edisp_map, events):
        """Sample energy dispersion map.

        Parameters
        ----------
        edisp_map : `~gammapy.irf.EDispMap`
            Energy dispersion map
        events : `~gammapy.data.EventList`
            Event list with the true energies

        Returns
        -------
        events : `~gammapy.data.EventList`
            Event list with reconstructed energy column.
        """
        coord = MapCoord(
            {
                "lon": events.table["RA_TRUE"].quantity,
                "lat": events.table["DEC_TRUE"].quantity,
                "energy_true": events.table["ENERGY_TRUE"].quantity,
            },
            frame="icrs",
        )

        coords_reco = edisp_map.sample_coord(coord, self.random_state)
        events.table["ENERGY"] = coords_reco["energy"]
        return events
Пример #5
0
    def map_coord(self, geom):
        """Event map coordinates for a given geometry.

        Parameters
        ----------
        geom : `~gammapy.maps.Geom`
            Geometry

        Returns
        -------
        coord : `~gammapy.maps.MapCoord`
            Coordinates
        """
        coord = {"skycoord": self.radec}

        cols = {k.upper(): v for k, v in self.table.columns.items()}

        for axis in geom.axes:
            try:
                col = cols[axis.name.upper()]
                coord[axis.name] = Quantity(col).to(axis.unit)
            except KeyError:
                raise KeyError(
                    f"Column not found in event list: {axis.name!r}")

        return MapCoord.create(coord)
    def run(self, geom):
        """Create and fill the map dataset"""
        dataset = MapDataset.create(geom, binsz_irf=1.0)
        dataset.counts.fill_events(self.events)

        dataset.gti = self._make_gti()

        self._fill_psfmap(self.psf, dataset)

        # recompute exposure on geom
        coords = geom.get_coord()
        # this is to change the axis name. Can we avoid this?
        coords = MapCoord.create(
            dict(skycoord=coords.skycoord, energy_true=coords['energy']))
        values = self.exposure.interp_by_coord(coords)
        dataset.exposure = Map.from_geom(geom,
                                         data=values,
                                         unit=self.exposure.unit)

        # Not the real Fermi-LAT EDISP: Use 5% energy resolution as approximation
        energy = geom.axes[0]
        edisp = EDispKernel.from_gauss(e_true=energy.edges,
                                       e_reco=energy.edges,
                                       sigma=0.05,
                                       bias=0)
        dataset.edisp = edisp

        return dataset
Пример #7
0
    def get_flux_points(self, position=None):
        """Extract flux point at a given position.

        Parameters
        ---------
        position : `~astropy.coordinates.SkyCoord`
            Position where the flux points are extracted.

        Returns
        -------
        flux_points : `~gammapy.estimators.FluxPoints`
            Flux points object
        """
        if position is None:
            position = self.geom.center_skydir

        with np.errstate(invalid="ignore", divide="ignore"):
            ref_fluxes = self.reference_spectral_model.reference_fluxes(
                self.energy_axis)

        table = Table(ref_fluxes)
        table.meta["SED_TYPE"] = "likelihood"

        coords = MapCoord.create({
            "skycoord": position,
            "energy": self.energy_ref
        })

        # TODO: add support of norm and stat scan
        for name in self.data:
            m = getattr(self, name)
            table[name] = m.get_by_coord(coords) * m.unit

        return FluxPoints(
            table, reference_spectral_model=self.reference_spectral_model)
Пример #8
0
    def make_mask_energy_aeff_max(self, dataset):
        """Make safe energy mask from effective area maximum value.

        Parameters
        ----------
        dataset : `~gammapy.datasets.MapDataset` or `~gammapy.datasets.SpectrumDataset`
            Dataset to compute mask for.

        Returns
        -------
        mask_safe : `~numpy.ndarray`
            Safe data range mask.
        """
        geom = dataset._geom

        if isinstance(dataset, MapDataset):
            position = self.position
            if position is None:
                position = dataset.counts.geom.center_skydir
            exposure = dataset.exposure
            energy = exposure.geom.get_axis_by_name("energy_true")
            coord = MapCoord.create({"skycoord": position, "energy_true": energy.center})
            exposure_1d = exposure.interp_by_coord(coord)
            aeff = EffectiveAreaTable(
                energy_lo=energy.edges[:-1],
                energy_hi=energy.edges[1:],
                data=exposure_1d,
            )
        else:
            aeff = dataset.aeff

        aeff_thres = (self.aeff_percent / 100) * aeff.max_area
        e_min = aeff.find_energy(aeff_thres)
        return geom.energy_mask(emin=e_min)
Пример #9
0
    def get_flux_points(self, coord=None):
        """Extract flux point at a given position.

        The flux points are returned in the the form of a `~gammapy.estimators.FluxPoints` object
        (which stores the flux points in an `~astropy.table.Table`)

        Parameters
        ---------
        coord : `~astropy.coordinates.SkyCoord`
            the coordinate where the flux points are extracted.

        Returns
        -------
        fluxpoints : `~gammapy.estimators.FluxPoints`
            the flux points object
        """
        if coord is None:
            coord = self.geom.center_skydir
        energies = self.energy_ref
        coords = MapCoord.create(dict(skycoord=coord, energy=energies))

        ref = self.dnde_ref.squeeze()

        fp = dict()
        fp["norm"] = self.norm.get_by_coord(coords) * self.norm.unit

        for quantity in self._available_quantities:
            norm_quantity = f"norm_{quantity}"
            res = getattr(self, norm_quantity).get_by_coord(coords)
            res *= getattr(self, norm_quantity).unit
            fp[norm_quantity] = res

        for additional_quantity in self._additional_maps:
            res = self.data[additional_quantity].get_by_coord(coords)
            res *= self.data[additional_quantity].unit
            fp[additional_quantity] = res

        # TODO: add support of norm and stat scan

        rows = []
        for idx, energy in enumerate(self.energy_ref):
            result = dict()
            result["e_ref"] = energy
            result["e_min"] = self.energy_min[idx]
            result["e_max"] = self.energy_max[idx]
            result["ref_dnde"] = ref[idx]
            result["norm"] = fp["norm"][idx]
            for quantity in self._available_quantities:
                norm_quantity = f"norm_{quantity}"
                result[norm_quantity] = fp[norm_quantity][idx]
            for key in self._additional_maps:
                result[key] = fp[key][idx]
            rows.append(result)
        table = table_from_row_data(rows=rows, meta={"SED_TYPE": "likelihood"})
        return FluxPoints(table).to_sed_type('dnde')
Пример #10
0
def test_sample_coord_gauss():
    psf_map = make_test_psfmap(0.1 * u.deg, shape="gauss")

    lon, lat = np.zeros(10000) * u.deg, np.zeros(10000) * u.deg
    energy = np.ones(10000) * u.TeV
    coords_in = MapCoord.create(
        {"lon": lon, "lat": lat, "energy_true": energy}, frame="icrs"
    )
    coords = psf_map.sample_coord(coords_in)

    assert_allclose(np.mean(coords.skycoord.data.lon.wrap_at("180d").deg), 0, atol=2e-3)
    assert_allclose(np.mean(coords.lat), 0, atol=2e-3)
Пример #11
0
def test_sample_coord():
    edisp_map = make_edisp_map_test()

    coords = MapCoord(
        {"lon": [0, 0] * u.deg, "lat": [0, 0.5] * u.deg, "energy": [1, 3] * u.TeV},
        coordsys="CEL",
    )

    coords_corrected = edisp_map.sample_coord(map_coord=coords)

    assert len(coords_corrected["energy"]) == 2
    assert_allclose(coords_corrected["energy"], [0.9961658, 1.11269299], rtol=1e-5)
Пример #12
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG, **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = WcsNDMap.create(skydir=skydir,
                                 binsz=scan_cdelt,
                                 npix=(nstep, nstep),
                                 frame=wcs_utils.coordsys_to_frame(
                                     wcs_utils.get_coordsys(self.geom.wcs)))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        coord = MapCoord.create(lnlmap.geom.get_coord(flat=True),
                                frame=lnlmap.geom.frame)
        scan_skydir = coord.skycoord.icrs
        for lon, lat, ra, dec in zip(coord.lon, coord.lat, scan_skydir.ra.deg,
                                     scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG, **optimizer)
            lnlmap.set_by_coord((lon, lat), fit_output['loglike'])

        self.set_source_morphology(name,
                                   spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = WcsNDMap(lnlmap.geom, 2.0 * lnlmap.data)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Пример #13
0
def test_sample_coord():
    psf_map = make_test_psfmap(0.1 * u.deg, shape="gauss")

    coords_in = MapCoord(
        {"lon": [0, 0] * u.deg, "lat": [0, 0.5] * u.deg, "energy_true": [1, 3] * u.TeV},
        frame="icrs",
    )

    coords = psf_map.sample_coord(map_coord=coords_in)
    assert coords.frame == "icrs"
    assert len(coords.lon) == 2
    assert_allclose(coords.lon, [0.07498478, 0.04274561], rtol=1e-3)
    assert_allclose(coords.lat, [-0.10173629, 0.34703959], rtol=1e-3)
Пример #14
0
def test_sample_coord():
    edisp_map = make_edisp_map_test()

    coords = MapCoord(
        {"lon": [0, 0] * u.deg, "lat": [0, 0.5] * u.deg, "energy_true": [1, 3] * u.TeV},
        frame="icrs",
    )

    coords_corrected = edisp_map.sample_coord(map_coord=coords)

    assert len(coords_corrected["energy"]) == 2
    assert coords_corrected["energy"].unit == "TeV"
    assert_allclose(coords_corrected["energy"].value, [1.024664, 3.34484], rtol=1e-5)
Пример #15
0
    def estimate_kernel(self, dataset):
        """Get the convolution kernel for the input dataset.

        Convolves the model with the PSFKernel at the center of the dataset.

        Parameters
        ----------
        dataset : `~gammapy.datasets.MapDataset`
            Input dataset.

        Returns
        -------
        kernel : `Map`
            Kernel map

        """
        # TODO: further simplify the code below
        geom = dataset.exposure.geom

        model = self.model.copy()
        model.spatial_model.position = geom.center_skydir

        geom_kernel = geom.to_odd_npix(max_radius=self.kernel_width / 2)

        # Creating exposure map with exposure at map center
        exposure = Map.from_geom(geom_kernel, unit="cm2 s1")
        coord = MapCoord.create(
            dict(skycoord=geom.center_skydir,
                 energy_true=geom.axes["energy_true"].center))
        exposure.data[...] = dataset.exposure.get_by_coord(coord)[:,
                                                                  np.newaxis,
                                                                  np.newaxis]

        # We use global evaluation mode to not modify the geometry
        evaluator = MapEvaluator(model, evaluation_mode="global")
        evaluator.update(
            exposure,
            dataset.psf,
            dataset.edisp,
            dataset.counts.geom,
            dataset.mask_fit,
        )

        kernel = evaluator.compute_npred()
        kernel.data /= kernel.data.sum()

        if (self.kernel_width >= geom.width).any():
            raise ValueError(
                "Kernel shape larger than map shape, please adjust"
                " size of the kernel")
        return kernel
Пример #16
0
    def _scan_position(self, name, **kwargs):

        saved_state = LikelihoodState(self.like)

        skydir = kwargs.pop('skydir', self.roi[name].skydir)
        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)
        nstep = kwargs.pop('nstep', 5)
        use_cache = kwargs.get('use_cache', True)
        use_pylike = kwargs.get('use_pylike', False)
        optimizer = kwargs.get('optimizer', {})

        # Fit without source
        self.zero_source(name, loglevel=logging.DEBUG)
        fit_output_nosrc = self._fit(loglevel=logging.DEBUG,
                                     **optimizer)
        self.unzero_source(name, loglevel=logging.DEBUG)
        saved_state.restore()
        self.free_norm(name, loglevel=logging.DEBUG)

        lnlmap = WcsNDMap.create(skydir=skydir, binsz=scan_cdelt, npix=(nstep, nstep),
                                 coordsys=wcs_utils.get_coordsys(self.geom.wcs))

        src = self.roi.copy_source(name)

        if use_cache and not use_pylike:
            self._create_srcmap_cache(src.name, src)

        coord = MapCoord.create(lnlmap.geom.get_coord(flat=True),
                                coordsys=lnlmap.geom.coordsys)
        scan_skydir = coord.skycoord.icrs
        for lon, lat, ra, dec in zip(coord.lon, coord.lat,
                                     scan_skydir.ra.deg, scan_skydir.dec.deg):

            spatial_pars = {'ra': ra, 'dec': dec}
            self.set_source_morphology(name,
                                       spatial_pars=spatial_pars,
                                       use_pylike=use_pylike)
            fit_output = self._fit(loglevel=logging.DEBUG,
                                   **optimizer)
            lnlmap.set_by_coord((lon, lat), fit_output['loglike'])

        self.set_source_morphology(name, spatial_pars=src.spatial_pars,
                                   use_pylike=use_pylike)
        saved_state.restore()

        lnlmap.data -= fit_output_nosrc['loglike']
        tsmap = WcsNDMap(lnlmap.geom, 2.0 * lnlmap.data)

        self._clear_srcmap_cache()
        return tsmap, fit_output_nosrc['loglike']
Пример #17
0
def test_mapcoords_to_frame():
    lon, lat = np.array([0.0, 1.0]), np.array([2.0, 3.0])
    energy = np.array([100.0, 1000.0])
    skycoord_cel = SkyCoord(lon, lat, unit="deg", frame="icrs")
    skycoord_gal = SkyCoord(lon, lat, unit="deg", frame="galactic")

    coords = MapCoord.create(dict(lon=lon, lat=lat, energy=energy),
                             frame="icrs")
    assert coords.frame == "icrs"
    assert_allclose(
        coords.skycoord.transform_to("icrs").ra.deg, skycoord_cel.ra.deg)
    assert_allclose(
        coords.skycoord.transform_to("icrs").dec.deg, skycoord_cel.dec.deg)
    coords = coords.to_frame("galactic")
    assert coords.frame == "galactic"
    assert_allclose(
        coords.skycoord.transform_to("galactic").l.deg,
        skycoord_cel.galactic.l.deg)
    assert_allclose(
        coords.skycoord.transform_to("galactic").b.deg,
        skycoord_cel.galactic.b.deg)

    coords = MapCoord.create(dict(lon=lon, lat=lat, energy=energy),
                             frame="galactic")
    assert coords.frame == "galactic"
    assert_allclose(
        coords.skycoord.transform_to("galactic").l.deg, skycoord_gal.l.deg)
    assert_allclose(
        coords.skycoord.transform_to("galactic").b.deg, skycoord_gal.b.deg)
    coords = coords.to_frame("icrs")
    assert coords.frame == "icrs"
    assert_allclose(
        coords.skycoord.transform_to("icrs").ra.deg, skycoord_gal.icrs.ra.deg)
    assert_allclose(
        coords.skycoord.transform_to("icrs").dec.deg,
        skycoord_gal.icrs.dec.deg)
Пример #18
0
def test_sample_coord():
    psf_map = make_test_psfmap(0.1 * u.deg, shape="gauss")

    coords_in = MapCoord(
        {
            "lon": [0, 0] * u.deg,
            "lat": [0, 0.5] * u.deg,
            "energy": [1, 3] * u.TeV
        },
        coordsys="CEL",
    )

    coords = psf_map.sample_coord(map_coord=coords_in)
    assert coords.coordsys == "CEL"
    assert len(coords.lon) == 2
    assert_allclose(coords.lon, [3.599708e02, 7.749678e-02], rtol=1e-3)
    assert_allclose(coords.lat, [-0.055216, 0.439184], rtol=1e-3)
Пример #19
0
    def _get_irf_coords(self, **kwargs):
        coords = MapCoord.create(kwargs)

        geom = self.psf_map.geom.to_image()
        lon_pix, lat_pix = geom.coord_to_pix((coords.lon, coords.lat))

        coords_irf = {
            "lon_idx": lon_pix,
            "lat_idx": lat_pix,
            "energy_true": coords["energy_true"],
        }

        try:
            coords_irf["rad"] = coords["rad"]
        except KeyError:
            pass

        return coords_irf
Пример #20
0
    def sample_coord(self, map_coord, random_state=0):
        """Apply PSF corrections on the coordinates of a set of simulated events.

        Parameters
        ----------
        map_coord : `~gammapy.maps.MapCoord` object.
            Sequence of coordinates and energies of sampled events.
        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}
            Defines random number generator initialisation.
            Passed to `~gammapy.utils.random.get_random_state`.

        Returns
        -------
        corr_coord : `~gammapy.maps.MapCoord` object.
            Sequence of PSF-corrected coordinates of the input map_coord map.
        """

        random_state = get_random_state(random_state)
        rad_axis = self.psf_map.geom.axes["rad"]

        coord = {
            "skycoord": map_coord.skycoord.reshape(-1, 1),
            "energy_true": map_coord["energy_true"].reshape(-1, 1),
            "rad": rad_axis.center,
        }

        pdf = (
            self.psf_map.interp_by_coord(coord)
            * rad_axis.center.value
            * rad_axis.bin_width.value
        )

        sample_pdf = InverseCDFSampler(pdf, axis=1, random_state=random_state)
        pix_coord = sample_pdf.sample_axis()
        separation = rad_axis.pix_to_coord(pix_coord)

        position_angle = random_state.uniform(360, size=len(map_coord.lon)) * u.deg

        event_positions = map_coord.skycoord.directional_offset_by(
            position_angle=position_angle, separation=separation
        )
        return MapCoord.create(
            {"skycoord": event_positions, "energy_true": map_coord["energy_true"]}
        )
Пример #21
0
def test_wcsndmap_set_get_by_coord(npix, binsz, coordsys, proj, skydir, axes):
    geom = WcsGeom.create(npix=npix,
                          binsz=binsz,
                          skydir=skydir,
                          proj=proj,
                          coordsys=coordsys,
                          axes=axes)
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    m.set_by_coord(coords, coords[0])
    assert_allclose(coords[0], m.get_by_coord(coords))

    if not geom.is_allsky:
        coords[1][...] = 0.0
        assert_allclose(np.nan * np.ones(coords[0].shape),
                        m.get_by_coord(coords))

    # Test with SkyCoords
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    skydir = SkyCoord(coords[0],
                      coords[1],
                      unit="deg",
                      frame=coordsys_to_frame(geom.coordsys))
    skydir_cel = skydir.transform_to("icrs")
    skydir_gal = skydir.transform_to("galactic")

    m.set_by_coord((skydir_gal, ) + tuple(coords[2:]), coords[0])
    assert_allclose(coords[0], m.get_by_coord(coords))
    assert_allclose(
        m.get_by_coord((skydir_cel, ) + tuple(coords[2:])),
        m.get_by_coord((skydir_gal, ) + tuple(coords[2:])),
    )

    # Test with MapCoord
    m = WcsNDMap(geom)
    coords = m.geom.get_coord()
    coords_dict = dict(lon=coords[0], lat=coords[1])
    if axes:
        for i, ax in enumerate(axes):
            coords_dict[ax.name] = coords[i + 2]
    map_coords = MapCoord.create(coords_dict, coordsys=coordsys)
    m.set_by_coord(map_coords, coords[0])
    assert_allclose(coords[0], m.get_by_coord(map_coords))
Пример #22
0
def make_test_coords(geom, lon, lat):
    coords = [lon, lat] + [ax.center for ax in geom.axes]
    coords = np.meshgrid(*coords)
    coords = tuple([np.ravel(t) for t in coords])
    return MapCoord.create(coords)
Пример #23
0
def test_mapcoords_create():
    # From existing MapCoord
    coords_cel = MapCoord.create((0.0, 1.0), frame="icrs")
    coords_gal = MapCoord.create(coords_cel, frame="galactic")
    assert_allclose(coords_gal.lon, coords_cel.skycoord.galactic.l.deg)
    assert_allclose(coords_gal.lat, coords_cel.skycoord.galactic.b.deg)

    # 2D Tuple of scalars
    coords = MapCoord.create((0.0, 1.0))
    assert_allclose(coords.lon, 0.0)
    assert_allclose(coords.lat, 1.0)
    assert_allclose(coords[0], 0.0)
    assert_allclose(coords[1], 1.0)
    assert coords.frame is None
    assert coords.ndim == 2

    # 3D Tuple of scalars
    coords = MapCoord.create((0.0, 1.0, 2.0))
    assert_allclose(coords[0], 0.0)
    assert_allclose(coords[1], 1.0)
    assert_allclose(coords[2], 2.0)
    assert coords.frame is None
    assert coords.ndim == 3

    # 2D Tuple w/ NaN coordinates
    coords = MapCoord.create((np.nan, np.nan))

    # 2D Tuple w/ NaN coordinates
    lon, lat = np.array([np.nan, 1.0]), np.array([np.nan, 3.0])
    coords = MapCoord.create((lon, lat))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)

    # 2D Tuple w/ SkyCoord
    lon, lat = np.array([0.0, 1.0]), np.array([2.0, 3.0])
    energy = np.array([100.0, 1000.0])
    skycoord_cel = SkyCoord(lon, lat, unit="deg", frame="icrs")
    skycoord_gal = SkyCoord(lon, lat, unit="deg", frame="galactic")
    coords = MapCoord.create((skycoord_cel, ))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert coords.frame == "icrs"
    assert coords.ndim == 2

    coords = MapCoord.create((skycoord_gal, ))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert coords.frame == "galactic"
    assert coords.ndim == 2

    # SkyCoord
    coords = MapCoord.create(skycoord_cel)
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert coords.frame == "icrs"
    assert coords.ndim == 2
    coords = MapCoord.create(skycoord_gal)
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert coords.frame == "galactic"
    assert coords.ndim == 2

    # 2D dict w/ vectors
    coords = MapCoord.create(dict(lon=lon, lat=lat))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert coords.ndim == 2

    # 3D dict w/ vectors
    coords = MapCoord.create(dict(lon=lon, lat=lat, energy=energy))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert_allclose(coords["energy"], energy)
    assert coords.ndim == 3

    # 3D dict w/ SkyCoord
    coords = MapCoord.create(dict(skycoord=skycoord_cel, energy=energy))
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert_allclose(coords["energy"], energy)
    assert coords.frame == "icrs"
    assert coords.ndim == 3

    # 3D dict  w/ vectors
    coords = MapCoord.create({"energy": energy, "lat": lat, "lon": lon})
    assert_allclose(coords.lon, lon)
    assert_allclose(coords.lat, lat)
    assert_allclose(coords["energy"], energy)
    assert_allclose(coords[0], energy)
    assert_allclose(coords[1], lat)
    assert_allclose(coords[2], lon)
    assert coords.ndim == 3

    # Quantities
    coords = MapCoord.create(dict(energy=energy * u.TeV, lat=lat, lon=lon))
    assert coords["energy"].unit == "TeV"
Пример #24
0
def test_mapcoord_repr():
    coord = MapCoord({"lon": 0, "lat": 0, "energy": 5})
    assert "MapCoord" in repr(coord)