How to use the pyregion.open 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_AstroMagic / PTS / pts / magic / basics / skyregion.py View on Github external
"""
        This function ...
        :param path:
        :param only:
        :param ignore:
        :param color:
        :param ignore_color:
        :return:
        """

        # Create a new sky region
        region = cls()

        # Open the region file with pyregion and check if its in sky coordinates
        _region = pyregion.open(path)
        def check_sky_coord(_region):
            if [s for s in _region if s.coord_format != "fk5"]: return False
            else: return True
        if not check_sky_coord(_region): raise ValueError("Region is not in sky coordinates")

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

            # Meta information
            meta = {}
            if "text" in shape.attr[1]: meta["text"] = shape.attr[1]["text"]
            if "color" in shape.attr[1]: meta["color"] = shape.attr[1]["color"]
            if "point" in shape.attr[1]: meta["point"] = shape.attr[1]["point"]

            # Check the color of the shape
            if color is not None and shape.attr[1]["color"] != color: continue
github yt-project / yt / yt / frontends / fits / misc.py View on Github external
The data container that will be used to create the new region.
        Defaults to ds.all_data.
    field_parameters : dictionary, optional
        A set of field parameters to apply to the region.

    Examples
    --------

    >>> ds = yt.load("m33_hi.fits")
    >>> circle_region = ds9_region(ds, "circle.reg")
    >>> print circle_region.quantities.extrema("flux")
    """
    import pyregion
    from yt.frontends.fits.api import EventsFITSDataset
    if os.path.exists(reg):
        r = pyregion.open(reg)
    else:
        r = pyregion.parse(reg)
    reg_name = reg
    filter = r.get_filter(header=ds.wcs_2d.to_header())
    nx = ds.domain_dimensions[ds.lon_axis]
    ny = ds.domain_dimensions[ds.lat_axis]
    mask = filter.mask((ny, nx)).transpose()
    if isinstance(ds, EventsFITSDataset):
        prefix = "event_"
    else:
        prefix = ""
    def _reg_field(field, data):
        i = data[prefix+"xyz"[ds.lon_axis]].d.astype("int")-1
        j = data[prefix+"xyz"[ds.lat_axis]].d.astype("int")-1
        new_mask = mask[i,j]
        ret = np.zeros(data[prefix+"x"].shape)
github Stargrazer82301 / CAAPR / CAAPR / CAAPR_AstroMagic / CAAPR_AstroMagic.py View on Github external
# Check if galaxy catalogue file has any row sin before continuing
    if sum(1 for line in open(os.path.join(temp_dir_path, 'AstroMagic', band_dict['band_name'],'Galaxies.cat'))) <= 1:
        shutil.copy2(sat_path, sat_path.replace('.reg','_revised.reg'))
        shutil.copy2(star_path, star_path.replace('.reg','_revised.reg'))
        return star_segments

    # Open galaxy catalogue file, and determine the "primary" name of the one that has been deemed principal
    gal_cat = astropy.table.Table.read(os.path.join(temp_dir_path, 'AstroMagic', band_dict['band_name'], 'Galaxies.cat'), format='ascii')
    where_principal = np.where( np.array([ gal_cat['Name'][i].replace(' ','')==source_dict['name'] for i in range(0,len(gal_cat)) ])==True )
    if where_principal[0].shape[0]==0:
        gal_principal = 'NULL'
    else:
        gal_principal = gal_cat['Name'][where_principal][0].replace(' ','')

    # Loop over galaxy region file, identify region corresponding to target galaxy, and create mask array of it
    gal_regions = pyregion.open(gal_path)
    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([])
github astropy / pyregion / docs / pyregion / examples / demo_region03.py View on Github external
nrows_ncols = (ny, nx)
    grid= ImageGrid(fig, 111, nrows_ncols,
                    ngrids=n,  add_all=True, share_all=True,
                    axes_class=(pywcsgrid2.Axes, dict(header=h)))

    ax = grid[0]
    ax.set_xlim(300, 1300)
    ax.set_ylim(300, 1300)
    ax.set_aspect(1)

    #plt.imshow(d, origin="lower", cmap=plt.cm.gray_r)

    from mpl_toolkits.axes_grid.anchored_artists import AnchoredText

    for ax, reg_name in zip(grid, region_list):
        r = pyregion.open(reg_name).as_imagecoord(h)

        patch_list, text_list = r.get_mpl_patches_texts()
        for p in patch_list:
            ax.add_patch(p)
        for t in text_list:
            ax.add_artist(t)


        atext = AnchoredText(reg_name.replace("_", r"\_"),
                             loc=2)
        ax.add_artist(atext)

    plt.draw()
    plt.show()
github astropy / pyregion / examples / demo_region03.py View on Github external
# Create axes
ax1 = WCSAxes(fig, [0.1, 0.1, 0.4, 0.8], wcs=wcs)
fig.add_axes(ax1)
ax2 = WCSAxes(fig, [0.5, 0.1, 0.4, 0.8], wcs=wcs)
fig.add_axes(ax2)

# Hide labels on y axis
ax2.coords[1].set_ticklabel_position('')

for ax, reg_name in zip([ax1, ax2], region_list):

    ax.set_xlim(300, 1300)
    ax.set_ylim(300, 1300)
    ax.set_aspect(1)

    r = pyregion.open(reg_name).as_imagecoord(header)

    patch_list, text_list = r.get_mpl_patches_texts()

    for p in patch_list:
        ax.add_patch(p)

    for t in text_list:
        ax.add_artist(t)

    atext = AnchoredText(reg_name, loc=2)

    ax.add_artist(atext)

plt.draw()
plt.show()
github astropy / pyregion / docs / figures / region_drawing.py View on Github external
try:
    from astropy.wcs import WCS
    from astropy.visualization.wcsaxes import WCSAxes

    wcs = WCS(f_xray[0].header)
    fig = plt.figure()
    ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
    fig.add_axes(ax)
except ImportError:
    ax = plt.subplot(111)

ax.imshow(f_xray[0].data,
          cmap=cm.gray, vmin=0., vmax=0.00038, origin="lower")

reg_name = "test.reg"
r = pyregion.open(reg_name).as_imagecoord(f_xray[0].header)

patch_list, text_list = r.get_mpl_patches_texts()
for p in patch_list:
    ax.add_patch(p)
for t in text_list:
    ax.add_artist(t)

plt.show()
github aplpy / aplpy / aplpy / regions.py View on Github external
def ds9(region_file, header, zorder=3, **kwargs):
    """
    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:
