def check_flagged_region(mosaicname, ra, dec, maj, min, pa, plot=False): mosaicfile = get_mosaic_name(mosaicname) maj = np.max((maj, 0.001)) lhdu = extract_subim(mosaicfile, ra, dec, 2 * maj, verbose=False) if lhdu is None: print mosaicname, ra, dec, maj return True region = pyregion.parse('fk5;ellipse({ra},{dec},{a},{b},{pa})'.format( ra=ra, dec=dec, a=maj, b=min, pa=pa - 90)) data = lhdu[0].data region_mask = region.get_mask(lhdu[0]) flagged = np.any(np.isnan(data[region_mask])) if plot: plt.figure() plt.subplot(131) plt.imshow(data) plt.subplot(132) plt.imshow(region_mask) plt.subplot(133) plt.imshow(data * region_mask) return flagged
def ellipses_from_coordinates(coordinates): """ This function creates a region consisting of ellipses, based on a list of coordinates :param coordinates: the list of coordinates for the different ellipses :return: the region of ellipses """ # Initialize the region string region_string = "# Region file format: DS9 version 3.0\n" region_string += "global color=green\n" region_string += "image\n" # 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 positions_of_stars_from_ds9(image_name, message, catalogue_name): # Display image d = ds9.ds9() d.set("file " + image_name) # Tell the user to select the regions answer = False while answer == False: window = myWindow(message) window.box() try: region = pyregion.parse(d.get("region")) answer = True except ValueError: # No regions defined print "\n There is no region loaded in the image! \n" coords_RADEC = [cc.coord_list[0:2] for cc in region] #hdr = fits.getheader(image_name) #w = wcs.WCS(hdr) #coords_RADEC = w.all_pix2world(xyout,1) with open(catalogue_name, 'w') as fd: for reg in coords_RADEC: fd.write(" {0} {1} \n".format(*reg)) return region
def filterImage(maskFileName, imageFileName, filterType): imgList = [] imgData, _ = readFitsImage(imageFileName) xlim, ylim = imgData.shape if filterType == "REG": reg = open(maskFileName, 'r').read() hdulist = pyfits.open(imageFileName) maskData = pyregion.parse(reg).get_mask(hdu=hdulist[0]) #maskData = writeMaskFile(maskData, 'mask.fits') if filterType == "FITS": maskData, _ = readFitsImage(maskFileName) assert (maskData.shape == imgData.shape ), "Mask shape does not match image shape!" if filterType == "NONE": maskData = np.ones((xlim, ylim)) for i in range(xlim): for j in range(ylim): if maskData[i][j] != 0: if (i + j) % 2 == 1: type = 'v' else: type = 'o' #type = 'v' imgList.append((j, i, imgData[i][j], type)) return imgList
def __init__(self, X, Y, t, header, regionDefinition): self.X = X self.Y = Y self.t = t self.regions = [pyregion.parse(regionDefinition).as_imagecoord(header)]
def _parseLines(self, lines, headerWCS): regDefinitions = filter(lambda x: x != 'fk5\n', lines) if len(regDefinitions) > 0: # Extract all circle(ra,dec,radius) expressions # (catch the warnings generated by pyregion, which are # harmless) with warnings.catch_warnings(): warnings.filterwarnings(action="ignore", category=AstropyDeprecationWarning) warnings.filterwarnings(action="ignore", category=FITSFixedWarning) regions = pyregion.parse( " ".join(lines)).as_imagecoord(headerWCS) self.filter = regions self.n = len(regions) else: # There are no regions! self.filter = None self.n = 0
def maskFits(regFile, imageFile): f1 = open(regFile,'r') reg = f1.read() hdulist = pyfits.open(imageFile) h = pyfits.getheader(imageFile) hdr = h.copy() matrix =hdulist[0].data r = pyregion.parse(reg) Xrange = matrix.shape[0] Yrange = matrix.shape[1] mask = r.get_mask(hdu=hdulist[0]) new_matrix = np.zeros((Xrange,Yrange)) mask_matrix = np.ones((Xrange,Yrange)) for i in range(Xrange): for j in range(Yrange): if(mask[i,j]!=True): mask_matrix[i,j] = 0 new_matrix[i,j]=matrix[i,j] # write out the new fits file. imageName = imageFile.split('.') outName = imageName[0] + "_masked." +imageName[1] hdu=fits.PrimaryHDU(new_matrix) hdu.writeto(outName,clobber='true') hdu_mask=fits.PrimaryHDU(mask_matrix) hdu_mask.writeto("mask.fits",clobber='true') f1.close() hdulist.close()
def test_estimate_cdelt(): l, b = 0, 0 # This is the ra,dec of l,b=0,0 ra, dec = 266.404497776, -28.9364329295 # This is 'almost' the ra,dec of l,b=0,0 - works # ra,dec=266.40,-28.93 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 test_estimate_cdelt(): l,b=0,0 # This is the ra,dec of l,b=0,0 ra,dec=266.404497776,-28.9364329295 # This is 'almost' the ra,dec of l,b=0,0 - works # ra,dec=266.40,-28.93 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 load_regions(region_file): with open(region_file) as f: region_string = f.read() # Workaround for bug in pyregion.parse when color is of form '#fff' region_string = region_string.replace('color=#', 'color=') regions = pyregion.parse(region_string) return regions
def pix_val_in_reg(reg_ds9, coord, fits_data, fits_head): """ get the pixel values in the region reg_ds9 :param reg_ds9: ds9 region in the format of e.g., 'ellipse(a, b, ...', no header :param coord: the coordinate system of the region, e.g. 'galactic', 'icrs', etc :param fits_img: the fits image :return: an numpy array containing the values of pixels within the region """ n_pix_y, n_pix_x = fits_data.shape # create a filter using the region r = pyregion.parse(coord+';' + reg_ds9).as_imagecoord(fits_head) reg_filter = r.get_filter() # read the numbers in the region splits = reg_ds9.split(',') # degree; the Galactic longitude of the center if the region is ellipse, circle or box; # one point if the region is polygon head = splits[0].split('(') region_type = head[0] if region_type == 'polygon': coords = [] coords.append(head[1]) n = len(splits) for i in range(1, n-1): coords.append(splits[i]) tail = splits[-1].split(')')[0] coords.append(tail) coords = [float(i) for i in coords] glons = coords[0::2] glats = coords[1::2] glon = np.mean(glons) glat = np.mean(glats) glon_delta = (max(glons) - min(glons)) / 2. glat_delta = (max(glats) - min(glats)) / 2. l_box = max(glon_delta, glat_delta) * 1.2 # create a box to search pix in the region w = wcs.WCS(fits_head) bottom_left = w.wcs_world2pix(glon + l_box, glat - l_box, 1) up_right = w.wcs_world2pix(glon - l_box, glat + l_box, 1) # get the mean; avoid the pix number out of bounds i_min = int(max(bottom_left[0], 0)) i_max = int(min(up_right[0], n_pix_x)) j_min = int(max(bottom_left[1], 0)) j_max = int(min(up_right[1], n_pix_y)) pix_val = [] for i in range(i_min, i_max): for j in range(j_min, j_max): if reg_filter.inside1(i, j): pix_val.append(fits_data[j, i]) return np.asarray(pix_val)
def filterImage(maskFileName, imageFileName, filterType): imgList = [] imgData, _ = readFitsImage(imageFileName) xlim, ylim = imgData.shape if filterType=="REG": reg = open(maskFileName, 'r').read() hdulist = pyfits.open(imageFileName) maskData = pyregion.parse(reg).get_mask(hdu=hdulist[0]) maskData = writeMaskFile(maskData, 'mask.fits') if filterType=="FITS": maskData, _= readFitsImage(maskFileName) assert (maskData.shape==imgData.shape), "Mask shape does not match image shape!" if filterType=="NONE": maskData = np.ones((xlim, ylim)) for i in range(xlim): for j in range(ylim): if maskData[i][j]!=0: if (i+j)%2 ==1: type = 'v' else: type = 'o' #type = 'v' imgList.append((j,i, imgData[i][j], type)) return imgList
def ds9_region(ds, reg, obj=None, field_parameters=None): r""" Create a data container from a ds9 region file. Requires the pyregion package (https://pyregion.readthedocs.io/en/latest/) to be installed. Parameters ---------- ds : FITSDataset The Dataset to create the region from. reg : string The filename of the ds9 region, or a region string to be parsed. obj : data container, optional 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 header = ds.wcs_2d.to_header() # The FITS header only contains WCS-related keywords header["NAXIS1"] = nx = ds.domain_dimensions[ds.lon_axis] header["NAXIS2"] = ny = ds.domain_dimensions[ds.lat_axis] filter = r.get_filter(header=header) 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) ret[new_mask] = 1.0 return ret ds.add_field(("gas", reg_name), sampling_type="cell", function=_reg_field) if obj is None: obj = ds.all_data() if field_parameters is not None: for k, v in field_parameters.items(): obj.set_field_parameter(k, v) return obj.cut_region(["obj['%s'] > 0" % (reg_name)])
def subcubes_from_ds9(cube, region_file='../nro_maps/SouthShells.reg', pad_factor=1., shape='exact'): """ Extracts subcubes using the ds9 region file. Parameters ---------- cube : SpectralCube, str The cube to be chopped. Must be type spectral_cube.SpectralCube or str filename. region_file : str Path to a ds9 region file. pad_factor : float, optional Expand the subcube around the region by this factor. shape : {'square', 'exact'} The shape of the subcube returned. 'square' returns the smallest square subcube that contains the region. 'exact' returns only the pixels contained within the region. Returns ------- subcubes: list of SpectralCube of SpectralCube """ from spectral_cube import SpectralCube import pyregion try: #If cube is a str filename, read a SpectralCube. cube = SpectralCube.read(cube) except ValueError: pass if shape == 'square': import astropy.units as u subcube_list = [] region_list = pyregion.open(region_file) for region in region_list: half_width = region.coord_list[2] * pad_factor * u.deg ra_center = region.coord_list[0] * u.deg dec_center = region.coord_list[1] * u.deg ra_range = [ra_center - half_width, ra_center + half_width] dec_range = [dec_center - half_width, dec_center + half_width] #print(ra_range, dec_range) subcube_list.append(cube.subcube(ra_range[1], ra_range[0], dec_range[0], dec_range[1])) if shape == 'exact': region_list = pyregion.open(region_file) subcube_list = [] for region in region_list: if pad_factor != 1.: new_string = '{};{}({},{},{}")'.format(region.coord_format, region.name, region.coord_list[0], region.coord_list[1], region.coord_list[2]*3600.*pad_factor) region = pyregion.parse(new_string)[0] subcube_list.append(cube.subcube_from_ds9region(pyregion.ShapeList([region]))) if len(subcube_list) == 1: return subcube_list[0] else: return subcube_list
def cross_match_CSAR(getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo/+catalogs/L1157.sw.final.reliable.ok.cat', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1157/CSAR/CEPl1157_CSAR.dat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_255_mu.image.resamp.fits', CSAR_core_indices='L1157_matched_CSAR_cores.dat'): # Import getsources "good core" data table cores_array1 = numpy.loadtxt(getsources_core_catalog,comments='!') good_core_indices = good_cores_getsources.get_good_cores(getsources_core_catalog) cores_array = cores_array1[numpy.array(good_core_indices)] ### Import the CSAR catalog ### ***MAKE SURE FIRST TWO COLUMNS OF "CSAR_catalog" FILE ARE X_POSITION AND Y_POSITION OF SOURCE IN DECIMAL DEGREES*** CSAR_array = numpy.loadtxt(CSAR_catalog,comments='#') #print CSAR_array CSAR_positions = numpy.column_stack((CSAR_array[:,0], CSAR_array[:,1])) #print CSAR_positions w = wcs.WCS(high_res_coldens_image) pos_pix = w.wcs_world2pix(CSAR_positions, 1) ### Loop through the potential matched cores identified in the step above. counter = 0 matched_cores = [] for line in cores_array: x_coor = str(line[3]) y_coor = str(line[4]) ### Create a DS9 region string for the core's getsources ellipse, ### from which a mask will be created. region = ('fk5;ellipse(' + x_coor + ', ' + y_coor + ', ' + str((line[50]/2.0)/3600.) + ', ' + str((line[51]/2.0)/3600.) + ', ' + str(line[52]+90.0)+')') r = pyregion.parse(region) f=fits.open(high_res_coldens_image) mymask = r.get_mask(hdu=f[0]) f.close() newmask=mymask ### Set all values outside the core's ellipse to zero, ### all values inside the ellipse are set to one. newmask=numpy.where(newmask==0,0,1) mask_shape = numpy.shape(newmask) ### Loop through the CSAR catalog ### If any CSAR cores fall within a getsources core's ellipse, ### store the getsources core's index match_counter=0 for i in pos_pix: ypos = int(round(i[1],0))-1 xpos = int(round(i[0],0))-1 if ypos<=mask_shape[0] and xpos<=mask_shape[1]: if newmask[ypos][xpos]==1 and match_counter==0: matched_cores.append(counter) # match_counter prevents counting indices twice # if two CSAR cores fall within getsources ellipse match_counter+=1 #print len(matched_cores) counter += 1 print 'CSAR_matched:total ratio =' + str(round(float(len(matched_cores)) / float(len(cores_array[:,0])),3)) ### Save the CSAR matched core indices to a file #numpy.savetxt(CSAR_core_indices, matched_cores, fmt='%i') return numpy.array(matched_cores)
def parse(region_string): """ This function is a simple wrapper around the pyregion.parse function, to contain :param region_string: :return: """ # Parse the region string and create a region return pyregion.parse(region_string)
def draw_ellipse(ax, center, region_string): header = ax.projection._pywcs.to_header() cel_ax['fk5'].plot([center.ra()],[center.dec()],'r+', zorder=10, markersize=20) reg = pyregion.parse(region_string).as_imagecoord(header) patch_list, artist_list = reg.get_mpl_patches_texts() for p in patch_list: p.set_zorder(10) ax.add_patch(p)
def get_max_intensity(source, pyfits, roi, colorbar_radius=None): """ Return the maximum value in the pyfits file either within the extended source's size or otherwise within the 68% containment radius of the PSF (at the lowest energy). """ try: import pyregion except: return pyfits[0].data.max() if source is None and colorbar_radius is None: return pyfits[0].data.max() if colorbar_radius is not None: ra, dec = roi.roi_dir.ra(), roi.roi_dir.dec() reg = pyregion.parse("fk5; circle(%.4f, %.4f, %.4f)" % (ra, dec, colorbar_radius)) extensionmask = reg.get_mask(pyfits[0]) elif hasattr(source, 'spatial_model'): # For extended sources, # Get the maximum intensity value inside # the spatial model's extension extension_string = '\n'.join( region_writer.unparse_extension(source.spatial_model, r68=True)) reg = pyregion.parse(extension_string) extensionmask = reg.get_mask(pyfits[0]) else: extensionmask = False # no mask # Get the maximum intensity inside the PSF (in lowest bin) emin = roi.bin_edges[0] ra, dec = source.skydir.ra(), source.skydir.dec() r68 = roi.sa.psf.inverse_integral(emin, 1, 68) # 1=front entering events reg = pyregion.parse("fk5; circle(%.4f, %.4f, %.4f)" % (ra, dec, r68)) psfmask = reg.get_mask(pyfits[0]) # use whatever region mask is bigger return pyfits[0].data[psfmask | extensionmask].max()
def ds9_region(ds, reg, obj=None, field_parameters=None): r""" Create a data container from a ds9 region file. Requires the pyregion package (http://leejjoon.github.io/pyregion/) to be installed. Parameters ---------- ds : FITSDataset The Dataset to create the region from. reg : string The filename of the ds9 region, or a region string to be parsed. obj : data container, optional 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 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() def _reg_field(field, data): i = data["xyz"[ds.lon_axis]].ndarray_view().astype("int") - 1 j = data["xyz"[ds.lat_axis]].ndarray_view().astype("int") - 1 new_mask = mask[i, j] ret = data["zeros"].copy() ret[new_mask] = 1. return ret ds.add_field(("gas", reg_name), function=_reg_field) if obj is None: obj = ds.all_data() if field_parameters is not None: for k, v in field_parameters.items(): obj.set_field_parameter(k, v) return obj.cut_region(["obj['%s'] > 0" % (reg_name)])
def get_rms_map(infilename,ds9region,outfilename): polylist = convert_regionfile_to_poly(ds9region) hdu=fits.open(infilename) hduflat = flatten(hdu) map=hdu[0].data for direction,ds9region in enumerate(polylist): r = pyregion.parse(ds9region) manualmask = r.get_mask(hdu=hduflat) rmsval = get_rms_array(hdu[0].data[0][0][np.where(manualmask == True)]) hdu[0].data[0][0][np.where(manualmask == True)] = rmsval print 'RMS = %s for direction %i'%(rmsval,direction) hdu.writeto(outfilename,clobber=True)
def reg2sl(self): """Convert a region file to a starlist.""" import pyregion import astropy.coordinates as coord import astropy.units as u print( "Converting '{input:s}' ds9 region file to '{output:s}' starlist.". format(**vars(self.opts))) with open(self.opts.input, 'r') as regionfile: regions = pyregion.parse(regionfile.read()) with open(self.opts.output, 'w') as starlist: for i, region in enumerate(regions): if region.coord_format != 'fk5': self.log.critical("Coordinate system {!r} unkown!".format( region.coord_format)) break # We only parse circles! if region.name == 'circle': # Parse the location ra, dec = region.coord_list[0:2] loc = coord.FK5(ra=ra, dec=dec, unit=(u.degree, u.degree)) if "text" in region.attr[1]: name = region.attr[1]["text"] else: name = "Target%d" % i # Handle comments comments = region.comment.split() for comment in comments: if comment.startswith("text={"): comments.remove(comment) # Write out the starlist line starlist.write( "{name:<15s} {ra:s} {dec:s} {epoch:.0f} {keywords:s}". format( name=name.strip(), ra=loc.ra.format(u.hour, sep=" ", pad=True), dec=loc.dec.format(sep=" ", alwayssign=True), epoch=loc.equinox.jyear, keywords=" ".join(comments), )) starlist.write("\n") else: self.log.warning( "Region {!r} not parsed. It is not a circle.".format( region))
def get_rms_map(infilename,ds9region,outfilename): polylist = convert_regionfile_to_poly(ds9region) hdu=fits.open(infilename) hduflat = flatten(hdu) map=hdu[0].data for direction,ds9region in enumerate(polylist): print direction,ds9region r = pyregion.parse(ds9region) manualmask = r.get_mask(hdu=hduflat) rmsval = get_rms_array(hdu[0].data[0][0][np.where(manualmask == True)]) hdu[0].data[0][0][np.where(manualmask == True)] = rmsval print 'RMS = %s for direction %i'%(rmsval,direction) hdu.writeto(outfilename,clobber=True)
def ds9_region(ds, reg, obj=None, field_parameters=None): r""" Create a data container from a ds9 region file. Requires the pyregion package (http://leejjoon.github.io/pyregion/) to be installed. Parameters ---------- ds : FITSDataset The Dataset to create the region from. reg : string The filename of the ds9 region, or a region string to be parsed. obj : data container, optional 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 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() def _reg_field(field, data): i = data["xyz"[ds.lon_axis]].ndarray_view().astype("int")-1 j = data["xyz"[ds.lat_axis]].ndarray_view().astype("int")-1 new_mask = mask[i,j] ret = data["zeros"].copy() ret[new_mask] = 1. return ret ds.add_field(("gas",reg_name), function=_reg_field) if obj is None: obj = ds.all_data() if field_parameters is not None: for k,v in field_parameters.items(): obj.set_field_parameter(k,v) return obj.cut_region(["obj['%s'] > 0" % (reg_name)])
def mask_from_ds9(image_name, message): # Display image d = ds9.ds9() d.set("file " + image_name) # Tell the user to select the regions answer = False while answer == False: window = myWindow(message) window.box() try: region = pyregion.parse(d.get("region")) answer = True except ValueError: # No regions defined print "\n There is no region loaded in the image! \n" return region
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
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 one_ellipse(parameters): """ This function ... :param parameters: :return: """ # Create a string identifying this ellipse region_string = "# Region file format: DS9 version 3.0\n" region_string += "global color=green\n" region_string += "image\n" region_string += "ellipse(" + str(parameters[0]) + "," + str(parameters[1]) + "," + str(parameters[2]) + "," + str(parameters[3]) + "," + str(parameters[4]) + ")\n" # Create a region and return it return pyregion.parse(region_string)
def ds9_photometry(xpapoint): D = ds9.ds9(xpapoint) try: reg = pyregion.parse(D.get("regions selected -format ds9 -system wcs -sky fk5 -skyformat sexagesimal")) except Exception as ex: print ex raise ex pf = D.get_pyfits() ph = pyfits.PrimaryHDU(data=pf[0].data,header=pf[0].header) mask = reg.get_mask(ph) arr = pf[0].data wherenotnan = (arr == arr) mask = mask*wherenotnan hdr = pf[0].header try: wcs = pywcs.WCS(hdr.tostring()) except AttributeError: wcs = pywcs.WCS(hdr) try: try: bmaj = float(hdr['BMAJ']) bmin = float(hdr['BMIN']) except KeyError: # VLA imfits bmin = None; bmaj = None for k,v in hdr.iteritems(): if numpy.iterable(v) and "BMAJ" in v: bmaj = float(v.split()[3]) bmin = float(v.split()[5]) if bmin is None or bmaj is None: raise KeyError("BMIN and BMAJ not found") try: cd1 = wcs.wcs.cd[0,0] cd2 = wcs.wcs.cd[1,1] except AttributeError: cd1,cd2 = wcs.wcs.cdelt[:2] ppbeam = 2*numpy.pi*bmin*bmaj / abs(cd1*cd2) / (8*numpy.log(2)) #print "CD1: %g CD2: %g" % (cd1, cd2) sys.stdout.write( "BMAJ: %g BMIN: %g PPBEAM: %g SUM/PPBEAM: %g\n" % (bmaj,bmin,ppbeam,arr[mask].sum()/ppbeam) ) except KeyError: print "ds9_phot failed - check for BMAJ/BMIN in header" pass except Exception as inst: print "ds9_phot failed - not a header KeyError, something else" print inst.args pass return arr[mask].sum(),arr[mask].mean(),numpy.median(arr[mask]),arr[mask].std(),mask.sum()
def mask_bright_stars(imagefile,star_region_strings,outputname): f = pf.open(imagefile) head = f[0].header data = f[0].data r = pyregion.parse(star_region_strings) r2= r.as_imagecoord(head) #create the mask mymask = r2.get_mask(hdu=f[0]) #Reverse the True and False mymask = np.logical_not(mymask) maskint = mymask*1 #Multiply the mask and the data to cut the stars (where False == 1 i.e., no mask) newimage = data * maskint #can write directly if you want #pf.writeto(outputname, newimage, head) #newimage is the data with the stars cut out whereas maskint is the integer mask with a 0 where the stars are masked and 1 everywhere else and head is the appropriate header return data, maskint, newimage
def extract_from_region(cls, specfile, region): # Each pixel is in Jy/beam # Sum to get Jy.pixel/beam # Divide by boxarea to get Jy/beam again # Multiply by N_beams = boxarea/area to get Jy # sum(box)/boxarea * (boxarea/area) = sum(box)/area hdu = fits.open(specfile) hdr = hdu[0].header cube = hdu[0].data[0, :, :, :] vel = get_velocity(hdr) beam = extract_beam_info(hdr) trimhdu = get_trimmed_HDU(specfile) objname = hdr['object'] with warnings.catch_warnings(): warnings.simplefilter("ignore") try: r = pyregion.open(region).as_imagecoord(trimhdu.header) except IOError: r = pyregion.parse(region).as_imagecoord(trimhdu.header) mask = r.get_mask(hdu=hdu[0], shape=cube.shape[-2:]) #hdu=trimhdu) flux = np.zeros(vel.shape) for i in range(len(vel)): im = cube[i, :, :] flux[i] = np.sum(im[mask]) / beam['area'] pix_asec = abs(hdr['CDELT1']) * 3600 regarea = np.sum(mask) * pix_asec**2 dv = vel[1] - vel[0] vobs = hdr['RESTFRQ'] spec = dict(velocity=vel, flux=flux) kwds = dict(delta_v=dv, area=regarea, pix_asec=pix_asec, restfrq=vobs / 1e9, bmaj=beam['major'], bmin=beam['minor'], bpa=beam['pa'], barea=beam['area'], objname=objname) return cls(spec, **kwds)
def get_rms_map2(infilename,ds9region,outfilename): runcommand = "MakeMask.py --RestoredIm=%s --OutName=%s.rmsmapmask --Th=%s --Box=50,2 --OutNameNoiseMap='%s.rms'"%(infilename,infilename,3.0,infilename) run(runcommand,log=None) infilename = '%s.rms.fits.fits'%infilename polylist = convert_regionfile_to_poly(ds9region) hdu=fits.open(infilename) hduflat = flatten(hdu) map=hdu[0].data for direction,ds9region in enumerate(polylist): r = pyregion.parse(ds9region) manualmask = r.get_mask(hdu=hduflat) rmsval = np.mean(hdu[0].data[0][0][np.where(manualmask == True)]) hdu[0].data[0][0][np.where(manualmask == True)] = rmsval print 'RMS = %s for direction %i'%(rmsval,direction) hdu.writeto(outfilename,clobber=True)
def prior_mask(priorfile, imhdr, struct): "Create a binary mask with the prior limits." opthdr = fits.getheader(priorfile, 1) if opthdr.get('RA_MIN'): ramin, ramax, decmin, decmax = [ opthdr.get(k) for k in ['RA_MIN', 'RA_MAX', 'DEC_MIN', 'DEC_MAX'] ] opt_limits = [ ramin, decmin, ramin, decmax, ramax, decmax, ramax, decmin, ramin, decmin ] opt_limits = ','.join([str(o) for o in opt_limits]) region = pyregion.parse('fk5;polygon({0})'.format(opt_limits)) mask = regions_mask(region, imhdr, struct, dilate=False) else: mask = None return mask
def reg2sl(self): """Convert a region file to a starlist.""" import pyregion import astropy.coordinates as coord import astropy.units as u print("Converting '{input:s}' ds9 region file to '{output:s}' starlist.".format(**vars(self.opts))) with open(self.opts.input,'r') as regionfile: regions = pyregion.parse(regionfile.read()) with open(self.opts.output,'w') as starlist: for i,region in enumerate(regions): if region.coord_format != 'fk5': self.log.critical("Coordinate system {!r} unkown!".format(region.coord_format)) break # We only parse circles! if region.name == 'circle': # Parse the location ra,dec = region.coord_list[0:2] loc = coord.FK5(ra=ra,dec=dec,unit=(u.degree,u.degree)) if "text" in region.attr[1]: name = region.attr[1]["text"] else: name = "Target%d" % i # Handle comments comments = region.comment.split() for comment in comments: if comment.startswith("text={"): comments.remove(comment) # Write out the starlist line starlist.write("{name:<15s} {ra:s} {dec:s} {epoch:.0f} {keywords:s}".format( name = name.strip(), ra = loc.ra.format(u.hour, sep=" ", pad=True), dec = loc.dec.format(sep=" ", alwayssign=True), epoch = loc.equinox.jyear, keywords = " ".join(comments), )) starlist.write("\n") else: self.log.warning("Region {!r} not parsed. It is not a circle.".format(region))
def get_rms_map2(infilename,ds9region,outfilename): runcommand = "MakeMask.py --RestoredIm=%s --OutName=rmsmapmask --Th=%s --Box=50,2 --OutNameNoiseMap=%s.noise"%(infilename,3.0,infilename) run(runcommand,log=None) infilename = '%s.noise.fits'%infilename polylist = convert_regionfile_to_poly(ds9region) hdu=fits.open(infilename) hduflat = flatten(hdu) map=hdu[0].data for direction,ds9region in enumerate(polylist): print direction,ds9region r = pyregion.parse(ds9region) manualmask = r.get_mask(hdu=hduflat) rmsval = np.mean(hdu[0].data[0][0][np.where(manualmask == True)]) hdu[0].data[0][0][np.where(manualmask == True)] = rmsval print 'RMS = %s for direction %i'%(rmsval,direction) hdu.writeto(outfilename,clobber=True)
def filter_events(self, region): """ Filter events using a ds9 *region*. Requires the `pyregion <http://pyregion.readthedocs.org/en/latest/>`_ package. Returns a new :class:`~pyxsim.event_list.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 _sum_flux(self, ds9_string, data, header): ''' Adds the flux from each pixel within the region in order to get the total flux for the region. :param ds9_string: The information for a region in a string format :param data: The data array of the visit file to be examined :param header: The header of the visit file to be examined :return sum_flux: The total flux for this region ''' reg_definition = 'icrs;%s' % ds9_string.replace(" ", "") reg = pyregion.parse(reg_definition).as_imagecoord(header) filt = reg.get_filter() mask = filt.mask(data) sum_flux = np.sum(data[mask]) return sum_flux
def __init__(self, x, y, r, ds9_string=None): ''' Constructs a CircularRegion object. :param x: The horizontal location of the center of the region :param y: The vertical location of the center of the region :param r: Radius of the region if it is a circle (in pixels) ''' self._x = x self._y = y self._radius_pixels = r self._mask = None self._ds9_string = ds9_string if self._ds9_string is not None: self._pyregion = pyregion.parse(self._ds9_string)
def make_predict_mask(infilename, ds9region, outfilename, npix_out=10000): """ Make mask that is `infilename` everywhere except in regions specified by `ds9region` which is zero. :param infilename: :param ds9region: :param outfilename: :return: """ logger.info('Making: {}'.format(outfilename)) npix_in = getimsize(infilename) s = "image;box({},{},{},{},0)".format(npix_in // 2, npix_in // 2, npix_out, npix_out) with open(ds9region, 'w') as f: f.write(s) with fits.open(infilename) as hdu: hduflat = flatten(hdu) r = pyregion.parse(s) manualmask = r.get_mask(hdu=hduflat) hdu[0].data[0][0][np.where(manualmask == True)] = 0.0 hdu.writeto(outfilename, overwrite=True) if not os.path.isfile(outfilename): raise IOError("Did not successfully create {}".format(outfilename))
def pix_val_in_reg_old(reg_ds9, coord, fits_data, fits_head): """ get the pixel values in the region reg_ds9 :param reg_ds9: ds9 region in the format of e.g., 'ellipse(a, b, ...', no header :param coord: the coordinate system of the region, e.g. 'galactic', 'icrs', etc :param fits_img: the fits image :return: an numpy array containing the values of pixels within the region """ n_pix_y, n_pix_x = fits_data.shape # create a filter using the region r = pyregion.parse(coord+';' + reg_ds9).as_imagecoord(fits_head) reg_filter = r.get_filter() # read the numbers in the region splits = reg_ds9.split(',') # degree; the Galactic longitude of the center if the region is ellipse, circle or box; # one point if the region is polygon glon = float(splits[0].split('(')[1]) glat = float(splits[1]) # degree l_box = 1.5 # degree, to make sure all pix in a region are included # create a box to search pix in the region w = wcs.WCS(fits_head) bottom_left = w.wcs_world2pix(glon + l_box, glat - l_box, 1) up_right = w.wcs_world2pix(glon - l_box, glat + l_box, 1) # get the mean; avoid the pix number out of bounds i_min = int(max(bottom_left[0], 0)) i_max = int(min(up_right[0], n_pix_x)) j_min = int(max(bottom_left[1], 0)) j_max = int(min(up_right[1], n_pix_y)) pix_val = [] for i in range(i_min, i_max): for j in range(j_min, j_max): if reg_filter.inside1(i, j): pix_val.append(fits_data[j, i]) return np.asarray(pix_val)
def beam_ellipse(ra, dec, image): """ Return pyregion ellpse regon coresponding to the image beam at ra, dec Parameters ---------- ra: float, ra in degrees dec: float, dec in degrees image: obj, lib_fits.Image Returns ------- beam_ellipse: obj, pyregion region """ b = image.get_beam() ra = Angle(str(ra) + 'd', unit=u.deg).to_string(sep=':', unit=u.hour) dec = Angle(dec, unit=u.deg).to_string(sep=':') fact = 1 / np.sqrt( 4 * np.log(2) ) # this factor is needed to make the pixels in the beam area match the beam_area from the lib_fits function. Not sure why... ell_str = f"fk5;ellipse({ra}, {dec}, {b[0]*3600*fact}\", {b[1]*3600*fact}\", {b[2]})" reg_obj = pyregion.parse(ell_str) return reg_obj
except IOError as e: print 'FATAL ERROR: ',e sys.exit() try: rm=radiomap(f,verbose=True) except RadioError as e: print 'FATAL ERROR: ',e sys.exit() #print 'Frequency is %g Hz' % rm.frq # now apply regions if b_region: bg_ir=pyregion.parse(b_region).as_imagecoord(rm.headers[0]) bg=applyregion(rm,bg_ir) print 'Pixels in background region',bg.pixels for i in range(rm.nchans): print '%8.4g Hz Background rms is %f Jy/beam' % (rm.frq[i],bg.rms[i]) print ' Background mean is',bg.mean[i],'Jy/beam' noise=bg.rms else: if bgsub: raise Error('Background subtraction requested but no bg region') noise=None fg_ir=pyregion.parse(f_region).as_imagecoord(rm.headers[0]) if bgsub: fg=applyregion(rm,fg_ir,offsource=noise,background=bg.mean) else:
def cross_match(getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo/+catalogs/L1157.sw.final.reliable.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo_proto/+catalogs/L1157.sw.final.reliable.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_255_mu.image.resamp.fits', proto_core_indices='L1157_matched_protostellar_cores.dat'): # Import getsources "good core" data table cores_array1 = numpy.loadtxt(getsources_core_catalog,comments='!') good_core_indices = good_cores_getsources.get_good_cores(getsources_core_catalog) cores_array = cores_array1[numpy.array(good_core_indices)] NO, XCO_P, YCO_P, WCS_ACOOR, WCS_DCOOR, SIG_GLOB, FG, GOOD, SIG_MONO01, FM01, FXP_BEST01, FXP_ERRO01, FXT_BEST01, FXT_ERRO01, AFWH01, BFWH01, THEP01, SIG_MONO02, FM02, FXP_BEST02, FXP_ERRO02, FXT_BEST02, FXT_ERRO02, AFWH02, BFWH02, THEP02, SIG_MONO03, FM03, FXP_BEST03, FXP_ERRO03, FXT_BEST03, FXT_ERRO03, AFWH03, BFWH03, THEP03, SIG_MONO04, FM04, FXP_BEST04, FXP_ERRO04, FXT_BEST04, FXT_ERRO04, AFWH04, BFWH04, THEP04, SIG_MONO05, FM05, FXP_BEST05, FXP_ERRO05, FXT_BEST05, FXT_ERRO05, AFWH05, BFWH05, THEP05, SIG_MONO06, FM06, FXP_BEST06, FXP_ERRO06, FXT_BEST06, FXT_ERRO06, AFWH06, BFWH06, THEP06, SIG_MONO07, FM07, FXP_BEST07, FXP_ERRO07, FXT_BEST07, FXT_ERRO07, AFWH07, BFWH07, THEP07 = numpy.loadtxt(YSO_catalog,comments='!', unpack=True) good_proto_indices = good_protostars_getsources.get_good_protostars(YSO_catalog) #print len(good_proto_indices) ### Loop through entire core catalog to find cores that are close to YSOs. ### This step significantly reduces the time it would take to run through ### entire catalog. potential_matches = [] count = 0 for line in cores_array: match_counter=0 for i in good_proto_indices: distance = ((line[3]-WCS_ACOOR[i])**2 + (line[4]-WCS_DCOOR[i])**2)**0.5 if distance < 200.0/3600. and match_counter==0: # matched_counter prevents counting indices twice # if two YSO candidates fall within getsources ellipse potential_matches.append(count) match_counter+=1 count += 1 #print len(potential_matches) ### Loop through the potential matched cores identified in the step above. matched_cores = [] matched_cores_proto_index = [] for value in potential_matches: line = cores_array[value] x_coor = str(line[3]) y_coor = str(line[4]) ### Create a DS9 region string for the core's getsources ellipse, ### from which a mask will be created. region = ('fk5;ellipse(' + x_coor + ', ' + y_coor + ', ' + str((line[50]/2.0)/3600.) + ', ' + str((line[51]/2.0)/3600.) + ', ' + str(line[52]+90.0)+')') r = pyregion.parse(region) f=fits.open(high_res_coldens_image) mymask = r.get_mask(hdu=f[0]) f.close() newmask=mymask ### Set all values outside the core's ellipse to zero, ### all valus inside the ellipse are set to one. newmask=numpy.where(newmask==0,0,1) ### Loop through the 70 micron point sources ### If any fall within a core's ellipse, store that core's index match_counter=0 good_protostar_index = 0 for i in good_proto_indices: if newmask[int(round(YCO_P[i],0))-1][int(round(XCO_P[i],0))-1]!=0 and match_counter==0: matched_cores.append(value) matched_cores_proto_index.append(good_protostar_index) # matched_counter prevents counting indices twice # if two YSO candidates fall within getsources ellipse match_counter+=1 good_protostar_index+=1 else: good_protostar_index+=1 #print len(matched_cores) #print matched_cores #print matched_cores_proto_index ### Save the protostellar core indices to a file #numpy.savetxt(proto_core_indices, matched_cores, fmt='%i') # Return indices of matched cores and protostars from the "good" lists of each # i.e., The indices are the index from the "good" lists and not the unprocessed original, total getsources list return numpy.column_stack((numpy.array(matched_cores), numpy.array(matched_cores_proto_index)))
import pyregion import webbrowser import numpy as np xpa = sys.argv[1] dd = ds9.ds9(xpa) if len(sys.argv) > 2: regionid = int(sys.argv[2]) else: # use the most recent region regionid = -1 rstringlist = dd.get('regions -system wcs -prop select 1') regions = pyregion.parse(rstringlist) if len(regions) == 0: sys.exit("No regions found") reg = regions[regionid] coord_fmt = 'Gal' if reg.coord_format == 'galactic' else 'fk5' coord = reg.coord_list[:2] url = "http://simbad.u-strasbg.fr/simbad/sim-coo?CooFrame={frame}&Coord={coord}".format(frame=coord_fmt, coord='{0} {1}'.format(*coord)) if reg.name == 'circle': radius = reg.coord_list[2] url += "&Radius={radius}&Radius.unit=deg".format(radius=radius)
format='ascii.ipac') #dendromask = fits.open('dendrograms_min1mJy_diff1mJy_mask_pruned.fits') for spw in (0,1,2,3): cube = SpectralCube.read(tmplt.format(spw)) print(cube) #mask_reproj = FITS_tools.hcongrid.hastrom(dendromask[0].data.astype('float'), # dendromask[0].header, # FITS_tools.strip_headers.flatten_header(cube.header)) #rmask = np.round(mask_reproj.data).astype('int') for row in pruned_ppcat: name = row['_idx'] print("Extracting {0} from {1}".format(name, spw)) SL = pyregion.parse("fk5; circle({0},{1},0.5\")" .format(row['x_cen'], row['y_cen'])) #mask = rmask == name #dend_inds = np.where(mask) #view = (slice(None), # all spectral channels # slice(dend_inds[0].min(), dend_inds[0].max()+1), # slice(dend_inds[1].min(), dend_inds[1].max()+1), # ) #sc = cube[view].with_mask(mask[view[1:]]) sc = cube.subcube_from_ds9region(SL) spec = sc.mean(axis=(1,2)) spec.meta['beam'] = radio_beam.Beam(major=np.nanmedian([bm.major.to(u.deg).value for bm in spec.beams]), minor=np.nanmedian([bm.minor.to(u.deg).value for bm in spec.beams]), pa=np.nanmedian([bm.pa.to(u.deg).value for bm in spec.beams]), )
ss = rp.parse(s) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) sss3 = rp.sky_to_image(sss2, header, rot_wrt_axis=rot_wrt_axis) return rp.filter_shape(sss3) def get_mask(region, hdu, origin=1): """ f = pyfits.read("test.fits") reg = read_region_as_imagecoord(s, f[0].header) mask = get_mask(reg, f[0]) """ from pyregion.region_to_filter import as_region_filter data = hdu.data region_filter = as_region_filter(region, origin=origin) mask = region_filter.mask(data) return mask if __name__ == '__main__': #reg = pyregion.open("../mos_fov.reg") import pyregion proposed_fov = 'fk5;circle(290.96388,14.019167,843.31194")' reg = pyregion.parse(proposed_fov) reg_imagecoord = reg.as_imagecoord(header) patches, txts = reg.get_mpl_patches_texts() m = reg.get_mask(hdu=f[0])
def _combine_exclude_mask(self, mask): # create masks from exclude/include regions and combine it with the # input DQ mask: # regmask = None if self.src_find_filters is not None and \ 'region_file' in self.src_find_filters: reg_file_name = self.src_find_filters['region_file'] if not os.path.isfile(reg_file_name): raise IOError("The 'exclude' region file '{:s}' does not exist." .format(reg_file_name)) else: return mask # get data image size: (img_ny, img_nx) = self.source.shape # find out if user provided a region file or a mask FITS file: reg_file_ext = os.path.splitext(reg_file_name)[-1] if reg_file_ext.lower().strip() in ['.fits', '.fit'] and \ basicFITScheck(reg_file_name): # likely we are dealing with a FITS file. # check that the file is a simple with 2 axes: hdulist = fits.open(reg_file_name) extlist = get_extver_list(hdulist,extname=None) for ext in extlist: usermask = hdulist[ext].data if usermask.shape == (img_ny, img_nx): regmask = usermask.astype(np.bool) break hdulist.close() if regmask is None: raise ValueError("None of the image-like extensions in the " "user-provided exclusion mask '{}' has a " "correct shape".format(reg_file_name)) else: # we are dealing with a region file: reglist = pyregion.open(reg_file_name) ## check that regions are in image-like coordinates: ##TODO: remove the code below once 'pyregion' package can correctly ## (DS9-like) convert sky coordinates to image coordinates for all ## supported shapes. #if not all([ (x.coord_format == 'image' or \ # x.coord_format == 'physical') for x in reglist]): # print("WARNING: Some exclusion regions are in sky coordinates.\n" # " These regions will be ignored.") # # filter out regions in sky coordinates: # reglist = pyregion.ShapeList( # [x for x in reglist if x.coord_format == 'image' or \ # x.coord_format == 'physical'] # ) #TODO: comment out next lines if we do not support region files # in sky coordinates and uncomment previous block: # Convert regions from sky coordinates to image coordinates: auxwcs = _AuxSTWCS(self.wcs) reglist = reglist.as_imagecoord(auxwcs, rot_wrt_axis=2) # if all regions are exclude regions, then assume that the entire image # should be included and that exclude regions exclude from this # rectangular region representing the entire image: if all([x.exclude for x in reglist]): # we slightly widen the box to make sure that # the entire image is covered: imreg = pyregion.parse("image;box({:.1f},{:.1f},{:d},{:d},0)" .format((img_nx+1)/2.0, (img_ny+1)/2.0, img_nx+1, img_ny+1) ) reglist = pyregion.ShapeList(imreg + reglist) # create a mask from regions: regmask = np.asarray( reglist.get_mask(shape=(img_ny, img_nx)), dtype=np.bool ) if mask is not None and regmask is not None: mask = np.logical_and(regmask, mask) else: mask = regmask #DEBUG: if mask is not None: fn = os.path.splitext(self.fname)[0] + '_srcfind_mask.fits' fits.writeto(fn, mask.astype(dtype=np.uint8), clobber=True) return mask
def auto_zoomed_cores(getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo/+catalogs/L1157.sw.final.reliable.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo_proto/+catalogs/L1157.sw.final.reliable.ok.cat', core_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1157/core_figures/', Herschel_70um_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cepL1157_070_mu_emission.image.resamp.fits', Herschel_160um_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cepL1157_160_mu_emission.image.resamp.fits', Herschel_250um_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_250_mu.image.resamp.fits', Herschel_350um_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_350_mu.image.resamp.fits', Herschel_500um_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_500_mu.image.resamp.fits', Herschel_coldens_image='/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_255_mu.image.resamp.fits', distance=325.): # Import getsources "good core" data table cores_array1 = numpy.loadtxt(getsources_core_catalog,comments='!') good_core_indices = good_cores_getsources.get_good_cores(getsources_core_catalog) cores_array = cores_array1[numpy.array(good_core_indices)] core_center_RA = cores_array[:,3] core_center_Dec = cores_array[:,4] core_index = 1 for line in cores_array: x_coor = str(line[3]) y_coor = str(line[4]) AFWHM_array = [line[14], line[23], line[41], line[59], line[68], line[50]] # 70,160,250,350,500,coldens BFWHM_array = [line[15], line[24], line[42], line[60], line[69], line[51]] Theta_array = [line[16], line[25], line[43], line[61], line[70], line[52]] SIG_array = [line[8], line[17], line[35], line[53], line[62], line[44]] images_array = [Herschel_70um_image, Herschel_160um_image, Herschel_250um_image, Herschel_350um_image, Herschel_500um_image, Herschel_coldens_image] wavelengths = ['070', '160', '250', '350', '500', '255'] maximums = numpy.zeros(len(AFWHM_array)) minimums = numpy.zeros(len(AFWHM_array)) counter = 0 for i in wavelengths: ### Create a DS9 region string for the core's getsources ellipse, ### from which a mask will be created. region = ('fk5;box(' + x_coor + ', ' + y_coor + ', ' + str(0.05) + ', ' + str(0.05) + ', ' + str(0.0)+')') r = pyregion.parse(region) f = fits.open(images_array[counter]) header_primary = fits.getheader(images_array[counter]) data = fits.getdata(images_array[counter]) mymask = r.get_mask(hdu=f[0]) newmask=numpy.where(mymask!=0) maximums[counter] = max(data[newmask]) minimums[counter] = min(data[newmask]) f.close() newmask2=numpy.where(mymask==0, 0, data) fits.writeto(i + '_contour_mask.fits', newmask2, header_primary, clobber=True) counter+=1 microns = ['mu_070', 'mu_160', 'mu_250', 'mu_350', 'mu_500', 'mu_255'] v_max = maximums v_min = minimums contour_levels = [(maximums[0]*0.3,maximums[0]*0.5,maximums[0]*0.7,maximums[0]*0.9), (maximums[1]*0.3,maximums[1]*0.5,maximums[1]*0.7,maximums[1]*0.9), (maximums[2]*0.3,maximums[2]*0.5,maximums[2]*0.7,maximums[2]*0.9), (maximums[3]*0.3,maximums[3]*0.5,maximums[3]*0.7,maximums[3]*0.9), (maximums[4]*0.3,maximums[4]*0.5,maximums[4]*0.7,maximums[4]*0.9), (maximums[5]*0.3,maximums[5]*0.5,maximums[5]*0.7,maximums[5]*0.9)] fig = plt.figure(figsize=(8,5.5)) f=0 for i in wavelengths: microns[f]=aplpy.FITSFigure(i + '_contour_mask.fits', figure=fig, subplot=(2,3,f+1)) microns[f].recenter(line[3],line[4],0.025) microns[f].show_contour(i + '_contour_mask.fits', colors=('white', 'white', 'white','grey'), levels=contour_levels[f], overlap=True) microns[f].show_colorscale(cmap='gist_stern', vmin=v_min[f], vmax=v_max[f]) #microns[f].show_regions('/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1157/L1157_core_SED/255_all_cores_good.reg') microns[f].add_colorbar() if f==2 or f==5: microns[f].colorbar.set_axis_label_text('MJy/sr') scale = str('{:.2f}'.format(2*(distance*numpy.tan(numpy.radians(0.5*(1.0/60.)))))) if f==0: microns[f].add_scalebar((1./60.), path_effects=[Patheffects.withStroke(linewidth=3, foreground='white')]) microns[f].scalebar.show(1./60.) # length in degrees (one arcminute) microns[f].scalebar.set_corner('top left') microns[f].scalebar.set_label('1' + "'" + ' = ' + scale + ' pc') if SIG_array[f]>5.: line_type = 'solid' else: line_type = 'dashed' microns[f].show_ellipses(line[3], line[4], AFWHM_array[f]/3600., BFWHM_array[f]/3600., Theta_array[f]+90., color='#00FF00', zorder=10, linewidth=1.0, linestyle=line_type) #microns[f].show_markers(line[3], line[4], c='#00FF00', marker='x', zorder=10, linewidths=1.5,s=20) #microns[f].show_markers(line[3], line[4], c='black', marker='x', zorder=9, linewidths=2.0,s=30) microns[f].tick_labels.hide() microns[f].axis_labels.hide() #microns[f].set_title('L' + name) if i=='255': microns[f].add_label(0.3,0.1,'N$_{H2}$',relative=True, path_effects=[Patheffects.withStroke(linewidth=3, foreground='white')]) else: microns[f].add_label(0.3,0.1,i + ' $\mu$' + 'm',relative=True, path_effects=[Patheffects.withStroke(linewidth=3, foreground='white')]) f=f+1 fig.subplots_adjust(hspace=0.05, wspace=0.35) fig.canvas.draw() fig.suptitle('Core Number ' + str(core_index) + ' - RA: ' + str(line[3]) + ' Dec: ' + str(line[4])) fig.savefig(core_figure_directory + 'core' +str(core_index) + '.pdf') print 'Core Number = ' + str(core_index) for i in range(6): microns[i].close() core_index = core_index + 1
import pyregion from astropy import units as u from astropy.coordinates import SkyCoord from photutils import CircularAperture from photutils import aperture_photometry fits = sys.argv[1] reg = sys.argv[2] rtn_type = sys.argv[3] hdu = pyfits.open(fits) data = hdu[0].data hdr = hdu[0].header r = pyregion.parse(reg)[0] r_name = r.name r_format = r.coord_format r_coordlist = r.coord_list x_px = r_coordlist[0]-1 # ds9 region is one-indexed y_px = r_coordlist[1]-1 # ds9 region is one-indexed pixscale = hdr['CDELT1'] ap = [] radii = [] last_ap_flux = 0 for i, radius in enumerate(r_coordlist[3:]): apertures = CircularAperture([(x_px, y_px)], r=radius) phot_table = aperture_photometry(data, apertures) this_ap_flux = float(phot_table['aperture_sum'][0])
from astropy.wcs import WCS from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel import pyregion try: knot_region_file = sys.argv[1] line_id = sys.argv[2] region_frame = sys.argv[3] except IndexError: sys.exit("Usage: {} KNOT_REGION_FILE (ha|nii) (linear|image)".format(sys.argv[0])) with open(knot_region_file) as f: knot_region_string = f.read() # Workaround for bug in pyregion.parse when color is of form '#fff' knot_region_string = knot_region_string.replace("color=#", "color=") knot_regions = pyregion.parse(knot_region_string) knot_dict = { knot.attr[1]["text"]: pyregion.ShapeList([knot]) for knot in knot_regions if "text" in knot.attr[1] and knot.name == "ellipse" } tab = Table.read("alba-knots-frompdf.tab", format="ascii", delimiter="\t") vcol = {"ha": "V(Ha)", "nii": "V([N II])"} wcol = {"ha": "W(Ha)", "nii": "W([N II])"} imhdu = fits.open("new-slits-{}-allvels.fits".format(line_id))["scaled"] imwcs = WCS(imhdu.header) ny, nx = imhdu.data.shape
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()