How to use the pyregion.ShapeList function in pyregion

To help you get started, we’ve selected a few pyregion examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Stargrazer82301 / CAAPR / CAAPR / CAAPR_AstroMagic / CAAPR_AstroMagic.py View on Github external
gal_found = False
    for gal_region in gal_regions:
        if 'text' in gal_region.attr[1].keys():
            gal_name = gal_region.attr[1]['text'].replace(' ','').replace(' (principal)','')
            if gal_name==gal_principal:
                gal_found = True
                break
    if gal_found==False:
        shutil.copy2(sat_path, sat_path.replace('.reg','_revised.reg'))
        shutil.copy2(star_path, star_path.replace('.reg','_revised.reg'))
        return star_segments



    # Loop back over the saturation regions, not keeping those that aren't being retained, or which wholly encompass target galaxy, or are too lose to galaxy centre
    sat_regions_out = pyregion.ShapeList([])
    principal_dist_beam_thresh = 2.0
    star_regions = pyregion.open(star_path)
    for sat_region in sat_regions:

        # Do initial check if saturation region encompasses centre of principal galaxy
        i_dist = gal_region.coord_list[0] - sat_region.coord_list[0]
        j_dist = gal_region.coord_list[1] - sat_region.coord_list[1]
        if (i_dist**2.0+j_dist**2.0)<=(np.min(sat_region.coord_list[2:4]))**2.0:

            # If initial check indicates risk, do full mask check
            sat_mask = ChrisFuncs.Photom.EllipseMask( np.zeros(image.shape), np.max(sat_region.coord_list[2:4]), np.max(sat_region.coord_list[2:4])/np.min(sat_region.coord_list[2:4]), sat_region.coord_list[4], sat_region.coord_list[1], sat_region.coord_list[0])
            if sat_mask[ pod['centre_i'], pod['centre_j'] ]==1.0:

                # If saturation region envelops galaxy core, find corresponding star region
                sat_region_index = sat_region.attr[1]['text']
                for star_region in star_regions:
github astropy / pyregion / docs / figures / region_drawing2.py View on Github external
# Use custom function for patch attribute
def fixed_color(shape, saved_attrs):
    attr_list, attr_dict = saved_attrs
    attr_dict["color"] = "red"
    kwargs = properties_func_default(shape, (attr_list, attr_dict))

    return kwargs


# select region shape with tag=="Group 1"
r1 = pyregion.ShapeList([rr for rr in r if rr.attr[1].get("tag") == "Group 1"])
patch_list1, artist_list1 = r1.get_mpl_patches_texts(fixed_color)

r2 = pyregion.ShapeList([rr for rr in r if rr.attr[1].get("tag") != "Group 1"])
patch_list2, artist_list2 = r2.get_mpl_patches_texts()

for p in patch_list1 + patch_list2:
    ax.add_patch(p)
for t in artist_list1 + artist_list2:
    ax.add_artist(t)

plt.show()
github astropy / astroquery / docs / gallery-examples / example7_alma.py View on Github external
fig = aplpy.FITSFigure(m83_images[0])
fig.show_grayscale(stretch='arcsinh', vmid=0.1)
fig.show_circles(unique_public_circle_parameters[:, 0],
                 unique_public_circle_parameters[:, 1],
                 unique_public_circle_parameters[:, 2],
                 color='b', alpha=0.2)


# Use pyregion to write the observed regions to disk.  Pyregion has a very
# awkward API; there is (in principle) work in progress to improve that
# situation but for now one must do all this extra work.

import pyregion
from pyregion.parser_helper import Shape
prv_regions = pyregion.ShapeList([Shape('circle', [x, y, r]) for x, y, r in private_circle_parameters])
pub_regions = pyregion.ShapeList([Shape('circle', [x, y, r]) for x, y, r in public_circle_parameters])
for r, (x, y, c) in zip(prv_regions+pub_regions,
                     np.vstack([private_circle_parameters,
                                public_circle_parameters])):
    r.coord_format = 'fk5'
    r.coord_list = [x, y, c]
    r.attr = ([], {'color': 'green',  'dash': '0 ',  'dashlist': '8 3 ',  'delete': '1 ',  'edit': '1 ',
                   'fixed': '0 ',  'font': '"helvetica 10 normal roman"',  'highlite': '1 ',
                   'include': '1 ',  'move': '1 ',  'select': '1 ',  'source': '1',  'text': '',
                   'width': '1 '})

prv_regions.write('M83_observed_regions_private_March2015.reg')
pub_regions.write('M83_observed_regions_public_March2015.reg')

prv_mask = fits.PrimaryHDU(prv_regions.get_mask(m83_images[0][0]).astype('int'),
                           header=m83_images[0][0].header)
github astropy / astroquery / docs / gallery-examples / example7_alma.py View on Github external
def pyregion_subset(region, data, mywcs):
    """
    Return a subset of an image (`data`) given a region.
    """
    shapelist = pyregion.ShapeList([region])
    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 = mywcs.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
    # (but it's a legit hack - pyregion needs a major internal refactor
    # before we can approach this any other way, I think -AG)
    mpl_objs = pixel_regions.get_mpl_patches_texts()[0]
