Example #1
0
def smoothing(m,fwhm=0.0,sigma=None,degree=False,
              arcmin=False):
    """Smooth a map with a Gaussian symmetric beam.

    Input:
      - map: either an array representing one map, or a sequence of
             3 arrays representing 3 maps
    Parameters:
      - fwhm: the full width half max parameter of the Gaussian. Default:0.0
      - sigma: the sigma of the Gaussian. Override fwhm.
      - degree: if True, parameter given in degree. Override arcmin.
                Default: False
      - arcmin: if True, parameter given in arcmin. Default: False
      - mmax: the maximum m for alm. Default: mmax=lmax
    Return:
      - the smoothed map(s)
    """
    if type(m[0]) is npy.ndarray:
        if len(m) != 3:
            raise TypeError("map must be en array or a list of 3 arrays")
        nside = pixelfunc.npix2nside(m[0].size)
        if (pixelfunc.npix2nside(m[1].size) != nside
            or pixelfunc.npix2nside(m[2].size) != nside):
            raise TypeError("all maps in the array must have identical nside")
    elif type(m) == npy.ndarray:
        nside=pixelfunc.npix2nside(m.size)
    else:
        raise TypeError("map must be en array or a list of 3 arrays")
    alm = map2alm(m)
    return alm2map(alm,nside,fwhm=fwhm,sigma=sigma,
                   degree=degree,arcmin=arcmin)
Example #2
0
def smoothing(m, fwhm=0.0, sigma=None, degree=False, arcmin=False):
    """Smooth a map with a Gaussian symmetric beam.

    Input:
      - map: either an array representing one map, or a sequence of
             3 arrays representing 3 maps
    Parameters:
      - fwhm: the full width half max parameter of the Gaussian. Default:0.0
      - sigma: the sigma of the Gaussian. Override fwhm.
      - degree: if True, parameter given in degree. Override arcmin.
                Default: False
      - arcmin: if True, parameter given in arcmin. Default: False
      - mmax: the maximum m for alm. Default: mmax=lmax
    Return:
      - the smoothed map(s)
    """
    if type(m[0]) is npy.ndarray:
        if len(m) != 3:
            raise TypeError("map must be en array or a list of 3 arrays")
        nside = pixelfunc.npix2nside(m[0].size)
        if (pixelfunc.npix2nside(m[1].size) != nside
                or pixelfunc.npix2nside(m[2].size) != nside):
            raise TypeError("all maps in the array must have identical nside")
    elif type(m) == npy.ndarray:
        nside = pixelfunc.npix2nside(m.size)
    else:
        raise TypeError("map must be en array or a list of 3 arrays")
    alm = map2alm(m)
    return alm2map(alm,
                   nside,
                   fwhm=fwhm,
                   sigma=sigma,
                   degree=degree,
                   arcmin=arcmin)
