示例#1
0
def single_cutout(ax,position,image,mask1=None,mask2=None,points=None,label=None,size=6*u.arcsec):
    
    cutout_image = Cutout2D(image.data,position,size=size,wcs=image.wcs)
    norm = simple_norm(cutout_image.data,clip=False,stretch='linear',percent=99.5)

    ax.imshow(cutout_image.data,origin='lower',norm=norm,cmap=plt.cm.gray_r)

    # plot the nebulae catalogue
    cutout_mask, _  = reproject_interp(mask1,output_projection=cutout_image.wcs,shape_out=cutout_image.shape,order='nearest-neighbor')    
    region_ID = np.unique(cutout_mask[~np.isnan(cutout_mask)])

    contours = []
    for i in region_ID:
        blank_mask = np.zeros_like(cutout_mask)
        blank_mask[cutout_mask==i] = 1
        contours += find_contours(blank_mask, 0.5)

    for coords in contours:
        ax.plot(coords[:,1],coords[:,0],color='tab:red',lw=1,label='HII-region')


    mask = np.zeros((*cutout_mask.shape,4))
    mask[~np.isnan(cutout_mask.data),:] = (0.84, 0.15, 0.16,0.1)
    ax.imshow(mask,origin='lower')

    # plot the association catalogue
    if mask2:
        cutout_mask, _  = reproject_interp(mask2,output_projection=cutout_image.wcs,shape_out=cutout_image.shape,order='nearest-neighbor')    
        region_ID = np.unique(cutout_mask[~np.isnan(cutout_mask)])

        contours = []
        for i in region_ID:
            blank_mask = np.zeros_like(cutout_mask)
            blank_mask[cutout_mask==i] = 1
            contours += find_contours(blank_mask, 0.5)

        for coords in contours:
            ax.plot(coords[:,1],coords[:,0],color='tab:blue',lw=1,label='association')

        mask = np.zeros((*cutout_mask.shape,4))
        mask[~np.isnan(cutout_mask.data),:] = (0.12,0.47,0.71,0.1)
        ax.imshow(mask,origin='lower')

    # mark the position of the clusters within the cutout
    if points:
        region = RectangleSkyRegion(position,0.9*size,0.9*size)
        in_frame = points[region.contains(points['SkyCoord'],cutout_image.wcs)]
        for row in in_frame:
            x,y = row['SkyCoord'].to_pixel(cutout_image.wcs)
            if 5<x<cutout_image.data.shape[0]-5 and 5<y<cutout_image.data.shape[1]-5:
                ax.scatter(x,y,marker='o',facecolors='none',s=20,lw=0.4,color='tab:blue',label='cluster')

    if label:
        t = ax.text(0.07,0.875,label, transform=ax.transAxes,color='black',fontsize=8)
        t.set_bbox(dict(facecolor='white', alpha=1, ec='white'))

    ax.set_xticks([])
    ax.set_yticks([])
    
    return ax
示例#2
0
def getReference(image_in, header_in, reference_fits_file, useExactReproj=False):
    """Return the reference image aligned with the input image.

    getReference accepts a numpy array (masked or not) and a header with WCS information and a master reference fits file and return
    a reprojected reference image array for the same portion of the sky.
    Return reference_image"""
    from reproject import reproject_interp, reproject_exact

    refHasWCS = _headerHasWCS(fits.getheader(reference_fits_file))

    refhdulist = fits.open(reference_fits_file)
    
    ref_mask = np.zeros(refhdulist[0].data.shape, dtype='bool')
    for anhdu in refhdulist[1:]:
        #Combine all the 'bad' and 'mask' masks into a single one, if any
        if any(s in anhdu.name for s in ["bad", "mask"]):
            ref_mask = ref_mask | anhdu.data

    #Check if there is a header available
    if (header_in is not None) and _headerHasWCS(header_in) and refHasWCS:
        #reproject with reproject here...

        if useExactReproj: ref_reproj_data, __ = reproject_exact(refhdulist[0], header_in)
        else: ref_reproj_data, __ = reproject_interp(refhdulist[0], header_in)
        ref_reproj_mask, __ = reproject_interp((ref_mask, refhdulist[0].header), header_in)
        
        gold_master = np.ma.array(data=ref_reproj_data, mask=ref_reproj_mask)

    else:
        #Here do the no WCS method
        gold_master = _no_wcs_available(image_in, np.ma.array(refhdulist[0].data, mask=ref_mask))

    return gold_master
示例#3
0
文件: rgb.py 项目: rag9704/PTS
    def example(self):
        """
        This function ...
        :return:
        """

        # Read in the three images downloaded from here:
        # g: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-g-001737-5-0039.fits.bz2
        # r: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-r-001737-5-0039.fits.bz2
        # i: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-i-001737-5-0039.fits.bz2
        g = fits.open('frame-g-001737-5-0039.fits.bz2')[0]
        r = fits.open('frame-r-001737-5-0039.fits.bz2')[0]
        i = fits.open('frame-i-001737-5-0039.fits.bz2')[0]

        # remap r and i onto g
        r_new, r_mask = reproject_interp(r, g.header)
        i_new, i_mask = reproject_interp(i, g.header)

        # zero out the unmapped values
        i_new[np.logical_not(i_mask)] = 0
        r_new[np.logical_not(r_mask)] = 0

        # red=i, green=r, blue=g
        # make a file with the default scaling
        rgb_default = make_lupton_rgb(i_new,
                                      r_new,
                                      g.data,
                                      filename="ngc6976-default.jpeg")
        # this scaling is very similar to the one used in Lupton et al. (2004)
        rgb = make_lupton_rgb(i_new,
                              r_new,
                              g.data,
                              Q=10,
                              stretch=0.5,
                              filename="ngc6976.jpeg")
示例#4
0
def IQU_to_lic(fitsname, licfname):
    I, Q, U = hp.read_map(fitsname, field=[0, 1, 2])
    U = U * 2
    psi = np.arctan2(-U, Q) * 0.5

    I_car, psi_car = healpix_to_carteian(I, psi)

    I_mol, footprint = reproject_interp((I_car, WCS(car_header)), mol_header)
    psi_mol, footprint = reproject_interp((psi_car, WCS(car_header)),
                                          mol_header)

    licmap_mol = calc_lic(psi_mol)
    licmap_car = calc_lic(psi_car)

    hdul = fits.HDUList()
    hdul.append(fits.PrimaryHDU())
    hdul.append(
        fits.ImageHDU(name='Imap', data=I_mol[:, ::-1], header=mol_header))
    hdul.append(
        fits.ImageHDU(name='LIC', data=licmap_mol[:, ::-1], header=mol_header))
    hdul.append(
        fits.ImageHDU(name='Imap', data=I_car[:, ::-1], header=car_header))
    hdul.append(
        fits.ImageHDU(name='LIC', data=licmap_car[:, ::-1], header=car_header))

    hdul.writeto(licfname, overwrite=True)
示例#5
0
文件: rgb.py 项目: SKIRT/PTS
def make_example_rgbs(self):

    """
    This function ...
    :return:
    """

    # Read in the three images downloaded from here:
    # g: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-g-001737-5-0039.fits.bz2
    # r: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-r-001737-5-0039.fits.bz2
    # i: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-i-001737-5-0039.fits.bz2
    g = fits.open('frame-g-001737-5-0039.fits.bz2')[0]
    r = fits.open('frame-r-001737-5-0039.fits.bz2')[0]
    i = fits.open('frame-i-001737-5-0039.fits.bz2')[0]

    # remap r and i onto g
    r_new, r_mask = reproject_interp(r, g.header)
    i_new, i_mask = reproject_interp(i, g.header)

    # zero out the unmapped values
    i_new[np.logical_not(i_mask)] = 0
    r_new[np.logical_not(r_mask)] = 0

    # red=i, green=r, blue=g
    # make a file with the default scaling
    rgb_default = make_lupton_rgb(i_new, r_new, g.data, filename="ngc6976-default.jpeg")
    # this scaling is very similar to the one used in Lupton et al. (2004)
    rgb = make_lupton_rgb(i_new, r_new, g.data, Q=10, stretch=0.5, filename="ngc6976.jpeg")
示例#6
0
def initDeflection_Image(imagefile, deflectionFileX, deflectionFileY, zlens,
                         zsource_in, zsource_out):

    ### Read in image file
    ### Read in deflection maps,
    ### reproject to image file coordinates

    imhdu = fits.open(imagefile)
    imdata = imhdu[0].data

    hdudeflx = fits.open(deflectionFileX)
    hdudefly = fits.open(deflectionFileY)

    #reproject deflection fields to HST WCS pixels
    deflxHST, footprint = reproject_interp(hdudeflx[0], imhdu[0].header)
    deflyHST, footprint = reproject_interp(hdudefly[0], imhdu[0].header)
    ax = deflxHST / 0.06  # arcsec -> pixels
    ay = deflyHST / 0.06  # arcsec -> pixels

    # convert back to Dds / Ds = 1
    if zsource_in == 0:
        Dds_Ds_out = Dds_Ds(zlens, zsource_out)

        ax = ax * Dds_Ds_out
        ay = ay * Dds_Ds_out
    else:
        Dds_Ds_in = Dds_Ds(zlens, zsource_in)
        Dds_Ds_out = Dds_Ds(zlens, zsource_out)

        ax = ax / Dds_Ds_in * Dds_Ds_out
        ay = ay / Dds_Ds_in * Dds_Ds_out

    return ax, ay, imdata
示例#7
0
    def reproject_dustmap(self, outheader):
        """
        Reprojects dust map (and errors) on the desired WCS
        :param outheader: `~astropy.io.fits.header.Header`
        output map header
        :return: outmap: `~numpy.ndarray`
        output map
        :return: errormap: `~numpy.ndarray`
        erromap
        """

        if self.hpx:
            # load properties of healpix grid
            coordsys = self.dustmap.header['COORDSYS']
            if coordsys == 'C':
                coordsys = 'ICRS'
            elif coordsys == 'E':
                coordsys = 'Ecliptic'
            elif coordsys == 'G':
                coordsys = 'Galactic'
            else:
                print('coordinate system of input dust map unknown:', coordsys)

            nested = self.dustmap.header['ORDERING']
            if nested == 'NESTED':
                nested = True
            elif nested == 'RING':
                nested = False
            else:
                print('ordering of input dust map unknown:', nested)

            # dust map
            if self.dustmap.header['TFORM1'] == '1024E':
                outmap, footprint = reproject_from_healpix(self.dustmap[1],outheader)
            else:
                outmap, footprint = reproject_from_healpix((self.dustmap[1].data[self.mapname], coordsys),
                                                           outheader, nested=nested)

            # error map
            if self.errorname == 'None':
                errormap = np.ones(np.shape(outmap))
            else:
                errormap, footprint = reproject_from_healpix(
                    (self.dustmap[1].data[self.errorname], coordsys),
                    outheader, nested=nested)
        else:
            outmap, footprint = reproject_interp(self.dustmap[self.mapname], outheader)
            if self.errorname == 'None':
                errormap = np.ones(np.shape(outmap))
            else:
                errormap, footprint = reproject_interp(self.dustmap[self.errorname], outheader)

        outmap *= self.scale
        errormap *= self.scale

        return outmap, errormap
