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
def _reproject_wcs(self, geom, order=1, mode='interp'): from reproject import reproject_from_healpix from .wcsnd import WcsNDMap map_out = WcsNDMap(geom) coordsys = 'galactic' if geom.coordsys == 'GAL' else 'icrs' 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: raise NotImplementedError # TODO: Create WCS object for image plane if # multi-resolution geom shape_out = geom.get_image_shape(idx)[::-1] data, footprint = reproject_from_healpix((img, coordsys), geom.wcs, shape_out=shape_out) vals[...] = data return map_out
def _reproject_hpx( self, data, hdu_in=None, order="bilinear", nested=False, field=0, smooth=None ): if isinstance(data, np.ndarray): data = (data, self.header["RADESYS"]) # It's normal for reproject_from_healpix to produce some Numpy invalid # value warnings for points that land outside the projection. with np.errstate(invalid="ignore"): img, mask = reproject_from_healpix( data, self.header, hdu_in=hdu_in, order=order, nested=nested, field=field, ) img = np.ma.array(img, mask=~mask.astype(bool)) if smooth is not None: pixsize = np.mean(np.abs(self.wcs.wcs.cdelt)) * u.deg smooth = (smooth / pixsize).to(u.dimensionless_unscaled).value kernel = Gaussian2DKernel(smooth) # Ignore divide by zero warnings for pixels that have no valid # neighbors. with np.errstate(invalid="ignore"): img = convolve_fft(img, kernel, fill_value=np.nan) return img
def reproject(self, reference, **kwargs): """ Reproject healpix image to given reference. Parameters ---------- reference : `~astropy.io.fits.Header`, or `~gammapy.image.SkyImage` Reference image specification to reproject the data on. **kwargs : dict Keyword arguments passed to `~reproject.reproject_from_healpix`. Returns ------- image : `~gammapy.image.SkyImage` Image reprojected onto ``reference``. """ from reproject import reproject_from_healpix if isinstance(reference, SkyImage): wcs_reference = reference.wcs.deepcopy() 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`.") out = reproject_from_healpix((self.data, self.wcs.coordsys), wcs_reference, nested=self.wcs.nested, shape_out=shape_out) return SkyImage(name=self.name, data=out[0], wcs=wcs_reference)
def freproj_fromHEALPix(healpix_file,fits_file,output_file,coord="G",field=False,nested=False,write=True): ''' Reprojects a HEALPix image to a standard FITS projection. Input: healpix_file : directory to HEALPix file to be reprojected fits_file : directory to FITS file which the HEALPix image will be reprojected to output_file : directory to reprojected FITS file coord : coordinate system of input HEALPix image ("G" for Galactic or "C" for celestial) field : specifies healpix field [False or integer] nested : order of HEALPix data (True for nested or False for ring) write : if True, writes reprojected FITS file Output: healpix_data_reproj : reprojected HEALPix data footprint : reprojection footprint ''' if field==False: healpix_data = hp.read_map(healpix_file) else: healpix_data = hp.read_map(healpix_file,field=field) fits_data,fits_header = fits.getdata(fits_file,header=True) healpix_data_reproj,footprint = reproject_from_healpix((healpix_data,coord),fits_header,nested=nested) if write==True: fits.writeto(output_file,healpix_data_reproj,fits_header,overwrite=True) return healpix_data_reproj,footprint
def h2f(hmap, target_header, coord_in='C'): #project healpix -> flatsky pr, footprint = reproject.reproject_from_healpix((hmap, coord_in), target_header, shape_out=(500, 500), order='nearest-neighbor', nested=False) return pr
def fRotateHealpix_GC_reproject(healpix_filedir,I_field,Q_field,U_field,template_filedir,inepoch=2000.,outepoch=2000.,save=False,verbose=True): ''' Rotates a Healpix FITS file between Galactic and Celestial coordinate systems. Input healpix_filedir : path to Healpix file I_field : field of Stokes I data Q_field : field of Stokes Q data U_field : field of Stokes U data template_filedir : path to template file for reprojection inepoch : epoch of input data outepoch : epoch of output data ''' # first rotate healpix data from Galactic to Celestial coordinates if verbose==True: print("Rotating healpix data...") I_rotated_data,Q_rotated_data,U_rotated_data = fRotateHealpix_GC(healpix_filedir,I_field,Q_field,U_field,inepoch=inepoch,outepoch=outepoch) # reproject to new Celestial grid template_header = fits.getheader(template_filedir) if verbose==True: print("Reprojecting Stokes I data...") I_rotated_reproj_data,_ = reproject_from_healpix((I_rotated_data,"C"),template_header,nested=False) if verbose==True: print("Reprojecting Stokes Q data...") Q_rotated_reproj_data,_ = reproject_from_healpix((Q_rotated_data,"C"),template_header,nested=False) if verbose==True: print("Reprojecting Stokes U data...") U_rotated_reproj_data,_ = reproject_from_healpix((U_rotated_data,"C"),template_header,nested=False) if save==True: if verbose==True: print("Saving data...") I_rotated_reproj_filedir = healpix_filedir.split(".fits")[0]+"_I_rotated_GC_reproj.fits" Q_rotated_reproj_filedir = healpix_filedir.split(".fits")[0]+"_Q_rotated_GC_reproj.fits" U_rotated_reproj_filedir = healpix_filedir.split(".fits")[0]+"_U_rotated_GC_reproj.fits" fits.writeto(I_rotated_reproj_filedir,I_rotated_reproj_data,template_header,overwrite=True) fits.writeto(Q_rotated_reproj_filedir,Q_rotated_reproj_data,template_header,overwrite=True) fits.writeto(U_rotated_reproj_filedir,U_rotated_reproj_data,template_header,overwrite=True)
def image_reproject_from_healpix_to_file(source_image_hdu, target_image_hdu_header, filepath=None): """ reproject from healpix image to normal wcs image :param source_image_hdu: the HDU object of source image (healpix) :param target_image_hdu_header: the HDU object of target image (wcs) :param filepath: the output file path :return: array, footprint """ array, footprint = reproject_from_healpix(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
def freproject_HI4PI(HI4PI_input_file,FITS_file,HI4PI_output_file,VERBOSE=True): ''' Reprojects the HI4PI hdf5 file to a FITS file. Input HI4PI_input_file : directory to HI4PI file to be reprojected FITS_file : directory to FITS file which the HI4PI file will be reprojected to HI4PI_output_file : directory to save reprojected HI4PI file ''' # FITS header for reprjection FITS_data,FITS_header = fits.getdata(FITS_file,header=True) FITS_wcs = wcs.WCS(FITS_header) # read in HI4PI data for image size f = h5py.File(HI4PI_input_file,"r") HI4PI_data = f["survey"] #initialize reprojected data cube HI4PI_cube_reproj_data = np.ones(shape=(HI4PI_data.shape[1],FITS_data.shape[0],FITS_data.shape[1])) # read in hdf5 data with h5py.File(HI4PI_input_file,"r") as f: # iterate through each velocity channel for i in np.arange(HI4PI_data.shape[1]): if VERBOSE: print("Reading in slice {}".format(i)) # HEALPix image for ith velocity channe; vslice = f["survey"][:,i] # reproject from HEALPix to input FITS header if VERBOSE: print("Reprojecting slice {}".format(i)) healpix_data_reproj,footprint = reproject_from_healpix((vslice,"G"),FITS_wcs,shape_out=FITS_data.shape,hdu_in=1,nested=False) # update velocity channel in reprojected FITS cube HI4PI_cube_reproj_data[i]*=healpix_data_reproj # save intermediate FITS file in case kernel dies if i%10==0: if VERBOSE: print("Saving intermediate FITS file: {}".format(HI4PI_output_file)) fits.writeto(HI4PI_output_file,HI4PI_cube_reproj_data,overwrite=True) # save to FITS file if VERBOSE: print("Saving FITS file: {}".format(HI4PI_output_file)) fits.writeto(HI4PI_output_file,HI4PI_cube_reproj_data,overwrite=True)
def _reproject_to_wcs(self, geom, order=1, mode='interp'): from reproject import reproject_from_healpix data = np.empty(geom.data_shape) coordsys = 'galactic' if geom.coordsys == 'GAL' else 'icrs' 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] vals, footprint = reproject_from_healpix((img, coordsys), geom.wcs, shape_out=shape_out, nested=self.geom.nest, order=order) data[idx] = vals return self._init_copy(geom=geom, data=data)
def _fullsky_projection(self, wcs: WCS, shape: tuple, display_visible_sky: bool): """ """ values = copy.deepcopy(self.value) if display_visible_sky: values[~self.visible_sky] = np.nan if isinstance(values, da.Array): with ProgressBar() if log.getEffectiveLevel() <= logging.INFO else DummyCtMgr(): values = values.compute() with np.errstate(invalid='ignore'): # Ignore the invalid value in bilinear_interpolation (astropy-healpix) array, _ = reproject_from_healpix( (values, ICRS()), wcs, nested=False, shape_out=shape ) return array
def _reproject_to_wcs(self, geom, order=1, mode="interp"): from reproject import reproject_from_healpix data = np.empty(geom.data_shape) coordsys = "galactic" if geom.coordsys == "GAL" else "icrs" 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] vals, footprint = reproject_from_healpix( (img, coordsys), geom.wcs, shape_out=shape_out, nested=self.geom.nest, order=order, ) data[idx] = vals return self._init_copy(geom=geom, data=data)
def _reproject_hpx(self, data, hdu_in=None, order='bilinear', nested=False, field=0, smooth=None): if isinstance(data, np.ndarray): data = (data, self.header['RADESYS']) img, mask = reproject_from_healpix(data, self.header, hdu_in=hdu_in, order=order, nested=nested, field=field) img = np.ma.array(img, mask=~mask.astype(bool)) if smooth is not None: pixsize = np.mean(np.abs(self.wcs.wcs.cdelt)) * u.deg smooth = (smooth / pixsize).to(u.dimensionless_unscaled).value img = gaussian_filter(img, smooth) return img
def h2f(hmap, target_header, coord_in='C'): """ Returns a target square submap from a projected HEALPIX map, given a WCS header, using :py:mod:`reproject` package **Parameters** - ``hmap`` : {array} healpix map - ``target_header``: header defined from :func:`set_header` """ pr, footprint = reproject.reproject_from_healpix((hmap, coord_in), target_header, shape_out=(500, 500), order='nearest-neighbor', nested=False) return pr
def main(outf: str, inf: str, outf1: str, ext: int, field: int, coordsys: str) -> None: """Main script. Args: outf (str): Healpix file inf (str): Target file outf1 (str): Output file ext (int): Healpix extension field (int): Column from healpix file. coordsys (str): Coordsys to use. """ # Read in the HEALPIX file print("Reading files...") # Read in HEALPIX file hdu2 = fits.open(outf)[int(ext)] # Read in target fits file hdu1 = fits.open(inf)[0] print("Generating header...") target_wcs = WCS(hdu1) target_header = target_wcs.celestial.to_header() hdu2.header["COORDSYS"] = coordsys # Regrid print("Regridding...") array, footprint = reproject_from_healpix( hdu2, target_header, field=int(field), shape_out=target_wcs.celestial.array_shape) # Save the file! print("Saving output to " + outf1) hdu = fits.PrimaryHDU(array, header=target_header) hdul = fits.HDUList([hdu]) hdul.writeto(outf1, overwrite=True)
CRVAL1 = CDELT1 = CTYPE2 = CRPIX2 = CRVAL2 = CDELT2 = """, sep='\n') # Copy target information for i in target_header: target_header[i] = hdu1.header[i] # Force the axes to be 2D target_header['NAXIS'] = 2 hdu2.header['COORDSYS'] = args.COORDSYS # Regrid print 'Regridding...' array, footprint = reproject_from_healpix(hdu2, target_header, field=int(args.field)) # Save the file! outf1 = args.out[0] print 'Saving output to ' + outf1 hdu = fits.PrimaryHDU(array, header=target_header) hdul = fits.HDUList([hdu]) hdul.writeto(outf1, overwrite=True)
def plot(self, **kwargs): r""" Display the selected content of the :attr:`~nenupy.astro.sky.Sky.value` attribute belonging to a :class:`~nenupy.astro.sky.Sky` instance as a celestial map in equatorial coordinates. This method is available on a :class:`~nenupy.astro.sky.SkySlice` instance, resulting from a selection upon a :class:`~nenupy.astro.sky.Sky` instance (using the indexing operator). Several parameters, listed below, can be tuned to adapt the plot to the user requirements: .. rubric:: Data display keywords :param center: Coordinates of the celestial map to be displayed at the center of the image. Default is ``(RA=0deg, Dec=0deg)``. :type center: :class:`~astropy.coordinates.SkyCoord` :param radius: Angular radius from the center of the image above which the plot should be cropped. Default is ``None`` (i.e., full sky image). :type radius: :class:`~astropy.units.Quantity` :param resolution: Set the pixel resolution. The upper threshold is 0.775 deg, any value above that does not affect the figure appearence. Default is ``astropy.units.Quantity(1, unit="deg")``. :type resolution: :class:`~astropy.units.Quantity` :param only_visible: If set to ``True`` only the sky above the horizon is displayed. Setting this parameter to ``False`` does not really make sense for :class:`~nenupy.astro.sky.Sky` instances representing antenna response for instance. Default is ``True``. :type only_visible: `bool` :param decibel: If set to ``True``, the data values are displayed at the decibel scale, i.e., :math:`10 \log( \rm{data} )`. Default is ``False``. :type decibel: `bool` .. rubric:: Overplot keywords :param scatter: Add a scatter plot (as defined in `matplotlib.pyplot.scatter`). Expected syntax is ``(<SkyCoord>, <marker_size>, <color>)``. Default is ``None`` (i.e., no scatter overplot). :type scatter: `tuple` :param text: Add a text overlay (as defined in `matplotlib.pyplot.text`). Expected syntax is ``(<SkyCoord>, <[text]>, <color>)``. Default is ``None`` (i.e., no text overplot). :type text: `tuple` :param contour: Add a contour plot (as defined in `matplotlib.pyplot.contour`). Expected syntax is ``(<numpy.ndarray>, <[levels]>, <colormap>)``. Default is ``None`` (i.e., no contour overplot). :type contour: `tuple` .. rubric:: Plotting layout keywords :param altaz_overlay: If set to ``True``, the horizontal coordinates grid is overplotted in addition to the equatorial one. Default is ``False``. :type altaz_overlay: `bool` :param cmap: Color map applied while representing the data (see `Matplotlib colormaps <https://matplotlib.org/stable/gallery/color/colormap_reference.html>`_). Default is ``"YlGnBu_r"``. :type cmap: `str` :param show_colorbar: Show or not the color bar. Default is ``True``. :type show_colorbar: `bool` :param colorbar_label: Set the label of the color bar. Default is ``""``. :type colorbar_label: `str` :param figname: Name of the file (absolute or relative path) to save the figure. If set to ``"return"``, the method returns the `tuple` ``(fig, ax)`` (as defined by `matplotlib <https://matplotlib.org/>`_). Default is ``None`` (i.e., only show the figure). :type figname: `str` :param figsize: Set the figure size. Default is ``(15, 10)``. :type figsize: `tuple` :param ticks_color: Set the color of the equatorial grid and the Right Ascension ticks. Default is ``"0.9"`` (grey). :type ticks_color: `str` :param title: Set the figure title. Default is ``"<time>, <frequency>"``. :type title: `str` """ # Parsing the keyword arguments resolution = kwargs.get("resolution", 1*u.deg) figname = kwargs.get("figname", None) cmap = kwargs.get("cmap", "YlGnBu_r") figsize = kwargs.get("figsize", (15, 10)) center = kwargs.get("center", SkyCoord(0*u.deg, 0*u.deg)) radius = kwargs.get("radius", None) ticks_color = kwargs.get("ticks_color", "0.9") colorbar_label = kwargs.get("colorbar_label", "") title = kwargs.get("title", f"{self.time.isot.split('.')[0]}, {self.frequency:.2f}") visible_sky = kwargs.get("only_visible", True) decibel = kwargs.get("decibel", False) altaz_overlay = kwargs.get("altaz_overlay", False) # Initialize figure wcs, shape = self._compute_wcs( center=center, resolution=getattr(self, "resolution", resolution), radius=radius ) fig = plt.figure(figsize=figsize) ax = plt.subplot( projection=wcs, frame_class=EllipticalFrame ) # Get the data projected on fullsky data = self._fullsky_projection( wcs=wcs, shape=shape, display_visible_sky=visible_sky ) # Scale the data in decibel if decibel: data = 10 * np.log10(data) vmin = kwargs.get("vmin", np.nanmin(data)) vmax = kwargs.get("vmax", np.nanmax(data)) # Plot the data im = ax.imshow( data, origin="lower", interpolation="quadric", cmap=cmap, vmin=vmin, vmax=vmax ) # Define ax ticks ax.coords.grid(color=ticks_color, alpha=0.5) path_effects=[patheffects.withStroke(linewidth=3, foreground='black')] ra_axis = ax.coords[0] dec_axis = ax.coords[1] ra_axis.set_ticks_visible(False) ra_axis.set_ticklabel_visible(True) ra_axis.set_ticklabel(color=ticks_color, exclude_overlapping=True, path_effects=path_effects) ra_axis.set_axislabel("RA", color=ticks_color, path_effects=path_effects) ra_axis.set_major_formatter("d") ra_axis.set_ticks(number=12) dec_axis.set_ticks_visible(False) dec_axis.set_ticklabel_visible(True) dec_axis.set_axislabel("Dec", minpad=2) dec_axis.set_major_formatter("d") dec_axis.set_ticks(number=10) if altaz_overlay: frame = AltAz(obstime=self.time, location=self.observer) overlay = ax.get_coords_overlay(frame) overlay.grid(color="tab:orange", alpha=0.5) az_axis = overlay[0] alt_axis = overlay[1] az_axis.set_axislabel("Azimuth", color=ticks_color, path_effects=path_effects) az_axis.set_ticks_visible(False) az_axis.set_ticklabel_visible(True) az_axis.set_ticklabel(color=ticks_color, path_effects=path_effects) az_axis.set_major_formatter("d") az_axis.set_ticks(number=12) alt_axis.set_axislabel("Elevation") alt_axis.set_ticks_visible(False) alt_axis.set_ticklabel_visible(True) alt_axis.set_major_formatter("d") alt_axis.set_ticks(number=10) # Add NSEW points nesw_labels = np.array(["N", "E", "S", "W"]) nesw = SkyCoord( np.array([0, 90, 180, 270]), np.array([0, 0, 0, 0]), unit="deg", frame=frame ).transform_to(ICRS) for label, coord in zip(nesw_labels, nesw): ax.text( x=coord.ra.deg, y=coord.dec.deg, s=label, color="tab:orange", transform=ax.get_transform("world"), path_effects=path_effects, verticalalignment="center", horizontalalignment="center", clip_on=True ) # Colorbar if kwargs.get("show_colorbar", True): cax = inset_axes( ax, width='3%', height='100%', loc='lower left', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0, ) cb = ColorbarBase( cax, cmap=get_cmap(name=cmap), orientation='vertical', norm=Normalize( vmin=vmin, vmax=vmax ), ticks=LinearLocator() ) cb.solids.set_edgecolor("face") cb.set_label(colorbar_label) cb.formatter.set_powerlimits((0, 0)) # Overplot # if kwargs.get("circle", None) is not None: # from matplotlib.patches import Circle # frame = AltAz(obstime=self.time, location=self.observer) # c = Circle( # (0, 75), # 20, # edgecolor='yellow', # linewidth=5, # facecolor='none', # #transform=ax.get_transform('world') # #transform=ax.get_transform('fk5') # transform=ax.get_transform(frame) # ) # ax.add_patch(c) if kwargs.get("moc", None) is not None: # In order fo that to work; I had to comment #axis_viewport.set(ax, wcs) # from add_patches_to_mpl_axe() in mocpy/moc/plot/fill.py # OR re-set the limits (done here) try: frame = AltAz(obstime=self.time, location=self.observer) xlimits = ax.get_xlim() ylimits = ax.get_ylim() mocs = kwargs["moc"] if isinstance(kwargs["moc"], list) else [kwargs["moc"]] for moc, color in zip(mocs, ["tab:red", "tab:green"]): moc.fill( ax=ax, wcs=wcs, alpha=0.5, fill=True, color=color, linewidth=0, ) ax.set_xlim(xlimits) ax.set_ylim(ylimits) except AttributeError: log.warning("A 'MOC' object, generated from mocpy is expected.") raise if kwargs.get("altaz_moc", None) is not None: xlimits = ax.get_xlim() ylimits = ax.get_ylim() altaz = self.horizontal_coordinates mask = kwargs["altaz_moc"].contains(altaz.az, altaz.alt) ax.scatter( x=self.coordinates[mask].ra.deg, y=self.coordinates[mask].dec.deg, s=0.1,#[marker_size]*coords.size, facecolor="red", edgecolor=None, alpha=0.5, transform=ax.get_transform("world") ) ax.set_xlim(xlimits) ax.set_ylim(ylimits) if kwargs.get("scatter", None) is not None: parameters = kwargs["scatter"] if len(parameters) != 3: raise ValueError( "'scatter' syntax should be: (<SkyCoord>, <size>, <color>)" ) coords = parameters[0] if coords.isscalar: coords = coords.reshape((1,)) marker_size = parameters[1] marker_color = parameters[2] ax.scatter( x=coords.ra.deg, y=coords.dec.deg, s=[marker_size]*coords.size, color=marker_color, transform=ax.get_transform("world") ) if kwargs.get("text", None) is not None: parameters = kwargs["text"] if len(parameters) != 3: raise ValueError( "'text' syntax should be: (<SkyCoord>, <[text]>, <color>)" ) coords = parameters[0] if coords.isscalar: coords = coords.reshape((1,)) text = parameters[1] text_color = parameters[2] for i in range(coords.size): ax.text( x=coords[i].ra.deg, y=coords[i].dec.deg, s=text[i], color=text_color, transform=ax.get_transform("world"), clip_on=True ) if kwargs.get("contour", None) is not None: parameters = kwargs["contour"] data = parameters[0] if len(parameters) != 3: raise ValueError( "'contour' syntax should be: (<numpy.ndarray>, <[levels]>, <colormap>)" ) contour, _ = reproject_from_healpix( (data, ICRS()), wcs, nested=False, shape_out=shape#(ndec, nra) ) ax.contour( contour, levels=parameters[1], cmap=parameters[2], ) # Other im.set_clip_path(ax.coords.frame.patch) ax.set_title(title, pad=20) # Save or show if figname is None: plt.show() elif figname.lower() == "return": return fig, ax else: fig.savefig( figname, dpi=300, transparent=True, bbox_inches='tight' ) plt.close('all')
NAXIS1 = 1000 NAXIS2 = 800 CTYPE1 = 'RA---MOL' CRPIX1 = 500 CRVAL1 = 180.0 CDELT1 = -0.4 CUNIT1 = 'deg ' CTYPE2 = 'DEC--MOL' CRPIX2 = 400 CRVAL2 = 0.0 CDELT2 = 0.4 CUNIT2 = 'deg ' COORDSYS= 'icrs ' """, sep='\n') array, footprint = reproject_from_healpix(filename_ligo, target_header) from astropy.wcs import WCS import matplotlib.pyplot as plt ax = plt.subplot(1, 1, 1, projection=WCS(target_header)) #ax.imshow(array, vmin=0, vmax=1.e-8) #ax.coords.grid(color='white') ax.coords.frame.set_color('none') import numpy as np np.random.seed(19680801) x = 30 * np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std()
#Or open wcs from FITS file (HI for exemple) path = "/data/amarchal/EN/" fitsname = "data/GHIGLS_N1_Tb.fits" hdu = fits.open(path+fitsname) hdr = hdu[0].header cube = hdu[0].data[0] size=(cube.shape[1],cube.shape[2]) target_wcs = tb.proj.wcs2D(hdr) target_hdr = target_wcs.to_header() freq = np.array([np.full((size[0],size[1]),i) for i in np.array([353,545,857,3000])])*u.GHz wavelength = (const.c / freq).to(u.micron) #Projection proj_353, foo = reproject_from_healpix((pl_353_smoothed,'g'), target_hdr, shape_out=size, nested=False) proj_545, foo = reproject_from_healpix((pl_545_smoothed,'g'), target_hdr, shape_out=size, nested=False) proj_857, foo = reproject_from_healpix((pl_857_smoothed,'g'), target_hdr, shape_out=size, nested=False) proj_3000, foo = reproject_from_healpix((iris_3000_smoothed,'g'), target_hdr, shape_out=size, nested=False) cube = np.array([proj_353,proj_545,proj_857,proj_3000]) * u.MJy / (2. * const.h * freq**3. / const.c**2) cube = cube.decompose() #Write FITS file # pathout = "/data/amarchal/PLANCK_IRIS-SFD_adim/" pathout = "/data/amarchal/GNILC_IRIS-SFD_adim/" hdu = fits.PrimaryHDU(cube.value) hdu.header["CRPIX1"] = target_hdr["CRPIX1"] hdu.header["CRVAL1"] = target_hdr["CRVAL1"] hdu.header["CDELT1"] = target_hdr["CDELT1"]
CTYPE1='RA---AIT', CTYPE2='DEC--AIT', RADESYS='ICRS')) wcs = WCS(header) fig = pl.figure(figsize=[8,6]) ax = pl.axes(projection=wcs, frame_class=RectangularFrame, aspect=1) world_transform = ax.get_transform('world') ax.set_xlim((180 - args.size) * deg_per_pix, (180 + args.size) * deg_per_pix) ax.set_ylim((90 - args.size) * deg_per_pix, (90 + args.size) * deg_per_pix) cls = postprocess.find_greedy_credible_levels(optprob) cls, _ = reproject_from_healpix((cls, 'icrs'), header) cs = ax.contour(cls, levels=[0.5, 0.9], colors='C0') ax.plot([],[], '-', color='C0', label='Exact masses') ## Work on the suboptimal skymap prob, _ = read_sky_map(args.fits_file, nest=False, distances=False) nside = hp.npix2nside(len(prob)) deg2perpix = hp.nside2pixarea(nside, degrees=True) radec = [float(x) for x in args.radec] deg_per_pix = 4 header = Header(dict( NAXIS=2,
type=float, required=True) parser.add_argument('--dec', help='Dec. of center of map', type=float, required=True) args = parser.parse_args() target_header = fits.Header.fromstring(""" NAXIS = 2 NAXIS1 = 1000 NAXIS2 = 800 CTYPE1 = 'RA---AIT' CRPIX1 = 500 CRVAL1 = %s CDELT1 = -0.4 CUNIT1 = 'deg ' CTYPE2 = 'DEC--AIT' CRPIX2 = 400 CRVAL2 = %s CDELT2 = 0.4 CUNIT2 = 'deg ' COORDSYS= 'icrs ' """ % (args.ra, args.dec), sep='\n') array, footprint = reproject_from_healpix(args.in_map, target_header) fits.writeto(args.out_map, array, header=target_header)
def plot(self, figname=None, db=True, **kwargs): """ Plot the HEALPix :attr:`~nenupy.astro.hpxsky.HpxSky.skymap` on an equatorial grid with a Elliptical frame. :param figname: Figure name, if ``None`` (default value), the figure is not saved. :type figname: `str` :param db: Sacle the data in decibel units. Default is ``True``. :type db: `bool` :param cmap: Name of the colormap. Default is ``'YlGnBu_r'``. :type cmap: `str` :param vmin: Minimum value to scale the figure. Default is min(:attr:`~nenupy.astro.hpxsky.HpxSky.skymap`). :type vmin: `float` :param vmax: Maximum value to scale the figure. Default is max(:attr:`~nenupy.astro.hpxsky.HpxSky.skymap`). :type vmax: `float` :param tickscol: Color of the RA ticks. Default is ``'black'``. :type tickscol: `str` :param title: Title of the plot. Default is ``None``. :type title: `str` :param cblabel: Colorbar label. Default is ``'Amp'`` if ``db=False`` of ``'dB'`` if ``db=True``. :type cblabel: `str` :param grid: Show the equatorial grid. :type grid: `bool` :param cbar: Plot a colorbar. :type cbar: `bool` :param center: Center of the plot. Default is ``SkyCoord(0.*u.deg, 0.*u.deg)``. :type center: :class:`~astropy.coordinates.SkyCoord` :param size: Diameter of the cutout. Default is whole sky. :type size: `float` or :class:`~astropy.units.Quantity` :param figsize: Figure size in inches. Default is ``(15, 10)``. :type figsize: `tuple` :param indices: Default is ``None``. If not, a scatter plot is made on the desired HEALPix indices: ``(indices, size, color)``. :type indices: `tuple` :param scatter: Default is ``None``. If not, a scatter plot is made on the desired equatorial coordinates: ``(ra (deg), dec (deg), size, color)``. :type scatter: `tuple` :param text: Default is ``None``. If not, text is overplotted on the desired equatorial coordinates: ``(ra (deg), dec (deg), text, color)``. :type text: `tuple` :param curve: Default is ``None``. If not, a curve plot is made on the desired equatorial coordinates: ``(ra (deg), dec (deg), linestyle, color)``. :type curve: `tuple` """ # Lot of imports for this one... from reproject import reproject_from_healpix from astropy.coordinates import ICRS from astropy.visualization.wcsaxes.frame import EllipticalFrame import matplotlib.pyplot as plt from matplotlib.colorbar import ColorbarBase from matplotlib.ticker import LinearLocator from matplotlib.colors import Normalize from matplotlib.cm import get_cmap from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Cutout? raauto = True if 'center' not in kwargs.keys(): kwargs['center'] = SkyCoord(0. * u.deg, 0. * u.deg) if not isinstance(kwargs['center'], SkyCoord): raise TypeError('center must be a SkyCoord object.') # Preparing WCS projection dangle = 0.675 scale = int(dangle / self.resolution.deg) scale = 1 if scale <= 1 else scale nra = 480 * scale ndec = 240 * scale if 'size' in kwargs.keys(): if isinstance(kwargs['size'], u.Quantity): kwargs['size'] = kwargs['size'].to(u.deg).value resol = dangle / scale nra = int(kwargs['size'] / resol) ndec = nra raauto = False wcs = WCS(naxis=2) wcs.wcs.crpix = [nra / 2 + 0.5, ndec / 2 + 0.5] wcs.wcs.cdelt = np.array([-dangle / scale, dangle / scale]) wcs.wcs.crval = [kwargs['center'].ra.deg, kwargs['center'].dec.deg] wcs.wcs.ctype = ['RA---AIT', 'DEC--AIT'] # Make an array out of HEALPix representation skymap = self.skymap.copy() if self.visible_sky: skymap[~self._is_visible] = np.nan array, fp = reproject_from_healpix((skymap, ICRS()), wcs, nested=False, shape_out=(ndec, nra)) # Decibel or linear? if db: data = 10 * np.log10(array) cblabel = 'dB' else: data = array cblabel = 'Amp' mask = ~np.isnan(data) * ~np.isinf(data) # Make sure everything is correctly set up if 'cmap' not in kwargs.keys(): kwargs['cmap'] = 'YlGnBu_r' if 'vmin' not in kwargs.keys(): kwargs['vmin'] = np.min(data[mask]) elif kwargs['vmin'] is None: kwargs['vmin'] = np.min(data[mask]) else: pass if 'vmax' not in kwargs.keys(): kwargs['vmax'] = np.max(data[mask]) elif kwargs['vmax'] is None: kwargs['vmax'] = np.max(data[mask]) else: pass if 'tickscol' not in kwargs.keys(): kwargs['tickscol'] = 'black' if 'title' not in kwargs.keys(): kwargs['title'] = None if 'cblabel' not in kwargs.keys(): kwargs['cblabel'] = cblabel if 'grid' not in kwargs.keys(): kwargs['grid'] = True if 'cbar' not in kwargs.keys(): kwargs['cbar'] = True if 'figsize' not in kwargs.keys(): kwargs['figsize'] = (15, 10) if 'indices' not in kwargs.keys(): kwargs['indices'] = None if 'scatter' not in kwargs.keys(): kwargs['scatter'] = None if 'curve' not in kwargs.keys(): kwargs['curve'] = None if 'text' not in kwargs.keys(): kwargs['text'] = None # Initialize figure fig = plt.figure(figsize=kwargs['figsize']) ax = plt.subplot(projection=wcs, frame_class=EllipticalFrame) # Full sky im = ax.imshow(data, origin='lower', interpolation='none', cmap=kwargs['cmap'], vmin=kwargs['vmin'], vmax=kwargs['vmax']) axra = ax.coords[0] axdec = ax.coords[1] if kwargs['grid']: ax.coords.grid(color=kwargs['tickscol'], alpha=0.5) axra.set_ticks_visible(False) axra.set_ticklabel(color=kwargs['tickscol']) axra.set_axislabel('RA', color=kwargs['tickscol']) axra.set_major_formatter('d') if raauto: axra.set_ticks([0, 45, 90, 135, 225, 270, 315] * u.degree) else: axra.set_ticks(number=10) axdec.set_ticks_visible(False) axdec.set_axislabel('Dec') axdec.set_major_formatter('d') axdec.set_ticks(number=10) else: axra.set_ticks_visible(False) axdec.set_ticks_visible(False) axra.set_ticklabel_visible(False) axdec.set_ticklabel_visible(False) # Overplot if kwargs['indices'] is not None: ax.scatter(x=self.eq_coords[kwargs['indices'][0]].ra.deg, y=self.eq_coords[kwargs['indices'][0]].dec.deg, s=[kwargs['indices'][1]] * len(kwargs['indices'][0]), color=kwargs['indices'][2], transform=ax.get_transform('world')) if kwargs['scatter'] is not None: ax.scatter(x=kwargs['scatter'][0], y=kwargs['scatter'][1], s=[kwargs['scatter'][2]] * len(kwargs['scatter'][0]), color=kwargs['scatter'][3], transform=ax.get_transform('world')) if kwargs['curve'] is not None: ax.plot(kwargs['curve'][0], kwargs['curve'][1], linestyle=kwargs['curve'][2], color=kwargs['curve'][3], transform=ax.get_transform('world')) if kwargs['text'] is not None: for i in range(len(kwargs['text'][0])): ax.text(x=kwargs['text'][0][i], y=kwargs['text'][1][i], s=kwargs['text'][2][i], color=kwargs['text'][3], transform=ax.get_transform('world')) im.set_clip_path(ax.coords.frame.patch) ax.set_title(kwargs['title'], pad=25) # Colorbar if kwargs['cbar']: cax = inset_axes( ax, width='3%', height='100%', loc='lower left', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0, ) cb = ColorbarBase(cax, cmap=get_cmap(name=kwargs['cmap']), orientation='vertical', norm=Normalize(vmin=kwargs['vmin'], vmax=kwargs['vmax']), ticks=LinearLocator()) cb.solids.set_edgecolor('face') cb.set_label(kwargs['cblabel']) cb.formatter.set_powerlimits((0, 0)) # Save or show if figname is None: plt.show() elif figname.lower() == 'return': return fig, ax else: fig.savefig(figname, dpi=300, transparent=True, bbox_inches='tight') plt.close('all') return