Example #3
0
def write_map(filename, m, nest=False, dtype=npy.float32, fits_IDL=True):
    """Writes an healpix map into an healpix file.

    Input:
      - filename: the fits file name
      - m: the map to write. Possibly a sequence of 3 maps of same size.
           They will be considered as I, Q, U maps
      - nest=False: ordering scheme
      - fits_IDL = true reshapes columns in rows of 1024, otherwise all the data will 
        go in one column
    """
    if not hasattr(m, "__len__"):
        raise TypeError("The map must be a sequence")
    # check the dtype and convert it
    fitsformat = getformat(dtype)
    # print 'format to use: "%s"'%fitsformat
    if hasattr(m[0], "__len__"):
        # we should have three maps
        if len(m) != 3 or len(m[1]) != len(m[0]) or len(m[2]) != len(m[0]):
            raise ValueError("You should give 3 maps of same size " "for polarisation...")
        nside = pixelfunc.npix2nside(len(m[0]))
        if nside < 0:
            raise ValueError("Invalid healpix map : wrong number of pixel")
        cols = []
        colnames = ["I_STOKES", "Q_STOKES", "U_STOKES"]
        for cn, mm in zip(colnames, m):
            if len(mm) > 1024 and fits_IDL:
                # I need an ndarray, for reshape:
                mm2 = npy.asarray(mm)
                cols.append(pyf.Column(name=cn, format="1024%s" % fitsformat, array=mm2.reshape(mm2.size / 1024, 1024)))
            else:
                cols.append(pyf.Column(name=cn, format="%s" % fitsformat, array=mm))
    else:  # we write only one map
        nside = pixelfunc.npix2nside(len(m))
        if nside < 0:
            raise ValueError("Invalid healpix map : wrong number of pixel")
        if m.size > 1024 and fits_IDL:
            cols = [pyf.Column(name="I_STOKES", format="1024%s" % fitsformat, array=m.reshape(m.size / 1024, 1024))]
        else:
            cols = [pyf.Column(name="I_STOKES", format="%s" % fitsformat, array=m)]

    coldefs = pyf.ColDefs(cols)
    tbhdu = pyf.new_table(coldefs)
    # add needed keywords
    tbhdu.header.update("PIXTYPE", "HEALPIX", "HEALPIX pixelisation")
    if nest:
        ordering = "NESTED"
    else:
        ordering = "RING"
    tbhdu.header.update("ORDERING", ordering, "Pixel ordering scheme, either RING or NESTED")
    tbhdu.header.update("EXTNAME", "xtension", "name of this binary table extension")
    tbhdu.header.update("NSIDE", nside, "Resolution parameter of HEALPIX")
    tbhdu.header.update("FIRSTPIX", 0, "First pixel # (0 based)")
    tbhdu.header.update("LASTPIX", pixelfunc.nside2npix(nside) - 1, "Last pixel # (0 based)")
    tbhdu.header.update("INDXSCHM", "IMPLICIT", "Indexing: IMPLICIT or EXPLICIT")
    tbhdu.writeto(filename, clobber=True)
Example #4
0
def _get_nside(m):
    if hasattr(m, '__len__'):
        if len(m) == 0:
            raise TypeError('Empty sequence !')
        if hasattr(m[0], '__len__'):
            nside = pixelfunc.npix2nside(len(m[0]))
        else:
            nside = pixelfunc.npix2nside(len(m))
    else:
        raise TypeError('You must give an array or a tuple of arrays '
                        'as input')
    return nside
Example #5
0
def _get_nside(m):
    if hasattr(m,'__len__'):
        if len(m) == 0:
            raise TypeError('Empty sequence !')
        if hasattr(m[0],'__len__'):
            nside=pixelfunc.npix2nside(len(m[0]))
        else:
            nside=pixelfunc.npix2nside(len(m))
    else:
        raise TypeError('You must give an array or a tuple of arrays '
                        'as input')
    return nside
Example #6
0
 def projmap(self,map,nest=False,**kwds):
     nside = pixelfunc.npix2nside(pixelfunc.get_map_size(map))
     f = lambda x,y,z: pixelfunc.vec2pix(nside,x,y,z,nest=nest)
     xsize = kwds.pop('xsize',200)
     ysize = kwds.pop('ysize',None)
     reso = kwds.pop('reso',1.5)
     super(HpxGnomonicAxes,self).projmap(map,f,xsize=xsize,
                                         ysize=ysize,reso=reso,**kwds)
Example #7
0
 def projmap(self,map,nest=False,**kwds):
     nside = pixelfunc.npix2nside(pixelfunc.get_map_size(map))
     f = lambda x,y,z: pixelfunc.vec2pix(nside,x,y,z,nest=nest)
     xsize = kwds.pop('xsize',200)
     ysize = kwds.pop('ysize',None)
     reso = kwds.pop('reso',1.5)
     super(HpxGnomonicAxes,self).projmap(map,f,xsize=xsize,
                                         ysize=ysize,reso=reso,**kwds)
