Ejemplo n.º 1
0
def draw_filter(
    fig,
    weights,
    extent,
    cmap,
    sub=None,
    order=1,
    vmin=None,
    vmax=None,
    xsize=600,
    ysize=600,
    show_values=False,
    val2str=val2str,
):
    """Return a 2D image of a filter.

    Args:
        * weights (array): Array of filter weights
        * order (int): Order of the filter (1st, 2nd neighbours). So
          far only ``order=1`` works.

    Returns:
        An array containing the 2-D grayscale image of the input filter.
    """

    order_fn = {1: nnh.pixel_1st_neighbours, 2: nnh.pixel_2nd_neighbours}
    assert (order in order_fn.keys(
    )), "invalid order ({0}) passed to filter, valid values are {1}".format(
        order, ", ".join([str(x) for x in order_fn.keys()]))
    fn = order_fn[order]
    nside = 16
    ipix = hp.ang2pix(nside, np.pi / 2, 0)
    pix_num = fn(ipix, nside)
    m = np.zeros(hp.nside2npix(nside)) + np.inf
    m[pix_num] = weights

    ax = pa.HpxGnomonicAxes(fig, extent, rot=[0, 2])
    fig.add_axes(ax)

    ax.projmap(m,
               reso=1.8,
               vmin=vmin,
               vmax=vmax,
               xsize=xsize,
               ysize=ysize,
               cmap=cmap)

    if show_values:
        for i, curpix in enumerate(pix_num):
            theta, phi = hp.pix2ang(nside, curpix)
            ax.projtext(
                theta,
                phi,
                val2str(weights[i]),
                horizontalalignment="center",
                verticalalignment="center",
                color="black",
                bbox=dict(facecolor="white", linewidth=0, alpha=0.7),
            )

    return ax
Ejemplo n.º 2
0
def cutout_gnomonic(map,
                    rot=None,
                    coord=None,
                    xsize=200,
                    ysize=None,
                    reso=1.5,
                    nest=False,
                    remove_dip=False,
                    remove_mono=False,
                    gal_cut=0,
                    flip='astro'):
    """Obtain a cutout from a healpix map (given as an array) in Gnomonic projection.

    Parameters
    ----------
    map : array-like
      The map to project, supports masked maps, see the `ma` function.
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    xsize : int, optional
      The size of the image. Default: 200
    ysize : None or int, optional
      The size of the image. Default: None= xsize
    reso : float, optional
      Resolution (in arcmin). Default: 1.5 arcmin
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    

    See Also
    --------
    gnomview, mollview, cartview, orthview, azeqview
    """
    import pylab
    import healpy as hp
    import healpy.projaxes as PA

    margins = (0.075, 0.05, 0.075, 0.05)
    extent = (0.0, 0.0, 1.0, 1.0)
    extent = (extent[0] + margins[0], extent[1] + margins[1],
              extent[2] - margins[2] - margins[0],
              extent[3] - margins[3] - margins[1])
    f = pylab.figure(0, figsize=(5.5, 6))
    map = hp.pixelfunc.ma_to_array(map)
    ax = PA.HpxGnomonicAxes(f,
                            extent,
                            coord=coord,
                            rot=rot,
                            format="%.3g",
                            flipconv=flip)
    if remove_dip:
        map = hp.pixelfunc.remove_dipole(map,
                                         gal_cut=gal_cut,
                                         nest=nest,
                                         copy=True)
    elif remove_mono:
        map = hp.pixelfunc.remove_monopole(map,
                                           gal_cut=gal_cut,
                                           nest=nest,
                                           copy=True)
    img = ax.projmap(map,
                     nest=nest,
                     coord=coord,
                     xsize=xsize,
                     ysize=ysize,
                     reso=reso)

    pylab.close(f)
    return img
