def get_count_stats(out_file, region_file): region = np.flipud(copy_piximgvals(read_file(region_file))) output = np.loadtxt(out_file) imsize = output.shape[1] niter = int(output.shape[0] / imsize) count_sums = np.zeros(niter) for i in range(niter): count_sums[i] = (np.flipud(output[i * imsize:(i + 1) * imsize, :]) * region).sum() return count_sums
def _try_image(crate, make_copy=False, fix_type=False, dtype=SherpaFloat): if make_copy: # Make a copy if a filename passed in dat = pycrates.copy_piximgvals(crate).squeeze() else: # Use a reference if a crate passed in dat = pycrates.get_piximgvals(crate).squeeze() if fix_type: dat = dat.astype(dtype) # FITS standard is FORTRAN filling, Sherpa is c-style # return dat.reshape(dat.shape[::-1]) # Crates now returns image in c-style filling return dat
def _try_image(crate, make_copy=False, fix_type=False, dtype=SherpaFloat): """ checked for new crates """ if make_copy: # Make a copy if a filename passed in dat = pycrates.copy_piximgvals(crate).squeeze() else: # Use a reference if a crate passed in dat = pycrates.get_piximgvals(crate).squeeze() if fix_type: dat = dat.astype(dtype) # FITS standard is FORTRAN filling, Sherpa is c-style # return dat.reshape(dat.shape[::-1]) # Crates now returns image in c-style filling return dat
def get_centroids(out_file, region_file): region = np.flipud(copy_piximgvals(read_file(region_file))) output = np.loadtxt(out_file) imsize = output.shape[1] niter = int(output.shape[0] / imsize) avg_image = np.zeros((imsize, imsize)) xvals = np.zeros(niter) yvals = np.zeros(niter) count_sums = np.zeros(niter) dmcoords.punlearn() for i in range(niter): avg_image += output[i * imsize : (i + 1) * imsize, :] xvals[i], yvals[i] = centroid( np.flipud(output[i * imsize : (i + 1) * imsize, :]) * region, region_file ) count_sums[i] = ((output[i * imsize : (i + 1) * imsize, :]) * region).sum() return xvals, yvals, count_sums
def get_pixel_values(filename): image = pc.read_file(filename) return pc.copy_piximgvals(image) # returns a numpy array
def get_F_C_exp(evtfile, sregs, breg, psfs, exps, exposure): """ Inputs: evtfile Event list file name (used to determine counts in regions) sregs List of source region fits file names breg Background region fits file name psfs List of source psf fits image file names Compute array of psf fractions F and vector of total counts C, such that F[i,j] is PSF fraction of source j in source region i C[i] is total counts in source region i Here, the last source region is actually the background region, so F[n,j] is the PSF fraction of source j in the background region and C[n] is the total counts in the background region. Array F and vector C are returned. In this version, observation exposure is accounted for, either via exposure maps stack exps (one per source/background region) or header keyword. """ import numpy as np import pycrates as pc import region as re # First determine sizes of F and C: ldim = len(sregs) ndim = ldim + 1 C = np.zeros(ndim) # If no psfs are provided, assume source ecf=1 F = np.identity(ndim) # Now build C. First the source regions: for i in np.arange(0, ldim): evtfilter = "%s[sky=region(%s)]" % (evtfile, sregs[i]) evts = pc.read_file(evtfilter) crtype = pc.get_crate_type(evts) if crtype == 'Table': C[i] = len(pc.get_colvals( evts, 0)) # assuming event list has at least 1 column if crtype == 'Image': C[i] = np.sum(pc.copy_piximgvals(evts)) # and now the background region: evtfilter = "%s[sky=region(%s)]" % (evtfile, breg) evts = pc.read_file(evtfilter) crtype = pc.get_crate_type(evts) if crtype == 'Table': C[ldim] = len(pc.get_colvals( evts, 0)) # assuming event list has at least 1 column if crtype == 'Image': C[ldim] = np.sum(pc.copy_piximgvals(evts)) # Next, build F. If psfs are specified, use them to generate the ecf's if len(psfs) > 0: # All but the last row and all but the last column of F contain # the ecf's of source j in region i: for i in np.arange(0, ldim): # row loop for j in np.arange(0, ldim): # column loop imgfilter = "%s[sky=region(%s)]" % (psfs[j], sregs[i]) F[i, j] = np.sum(pc.copy_piximgvals(pc.read_file(imgfilter))) # All but the last column of the last row of F contain the ecf's of # source j in the background region: for j in np.arange(0, ldim): imgfilter = "%s[sky=region(%s)]" % (psfs[j], breg) F[ldim, j] = np.sum(pc.copy_piximgvals(pc.read_file(imgfilter))) # The last column in F contains region areas. All but the last are source regions: for i in np.arange(0, ldim): F[i, ldim] = re.regArea(re.regParse("region(%s)" % sregs[i])) # And the last row, last column entry is the background region area. F[ldim, ldim] = re.regArea(re.regParse("region(%s)" % breg)) # Finally, modify by exposure. If exps are specified, compute average map value in # each region: ereg = np.ones(ndim) if len(exps) > 0: # average expmap in each source region for i in np.arange(0, ldim): imgfilter = "%s[sky=region(%s)]" % (exps[i], sregs[i]) evals = pc.copy_piximgvals(pc.read_file(imgfilter)) enums = evals.copy() enums[enums > 0.0] = 1.0 ereg[i] = np.sum(evals) / np.sum(enums) # Average expmap in background region imgfilter = "%s[sky=region(%s)]" % (exps[ldim], breg) evals = pc.copy_piximgvals(pc.read_file(imgfilter)) enums = evals.copy() enums[enums > 0.0] = 1.0 ereg[ldim] = np.sum(evals) / np.sum(enums) # otherwise, use exposure from header for all regions else: ereg = ereg * exposure F = F * ereg.reshape(ndim, 1) return F, C
def smooth_image_crate(cr, stype, *args, **kwargs): """Smooth the pixel values in the crate. This changes the pixel values stored in the image crate but retains other metadata, such as WCS mapping. Parameters ---------- cr The IMAGECrate to change. stype : str The type of smoothing to apply. The list of supported values is given in the Notes section below. *args, **kwargs The supported arguments depend on the value of the 'stype' argument. See Also -------- scale_image_crate Notes ----- The supported smoothing types, and their arguments, are given below, where function indicates which function from ciao_contrib.smooth is used to smooth the image (it also determines the meaning of the "args and kwargs" column): ======= =========== ======== ================================= stype smoothing function args and kwargs ======= =========== ======== ================================= none none gauss gaussian gsmooth sigma, hwidth=5 boxcar box-car bsmooth radius tophat top-hat tsmooth radius file by file fsmooth filename, norm=True, origin=None image by image ismooth kernel, norm=True, origin=None ======= =========== ======== ================================= Numeric values such as sigma and radius refer to logical pixels, and not SKY or WCS units. This routine modifies the data in the input crate, it does *NOT* return a copy of the crate. Examples -------- Smooth the data with a gaussian with a 3-pixel sigma, using a box half-width of 5 sigmaL >>> cr = read_file('img.fits') >>> smooth_image_crate(cr, 'gauss', 3) Change to use a bow half-width of 7 sigma: >>> cr = read_file('img.fits') >>> smooth_image_crate(cr, 'gauss', sigma=3, hwidth=7) Smooth the pixel values in chandra.img by the image stored in xmm_psf.fits: >>> cr = read_file('chandra.img') >>> smooth_image_crate(cr, 'file', 'xmm_psf.fits') Create a three-by-three kernel and use it to smooth the image stored in cr: >>> kern = np.asarray([0, 1, 0, 1, 2, 1, 0, 1, 0]).reshape(3, 3) >>> smooth_image_crate(cr, 'image', kern) """ if not isinstance(cr, pycrates.IMAGECrate): raise ValueError("First argument must be an image crate.") # Short cut if stype == "none": return ivals = pycrates.copy_piximgvals(cr) try: sfunc = _image_smooth[stype] except KeyError: raise ValueError("Invalid smooth value of '{}': must be one of\n {}".format( stype, " ".join(_image_smooth.keys()))) nvals = sfunc(ivals, *args, **kwargs) pycrates.set_piximgvals(cr, nvals)
def scale_image_crate(cr, scaling="arcsinh"): """Scale the pixel values in the image crate. This changes the pixel values stored in the image crate but retains other metadata, such as WCS mapping. Parameters ---------- cr The IMAGECrate to change. scaling : optional The default value is 'arcsinh', and the list of supported values is given in the Notes section below. See Also -------- smooth_image_crate Notes ----- The supported scaling values, and their meanings, are 'none' This does not change the pixel values. 'arcsinh' The pixel values are replaced by arcsinh(values). 'asinh' The same as 'arcsinh'. 'sqrt' Take the square root of the pixel values. 'square' Take the square of the pixel values. 'log10' The pixel values are replaced by log10(values). 'log' This is similar to 'log10' but uses the natural logarithm. This routine modifies the data in the input crate, it does *NOT* return a copy of the crate. Examples -------- >>> cr = read_file('img.fits') >>> scale_image_crate(cr, 'log10') """ if not isinstance(cr, pycrates.IMAGECrate): raise ValueError("First argument must be an image crate.") # Short cut if scaling == "none": return ivals = pycrates.copy_piximgvals(cr) try: sfunc = _image_scalings[scaling] except KeyError: raise ValueError("Invalid scaling value of '{}': must be one of\n {}".format( scaling, " ".join(_image_scalings.keys()))) pycrates.set_piximgvals(cr, sfunc(ivals))