Example #8
0
def smoothing(m, fwhm=0.0, sigma=None, degree=False, arcmin=False):
    """Smooth a map with a Gaussian symmetric beam.

    Parameters
    ----------
    map : array or sequence of 3 arrays
      Either an array representing one map, or a sequence of
      3 arrays representing 3 maps
    fwhm : float, optional
      The full width half max parameter of the Gaussian. Default:0.0
    sigma : float, optional
      The sigma of the Gaussian. Override fwhm.
    degree : bool, optional
      If True, parameter given in degree. Override arcmin. Default: False
    arcmin : bool, optional
      If True, parameter given in arcmin. Default: False
    mmax : int, optional
      The maximum m for alm. Default: mmax=lmax

    Returns
    -------
    map_smo : array or tuple of 3 arrays
      The smoothed map(s)
    """
    if type(m[0]) is npy.ndarray:
        if len(m) != 3:
            raise TypeError("map must be en array or a list of 3 arrays")
        nside = pixelfunc.npix2nside(m[0].size)
        if (pixelfunc.npix2nside(m[1].size) != nside
                or pixelfunc.npix2nside(m[2].size) != nside):
            raise TypeError("all maps in the array must have identical nside")
    elif type(m) == npy.ndarray:
        nside = pixelfunc.npix2nside(m.size)
    else:
        raise TypeError("map must be en array or a list of 3 arrays")
    # Replace UNSEEN pixels with zeros
    m[m == UNSEEN] = 0
    alm = map2alm(m)
    return alm2map(alm,
                   nside,
                   fwhm=fwhm,
                   sigma=sigma,
                   degree=degree,
                   arcmin=arcmin)
Example #9
0
def smoothing(m,fwhm=0.0,sigma=None,degree=False,
              arcmin=False):
    """Smooth a map with a Gaussian symmetric beam.

    Parameters
    ----------
    map : array or sequence of 3 arrays
      Either an array representing one map, or a sequence of
      3 arrays representing 3 maps
    fwhm : float, optional
      The full width half max parameter of the Gaussian. Default:0.0
    sigma : float, optional
      The sigma of the Gaussian. Override fwhm.
    degree : bool, optional
      If True, parameter given in degree. Override arcmin. Default: False
    arcmin : bool, optional
      If True, parameter given in arcmin. Default: False
    mmax : int, optional
      The maximum m for alm. Default: mmax=lmax

    Returns
    -------
    map_smo : array or tuple of 3 arrays
      The smoothed map(s)
    """
    if type(m[0]) is npy.ndarray:
        if len(m) != 3:
            raise TypeError("map must be en array or a list of 3 arrays")
        nside = pixelfunc.npix2nside(m[0].size)
        if (pixelfunc.npix2nside(m[1].size) != nside
            or pixelfunc.npix2nside(m[2].size) != nside):
            raise TypeError("all maps in the array must have identical nside")
    elif type(m) == npy.ndarray:
        nside=pixelfunc.npix2nside(m.size)
    else:
        raise TypeError("map must be en array or a list of 3 arrays")
    # Replace UNSEEN pixels with zeros
    m[m == UNSEEN] = 0
    alm = map2alm(m)
    return alm2map(alm,nside,fwhm=fwhm,sigma=sigma,
                   degree=degree,arcmin=arcmin)
Example #10
0
 def projmap(self,map,nest=False,**kwds):
     nside = pixelfunc.npix2nside(pixelfunc.get_map_size(map))
     f = lambda x,y,z: pixelfunc.vec2pix(nside,x,y,z,nest=nest)
     super(HpxCartesianAxes,self).projmap(map,f,**kwds)