Ejemplo n.º 3
0
def get_gnomonic_projection(figure, hpx_map, **kwargs):
    """
    Returns an array containing the Gnomonic projection of the provided Healpix map.

    This is equivalent to hp.gnomview of Healpy BUT the projected array is NOT plotted in the figure, so you can
    plot it later on.

    :param figure: a matplotlib Figure
    :param hpx_map: the healpix map
    :param **kwargs: keywords accepted by hp.gnomview
    :return: the array containing the projection.
    """

    defaults = {
        'coord': 'C',
        'rot': None,
        'format': '%g',
        'flip': 'astro',
        'xsize': 200,
        'ysize': None,
        'reso': 1.5,
        'nest': False,
        'min': None,
        'max': None,
        'cmap': None,
        'norm': None
    }

    for key, default_value in list(defaults.items()):

        if key not in kwargs:

            kwargs[key] = default_value

    ## Colas, 2018-07-11: The following fails for really tall figures,
    ## as happens with 2D binning. Top ends up negative, probably matplotlib bug.
    ## So hard code extent instead. Keep the code for now if we want to fix it.
    # left, bottom, right, top = np.array(plt.gca().get_position()).ravel()
    # extent = (left, bottom, right - left, top - bottom)
    # margins = (0.01, 0.0, 0.0, 0.02)
    # extent = (extent[0] + margins[0],
    #           extent[1] + margins[1],
    #           extent[2] - margins[2] - margins[0],
    #           extent[3] - margins[3] - margins[1])
    extent = (0.05, 0.05, 0.9, 0.9)

    ax = PA.HpxGnomonicAxes(figure,
                            extent,
                            coord=kwargs['coord'],
                            rot=kwargs['rot'],
                            format=kwargs['format'],
                            flipconv=kwargs['flip'])

    # Suppress warnings about nans
    with np.warnings.catch_warnings():

        np.warnings.filterwarnings('ignore')

        img = ax.projmap(hpx_map,
                         nest=kwargs['nest'],
                         coord=kwargs['coord'],
                         vmin=kwargs['min'],
                         vmax=kwargs['max'],
                         xsize=kwargs['xsize'],
                         ysize=kwargs['ysize'],
                         reso=kwargs['reso'],
                         cmap=kwargs['cmap'],
                         norm=kwargs['norm'])

    return img
Ejemplo n.º 4
0
def get_gnomonic_projection(figure, hpx_map, **kwargs):
    """
    Returns an array containing the Gnomonic projection of the provided Healpix map.

    This is equivalent to hp.gnomview of Healpy BUT the projected array is NOT plotted in the figure, so you can
    plot it later on.

    :param figure: a matplotlib Figure
    :param hpx_map: the healpix map
    :param **kwargs: keywords accepted by hp.gnomview
    :return: the array containing the projection.
    """

    defaults = {
        'coord': 'C',
        'rot': None,
        'format': '%g',
        'flip': 'astro',
        'xsize': 200,
        'ysize': None,
        'reso': 1.5,
        'nest': False,
        'min': None,
        'max': None,
        'cmap': None,
        'norm': None
    }

    for key, default_value in defaults.items():

        if key not in kwargs:

            kwargs[key] = default_value

    left, bottom, right, top = np.array(plt.gca().get_position()).ravel()

    extent = (left, bottom, right - left, top - bottom)
    margins = (0.01, 0.0, 0.0, 0.02)
    extent = (extent[0] + margins[0], extent[1] + margins[1],
              extent[2] - margins[2] - margins[0],
              extent[3] - margins[3] - margins[1])

    ax = PA.HpxGnomonicAxes(figure,
                            extent,
                            coord=kwargs['coord'],
                            rot=kwargs['rot'],
                            format=kwargs['format'],
                            flipconv=kwargs['flip'])

    # Suppress warnings about nans
    with np.warnings.catch_warnings():

        np.warnings.filterwarnings('ignore')

        img = ax.projmap(hpx_map,
                         nest=kwargs['nest'],
                         coord=kwargs['coord'],
                         vmin=kwargs['min'],
                         vmax=kwargs['max'],
                         xsize=kwargs['xsize'],
                         ysize=kwargs['ysize'],
                         reso=kwargs['reso'],
                         cmap=kwargs['cmap'],
                         norm=kwargs['norm'])

    return img