示例#8
0
文件: tdep_v2.py 项目: heh15/Arp240
def reproj_binning2(data, wcs_in, bin_num, centerCoord='', shape_out=''):
    '''
    centerCoord is the array of central coordinates in degree. 
    '''
    map_in_shape = np.shape(data)
    nx_in, ny_in = map_in_shape
    nx_out = math.trunc(nx_in / bin_num)
    ny_out = math.trunc(ny_in / bin_num)
    if shape_out == '':
        shape_out = (nx_out, ny_out)
    if centerCoord == '':
        centerCoord = wcs_in.wcs.crval
    wcs_out = WCS(naxis=2)
    wcs_out.wcs.crval = centerCoord
    wcs_out.wcs.crpix = [
        math.trunc(shape_out[1] / 2),
        math.trunc(shape_out[0] / 2)
    ]
    wcs_out.wcs.cdelt = wcs_in.wcs.cdelt * bin_num
    wcs_out.wcs.ctype = ['RA---SIN', 'DEC--SIN']
    data_binned, footprint = reproject_interp((data, wcs_in),
                                              wcs_out,
                                              shape_out=shape_out)

    return wcs_out, data_binned
示例#9
0
    def _reproject_to_wcs(self, geom, mode="interp", order=1):
        from reproject import reproject_interp, reproject_exact

        data = np.empty(geom.data_shape)

        for img, idx in self.iter_by_image():
            # TODO: Create WCS object for image plane if
            # multi-resolution geom
            shape_out = geom.get_image_shape(idx)[::-1]

            if self.geom.projection == "CAR" and self.geom.is_allsky:
                vals, footprint = reproject_car_to_wcs(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            elif mode == "interp":
                vals, footprint = reproject_interp(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            elif mode == "exact":
                vals, footprint = reproject_exact(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            else:
                raise TypeError(
                    "mode must be 'interp' or 'exact'. Got: {!r}".format(mode)
                )

            data[idx] = vals

        return self._init_copy(geom=geom, data=data)
示例#10
0
def reprojection(table, outfolder_splus, outfolder_sdss):

    for i in range(len(table)):
        ra = table['RA'][i]
        dec = table['DEC'][i]
        id_1 = table['ID'][i]
        #id_ = id_1[0:len(id_1) - 1]
        name = '%s_%.6f_%.6f' % (id_1, ra, dec)

        hdu_splus = fits.open(outfolder_splus + '/' + name + '-crop.fits')[0]

        pasta = outfolder_sdss + '/' + name
        try:
            caminhos = [
                os.path.join(pasta, nome) for nome in os.listdir(pasta)
            ]
        except FileNotFoundError:
            continue
        arquivos = [arq for arq in caminhos if os.path.isfile(arq)]
        sdss_files = [
            arq for arq in arquivos if arq.lower().endswith(".fits.gz")
        ]

        for i in range(len(sdss_files)):
            filename_sdss = sdss_files[i]
            hdu_sdss = fits.open(gzip.open(filename_sdss))[0]
            array, footprint = reproject_interp(hdu_sdss, hdu_splus.header)
            fits.writeto(outfolder_sdss + '/' + name + '/' + name + '-rep' +
                         str(i) + '.fits',
                         array,
                         hdu_sdss.header,
                         overwrite=True)
def build_image(id_,
                set_,
                bands=['EUC_VIS', 'EUC_H', 'EUC_J', 'EUC_Y'],
                img_size=200,
                scale=100,
                clip=True):
    tables = []
    data = np.empty((img_size, img_size, len(bands)))
    for i, band in enumerate(bands):
        fname = get_image_filename_from_id(id_, band, set_)
        try:
            tables.append(fits.open(fname))
        except FileNotFoundError as fe:
            raise
        if band != 'EUC_VIS':
            band_data, data_footprint = reproject_interp(
                tables[i][0], tables[0][0].header)
        else:
            band_data = tables[0][0].data
        band_data[np.isnan(band_data)] = 0.
        if clip:
            interval = AsymmetricPercentileInterval(0.25,
                                                    99.75,
                                                    n_samples=100000)
            vmin, vmax = interval.get_limits(band_data)
            stretch = MinMaxInterval() + LogStretch()
            data[:, :, i] = stretch(
                ((np.clip(band_data, -vmin * 0.7, vmax)) / (vmax)))
        else:
            stretch = LogStretch() + MinMaxInterval()
            data[:, :, i] = stretch(band_data)
    for t in tables:
        t.close()
    return data.astype(np.float32)
示例#12
0
def merge_maps(maps, outmap, target_res, lmin, lmax, bmin, bmax):
    # create output hdu
    # determine map properties
    nx = int((lmax - lmin) / target_res)
    dx = (lmax - lmin) / nx
    ny = int((bmax - bmin) / target_res)
    dy = (bmax - bmin) / ny
    crpix_y = -bmin / dy + 1
    # wcs
    w = wcs.WCS(naxis=2)
    w.wcs.crpix = [1., crpix_y]
    w.wcs.cdelt = np.array([-dx, dy])
    w.wcs.crval = [lmax, 0.]
    w.wcs.ctype = ["GLON-CAR", "GLAT-CAR"]
    # header
    header = w.to_header()
    # empty map
    map_data = np.zeros([ny, nx])
    # hdu
    hdu = fits.PrimaryHDU(map_data, header=header)

    # reproject input maps onto output map
    # and fill output map with input giving precedence to maps at the end of the list
    for map in maps:
        # reproject
        array, footprint = reproject_interp(fits.open(map)[0], hdu.header)
        hdu.data[footprint == 1] = array[footprint == 1]

    # write new file
    hdu.writeto(outmap)
示例#13
0
    def reproject_to(self, reference_cube, projection_type='bicubic'):
        """Spatially reprojects a `SkyCube` onto a reference cube.

        Parameters
        ----------
        reference_cube : `SkyCube`
            Reference cube with the desired spatial projection.
        projection_type : {'nearest-neighbor', 'bilinear',
            'biquadratic', 'bicubic', 'flux-conserving'}
            Specify method of reprojection. Default: 'bilinear'.

        Returns
        -------
        reprojected_cube : `SkyCube`
            Cube spatially reprojected to the reference cube.
        """
        from reproject import reproject_interp

        reference = reference_cube.data
        shape_out = reference[0].shape
        try:
            wcs_in = self.wcs.dropaxis(2)
        except:
            wcs_in = self.wcs
        try:
            wcs_out = reference_cube.wcs.dropaxis(2)
        except:
            wcs_out = reference_cube.wcs
        energy = self.energy

        cube = self.data
        new_cube = np.zeros((cube.shape[0], reference.shape[1],
                             reference.shape[2]))
        energy_slices = np.arange(cube.shape[0])
        # TODO: Re-implement to reproject cubes directly without needing
        # to loop over energies here. Errors with reproject when doing this
        # first need to be understood and fixed.
        for i in energy_slices:
            array = cube[i]
            data_in = (array.value, wcs_in)
            new_cube[i] = reproject_interp(data_in, wcs_out, shape_out, order=projection_type)[0]
        new_cube = Quantity(new_cube, array.unit)
        # Create new wcs
        header_in = self.wcs.to_header()
        header_out = reference_cube.wcs.to_header()
        # Keep output energy info the same as input, but changes spatial information
        # So need to restore energy parameters to input values here
        try:
            header_out['CRPIX3'] = header_in['CRPIX3']
            header_out['CDELT3'] = header_in['CDELT3']
            header_out['CTYPE3'] = header_in['CTYPE3']
            header_out['CRVAL3'] = header_in['CRVAL3']
        except:
            pass

        wcs_out = WCS(header_out).celestial

        # TODO: how to fill 'meta' in better way?
        meta = OrderedDict(header_out)
        return SkyCube(data=new_cube, wcs=wcs_out, energy=energy, meta=meta)
示例#14
0
    def _reproject_to_wcs(self, geom, mode='interp', order=1):
        from reproject import reproject_interp, reproject_exact

        data = np.empty(geom.data_shape)

        for img, idx in self.iter_by_image():
            # TODO: Create WCS object for image plane if
            # multi-resolution geom
            shape_out = geom.get_image_shape(idx)[::-1]

            if self.geom.projection == 'CAR' and self.geom.is_allsky:
                vals, footprint = reproject_car_to_wcs((img, self.geom.wcs),
                                                       geom.wcs,
                                                       shape_out=shape_out)
            elif mode == 'interp':
                vals, footprint = reproject_interp((img, self.geom.wcs),
                                                   geom.wcs,
                                                   shape_out=shape_out)
            elif mode == 'exact':
                vals, footprint = reproject_exact((img, self.geom.wcs),
                                                  geom.wcs,
                                                  shape_out=shape_out)
            else:
                raise TypeError(
                    "Invalid reprojection mode, either choose 'interp' or 'exact'")

            data[idx] = vals

        return self._init_copy(geom=geom, data=data)
示例#15
0
def heliographic(m):
    shape_out = [720, 1440]
    frame_out = SkyCoord(0,
                         0,
                         unit=u.deg,
                         frame="heliographic_stonyhurst",
                         obstime=m.date)
    header = sunpy.map.make_fitswcs_header(
        shape_out,
        frame_out,
        scale=[180 / shape_out[0], 360 / shape_out[1]] * u.deg / u.pix,
        projection_code="CAR")

    out_wcs = astropy.wcs.WCS(header)
    array, footprint = reproject_interp(m, out_wcs, shape_out=shape_out)
    outmap = sunpy.map.Map((array, header))
    outmap.plot_settings = m.plot_settings

    fig = plt.figure()
    ax = plt.subplot(projection=outmap)
    outmap.plot(ax)

    ax.set_xlim(0, shape_out[1])
    ax.set_ylim(0, shape_out[0])

    plt.show()
示例#16
0
def calc_stellar_mass(iracFile, MtoLFile, outFile):
    '''
    Calculate the stellar mass surface density for a given IRAC image
    and MtoL image.
    '''

    # open IRAC data file
    irac = fits.open(iracFile)
    iracData = irac[0].data
    iracHdr = irac[0].header

    # open MtoL data file
    MtoL = fits.open(MtoLFile)
    MtoL_regrid = reproject_interp(MtoL,
                                   output_projection=iracHdr,
                                   hdu_in=0,
                                   order='nearest-neighbor',
                                   return_footprint=False)
    irac.close()
    MtoL.close()

    # Equation 8 from Leroy+ 2019 (z0mgs paper)
    mstarirac1 = 3.5e2 * (MtoL_regrid / 0.5) * (iracData)

    # create output file
    outHdr = iracHdr
    outHdr['BUNIT'] = 'MSUN/PC^2'
    outfits = fits.PrimaryHDU(data=mstarirac1, header=outHdr)
    outfits.writeto(outFile, overwrite=True)
示例#17
0
文件: frame.py 项目: wdobbels/CAAPR
    def rebin(self, reference_wcs, exact=True, parallel=True):
        """
        This function ...
        :param reference_wcs:
        :param exact:
        :param parallel:
        :return:
        """

        # Calculate rebinned data and footprint of the original image
        if exact:
            new_data, footprint = reproject_exact(
                (self._data, self.wcs),
                reference_wcs,
                shape_out=reference_wcs.shape,
                parallel=parallel)
        else:
            new_data, footprint = reproject_interp(
                (self._data, self.wcs),
                reference_wcs,
                shape_out=reference_wcs.shape)

        # Replace the data and WCS
        self._data = new_data
        self._wcs = reference_wcs

        # Return the footprint
        return Frame(footprint)
示例#18
0
文件: wcsnd.py 项目: gammapy/gammapy
    def _reproject_to_wcs(self, geom, mode="interp", order=1):
        from reproject import reproject_interp, reproject_exact

        data = np.empty(geom.data_shape)

        for img, idx in self.iter_by_image():
            # TODO: Create WCS object for image plane if
            # multi-resolution geom
            shape_out = geom.get_image_shape(idx)[::-1]

            if self.geom.projection == "CAR" and self.geom.is_allsky:
                vals, footprint = reproject_car_to_wcs(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            elif mode == "interp":
                vals, footprint = reproject_interp(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            elif mode == "exact":
                vals, footprint = reproject_exact(
                    (img, self.geom.wcs), geom.wcs, shape_out=shape_out
                )
            else:
                raise TypeError(
                    "mode must be 'interp' or 'exact'. Got: {!r}".format(mode)
                )

            data[idx] = vals

        return self._init_copy(geom=geom, data=data)
示例#19
0
def err_func(pars,
             inp,
             data,
             wcs_hires,
             wcs_lowres,
             pixscale=0.03,
             bounds=np.array([[6, 20], [42, 57]])):
    norm, fwhm, offset = pars
    numseepix = fwhm / pixscale
    nanpix_data = np.where(np.isnan(data))
    data[nanpix_data] = 0

    kern = Gaussian2DKernel(numseepix /
                            2.355)  # FWHM = sigma * 2 sqrt(2.*ln(2))
    if offset is None:
        convdat = norm * convolve_fft(inp, kern, boundary='extend')
    else:
        convdat = norm * convolve_fft(inp, kern, boundary='extend') + offset
    #convdat = norm * convolve(inp, kern, boundary='extend')
    inpreproj, inpfootprint = \
        reproject_interp((convdat, wcs_hires), wcs_lowres, order='nearest-neighbor',
                         shape_out=np.shape(data))
    model = inpreproj
    model[nanpix_data] = 0
    nanpix_inp = np.where(np.isnan(model))
    model[nanpix_inp] = 0
    data[nanpix_inp] = 0
    return np.sum(
        (data[bounds[1, 0]:bounds[1, 1], bounds[0, 0]:bounds[0, 1]] -
         model[bounds[1, 0]:bounds[1, 1], bounds[0, 0]:bounds[0, 1]])**2)
示例#20
0
def comparison(source_name):
    num_name = source_name[4:8]
    hdu_MIPS24 = fits.open(direc + 'Bulles_Nicolas/MB' + str(num_name) +
                           '/MIPS24_MB' + str(num_name) + '.fits')
    Source = np.load(str(source_name) + '.npy', allow_pickle=True).item()
    #test=Source['NII_122_em']
    test = Source['OH_119']
    wcs_MIPS = WCS(hdu_MIPS24[0].header)
    WCS_Source = test[2]
    New_MIPS, footprint = reproject_interp(hdu_MIPS24,
                                           WCS_Source,
                                           shape_out=np.shape(test[0]))

    fig = plt.figure(0)
    fig.suptitle('Reprojection MIPS24 on Herschel')

    gs = GridSpec(2, 2, hspace=0.3, wspace=0.3)
    ax1 = plt.subplot(gs[0, 0], projection=wcs_MIPS)
    ax2 = plt.subplot(gs[1, 0], projection=WCS_Source)
    ax3 = plt.subplot(gs[0, 1], projection=WCS_Source)
    ax4 = plt.subplot(gs[1, 1], projection=WCS_Source)

    ax1.imshow(hdu_MIPS24[0].data)
    ax1.set_title('MIPS24', fontsize=11)
    ax1.coords[0].set_ticks(exclude_overlapping=True)
    ax1.set_xlabel('RA (J2000)')
    ax1.set_ylabel('DEC (J2000)')
    ax1.grid()

    ax2.imshow(test[0])
    ax2.set_title('Herschel NII', fontsize=11)
    ax2.coords[0].set_ticks(exclude_overlapping=True)
    ax2.set_xlabel('RA (J2000)')
    ax2.set_ylabel('DEC (J2000)')
    ax2.contour(hdu_MIPS24[0].data,
                transform=ax2.get_transform(wcs_MIPS),
                colors='white',
                linewidths=0.5)
    ax2.set_xlim(0, len(test[0]) - 1)
    ax2.set_ylim(0, len(test[0]) - 1)
    #ax2.imshow(hdu_MIPS24[0].data, alpha=0.5)
    ax2.grid()

    ax3.imshow(New_MIPS)
    ax3.set_title('MIPS24 on Herschel NII', fontsize=11)
    ax3.coords[0].set_ticks(exclude_overlapping=True)
    ax3.set_xlabel('RA (J2000)')
    ax3.set_ylabel('DEC (J2000)')

    ax4.imshow(test[0])
    ax4.contour(New_MIPS, colors='white', linewidths=0.5)
    ax4.coords[0].set_ticks(exclude_overlapping=True)
    ax4.set_title('Overlap', fontsize=11)
    ax4.set_xlabel('RA (J2000)')
    ax4.set_ylabel('DEC (J2000)')

    plt.show()

    return hdu_MIPS24
    def reproject(self, header, order='bilinear'):
        """
        Reproject the image into a new header.

        Parameters
        ----------
        header : `astropy.io.fits.Header`
            A header specifying a cube in valid WCS
        order : int or str, optional
            The order of the interpolation (if ``mode`` is set to
            ``'interpolation'``). This can be either one of the following
            strings:

                * 'nearest-neighbor'
                * 'bilinear'
                * 'biquadratic'
                * 'bicubic'

            or an integer. A value of ``0`` indicates nearest neighbor
            interpolation.
        """

        self._raise_wcs_no_celestial()

        try:
            from reproject.version import version
        except ImportError:
            raise ImportError("Requires the reproject package to be"
                              " installed.")

        # Need version > 0.2 to work with cubes
        from distutils.version import LooseVersion
        if LooseVersion(version) < "0.3":
            raise Warning("Requires version >=0.3 of reproject. The current "
                          "version is: {}".format(version))

        from reproject import reproject_interp

        # TODO: Find the minimal footprint that contains the header and only reproject that
        # (see FITS_tools.regrid_cube for a guide on how to do this)

        newwcs = wcs.WCS(header)
        shape_out = [
            header['NAXIS{0}'.format(i + 1)] for i in range(header['NAXIS'])
        ][::-1]

        newproj, newproj_valid = reproject_interp((self.value, self.header),
                                                  newwcs,
                                                  shape_out=shape_out,
                                                  order=order)

        self = Projection(newproj,
                          unit=self.unit,
                          wcs=newwcs,
                          meta=self.meta,
                          header=header,
                          read_beam=True)

        return self
def get_cont(header):
    contfn = paths.dpath('W51_te_continuum_best.fits')
    beam = radio_beam.Beam.from_fits_header(contfn)
    cont_Jy = reproject.reproject_interp(input_data=contfn,
                                         output_projection=header)[0]*u.Jy
    cont_K = cont_Jy.to(u.K, u.brightness_temperature(beam,
                                                      continuum_frequency))
    return cont_K
示例#23
0
def reproject_interp_rgb(input_data, *args, **kwargs):
    data = input_data.data
    wcs = WCS(input_data.header).celestial
    return np.moveaxis(
        np.stack([
            reproject_interp((data[:, :, i], wcs), *args,
                             **kwargs)[0].astype(data.dtype) for i in range(3)
        ]), 0, -1)
示例#24
0
    def reproject(self, reference, mode='interp', *args, **kwargs):
        """
        Reproject image to given reference.

        Parameters
        ----------
        reference : `~astropy.io.fits.Header`, or `~gammapy.image.SkyImage`
            Reference image specification to reproject the data on.
        mode : {'interp', 'exact'}
            Interpolation mode.
        *args : list
            Arguments passed to `~reproject.reproject_interp` or
            `~reproject.reproject_exact`.
        **kwargs : dict
            Keyword arguments passed to `~reproject.reproject_interp` or
            `~reproject.reproject_exact`.

        Returns
        -------
        image : `~gammapy.image.SkyImage`
            Image reprojected onto ``reference``.
        """

        from reproject import reproject_interp, reproject_exact

        if isinstance(reference, SkyImage):
            wcs_reference = reference.wcs
            shape_out = reference.data.shape
        elif isinstance(reference, fits.Header):
            wcs_reference = WCS(reference)
            shape_out = (reference['NAXIS2'], reference['NAXIS1'])
        else:
            raise TypeError("Invalid reference image. Must be either instance"
                            "of `Header`, `WCS` or `SkyImage`.")

        if mode == 'interp':
            out = reproject_interp((self.data, self.wcs),
                                   wcs_reference,
                                   shape_out=shape_out,
                                   *args,
                                   **kwargs)
        elif mode == 'exact':
            out = reproject_exact((self.data, self.wcs),
                                  wcs_reference,
                                  shape_out=shape_out,
                                  *args,
                                  **kwargs)
        else:
            raise TypeError(
                "Invalid reprojection mode, either choose 'interp' or 'exact'")

        return self.__class__(
            name=self.name,
            data=out[0],
            wcs=wcs_reference,
            unit=self.unit,
            meta=self.meta,
        )
示例#25
0
    def reproject_ref2sci(self, how: str = "swarp", **kwargs):
        """

        :param how: 'swarp' or 'reproject'
        :return:
        """
        if how == "swarp":
            nthreads = kwargs.get("nthreads", 4)

            command, ref_reprojected, weight_name = prepare_swarp_align(
                self, nthreads=nthreads)

            _ = subprocess.run(command.split(),
                               capture_output=True,
                               check=True)

            # load the result
            with fits.open(ref_reprojected) as hdulist:
                ref_projected = hdulist[0].data

            # clean up
            keep_tmp = kwargs.get("keep_tmp", False)

            if not keep_tmp:
                _, _, field, filt, ccd, _, quad = self.name.split("_")

                path_ref_base = pathlib.Path(
                    os.path.join(self.path_base, "ref"))
                path_ref = path_ref_base / pathlib.Path(
                    f"{field}/{ccd}/{quad}/{filt}/")
                fs = list(
                    path_ref.glob(f"ref.{field}_{ccd}_{quad}_{filt}*remap*"))

                if self.verbose:
                    print(fs)

                for ff in fs:
                    try:
                        if self.verbose:
                            print(f"removing {str(ff)}")
                        os.remove(str(ff))
                    except OSError:
                        if self.verbose:
                            print(f"failed to remove {str(ff)}")

        elif how == "reproject":
            order = kwargs.get("order", "bicubic")  # 'bilinear'

            ref_projected = reproject_interp(
                (self.ref, self.header_ref),
                self.header_sci,
                order=order,
                return_footprint=False,
            )
        else:
            raise ValueError("unknown reproject method")

        return ref_projected
示例#26
0
def spin_and_trim(imlist,
                  wcsrefimname,
                  trimfrac=0.4,
                  trimdir='DIA_TRIM',
                  verbose=False):
    """ Rotate images to match the WCS of the WCS reference image (spin) and
    then cut off a fraction of the outer region of the image (trim).
    Returns a list of the trimmed images.
    """
    if verbose:
        print('Spinning Input Images: ' + str(imlist))
        print("to match WCS Ref image: " + wcsrefimname)
        print("and trimming by : %i pct" % (trimfrac * 100))

    if not os.path.exists(trimdir):
        os.makedirs(trimdir)
    trimmed_image_list = []
    hdr_imref = fits.getheader(wcsrefimname)
    wcs_imref = WCS(hdr_imref)
    for imname in list(imlist) + [wcsrefimname]:
        imname_trimmed = os.path.join(
            trimdir,
            os.path.basename(imname).replace('.fits', '_trim.fits'))
        if os.path.isfile(imname_trimmed):
            print("%s exists.  Skipping trimming." % imname_trimmed,
                  file=sys.stderr)
            continue
        if verbose:
            print("Reprojecting %s to x,y frame of %s " %
                  (imname, wcsrefimname),
                  file=sys.stderr)
        im = fits.open(imname)
        if imname != wcsrefimname:
            array, footprint = reproject_interp(im[0], hdr_imref)
        else:
            # WCS Ref image does not need reprojection
            array = im[0].data

        # Trim off the outer trimfrac to reduce chances of NaN errors due to
        # empty array segments after rotation (also speeds up DIA processing)
        arraysize = array.shape
        cutout = Cutout2D(array,
                          position=[arraysize[1] / 2., arraysize[0] / 2.],
                          size=[
                              round(arraysize[1] * (1 - trimfrac)),
                              round(arraysize[0] * (1 - trimfrac))
                          ],
                          wcs=wcs_imref)

        # save reprojected-and-trimmed image:
        im[0].data = cutout.data
        im[0].header.update(cutout.wcs.to_header())
        im.writeto(imname_trimmed, output_verify='fix+warn')
        im.close()

        trimmed_image_list.append(imname_trimmed)
    return (trimmed_image_list)
    def align_image(self, img, header, ref_img_header):
        """
        Takes an ImageHDU object as img, the header of that image for header
        and a astropy header object from the reference image for ref_img
        """

        aligned_img, footprint = reproject_interp((img, header),
                                                  ref_img_header)
        return aligned_img
示例#28
0
def FitsCutout(pathname, ra, dec, rad_arcsec, pix_width_arcsec=None, exten=0, reproj=False, variable=False, outfile=False, parallel=True, fast=True):

    # Open input fits and extract data
    if isinstance(pathname,basestring):
        in_fitsdata = astropy.io.fits.open(pathname)
    elif isinstance(pathname,astropy.io.fits.HDUList):
        in_fitsdata = pathname
    in_map = in_fitsdata[exten].data
    in_header = in_fitsdata[exten].header
    in_wcs = astropy.wcs.WCS(in_header)

    # If reprojection not requesed, pass input parameters to astropy cutout function
    if reproj==False:
        pos = astropy.coordinates.SkyCoord(ra, dec, unit='deg')
        size = astropy.units.Quantity(2.0*rad_arcsec, astropy.units.arcsec)
        cutout_obj = astropy.nddata.utils.Cutout2D(in_map, pos, size, wcs=in_wcs, mode='partial', fill_value=np.NaN)

        # Extract outputs of interest
        out_map = cutout_obj.data
        out_wcs = cutout_obj.wcs
        out_header = out_wcs.to_header()

    # If reporjection requested, pass input parameters to reprojection function (fast or thorough, as specified)
    if reproj==True:
        import reproject
        width_deg = ( 2.0 * float(rad_arcsec) ) / 3600.0
        if pix_width_arcsec == None:
            pix_width_arcsec = 3600.0*np.mean(np.abs(np.diagonal(in_wcs.pixel_scale_matrix)))
        cutout_header = FitsHeader(ra, dec, width_deg, pix_width_arcsec)
        cutout_shape = ( cutout_header['NAXIS1'],  cutout_header['NAXIS1'] )
        try:
            if fast==False:
                cutout_tuple = reproject.reproject_exact(in_fitsdata, cutout_header, shape_out=cutout_shape, hdu_in=exten, parallel=parallel)
            elif fast==True:
                cutout_tuple = reproject.reproject_interp(in_fitsdata, cutout_header, shape_out=cutout_shape, hdu_in=exten)
        except Exception as exception:
            print(exception.message)

        # Extract outputs of interest
        try:
            out_map = cutout_tuple[0]
        except:
            pdb.set_trace()
        out_wcs = astropy.wcs.WCS(cutout_header)
        out_header = cutout_header

    # Save, tidy, and return; all to taste
    if outfile!=False:
        out_hdu = astropy.io.fits.PrimaryHDU(data=out_map, header=out_header)
        out_hdulist = astropy.io.fits.HDUList([out_hdu])
        out_hdulist.writeto(outfile, overwrite=True)
    if isinstance(pathname,basestring):
        in_fitsdata.close()
    if variable==True:
        out_hdu = astropy.io.fits.PrimaryHDU(data=out_map, header=out_header)
        out_hdulist = astropy.io.fits.HDUList([out_hdu])
        return out_hdulist
示例#29
0
def convolve_reproj(inp,
                    norm,
                    fwhm,
                    data,
                    wcs_hires,
                    wcs_lowres,
                    offset=None,
                    pixscale=0.03,
                    bounds=np.array([[10, 23], [37, 52]]),
                    inneroffset=None,
                    angle=None):
    if isinstance(fwhm, float):
        numseepix = fwhm / pixscale
        kern = Gaussian2DKernel(numseepix /
                                2.355)  # FWHM = sigma * 2 sqrt(2.*ln(2))
    else:
        try:
            fwhmx, fwhmy = fwhm
        except:
            import pdb
            pdb.set_trace()
        numseepix_x = fwhmx / pixscale
        numseepix_y = fwhmy / pixscale
        if angle is None:
            angle = 0
        try:
            kern = Gaussian2DKernel(numseepix_x / 2.355,
                                    numseepix_y / 2.355,
                                    theta=angle)
        except:
            import pdb
            pdb.set_trace()
    if (offset is None) & (inneroffset is None):
        convdat = norm * convolve_fft(inp, kern, boundary='wrap')
    elif (inneroffset is None):
        convdat = norm * convolve_fft(inp, kern, boundary='wrap') + offset
    elif (offset is None):
        convdat = norm * convolve_fft(inp + inneroffset, kern, boundary='wrap')
    else:
        convdat = norm * convolve_fft(inp + inneroffset, kern,
                                      boundary='wrap') + offset
    #convdat = norm * convolve(inp, kern, boundary='extend')
    try:
        inpreproj, inpfootprint = \
            reproject_interp((convdat, wcs_hires), wcs_lowres,
                         order='nearest-neighbor',
                         shape_out=np.shape(data))
    except:
        import pdb
        pdb.set_trace()
    if offset is not None:
        inpreproj += offset
    if bounds is not None:
        return inpreproj[bounds[1, 0]:bounds[1, 1], bounds[0, 0]:bounds[0, 1]]
    else:
        return inpreproj
    def reproject(self, header, order='bilinear'):
        """
        Reproject the image into a new header.

        Parameters
        ----------
        header : `astropy.io.fits.Header`
            A header specifying a cube in valid WCS
        order : int or str, optional
            The order of the interpolation (if ``mode`` is set to
            ``'interpolation'``). This can be either one of the following
            strings:

                * 'nearest-neighbor'
                * 'bilinear'
                * 'biquadratic'
                * 'bicubic'

            or an integer. A value of ``0`` indicates nearest neighbor
            interpolation.
        """

        self._raise_wcs_no_celestial()

        try:
            from reproject.version import version
        except ImportError:
            raise ImportError("Requires the reproject package to be"
                              " installed.")

        # Need version > 0.2 to work with cubes
        from distutils.version import LooseVersion
        if LooseVersion(version) < "0.3":
            raise Warning("Requires version >=0.3 of reproject. The current "
                          "version is: {}".format(version))

        from reproject import reproject_interp

        # TODO: Find the minimal footprint that contains the header and only reproject that
        # (see FITS_tools.regrid_cube for a guide on how to do this)

        newwcs = wcs.WCS(header)
        shape_out = [header['NAXIS{0}'.format(i + 1)] for i in range(header['NAXIS'])][::-1]

        newproj, newproj_valid = reproject_interp((self.value,
                                                   self.header),
                                                  newwcs,
                                                  shape_out=shape_out,
                                                  order=order)

        self = Projection(newproj, unit=self.unit, wcs=newwcs,
                          meta=self.meta, header=header,
                          read_beam=True)

        return self
示例#31
0
	def align_objects(self, object_list, output_dir, method):
		"""Align a series of frames to a reference frame via ASTROALIGN or WCS REPROJECTION"""

		if len(object_list) == 0 or len(object_list) == 1:

			print("Insufficient number of images for alignment")

		else:

			print("Opening reference frame", object_list[0])
			reference_frame = fits.open(object_list[0])
			reference_data = reference_frame[0].data
			reference_header = reference_frame[0].header

			print("Converting reference data to FITS")
			reference_hdu = fits.PrimaryHDU(reference_data, header=reference_header)

			print("Writing reference frame to output directory")
			reference_hdu.writeto(output_dir + "/a-" + str(object_list[0]), overwrite=True)

			for i in range(1, len(object_list)):

				if os.path.isfile("a-" + object_list[i]):

					print("Skipping align on", object_list[i])

				else:

					print("Opening target frame", object_list[i])
					target_frame = fits.open(object_list[i])
					target_data = target_frame[0].data
					target_header = target_frame[0].header

					if method == "astroalign":

						print("Aligning target frame with reference frame via ASTROALIGN")
						array = aa.register(target_data, reference_data)

					elif method == "reproject":

						print("Converting target data to FITS")
						target_hdu = fits.PrimaryHDU(target_data, header=target_header)

						print("Aligning target frame with reference frame via WCS")
						array, footprint = reproject_interp(target_hdu, reference_header)

					print("Converting aligned target data to FITS")
					target_hdu = fits.PrimaryHDU(array, header=target_header)

					print("Writing aligned frame to output directory")
					target_hdu.writeto(output_dir + "/a-" + str(object_list[i]), overwrite=True)

		return
示例#32
0
def project_data_into_region():
    
    to_region_fn = "/Volumes/DataDavy/GALFA/SC_241/LAB_corrected_coldens.fits"
    to_region_hdr = fits.getheader(to_region_fn)
    
    allsky_fn = "/Volumes/DataDavy/GALFA/DR2/FullSkyNarrow/GALFA_HI_W_S1011_V-009.2kms.fits"
    allsky_hdr = fits.getheader(allsky_fn)
    allsky_data = fits.getdata(allsky_fn)
     
    new_image, footprint = reproject_interp((allsky_data, allsky_hdr), to_region_hdr) 
    
    return new_image
示例#33
0
def project_data_into_region(from_data_fn, to_region = "SC_241"):
    
    if to_region == "SC_241":
        to_region_fn = "/Volumes/DataDavy/GALFA/SC_241/LAB_corrected_coldens.fits"
        to_region_hdr = fits.getheader(to_region_fn)
    
    from_data_hdr = fits.getheader(from_data_fn)
    from_data_data = fits.getdata(from_data_fn)
     
    new_image, footprint = reproject_interp((from_data_data, from_data_hdr), to_region_hdr) 
    
    return new_image
示例#34
0
def inject_model_into_precal_single(precal_name, model_name):
    # Lets reproject the simulation file to the exposure CCDs planes
    target_projection = fits.open(precal_name, mode="update")
    simulated_frame = fits.open(model_name)
    array, footprint = reproject_interp(simulated_frame[0],
                                        target_projection[1].header)
    array[np.isnan(array)] = 0
    array = array / target_projection[1].header['FLXSCALE']
    target_projection[1].data = target_projection[1].data + array
    target_projection.flush()
    target_projection.close()
    return (precal_name)
示例#35
0
def getReference(image_in,
                 header_in,
                 reference_fits_file,
                 useExactReproj=False):
    """Return the reference image aligned with the input image.

    getReference accepts a numpy array (masked or not) and a header with WCS information and a master reference fits file and return
    a reprojected reference image array for the same portion of the sky.
    Return reference_image"""
    from reproject import reproject_interp, reproject_exact

    refHasWCS = _headerHasWCS(fits.getheader(reference_fits_file))

    refhdulist = fits.open(reference_fits_file)

    ref_mask = np.zeros(refhdulist[0].data.shape, dtype='bool')
    for anhdu in refhdulist[1:]:
        #Combine all the 'bad' and 'mask' masks into a single one, if any
        if any(s in anhdu.name for s in ["bad", "mask"]):
            ref_mask = ref_mask | anhdu.data

    #Check if there is a header available
    if (header_in is not None) and _headerHasWCS(header_in) and refHasWCS:
        #reproject with reproject here...

        if useExactReproj:
            ref_reproj_data, __ = reproject_exact(refhdulist[0], header_in)
        else:
            ref_reproj_data, __ = reproject_interp(refhdulist[0], header_in)
        ref_reproj_mask, __ = reproject_interp(
            (ref_mask, refhdulist[0].header), header_in)

        gold_master = np.ma.array(data=ref_reproj_data, mask=ref_reproj_mask)

    else:
        #Here do the no WCS method
        gold_master = _no_wcs_available(
            image_in, np.ma.array(refhdulist[0].data, mask=ref_mask))

    return gold_master
def assemble_reference(refdatas, wcs, shape):
    """Reproject and stack the reference images to match the science image"""
    refdatas_reprojected = []
    refdata_foot = np.zeros(shape, float)
    for data in refdatas:
        reprojected, foot = reproject_interp((data.data, data.wcs), wcs, shape)
        refdatas_reprojected.append(reprojected)
        refdata_foot += foot

    refdata_reproj = np.nanmean(refdatas_reprojected, axis=0)
    refdata_reproj[np.isnan(refdata_reproj)] = 0.
    refdata = CCDData(refdata_reproj, wcs=wcs, mask=refdata_foot == 0., unit='adu')
    return refdata
示例#37
0
def image_reproject_wcs_to_file(source_image_hdu, target_image_hdu_header, filepath=None):
    """reproject one wcs image to the wcs of another image

    :param source_image_hdu:        the HDU object of source image
    :param target_image_hdu_header: the header object of target image
    :param filepath:                the output file path
    :return:
    """
    array, footprint = reproject_interp(source_image_hdu, target_image_hdu_header)
    if filepath is not None:
        # write file
        fits.writeto(filepath, array, target_image_hdu_header, clobber=True)  # clobber=OVERWRITE
    else:
        # return array & footprint
        return array, footprint
示例#38
0
文件: core.py 项目: dltiziani/gammapy
    def reproject(self, reference, mode='interp', *args, **kwargs):
        """
        Reproject image to given reference.

        Parameters
        ----------
        reference : `~astropy.io.fits.Header`, or `~gammapy.image.SkyImage`
            Reference image specification to reproject the data on.
        mode : {'interp', 'exact'}
            Interpolation mode.
        *args : list
            Arguments passed to `~reproject.reproject_interp` or
            `~reproject.reproject_exact`.
        **kwargs : dict
            Keyword arguments passed to `~reproject.reproject_interp` or
            `~reproject.reproject_exact`.

        Returns
        -------
        image : `~gammapy.image.SkyImage`
            Image reprojected onto ``reference``.
        """

        from reproject import reproject_interp, reproject_exact

        if isinstance(reference, SkyImage):
            wcs_reference = reference.wcs
            shape_out = reference.data.shape
        elif isinstance(reference, fits.Header):
            wcs_reference = WCS(reference)
            shape_out = (reference['NAXIS2'], reference['NAXIS1'])
        else:
            raise TypeError("Invalid reference image. Must be either instance"
                            "of `Header`, `WCS` or `SkyImage`.")

        if mode == 'interp':
            out = reproject_interp((self.data, self.wcs), wcs_reference,
                                   shape_out=shape_out, *args, **kwargs)
        elif mode == 'exact':
            out = reproject_exact((self.data, self.wcs), wcs_reference,
                                  shape_out=shape_out, *args, **kwargs)
        else:
            raise TypeError("Invalid reprojection mode, either choose 'interp' or 'exact'")

        return self.__class__(
            name=self.name, data=out[0], wcs=wcs_reference,
            unit=self.unit, meta=self.meta,
        )
示例#39
0
文件: mask.py 项目: SKIRT/PTS
    def rebin(self, reference_wcs, exact=False, parallel=True, threshold=0.5, dilate=False, rank=2, connectivity=1,
              iterations=2):

        """
        This function ...
        :param reference_wcs:
        :param exact:
        :param parallel:
        :param threshold:
        :param dilate:
        :param rank:
        :param connectivity:
        :param iterations:
        :return:
        """

        from .frame import Frame

        # Check whether the frame has a WCS
        if not self.has_wcs: raise RuntimeError("Cannot rebin a mask without coordinate system")

        # Check whether the WCS is the same
        if self.wcs == reference_wcs: return Frame.ones_like(self)

        #from ..tools import plotting
        #print(self._data.shape)
        #plotting.plot_box(self._data.astype(int), title="before")

        # Calculate rebinned data and footprint of the original image
        if exact: new_data, footprint = reproject_exact((self._data.astype(int), self.wcs), reference_wcs, shape_out=reference_wcs.shape, parallel=parallel)
        else: new_data, footprint = reproject_interp((self._data.astype(int), self.wcs), reference_wcs, shape_out=reference_wcs.shape)

        #from ..tools import plotting
        #print(new_data.shape)
        #plotting.plot_box(new_data, title="after")

        # Get binary mask data
        mask_data = np.logical_or(new_data > threshold, np.isnan(new_data))

        # Replace the data and WCS
        self._data = mask_data
        self._wcs = reference_wcs.copy()

        # Dilate?
        if dilate: self.dilate_rc(rank, connectivity=connectivity, iterations=iterations)  # 1 also worked in test

        # Return the footprint
        return Frame(footprint, wcs=reference_wcs.copy())
示例#40
0
def extract_mapcube_region(infile, skydir, outfile, maphdu=0):
    """Extract a region out of an all-sky mapcube file.

    Parameters
    ----------

    infile : str
        Path to mapcube file.

    skydir : `~astropy.coordinates.SkyCoord`

    """

    h = fits.open(os.path.expandvars(infile))

    npix = 200
    shape = list(h[maphdu].data.shape)
    shape[1] = 200
    shape[2] = 200

    wcs = WCS(h[maphdu].header)
    skywcs = WCS(h[maphdu].header, naxis=[1, 2])
    coordsys = get_coordsys(skywcs)

    region_wcs = wcs.deepcopy()

    if coordsys == 'CEL':
        region_wcs.wcs.crval[0] = skydir.ra.deg
        region_wcs.wcs.crval[1] = skydir.dec.deg
    elif coordsys == 'GAL':
        region_wcs.wcs.crval[0] = skydir.galactic.l.deg
        region_wcs.wcs.crval[1] = skydir.galactic.b.deg
    else:
        raise Exception('Unrecognized coordinate system.')

    region_wcs.wcs.crpix[0] = npix // 2 + 0.5
    region_wcs.wcs.crpix[1] = npix // 2 + 0.5

    from reproject import reproject_interp
    data, footprint = reproject_interp(h, region_wcs.to_header(),
                                       hdu_in=maphdu,
                                       shape_out=shape)

    hdu_image = fits.PrimaryHDU(data, header=region_wcs.to_header())
    hdulist = fits.HDUList([hdu_image, h['ENERGIES']])
    hdulist.writeto(outfile, clobber=True)
示例#41
0
文件: wcsnd.py 项目: pdeiml/gammapy
    def _reproject_wcs(self, geom, mode='interp', order=1):
        from reproject import reproject_interp, reproject_exact

        map_out = WcsNDMap(geom)
        axes_eq = np.all([ax0 == ax1 for ax0, ax1 in
                          zip(geom.axes, self.geom.axes)])

        for vals, idx in map_out.iter_by_image():

            if self.geom.ndim == 2 or axes_eq:
                img = self.data[idx[::-1]]
            else:
                coords = axes_pix_to_coord(geom.axes, idx)
                img = self.interp_image(coords, order=order).data

            # FIXME: This is a temporary solution for handling maps
            # with undefined pixels
            if np.any(~np.isfinite(img)):
                img = img.copy()
                img[~np.isfinite(img)] = 0.0

            # TODO: Create WCS object for image plane if
            # multi-resolution geom
            shape_out = geom.get_image_shape(idx)[::-1]

            if self.geom.projection == 'CAR' and self.geom.is_allsky:
                data, footprint = reproject_car_to_wcs((img, self.geom.wcs),
                                                       geom.wcs,
                                                       shape_out=shape_out)
            elif mode == 'interp':
                data, footprint = reproject_interp((img, self.geom.wcs),
                                                   geom.wcs,
                                                   shape_out=shape_out)
            elif mode == 'exact':
                data, footprint = reproject_exact((img, self.geom.wcs),
                                                  geom.wcs,
                                                  shape_out=shape_out)
            else:
                raise TypeError(
                    "Invalid reprojection mode, either choose 'interp' or 'exact'")

            vals[...] = data

        return map_out
示例#42
0
    def rebin(self, reference_wcs, exact=True, parallel=True):

        """
        This function ...
        :param reference_wcs:
        :param exact:
        :param parallel:
        :return:
        """

        # Calculate rebinned data and footprint of the original image
        if exact: new_data, footprint = reproject_exact((self._data, self.wcs), reference_wcs, shape_out=reference_wcs.shape, parallel=parallel)
        else: new_data, footprint = reproject_interp((self._data, self.wcs), reference_wcs, shape_out=reference_wcs.shape)

        # Replace the data and WCS
        self._data = new_data
        self._wcs = reference_wcs

        # Return the footprint
        return Frame(footprint)
def project_to_header(fitsfile, header, **kwargs):
    """
    Reproject an image to a header.  Simple wrapper of
    reproject.reproject_interp

    Parameters
    ----------
    fitsfile : string
        a FITS file name
    header : pyfits.Header
        A pyfits Header instance with valid WCS to project to
    quiet : bool
        Silence Montage's output

    Returns
    -------
    np.ndarray image projected to header's coordinates

    """
    import reproject
    return reproject.reproject_interp(fitsfile, header, **kwargs)[0]
示例#44
0
def regrid(hdu, output_header, order='bilinear'):
    outh = output_header['N2HASH']
    logger.info('(regrid) output_header={outh}, order={order}'.format(**locals()))
    logger.info('(regrid) start calculation'.format(**locals()))
    regrided, footprint = reproject.reproject_interp(hdu, output_header, order=order)
    logger.info('(regrid) done'.format(**locals()))
    
    new_hdu = astropy.io.fits.PrimaryHDU(regrided, output_header)
    
    hist1 = hdu.header['HISTORY']
    hist2 = new_hdu.header['HISTORY']

    hist1n2 = '\n'.join([_ for _ in str(hist1).split('\n')
                         if _.startswith('n2:')])
    hist2other = '\n'.join([_ for _ in str(hist1).split('\n')
                            if not _.startswith('n2:')])
    new_hist = hist2other + '\n' + hist1n2
    try:
        new_hdu.header.pop('HISTORY')
    except KeyError:
        pass
    [new_hdu.header.add_history(_) for _ in new_hist.split('\n')]
    
    if 'BUNIT' in hdu.header: new_hdu.header['BUNIT'] = hdu.header['BUNIT']
    if 'BSCALE' in hdu.header: new_hdu.header['BSCALE'] = hdu.header['BSCALE']
    if 'BZERO' in hdu.header: new_hdu.header['BZERO'] = hdu.header['BZERO']
    if 'BMAJ' in hdu.header: new_hdu.header['BMAJ'] = hdu.header['BMAJ']
    if 'BMIN' in hdu.header: new_hdu.header['BMIN'] = hdu.header['BMIN']
    if 'BTYPE' in hdu.header: new_hdu.header['BTYPE'] = hdu.header['BTYPE']
    if 'BUNIT' in hdu.header: new_hdu.header['BUNIT'] = hdu.header['BUNIT']
    if 'OBJECT' in hdu.header: new_hdu.header['OBJECT'] = hdu.header['OBJECT']
    if 'MAPID' in hdu.header: new_hdu.header['MAPID'] = hdu.header['MAPID']
    if 'MAPVER' in hdu.header: new_hdu.header['MAPVER'] = hdu.header['MAPVER']
    if 'RESTFRQ' in hdu.header: new_hdu.header['RESTFRQ'] = hdu.header['RESTFRQ']
    if 'SPECSYS' in hdu.header: new_hdu.header['SPECSYS'] = hdu.header['SPECSYS']
    if 'LINE' in hdu.header: new_hdu.header['LINE'] = hdu.header['LINE']
    if 'TELESCOP' in hdu.header: new_hdu.header['TELESCOP'] = hdu.header['TELESCOP']
    if 'INSTRUME' in hdu.header: new_hdu.header['INSTRUME'] = hdu.header['INSTRUME']
    return new_hdu
                            CRVAL2=-2.839256111111E+01,
                            CDELT2=0.0002777777777777778,
                            CRPIX2=225.0,
                            CUNIT2='deg     ',)
                      )


tbl = table.Table.read(paths.tpath("continuum_photometry.ipac"), format='ascii.ipac',)

for imname in files:
    tbl.add_column(table.Column(name=imname, data=np.zeros(len(tbl),
                                                           dtype='float'),
                                unit=files[imname]['bunit']))

    ffile = fits.open(os.path.join(datapath, files[imname]['filename']))
    new_data,_ = reproject.reproject_interp(ffile, alma_hdr)
    new_hdu = fits.PrimaryHDU(data=new_data, header=alma_hdr)

    files[imname]['file'] = new_hdu

    ww = wcs.WCS(files[imname]['file'].header)
    files[imname]['wcs'] = ww

    assert ww.naxis == 2

# Fix column around Sgr B2
col = files['Column']['file'].data
col_conv = convolve_fft(col, Gaussian2DKernel(5), interpolate_nan=True,
                        normalize_kernel=True)
files['Column']['file'].data[np.isnan(col)] = col_conv[np.isnan(col)]
files['Column']['file'].data *= 1e21
示例#46
0
#!/usr/bin/env python

import numpy as np
from astropy.io import fits
from astropy.wcs import WCS
import glob

# an astropy module to reproject images
from reproject import reproject_interp


import argparse

parser = argparse.ArgumentParser(description ='group objects by filter and target for combining with swarp')
parser.add_argument('--image1', dest = 'image1', default = 'test-ha.fits', help = 'Image to serve as reference')
parser.add_argument('--image2', dest = 'image2', default = 'test-r.fits', help = 'Image to align to reference')

args = parser.parse_args()

hdu1 = fits.open(args.image1)[0]
hdu2 = fits.open(args.image2)[0]

im2new, im2footprint = reproject_interp(hdu2, hdu1.header)

fits.writeto(args.image2.split('.fits')[0]+'-shifted.fits', im2new, hdu1.header, overwrite=True)

#hdu1.close()
#hdu2.close()
示例#47
0
def make_cutouts(catalogname, imagename, image_label, apply_rotation=False,
                 table_format='ascii.ecsv', image_ext=0, clobber=False,
                 verbose=True):
    """Make cutouts from a 2D image and write them to FITS files.

    Catalog must have the following columns with unit info, where applicable:

        * ``'id'`` - ID string; no unit necessary.
        * ``'ra'`` - RA (e.g., in degrees).
        * ``'dec'`` - DEC (e.g., in degrees).
        * ``'cutout_x_size'`` - Cutout width (e.g., in arcsec).
        * ``'cutout_y_size'`` - Cutout height (e.g., in arcsec).
        * ``'cutout_pa'`` - Cutout angle (e.g., in degrees). This is only
          use if user chooses to rotate the cutouts. Positive value
          will result in a clockwise rotation.
        * ``'spatial_pixel_scale'`` - Pixel scale (e.g., in arcsec/pix).

    The following are no longer used, so they are now optional:

        * ``'slit_pa'`` - Slit angle (e.g., in degrees).
        * ``'slit_width'`` - Slit width (e.g., in arcsec).
        * ``'slit_length'`` - Slit length (e.g., in arcsec).

    Cutouts are organized as follows::

        working_dir/
            <image_label>_cutouts/
                <id>_<image_label>_cutout.fits

    Each cutout image is a simple single-extension FITS with updated WCS.
    Its header has the following special keywords:

        * ``OBJ_RA`` - RA of the cutout object in degrees.
        * ``OBJ_DEC`` - DEC of the cutout object in degrees.
        * ``OBJ_ROT`` - Rotation of cutout object in degrees.

    Parameters
    ----------
    catalogname : str
        Catalog table defining the sources to cut out.

    imagename : str
        Image to cut.

    image_label : str
        Label to name the cutout sub-directory and filenames.

    apply_rotation : bool
        Cutout will be rotated to a given angle. Default is `False`.

    table_format : str, optional
        Format as accepted by `~astropy.table.QTable`. Default is ECSV.

    image_ext : int, optional
        Image extension to extract header and data. Default is 0.

    clobber : bool, optional
        Overwrite existing files. Default is `False`.

    verbose : bool, optional
        Print extra info. Default is `True`.

    """
    # Optional dependencies...
    from reproject import reproject_interp

    table = QTable.read(catalogname, format=table_format)

    with fits.open(imagename) as pf:
        data = pf[image_ext].data
        wcs = WCS(pf[image_ext].header)

    # It is more efficient to operate on an entire column at once.
    c = SkyCoord(table['ra'], table['dec'])
    x = (table['cutout_x_size'] / table['spatial_pixel_scale']).value  # pix
    y = (table['cutout_y_size'] / table['spatial_pixel_scale']).value  # pix
    pscl = table['spatial_pixel_scale'].to(u.deg / u.pix)

    # Do not rotate if column is missing.
    if 'cutout_pa' not in table.colnames:
        apply_rotation = False

    # Sub-directory, relative to working directory.
    path = '{0}_cutouts'.format(image_label)
    if not os.path.exists(path):
        os.mkdir(path)

    cutcls = partial(Cutout2D, data, wcs=wcs, mode='partial')

    for position, x_pix, y_pix, pix_scl, row in zip(c, x, y, pscl, table):

        if apply_rotation:
            pix_rot = row['cutout_pa'].to(u.degree).value

            cutout_wcs = WCS(naxis=2)
            cutout_wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
            cutout_wcs.wcs.crval = [position.ra.deg, position.dec.deg]
            cutout_wcs.wcs.crpix = [(x_pix - 1) * 0.5, (y_pix - 1) * 0.5]

            try:
                cutout_wcs.wcs.cd = wcs.wcs.cd
                cutout_wcs.rotateCD(-pix_rot)
            except AttributeError:
                cutout_wcs.wcs.cdelt = wcs.wcs.cdelt
                cutout_wcs.wcs.crota = [0, -pix_rot]

            cutout_hdr = cutout_wcs.to_header()

            try:
                cutout_arr = reproject_interp(
                    (data, wcs), cutout_hdr,
                    shape_out=(math.floor(y_pix + math.copysign(0.5, y_pix)),
                               math.floor(x_pix + math.copysign(0.5, x_pix))),
                    order=2)
            except Exception:
                if verbose:
                    log.info('reproject failed: '
                             'Skipping {0}'.format(row['id']))
                continue

            cutout_arr = cutout_arr[0]  # Ignore footprint
            cutout_hdr['OBJ_ROT'] = (pix_rot, 'Cutout rotation in degrees')

        else:
            try:
                cutout = cutcls(position, size=(y_pix, x_pix))
            except NoConvergence:
                if verbose:
                    log.info('WCS solution did not converge: '
                             'Skipping {0}'.format(row['id']))
                continue
            except NoOverlapError:
                if verbose:
                    log.info('Cutout is not on image: '
                             'Skipping {0}'.format(row['id']))
                continue
            else:
                cutout_hdr = cutout.wcs.to_header()
                cutout_arr = cutout.data

        if np.array_equiv(cutout_arr, 0):
            if verbose:
                log.info('No data in cutout: Skipping {0}'.format(row['id']))
            continue

        fname = os.path.join(
            path, '{0}_{1}_cutout.fits'.format(row['id'], image_label))

        # Construct FITS HDU.
        hdu = fits.PrimaryHDU(cutout_arr)
        hdu.header.update(cutout_hdr)
        hdu.header['OBJ_RA'] = (position.ra.deg, 'Cutout object RA in deg')
        hdu.header['OBJ_DEC'] = (position.dec.deg, 'Cutout object DEC in deg')

        hdu.writeto(fname, clobber=clobber)

        if verbose:
            log.info('Wrote {0}'.format(fname))
示例#48
0
文件: rgb.py 项目: aplpy/aplpy
def make_rgb_cube(files, output, north=True):
    """
    Make an RGB data cube from a list of three FITS images.

    This method can read in three FITS files with different
    projections/sizes/resolutions and uses the `reproject
    <https://reproject.readthedocs.io/en/stable/>`_ package to reproject them all
    to the same projection.

    Two files are produced by this function. The first is a three-dimensional
    FITS cube with a filename give by ``output``, where the third dimension
    contains the different channels. The second is a two-dimensional FITS
    image with a filename given by ``output`` with a `_2d` suffix. This file
    contains the mean of the different channels, and is required as input to
    FITSFigure if show_rgb is subsequently used to show a color image
    generated from the FITS cube (to provide the correct WCS information to
    FITSFigure).

    Parameters
    ----------

    files : tuple or list
       A list of the filenames of three FITS filename to reproject.
       The order is red, green, blue.

    output : str
       The filename of the output RGB FITS cube.

    north : bool, optional
        Whether to rotate the image so that north is up. By default, this is
        assumed to be 'north' in the ICRS frame, but you can also pass any
        astropy :class:`~astropy.coordinates.BaseCoordinateFrame` to indicate
        to use the north of that frame.
    """

    # Check that input files exist
    for f in files:
        if not os.path.exists(f):
            raise Exception("File does not exist : " + f)

    if north is not False:
        frame = ICRS() if north is True else north
        auto_rotate = False
    else:
        frame = None
        auto_rotate = True

    # Find optimal WCS and shape based on input images
    wcs, shape = find_optimal_celestial_wcs(files, frame=frame, auto_rotate=auto_rotate)
    header = wcs.to_header()

    # Generate empty datacube
    image_cube = np.zeros((len(files),) + shape, dtype=np.float32)

    # Loop through files and reproject
    for i, filename in enumerate(files):
        image_cube[i, :, :] = reproject_interp(filename, wcs, shape_out=shape)[0]

    # Write out final cube
    fits.writeto(output, image_cube, header, overwrite=True)

    # Write out collapsed version of cube
    fits.writeto(output.replace('.fits', '_2d.fits'),
                 np.mean(image_cube, axis=0), header, overwrite=True)
示例#49
0
model = model[::-1, ::-1]

sd_beam = Beam.from_fits_header(append_path("M33_14B-088_HI_model_channel_330.fits"))
fft_sd = np.fft.fftshift(np.fft.fft2(np.nan_to_num(model)))

# Also load in the original Arecibo channel that has not been regridded.
low_hdu_orig = \
    fits.open(append_path("M33_14B-088_HI_model_original_arecibo.fits"))[0]

# The commented out sections were for ensuring that the model matched
# regridded versions using FITS_tools and reproject. On the large scales that
# matter, the answer is yes they do match.
# regrid_model, footprint = reproject_interp(low_hdu_orig, low_hdu.header)
# regrid_model_fitstools = hcongrid(low_hdu_orig.data, low_hdu_orig.header,
#                                   low_hdu.header)
regrid_mask = reproject_interp(mask_hdu, low_hdu_orig.header)[0]
regrid_mask[np.isnan(regrid_mask)] = 0.0
regrid_mask = regrid_mask == 1.0
regrid_mask = nd.binary_fill_holes(regrid_mask)


low_hdu_orig.data[~regrid_mask] = np.NaN
# regrid_model[~mask[::-1, ::-1]] = np.NaN

fft_sd_arecibo = np.fft.fftshift(np.fft.fft2(np.nan_to_num(low_hdu_orig.data)))

pixscale_arecibo = \
    wcs.utils.proj_plane_pixel_area(wcs.WCS(low_hdu_orig))**0.5 * \
    u.deg

# SD Azimuthal average
示例#50
0
def cleaning(filename_cube='paws-pdbi+30m-12co10-1as.cube.fixed', filename_rotmap='paws_rotmod'):
	"""
	Argument format:
	"(filename_cube='paws-pdbi+30m-12co10-1as.cube.fixed', filename_rotmap='paws_rotmod')".
	Be sure to leave out the ".fits" extension when inputting a file name.

	filename_cube - the filename of the .fits file containing the uncorrected spectral data that we want to work with.
	filename_rotmap - the filename of the above file's corresponding rotational velocity map.

	NOTE: Currently only supports 'paws-pdbi+30m-12co10-1as.cube.fixed' (M51) and 'm33.co21_iram' (M33), along with
		their respective velocity maps.

	"""

	cube = SpectralCube.read(filename_cube+".fits")     # This is the cube of the raw, uncorrected data.
	rot = fits.open(filename_rotmap+'.fits')[0]


	# Checks if 'reprojection' is necessary. If so, then it reprojects the rotational velocity map to match
	#    the cube's dimensions.

	data = cube.filled_data[:]   # Pulls "cube"'s information (position, spectral info (?)) into a 3D Numpy array.
	data0 = data.value

	if (cube.shape[1] == rot.shape[0]) and (cube.shape[2] == rot.shape[1]):
	    # The spatial dimensions of the cube and its rotation map match. Reprojection is not necessary.
	    if filename_cube =='m33.co21_iram':       	# Checks if we're using the M33 data, which is in m/s for some reason.
		array = rot.data/1000.0          	# If so, converts M33's data from m/s to km/s.
	    else:
		array = rot.data
	else:
	    # The spatial dimensions of the cube and its rotation map DO NOT match. Reprojection is necessary,
	    # 	and the cube information must appear in a moment map for it to work.
	    moment0 = cube.moment(axis=0,order=0)
	    if os.path.isfile(filename_cube+'.mom0.fits') == False:
		moment0.write(filename_cube+'.mom0.fits')
	    else:
		print "WARNING: "+filename_cube+".mom0.fits' already exists. Please delete the file and try again."
	    array, footprint = reproject_interp(rot, moment0.header)
	    if filename_cube =='m33.co21_iram':
		array = array/1000.			# Converts M33's data from m/s to km/s.

#	(!!!)	INCOMPLETE	(!!!)
#	This "spec_peak" is not the central velocity of "array". But it should be.
	if filename_cube =='m33.co21_iram':                                 # Checks if we're dealing with M33 or M51.
	    spec_peak = cube.spectral_axis[data0.shape[0]/2].value / 1000.  # M33's data's velocity axis is NOT centered at
		                                                            #  zero. Will be accounted for later.
	else:
	    spec_peak = 0

#	(!!!)  PICK ONE. At the moment, 'spec_peak' is not the correct value to use.
#			Neither is np.mean(array), but it's much closer.	
#	array = array - spec_peak			# Creates a ROTATIONAL velocity map, centered at zero km/s.
	array = array - np.mean(array)			# Creates a ROTATIONAL velocity map, centered at zero km/s.

	velocityres = cube.header['CDELT3']
	velocityres = velocityres / 1000.		# This is the velocity resolution of the raw data file in km/s.

	# f(x) = magnitude of each entry in 3D cube, where "x" refers to the velocity we're receiving at. There's a different
	#	f(x) for each "position" on the cube.
	#
	# For each pixel on the *601x935* velocity distribution plot (which has its own *f(x)*):
	#  1. Find its *F(s)*, multiply it by *e<sup>$-i2\pi as$</sup>*, where "a" is the rotational velocity at that pixel.
	#	Note: The "s" refers to the corresponding frequencies to the Fourier Transform of f(x). This "s"
	#	should be a vector with the same length as *F(s)*, which in turn has the same length as f(x).
	#  2. Use that e<sup>$-i2\pi as$</sup> *F(s)* to find *f(x-a)*, and populate an empty matrix with the cube's dimensions with it. 
	#	When all *f(x-a)* values are found, the result SHOULD BE a 3D matrix like"cube", but corrected for rotational velocity.




	vmax,ymax,xmax = data0.shape

	cleancube = np.zeros(vmax*ymax*xmax).reshape(vmax,ymax,xmax)    # This is the final rotation-corrected cube that we'll use.

	if os.path.isfile(filename_cube+'_CLEANED.fits') == False:
		for i in range (0,xmax):
		    for j in range (0,ymax):
			fx = data0[:,j,i]      	# This is the f(x) mentioned above.
			fx_bad = np.array(np.isnan(fx), dtype=np.float)   	# This is an array of all the values in "fx" that are NaN.
			fx_temp = np.nan_to_num(fx)	# Copy of fx, but all NaN values are now zeroes.
		
			Fs = np.fft.fft(fx_temp)    	# This is the F(s) of f(x), including all the NaN values which were
				                    	#     (inaccurately) turned into zeroes.
			Fs_bad = np.fft.fft(fx_bad) 	# This is the F_bad(s) of fx_bad. Will be turned into F_bad(x-a) to deal with the
				                    	#     final result.
		
			s = np.fft.fftfreq(len(fx_temp)) 	# These are the frequencies corresponding to each F(s) value.
		
			shift = (array[j,i]) / velocityres
			phase = np.exp(2*np.pi*s*1j * shift) 	# This "j" is not to be confused with the parameter used in the For loop.
		
			fxa = np.fft.ifft(Fs*phase) 	# This is f(x-a). We just need to turn all those near-zero values back to NaN.
			fxa_bad = np.fft.ifft(Fs_bad*phase)
			fxa[fxa_bad>0.001]=np.nan
		
			cleancube[:,j,i] = fxa      	# Populates each "position" with the corrected velocity spectrum.

		hdu = fits.PrimaryHDU(cleancube,header=cube.header)
		hdulist = fits.HDUList([hdu])
		hdulist.writeto(filename_cube+'_CLEANED.fits')
	else:
		print "\n ERROR: "+filename_cube+"_CLEANED.fits' already exists. Please delete the file and try again."
示例#51
0
slices = (slice(330, 680), slice(250, 820))

ordering = ["HI", "CO(2-1)", r"H$\alpha$", "24 $\mu$m", "250 $\mu$m", "UV"]

for ii, key in enumerate(ordering):

    if key != "HI":
        # Why so many redundant axes!!
        if key == "CO(2-1)":
            arr = data[key].data.squeeze()
            mywcs = wcs.WCS(data[key].header).dropaxis(2)
            input_data = (arr, mywcs)
        else:
            input_data = data[key]
        # Regrid to the HERACLES data
        arr = reproject_interp(input_data, hi_wcs_corr,
                               shape_out=data["HI"].data.squeeze().shape)[0]
    else:
        arr = data[key].data.squeeze()

    y, x = np.unravel_index(ii, (Nrows, Ncols))
    # if key == r"H$\alpha$":
    #     vmin = 0
    #     vmax = 10
    # else:
    vmin = None
    vmax = None
    im = ax[y, x].imshow(np.arctan(arr[slices] / np.nanpercentile(arr[slices], 85)),
                         origin='lower', cmap=p.cm.gray_r,
                         vmin=vmin, vmax=vmax)

    ax[y, x].annotate(key, (0.7, 0.9),
vcube7m = cube7m.with_spectral_unit(u.km/u.s, velocity_convention='radio')
vcube12m = cube12m.with_spectral_unit(u.km/u.s, velocity_convention='radio')

bg7m = vcube7m.spectral_slab(-150*u.km/u.s, -5*u.km/u.s).median(axis=0)
bg12m = vcube12m.spectral_slab(-150*u.km/u.s, -5*u.km/u.s).median(axis=0)
bg7m12m = vcube7m12m.spectral_slab(-150*u.km/u.s, -5*u.km/u.s).median(axis=0)

ch_65kms_7m = vcube7m.closest_spectral_channel(65*u.km/u.s)
ch_65kms_12m = vcube12m.closest_spectral_channel(65*u.km/u.s)
ch_65kms_7m12m = vcube7m12m.closest_spectral_channel(65*u.km/u.s)

slc7m = cube7m[ch_65kms_7m] - bg7m
slc12m = cube12m[ch_65kms_12m] - bg12m
slc7m12m = vcube7m12m[ch_65kms_12m] - bg7m12m
slcTP = reproject_interp(fits.open(tp_fn), slc12m.header)[0]

pixscale7m = wcs.utils.proj_plane_pixel_area(cube7m.wcs.celestial)**0.5 * u.deg
pixscale12m = wcs.utils.proj_plane_pixel_area(cube12m.wcs.celestial)**0.5 * u.deg
pixscaleTP = pixscale12m
#old pixscaletp = wcs.utils.proj_plane_pixel_area(wcs.WCS(fits.getheader(tp_fn)))**0.5 * u.deg

convbeam_12mto7m = cube7m.beams[ch_65kms_7m].deconvolve(cube12m.beams[ch_65kms_12m])
kernel = convbeam_12mto7m.as_kernel(pixscale12m)
slc12m_conv_to_7m = convolve_fft(slc12m.value, kernel)

frq7m,pow7m = fft_psd_tools.psds.pspec(fft_psd_tools.psds.PSD2(slc7m.value*jtok_7m[ch_65kms_7m]), view=False)
frq12m,pow12m = fft_psd_tools.psds.pspec(fft_psd_tools.psds.PSD2(slc12m.value*jtok_12m[ch_65kms_12m]), view=False)
frq12m_conv,pow12m_conv = fft_psd_tools.psds.pspec(fft_psd_tools.psds.PSD2(slc12m_conv_to_7m*jtok_12m[ch_65kms_12m]), view=False)
frqTP,powTP = fft_psd_tools.psds.pspec(fft_psd_tools.psds.PSD2(slcTP), view=False)
frq7m12m,pow7m12m = fft_psd_tools.psds.pspec(fft_psd_tools.psds.PSD2(slc7m12m.value*jtok_7m12m[ch_65kms_7m12m]), view=False)
示例#53
0
文件: core.py 项目: Sondanaa/ccdproc
def wcs_project(ccd, target_wcs, target_shape=None, order='bilinear'):
    """
    Given a CCDData image with WCS, project it onto a target WCS and
    return the reprojected data as a new CCDData image.

    Any flags, weight, or uncertainty are ignored in doing the
    reprojection.

    Parameters
    ----------
    ccd : `~ccdproc.CCDData`
        Data to be projected.

    target_wcs : `~astropy.wcs.WCS` object
        WCS onto which all images should be projected.

    target_shape : two element list-like or None, optional
        Shape of the output image. If omitted, defaults to the shape of the
        input image.
        Default is ``None``.

    order : str, optional
        Interpolation order for re-projection. Must be one of:

        + 'nearest-neighbor'
        + 'bilinear'
        + 'biquadratic'
        + 'bicubic'

        Default is ``'bilinear'``.

    {log}

    Returns
    -------
    ccd : `~ccdproc.CCDData`
        A transformed CCDData object.
    """
    from reproject import reproject_interp

    if not (ccd.wcs.is_celestial and target_wcs.is_celestial):
        raise ValueError('one or both WCS is not celestial.')

    if target_shape is None:
        target_shape = ccd.shape

    projected_image_raw, _ = reproject_interp((ccd.data, ccd.wcs),
                                              target_wcs,
                                              shape_out=target_shape,
                                              order=order)

    reprojected_mask = None
    if ccd.mask is not None:
        reprojected_mask, _ = reproject_interp((ccd.mask, ccd.wcs),
                                               target_wcs,
                                               shape_out=target_shape,
                                               order=order)
        # Make the mask 1 if the reprojected mask pixel value is non-zero.
        # A small threshold is included to allow for some rounding in
        # reproject_interp.
        reprojected_mask = reprojected_mask > 1e-8

    # The reprojection will contain nan for any pixels for which the source
    # was outside the original image. Those should be masked also.
    output_mask = np.isnan(projected_image_raw)

    if reprojected_mask is not None:
        output_mask = output_mask | reprojected_mask

    # Need to scale counts by ratio of pixel areas
    area_ratio = (proj_plane_pixel_area(target_wcs) /
                  proj_plane_pixel_area(ccd.wcs))

    # If nothing ended up masked, don't create a mask.
    if not output_mask.any():
        output_mask = None

    nccd = CCDData(area_ratio * projected_image_raw, wcs=target_wcs,
                   mask=output_mask,
                   header=ccd.header, unit=ccd.unit)

    return nccd
示例#54
0
文件: repro.py 项目: BIDS/Kira
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import numpy as np
import sep
import sys
from astropy.io import fits
from astropy.wcs import WCS
import reproject
from reproject import reproject_interp

from pyspark import SparkContext

if __name__ == "__main__":
	sc = SparkContext(appName="Reproject")
	rdd = sc.fitsFiles("/Users/zhaozhang/projects/SDSS/data")
	header = rdd.take(1).pop().pop().header
	rprordd = rdd.map(lambda x: reproject_interp(x.pop(), header))
	nrdd = rprordd.zipWithIndex()
	nrdd.foreach(lambda ((array, footprint), index): fits.writeto(str(index)+".fits", array, header))	

	sc.stop()
示例#55
0
hi_beam = average_beams(hi_cube.beams)

# Estimate the noise level in an equivalent slab
hi_mom0 = hi_cube.spectral_slab(-180 * u.km / u.s, -183 * u.km / u.s).moment0()
sigma = sig_clip(hi_mom0.value, nsig=10) * \
    hi_beam.jtok(hi_freq).value

for i, (end, start) in enumerate(ProgressBar(zip(vels[1:], vels[:-1]))):

    hi_slab = hi_cube.spectral_slab(start, end)
    hi_mom0 = hi_slab.moment0() * hi_beam.jtok(hi_freq) / u.Jy

    # Make the CO slab, then reproject onto the HI grid
    co_mom0 = co_cube.spectral_slab(start, end).moment0()
    co_mom0_reproj = reproject_interp(co_mom0.hdu, hi_mom0.header)[0]
    co_mom0 = Projection(co_mom0_reproj, wcs=hi_mom0.wcs)

    # Need a mask from the HI
    # Adjust the sigma in a single channel to the moment0 in the slab
    # sigma = 0.00152659 * hi_slab.shape[0] * \
    #     np.abs((hi_slab.spectral_axis[1] - hi_slab.spectral_axis[0]).value)

    bub = BubbleFinder2D(hi_mom0, auto_cut=False, sigma=sigma)
    bub.create_mask(bkg_nsig=30, region_min_nsig=60, mask_clear_border=False)

    # skeleton = medial_axis(~bub.mask)
    # skeletons.append(skeleton)

    edge_mask = find_boundaries(bub.mask, connectivity=2, mode='outer')
    hole_mask = bub.mask.copy()
                   colors=['r']*11,
                   levels=[0.015, 0.0256944, 0.0577778, 0.11125, 0.186111,
                           0.282361, 0.4, ])

    F.add_scalebar((0.025*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
    F.scalebar.set_label('5000 au / 0.025 pc')
    F.scalebar.set_color('k')

    F.save(paths.fpath("chemistry/{0}_continuum_contours_on_ch3oh_temperature.png".format(source)))



    # compare CH3OH LTE column to dust emission
    ch3ohN_hdul = fits.open(paths.dpath('12m/moments/CH3OH_{0}_cutout_columnmap.fits'.format(source)))
    ch3ohT_hdul = fits.open(paths.dpath('12m/moments/CH3OH_{0}_cutout_temperaturemap.fits'.format(source)))
    dust_brightness,wts = reproject.reproject_interp(fits.open(paths.dpath('W51_te_continuum_best.fits')),
                                                     ch3ohN_hdul[0].header)

    w = wcs.WCS(ch3ohT_hdul[0].header)
    pixscale = (w.pixel_scale_matrix.diagonal()**2).sum()**0.5 * u.deg

    pl.figure(5).clf()
    ch3ohN = ch3ohN_hdul[0].data
    ch3ohT = ch3ohT_hdul[0].data
    pl.scatter(dust_brightness, ch3ohN, c=ch3ohT, vmax=600, vmin=50,
               edgecolor='none', alpha=0.9)
    pl.axis((1e-3, 0.2, 1e17, 1e19))
    pl.loglog()
    pl.xlabel("Dust Brightness (Jy/beam)")
    pl.ylabel("N(CH$_3$OH) [cm$^{-2}$]")
    cb = pl.colorbar()
    cb.set_label('CH$_3$OH-derived Temperature')
#hdu_todata.data = galfa_cube_data[0, :, :]

#new_header = fits.getheader(hdu_todata)#copy.copy(hdu_todata.header)


for thet_i in xrange(nthets):
    allsky_fn = path_to_rht_thetaslices + "GALFA_HI_allsky_-10_10_w75_s15_t70_thetabin_"+str(thet_i)+".fits"
    allsky_thetaslice_data = fits.getdata(allsky_fn)
    allsky_thetaslice_hdr = fits.getheader(allsky_fn)
    
    # try reprojecting allsky thetaslice first
    allsky_thetaslice_hdr_new = copy.copy(allsky_thetaslice_hdr)
    allsky_thetaslice_hdr_new['CTYPE1'] = 'RA      '
    allsky_thetaslice_hdr_new['CTYPE2'] = 'DEC     '
    
    output0, footprint0 = reproject_interp((allsky_thetaslice_data, allsky_thetaslice_hdr), allsky_thetaslice_hdr_new)
    
    print('theta_i', thet_i)
    
    # Reproject each theta slice into appropriate theta bin in cube
    output, footprint = reproject_interp((allsky_thetaslice_data, allsky_thetaslice_hdr), new_header)
    rht_data_cube[thet_i, :, :] = output

new_hdr = copy.copy(galfa_cube_hdr)    
new_hdr['NAXIS3'] = nthets
new_hdr['CTYPE3'] = 'THETARHT'
new_hdr['CRVAL3'] = 0.000000
new_hdr['CRPIX3'] = 0.000000
new_hdr['CDELT3'] = np.pi/nthets

out_fn = path_to_galfa_cubes + galfa_cube_name + "_RHT.fits"
示例#58
0
result = Observations.query_object('M83')
selected_bands = result[(result['obs_collection'] == 'HST') &
                        (result['instrument_name'] == 'WFC3/UVIS') &
                        ((result['filters'] == 'F657N') |
                         (result['filters'] == 'F487N') |
                         (result['filters'] == 'F336W')) &
                        (result['target_name'] == 'MESSIER-083')]
prodlist = Observations.get_product_list(selected_bands)
filtered_prodlist = Observations.filter_products(prodlist)

downloaded = Observations.download_products(filtered_prodlist)

blue = fits.open(downloaded['Local Path'][2])
red = fits.open(downloaded['Local Path'][5])
green = fits.open(downloaded['Local Path'][8])

target_header = red['SCI'].header
green_repr, _ = reproject.reproject_interp(green['SCI'], target_header)
blue_repr, _ = reproject.reproject_interp(blue['SCI'], target_header)


rgb_img = make_lupton_rgb(ImageNormalize(vmin=0, vmax=1)(red['SCI'].data),
                          ImageNormalize(vmin=0, vmax=0.3)(green_repr),
                          ImageNormalize(vmin=0, vmax=1)(blue_repr),
                          stretch=0.1,
                          minimum=0,
                         )

plt.imshow(rgb_img, origin='lower', interpolation='none')
示例#59
0
'''
Reproject the CO to match the HI.

Not taking the beam difference into account here since they are quite close.

Once this is merged https://github.com/astrofrog/reproject/pull/115/files,
make a full regrid of the whole cube.

'''

hi_header = fits.getheader(fourteenB_HI_data_path(moment0_name))

co_ico = fits.open(iram_co21_data_path("m33.ico.fits"))[0]

proj = Projection(co_ico.data.squeeze(),
                  wcs=WCS(co_ico.header).dropaxis(3).dropaxis(2))

rep_array, footprint = reproject_interp(proj.hdu, hi_header)

new_header = hi_header.copy()

# Need to change some of the properties before saving
keys = ["BMAJ", "BMIN", "BPA", "BUNIT"]
for key in keys:
    new_header[key] = co_ico.header[key]

new_hdu = fits.PrimaryHDU(rep_array, header=new_header)
new_hdu.writeto(iram_co21_data_path("m33.ico.hireprojection.fits",
                                    no_check=True), clobber=True)