Example #11
0
def mollview(m, rot=None, coord=None, unit='',
             xsize=1000, nest=False,
             min=None, max=None, flip='astro',
             format='%g',
             cbar=True, cmap=None,
             norm=None, 
             graticule=False, graticule_labels=False,
             **kwargs):
    """Plot an healpix map (given as an array) in Mollweide projection.
    
    Parameters
    ----------
    map : float, array-like or None
      An array containing the map, supports masked maps, see the `ma` function.
      If None, will display a blank map, useful for overplotting.
    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.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    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)
    format : str, optional
      The format of the scale label. Default: '%g'
    cbar : bool, optional
      Display the colorbar. Default: True
    norm : {'hist', 'log', None}
      Color normalization, hist= histogram equalized color mapping,
      log= logarithmic color mapping, default: None (linear color mapping)
    kwargs : keywords
      any additional keyword is passed to pcolormesh
    graticule : bool
      add graticule
    graticule_labels : bool
      longitude and latitude labels
    """

    # not implemented features
    if not (norm is None):
        raise exceptions.NotImplementedError()

    # Create the figure
    import matplotlib.pyplot as plt
    from matplotlib.backends import pylab_setup
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

    width = 8.5
    fig = plt.figure(figsize=(width,width*.63))
    ax = fig.add_subplot(111, projection="mollweide")
    # FIXME: make a more general axes creation that works also with subplots
    #ax = plt.gcf().add_axes((.125, .1, .9, .9), projection="mollweide")

    # remove white space around the image
    plt.subplots_adjust(left=0.02, right=0.98, top=0.95, bottom=0.05)
    if graticule and graticule_labels:
        plt.subplots_adjust(left=0.04, right=0.98, top=0.95, bottom=0.05)

    # auto min and max
    if min is None:
        min = m.min()
    if max is None:
        max = m.max()

    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax.hold(hold)

    try:
        ysize = xsize/2
        theta = np.linspace(np.pi, 0, ysize)
        phi   = np.linspace(-np.pi, np.pi, xsize)

        longitude = np.radians(np.linspace(-180, 180, xsize))
        if flip == "astro":
            longitude = longitude[::-1]
        latitude = np.radians(np.linspace(-90, 90, ysize))
        # project the map to a rectangular matrix xsize x ysize
        PHI, THETA = np.meshgrid(phi, theta)
        # coord or rotation
        if coord or rot:
            r = Rotator(coord=coord, rot=rot, inv=True)
            THETA, PHI = r(THETA.flatten(), PHI.flatten())
            THETA = THETA.reshape(ysize, xsize)
            PHI = PHI.reshape(ysize, xsize)
        nside = npix2nside(len(m))
        grid_pix = ang2pix(nside, THETA, PHI, nest=nest)
        grid_map = m[grid_pix]

        # plot
        ret = plt.pcolormesh(longitude, latitude, grid_map, vmin=min, vmax=max, rasterized=True, **kwargs)

        # graticule
        plt.grid(graticule)
        if graticule:
            longitude_grid_spacing = 60 # deg
            ax.set_longitude_grid(longitude_grid_spacing)
            if width < 10:
                ax.set_latitude_grid(45)
                ax.set_longitude_grid_ends(90)

        if graticule_labels:
            ax.xaxis.set_major_formatter(ThetaFormatterShiftPi(longitude_grid_spacing))
        else:
            # remove longitude and latitude labels
            ax.xaxis.set_ticklabels([])
            ax.yaxis.set_ticklabels([])

        # colorbar
        if cbar:
            cb = fig.colorbar(ret, orientation='horizontal', shrink=.4, pad=0.05, ticks=[min, max])
            cb.ax.xaxis.set_label_text(unit)
            cb.ax.xaxis.labelpad = -8
            # workaround for issue with viewers, see colorbar docstring
            cb.solids.set_edgecolor("face")

        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret
Example #12
0
def write_map(filename,m,nest=False,dtype=np.float32,fits_IDL=True,coord=None):
    """Writes an healpix map into an healpix file.

    Parameters
    ----------
    filename : str
      the fits file name
    m : array or sequence of 3 arrays
      the map to write. Possibly a sequence of 3 maps of same size.
      They will be considered as I, Q, U maps
    nest : bool, optional
      If False, ordering scheme is NESTED, otherwise, it is RING. Default: RING.
    fits_IDL : bool, optional
      If True, reshapes columns in rows of 1024, otherwise all the data will 
      go in one column. Default: True
    coord : str
      The coordinate system, typically 'E' for Ecliptic, 'G' for Galactic or 'Q' for Equatorial  
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)
    #print 'format to use: "%s"'%fitsformat
    if hasattr(m[0], '__len__'):
        # we should have three maps
        if len(m) != 3 or len(m[1]) != len(m[0]) or len(m[2]) != len(m[0]):
            raise ValueError("You should give 3 maps of same size "
                             "for polarisation...")
        nside = pixelfunc.npix2nside(len(m[0]))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        cols=[]
        colnames=['I_STOKES','Q_STOKES','U_STOKES']
        for cn,mm in zip(colnames,m):
            if len(mm) > 1024 and fits_IDL:
                # I need an ndarray, for reshape:
                mm2 = np.asarray(mm)
                cols.append(pf.Column(name=cn,
                                       format='1024%s'%fitsformat,
                                       array=mm2.reshape(mm2.size/1024,1024)))
            else:
                cols.append(pf.Column(name=cn,
                                       format='%s'%fitsformat,
                                       array=mm))
    else: # we write only one map
        nside = pixelfunc.npix2nside(len(m))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        if m.size > 1024 and fits_IDL:
            cols = [pf.Column(name='I_STOKES',
                               format='1024%s'%fitsformat,
                               array=m.reshape(m.size/1024,1024))]
        else:
            cols = [pf.Column(name='I_STOKES',
                               format='%s'%fitsformat,
                               array=m)]
            
    tbhdu = pf.new_table(cols)
    # add needed keywords
    tbhdu.header.update('PIXTYPE','HEALPIX','HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else:    ordering = 'RING'
    tbhdu.header.update('ORDERING',ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    if coord:
        tbhdu.header.update('COORD',coord,
                            'Ecliptic, Galactic or eQuatorial')
    tbhdu.header.update('EXTNAME','xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE',nside,'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',pixelfunc.nside2npix(nside)-1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM','IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename,clobber=True)
Example #13
0
 def projmap(self, map, nest=False, **kwds):
     nside = pixelfunc.npix2nside(pixelfunc.get_map_size(map))
     f = lambda x, y, z: pixelfunc.vec2pix(nside, x, y, z, nest=nest)
     super(HpxCartesianAxes, self).projmap(map, f, **kwds)
Example #14
0
def write_map(filename,m,nest=False,dtype=np.float32,fits_IDL=True,coord=None,column_names=None):
    """Writes an healpix map into an healpix file.

    Parameters
    ----------
    filename : str
      the fits file name
    m : array or sequence of 3 arrays
      the map to write. Possibly a sequence of 3 maps of same size.
      They will be considered as I, Q, U maps. 
      Supports masked maps, see the `ma` function.
    nest : bool, optional
      If True, ordering scheme is assumed to be NESTED, otherwise, RING. Default: RING.
      The map ordering is not modified by this function, the input map array
      should already be in the desired ordering (run `ud_grade` beforehand).
    fits_IDL : bool, optional
      If True, reshapes columns in rows of 1024, otherwise all the data will 
      go in one column. Default: True
    coord : str
      The coordinate system, typically 'E' for Ecliptic, 'G' for Galactic or 'C' for
      Celestial (equatorial)
    column_names : str or list
      Column name or list of column names, if None we use:
      I_STOKES for 1 component,
      I/Q/U_STOKES for 3 components,
      II, IQ, IU, QQ, QU, UU for 6 components,
      COLUMN_0, COLUMN_1... otherwise
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)

    m = pixelfunc.ma_to_array(m)
    if pixelfunc.maptype(m) == 0: # a single map is converted to a list
        m = [m]

    if column_names is None:
        column_names = standard_column_names.get(len(m), ["COLUMN_%d" % n for n in range(len(m))])
    else:
        assert len(column_names) == len(m), "Length column_names != number of maps"

    # maps must have same length
    assert len(set(map(len, m))) == 1, "Maps must have same length"
    nside = pixelfunc.npix2nside(len(m[0]))

    if nside < 0:
        raise ValueError('Invalid healpix map : wrong number of pixel')

    cols=[]
    for cn, mm in zip(column_names, m):
        if len(mm) > 1024 and fits_IDL:
            # I need an ndarray, for reshape:
            mm2 = np.asarray(mm)
            cols.append(pf.Column(name=cn,
                                   format='1024%s' % fitsformat,
                                   array=mm2.reshape(mm2.size/1024,1024)))
        else:
            cols.append(pf.Column(name=cn,
                                   format='%s' % fitsformat,
                                   array=mm))
            
    tbhdu = pf.new_table(cols)
    # add needed keywords
    tbhdu.header.update('PIXTYPE','HEALPIX','HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else:    ordering = 'RING'
    tbhdu.header.update('ORDERING',ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    if coord:
        tbhdu.header.update('COORDSYS',coord,
                            'Ecliptic, Galactic or Celestial (equatorial)')
    tbhdu.header.update('EXTNAME','xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE',nside,'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',pixelfunc.nside2npix(nside)-1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM','IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename,clobber=True)
Example #15
0
 def projmap(self,map,nest=False,**kwds):
     nside = pixelfunc.npix2nside(len(map))
     f = lambda x,y,z: pixelfunc.vec2pix(nside,x,y,z,nest=nest)
     return super(HpxOrthographicAxes,self).projmap(map,f,**kwds)
Example #16
0
def write_map(filename,m,nest=False,dtype=npy.float32):
    """Writes an healpix map into an healpix file.

    Input:
      - filename: the fits file name
      - m: the map to write. Possibly a sequence of 3 maps of same size.
           They will be considered as I, Q, U maps
      - nest=False: ordering scheme
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)
    #print 'format to use: "%s"'%fitsformat
    if hasattr(m[0], '__len__'):
        # we should have three maps
        if len(m) != 3 or len(m[1]) != len(m[0]) or len(m[2]) != len(m[0]):
            raise ValueError("You should give 3 maps of same size "
                             "for polarisation...")
        nside = pixelfunc.npix2nside(len(m[0]))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        cols=[]
        colnames=['I_STOKES','Q_STOKES','U_STOKES']
        for cn,mm in zip(colnames,m):
            if len(mm) > 1024:
                # I need an ndarray, for reshape:
                mm2 = npy.asarray(mm)
                cols.append(pyf.Column(name=cn,
                                       format='1024%s'%fitsformat,
                                       array=mm2.reshape(mm2.size/1024,1024)))
            else:
                cols.append(pyf.Column(name=cn,
                                       format='%s'%fitsformat,
                                       array=mm))
    else: # we write only one map
        nside = pixelfunc.npix2nside(len(m))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        if m.size > 1024:
            cols = [pyf.Column(name='I_STOKES',
                               format='1024%s'%fitsformat,
                               array=m.reshape(m.size/1024,1024))]
        else:
            cols = [pyf.Column(name='I_STOKES',
                               format='%s'%fitsformat,
                               array=m)]
            
    coldefs=pyf.ColDefs(cols)
    tbhdu = pyf.new_table(coldefs)
    # add needed keywords
    tbhdu.header.update('PIXTYPE','HEALPIX','HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else:    ordering = 'RING'
    tbhdu.header.update('ORDERING',ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    tbhdu.header.update('EXTNAME','xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE',nside,'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',pixelfunc.nside2npix(nside)-1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM','IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename,clobber=True)