github astropy / astroquery / astroquery / alma / utils.py View on Github external
def pyregion_subset(region, data, mywcs):
    """
    Return a subset of an image (``data``) given a region.

    Parameters
    ----------
    region : `~pyregion.Shape`
        A Shape from a pyregion-parsed region file
    data : np.ndarray
        An array with shape described by WCS
    mywcs : `astropy.wcs.WCS`
        A world coordinate system describing the data
    """
    import pyregion

    shapelist = pyregion.ShapeList([region])
    if shapelist[0].coord_format not in ('physical', 'image'):
        celhdr = mywcs.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
    # (but it's a legit hack - pyregion needs a major internal refactor
    # before we can approach this any other way, I think -AG)
    mpl_objs = pixel_regions.get_mpl_patches_texts()[0]
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / tools / regions.py View on Github external
def expand(region, factor):

    """
    This function ...
    :param region:
    :param factor:
    :return:
    """

    # Create a new region
    region_expanded = pyregion.ShapeList([])

    # Loop over all shapes in the original region
    for shape in region:

        # Create a new shape
        expanded_shape = copy.deepcopy(shape)

        # Set the size of the new shape
        expanded_shape.coord_list[2] *= factor
        if shape.name == "ellipse": expanded_shape.coord_list[3] *= factor

        # Add the new shape to the new region
        region_expanded.append(expanded_shape)

    # Return the new region
    return region_expanded
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / magic / tools / regions.py View on Github external
def create_annulus(region, outer_factor, inner_factor=1.0):

    """
    This function ...
    :param region:
    :param outer_factor:
    :param inner_factor:
    :return:
    """

    # Create a new region
    region_annulus = pyregion.ShapeList([])

    # ...
    for shape in region:

        # Create new shapes by deep-copying the original shape
        # Creating new shapes from scratch: pyregion.parser_helper.Shape(None, None)
        inner_shape = copy.deepcopy(shape)
        outer_shape = copy.deepcopy(shape)

        # Add a '-' symbol to the name of the inner region
        inner_shape.name = '-' + shape.name

        # Set the size of the inner shape
        inner_shape.coord_list[2] *= inner_factor
        inner_shape.coord_list[3] *= inner_factor
github Stargrazer82301 / CAAPR / CAAPR / CAAPR_AstroMagic / CAAPR_AstroMagic.py View on Github external
# Update saturated star segments map
                            star_segments[ np.where(star_segments==float(sat_region_index)) ] = 0.0
                            sat_mask_new = ChrisFuncs.Photom.EllipseMask( np.zeros(image.shape), np.max(sat_region.coord_list[2:4]), np.max(sat_region.coord_list[2:4])/np.min(sat_region.coord_list[2:4]), sat_region.coord_list[4], sat_region.coord_list[1], sat_region.coord_list[0])
                            star_segments[ np.where(sat_mask_new==1.0) ] = float(sat_region_index)
                            sat_regions_out.append(sat_region)
                            #sat_indices_bad.append( float(sat_region.attr[1]['text']) )
                            continue
        else:
            sat_regions_out.append(sat_region)



    # Now read in and loop over the star region file
    star_regions = pyregion.open(star_path)
    star_regions_out = pyregion.ShapeList([])
    for star_region in star_regions:

        # Remove stars that are located too close to centre of principal galaxy
        principal_dist = np.sqrt( (gal_region.coord_list[0]-star_region.coord_list[0])**2.0 + (gal_region.coord_list[1]-star_region.coord_list[1])**2.0 )
        if principal_dist<=((band_dict['beam_arcsec']/pod['pix_arcsec'])*principal_dist_beam_thresh):
            continue

        # If star has passed all criteria, record it to output
        star_regions_out.append(star_region)



    # Save updated regions to file
    if len(sat_regions_out)>0:
        sat_regions_out.write(sat_path.replace('.reg','_revised.reg'))
    else:
github aplpy / aplpy / aplpy / regions.py View on Github external
"""
    Wrapper to return a PatchCollection given a ds9 region file
    and a fits header.

    zorder - defaults to 3 so that regions are on top of contours
    """

    try:
        import pyregion
    except Exception:
        raise ImportError("The pyregion package is required to load region files")

    # read region file
    if isinstance(region_file, str):
        rr = pyregion.open(region_file)
    elif isinstance(region_file, pyregion.ShapeList):
        rr = region_file
    else:
        raise Exception("Invalid type for region_file: %s - should be string or pyregion.ShapeList" % type(region_file))

    if isinstance(header, wcs.WCS):
        header = header.to_header()

    # convert coordinates to image coordinates
    rrim = rr.as_imagecoord(header)

    # pyregion and aplpy both correct for the FITS standard origin=1,1
    # need to avoid double-correcting. Also, only some items in `coord_list`
    # are pixel coordinates, so which ones should be corrected depends on the
    # shape.
    for r in rrim:
        if r.name == 'polygon':