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)
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)
def read_map(filename,field=0,dtype=np.float64,nest=False,hdu=1,h=False, verbose=False): """Read an healpix map from a fits file. Parameters ---------- filename : str the fits file name field : int or tuple of int, optional The column to read. Default: 0. By convention 0 is temperature, 1 is Q, 2 is U. Field can be a tuple to read multiple columns (0,1,2) dtype : data type, optional Force the conversion to some type. Default: np.float64 nest : bool, optional If True return the map in NEST ordering, otherwise in RING ordering; use fits keyword ORDERING to decide whether conversion is needed or not If None, no conversion is performed. hdu : int, optional the header number to look at (start at 0) h : boo, optional If True, return also the header. Default: False. verbose : bool, optional If True, print a number of diagnostic messages Returns ------- m | (m0, m1, ...) [, header] : array or a tuple of arrays, optionally with header appended The map(s) read from the file, and the header if *h* is True. """ hdulist=pf.open(filename) #print hdulist[1].header nside = hdulist[hdu].header.get('NSIDE') if nside is None: warnings.warn("No NSIDE in the header file : will use length of array", HealpixFitsWarning) else: nside = int(nside) if verbose: print 'NSIDE = %d'%nside if not pixelfunc.isnsideok(nside): raise ValueError('Wrong nside parameter.') ordering = hdulist[hdu].header.get('ORDERING','UNDEF').strip() if ordering == 'UNDEF': ordering = (nest and 'NESTED' or 'RING') warnings.warn("No ORDERING keyword in header file : " "assume %s"%ordering) if verbose: print 'ORDERING = %s in fits file'%ordering sz=pixelfunc.nside2npix(nside) if not hasattr(field, '__len__'): field = (field,) ret = [] for ff in field: m=hdulist[hdu].data.field(ff).astype(dtype).ravel() if (not pixelfunc.isnpixok(m.size) or (sz>0 and sz != m.size)) and verbose: print 'nside=%d, sz=%d, m.size=%d'%(nside,sz,m.size) raise ValueError('Wrong nside parameter.') if not nest is None: # no conversion with None if nest and ordering == 'RING': idx = pixelfunc.nest2ring(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] if verbose: print 'Ordering converted to NEST' elif (not nest) and ordering == 'NESTED': idx = pixelfunc.ring2nest(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] if verbose: print 'Ordering converted to RING' try: m[pixelfunc.mask_bad(m)] = UNSEEN except OverflowError, e: pass ret.append(m)
def in_ring(nside, iz, phi0, dphi, nest=False): """Compute the list of pixels in ring number iz in phi interval [phi0,phi0+dphi] Input: - nside: a power of 2 - iz: ring number - phi0: the starting longitude - dphi: interval of longitude Keyword: - nested: if True, return pixel number in nested scheme. Default: False (RING) Return: - list of pixel numbers """ from numpy import pi, arange, concatenate, hstack, fabs, round from pixelfunc import nside2npix, ring2nest npix = nside2npix(nside) take_all = 0 to_top = 0 twopi = 2.0 * pi ncap = 2 * nside * (nside - 1) listir = -1 nir = 0 phi_low = (phi0 - dphi) % twopi if (phi_low < 0): phi_low = phi_low + twopi phi_hi = (phi0 + dphi) % twopi if (phi_hi < 0): phi_hi = phi_hi + twopi if (fabs(dphi - pi) < 1e-6): take_all = 1 # equatorial region if ((iz >= nside) & (iz <= 3 * nside)): ir = iz - nside + 1 ipix1 = ncap + 4 * nside * (ir - 1) ipix2 = ipix1 + 4 * nside - 1 kshift = ir % 2 nr = nside * 4 else: if (iz < nside): ir = iz ipix1 = 2 * ir * (ir - 1) ipix2 = ipix1 + 4 * ir - 1 else: ir = 4 * nside - iz ipix1 = npix - 2 * ir * (ir + 1) ipix2 = ipix1 + 4 * ir - 1 nr = ir * 4 kshift = 1 if (take_all == 1): nir = ipix2 - ipix1 + 1 listir = arange(ipix1, ipix2 + 1, 1) if (take_all == 0): shift = kshift * .5 ip_low = int(round(nr * phi_low / twopi - shift)) ip_hi = int(round(nr * phi_hi / twopi - shift)) ip_low = ip_low % nr ip_hi = ip_hi % nr if (ip_low > ip_hi): to_top = 1 ip_low = ip_low + ipix1 ip_hi = ip_hi + ipix1 if (to_top == 1): nir1 = ipix2 - ip_low + 1 nir2 = ip_hi - ipix1 + 1 nir = nir1 + nir2 if ((nir1 > 0) & (nir2 > 0)): #listir = concatenate(arange(0,nir2,1)+ipix1, arange(0,nir1,1)+ip_low) list1 = arange(0, nir1, 1) + ip_low list2 = arange(0, nir2, 1) + ipix1 listir = concatenate((list1, list2)) else: if (nir1 == 0): listir = arange(0, nir2, 1) + ipix1 if (nir2 == 0): listir = arange(0, nir1, 1) + ip_low else: nir = ip_hi - ip_low + 1 listir = arange(0, nir, 1) + ip_low if (nest): listir = ring2nest(nside, listir) return listir
def read_map(filename, field=0, dtype=npy.float64, nest=False, hdu=1, h=False, verbose=False): """Read an healpix map from a fits file. Input: - filename: the fits file name Parameters: - field: the column to read Default: 0 by convention 0 is temperature, 1 is Q, 2 is U field can be a tuple to read multiple columns (0,1,2) - dtype: force the conversion to some type. Default: npy.float64 - nest=False: if True return the map in NEST ordering, otherwise in RING ordering; use fits keyword ORDERING to decide whether conversion is needed or not if None, no conversion is performed - hdu=1: the header number to look at (start at 0) - h=False: if True, return also the header - verbose=False: if True, print a number of diagnostic messages Return: - an array, a tuple of array, possibly with the header at the end if h is True """ hdulist = pyf.open(filename) # print hdulist[1].header nside = int(hdulist[hdu].header.get("NSIDE")) if nside is None: warnings.warn("No NSIDE in the header file : will use length of array", HealpixFitsWarning) if verbose: print "NSIDE = %d" % nside if not pixelfunc.isnsideok(nside): raise ValueError("Wrong nside parameter.") ordering = hdulist[hdu].header.get("ORDERING", "UNDEF").strip() if ordering == "UNDEF": ordering = nest and "NESTED" or "RING" warnings.warn("No ORDERING keyword in header file : " "assume %s" % ordering) if verbose: print "ORDERING = %s in fits file" % ordering sz = pixelfunc.nside2npix(nside) if not hasattr(field, "__len__"): field = (field,) ret = [] for ff in field: m = hdulist[hdu].data.field(ff).astype(dtype).ravel() if (not pixelfunc.isnpixok(m.size) or (sz > 0 and sz != m.size)) and verbose: print "nside=%d, sz=%d, m.size=%d" % (nside, sz, m.size) raise ValueError("Wrong nside parameter.") if nest != None: # no conversion with None if nest and ordering == "RING": idx = pixelfunc.nest2ring(nside, npy.arange(m.size, dtype=npy.int32)) m = m[idx] if verbose: print "Ordering converted to NEST" elif (not nest) and ordering == "NESTED": idx = pixelfunc.ring2nest(nside, npy.arange(m.size, dtype=npy.int32)) m = m[idx] if verbose: print "Ordering converted to RING" try: m[pixelfunc.mask_bad(m)] = UNSEEN except OverflowError, e: pass ret.append(m)
def in_ring(nside,iz,phi0,dphi,nest=False): """Compute the list of pixels in ring number iz in phi interval [phi0,phi0+dphi] Input: - nside: a power of 2 - iz: ring number - phi0: the starting longitude - dphi: interval of longitude Keyword: - nested: if True, return pixel number in nested scheme. Default: False (RING) Return: - list of pixel numbers """ from numpy import pi,arange,concatenate,hstack,fabs,round from pixelfunc import nside2npix,ring2nest npix = nside2npix(nside) take_all = 0 to_top = 0 twopi = 2.0 * pi ncap = 2*nside*(nside-1) listir = -1 nir = 0 phi_low = (phi0 - dphi) % twopi if (phi_low < 0): phi_low = phi_low + twopi phi_hi = (phi0 + dphi) % twopi if (phi_hi < 0): phi_hi = phi_hi + twopi if (fabs(dphi-pi) < 1e-6): take_all = 1 # equatorial region if ((iz >= nside) & (iz <= 3*nside)): ir = iz - nside + 1 ipix1 = ncap + 4*nside*(ir-1) ipix2 = ipix1 + 4*nside - 1 kshift = ir % 2 nr = nside*4 else: if (iz < nside): ir = iz ipix1 = 2*ir*(ir-1) ipix2 = ipix1 + 4*ir - 1 else: ir = 4*nside - iz ipix1 = npix - 2*ir*(ir+1) ipix2 = ipix1 + 4*ir - 1 nr = ir*4 kshift = 1 if (take_all == 1): nir = ipix2 - ipix1 + 1 listir = arange(ipix1,ipix2+1,1) if (take_all == 0): shift = kshift * .5 ip_low = int(round (nr * phi_low / twopi - shift)) ip_hi = int(round(nr * phi_hi / twopi - shift)) ip_low = ip_low % nr ip_hi = ip_hi % nr if (ip_low > ip_hi): to_top = 1 ip_low = ip_low + ipix1 ip_hi = ip_hi + ipix1 if (to_top == 1): nir1 = ipix2 - ip_low + 1 nir2 = ip_hi - ipix1 + 1 nir = nir1 + nir2 if ((nir1 > 0) & (nir2 > 0)): #listir = concatenate(arange(0,nir2,1)+ipix1, arange(0,nir1,1)+ip_low) list1 = arange(0,nir1,1)+ip_low list2 = arange(0,nir2,1)+ipix1 listir = concatenate((list1,list2)) else: if (nir1 == 0) : listir = arange(0,nir2,1)+ipix1 if (nir2 == 0) : listir = arange(0,nir1,1)+ip_low else: nir = ip_hi - ip_low + 1 listir = arange(0,nir,1)+ip_low if (nest): listir = ring2nest(nside,listir) return listir
def query_disc(nside, v0, radius, nest=False, deg=True): """Return the list of pixels within angle 'radius' from vector direction 'v0' Input: - nside: a power of 2 - v0: the vector describing the direction of the center of the disc - radius: the opening angle of the disc Keywords: - nest: if True, pixel returned in nested scheme. Default: False (RING) - deg: if False, radius angle expected in radian. Default: True (DEGREE) Return: - list of pixel (as a numpy array) """ # assumes input in degrees from numpy import sqrt, sin, cos, pi, array, fabs, arccos, arcsin, size, empty, concatenate, arctan2, asarray from pixelfunc import vec2pix, nside2npix npix = nside2npix(nside) ang_conv = 1.0 if (deg): ang_conv = pi / 180.0 cosang = cos(radius * ang_conv) # radius in radians radius_eff = radius * ang_conv v0 = asarray(v0) v0 /= sqrt((v0**2).sum()) x0, y0, z0 = v0 a = x0 * x0 + y0 * y0 phi0 = 0.0 if ((x0 != 0.0) | (y0 != 0.0)): phi0 = arctan2(y0, x0) cosphi0 = cos(phi0) rlat0 = arcsin(z0) rlat1 = rlat0 + radius_eff rlat2 = rlat0 - radius_eff if (rlat1 >= pi / 2.0): zmax = 1.0 else: zmax = sin(rlat1) irmin = max(ring_num(nside, zmax) - 1, 1) if (rlat2 <= -pi / 2.0): zmin = -1.0 else: zmin = sin(rlat2) irmax = min(ring_num(nside, zmin) + 1, 4 * nside - 1) #first = 1 work = [[]] for iz in xrange(irmin, irmax + 1): skip = 0 z = ring2z(nside, iz) b = cosang - z * z0 c = 1.0 - z * z cosdphi = b / sqrt(a * c) if ((x0 == 0) & (y0 == 0)): cosdphi = -1.0 dphi = pi if (fabs(cosdphi) <= 1): dphi = arccos(cosdphi) else: if (cosphi0 < cosdphi): skip = 1 dphi = pi if (skip == 0): listir = in_ring(nside, iz, phi0, dphi, nest=nest) nir = size(listir) if (nir > 0): work.append(listir) if len(work) > 1: work = concatenate(work[1:]) else: work = asarray([], dtype=int) return work
def query_disc(nside,v0,radius,nest=False,deg=True): """Return the list of pixels within angle 'radius' from vector direction 'v0' Input: - nside: a power of 2 - v0: the vector describing the direction of the center of the disc - radius: the opening angle of the disc Keywords: - nest: if True, pixel returned in nested scheme. Default: False (RING) - deg: if False, radius angle expected in radian. Default: True (DEGREE) Return: - list of pixel (as a numpy array) """ # assumes input in degrees from numpy import sqrt,sin,cos,pi,array,fabs,arccos,arcsin,size,empty,concatenate,arctan2,asarray from pixelfunc import vec2pix,nside2npix npix = nside2npix(nside) ang_conv = 1.0 if (deg): ang_conv = pi/180.0 cosang = cos(radius*ang_conv) # radius in radians radius_eff = radius * ang_conv v0 = asarray(v0) v0 /= sqrt((v0**2).sum()) x0,y0,z0 = v0 a = x0*x0 + y0*y0 phi0 = 0.0 if ((x0!= 0.0)|(y0!=0.0)): phi0 = arctan2(y0, x0) cosphi0 = cos(phi0) rlat0 = arcsin(z0) rlat1 = rlat0 + radius_eff rlat2 = rlat0 - radius_eff if (rlat1 >= pi/2.0): zmax = 1.0 else : zmax = sin(rlat1) irmin = max(ring_num(nside,zmax) - 1,1) if (rlat2 <= -pi/2.0): zmin = -1.0 else : zmin = sin(rlat2) irmax = min(ring_num(nside,zmin) + 1,4*nside-1) #first = 1 work = [[]] for iz in xrange(irmin,irmax+1): skip = 0 z = ring2z(nside,iz) b = cosang - z*z0 c = 1.0 - z*z cosdphi = b/sqrt(a*c) if ((x0 == 0)&(y0==0)): cosdphi = -1.0 dphi = pi if (fabs(cosdphi) <= 1): dphi = arccos(cosdphi) else: if (cosphi0 < cosdphi): skip = 1 dphi = pi if (skip == 0): listir = in_ring(nside, iz, phi0, dphi,nest=nest) nir = size(listir) if (nir>0): work.append(listir) if len(work) > 1: work = concatenate(work[1:]) else: work = asarray([], dtype=int) return work
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)
def read_map(filename, field=0, dtype=npy.float64, nest=False, hdu=1, h=False, verbose=False): """Read an healpix map from a fits file. Input: - filename: the fits file name Parameters: - field: the column to read Default: 0 by convention 0 is temperature, 1 is Q, 2 is U field can be a tuple to read multiple columns (0,1,2) - dtype: force the conversion to some type. Default: npy.float64 - nest=False: if True return the map in NEST ordering, otherwise in RING ordering; use fits keyword ORDERING to decide whether conversion is needed or not if None, no conversion is performed - hdu=1: the header number to look at (start at 0) - h=False: if True, return also the header - verbose=False: if True, print a number of diagnostic messages Return: - an array, a tuple of array, possibly with the header at the end if h is True """ hdulist = pyf.open(filename) #print hdulist[1].header nside = int(hdulist[hdu].header.get('NSIDE')) if nside is None: warnings.warn("No NSIDE in the header file : will use length of array", HealpixFitsWarning) if verbose: print 'NSIDE = %d' % nside if not pixelfunc.isnsideok(nside): raise ValueError('Wrong nside parameter.') ordering = hdulist[hdu].header.get('ORDERING', 'UNDEF').strip() if ordering == 'UNDEF': ordering = (nest and 'NESTED' or 'RING') warnings.warn("No ORDERING keyword in header file : " "assume %s" % ordering) if verbose: print 'ORDERING = %s in fits file' % ordering sz = pixelfunc.nside2npix(nside) if not hasattr(field, '__len__'): field = (field, ) ret = [] for ff in field: m = hdulist[hdu].data.field(ff).astype(dtype).ravel() if (not pixelfunc.isnpixok(m.size) or (sz > 0 and sz != m.size)) and verbose: print 'nside=%d, sz=%d, m.size=%d' % (nside, sz, m.size) raise ValueError('Wrong nside parameter.') if nest != None: # no conversion with None if nest and ordering == 'RING': idx = pixelfunc.nest2ring(nside, npy.arange(m.size, dtype=npy.int32)) m = m[idx] if verbose: print 'Ordering converted to NEST' elif (not nest) and ordering == 'NESTED': idx = pixelfunc.ring2nest(nside, npy.arange(m.size, dtype=npy.int32)) m = m[idx] if verbose: print 'Ordering converted to RING' try: m[pixelfunc.mask_bad(m)] = UNSEEN except OverflowError, e: pass ret.append(m)
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)
def read_map(filename,field=0,dtype=npy.float64,nest=False,hdu=1,h=False): """Read an healpix map from a fits file. Input: - filename: the fits file name Parameters: - field: the column to read Default: 0 by convention 0 is temperature, 1 is Q, 2 is U field can be a tuple to read multiple columns (0,1,2) - dtype: force the conversion to some type. Default: npy.float64 - nest=False: if True return the map in NEST ordering, otherwise in RING ordering; use fits keyword ORDERING to decide whether conversion is needed or not if None, no conversion is performed - hdu=1: the header number to look at (start at 0) - h=False: if True, return also the header Return: - an array, a tuple of array, possibly with the header at the end if h is True """ hdulist=pyf.open(filename) #print hdulist[1].header nside = int(hdulist[hdu].header.get('NSIDE')) if nside is None: warnings.warn("No NSIDE in the header file : will use length of array", HealpixFitsWarning) print 'NSIDE = %d'%nside if not pixelfunc.isnsideok(nside): raise ValueError('Wrong nside parameter.') ordering = hdulist[hdu].header.get('ORDERING','UNDEF').strip() if ordering == 'UNDEF': ordering = (nest and 'NESTED' or 'RING') warnings.warn("No ORDERING keyword in header file : " "assume %s"%ordering) print 'ORDERING = %s in fits file'%ordering sz=pixelfunc.nside2npix(nside) if not hasattr(field, '__len__'): field = (field,) ret = [] for ff in field: m=hdulist[hdu].data.field(ff).astype(dtype).ravel() if not pixelfunc.isnpixok(m.size) or (sz>0 and sz != m.size): print 'nside=%d, sz=%d, m.size=%d'%(nside,sz,m.size) raise ValueError('Wrong nside parameter.') if nest != None: # no conversion with None if nest and ordering == 'RING': idx = pixelfunc.nest2ring(nside,npy.arange(m.size,dtype=npy.int32)) m = m[idx] print 'Ordering converted to NEST' elif (not nest) and ordering == 'NESTED': idx = pixelfunc.ring2nest(nside,npy.arange(m.size,dtype=npy.int32)) m = m[idx] print 'Ordering converted to RING' m[m<-1.637e30] = UNSEEN ret.append(m) if len(ret) == 1: if h: return ret[0],hdulist[hdu].header.items() else: return ret[0] else: if h: ret.append(hdulist[hdu].header.items()) return tuple(ret) else: return tuple(ret)