Пример #1
0
def reproject_to(ref_file, in_tag='orig', out_tag='repro',
                 interpol_dict={'order': 3},
                 clobber=True):
    """Reproject cubes e.g. to match a HESS survey map.

    Can be computationally and memory intensive if the
    HESS map is large or you have many energy bands."""
    logging.info('Reprojecting to {0}'.format(ref_file))
    ref_image = FITSimage(ref_file)
    for ii in range(len(components)):
        in_file = filename(in_tag, ii)
        out_file = filename(out_tag, ii)
        logging.info('Reading {0}'.format(in_file))
        in_image = FITSimage(in_file)
        logging.info('Reprojecting ...')
        out_image = in_image.reproject_to(ref_image.hdr,
                                          interpol_dict=interpol_dict)
        logging.info('Writing {0}'.format(out_file))
        out_image.writetofits(out_file, clobber=clobber)

        # TODO: do this with `astropy.io.fits` instead of calling `fappend`!
        logging.info('Copying energy extension')
        cmd = ['fappend',
               '{0}[ENERGIES]'.format(in_file),
               '{0}'.format(out_file)]
        #call(cmd)
        raise NotImplementedError
Пример #2
0
def make_mask_and_area(ref_file, clobber=True):
    """Make the mask and area images for use by Galprop
    mask == 0 pixels are excluded,
    mask == 1 pixels are included"""
    ref_image = FITSimage(ref_file)
    mask = (ref_image.dat != 0).astype(np.uint8)
    mask_image = FITSimage(externaldata=mask, externalheader=ref_image.hdr)
    mask_image.writetofits('mask.fits', clobber=clobber)
    area = iu.area(ref_image, deg=False)
    area_image = FITSimage(externaldata=area, externalheader=ref_image.hdr)
    area_image.writetofits('area.fits', clobber=clobber)
Пример #3
0
 def __init__(self, tag='repro', clobber=False):
     """dir should contain the cubes already as produced by prepare()"""
     self.tag = tag
     self.clobber = clobber
     # Use toal component as reference
     self.ref_file = filename(tag=tag)
     self.fitsimage = FITSimage(self.ref_file)
     # Construct vectors of glon, glat, energy e.g. for plotting
     ac = iu.axis_coordinates(self.fitsimage)
     self.glon = ac['GLON']
     self.glat = ac['GLAT']
     self.energy = 10 ** ac['PHOTON ENERGY']
     # Read mask if there is one, else don't use a mask
     try:
         self.mask = fits.getdata('mask.fits')
         logging.info('Loaded mask.fits')
     except IOError:
         self.mask = 1
         logging.info('mask.fits not found')
     try:
         self.area = fits.getdata('area.fits')
         logging.info('Loaded area.fits')
     except IOError:
         self.area = iu.area(self.fitsimage, deg=False)
         logging.info('area.fits not found')
Пример #4
0
 def __read_lookup__(self):
     """Read lookup table from FITS file."""
     # TODO: use astropy, not kapteyn here
     from kapteyn.maputils import FITSimage
     dirname = '/Users/deil/work/workspace/galpop/data/GALPROP'
     filename = join(dirname, 'MilkyWay_DR0.5_DZ0.1_DPHI10_RMAX20_ZMAX5_galprop_format.fits')
     # The FITS header is missing the CRPIX keywords, so FITSimage would complain.
     # That's why we read it with pyfits, add the keywords, and then create the FITSimage.
     data = fits.getdata(filename)
     header = fits.getheader(filename)
     for axis in [1, 2, 3, 4]:
         header['CRPIX{0}'.format(axis)] = 1
     self.lookup = FITSimage(externaldata=data, externalheader=header)
Пример #5
0
def _to_image_gaussian(catalog, image):
    """Add catalog of asymmetric Gaussian sources to an image.

    @type catalog: atpy.Table
    @type image: maputils.FITSimage
    @return: maputils.FITSimage"""
    from kapteyn.maputils import FITSimage
    logging.info('Adding %d sources.' % len(catalog.data))

    #
    # Read catalog
    #
    l_center = catalog.data['glon']
    b_center = catalog.data['glat']
    a = catalog.data['a']
    b = catalog.data['b']
    theta = catalog.data['theta']
    flux = catalog.data['flux']

    # Compute matrix entries that describe the ellipse, as defined in
    # the section "9.1.6. Ellipse parameters" in the SExtractor Manual.
    # Note that clb already contains the factor of 2!
    #
    # Another reference giving formulas is
    # http://en.wikipedia.org/wiki/Gaussian_function
    cll = np.cos(theta)**2 / a**2 + np.sin(theta)**2 / b**2
    cbb = np.sin(theta)**2 / a**2 + np.cos(theta)**2 / b**2
    clb = 2 * np.cos(theta) * np.sin(theta) * (a**-2 - b**-2)

    #
    # Add sources to image
    #
    data = image.dat
    header = image.hdr
    for i in range(len(catalog)):  # Loop sources
        l, b = utils.coordinates(image)
        # convert l to the range -180 to +180
        l = np.where(l > 180, l - 360, l)
        exponent = cll[i] * (l - l_center[i]) ** 2 + \
            cbb[i] * (b - b_center[i]) ** 2 + \
            clb[i] * (l - l_center[i]) * (b - b_center[i])
        data += flux[i] * np.exp(-exponent)

    # Return image with sources
    image_out = FITSimage(externalheader=header, externaldata=data)
    return image_out
