def test_region(self): pos = SkyCoord(81, 21, unit='deg', frame='icrs') radius = Angle(1, 'deg') circ = CircleSkyRegion(pos, radius) idx = circ.contains(self.events.radec) table = self.events.table[idx] assert_allclose(table[4]['RA'], 81, rtol=1) assert_allclose(table[2]['DEC'], 21, rtol=1) assert len(table) == 5
def test_EventList_region(): filename = gammapy_extra.filename("test_datasets/unbundled/hess/run_0023037_hard_eventlist.fits.gz") event_list = EventList.read(filename, hdu="EVENTS") pos = SkyCoord(81, 21, unit="deg", frame="icrs") radius = Angle(1, "deg") circ = CircleSkyRegion(pos, radius) idx = circ.contains(event_list.radec) filtered_list = event_list[idx] assert_allclose(filtered_list[4]["RA"], 81, rtol=1) assert_allclose(filtered_list[2]["DEC"], 21, rtol=1) assert len(filtered_list) == 5
def exclusion_mask(geom): """Example mask for testing.""" pos = SkyCoord(83.633, 22.014, unit="deg", frame="icrs") region = CircleSkyRegion(pos, Angle(0.3, "deg")) exclusion = WcsNDMap.from_geom(geom) exclusion.data = geom.region_mask([region], inside=False) return exclusion
def test_lookup_max_region(self): center = SkyCoord(0, 0, unit='deg', frame='galactic') circle = CircleSkyRegion(center, radius=Quantity(1, 'deg')) pos, value = self.image.lookup_max(circle) assert value == 15 assert_allclose((359.93, -0.01), (pos.galactic.l.deg, pos.galactic.b.deg))
def spectrum_dataset_crab_fine(): e_true = MapAxis.from_edges(np.logspace(-2, 2.5, 109) * u.TeV, name="energy_true") e_reco = MapAxis.from_edges(np.logspace(-2, 2, 73) * u.TeV, name="energy") pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs") radius = Angle(0.11, "deg") region = CircleSkyRegion(pos, radius) return SpectrumDataset.create(e_reco, e_true, region=region)
def test_select_mask(models_gauss): center_sky = SkyCoord("0d", "0d") circle = CircleSkyRegion(center=center_sky, radius=1 * u.deg) axis = MapAxis.from_energy_edges(np.logspace(-1, 1, 3), unit="TeV") geom = WcsGeom.create(skydir=center_sky, width=(5, 4), axes=[axis], binsz=0.02) mask = geom.region_mask([circle]) contribute = models_gauss.select_mask(mask, margin=None, use_evaluation_region=True) assert contribute.names == ["source-1", "source-2"] inside = models_gauss.select_mask(mask, margin=None, use_evaluation_region=False) assert inside.names == ["source-1"] contribute_margin = models_gauss.select_mask(mask, margin=0.1 * u.deg, use_evaluation_region=True) assert contribute_margin.names == ["source-1", "source-2", "source-3"]
def test_to_spectrum_dataset(sky_model, geom, geom_etrue): dataset_ref = get_map_dataset(sky_model, geom, geom_etrue, edisp=True) dataset_ref.counts = dataset_ref.background_model.map * 0.0 dataset_ref.counts.data[1, 50, 50] = 1 dataset_ref.counts.data[1, 60, 50] = 1 gti = GTI.create([0 * u.s], [1 * u.h], reference_time="2010-01-01T00:00:00") dataset_ref.gti = gti on_region = CircleSkyRegion(center=geom.center_skydir, radius=0.05 * u.deg) spectrum_dataset = dataset_ref.to_spectrum_dataset(on_region) spectrum_dataset_corrected = dataset_ref.to_spectrum_dataset( on_region, containment_correction=True) assert np.sum(spectrum_dataset.counts.data) == 1 assert spectrum_dataset.data_shape == (2, 1, 1) assert spectrum_dataset.background.geom.axes[0].nbin == 2 assert spectrum_dataset.aeff.energy.nbin == 3 assert spectrum_dataset.aeff.data.data.unit == "m2" assert spectrum_dataset.edisp.e_reco.nbin == 2 assert spectrum_dataset.edisp.e_true.nbin == 3 assert spectrum_dataset_corrected.aeff.data.data.unit == "m2" assert_allclose(spectrum_dataset.aeff.data.data.value[1], 853023.423047, rtol=1e-5) assert_allclose(spectrum_dataset_corrected.aeff.data.data.value[1], 559476.3357, rtol=1e-5)
def setup(self): from regions import CircleSkyRegion kwargs = {} # Define energy range kwargs['emin'] = 1 * u.TeV kwargs['emax'] = 10 * u.TeV # Define reference image wcs_spec = {'nxpix': 21, 'nypix': 21, 'xref': 83.633083, 'yref': 22.0145, 'coordsys': 'CEL', 'proj': 'CAR', 'binsz': 0.5} kwargs['reference'] = SkyImage.empty(**wcs_spec) # Define background estimator r_in = 0.3 * u.deg width = 0.2 * u.deg kwargs['background_estimator'] = RingBackgroundEstimator(r_in=r_in, width=width) # Defien exclusion mask center = SkyCoord(83.633083, 22.0145, frame='icrs', unit='deg') circle = CircleSkyRegion(center, radius=Angle(0.2, 'deg')) kwargs['exclusion_mask'] = kwargs['reference'].region_mask(circle) kwargs['exclusion_mask'].data = ~kwargs['exclusion_mask'].data self.estimator = IACTBasicImageEstimator(**kwargs) # setup data store and get list of observations data_store = DataStore.from_dir('$GAMMAPY_EXTRA/datasets/hess-crab4-hd-hap-prod2/') self.observations = data_store.obs_list([23523, 23526, 23559, 23592])
def test_get_spectrum(): axis = MapAxis.from_bounds(1, 10, nbin=3, unit="TeV", name="energy") geom = WcsGeom.create( skydir=(0, 0), width=(2.5, 2.5), binsz=0.5, axes=[axis], frame="galactic" ) m = Map.from_geom(geom) m.data += 1 center = SkyCoord(0, 0, frame="galactic", unit="deg") region = CircleSkyRegion(center=center, radius=1 * u.deg) spec = m.get_spectrum(region=region) assert_allclose(spec.data.squeeze(), [13.0, 13.0, 13.0]) spec = m.get_spectrum(region=region, func=np.mean) assert_allclose(spec.data.squeeze(), [1.0, 1.0, 1.0]) spec = m.get_spectrum() assert isinstance(spec.geom.region, RectangleSkyRegion) region = PointSkyRegion(center) spec = m.get_spectrum(region=region) assert_allclose(spec.data.squeeze(), [1.0, 1.0, 1.0])
def test_get_spectrum_weights(): axis = MapAxis.from_bounds(1, 10, nbin=3, unit="TeV", name="energy") geom = WcsGeom.create(skydir=(0, 0), width=(2.5, 2.5), binsz=0.5, axes=[axis], frame="galactic") m_int = Map.from_geom(geom, dtype="int") m_int.data += 1 weights = Map.from_geom(geom, dtype="bool") weights.data[:, 2, 2] = True bad_weights = Map.from_geom(geom.to_image(), dtype="bool") center = SkyCoord(0, 0, frame="galactic", unit="deg") region = CircleSkyRegion(center=center, radius=1 * u.deg) spec_int = m_int.get_spectrum(region=region, weights=weights) assert spec_int.data.dtype == np.dtype("int") assert_allclose(spec_int.data.squeeze(), [1, 1, 1]) with pytest.raises(ValueError): m_int.get_spectrum(region=region, weights=bad_weights)
def test_get_spectrum_type(): axis = MapAxis.from_bounds(1, 10, nbin=3, unit="TeV", name="energy") geom = WcsGeom.create(skydir=(0, 0), width=(2.5, 2.5), binsz=0.5, axes=[axis], frame="galactic") m_int = Map.from_geom(geom, dtype="int") m_int.data += 1 m_bool = Map.from_geom(geom, dtype="bool") m_bool.data += True center = SkyCoord(0, 0, frame="galactic", unit="deg") region = CircleSkyRegion(center=center, radius=1 * u.deg) spec_int = m_int.get_spectrum(region=region) assert spec_int.data.dtype == np.dtype("int") assert_allclose(spec_int.data.squeeze(), [13, 13, 13]) spec_bool = m_bool.get_spectrum(region=region, func=np.any) assert spec_bool.data.dtype == np.dtype("bool") assert_allclose(spec_bool.data.squeeze(), [1, 1, 1])
def test_regions_sky_has_wcs(self): from regions import (CircleSkyRegion, RectanglePixelRegion, CirclePixelRegion, EllipsePixelRegion) # Mimic interactive region (before) self.imviz._apply_interactive_region('bqplot:circle', (1.5, 2.5), (3.6, 4.6)) sky = SkyCoord(ra=337.5202808, dec=-20.833333059999998, unit='deg') my_reg_sky = CircleSkyRegion(sky, Angle(0.5, u.arcsec)) self.imviz.load_static_regions({'my_reg_sky_1': my_reg_sky}) # Mimic interactive regions (after) self.imviz._apply_interactive_region('bqplot:ellipse', (-2, 0), (5, 4.5)) self.imviz._apply_interactive_region('bqplot:rectangle', (0, 0), (10, 10)) # Check interactive regions. We do not check if the translation is correct, # that check hopefully is already done in glue-astronomy. # Apparently, static region ate up one number... subsets = self.imviz.get_interactive_regions() assert list(subsets.keys()) == ['Subset 1', 'Subset 3', 'Subset 4'], subsets assert isinstance(subsets['Subset 1'], CirclePixelRegion) assert isinstance(subsets['Subset 3'], EllipsePixelRegion) assert isinstance(subsets['Subset 4'], RectanglePixelRegion) # Check static region self.verify_region_loaded('my_reg_sky_1')
def create_data(input_dir, dataset_config, exclusion_map=None): telescope = dataset_config['telescope'] on_region_radius = dataset_config['on_radius'] energy_bins = dataset_config['e_reco_bins'] containment = dataset_config['containment_correction'] ds = DataStore.from_dir(os.path.join(input_dir, telescope)) observations = ds.get_observations(ds.obs_table['OBS_ID'].data) t_obs = sum([o.observation_live_time_duration for o in observations]) # from IPython import embed; embed() print(f'Total obstime for {telescope} is {t_obs.to("h")}') source_position = dataset_config['source_position'] on_region = CircleSkyRegion(center=source_position, radius=on_region_radius) print('Estimating Background') bkg_estimate = ReflectedRegionsBackgroundEstimator( observations=observations, on_region=on_region, exclusion_mask=exclusion_map) bkg_estimate.run() print('Extracting Count Spectra') extract = SpectrumExtraction( observations=observations, bkg_estimate=bkg_estimate.result, e_true=energy_bins, e_reco=energy_bins, containment_correction=containment, use_recommended_erange=False, # TODO this might have to be checked. ) extract.run() return extract
def test_filter_events(observation): custom_filter = { "type": "custom", "opts": { "parameter": "ENERGY", "band": Quantity([0.8 * u.TeV, 10.0 * u.TeV]) }, } target_position = SkyCoord(ra=229.2, dec=-58.3, unit="deg", frame="icrs") region_radius = Angle("0.2 deg") region = CircleSkyRegion(center=target_position, radius=region_radius) circular_region_filter = { "type": "circular_region", "opts": { "region": region } } time_filter = Time([53090.12, 53090.13], format="mjd", scale="tt") obs_filter = ObservationFilter( event_filters=[custom_filter, circular_region_filter], time_filter=time_filter) events = observation.events filtered_events = obs_filter.filter_events(events) assert np.all((filtered_events.energy >= 0.8 * u.TeV) & (filtered_events.energy < 10.0 * u.TeV)) assert np.all((filtered_events.time >= time_filter[0]) & (filtered_events.time < time_filter[1])) assert np.all( region.center.separation(filtered_events.radec) < region_radius)
def run(dataset, correlation_radius, sigma, negative): estimator_excess = ExcessMapEstimator( correlation_radius=correlation_radius, n_sigma=1, n_sigma_ul=3, selection_optional=None, energy_edges=energy_edges, ) result = estimator_excess.run(dataset) sources = find_peaks( result["sqrt_ts"], threshold=sigma, min_distance=correlation_radius, ) if negative is True: result["sqrt_ts"].data = -result["sqrt_ts"].data sources.vstack( find_peaks( result["sqrt_ts"], threshold=sigma, min_distance=correlation_radius, ) ) regions = [] for source in sources: skydir = SkyCoord(source["ra"], source["dec"], unit="deg", frame="icrs") if dataset.counts.geom.to_image().contains(skydir): regions.append(CircleSkyRegion(skydir, 0.2 * u.deg)) return dataset.counts.geom.to_image().region_mask(regions=regions, inside=False), result
def spec_extraction(): data_store = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1/") obs_ids = [23523, 23526] observations = data_store.get_observations(obs_ids) target_position = SkyCoord(ra=83.63308, dec=22.01450, unit="deg") on_region_radius = Angle("0.11 deg") on_region = CircleSkyRegion(center=target_position, radius=on_region_radius) bkg_estimator = ReflectedRegionsBackgroundEstimator( on_region=on_region, observations=observations) bkg_estimator.run() e_reco = EnergyBounds.equal_log_spacing(0.2, 100, 50, unit="TeV") # fine binning e_true = EnergyBounds.equal_log_spacing(0.05, 100, 200, unit="TeV") extraction = SpectrumExtraction( observations=observations, bkg_estimate=bkg_estimator.result, containment_correction=False, e_reco=e_reco, e_true=e_true, ) extraction.run() extraction.compute_energy_threshold(method_lo="area_max", area_percent_lo=10.0) return extraction
def spectrum_dataset_gc(): e_reco = np.logspace(0, 2, 5) * u.TeV e_true = np.logspace(-0.5, 2, 11) * u.TeV pos = SkyCoord(0.0, 0.0, unit="deg", frame="galactic") radius = Angle(0.11, "deg") region = CircleSkyRegion(pos, radius) return SpectrumDataset.create(e_reco, e_true, region=region)
def __init__(self, lambda_true: u.quantity.Quantity, index_true: float, normalization_true: u.quantity.Quantity, livetime: u.quantity.Quantity, pointing_galactic: dict, e_reco_binning: dict, on_region_radius: str, irf_file: str): normalization_true = normalization_true.to("cm-2 s-1 TeV-1") self.lambda_true = lambda_true self.index_true = index_true self.normalization_true = normalization_true pointing_l = pointing_galactic["pointing_l"] pointing_b = pointing_galactic["pointing_b"] pointing = SkyCoord(pointing_l, pointing_b, unit="deg", frame="galactic") e_reco_min = u.Quantity(e_reco_binning["e_reco_min"]).to("TeV").value e_reco_max = u.Quantity(e_reco_binning["e_reco_max"]).to("TeV").value n_e_reco = e_reco_binning["n_e_reco"] self.energy_axis = np.logspace(np.log10(e_reco_min), np.log10(e_reco_max), n_e_reco) * u.TeV on_region_radius = Angle(on_region_radius) self.on_region = CircleSkyRegion(center=pointing, radius=on_region_radius) irfs = load_cta_irfs(irf_file) self.obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
def create_stacked_dataset(analysis): # source_pos = SkyCoord.from_name("MSH 15-52") source_pos = SkyCoord(228.32, -59.08, unit="deg") # get the geom that we use geom = analysis.datasets[0].counts.geom energy_axis = analysis.datasets[0].counts.geom.axes["energy"] geom_image = geom.to_image().to_cube([energy_axis.squash()]) # Make the exclusion mask regions = CircleSkyRegion(center=source_pos, radius=0.3 * u.deg) exclusion_mask = geom_image.region_mask([regions], inside=False) ring_maker = RingBackgroundMaker(r_in="0.5 deg", width="0.3 deg", exclusion_mask=exclusion_mask) # Creation of the MapDatasetOnOff energy_axis_true = analysis.datasets[0].exposure.geom.axes["energy_true"] stacked_on_off = MapDatasetOnOff.create(geom=geom_image, energy_axis_true=energy_axis_true, name="stacked") for dataset in analysis.datasets: # Ring extracting makes sense only for 2D analysis dataset_on_off = ring_maker.run(dataset.to_image()) stacked_on_off.stack(dataset_on_off) return stacked_on_off
def test_reflected_bkg_maker_no_off(reflected_bkg_maker, observations, caplog): pos = SkyCoord(83.6333313, 21.51444435, unit="deg", frame="icrs") radius = Angle(0.11, "deg") region = CircleSkyRegion(pos, radius) maker = SpectrumDatasetMaker(selection=["counts"]) datasets = [] e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy") e_true = MapAxis.from_edges(np.logspace(-0.5, 2, 11) * u.TeV, name="energy_true") geom = RegionGeom.create(region=region, axes=[e_reco]) dataset_empty = SpectrumDataset.create(geom=geom, energy_axis_true=e_true) for obs in observations: dataset = maker.run(dataset_empty, obs) dataset_on_off = reflected_bkg_maker.run(dataset, obs) datasets.append(dataset_on_off) assert datasets[0].counts_off is None assert_allclose(datasets[0].acceptance_off, 0) assert_allclose(datasets[0].mask_safe.data, False) assert "WARNING" in [record.levelname for record in caplog.records] message1 = f"ReflectedRegionsBackgroundMaker failed. " \ f"No OFF region found outside exclusion mask for {datasets[0].name}." message2 = f"ReflectedRegionsBackgroundMaker failed. " \ f"Setting {datasets[0].name} mask to False." assert message1 in [record.message for record in caplog.records] assert message2 in [record.message for record in caplog.records]
def test_mapdatasetonoff_to_spectrum_dataset(images): e_reco = MapAxis.from_bounds(0.1, 10.0, 1, name="energy", unit=u.TeV, interp="log") new_images = dict() for key, image in images.items(): new_images[key] = Map.from_geom(image.geom.to_cube([e_reco]), data=image.data[np.newaxis, :, :]) dataset = get_map_dataset_onoff(new_images) gti = GTI.create([0 * u.s], [1 * u.h], reference_time="2010-01-01T00:00:00") dataset.gti = gti on_region = CircleSkyRegion(center=dataset.counts.geom.center_skydir, radius=0.1 * u.deg) spectrum_dataset = dataset.to_spectrum_dataset(on_region) assert spectrum_dataset.counts.data[0] == 8 assert spectrum_dataset.data_shape == (1, 1, 1) assert spectrum_dataset.counts_off.data[0] == 33914 assert_allclose(spectrum_dataset.alpha.data[0], 0.0002143, atol=1e-7) excess_map = new_images["counts"] - new_images["background"] excess_true = excess_map.get_spectrum(on_region, np.sum).data[0] excess = spectrum_dataset.excess.data[0] assert_allclose(excess, excess_true, atol=1e-6) assert spectrum_dataset.name != dataset.name
def test_targetsummary(data_manager): pos = SkyCoord(83.63 * u.deg, 22.01 * u.deg, frame='icrs') on_size = 0.3 * u.deg on_region = CircleSkyRegion(pos, on_size) target = Target(on_region, name='Test Target', obs_id=[23523, 23592]) assert 'Target' in str(target)
def spectrum_dataset_gc(): e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy") e_true = MapAxis.from_edges(np.logspace(-0.5, 2, 11) * u.TeV, name="energy_true") pos = SkyCoord(0.0, 0.0, unit="deg", frame="galactic") radius = Angle(0.11, "deg") region = CircleSkyRegion(pos, radius) return SpectrumDataset.create(e_reco, e_true, region=region)
def spectrum_dataset_crab_fine(): e_true = np.logspace(-2, 2.5, 109) * u.TeV e_reco = np.logspace(-2, 2, 73) * u.TeV pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs") radius = Angle(0.11, "deg") region = CircleSkyRegion(pos, radius) return SpectrumDataset.create(e_reco, e_true, region=region)
def build_exclusion_mask_from_catalog(geom, catalog="gamma-cat", min_radius="0.3 deg"): """Build exclusion mask from a given geometry and input catalog. Parameters: ----------- geom : `~gammapy.maps.WcsGeom` the input WCS geometry catalog : str or `~gammapy.catalog.SourceCatalog` the input catalog to use. Default is 'gamma-cat'. min_radius : `~astropy.coordinates.Angle` the minimum radius of the circular exclusion radius around a source. Default is 0.3 deg. """ if catalog is None: catalog = "gamma-cat" if isinstance(catalog, str): try: catalog = CATALOG_REGISTRY.get_cls(catalog)() except KeyError: raise ValueError(f"Unknown catalog name. Available catalogs are :\n{CATALOG_REGISTRY}") exclusion_regions = [] min_radius = Angle(min_radius) is_in_geom = geom.contains(catalog.positions) src_in_geom = catalog[is_in_geom].to_models() for src in src_in_geom.to_regions(): if not isinstance(src, PointSkyRegion): radius += src.width exclusion_regions.append(CircleSkyRegion(src.center, min_radius)) return ~geom.region_mask(exclusion_regions)
def exclusion_mask(): """Example mask for testing.""" pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs") exclusion_region = CircleSkyRegion(pos, Angle(0.3, "deg")) geom = WcsGeom.create(skydir=pos, binsz=0.02, width=10.0) mask = geom.region_mask([exclusion_region], inside=False) return WcsNDMap(geom, data=mask)
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)
def test_compute_flux_spatial_no_psf(): # check that spatial integration is not performed in the absence of a psf 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 = GaussianSpatialModel(lon_0=0 * u.deg, lat_0=0 * u.deg, frame="galactic", sigma="0.1 deg") models = SkyModel(spectral_model=spectral_model, spatial_model=spatial_model) model = Models(models) exposure_region = RegionNDMap.create(region, axes=[energy_axis_true]) exposure_region.data += 1.0 exposure_region.unit = "m2 s" evaluator = MapEvaluator(model=model[0], exposure=exposure_region) flux = evaluator.compute_flux_spatial() assert_allclose(flux, 1.0)
def target(): """An example Target for tests.""" center = SkyCoord(83.63, 22.01, unit='deg', frame='icrs') radius = Angle('0.11 deg') on_region = CircleSkyRegion(center, radius) target = Target(on_region) return target
def get_map_dataset(sky_model, geom, geom_etrue, edisp=True, **kwargs): """Returns a MapDatasets""" # define background model m = Map.from_geom(geom) m.quantity = 0.2 * np.ones(m.data.shape) background_model = BackgroundModel(m) psf = get_psf(geom_etrue) exposure = get_exposure(geom_etrue) if edisp: # define energy dispersion e_true = geom_etrue.get_axis_by_name("energy").edges e_reco = geom.get_axis_by_name("energy").edges edisp = EnergyDispersion.from_diagonal_response(e_true=e_true, e_reco=e_reco) else: edisp = None # define fit mask center = sky_model.spatial_model.position circle = CircleSkyRegion(center=center, radius=1 * u.deg) mask_fit = background_model.map.geom.region_mask([circle]) mask_fit = Map.from_geom(geom, data=mask_fit) return MapDataset(model=sky_model, exposure=exposure, background_model=background_model, psf=psf, edisp=edisp, mask_fit=mask_fit, **kwargs)
def spec_extraction(): data_store = DataStore.from_dir( '$GAMMAPY_EXTRA/datasets/hess-crab4-hd-hap-prod2/') obs_ids = [23523, 23526] obs_list = data_store.obs_list(obs_ids) target_position = SkyCoord(ra=83.63308, dec=22.01450, unit='deg') on_region_radius = Angle('0.11 deg') on_region = CircleSkyRegion(center=target_position, radius=on_region_radius) target = Target(on_region=on_region, name='Crab', tag='ana_crab') exclusion_file = '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits' allsky_mask = SkyImage.read(exclusion_file) exclusion_mask = allsky_mask.cutout( position=target.on_region.center, size=Angle('6 deg'), ) bkg_estimator = ReflectedRegionsBackgroundEstimator( on_region=on_region, obs_list=obs_list, exclusion_mask=exclusion_mask) bkg_estimator.run() e_reco = EnergyBounds.equal_log_spacing(0.2, 100, 50, unit='TeV') # fine binning e_true = EnergyBounds.equal_log_spacing(0.05, 100, 200, unit='TeV') extraction = SpectrumExtraction(obs_list=obs_list, bkg_estimate=bkg_estimator.result, containment_correction=False, e_reco=e_reco, e_true=e_true) extraction.run() extraction.compute_energy_threshold(method_lo='area_max', area_percent_lo=10.0) return extraction
def test_exclusion_region(tmp_path): config = get_example_config("1d") analysis = Analysis(config) exclusion_region = CircleSkyRegion(center=SkyCoord("85d 23d"), radius=1 * u.deg) exclusion_mask = Map.create(npix=(150, 150), binsz=0.05, skydir=SkyCoord("83d 22d")) mask = exclusion_mask.geom.region_mask([exclusion_region], inside=False) exclusion_mask.data = mask.astype(int) filename = tmp_path / "exclusion.fits" exclusion_mask.write(filename) config.datasets.background.method = "reflected" config.datasets.background.exclusion = filename analysis.get_observations() analysis.get_datasets() assert len(analysis.datasets) == 2 config = get_example_config("3d") analysis = Analysis(config) analysis.get_observations() analysis.get_datasets() geom = analysis.datasets[0]._geom exclusion = WcsNDMap.from_geom(geom) exclusion.data = geom.region_mask([exclusion_region], inside=False).astype(int) filename = tmp_path / "exclusion3d.fits" exclusion.write(filename) config.datasets.background.exclusion = filename analysis.get_datasets() assert len(analysis.datasets) == 1
from astropy.coordinates import SkyCoord, Angle from regions import ( make_example_dataset, CircleSkyRegion, ) import matplotlib.pyplot as plt config = dict(crpix=(18, 9), cdelt=(-10, 10), shape=(18, 36)) dataset = make_example_dataset(data='simulated', config=config) wcs = dataset.wcs fig = plt.figure() ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcs) ax.set_xlim(-0.5, dataset.config['shape'][1] - 0.5) ax.set_ylim(-0.5, dataset.config['shape'][0] - 0.5) ax.imshow(dataset.image.data, cmap='gray', vmin=0, vmax=1, interpolation='nearest', origin='lower') for source in dataset.source_table: # Plot a sky circle around each source center = SkyCoord(source['GLON'], source['GLAT'], unit='deg', frame='galactic') radius = Angle(20, 'deg') region = CircleSkyRegion(center=center, radius=radius) pix_region = region.to_pixel(wcs=wcs) pix_region.plot(ax=ax, edgecolor='yellow', facecolor='yellow', alpha=0.5, lw=3) plt.show()
# load example dataset to get skymap config = dict(crval=(0, 0), crpix=(180, 90), cdelt=(-1, 1), shape=(180, 360)) dataset = make_example_dataset(data='simulated', config=config) wcs = dataset.wcs # remove sources dataset.image.data = np.zeros_like(dataset.image.data) # define 2 sky circles circle1 = CircleSkyRegion( center=SkyCoord(20, 0, unit='deg', frame='galactic'), radius=Angle('30 deg') ) circle2 = CircleSkyRegion( center=SkyCoord(50, 45, unit='deg', frame='galactic'), radius=Angle('30 deg'), ) # define skycoords lon = np.arange(-180, 181, 10) lat = np.arange(-90, 91, 10) coords = np.array(np.meshgrid(lon, lat)).T.reshape(-1, 2) skycoords = SkyCoord(coords, unit='deg', frame='galactic') # get events in AND and XOR compound_and = circle1 & circle2
"""Example how to compute and plot reflected regions.""" from astropy.coordinates import SkyCoord, Angle from regions import CircleSkyRegion from gammapy.image import SkyMask from gammapy.background import find_reflected_regions mask = SkyMask.empty(name='Exclusion Mask', nxpix=801, nypix=701, binsz=0.01, coordsys='CEL', xref=83.2, yref=22.7) mask.fill_random_circles(n=8, min_rad=30, max_rad=80) pos = SkyCoord(80.2, 23.5, unit='deg') radius = Angle(0.4, 'deg') test_region = CircleSkyRegion(pos, radius) center = SkyCoord(82.8, 22.5, unit='deg') regions = find_reflected_regions(test_region, center, mask) import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 5), dpi=80) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=mask.wcs) mask.plot(ax, fig) for reg in regions: reg.plot(ax, facecolor='red') test_region.plot(ax, facecolor='blue') plt.show()
from regions import ( make_example_dataset, CircleSkyRegion, ) import matplotlib.pyplot as plt config = dict(crpix=(18, 9), cdelt=(-10, 10), shape=(18, 36)) dataset = make_example_dataset(data='simulated', config=config) wcs = dataset.wcs fig = plt.figure() ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcs) ax.set_xlim(-0.5, dataset.config['shape'][1] - 0.5) ax.set_ylim(-0.5, dataset.config['shape'][0] - 0.5) ax.imshow(dataset.image.data, cmap='gray', vmin=0, vmax=1, interpolation='nearest', origin='lower') for source in dataset.source_table: # Plot a sky circle around each source center = SkyCoord(source['GLON'], source['GLAT'], unit='deg', frame='galactic') radius = Angle(20, 'deg') region = CircleSkyRegion(center=center, radius=radius) pix_region = region.to_pixel(wcs=wcs) pix_region.plot(ax, edgecolor='green', facecolor='none', alpha=0.8, lw=3) region.plot(ax, edgecolor='yellow', facecolor='none', alpha=0.8, lw=3) plt.show()
"""Example how to compute and plot reflected regions.""" from astropy.coordinates import SkyCoord, Angle from regions import CircleSkyRegion from gammapy.image import SkyMask from gammapy.background import find_reflected_regions mask = SkyMask.empty(name='Exclusion Mask', nxpix=801, nypix=701, binsz=0.01, coordsys='CEL', xref=83.2, yref=22.7) mask.fill_random_circles(n=8, min_rad=30, max_rad=80) pos = SkyCoord(80.2, 23.5, unit='deg') radius = Angle(0.4, 'deg') test_region = CircleSkyRegion(pos, radius) center = SkyCoord(82.8, 22.5, unit='deg') regions = find_reflected_regions(test_region, center, mask) import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 5), dpi=80) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=mask.wcs) mask.plot(ax, fig) for reg in regions: reg.to_pixel(mask.wcs).plot(ax, facecolor='red') test_region.to_pixel(mask.wcs).plot(ax, facecolor='blue') plt.show()