github astropy / pyregion / examples / demo_helper.py View on Github external
def show_region(fig, region_list):
    h = demo_header()

    n = len(region_list)
    nx = int(math.ceil(n ** .5))
    ny = int(math.ceil(1. * n / nx))

    nrows_ncols = (ny, nx)

    grid = [plt.subplot(ny, nx, i + 1) for i in range(n)]

    for ax, reg_name in zip(grid, region_list):
        ax.set_aspect(1)

        r = pyregion.open(reg_name).as_imagecoord(h)

        patch_list, text_list = r.get_mpl_patches_texts()
        for p in patch_list:
            ax.add_patch(p)
        for t in text_list:
            ax.add_artist(t)

        if plt.rcParams["text.usetex"]:
            reg_name = reg_name.replace("_", r"\_")
        ax.set_title(reg_name, size=10)
        for t in ax.get_xticklabels() + ax.get_yticklabels():
            t.set_visible(False)

    return grid
github leejjoon / matplotlib_astronomy_gallery / w51c / w51c_rosat.py View on Github external
def annotate_w51c(ax, header):
    # draw + to mark center
    reg = pyregion.open("remnant_center.reg")
    cx, cy = reg[0].coord_list[:2]
    ax["fk5"].plot([290.896], [14.1669], "w+", ms=9, mew=2, zorder=3)

    # draw b=0 line
    axis = ax["gal"].new_floating_axis(1, 0.)
    axis.toggle(all=False, label=True)
    axis.label.set_text(r"$b=0^{\circ}$")
    ax.axis["b=0"] = axis



    # draw XMM Mos region
    reg = pyregion.open("mos_fov.reg").as_imagecoord(header)
    patches, txts = reg.get_mpl_patches_texts()
    circ = patches[0]
    ax.add_patch(circ)