Пример #6
0
def _to_image_simple(catalog, image):
    """Add sources from a catalog to an image.

    catalog = atpy.Table
    image = kapteyn.maputils.FITSimage

    Note: This implementation doesn't use bounding boxes and thus is slow.
    You should use the faster _to_image_bbox()"""
    from kapteyn.maputils import FITSimage
    from morphology.shapes import morph_types
    nsources = len(catalog)
    data = image.dat
    logging.info('Adding {0} sources.'.format(nsources))

    # Get coordinate maps
    l, b = utils.coordinates(image)

    # Add sources to image one at a time
    for i in range(nsources):
        logging.debug('Adding source {0:3d} of {1:3d}.' ''.format(i, nsources))
        # nans = np.isnan(data).sum()
        # if nans:
        #    logging.debug('Image contains {0} nan entries.'.format(nans))

        # Get relevant columns
        morph_type = catalog[i]['morph_type']
        xpos = catalog[i]['glon']
        xpos = np.where(xpos > 180, xpos - 360, xpos)
        ypos = catalog[i]['glat']
        ampl = catalog[i]['ampl']
        sigma = catalog[i]['sigma']
        epsilon = catalog[i]['epsilon']
        theta = catalog[i]['theta']
        r_in = catalog[i]['r_in']
        r_out = catalog[i]['r_out']

        pars = {
            'delta2d': (xpos, ypos, ampl),
            'shell2d': (xpos, ypos, ampl, r_in, r_out),
            'gauss2d': (xpos, ypos, ampl, sigma, epsilon, theta)
        }
        par = pars[morph_type]

        data += morph_types[morph_type](par, l, b)

    return FITSimage(externalheader=image.hdr, externaldata=data)
Пример #7
0
def make_mask_and_area(ref_file, clobber=True):
    """Make the mask and area images for use by Galprop
    mask == 0 pixels are excluded,
    mask == 1 pixels are included"""
    ref_image = FITSimage(ref_file)
    mask = (ref_image.dat != 0).astype(np.uint8)
    mask_image = FITSimage(externaldata=mask,
                           externalheader=ref_image.hdr)
    mask_image.writetofits('mask.fits', clobber=clobber)
    area = iu.area(ref_image, deg=False)
    area_image = FITSimage(externaldata=area,
                           externalheader=ref_image.hdr)
    area_image.writetofits('area.fits', clobber=clobber)
Пример #8
0
fd_cube = fits.open('gll_iem_v05.fits')
energies = fd_cube[1].data

energy = gmean([10, 500]) * 1000  #GeV to MeV

energy_array = fd_cube[1].data['Energy']
index = np.searchsorted(energy_array, energy)

actual_energy = energy_array[index]
print actual_energy
from kapteyn.maputils import FITSimage
from gammapy.image.utils import cube_to_image
energy_image = cube_to_image(fd_cube[0], index)
energy_image.writeto('fermi_diffuse_slice_10_500.fits', clobber=True)
#reproject to 0.1 deg per pixel resolution
original = FITSimage('fermi_diffuse_slice_10_500.fits', hdunr=1)
reference_data = fits.open('10_500_counts.fits')[0].data
reference_header = fits.open('10_500_counts.fits')[0].header
reference = fits.ImageHDU(data=reference_data, header=reference_header)
reference.writeto('10_500_counts2.fits', clobber=True)
reference = FITSimage('10_500_counts2.fits', hdunr=1)

from utils import image_reprojection

new = image_reprojection(original, reference)
new.writetofits('fermi_diffuse_10_500_reprojected.fits', clobber=True)
out_data = np.nan_to_num(
    fits.open('fermi_diffuse_10_500_reprojected.fits')[0].data)
out_header = fits.open('fermi_diffuse_10_500_reprojected.fits')[0].header
out = fits.ImageHDU(data=out_data, header=out_header)
out.writeto('fermi_diffuse_10_500_reprojected.fits', clobber=True)