Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
wcs = pywcs.WCS(naxis=2)
wcs.wcs.crpix = [5.5, 5.5]
wcs.wcs.cdelt = [0.1, -0.1]
wcs.wcs.crval = [l, b]
wcs.wcs.ctype = ["GLON-ZEA".encode("ascii"), "GLAT-ZEA".encode("ascii")]
import pyregion.wcs_helper as wcs_helper
proj = wcs_helper.get_kapteyn_projection(wcs)
cdelt = wcs_helper.estimate_cdelt(proj, 5.5, 5.5)
assert np.allclose([cdelt], [0.1])
region_string="fk5; circle(%s, %s, 0.5000)" % (ra,dec)
reg = pyregion.parse(region_string).as_imagecoord(wcs)
assert np.allclose([reg[0].coord_list[-1]], [0.5/0.1])
def filter_events(self, region):
"""
Filter events using a ds9 *region*. Requires the pyregion package.
Returns a new EventList.
"""
import pyregion
import os
if os.path.exists(region):
reg = pyregion.open(region)
else:
reg = pyregion.parse(region)
r = reg.as_imagecoord(header=self.wcs.to_header())
f = r.get_filter()
idxs = f.inside_x_y(self["xpix"], self["ypix"])
if idxs.sum() == 0:
raise RuntimeError("No events are inside this region!")
new_events = {}
for k, v in self.items():
new_events[k] = v[idxs]
return EventList(new_events, self.parameters)
def ellipses(ra_list, dec_list, height_list, width_list, angle_list):
# Initialize the region string
region_string = "# Region file format: DS9 version 3.0\n"
region_string += "global color=green\n"
region_string += "fk5\n"
for ra, dec, height, width, angle in zip(ra_list, dec_list, height_list, width_list, angle_list):
line = "fk5;ellipse(%s,%s,%.2f\",%.2f\",%s)\n" % (ra, dec, height, width, angle)
region_string += line
region = pyregion.parse(region_string)
# Return the region
return region
"""
Extract a masked subcube from a ds9 region or a pyregion Region object
(only functions on celestial dimensions)
Parameters
----------
ds9region: str or `pyregion.Shape`
The region to extract
allow_empty: bool
If this is False, an exception will be raised if the region
contains no overlap with the cube
"""
import pyregion
if isinstance(ds9region, six.string_types):
shapelist = pyregion.parse(ds9region)
else:
shapelist = ds9region
if shapelist[0].coord_format not in ('physical','image'):
# Requires astropy >0.4...
# pixel_regions = shapelist.as_imagecoord(self.wcs.celestial.to_header())
# convert the regions to image (pixel) coordinates
celhdr = self.wcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()
celhdr['NAXIS1'] = self.shape[2]
celhdr['NAXIS2'] = self.shape[1]
pixel_regions = shapelist.as_imagecoord(celhdr)
recompute_shifted_mask = False
else:
pixel_regions = copy.deepcopy(shapelist)
# we need to change the reference pixel after cropping
recompute_shifted_mask = True
import matplotlib.pyplot as plt
import pyregion
region = """
image
circle(100, 100, 80)
box(200, 150, 150, 120, 0)
"""
r = pyregion.parse(region)
mask_1or2 = r.get_mask(shape=(300, 300))
myfilter = r.get_filter()
mask_1and2 = (myfilter[0] & myfilter[1]).mask((300, 300))
plt.subplot(121).imshow(mask_1or2, origin="lower", interpolation="nearest")
plt.subplot(122).imshow(mask_1and2, origin="lower", interpolation="nearest")
plt.show()
# Loop over the objects in the coordinates list, adding a line for each one
for object in coordinates:
if type(object).__name__ == "Gaussian2D": line = "ellipse(" + str(object.x_mean.value) + "," + str(object.y_mean.value) + "," + str(object.x_stddev.value) + "," + str(object.y_stddev.value) + ",0.0)\n"
elif type(object).__name__ == "AiryDisk2D":
# see https://en.wikipedia.org/wiki/Airy_disk#Approximation_using_a_Gaussian_profile and
# http://astropy.readthedocs.org/en/latest/api/astropy.modeling.functional_models.AiryDisk2D.html#astropy.modeling.functional_models.AiryDisk2D
sigma = 0.42 * object.radius.value * 0.81989397882
line = "ellipse(" + str(object.x_0.value) + "," + str(object.y_0.value) + "," + str(sigma) + "," + str(sigma) + ",0.0)\n"
else: raise ValueError("Models other than Gaussian2D and AiryDisk2D are not yet supported")
region_string += line
# Parse the region string into a region object
region = pyregion.parse(region_string)
# Return the region
return region
def circles(ra_list, dec_list, radius_list):
# Initialize the region string
region_string = "# Region file format: DS9 version 3.0\n"
region_string += "global color=green\n"
region_string += "fk5\n"
for ra, dec, radius in zip(ra_list, dec_list, radius_list):
line = "fk5;circle(%s,%s,%.2f\")\n" % (ra, dec, radius)
region_string += line
region = pyregion.parse(region_string)
# Return the region
return region
def subcube_from_ds9region(self, ds9region):
"""
Extract a masked subcube from a ds9 region or a pyregion Region object
(only functions on celestial dimensions)
Parameters
----------
ds9region: str or `pyregion.Shape`
The region to extract
"""
import pyregion
if isinstance(ds9region, six.string_types):
shapelist = pyregion.parse(ds9region)
else:
shapelist = ds9region
if shapelist[0].coord_format not in ('physical','image'):
# Requires astropy >0.4...
# pixel_regions = shapelist.as_imagecoord(self.wcs.celestial.to_header())
# convert the regions to image (pixel) coordinates
celhdr = self.wcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()
pixel_regions = shapelist.as_imagecoord(celhdr)
else:
# For this to work, we'd need to change the reference pixel after cropping.
# Alternatively, we can just make the full-sized mask... todo....
raise NotImplementedError("Can't use non-celestial coordinates with regions.")
pixel_regions = shapelist
# This is a hack to use mpl to determine the outer bounds of the regions