index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
37,674 | healpy | disable_warnings |
.. deprecated:: 1.15.0
The disable_warnings function is deprecated and may be removed in a future version.
healpy uses logging now
This function has no effect | def disable_warnings():
"""healpy uses logging now
This function has no effect
"""
pass
| () |
37,675 | healpy | enable_warnings |
.. deprecated:: 1.15.0
The enable_warnings function is deprecated and may be removed in a future version.
healpy uses logging now
This function has no effect | def disable_warnings():
"""healpy uses logging now
This function has no effect
"""
pass
| () |
37,676 | healpy.pixelfunc | fit_dipole | Fit a dipole and a monopole to the map, excluding bad pixels.
Parameters
----------
m : float, array-like
the map to which a dipole is fitted and subtracted, accepts masked maps
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] degrees are not taken into account
Returns
-------
res : tuple of length 2
the monopole value in res[0] and the dipole vector (as array) in res[1]
See Also
--------
remove_dipole, fit_monopole, remove_monopole
| def fit_dipole(m, nest=False, bad=UNSEEN, gal_cut=0):
"""Fit a dipole and a monopole to the map, excluding bad pixels.
Parameters
----------
m : float, array-like
the map to which a dipole is fitted and subtracted, accepts masked maps
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] degrees are not taken into account
Returns
-------
res : tuple of length 2
the monopole value in res[0] and the dipole vector (as array) in res[1]
See Also
--------
remove_dipole, fit_monopole, remove_monopole
"""
m = ma_to_array(m)
m = np.asarray(m)
npix = m.size
nside = npix2nside(npix)
if nside > 128:
bunchsize = npix // 24
else:
bunchsize = npix
aa = np.zeros((4, 4), dtype=np.float64)
v = np.zeros(4, dtype=np.float64)
for ibunch in range(npix // bunchsize):
ipix = np.arange(ibunch * bunchsize, (ibunch + 1) * bunchsize)
ipix = ipix[(m.flat[ipix] != bad) & (np.isfinite(m.flat[ipix]))]
x, y, z = pix2vec(nside, ipix, nest)
if gal_cut > 0:
w = np.abs(z) >= np.sin(gal_cut * np.pi / 180)
ipix = ipix[w]
x = x[w]
y = y[w]
z = z[w]
del w
aa[0, 0] += ipix.size
aa[1, 0] += x.sum()
aa[2, 0] += y.sum()
aa[3, 0] += z.sum()
aa[1, 1] += (x ** 2).sum()
aa[2, 1] += (x * y).sum()
aa[3, 1] += (x * z).sum()
aa[2, 2] += (y ** 2).sum()
aa[3, 2] += (y * z).sum()
aa[3, 3] += (z ** 2).sum()
v[0] += m.flat[ipix].sum()
v[1] += (m.flat[ipix] * x).sum()
v[2] += (m.flat[ipix] * y).sum()
v[3] += (m.flat[ipix] * z).sum()
aa[0, 1] = aa[1, 0]
aa[0, 2] = aa[2, 0]
aa[0, 3] = aa[3, 0]
aa[1, 2] = aa[2, 1]
aa[1, 3] = aa[3, 1]
aa[2, 3] = aa[3, 2]
res = np.dot(np.linalg.inv(aa), v)
mono = res[0]
dipole = res[1:4]
return mono, dipole
| (m, nest=False, bad=-1.6375e+30, gal_cut=0) |
37,677 | healpy.pixelfunc | fit_monopole | Fit a monopole to the map, excluding unseen pixels.
Parameters
----------
m : float, array-like
the map to which a dipole is fitted and subtracted, accepts masked arrays
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] degrees are not taken into account
Returns
-------
res: float
fitted monopole value
See Also
--------
fit_dipole, remove_monopole, remove_monopole
| def fit_monopole(m, nest=False, bad=UNSEEN, gal_cut=0):
"""Fit a monopole to the map, excluding unseen pixels.
Parameters
----------
m : float, array-like
the map to which a dipole is fitted and subtracted, accepts masked arrays
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] degrees are not taken into account
Returns
-------
res: float
fitted monopole value
See Also
--------
fit_dipole, remove_monopole, remove_monopole
"""
m = ma_to_array(m)
m = np.asarray(m)
npix = m.size
nside = npix2nside(npix)
if nside > 128:
bunchsize = npix // 24
else:
bunchsize = npix
aa = v = 0.0
for ibunch in range(npix // bunchsize):
ipix = np.arange(ibunch * bunchsize, (ibunch + 1) * bunchsize)
ipix = ipix[(m.flat[ipix] != bad) & (np.isfinite(m.flat[ipix]))]
x, y, z = pix2vec(nside, ipix, nest)
if gal_cut > 0:
w = np.abs(z) >= np.sin(gal_cut * np.pi / 180)
ipix = ipix[w]
x = x[w]
y = y[w]
z = z[w]
del w
aa += ipix.size
v += m.flat[ipix].sum()
mono = v / aa
return mono
| (m, nest=False, bad=-1.6375e+30, gal_cut=0) |
37,679 | healpy.sphtfunc | gauss_beam | Gaussian beam window function
Computes the spherical transform of an axisimmetric gaussian beam
For a sky of underlying power spectrum C(l) observed with beam of
given FWHM, the measured power spectrum will be
C(l)_meas = C(l) B(l)^2
where B(l) is given by gaussbeam(Fwhm,Lmax).
The polarization beam is also provided (when pol = True ) assuming
a perfectly co-polarized beam
(e.g., Challinor et al 2000, astro-ph/0008228)
Parameters
----------
fwhm : float
full width half max in radians
lmax : integer
ell max
pol : bool
if False, output has size (lmax+1) and is temperature beam
if True output has size (lmax+1, 4) with components:
* temperature beam
* grad/electric polarization beam
* curl/magnetic polarization beam
* temperature * grad beam
Returns
-------
beam : array
beam window function [0, lmax] if dim not specified
otherwise (lmax+1, 4) contains polarized beam
| def gauss_beam(fwhm, lmax=512, pol=False):
"""Gaussian beam window function
Computes the spherical transform of an axisimmetric gaussian beam
For a sky of underlying power spectrum C(l) observed with beam of
given FWHM, the measured power spectrum will be
C(l)_meas = C(l) B(l)^2
where B(l) is given by gaussbeam(Fwhm,Lmax).
The polarization beam is also provided (when pol = True ) assuming
a perfectly co-polarized beam
(e.g., Challinor et al 2000, astro-ph/0008228)
Parameters
----------
fwhm : float
full width half max in radians
lmax : integer
ell max
pol : bool
if False, output has size (lmax+1) and is temperature beam
if True output has size (lmax+1, 4) with components:
* temperature beam
* grad/electric polarization beam
* curl/magnetic polarization beam
* temperature * grad beam
Returns
-------
beam : array
beam window function [0, lmax] if dim not specified
otherwise (lmax+1, 4) contains polarized beam
"""
sigma = fwhm / np.sqrt(8.0 * np.log(2.0))
ell = np.arange(lmax + 1)
sigma2 = sigma ** 2
g = np.exp(-0.5 * ell * (ell + 1) * sigma2)
if not pol: # temperature-only beam
return g
else: # polarization beam
# polarization factors [1, 2 sigma^2, 2 sigma^2, sigma^2]
pol_factor = np.exp([0.0, 2 * sigma2, 2 * sigma2, sigma2])
return g[:, np.newaxis] * pol_factor
| (fwhm, lmax=512, pol=False) |
37,680 | healpy.pixelfunc | get_all_neighbours | Return the 8 nearest pixels.
Parameters
----------
nside : int
the nside to work with
theta, phi : scalar or array-like
if phi is not given or None, theta is interpreted as pixel number,
otherwise, theta[rad],phi[rad] are angular coordinates
nest : bool
if ``True``, pixel number will be NESTED ordering, otherwise RING ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
ipix : int, array
pixel number of the SW, W, NW, N, NE, E, SE and S neighbours,
shape is (8,) if input is scalar, otherwise shape is (8, N) if input is
of length N. If a neighbor does not exist (it can be the case for W, N, E and S)
the corresponding pixel number will be -1.
See Also
--------
get_interp_weights, get_interp_val
Examples
--------
>>> import healpy as hp
>>> print(hp.get_all_neighbours(1, 4))
[11 7 3 -1 0 5 8 -1]
>>> print(hp.get_all_neighbours(1, np.pi/2, np.pi/2))
[ 8 4 0 -1 1 6 9 -1]
>>> print(hp.get_all_neighbours(1, 90, 0, lonlat=True))
[ 8 4 0 -1 1 6 9 -1]
| def get_all_neighbours(nside, theta, phi=None, nest=False, lonlat=False):
"""Return the 8 nearest pixels.
Parameters
----------
nside : int
the nside to work with
theta, phi : scalar or array-like
if phi is not given or None, theta is interpreted as pixel number,
otherwise, theta[rad],phi[rad] are angular coordinates
nest : bool
if ``True``, pixel number will be NESTED ordering, otherwise RING ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
ipix : int, array
pixel number of the SW, W, NW, N, NE, E, SE and S neighbours,
shape is (8,) if input is scalar, otherwise shape is (8, N) if input is
of length N. If a neighbor does not exist (it can be the case for W, N, E and S)
the corresponding pixel number will be -1.
See Also
--------
get_interp_weights, get_interp_val
Examples
--------
>>> import healpy as hp
>>> print(hp.get_all_neighbours(1, 4))
[11 7 3 -1 0 5 8 -1]
>>> print(hp.get_all_neighbours(1, np.pi/2, np.pi/2))
[ 8 4 0 -1 1 6 9 -1]
>>> print(hp.get_all_neighbours(1, 90, 0, lonlat=True))
[ 8 4 0 -1 1 6 9 -1]
"""
check_nside(nside, nest=nest)
if phi is not None:
theta = ang2pix(nside, theta, phi, nest=nest, lonlat=lonlat)
if nest:
r = pixlib._get_neighbors_nest(nside, theta)
else:
r = pixlib._get_neighbors_ring(nside, theta)
res = np.array(r[0:8])
return res
| (nside, theta, phi=None, nest=False, lonlat=False) |
37,681 | healpy.pixelfunc | get_interp_val | Return the bi-linear interpolation value of map(s) using 4 nearest neighbours.
Parameters
----------
m : array-like, shape (npix,) or (nmaps, npix)
a healpix map or sequence thereof, accepts masked arrays
theta, phi : float, scalar or array-like
angular coordinates of point at which to interpolate the map
nest : bool
if True, the is assumed to be in NESTED ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
val : float, scalar or array-like
the interpolated value(s), usual numpy broadcasting rules apply.
See Also
--------
get_interp_weights, get_all_neighbours
Examples
--------
>>> import healpy as hp
>>> hp.get_interp_val(np.arange(12.), np.pi/2, 0)
4.0
>>> hp.get_interp_val(np.arange(12.), np.pi/2, np.pi/2)
5.0
>>> hp.get_interp_val(np.arange(12.), np.pi/2, np.pi/2 + 2*np.pi)
5.0
>>> hp.get_interp_val(np.arange(12.), np.linspace(0, np.pi, 10), 0)
array([ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ])
>>> hp.get_interp_val(np.arange(12.), 0, np.linspace(90, -90, 10), lonlat=True)
array([ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ])
>>> hp.get_interp_val(
... [np.arange(12.), 2 * np.arange(12.)], np.linspace(0, np.pi, 10), 0
... )
array([[ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ],
[ 3. , 3. , 3. , 4.41236857, 6.80412286,
10.63092972, 15.89278916, 19. , 19. , 19. ]])
| def get_interp_val(m, theta, phi, nest=False, lonlat=False):
"""Return the bi-linear interpolation value of map(s) using 4 nearest neighbours.
Parameters
----------
m : array-like, shape (npix,) or (nmaps, npix)
a healpix map or sequence thereof, accepts masked arrays
theta, phi : float, scalar or array-like
angular coordinates of point at which to interpolate the map
nest : bool
if True, the is assumed to be in NESTED ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
val : float, scalar or array-like
the interpolated value(s), usual numpy broadcasting rules apply.
See Also
--------
get_interp_weights, get_all_neighbours
Examples
--------
>>> import healpy as hp
>>> hp.get_interp_val(np.arange(12.), np.pi/2, 0)
4.0
>>> hp.get_interp_val(np.arange(12.), np.pi/2, np.pi/2)
5.0
>>> hp.get_interp_val(np.arange(12.), np.pi/2, np.pi/2 + 2*np.pi)
5.0
>>> hp.get_interp_val(np.arange(12.), np.linspace(0, np.pi, 10), 0)
array([ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ])
>>> hp.get_interp_val(np.arange(12.), 0, np.linspace(90, -90, 10), lonlat=True)
array([ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ])
>>> hp.get_interp_val(
... [np.arange(12.), 2 * np.arange(12.)], np.linspace(0, np.pi, 10), 0
... )
array([[ 1.5 , 1.5 , 1.5 , 2.20618428, 3.40206143,
5.31546486, 7.94639458, 9.5 , 9.5 , 9.5 ],
[ 3. , 3. , 3. , 4.41236857, 6.80412286,
10.63092972, 15.89278916, 19. , 19. , 19. ]])
"""
m = np.atleast_2d(m)
nmaps, npix = m.shape
nside = npix2nside(npix)
if lonlat:
theta, phi = lonlat2thetaphi(theta, phi)
if nest:
r = pixlib._get_interpol_nest(nside, theta, phi)
else:
r = pixlib._get_interpol_ring(nside, theta, phi)
p = np.array(r[0:4])
w = np.array(r[4:8])
del r
# NOTE: the [()] syntax converts a 0d array from np.squeeze to a Python scalar
return np.squeeze(np.sum(m[:, p] * w, axis=1))[()]
| (m, theta, phi, nest=False, lonlat=False) |
37,682 | healpy.pixelfunc | get_interp_weights | Return the 4 closest pixels on the two rings above and below the
location and corresponding weights.
Weights are provided for bilinear interpolation along latitude and longitude
Parameters
----------
nside : int
the healpix nside
theta, phi : float, scalar or array-like
if phi is not given, theta is interpreted as pixel number,
otherwise theta[rad],phi[rad] are angular coordinates
nest : bool
if ``True``, NESTED ordering, otherwise RING ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
res : tuple of length 2
contains pixel numbers in res[0] and weights in res[1].
Usual numpy broadcasting rules apply.
See Also
--------
get_interp_val, get_all_neighbours
Examples
--------
Note that some of the test inputs below that are on pixel boundaries
such as theta=pi/2, phi=pi/2, have a tiny value of 1e-15 added to them
to make them reproducible on i386 machines using x87 floating point
instruction set (see https://github.com/healpy/healpy/issues/528).
>>> import healpy as hp
>>> pix, weights = hp.get_interp_weights(1, 0)
>>> print(pix)
[0 1 4 5]
>>> weights
array([ 1., 0., 0., 0.])
>>> pix, weights = hp.get_interp_weights(1, 0, 0)
>>> print(pix)
[1 2 3 0]
>>> weights
array([ 0.25, 0.25, 0.25, 0.25])
>>> pix, weights = hp.get_interp_weights(1, 0, 90, lonlat=True)
>>> print(pix)
[1 2 3 0]
>>> weights
array([ 0.25, 0.25, 0.25, 0.25])
>>> pix, weights = hp.get_interp_weights(1, [0, np.pi/2 + 1e-15], 0)
>>> print(pix)
[[ 1 4]
[ 2 5]
[ 3 11]
[ 0 8]]
>>> np.testing.assert_allclose(
... weights,
... np.array([[ 0.25, 1. ],
... [ 0.25, 0. ],
... [ 0.25, 0. ],
... [ 0.25, 0. ]]), rtol=0, atol=1e-14)
| def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False):
"""Return the 4 closest pixels on the two rings above and below the
location and corresponding weights.
Weights are provided for bilinear interpolation along latitude and longitude
Parameters
----------
nside : int
the healpix nside
theta, phi : float, scalar or array-like
if phi is not given, theta is interpreted as pixel number,
otherwise theta[rad],phi[rad] are angular coordinates
nest : bool
if ``True``, NESTED ordering, otherwise RING ordering.
lonlat : bool
If True, input angles are assumed to be longitude and latitude in degree,
otherwise, they are co-latitude and longitude in radians.
Returns
-------
res : tuple of length 2
contains pixel numbers in res[0] and weights in res[1].
Usual numpy broadcasting rules apply.
See Also
--------
get_interp_val, get_all_neighbours
Examples
--------
Note that some of the test inputs below that are on pixel boundaries
such as theta=pi/2, phi=pi/2, have a tiny value of 1e-15 added to them
to make them reproducible on i386 machines using x87 floating point
instruction set (see https://github.com/healpy/healpy/issues/528).
>>> import healpy as hp
>>> pix, weights = hp.get_interp_weights(1, 0)
>>> print(pix)
[0 1 4 5]
>>> weights
array([ 1., 0., 0., 0.])
>>> pix, weights = hp.get_interp_weights(1, 0, 0)
>>> print(pix)
[1 2 3 0]
>>> weights
array([ 0.25, 0.25, 0.25, 0.25])
>>> pix, weights = hp.get_interp_weights(1, 0, 90, lonlat=True)
>>> print(pix)
[1 2 3 0]
>>> weights
array([ 0.25, 0.25, 0.25, 0.25])
>>> pix, weights = hp.get_interp_weights(1, [0, np.pi/2 + 1e-15], 0)
>>> print(pix)
[[ 1 4]
[ 2 5]
[ 3 11]
[ 0 8]]
>>> np.testing.assert_allclose(
... weights,
... np.array([[ 0.25, 1. ],
... [ 0.25, 0. ],
... [ 0.25, 0. ],
... [ 0.25, 0. ]]), rtol=0, atol=1e-14)
"""
check_nside(nside, nest=nest)
if phi is None:
theta, phi = pix2ang(nside, theta, nest=nest)
elif lonlat:
theta, phi = lonlat2thetaphi(theta, phi)
if nest:
r = pixlib._get_interpol_nest(nside, theta, phi)
else:
r = pixlib._get_interpol_ring(nside, theta, phi)
p = np.array(r[0:4])
w = np.array(r[4:8])
return (p, w)
| (nside, theta, phi=None, nest=False, lonlat=False) |
37,683 | healpy.pixelfunc | get_map_size | Returns the npix of a given map (implicit or explicit pixelization).
If map is a dict type, assumes explicit pixelization: use nside key if present, or use
nside attribute if present, otherwise use the smallest valid npix given the maximum key value.
otherwise assumes implicit pixelization and returns len(m).
Parameters
----------
m : array-like or dict-like
a map with implicit (array-like) or explicit (dict-like) pixellization
Returns
-------
npix : int
a valid number of pixel
Notes
-----
In implicit pixellization, raise a ValueError exception if the size of the input
is not a valid pixel number.
Examples
--------
>>> import healpy as hp
>>> m = {0: 1, 1: 1, 2: 1, 'nside': 1}
>>> print(hp.get_map_size(m))
12
>>> m = {0: 1, 767: 1}
>>> print(hp.get_map_size(m))
768
>>> print(hp.get_map_size(np.zeros(12 * 8 ** 2)))
768
| def get_map_size(m):
"""Returns the npix of a given map (implicit or explicit pixelization).
If map is a dict type, assumes explicit pixelization: use nside key if present, or use
nside attribute if present, otherwise use the smallest valid npix given the maximum key value.
otherwise assumes implicit pixelization and returns len(m).
Parameters
----------
m : array-like or dict-like
a map with implicit (array-like) or explicit (dict-like) pixellization
Returns
-------
npix : int
a valid number of pixel
Notes
-----
In implicit pixellization, raise a ValueError exception if the size of the input
is not a valid pixel number.
Examples
--------
>>> import healpy as hp
>>> m = {0: 1, 1: 1, 2: 1, 'nside': 1}
>>> print(hp.get_map_size(m))
12
>>> m = {0: 1, 767: 1}
>>> print(hp.get_map_size(m))
768
>>> print(hp.get_map_size(np.zeros(12 * 8 ** 2)))
768
"""
if isinstance(m, dict):
if "nside" in m:
return nside2npix(m["nside"])
elif hasattr(ma, "nside"):
return nside2npix(m.nside)
else:
nside = get_min_valid_nside(max(m.keys()) + 1)
return nside2npix(nside)
else:
if isnpixok(len(m)):
return len(m)
else:
raise ValueError("Wrong pixel number (it is not 12*nside**2)")
| (m) |
37,684 | healpy.pixelfunc | get_nside | Return the nside of the given map.
Parameters
----------
m : sequence
the map to get the nside from.
Returns
-------
nside : int
the healpix nside parameter of the map (or sequence of maps)
Notes
-----
If the input is a sequence of maps, all of them must have same size.
If the input is not a valid map (not a sequence, unvalid number of pixels),
a TypeError exception is raised.
| def get_nside(m):
"""Return the nside of the given map.
Parameters
----------
m : sequence
the map to get the nside from.
Returns
-------
nside : int
the healpix nside parameter of the map (or sequence of maps)
Notes
-----
If the input is a sequence of maps, all of them must have same size.
If the input is not a valid map (not a sequence, unvalid number of pixels),
a TypeError exception is raised.
"""
typ = maptype(m)
if typ == 0:
return npix2nside(len(m))
else:
return npix2nside(len(m[0]))
| (m) |
37,685 | healpy.visufunc | gnomview | Plot 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.
If None, use a blank map, useful for
overplotting.
fig : None or int, optional
A figure number. Default: None= create a new figure
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: 200
ysize : None or int, optional
The size of the image. Default: None= xsize
reso : float, optional
Resolution (in arcmin). Default: 1.5 arcmin
title : str, optional
The title of the plot. Default: 'Gnomonic view'
nest : bool, optional
If True, ordering scheme is NESTED. Default: False (RING)
min : float, scalar, optional
The minimum range value
max : float, scalar, 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)
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]
format : str, optional
The format of the scale label. Default: '%g'
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by a GnomonicAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a GnomonicAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
notext: bool, optional
If True: do not add resolution info text. Default=False
return_projected_map : bool, optional
if True returns the projected map in a 2d numpy array
no_plot : bool, optional
if True no figure will be created
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See an example usage of the alpha channel transparency in the documentation under
"Other tutorials"
See Also
--------
mollview, cartview, orthview, azeqview
| def gnomview(
map=None,
fig=None,
rot=None,
coord=None,
unit="",
xsize=200,
ysize=None,
reso=1.5,
title="Gnomonic view",
nest=False,
remove_dip=False,
remove_mono=False,
gal_cut=0,
min=None,
max=None,
flip="astro",
format="%.3g",
cbar=True,
cmap=None,
badcolor="gray",
bgcolor="white",
norm=None,
hold=False,
sub=None,
reuse_axes=False,
margins=None,
notext=False,
return_projected_map=False,
no_plot=False,
alpha=None,
):
"""Plot 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.
If None, use a blank map, useful for
overplotting.
fig : None or int, optional
A figure number. Default: None= create a new figure
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: 200
ysize : None or int, optional
The size of the image. Default: None= xsize
reso : float, optional
Resolution (in arcmin). Default: 1.5 arcmin
title : str, optional
The title of the plot. Default: 'Gnomonic view'
nest : bool, optional
If True, ordering scheme is NESTED. Default: False (RING)
min : float, scalar, optional
The minimum range value
max : float, scalar, 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)
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]
format : str, optional
The format of the scale label. Default: '%g'
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by a GnomonicAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a GnomonicAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
notext: bool, optional
If True: do not add resolution info text. Default=False
return_projected_map : bool, optional
if True returns the projected map in a 2d numpy array
no_plot : bool, optional
if True no figure will be created
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See an example usage of the alpha channel transparency in the documentation under
"Other tutorials"
See Also
--------
mollview, cartview, orthview, azeqview
"""
import pylab
if map is None:
map = np.zeros(12) + np.inf
cbar = False
# Ensure that the nside is valid
nside = pixelfunc.get_nside(map)
pixelfunc.check_nside(nside, nest=nest)
if not (hold or sub or reuse_axes):
f = pylab.figure(fig, figsize=(5.8, 6.4))
if not margins:
margins = (0.075, 0.05, 0.075, 0.05)
extent = (0.0, 0.0, 1.0, 1.0)
elif hold:
f = pylab.gcf()
left, bottom, right, top = np.array(pylab.gca().get_position()).ravel()
if not margins:
margins = (0.0, 0.0, 0.0, 0.0)
extent = (left, bottom, right - left, top - bottom)
f.delaxes(pylab.gca())
elif reuse_axes:
f = pylab.gcf()
else: # using subplot syntax
f = pylab.gcf()
if hasattr(sub, "__len__"):
nrows, ncols, idx = sub
else:
nrows, ncols, idx = sub // 100, (sub % 100) // 10, (sub % 10)
if idx < 1 or idx > ncols * nrows:
raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
c, r = (idx - 1) % ncols, (idx - 1) // ncols
if not margins:
margins = (0.01, 0.0, 0.0, 0.02)
extent = (
c * 1.0 / ncols,
1.0 - (r + 1) * 1.0 / nrows,
1.0 / ncols,
1.0 / nrows,
)
if not reuse_axes:
extent = (
extent[0] + margins[0],
extent[1] + margins[1],
extent[2] - margins[2] - margins[0],
extent[3] - margins[3] - margins[1],
)
# f=pylab.figure(fig,figsize=(5.5,6))
# Starting to draw : turn interactive off
wasinteractive = pylab.isinteractive()
pylab.ioff()
try:
map = pixelfunc.ma_to_array(map)
if reuse_axes:
ax = f.gca()
else:
ax = PA.HpxGnomonicAxes(
f, extent, coord=coord, rot=rot, format=format, flipconv=flip
)
f.add_axes(ax)
if remove_dip:
map = pixelfunc.remove_dipole(map, gal_cut=gal_cut, nest=nest, copy=True)
elif remove_mono:
map = pixelfunc.remove_monopole(map, gal_cut=gal_cut, nest=nest, copy=True)
img = ax.projmap(
map,
nest=nest,
coord=coord,
vmin=min,
vmax=max,
xsize=xsize,
ysize=ysize,
reso=reso,
cmap=cmap,
norm=norm,
badcolor=badcolor,
bgcolor=bgcolor,
alpha=alpha,
)
if cbar:
im = ax.get_images()[0]
b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
mappable = plt.cm.ScalarMappable(
norm=matplotlib.colors.Normalize(vmin=im.norm.vmin, vmax=im.norm.vmax),
cmap=cmap,
)
if matplotlib.__version__ >= "0.91.0":
cb = f.colorbar(
mappable,
ax=ax,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.08,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
else:
cb = f.colorbar(
mappable,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.08,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
cb.solids.set_rasterized(True)
ax.set_title(title)
if not notext:
ax.text(
-0.07,
0.02,
"%g '/pix, %dx%d pix"
% (
ax.proj.arrayinfo["reso"],
ax.proj.arrayinfo["xsize"],
ax.proj.arrayinfo["ysize"],
),
fontsize=12,
verticalalignment="bottom",
transform=ax.transAxes,
rotation=90,
)
ax.text(
-0.07,
0.6,
ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
rotation=90,
transform=ax.transAxes,
)
lon, lat = np.around(ax.proj.get_center(lonlat=True), ax._coordprec)
ax.text(
0.5,
-0.03,
"(%g,%g)" % (lon, lat),
verticalalignment="center",
horizontalalignment="center",
transform=ax.transAxes,
)
if cbar:
cb.ax.text(
1.05,
0.30,
unit,
fontsize=14,
fontweight="bold",
transform=cb.ax.transAxes,
ha="left",
va="center",
)
f.sca(ax)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
if no_plot:
pylab.close(f)
f.clf()
ax.cla()
if return_projected_map:
return img
| (map=None, fig=None, rot=None, coord=None, unit='', xsize=200, ysize=None, reso=1.5, title='Gnomonic view', nest=False, remove_dip=False, remove_mono=False, gal_cut=0, min=None, max=None, flip='astro', format='%.3g', cbar=True, cmap=None, badcolor='gray', bgcolor='white', norm=None, hold=False, sub=None, reuse_axes=False, margins=None, notext=False, return_projected_map=False, no_plot=False, alpha=None) |
37,686 | healpy.visufunc | graticule | Draw a graticule on the current Axes.
Parameters
----------
dpar, dmer : float, scalars
Interval in degrees between meridians and between parallels
coord : {'E', 'G', 'C'}
The coordinate system of the graticule (make rotation if needed,
using coordinate system of the map if it is defined).
local : bool
If True, draw a local graticule (no rotation is performed, useful for
a gnomonic view, for example)
Notes
-----
Other keyword parameters will be transmitted to the projplot function.
See Also
--------
delgraticules
| def graticule(dpar=None, dmer=None, coord=None, local=None, **kwds):
"""Draw a graticule on the current Axes.
Parameters
----------
dpar, dmer : float, scalars
Interval in degrees between meridians and between parallels
coord : {'E', 'G', 'C'}
The coordinate system of the graticule (make rotation if needed,
using coordinate system of the map if it is defined).
local : bool
If True, draw a local graticule (no rotation is performed, useful for
a gnomonic view, for example)
Notes
-----
Other keyword parameters will be transmitted to the projplot function.
See Also
--------
delgraticules
"""
import pylab
f = pylab.gcf()
wasinteractive = pylab.isinteractive()
pylab.ioff()
try:
if len(f.get_axes()) == 0:
ax = PA.HpxMollweideAxes(f, (0.02, 0.05, 0.96, 0.9), coord=coord)
f.add_axes(ax)
ax.text(
0.86,
0.05,
ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
transform=ax.transAxes,
)
for ax in f.get_axes():
if isinstance(ax, PA.SphericalProjAxes):
ax.graticule(dpar=dpar, dmer=dmer, coord=coord, local=local, **kwds)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
| (dpar=None, dmer=None, coord=None, local=None, **kwds) |
37,687 | healpy.pixelfunc | isnpixok | Return :const:`True` if npix is a valid value for healpix map size, :const:`False` otherwise.
Parameters
----------
npix : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is a valid number of pixel, :const:`False` otherwise
Examples
--------
>>> import healpy as hp
>>> hp.isnpixok(12)
True
>>> hp.isnpixok(768)
True
>>> hp.isnpixok([12, 768, 1002])
array([ True, True, False], dtype=bool)
| def isnpixok(npix):
"""Return :const:`True` if npix is a valid value for healpix map size, :const:`False` otherwise.
Parameters
----------
npix : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is a valid number of pixel, :const:`False` otherwise
Examples
--------
>>> import healpy as hp
>>> hp.isnpixok(12)
True
>>> hp.isnpixok(768)
True
>>> hp.isnpixok([12, 768, 1002])
array([ True, True, False], dtype=bool)
"""
nside = np.sqrt(np.asarray(npix) / 12.0)
return nside == np.floor(nside)
| (npix) |
37,688 | healpy.pixelfunc | isnsideok | Returns :const:`True` if nside is a valid nside parameter, :const:`False` otherwise.
NSIDE needs to be a power of 2 only for nested ordering
Parameters
----------
nside : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is a valid nside, :const:`False` otherwise.
Examples
--------
>>> import healpy as hp
>>> hp.isnsideok(13, nest=True)
False
>>> hp.isnsideok(13, nest=False)
True
>>> hp.isnsideok(32)
True
>>> hp.isnsideok([1, 2, 3, 4, 8, 16], nest=True)
array([ True, True, False, True, True, True], dtype=bool)
| def isnsideok(nside, nest=False):
"""Returns :const:`True` if nside is a valid nside parameter, :const:`False` otherwise.
NSIDE needs to be a power of 2 only for nested ordering
Parameters
----------
nside : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is a valid nside, :const:`False` otherwise.
Examples
--------
>>> import healpy as hp
>>> hp.isnsideok(13, nest=True)
False
>>> hp.isnsideok(13, nest=False)
True
>>> hp.isnsideok(32)
True
>>> hp.isnsideok([1, 2, 3, 4, 8, 16], nest=True)
array([ True, True, False, True, True, True], dtype=bool)
"""
# we use standard bithacks from http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
if hasattr(nside, "__len__"):
if not isinstance(nside, np.ndarray):
nside = np.asarray(nside)
is_nside_ok = (
(nside == nside.astype(int)) & (nside > 0) & (nside <= max_nside)
)
if nest:
is_nside_ok &= (nside.astype(int) & (nside.astype(int) - 1)) == 0
else:
is_nside_ok = nside == int(nside) and 0 < nside <= max_nside
if nest:
is_nside_ok = is_nside_ok and (int(nside) & (int(nside) - 1)) == 0
return is_nside_ok
| (nside, nest=False) |
37,690 | healpy.pixelfunc | ma | Return map as a masked array, with ``badval`` pixels masked.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
copy : bool, optional
If ``True``, a copy of the input map is made.
Returns
-------
a masked array with the same shape as the input map,
masked where input map is close to badval.
See Also
--------
mask_good, mask_bad, numpy.ma.masked_values
Examples
--------
>>> import healpy as hp
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.ma(m)
masked_array(data = [0.0 1.0 2.0 -- 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0],
mask = [False False False True False False False False False False False False],
fill_value = -1.6375e+30)
<BLANKLINE>
| def ma(m, badval=UNSEEN, rtol=1e-5, atol=1e-8, copy=True):
"""Return map as a masked array, with ``badval`` pixels masked.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
copy : bool, optional
If ``True``, a copy of the input map is made.
Returns
-------
a masked array with the same shape as the input map,
masked where input map is close to badval.
See Also
--------
mask_good, mask_bad, numpy.ma.masked_values
Examples
--------
>>> import healpy as hp
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.ma(m)
masked_array(data = [0.0 1.0 2.0 -- 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0],
mask = [False False False True False False False False False False False False],
fill_value = -1.6375e+30)
<BLANKLINE>
"""
return np.ma.masked_values(np.array(m), badval, rtol=rtol, atol=atol, copy=copy)
| (m, badval=-1.6375e+30, rtol=1e-05, atol=1e-08, copy=True) |
37,691 | healpy.sphtfunc | map2alm | Computes the alm of a Healpix map. The input maps must all be
in ring ordering.
For recommendations about how to set `lmax`, `iter`, and weights, see the
`Anafast documentation <https://healpix.sourceforge.io/html/fac_anafast.htm>`_
Pixel values are weighted before applying the transform:
* when you don't specify any weights, the uniform weight value 4*pi/n_pix is used
* with ring weights enabled (use_weights=True), pixels in every ring
are weighted with a uniform value similar to the one above, ring weights are
included in healpy
* with pixel weights (use_pixel_weights=True), every pixel gets an individual weight
Pixel weights provide the most accurate transform, so you should always use them if
possible. However they are not included in healpy and will be automatically downloaded
and cached in ~/.astropy the first time you compute a trasform at a specific nside.
If datapath is specified, healpy will first check that local folder before downloading
the weights.
The easiest way to setup the folder is to clone the healpy-data repository:
git clone --depth 1 https://github.com/healpy/healpy-data
cd healpy-data
bash download_weights_8192.sh
and set datapath to the root of the repository.
Parameters
----------
maps : array-like, shape (Npix,) or (n, Npix)
The input map or a list of n input maps. Must be in ring ordering.
lmax : int, scalar, optional
Maximum l of the power spectrum. Default: 3*nside-1
mmax : int, scalar, optional
Maximum m of the alm. Default: lmax
iter : int, scalar, optional
Number of iteration (default: 3)
pol : bool, optional
If True, assumes input maps are TQU. Output will be TEB alm's.
(input must be 1 or 3 maps)
If False, apply spin 0 harmonic transform to each map.
(input can be any number of maps)
If there is only one input map, it has no effect. Default: True.
use_weights: bool, scalar, optional
If True, use the ring weighting. Default: False.
datapath : None or str, optional
If given, the directory where to find the pixel weights.
See in the docstring above details on how to set it up.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] are not taken into account
use_pixel_weights: bool, optional
If True, use pixel by pixel weighting, healpy will automatically download the weights, if needed
verbose : bool, optional
Deprecated, has not effect.
Returns
-------
alms : array or tuple of array
alm or a tuple of 3 alm (almT, almE, almB) if polarized input.
Notes
-----
The pixels which have the special `UNSEEN` value are replaced by zeros
before spherical harmonic transform. They are converted back to `UNSEEN`
value, so that the input maps are not modified. Each map have its own,
independent mask.
| def synalm(cls, lmax=None, mmax=None, new=False, verbose=True):
"""Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
"""
if not cb.is_seq(cls):
raise TypeError("cls must be an array or a sequence of arrays")
if not cb.is_seq_of_seq(cls, True):
# Only one spectrum
if lmax is None or lmax < 0:
lmax = len(cls) - 1
if mmax is None or mmax < 0:
mmax = lmax
cls_list = [np.asarray(cls, dtype=np.float64)]
szalm = Alm.getsize(lmax, mmax)
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list = [alm]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return alm
# From here, we interpret cls as a list of spectra
cls_list = list(cls)
maxsize = max([len(c) for c in cls if c is not None])
if lmax is None or lmax < 0:
lmax = maxsize - 1
if mmax is None or mmax < 0:
mmax = lmax
Nspec = sphtlib._getn(len(cls_list))
if Nspec <= 0:
if len(cls_list) == 4:
if new: ## new input order: TT EE BB TE -> TT EE BB TE 0 0
cls_list = [cls[0], cls[1], cls[2], cls[3], None, None]
else: ## old input order: TT TE EE BB -> TT TE 0 EE 0 BB
cls_list = [cls[0], cls[1], None, cls[2], None, cls[3]]
Nspec = 3
else:
raise TypeError(
"The sequence of arrays must have either 4 elements "
"or n(n+1)/2 elements (some may be None)"
)
szalm = Alm.getsize(lmax, mmax)
alms_list = []
for i in range(Nspec):
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list.append(alm)
if new: # new input order: input given by diagonal, should be given by row
cls_list = new_to_old_spectra_order(cls_list)
# ensure cls are float64
cls_list = [
(np.asarray(cl, dtype=np.float64) if cl is not None else None)
for cl in cls_list
]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return np.array(alms_list)
| (maps, lmax=None, mmax=None, iter=3, pol=True, use_weights=False, datapath=None, gal_cut=0, use_pixel_weights=False, verbose=True) |
37,692 | healpy.sphtfunc | map2alm_lsq | Runs an iterative map analysis up to (lmax, mmax) and returns the result
including its quality.
Healpix map analysis is often interpreted as "compute the `alm` for which
`alm2map(alm) == map`". Unfortunately this inversion problem is not solvable
in many cases, since `alm` typically has fewer elements than `map`, which
makes the equation system overdetermined, so that a solution only exists
for a vanishingly small subset of all possible maps. (Even if there were
more `alm` elements than map pixels it can happen that the problem is
unsolvable, but this situation should not be relevant for practical use.)
This function aims to compute instead the `alm` for which the L2 norm of
`alm2map(alm) - map` is minimal, i.e. it tries to find the best possible
least-squares approximation. Since this is an iterative procedure, the user
needs to specify a tolerance at which the iteration is stopped and a maximum
iteration count to avoid excessive run times in extreme cases.
Compared to `map2alm` this algorithm has the following advantages and
disadvantages:
- the exact number of iterations need not be specified beforehand, it will
stop automatically once the desired accuracy is reached.
- during calculation it requires more memory than `map2alm`.
Parameters
----------
maps : array-like, shape (Npix,) or (n, Npix)
The input map or a list of n input maps. Must be in ring ordering.
lmax, mmax : int
The desired lmax and mmax parameters for the analysis
pol : bool, optional
If True, assumes input maps are TQU. Output will be TEB alm's.
(input must be 1 or 3 maps)
If False, apply spin 0 harmonic transform to each map.
(input can be any number of maps)
If there is only one input map, it has no effect. Default: True.
tol : float
The desired accuracy for the result. Once this is reached, the iteration
stops.
maxiter : int
maximum iteration count after which the minimization is stopped
Returns
-------
alm : numpy.ndarray(complex)
The reconstructed a_lm coefficients
rel_res : float
The norm of the residual map (i.e. `map-alm2map(alm)`), divided by the
norm of `maps`. This is a measure for the fraction of the map signal that
could not be modeled by the a_lm
n_iter : int
the number of iterations required
| def map2alm_lsq(maps, lmax, mmax, pol=True, tol=1e-10, maxiter=20):
"""Runs an iterative map analysis up to (lmax, mmax) and returns the result
including its quality.
Healpix map analysis is often interpreted as "compute the `alm` for which
`alm2map(alm) == map`". Unfortunately this inversion problem is not solvable
in many cases, since `alm` typically has fewer elements than `map`, which
makes the equation system overdetermined, so that a solution only exists
for a vanishingly small subset of all possible maps. (Even if there were
more `alm` elements than map pixels it can happen that the problem is
unsolvable, but this situation should not be relevant for practical use.)
This function aims to compute instead the `alm` for which the L2 norm of
`alm2map(alm) - map` is minimal, i.e. it tries to find the best possible
least-squares approximation. Since this is an iterative procedure, the user
needs to specify a tolerance at which the iteration is stopped and a maximum
iteration count to avoid excessive run times in extreme cases.
Compared to `map2alm` this algorithm has the following advantages and
disadvantages:
- the exact number of iterations need not be specified beforehand, it will
stop automatically once the desired accuracy is reached.
- during calculation it requires more memory than `map2alm`.
Parameters
----------
maps : array-like, shape (Npix,) or (n, Npix)
The input map or a list of n input maps. Must be in ring ordering.
lmax, mmax : int
The desired lmax and mmax parameters for the analysis
pol : bool, optional
If True, assumes input maps are TQU. Output will be TEB alm's.
(input must be 1 or 3 maps)
If False, apply spin 0 harmonic transform to each map.
(input can be any number of maps)
If there is only one input map, it has no effect. Default: True.
tol : float
The desired accuracy for the result. Once this is reached, the iteration
stops.
maxiter : int
maximum iteration count after which the minimization is stopped
Returns
-------
alm : numpy.ndarray(complex)
The reconstructed a_lm coefficients
rel_res : float
The norm of the residual map (i.e. `map-alm2map(alm)`), divided by the
norm of `maps`. This is a measure for the fraction of the map signal that
could not be modeled by the a_lm
n_iter : int
the number of iterations required
"""
from scipy.sparse.linalg import LinearOperator, lsqr, lsmr
from scipy.linalg import norm
from .pixelfunc import npix2nside
maps = ma_to_array(maps)
info = maptype(maps)
ncomp = 1 if info == 0 else info
maps = np.array(maps)
npix = maps.size / ncomp
nside = pixelfunc.get_nside(maps)
check_max_nside(nside)
# helper functions to convert between real- and complex-valued a_lm
def alm2realalm(alm):
alm = alm.reshape((ncomp, -1))
res = np.zeros((ncomp, alm.shape[1] * 2 - lmax - 1))
for i in range(ncomp):
res[i, 0 : lmax + 1] = alm[i, 0 : lmax + 1].real
res[i, lmax + 1 :] = alm[i, lmax + 1 :].view(np.float64) * np.sqrt(2.0)
return res.reshape((-1,))
def realalm2alm(alm):
alm = np.array(alm).reshape((ncomp, -1))
res = np.zeros((ncomp, (alm.shape[1] + lmax + 1) // 2), dtype=np.complex128)
for i in range(ncomp):
res[i, 0 : lmax + 1] = alm[i, 0 : lmax + 1]
res[i, lmax + 1 :] = alm[i, lmax + 1 :].view(np.complex128) * (
np.sqrt(2.0) / 2
)
if ncomp == 1:
res = res[0]
return res
def a2m2(x):
talm = realalm2alm(x)
res = alm2map(talm, lmax=lmax, nside=nside, pol=pol)
return res.reshape((-1,))
def m2a2(x):
talm = map2alm(x.reshape((ncomp, -1)), lmax=lmax, iter=0, pol=pol)
talm *= (12 * nside ** 2) / (4 * np.pi)
res = alm2realalm(talm)
return res
# initial guess
alm0 = m2a2(maps) / npix * (4 * np.pi)
op = LinearOperator(
matvec=a2m2, rmatvec=m2a2, shape=(len(maps) * maps[0].size, alm0.size)
)
res = lsqr(
A=op,
b=maps.reshape((-1,)),
x0=alm0,
atol=tol,
btol=tol,
iter_lim=maxiter,
show=False,
)
# res = lsmr(A=op, b=maps, x0=alm0, atol=tol, btol=tol, maxiter=maxiter, show=False)
return realalm2alm(res[0]), res[3] / norm(maps.reshape((-1,))), res[2]
| (maps, lmax, mmax, pol=True, tol=1e-10, maxiter=20) |
37,693 | healpy.pixelfunc | maptype | Describe the type of the map (valid, single, sequence of maps).
Checks : the number of maps, that all maps have same length and that this
length is a valid map size (using :func:`isnpixok`).
Parameters
----------
m : sequence
the map to get info from
Returns
-------
info : int
-1 if the given object is not a valid map, 0 if it is a single map,
*info* > 0 if it is a sequence of maps (*info* is then the number of
maps)
Examples
--------
>>> import healpy as hp
>>> hp.pixelfunc.maptype(np.arange(12))
0
>>> hp.pixelfunc.maptype([np.arange(12), np.arange(12)])
2
| def maptype(m):
"""Describe the type of the map (valid, single, sequence of maps).
Checks : the number of maps, that all maps have same length and that this
length is a valid map size (using :func:`isnpixok`).
Parameters
----------
m : sequence
the map to get info from
Returns
-------
info : int
-1 if the given object is not a valid map, 0 if it is a single map,
*info* > 0 if it is a sequence of maps (*info* is then the number of
maps)
Examples
--------
>>> import healpy as hp
>>> hp.pixelfunc.maptype(np.arange(12))
0
>>> hp.pixelfunc.maptype([np.arange(12), np.arange(12)])
2
"""
if not hasattr(m, "__len__"):
raise TypeError("input map is a scalar")
if len(m) == 0:
raise TypeError("input map has length zero")
try:
npix = len(m[0])
except TypeError:
npix = None
if npix is not None:
for mm in m[1:]:
if len(mm) != npix:
raise TypeError("input maps have different npix")
if isnpixok(len(m[0])):
return len(m)
else:
raise TypeError("bad number of pixels")
else:
if isnpixok(len(m)):
return 0
else:
raise TypeError("bad number of pixels")
| (m) |
37,694 | healpy.pixelfunc | mask_bad | Returns a bool array with ``True`` where m is close to badval.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
Returns
-------
mask
a bool array with the same shape as the input map, ``True`` where input map is
close to badval, and ``False`` elsewhere.
See Also
--------
mask_good, ma
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.mask_bad(m)
array([False, False, False, True, False, False, False, False, False,
False, False, False], dtype=bool)
| def mask_bad(m, badval=UNSEEN, rtol=1.0e-5, atol=1.0e-8):
"""Returns a bool array with ``True`` where m is close to badval.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
Returns
-------
mask
a bool array with the same shape as the input map, ``True`` where input map is
close to badval, and ``False`` elsewhere.
See Also
--------
mask_good, ma
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.mask_bad(m)
array([False, False, False, True, False, False, False, False, False,
False, False, False], dtype=bool)
"""
m = np.asarray(m)
atol = np.absolute(atol)
rtol = np.absolute(rtol)
return np.absolute(m - badval) <= atol + rtol * np.absolute(badval)
| (m, badval=-1.6375e+30, rtol=1e-05, atol=1e-08) |
37,695 | healpy.pixelfunc | mask_good | Returns a bool array with ``False`` where m is close to badval.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
Returns
-------
a bool array with the same shape as the input map, ``False`` where input map is
close to badval, and ``True`` elsewhere.
See Also
--------
mask_bad, ma
Examples
--------
>>> import healpy as hp
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.mask_good(m)
array([ True, True, True, False, True, True, True, True, True,
True, True, True], dtype=bool)
| def mask_good(m, badval=UNSEEN, rtol=1.0e-5, atol=1.0e-8):
"""Returns a bool array with ``False`` where m is close to badval.
Parameters
----------
m : a map (may be a sequence of maps)
badval : float, optional
The value of the pixel considered as bad (:const:`UNSEEN` by default)
rtol : float, optional
The relative tolerance
atol : float, optional
The absolute tolerance
Returns
-------
a bool array with the same shape as the input map, ``False`` where input map is
close to badval, and ``True`` elsewhere.
See Also
--------
mask_bad, ma
Examples
--------
>>> import healpy as hp
>>> m = np.arange(12.)
>>> m[3] = hp.UNSEEN
>>> hp.mask_good(m)
array([ True, True, True, False, True, True, True, True, True,
True, True, True], dtype=bool)
"""
m = np.asarray(m)
atol = np.absolute(atol)
rtol = np.absolute(rtol)
return np.absolute(m - badval) > atol + rtol * np.absolute(badval)
| (m, badval=-1.6375e+30, rtol=1e-05, atol=1e-08) |
37,696 | healpy.pixelfunc | max_pixrad | Maximum angular distance between any pixel center and its corners
Parameters
----------
nside : int
the nside to work with
degrees : bool
if True, returns pixel radius in degrees, in radians otherwise
Returns
-------
rads: double
angular distance (in radians or degrees)
Examples
--------
>>> '%.14f' % max_pixrad(1)
'0.84106867056793'
>>> '%.14f' % max_pixrad(16)
'0.06601476143251'
| def max_pixrad(nside, degrees=False):
"""Maximum angular distance between any pixel center and its corners
Parameters
----------
nside : int
the nside to work with
degrees : bool
if True, returns pixel radius in degrees, in radians otherwise
Returns
-------
rads: double
angular distance (in radians or degrees)
Examples
--------
>>> '%.14f' % max_pixrad(1)
'0.84106867056793'
>>> '%.14f' % max_pixrad(16)
'0.06601476143251'
"""
check_nside(nside, nest=False)
if degrees:
return np.rad2deg(pixlib._max_pixrad(nside))
return pixlib._max_pixrad(nside)
| (nside, degrees=False) |
37,697 | healpy.visufunc | mollview | Plot a 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.
fig : int or None, optional
The figure number to use. Default: create a new figure
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
title : str, optional
The title of the plot. Default: 'Mollweide view'
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 right, 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]
format : str, optional
The format of the scale label. Default: '%g'
format2 : str, optional
Format of the pixel value under mouse. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
notext : bool, optional
If True, no text is printed around the map
norm : {'hist', 'log', None}
Color normalization, hist= histogram equalized color mapping,
log= logarithmic color mapping, default: None (linear color mapping)
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by a MollweideAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a MollweideAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
return_projected_map : bool
if True returns the projected map in a 2d numpy array
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See Also
--------
gnomview, cartview, orthview, azeqview
| def mollview(
map=None,
fig=None,
rot=None,
coord=None,
unit="",
xsize=800,
title="Mollweide view",
nest=False,
min=None,
max=None,
flip="astro",
remove_dip=False,
remove_mono=False,
gal_cut=0,
format="%g",
format2="%g",
cbar=True,
cmap=None,
badcolor="gray",
bgcolor="white",
notext=False,
norm=None,
hold=False,
reuse_axes=False,
margins=None,
sub=None,
nlocs=2,
return_projected_map=False,
alpha=None,
):
"""Plot a 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.
fig : int or None, optional
The figure number to use. Default: create a new figure
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
title : str, optional
The title of the plot. Default: 'Mollweide view'
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 right, 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]
format : str, optional
The format of the scale label. Default: '%g'
format2 : str, optional
Format of the pixel value under mouse. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
notext : bool, optional
If True, no text is printed around the map
norm : {'hist', 'log', None}
Color normalization, hist= histogram equalized color mapping,
log= logarithmic color mapping, default: None (linear color mapping)
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by a MollweideAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a MollweideAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
return_projected_map : bool
if True returns the projected map in a 2d numpy array
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See Also
--------
gnomview, cartview, orthview, azeqview
"""
# Create the figure
import pylab
if map is None:
map = np.zeros(12) + np.inf
cbar = False
# Ensure that the nside is valid
nside = pixelfunc.get_nside(map)
pixelfunc.check_nside(nside, nest=nest)
if not (hold or sub or reuse_axes):
f = pylab.figure(fig, figsize=(8.5, 5.4))
if not margins:
margins = (0.02, 0.05, 0.02, 0.05)
extent = (0.0, 0.0, 1.0, 1.0)
elif hold:
f = pylab.gcf()
left, bottom, right, top = np.array(f.gca().get_position()).ravel()
if not margins:
margins = (0.0, 0.0, 0.0, 0.0)
extent = (left, bottom, right - left, top - bottom)
f.delaxes(f.gca())
elif reuse_axes:
f = pylab.gcf()
else: # using subplot syntax
f = pylab.gcf()
if hasattr(sub, "__len__"):
nrows, ncols, idx = sub
else:
nrows, ncols, idx = sub // 100, (sub % 100) // 10, (sub % 10)
if idx < 1 or idx > ncols * nrows:
raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
c, r = (idx - 1) % ncols, (idx - 1) // ncols
if not margins:
margins = (0.01, 0.0, 0.0, 0.02)
extent = (
c * 1.0 / ncols,
1.0 - (r + 1) * 1.0 / nrows,
1.0 / ncols,
1.0 / nrows,
)
if not reuse_axes:
extent = (
extent[0] + margins[0],
extent[1] + margins[1],
extent[2] - margins[2] - margins[0],
extent[3] - margins[3] - margins[1],
)
# Starting to draw : turn interactive off
wasinteractive = pylab.isinteractive()
pylab.ioff()
try:
map = pixelfunc.ma_to_array(map)
if alpha is not None:
alpha = pixelfunc.ma_to_array(alpha)
if reuse_axes:
ax = f.gca()
else:
ax = PA.HpxMollweideAxes(
f, extent, coord=coord, rot=rot, format=format2, flipconv=flip
)
f.add_axes(ax)
if remove_dip:
map = pixelfunc.remove_dipole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
elif remove_mono:
map = pixelfunc.remove_monopole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
img = ax.projmap(
map,
nest=nest,
xsize=xsize,
coord=coord,
vmin=min,
vmax=max,
cmap=cmap,
badcolor=badcolor,
bgcolor=bgcolor,
norm=norm,
alpha=alpha,
)
if cbar:
im = ax.get_images()[0]
b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
mappable = plt.cm.ScalarMappable(
norm=matplotlib.colors.Normalize(vmin=im.norm.vmin, vmax=im.norm.vmax),
cmap=cmap,
)
if matplotlib.__version__ >= "0.91.0":
cb = f.colorbar(
mappable,
ax=ax,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(nlocs, norm),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
else:
# for older matplotlib versions, no ax kwarg
cb = f.colorbar(
mappable,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(nlocs, norm),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
cb.solids.set_rasterized(True)
ax.set_title(title)
if not notext:
ax.text(
0.86,
0.05,
ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
transform=ax.transAxes,
)
if cbar:
cb.ax.text(
0.5,
-1.0,
unit,
fontsize=14,
transform=cb.ax.transAxes,
ha="center",
va="center",
)
f.sca(ax)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
if return_projected_map:
return img
| (map=None, fig=None, rot=None, coord=None, unit='', xsize=800, title='Mollweide view', nest=False, min=None, max=None, flip='astro', remove_dip=False, remove_mono=False, gal_cut=0, format='%g', format2='%g', cbar=True, cmap=None, badcolor='gray', bgcolor='white', notext=False, norm=None, hold=False, reuse_axes=False, margins=None, sub=None, nlocs=2, return_projected_map=False, alpha=None) |
37,698 | healpy.zoomtool | mollzoom | Interactive mollweide plot with zoomed gnomview.
Parameters:
-----------
map : float, array-like shape (Npix,)
An array containing the map,
supports masked maps, see the `ma` function.
if None, use map with inf value (white map), useful for
overplotting
fig : a figure number.
Default: create a new figure
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
title : str, optional
The title of the plot. Default: 'Mollweide view'
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)
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]
format : str, optional
The format of the scale label. Default: '%g'
| def mollzoom(
map=None,
fig=None,
rot=None,
coord=None,
unit="",
xsize=800,
title="Mollweide view",
nest=False,
min=None,
max=None,
flip="astro",
remove_dip=False,
remove_mono=False,
gal_cut=0,
format="%g",
cmap=None,
norm=None,
hold=False,
margins=None,
sub=None,
):
"""Interactive mollweide plot with zoomed gnomview.
Parameters:
-----------
map : float, array-like shape (Npix,)
An array containing the map,
supports masked maps, see the `ma` function.
if None, use map with inf value (white map), useful for
overplotting
fig : a figure number.
Default: create a new figure
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
title : str, optional
The title of the plot. Default: 'Mollweide view'
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)
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]
format : str, optional
The format of the scale label. Default: '%g'
"""
import pylab
# Ensure that the nside is valid
nside = pixelfunc.get_nside(map)
pixelfunc.check_nside(nside, nest=nest)
# create the figure (if interactive, it will open the window now)
f = pylab.figure(fig, figsize=(10.5, 5.4))
extent = (0.02, 0.25, 0.56, 0.72)
# Starting to draw : turn interactive off
wasinteractive = pylab.isinteractive()
pylab.ioff()
try:
if map is None:
map = np.zeros(12) + np.inf
map = pixelfunc.ma_to_array(map)
ax = PA.HpxMollweideAxes(
f, extent, coord=coord, rot=rot, format=format, flipconv=flip
)
f.add_axes(ax)
if remove_dip:
map = pixelfunc.remove_dipole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
elif remove_mono:
map = pixelfunc.remove_monopole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
ax.projmap(
map,
nest=nest,
xsize=xsize,
coord=coord,
vmin=min,
vmax=max,
cmap=cmap,
norm=norm,
)
im = ax.get_images()[0]
b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
if matplotlib.__version__ >= "0.91.0":
cb = f.colorbar(
ax.get_images()[0],
ax=ax,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
)
else:
# for older matplotlib versions, no ax kwarg
cb = f.colorbar(
ax.get_images()[0],
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
)
ax.set_title(title)
ax.text(
0.86,
0.05,
ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
transform=ax.transAxes,
)
cb.ax.text(
1.05,
0.30,
unit,
fontsize=14,
fontweight="bold",
transform=cb.ax.transAxes,
ha="left",
va="center",
)
f.sca(ax)
## Gnomonic axes
# extent = (0.02,0.25,0.56,0.72)
g_xsize = 600
g_reso = 1.0
extent = (0.60, 0.04, 0.38, 0.94)
g_ax = PA.HpxGnomonicAxes(
f, extent, coord=coord, rot=rot, format=format, flipconv=flip
)
f.add_axes(g_ax)
if remove_dip:
map = pixelfunc.remove_dipole(map, gal_cut=gal_cut, nest=nest, copy=True)
elif remove_mono:
map = pixelfunc.remove_monopole(map, gal_cut=gal_cut, nest=nest, copy=True)
g_ax.projmap(
map,
nest=nest,
coord=coord,
vmin=min,
vmax=max,
xsize=g_xsize,
ysize=g_xsize,
reso=g_reso,
cmap=cmap,
norm=norm,
)
im = g_ax.get_images()[0]
b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
if matplotlib.__version__ >= "0.91.0":
cb = f.colorbar(
g_ax.get_images()[0],
ax=g_ax,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.08,
fraction=0.1,
boundaries=b,
values=v,
)
else:
cb = f.colorbar(
g_ax.get_images()[0],
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.08,
fraction=0.1,
boundaries=b,
values=v,
)
g_ax.set_title(title)
g_ax.text(
-0.07,
0.02,
"%g '/pix, %dx%d pix"
% (
g_ax.proj.arrayinfo["reso"],
g_ax.proj.arrayinfo["xsize"],
g_ax.proj.arrayinfo["ysize"],
),
fontsize=12,
verticalalignment="bottom",
transform=g_ax.transAxes,
rotation=90,
)
g_ax.text(
-0.07,
0.8,
g_ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
rotation=90,
transform=g_ax.transAxes,
)
lon, lat = np.around(g_ax.proj.get_center(lonlat=True), g_ax._coordprec)
g_ax.text(
0.5,
-0.03,
"on (%g,%g)" % (lon, lat),
verticalalignment="center",
horizontalalignment="center",
transform=g_ax.transAxes,
)
cb.ax.text(
1.05,
0.30,
unit,
fontsize=14,
fontweight="bold",
transform=cb.ax.transAxes,
ha="left",
va="center",
)
# Add graticule info axes
grat_ax = pylab.axes([0.25, 0.02, 0.22, 0.25])
grat_ax.axis("off")
# Add help text
help_ax = pylab.axes([0.02, 0.02, 0.22, 0.25])
help_ax.axis("off")
t = help_ax.transAxes
help_ax.text(0.1, 0.8, "r/t .... zoom out/in", transform=t, va="baseline")
help_ax.text(0.1, 0.65, "p/v .... print coord/val", transform=t, va="baseline")
help_ax.text(0.1, 0.5, "c ...... go to center", transform=t, va="baseline")
help_ax.text(0.1, 0.35, "f ...... next color scale", transform=t, va="baseline")
help_ax.text(
0.1, 0.2, "k ...... save current scale", transform=t, va="baseline"
)
help_ax.text(0.1, 0.05, "g ...... toggle graticule", transform=t, va="baseline")
f.sca(g_ax)
# Set up the zoom capability
zt = ZoomTool(map, fig=f.number, nest=nest, cmap=cmap, norm=norm, coord=coord)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
| (map=None, fig=None, rot=None, coord=None, unit='', xsize=800, title='Mollweide view', nest=False, min=None, max=None, flip='astro', remove_dip=False, remove_mono=False, gal_cut=0, format='%g', cmap=None, norm=None, hold=False, margins=None, sub=None) |
37,699 | healpy.pixelfunc | nest2ring | Convert pixel number from NESTED ordering to RING ordering.
Parameters
----------
nside : int, scalar or array-like
the healpix nside parameter
ipix : int, scalar or array-like
the pixel number in NESTED scheme
Returns
-------
ipix : int, scalar or array-like
the pixel number in RING scheme
See Also
--------
ring2nest, reorder
Examples
--------
>>> import healpy as hp
>>> hp.nest2ring(16, 1130)
1504
>>> print(hp.nest2ring(2, np.arange(10)))
[13 5 4 0 15 7 6 1 17 9]
>>> print(hp.nest2ring([1, 2, 4, 8], 11))
[ 11 2 12 211]
| def nest2ring(nside, ipix):
"""Convert pixel number from NESTED ordering to RING ordering.
Parameters
----------
nside : int, scalar or array-like
the healpix nside parameter
ipix : int, scalar or array-like
the pixel number in NESTED scheme
Returns
-------
ipix : int, scalar or array-like
the pixel number in RING scheme
See Also
--------
ring2nest, reorder
Examples
--------
>>> import healpy as hp
>>> hp.nest2ring(16, 1130)
1504
>>> print(hp.nest2ring(2, np.arange(10)))
[13 5 4 0 15 7 6 1 17 9]
>>> print(hp.nest2ring([1, 2, 4, 8], 11))
[ 11 2 12 211]
"""
check_nside(nside, nest=True)
return pixlib._nest2ring(nside, ipix)
| (nside, ipix) |
37,700 | healpy.newvisufunc | newprojplot | newprojplot is a wrapper around :func:`matplotlib.Axes.plot` to support
colatitude theta and longitude phi and take into account the longitude convention
(see the `flip` keyword of :func:`projview`)
You can call this function as::
newprojplot(theta, phi) # plot a line going through points at coord (theta, phi)
newprojplot(theta, phi, 'bo') # plot 'o' in blue at coord (theta, phi)
Parameters
----------
theta, phi : float, array-like
Coordinates of point to plot in radians.
fmt : str
A format string (see :func:`matplotlib.Axes.plot` for details)
Notes
-----
Other keywords are passed to :func:`matplotlib.Axes.plot`.
| def newprojplot(theta, phi, fmt=None, **kwargs):
"""newprojplot is a wrapper around :func:`matplotlib.Axes.plot` to support
colatitude theta and longitude phi and take into account the longitude convention
(see the `flip` keyword of :func:`projview`)
You can call this function as::
newprojplot(theta, phi) # plot a line going through points at coord (theta, phi)
newprojplot(theta, phi, 'bo') # plot 'o' in blue at coord (theta, phi)
Parameters
----------
theta, phi : float, array-like
Coordinates of point to plot in radians.
fmt : str
A format string (see :func:`matplotlib.Axes.plot` for details)
Notes
-----
Other keywords are passed to :func:`matplotlib.Axes.plot`.
"""
import matplotlib.pyplot as plt
ax = plt.gca()
flip = getattr(ax, "healpy_flip", "astro")
longitude, latitude = lonlat(theta, phi)
if flip == "astro":
longitude = longitude * -1
if fmt is None:
ret = plt.plot(longitude, latitude, **kwargs)
else:
ret = plt.plot(longitude, latitude, fmt, **kwargs)
return ret
| (theta, phi, fmt=None, **kwargs) |
37,702 | healpy.pixelfunc | npix2nside | Give the nside parameter for the given number of pixels.
Parameters
----------
npix : int
the number of pixels
Returns
-------
nside : int
the nside parameter corresponding to npix
Notes
-----
Raise a ValueError exception if number of pixel does not correspond to
the number of pixel of a healpix map.
Examples
--------
>>> import healpy as hp
>>> hp.npix2nside(768)
8
>>> np.all([hp.npix2nside(12 * nside**2) == nside for nside in [2**n for n in range(12)]])
True
>>> hp.npix2nside(1000)
Traceback (most recent call last):
...
ValueError: Wrong pixel number (it is not 12*nside**2)
| def npix2nside(npix):
"""Give the nside parameter for the given number of pixels.
Parameters
----------
npix : int
the number of pixels
Returns
-------
nside : int
the nside parameter corresponding to npix
Notes
-----
Raise a ValueError exception if number of pixel does not correspond to
the number of pixel of a healpix map.
Examples
--------
>>> import healpy as hp
>>> hp.npix2nside(768)
8
>>> np.all([hp.npix2nside(12 * nside**2) == nside for nside in [2**n for n in range(12)]])
True
>>> hp.npix2nside(1000)
Traceback (most recent call last):
...
ValueError: Wrong pixel number (it is not 12*nside**2)
"""
if not isnpixok(npix):
raise ValueError("Wrong pixel number (it is not 12*nside**2)")
return int(np.sqrt(npix / 12.0))
| (npix) |
37,703 | healpy.pixelfunc | npix2order | Give the resolution order for the given number of pixels.
Parameters
----------
npix : int
the number of pixels
Returns
-------
order : int
corresponding resolution order
Notes
-----
A convenience function that successively applies npix2nside then nside2order to npix.
Examples
--------
>>> import healpy as hp
>>> hp.npix2order(768)
3
>>> np.all([hp.npix2order(12 * 4**order) == order for order in range(12)])
True
>>> hp.npix2order(1000)
Traceback (most recent call last):
...
ValueError: Wrong pixel number (it is not 12*nside**2)
| def npix2order(npix):
"""Give the resolution order for the given number of pixels.
Parameters
----------
npix : int
the number of pixels
Returns
-------
order : int
corresponding resolution order
Notes
-----
A convenience function that successively applies npix2nside then nside2order to npix.
Examples
--------
>>> import healpy as hp
>>> hp.npix2order(768)
3
>>> np.all([hp.npix2order(12 * 4**order) == order for order in range(12)])
True
>>> hp.npix2order(1000)
Traceback (most recent call last):
...
ValueError: Wrong pixel number (it is not 12*nside**2)
"""
nside = npix2nside(npix)
order = nside2order(nside)
return order
| (npix) |
37,704 | healpy.pixelfunc | nside2npix | Give the number of pixels for the given nside.
Parameters
----------
nside : int
healpix nside parameter
Returns
-------
npix : int
corresponding number of pixels
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> hp.nside2npix(8)
768
>>> np.all([hp.nside2npix(nside) == 12 * nside**2 for nside in [2**n for n in range(12)]])
True
>>> hp.nside2npix(7)
588
| def nside2npix(nside):
"""Give the number of pixels for the given nside.
Parameters
----------
nside : int
healpix nside parameter
Returns
-------
npix : int
corresponding number of pixels
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> hp.nside2npix(8)
768
>>> np.all([hp.nside2npix(nside) == 12 * nside**2 for nside in [2**n for n in range(12)]])
True
>>> hp.nside2npix(7)
588
"""
return 12 * nside * nside
| (nside) |
37,705 | healpy.pixelfunc | nside2order | Give the resolution order for a given nside.
Parameters
----------
nside : int
healpix nside parameter; an exception is raised if nside is not valid
(nside must be a power of 2, less than 2**30)
Returns
-------
order : int
corresponding order where nside = 2**(order)
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> hp.nside2order(128)
7
>>> np.all([hp.nside2order(2**o) == o for o in range(30)])
True
>>> hp.nside2order(7)
Traceback (most recent call last):
...
ValueError: 7 is not a valid nside parameter (must be a power of 2, less than 2**30)
| def nside2order(nside):
"""Give the resolution order for a given nside.
Parameters
----------
nside : int
healpix nside parameter; an exception is raised if nside is not valid
(nside must be a power of 2, less than 2**30)
Returns
-------
order : int
corresponding order where nside = 2**(order)
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> import numpy as np
>>> hp.nside2order(128)
7
>>> np.all([hp.nside2order(2**o) == o for o in range(30)])
True
>>> hp.nside2order(7)
Traceback (most recent call last):
...
ValueError: 7 is not a valid nside parameter (must be a power of 2, less than 2**30)
"""
check_nside(nside, nest=True)
return len("{0:b}".format(nside)) - 1
| (nside) |
37,706 | healpy.pixelfunc | nside2pixarea | Give pixel area given nside in square radians or square degrees.
Parameters
----------
nside : int
healpix nside parameter, must be a power of 2, less than 2**30
degrees : bool
if True, returns pixel area in square degrees, in square radians otherwise
Returns
-------
pixarea : float
pixel area in square radian or square degree
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> hp.nside2pixarea(128, degrees = True) # doctest: +FLOAT_CMP
0.2098234113027917
>>> hp.nside2pixarea(256)
1.5978966540475428e-05
>>> hp.nside2pixarea(7)
0.021371378595848933
| def nside2pixarea(nside, degrees=False):
"""Give pixel area given nside in square radians or square degrees.
Parameters
----------
nside : int
healpix nside parameter, must be a power of 2, less than 2**30
degrees : bool
if True, returns pixel area in square degrees, in square radians otherwise
Returns
-------
pixarea : float
pixel area in square radian or square degree
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> hp.nside2pixarea(128, degrees = True) # doctest: +FLOAT_CMP
0.2098234113027917
>>> hp.nside2pixarea(256)
1.5978966540475428e-05
>>> hp.nside2pixarea(7)
0.021371378595848933
"""
pixarea = 4 * np.pi / nside2npix(nside)
if degrees:
pixarea = np.rad2deg(np.rad2deg(pixarea))
return pixarea
| (nside, degrees=False) |
37,707 | healpy.pixelfunc | nside2resol | Give approximate resolution (pixel size in radian or arcmin) for nside.
Resolution is just the square root of the pixel area, which is a gross
approximation given the different pixel shapes
Parameters
----------
nside : int
healpix nside parameter, must be a power of 2, less than 2**30
arcmin : bool
if True, return resolution in arcmin, otherwise in radian
Returns
-------
resol : float
approximate pixel size in radians or arcmin
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> hp.nside2resol(128, arcmin = True) # doctest: +FLOAT_CMP
27.483891294539248
>>> hp.nside2resol(256)
0.0039973699529159707
>>> hp.nside2resol(7)
0.1461895297066412
| def nside2resol(nside, arcmin=False):
"""Give approximate resolution (pixel size in radian or arcmin) for nside.
Resolution is just the square root of the pixel area, which is a gross
approximation given the different pixel shapes
Parameters
----------
nside : int
healpix nside parameter, must be a power of 2, less than 2**30
arcmin : bool
if True, return resolution in arcmin, otherwise in radian
Returns
-------
resol : float
approximate pixel size in radians or arcmin
Notes
-----
Raise a ValueError exception if nside is not valid.
Examples
--------
>>> import healpy as hp
>>> hp.nside2resol(128, arcmin = True) # doctest: +FLOAT_CMP
27.483891294539248
>>> hp.nside2resol(256)
0.0039973699529159707
>>> hp.nside2resol(7)
0.1461895297066412
"""
resol = np.sqrt(nside2pixarea(nside))
if arcmin:
resol = np.rad2deg(resol) * 60
return resol
| (nside, arcmin=False) |
37,708 | healpy.pixelfunc | order2npix | Give the number of pixels for the given resolution order.
Parameters
----------
order : int
the resolution order
Returns
-------
npix : int
corresponding number of pixels
Notes
-----
A convenience function that successively applies order2nside then nside2npix to order.
Examples
--------
>>> import healpy as hp
>>> hp.order2npix(7)
196608
>>> print(hp.order2npix(np.arange(8)))
[ 12 48 192 768 3072 12288 49152 196608]
>>> hp.order2npix(31)
Traceback (most recent call last):
...
ValueError: 2147483648 is not a valid nside parameter (must be a power of 2, less than 2**30)
| def order2npix(order):
"""Give the number of pixels for the given resolution order.
Parameters
----------
order : int
the resolution order
Returns
-------
npix : int
corresponding number of pixels
Notes
-----
A convenience function that successively applies order2nside then nside2npix to order.
Examples
--------
>>> import healpy as hp
>>> hp.order2npix(7)
196608
>>> print(hp.order2npix(np.arange(8)))
[ 12 48 192 768 3072 12288 49152 196608]
>>> hp.order2npix(31)
Traceback (most recent call last):
...
ValueError: 2147483648 is not a valid nside parameter (must be a power of 2, less than 2**30)
"""
nside = order2nside(order)
npix = nside2npix(nside)
return npix
| (order) |
37,709 | healpy.pixelfunc | order2nside | Give the nside parameter for the given resolution order.
Parameters
----------
order : int
the resolution order
Returns
-------
nside : int
the nside parameter corresponding to order
Notes
-----
Raise a ValueError exception if order produces an nside out of range.
Examples
--------
>>> import healpy as hp
>>> hp.order2nside(7)
128
>>> print(hp.order2nside(np.arange(8)))
[ 1 2 4 8 16 32 64 128]
>>> hp.order2nside(31)
Traceback (most recent call last):
...
ValueError: 2147483648 is not a valid nside parameter (must be a power of 2, less than 2**30)
| def order2nside(order):
"""Give the nside parameter for the given resolution order.
Parameters
----------
order : int
the resolution order
Returns
-------
nside : int
the nside parameter corresponding to order
Notes
-----
Raise a ValueError exception if order produces an nside out of range.
Examples
--------
>>> import healpy as hp
>>> hp.order2nside(7)
128
>>> print(hp.order2nside(np.arange(8)))
[ 1 2 4 8 16 32 64 128]
>>> hp.order2nside(31)
Traceback (most recent call last):
...
ValueError: 2147483648 is not a valid nside parameter (must be a power of 2, less than 2**30)
"""
nside = 1 << order
check_nside(nside, nest=True)
return nside
| (order) |
37,710 | healpy.visufunc | orthview | Plot a healpix map (given as an array) in Orthographic projection.
Parameters
----------
map : float, array-like or None
An array containing the map.
If None, will display a blank map, useful for overplotting.
fig : int or None, optional
The figure number to use. Default: create a new figure
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.
half_sky : bool, optional
Plot only one side of the sphere. Default: False
unit : str, optional
A text describing the unit of the data. Default: ''
xsize : int, optional
The size of the image. Default: 800
title : str, optional
The title of the plot. Default: 'Orthographic view'
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)
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]
format : str, optional
The format of the scale label. Default: '%g'
format2 : str, optional
Format of the pixel value under mouse. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
notext : bool, optional
If True, no text is printed around the map
norm : {'hist', 'log', None}
Color normalization, hist= histogram equalized color mapping,
log= logarithmic color mapping, default: None (linear color mapping)
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by an OrthographicAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a OrthographicAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
return_projected_map : bool
if True returns the projected map in a 2d numpy array
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See Also
--------
mollview, gnomview, cartview, azeqview
| def orthview(
map=None,
fig=None,
rot=None,
coord=None,
unit="",
xsize=800,
half_sky=False,
title="Orthographic view",
nest=False,
min=None,
max=None,
flip="astro",
remove_dip=False,
remove_mono=False,
gal_cut=0,
format="%g",
format2="%g",
cbar=True,
cmap=None,
badcolor="gray",
bgcolor="white",
notext=False,
norm=None,
hold=False,
margins=None,
sub=None,
reuse_axes=False,
return_projected_map=False,
alpha=None,
):
"""Plot a healpix map (given as an array) in Orthographic projection.
Parameters
----------
map : float, array-like or None
An array containing the map.
If None, will display a blank map, useful for overplotting.
fig : int or None, optional
The figure number to use. Default: create a new figure
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.
half_sky : bool, optional
Plot only one side of the sphere. Default: False
unit : str, optional
A text describing the unit of the data. Default: ''
xsize : int, optional
The size of the image. Default: 800
title : str, optional
The title of the plot. Default: 'Orthographic view'
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)
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]
format : str, optional
The format of the scale label. Default: '%g'
format2 : str, optional
Format of the pixel value under mouse. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
notext : bool, optional
If True, no text is printed around the map
norm : {'hist', 'log', None}
Color normalization, hist= histogram equalized color mapping,
log= logarithmic color mapping, default: None (linear color mapping)
cmap : a color map
The colormap to use (see matplotlib.cm)
badcolor : str
Color to use to plot bad values
bgcolor : str
Color to use for background
hold : bool, optional
If True, replace the current Axes by an OrthographicAxes.
use this if you want to have multiple maps on the same
figure. Default: False
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot).
Default: None
reuse_axes : bool, optional
If True, reuse the current Axes (should be a OrthographicAxes). This is
useful if you want to overplot with a partially transparent colormap,
such as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top)
giving the margins on left,bottom,right and top
of the axes. Values are relative to figure (0-1).
Default: None
return_projected_map : bool
if True returns the projected map in a 2d numpy array
alpha : float, array-like or None
An array containing the alpha channel, supports masked maps, see the `ma` function.
If None, no transparency will be applied.
See Also
--------
mollview, gnomview, cartview, azeqview
"""
# Create the figure
import pylab
if map is None:
map = np.zeros(12) + np.inf
cbar = False
# Ensure that the nside is valid
nside = pixelfunc.get_nside(map)
pixelfunc.check_nside(nside, nest=nest)
if not (hold or sub or reuse_axes):
f = pylab.figure(fig, figsize=(8.5, 5.4))
if not margins:
margins = (0.02, 0.05, 0.02, 0.05)
extent = (0.0, 0.0, 1.0, 1.0)
elif hold:
f = pylab.gcf()
left, bottom, right, top = np.array(f.gca().get_position()).ravel()
if not margins:
margins = (0.0, 0.0, 0.0, 0.0)
extent = (left, bottom, right - left, top - bottom)
f.delaxes(f.gca())
elif reuse_axes:
f = pylab.gcf()
else: # using subplot syntax
f = pylab.gcf()
if hasattr(sub, "__len__"):
nrows, ncols, idx = sub
else:
nrows, ncols, idx = sub // 100, (sub % 100) // 10, (sub % 10)
if idx < 1 or idx > ncols * nrows:
raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
c, r = (idx - 1) % ncols, (idx - 1) // ncols
if not margins:
margins = (0.01, 0.0, 0.0, 0.02)
extent = (
c * 1.0 / ncols,
1.0 - (r + 1) * 1.0 / nrows,
1.0 / ncols,
1.0 / nrows,
)
if not reuse_axes:
extent = (
extent[0] + margins[0],
extent[1] + margins[1],
extent[2] - margins[2] - margins[0],
extent[3] - margins[3] - margins[1],
)
# Starting to draw : turn interactive off
wasinteractive = pylab.isinteractive()
pylab.ioff()
try:
if reuse_axes:
ax = f.gca()
else:
ax = PA.HpxOrthographicAxes(
f, extent, coord=coord, rot=rot, format=format2, flipconv=flip
)
f.add_axes(ax)
if remove_dip:
map = pixelfunc.remove_dipole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
elif remove_mono:
map = pixelfunc.remove_monopole(
map, gal_cut=gal_cut, nest=nest, copy=True
)
img = ax.projmap(
map,
nest=nest,
xsize=xsize,
half_sky=half_sky,
coord=coord,
vmin=min,
vmax=max,
cmap=cmap,
badcolor=badcolor,
bgcolor=bgcolor,
norm=norm,
alpha=alpha,
)
if cbar:
im = ax.get_images()[0]
b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
mappable = plt.cm.ScalarMappable(
norm=matplotlib.colors.Normalize(vmin=im.norm.vmin, vmax=im.norm.vmax),
cmap=cmap,
)
if matplotlib.__version__ >= "0.91.0":
cb = f.colorbar(
mappable,
ax=ax,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
else:
# for older matplotlib versions, no ax kwarg
cb = f.colorbar(
mappable,
orientation="horizontal",
shrink=0.5,
aspect=25,
ticks=PA.BoundaryLocator(),
pad=0.05,
fraction=0.1,
boundaries=b,
values=v,
format=format,
)
cb.solids.set_rasterized(True)
ax.set_title(title)
if not notext:
ax.text(
0.86,
0.05,
ax.proj.coordsysstr,
fontsize=14,
fontweight="bold",
transform=ax.transAxes,
)
if cbar:
cb.ax.text(
0.5,
-1.0,
unit,
fontsize=14,
transform=cb.ax.transAxes,
ha="center",
va="center",
)
f.sca(ax)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
if return_projected_map:
return img
| (map=None, fig=None, rot=None, coord=None, unit='', xsize=800, half_sky=False, title='Orthographic view', nest=False, min=None, max=None, flip='astro', remove_dip=False, remove_mono=False, gal_cut=0, format='%g', format2='%g', cbar=True, cmap=None, badcolor='gray', bgcolor='white', notext=False, norm=None, hold=False, margins=None, sub=None, reuse_axes=False, return_projected_map=False, alpha=None) |
37,711 | healpy.pixelfunc | pix2ang | pix2ang : nside,ipix,nest=False,lonlat=False -> theta[rad],phi[rad] (default RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
ipix : int or array-like
Pixel indices
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be co-latitude and longitude in radians (default)
Returns
-------
theta, phi : float, scalar or array-like
The angular coordinates corresponding to ipix. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, vec2pix, pix2vec
Examples
--------
>>> import healpy as hp
>>> hp.pix2ang(16, 1440)
(1.5291175943723188, 0.0)
>>> hp.pix2ang(16, [1440, 427, 1520, 0, 3068])
(array([ 1.52911759, 0.78550497, 1.57079633, 0.05103658, 3.09055608]), array([ 0. , 0.78539816, 1.61988371, 0.78539816, 0.78539816]))
>>> hp.pix2ang([1, 2, 4, 8], 11)
(array([ 2.30052398, 0.84106867, 0.41113786, 0.2044802 ]), array([ 5.49778714, 5.89048623, 5.89048623, 5.89048623]))
>>> hp.pix2ang([1, 2, 4, 8], 11, lonlat=True)
(array([ 315. , 337.5, 337.5, 337.5]), array([-41.8103149 , 41.8103149 , 66.44353569, 78.28414761]))
| def pix2ang(nside, ipix, nest=False, lonlat=False):
"""pix2ang : nside,ipix,nest=False,lonlat=False -> theta[rad],phi[rad] (default RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
ipix : int or array-like
Pixel indices
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be co-latitude and longitude in radians (default)
Returns
-------
theta, phi : float, scalar or array-like
The angular coordinates corresponding to ipix. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, vec2pix, pix2vec
Examples
--------
>>> import healpy as hp
>>> hp.pix2ang(16, 1440)
(1.5291175943723188, 0.0)
>>> hp.pix2ang(16, [1440, 427, 1520, 0, 3068])
(array([ 1.52911759, 0.78550497, 1.57079633, 0.05103658, 3.09055608]), array([ 0. , 0.78539816, 1.61988371, 0.78539816, 0.78539816]))
>>> hp.pix2ang([1, 2, 4, 8], 11)
(array([ 2.30052398, 0.84106867, 0.41113786, 0.2044802 ]), array([ 5.49778714, 5.89048623, 5.89048623, 5.89048623]))
>>> hp.pix2ang([1, 2, 4, 8], 11, lonlat=True)
(array([ 315. , 337.5, 337.5, 337.5]), array([-41.8103149 , 41.8103149 , 66.44353569, 78.28414761]))
"""
check_nside(nside, nest=nest)
if nest:
theta, phi = pixlib._pix2ang_nest(nside, ipix)
else:
theta, phi = pixlib._pix2ang_ring(nside, ipix)
if lonlat:
return thetaphi2lonlat(theta, phi)
else:
return theta, phi
| (nside, ipix, nest=False, lonlat=False) |
37,712 | healpy.pixelfunc | pix2vec | pix2vec : nside,ipix,nest=False -> x,y,z (default RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
ipix : int, scalar or array-like
Healpix pixel number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
x, y, z : floats, scalar or array-like
The coordinates of vector corresponding to input pixels. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, pix2ang, vec2pix
Examples
--------
>>> import healpy as hp
>>> hp.pix2vec(16, 1504)
(0.99879545620517241, 0.049067674327418015, 0.0)
>>> hp.pix2vec(16, [1440, 427])
(array([ 0.99913157, 0.5000534 ]), array([ 0. , 0.5000534]), array([ 0.04166667, 0.70703125]))
>>> hp.pix2vec([1, 2], 11)
(array([ 0.52704628, 0.68861915]), array([-0.52704628, -0.28523539]), array([-0.66666667, 0.66666667]))
| def pix2vec(nside, ipix, nest=False):
"""pix2vec : nside,ipix,nest=False -> x,y,z (default RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
ipix : int, scalar or array-like
Healpix pixel number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
x, y, z : floats, scalar or array-like
The coordinates of vector corresponding to input pixels. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, pix2ang, vec2pix
Examples
--------
>>> import healpy as hp
>>> hp.pix2vec(16, 1504)
(0.99879545620517241, 0.049067674327418015, 0.0)
>>> hp.pix2vec(16, [1440, 427])
(array([ 0.99913157, 0.5000534 ]), array([ 0. , 0.5000534]), array([ 0.04166667, 0.70703125]))
>>> hp.pix2vec([1, 2], 11)
(array([ 0.52704628, 0.68861915]), array([-0.52704628, -0.28523539]), array([-0.66666667, 0.66666667]))
"""
check_nside(nside, nest=nest)
if nest:
return pixlib._pix2vec_nest(nside, ipix)
else:
return pixlib._pix2vec_ring(nside, ipix)
| (nside, ipix, nest=False) |
37,713 | healpy.pixelfunc | pix2xyf | pix2xyf : nside,ipix,nest=False -> x,y,face (default RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2
ipix : int or array-like
Pixel indices
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
See Also
--------
xyf2pix
Examples
--------
>>> import healpy as hp
>>> hp.pix2xyf(16, 1440)
(8, 8, 4)
>>> hp.pix2xyf(16, [1440, 427, 1520, 0, 3068])
(array([ 8, 8, 8, 15, 0]), array([ 8, 8, 7, 15, 0]), array([4, 0, 5, 0, 8]))
>>> hp.pix2xyf([1, 2, 4, 8], 11)
(array([0, 1, 3, 7]), array([0, 0, 2, 6]), array([11, 3, 3, 3]))
| def pix2xyf(nside, ipix, nest=False):
"""pix2xyf : nside,ipix,nest=False -> x,y,face (default RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2
ipix : int or array-like
Pixel indices
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
See Also
--------
xyf2pix
Examples
--------
>>> import healpy as hp
>>> hp.pix2xyf(16, 1440)
(8, 8, 4)
>>> hp.pix2xyf(16, [1440, 427, 1520, 0, 3068])
(array([ 8, 8, 8, 15, 0]), array([ 8, 8, 7, 15, 0]), array([4, 0, 5, 0, 8]))
>>> hp.pix2xyf([1, 2, 4, 8], 11)
(array([0, 1, 3, 7]), array([0, 0, 2, 6]), array([11, 3, 3, 3]))
"""
check_nside(nside, nest=nest)
if nest:
return pixlib._pix2xyf_nest(nside, ipix)
else:
return pixlib._pix2xyf_ring(nside, ipix)
| (nside, ipix, nest=False) |
37,715 | healpy.sphtfunc | pixwin | Return the pixel window function for the given nside.
Parameters
----------
nside : int
The nside for which to return the pixel window function
pol : bool, optional
If True, return also the polar pixel window. Default: False
lmax : int, optional
Maximum l of the power spectrum (default: 3*nside-1)
Returns
-------
pw or pwT,pwP : array or tuple of 2 arrays
The temperature pixel window function, or a tuple with both
temperature and polarisation pixel window functions.
| def pixwin(nside, pol=False, lmax=None):
"""Return the pixel window function for the given nside.
Parameters
----------
nside : int
The nside for which to return the pixel window function
pol : bool, optional
If True, return also the polar pixel window. Default: False
lmax : int, optional
Maximum l of the power spectrum (default: 3*nside-1)
Returns
-------
pw or pwT,pwP : array or tuple of 2 arrays
The temperature pixel window function, or a tuple with both
temperature and polarisation pixel window functions.
"""
if lmax is None:
lmax = 3 * nside - 1
datapath = DATAPATH
if not pixelfunc.isnsideok(nside):
raise ValueError("Wrong nside value (must be a power of two).")
fname = os.path.join(datapath, "pixel_window_n%04d.fits" % nside)
if not os.path.isfile(fname):
raise ValueError("No pixel window for this nside " "or data files missing")
# return hfitslib._pixwin(nside,datapath,pol) ## BROKEN -> seg fault...
pw = pf.getdata(fname)
pw_temp, pw_pol = pw.field(0), pw.field(1)
if pol:
return pw_temp[: lmax + 1], pw_pol[: lmax + 1]
else:
return pw_temp[: lmax + 1]
| (nside, pol=False, lmax=None) |
37,718 | healpy.visufunc | projplot | projplot is a wrapper around :func:`matplotlib.Axes.plot` to take into account the
spherical projection.
You can call this function as::
projplot(theta, phi) # plot a line going through points at coord (theta, phi)
projplot(theta, phi, 'bo') # plot 'o' in blue at coord (theta, phi)
projplot(thetaphi) # plot a line going through points at coord (thetaphi[0], thetaphi[1])
projplot(thetaphi, 'bx') # idem but with blue 'x'
Parameters
----------
theta, phi : float, array-like
Coordinates of point to plot. Can be put into one 2-d array, first line is
then *theta* and second line is *phi*. See *lonlat* parameter for unit.
fmt : str
A format string (see :func:`matplotlib.Axes.plot` for details)
lonlat : bool, optional
If True, theta and phi are interpreted as longitude and latitude
in degree, otherwise, as colatitude and longitude in radian
coord : {'E', 'G', 'C', None}
The coordinate system of the points, only used if the coordinate
coordinate system of the Axes has been defined and in this
case, a rotation is performed
rot : None or sequence
rotation to be applied =(lon, lat, psi) : lon, lat will be position of the
new Z axis, and psi is rotation around this axis, all in degree.
if None, no rotation is performed
direct : bool
if True, the rotation to center the projection is not
taken into account
Notes
-----
Other keywords are passed to :func:`matplotlib.Axes.plot`.
See Also
--------
projscatter, projtext
| def projplot(*args, **kwds):
import pylab
f = pylab.gcf()
wasinteractive = pylab.isinteractive()
pylab.ioff()
ret = None
try:
for ax in f.get_axes():
if isinstance(ax, PA.SphericalProjAxes):
ret = ax.projplot(*args, **kwds)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
return ret
| (*args, **kwds) |
37,719 | healpy.visufunc | projscatter | Projscatter is a wrapper around :func:`matplotlib.Axes.scatter` to take into account the
spherical projection.
You can call this function as::
projscatter(theta, phi) # plot points at coord (theta, phi)
projplot(thetaphi) # plot points at coord (thetaphi[0], thetaphi[1])
Parameters
----------
theta, phi : float, array-like
Coordinates of point to plot. Can be put into one 2-d array, first line is
then *theta* and second line is *phi*. See *lonlat* parameter for unit.
lonlat : bool, optional
If True, theta and phi are interpreted as longitude and latitude
in degree, otherwise, as colatitude and longitude in radian
coord : {'E', 'G', 'C', None}, optional
The coordinate system of the points, only used if the coordinate
coordinate system of the axes has been defined and in this
case, a rotation is performed
rot : None or sequence, optional
rotation to be applied =(lon, lat, psi) : lon, lat will be position of the
new Z axis, and psi is rotation around this axis, all in degree.
if None, no rotation is performed
direct : bool, optional
if True, the rotation to center the projection is not
taken into account
Notes
-----
Other keywords are passed to :func:`matplotlib.Axes.plot`.
See Also
--------
projplot, projtext
| def projscatter(*args, **kwds):
import pylab
f = pylab.gcf()
wasinteractive = pylab.isinteractive()
pylab.ioff()
ret = None
try:
for ax in f.get_axes():
if isinstance(ax, PA.SphericalProjAxes):
ret = ax.projscatter(*args, **kwds)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
return ret
| (*args, **kwds) |
37,720 | healpy.visufunc | projtext | Projtext is a wrapper around :func:`matplotlib.Axes.text` to take into account the
spherical projection.
Parameters
----------
theta, phi : float, array-like
Coordinates of point to plot. Can be put into one 2-d array, first line is
then *theta* and second line is *phi*. See *lonlat* parameter for unit.
text : str
The text to be displayed.
lonlat : bool, optional
If True, theta and phi are interpreted as longitude and latitude
in degree, otherwise, as colatitude and longitude in radian
coord : {'E', 'G', 'C', None}, optional
The coordinate system of the points, only used if the coordinate
coordinate system of the axes has been defined and in this
case, a rotation is performed
rot : None or sequence, optional
rotation to be applied =(lon, lat, psi) : lon, lat will be position of the
new Z axis, and psi is rotation around this axis, all in degree.
if None, no rotation is performed
direct : bool, optional
if True, the rotation to center the projection is not
taken into account
Notes
-----
Other keywords are passed to :func:`matplotlib.Axes.text`.
See Also
--------
projplot, projscatter
| def projtext(*args, **kwds):
import pylab
f = pylab.gcf()
wasinteractive = pylab.isinteractive()
pylab.ioff()
ret = None
try:
for ax in f.get_axes():
if isinstance(ax, PA.SphericalProjAxes):
ret = ax.projtext(*args, **kwds)
finally:
pylab.draw()
if wasinteractive:
pylab.ion()
# pylab.show()
return ret
| (*args, **kwds) |
37,721 | healpy.newvisufunc | projview | Plot a healpix map (given as an array) in the chosen projection.
See examples of using this function in the documentation under "Other
tutorials". Overplot points or lines using :func:`newprojplot`.
.. warning::
this function is work in progress, the aim is to reimplement the healpy
plot functions using the new features of matplotlib and remove most
of the custom projection code.
Please report bugs or submit feature requests via Github.
The interface will change in future releases.
Parameters
----------
m : 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.
fig : int or None, optional
The figure number to use. Default: create a new figure
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. default: 'G'
unit : str, optional
A text describing the unit of the data. Default: ''
xsize : int, optional
The size of the image. Default: 800
width : float, optional
Sets the width of the figure. Use override_plot_properties for more.
Overrides the default width of the figure
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)
It creates the `healpy_flip` attribute on the Axes to save the convention
in the figure.
format : str, optional
The format of the scale label. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
cmap : str, optional
Specify the colormap. default: Viridis
norm : {'hist', 'log', 'symlog', 'symlog2', None}
Color normalization:
hist = histogram equalized color mapping.
log = logarithmic color mapping.
symlog = symmetric logarithmic, linear between -linthresh and linthresh.
symlog2 = similar to symlog, used for plack log colormap.
default: None (linear color mapping)
norm_dict : dict, optional
Parameters for normalization:
default is set to {"linthresh": 1, "base": 10, "linscale": 0.1}
where linthresh determines the linear regime of symlog norm,
and linscale sets the size of the linear regime on the cbar.
default: None
graticule : bool
add graticule
graticule_labels : bool
longitude and latitude labels
rot_graticule : bool
rotate also the graticule when rotating the map
graticule_coord : str
Either one of 'G', 'E' or 'C' to describe the coordinate system of the
graticule
override_rot_graticule_properties : dict
Override the following rotated graticule properties: "g_linestyle",
"g_linewidth", "g_color", "g_alpha", "t_step", "p_step".
return_only_data : bool, optional
Return array of data
projection_type : {'aitoff', 'hammer', 'lambert', 'mollweide', 'cart',
'3d', 'polar'}
type of the plot
cb_orientation : {'horizontal', 'vertical'}
color bar orientation
xlabel : str
set x axis label
ylabel : str
set y axis label
longitude_grid_spacing : float
set x axis grid spacing
latitude_grid_spacing : float
set y axis grid spacing
override_plot_properties : dict
Override the following plot properties: "cbar_shrink", "cbar_pad",
"cbar_label_pad", "cbar_tick_direction", "vertical_tick_rotation"
"figure_width": width, "figure_size_ratio": ratio.
title : str
set title of the plot
rlabel : str
set label at top right corner of axis
llabel : str
set label at top left corner of axis
xtick_label_color : str
Change the color of the graticule xticks
ytick_label_color : str
Change the color of the graticule yticks
graticule_color : str
Change the color of the graticule
fontname : str
Change the fontname of the text
fontsize: dict
Override fontsize of labels: "xlabel", "ylabel", "title", "xtick_label",
"ytick_label", "cbar_label", "cbar_tick_label".
phi_convention : string
convention on x-axis (phi), 'counterclockwise' (default), 'clockwise',
'symmetrical' (phi as it is truly given) if `flip` is "geo",
`phi_convention` should be set to 'clockwise'.
custom_xtick_labels : list
override x-axis tick labels
custom_ytick_labels : list
override y-axis tick labels
cbar_ticks : list
custom ticks on the colorbar
show_tickmarkers : bool, optional
Preserve tickmarkers for the full bar with labels specified by ticks
default: None
extend : str, optional
Whether to extend the colorbar to mark where min or max tick is less than
the min or max of the data. Options are "min", "max", "neither", or "both"
invRot : bool
invert rotation
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot). Default:
111
reuse_axes : bool, optional
If True, reuse the current Axes (should be a MollweideAxes). This is
useful if you want to overplot with a partially transparent colormap, such
as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top) giving the margins on
left,bottom,right and top of the axes. Values are relative to figure
(0-1). Default: None
hold : bool, optional
If True, replace the current Axes by new axis. use this if you want to
have multiple maps on the same figure. Default: False
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]
kwargs : dict
any leftover arguments will be passed to pcolormesh
| def projview(
m=None,
fig=None,
rot=None,
coord=None,
unit="",
xsize=1000,
width=None,
nest=False,
min=None,
max=None,
flip="astro",
format="%g",
cbar=True,
cmap="viridis",
norm=None,
norm_dict=None,
graticule=False,
graticule_labels=False,
rot_graticule=False,
graticule_coord=None,
override_rot_graticule_properties=None,
return_only_data=False,
projection_type="mollweide",
cb_orientation="horizontal",
xlabel=None,
ylabel=None,
longitude_grid_spacing=60,
latitude_grid_spacing=30,
override_plot_properties=None,
title=None,
rlabel=None,
llabel=None,
xtick_label_color="black",
ytick_label_color="black",
graticule_color=None,
fontname=None,
fontsize=None,
phi_convention="counterclockwise",
custom_xtick_labels=None,
custom_ytick_labels=None,
cbar_ticks=None,
show_tickmarkers=False,
extend=None,
invRot=True,
sub=111,
reuse_axes=False,
margins=None,
hold=False,
remove_dip=False,
remove_mono=False,
gal_cut=0,
**kwargs,
):
"""Plot a healpix map (given as an array) in the chosen projection.
See examples of using this function in the documentation under "Other
tutorials". Overplot points or lines using :func:`newprojplot`.
.. warning::
this function is work in progress, the aim is to reimplement the healpy
plot functions using the new features of matplotlib and remove most
of the custom projection code.
Please report bugs or submit feature requests via Github.
The interface will change in future releases.
Parameters
----------
m : 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.
fig : int or None, optional
The figure number to use. Default: create a new figure
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. default: 'G'
unit : str, optional
A text describing the unit of the data. Default: ''
xsize : int, optional
The size of the image. Default: 800
width : float, optional
Sets the width of the figure. Use override_plot_properties for more.
Overrides the default width of the figure
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)
It creates the `healpy_flip` attribute on the Axes to save the convention
in the figure.
format : str, optional
The format of the scale label. Default: '%g'
cbar : bool, optional
Display the colorbar. Default: True
cmap : str, optional
Specify the colormap. default: Viridis
norm : {'hist', 'log', 'symlog', 'symlog2', None}
Color normalization:
hist = histogram equalized color mapping.
log = logarithmic color mapping.
symlog = symmetric logarithmic, linear between -linthresh and linthresh.
symlog2 = similar to symlog, used for plack log colormap.
default: None (linear color mapping)
norm_dict : dict, optional
Parameters for normalization:
default is set to {"linthresh": 1, "base": 10, "linscale": 0.1}
where linthresh determines the linear regime of symlog norm,
and linscale sets the size of the linear regime on the cbar.
default: None
graticule : bool
add graticule
graticule_labels : bool
longitude and latitude labels
rot_graticule : bool
rotate also the graticule when rotating the map
graticule_coord : str
Either one of 'G', 'E' or 'C' to describe the coordinate system of the
graticule
override_rot_graticule_properties : dict
Override the following rotated graticule properties: "g_linestyle",
"g_linewidth", "g_color", "g_alpha", "t_step", "p_step".
return_only_data : bool, optional
Return array of data
projection_type : {'aitoff', 'hammer', 'lambert', 'mollweide', 'cart',
'3d', 'polar'}
type of the plot
cb_orientation : {'horizontal', 'vertical'}
color bar orientation
xlabel : str
set x axis label
ylabel : str
set y axis label
longitude_grid_spacing : float
set x axis grid spacing
latitude_grid_spacing : float
set y axis grid spacing
override_plot_properties : dict
Override the following plot properties: "cbar_shrink", "cbar_pad",
"cbar_label_pad", "cbar_tick_direction", "vertical_tick_rotation"
"figure_width": width, "figure_size_ratio": ratio.
title : str
set title of the plot
rlabel : str
set label at top right corner of axis
llabel : str
set label at top left corner of axis
xtick_label_color : str
Change the color of the graticule xticks
ytick_label_color : str
Change the color of the graticule yticks
graticule_color : str
Change the color of the graticule
fontname : str
Change the fontname of the text
fontsize: dict
Override fontsize of labels: "xlabel", "ylabel", "title", "xtick_label",
"ytick_label", "cbar_label", "cbar_tick_label".
phi_convention : string
convention on x-axis (phi), 'counterclockwise' (default), 'clockwise',
'symmetrical' (phi as it is truly given) if `flip` is "geo",
`phi_convention` should be set to 'clockwise'.
custom_xtick_labels : list
override x-axis tick labels
custom_ytick_labels : list
override y-axis tick labels
cbar_ticks : list
custom ticks on the colorbar
show_tickmarkers : bool, optional
Preserve tickmarkers for the full bar with labels specified by ticks
default: None
extend : str, optional
Whether to extend the colorbar to mark where min or max tick is less than
the min or max of the data. Options are "min", "max", "neither", or "both"
invRot : bool
invert rotation
sub : int, scalar or sequence, optional
Use only a zone of the current figure (same syntax as subplot). Default:
111
reuse_axes : bool, optional
If True, reuse the current Axes (should be a MollweideAxes). This is
useful if you want to overplot with a partially transparent colormap, such
as for plotting a line integral convolution. Default: False
margins : None or sequence, optional
Either None, or a sequence (left,bottom,right,top) giving the margins on
left,bottom,right and top of the axes. Values are relative to figure
(0-1). Default: None
hold : bool, optional
If True, replace the current Axes by new axis. use this if you want to
have multiple maps on the same figure. Default: False
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]
kwargs : dict
any leftover arguments will be passed to pcolormesh
"""
geographic_projections = ["aitoff", "hammer", "lambert", "mollweide"]
# Set min and max values if ticks are specified and min and max are not
if min is None and cbar_ticks is not None:
min = np.min(cbar_ticks)
if max is None and cbar_ticks is not None:
max = np.max(cbar_ticks)
# Update values for symlog normalization if specified
norm_dict_defaults = {"linthresh": 1, "base": 10, "linscale": 0.1}
if norm_dict is not None:
norm_dict_defaults = update_dictionary(norm_dict_defaults, norm_dict)
# Remove monopole and dipole
if remove_dip:
m = remove_dipole(m, gal_cut=gal_cut, nest=nest, copy=True)
elif remove_mono:
m = remove_monopole(m, gal_cut=gal_cut, nest=nest, copy=True)
# do this to find how many decimals are in the colorbar labels, so that the padding in the vertical cbar can done properly
def find_number_of_decimals(number):
try:
return len(str(number).split(".")[1])
except:
return 0
# default font sizes
fontsize_defaults = {
"xlabel": 12,
"ylabel": 12,
"title": 14,
"xtick_label": 12,
"ytick_label": 12,
"cbar_label": 12,
"cbar_tick_label": 10,
}
if fontsize is not None:
fontsize_defaults = update_dictionary(fontsize_defaults, fontsize)
# default plot settings
decs = np.max([find_number_of_decimals(min), find_number_of_decimals(max)])
if decs >= 3:
lpad = -27
else:
lpad = -9 * decs
ratio = 0.63
custom_width = width
if projection_type == "3d":
if cb_orientation == "vertical":
shrink = 0.55
pad = 0.02
width = 11.5
if cb_orientation == "horizontal":
shrink = 0.2
pad = 0
lpad = -10
width = 14
if projection_type in geographic_projections:
if cb_orientation == "vertical":
shrink = 0.6
pad = 0.03
if cbar_ticks is not None:
lpad = 0
else:
lpad = -8
width = 10
if cb_orientation == "horizontal":
shrink = 0.6
pad = 0.05
if cbar_ticks is not None:
lpad = 0
else:
lpad = -8
width = 8.5
if projection_type == "cart":
if cb_orientation == "vertical":
shrink = 0.6
pad = 0.03
if cbar_ticks is not None:
lpad = 0
else:
lpad = -8
width = 10
if cb_orientation == "horizontal":
shrink = 0.6
pad = 0.05
if cbar_ticks is not None:
lpad = 0
else:
lpad = -8
width = 8.5
if xlabel == None:
pad = pad + 0.01
ratio = 0.63
if projection_type == "polar":
if cb_orientation == "vertical":
shrink = 1
pad = 0.01
width = 10
if cb_orientation == "horizontal":
shrink = 0.4
pad = 0.01
lpad = 0
width = 12
# If width was passed as an input argument
if custom_width is not None:
width = custom_width
if cb_orientation == "vertical":
# If using rotated ticklabels, pad less.
if (
override_plot_properties is not None
and "vertical_tick_rotation" in override_plot_properties
):
lpad = (
4 if override_plot_properties["vertical_tick_rotation"] != 90 else lpad
)
if title is not None:
lpad += 8
# pass the default settings to the plot_properties dictionary
plot_properties = {
"cbar_shrink": shrink,
"cbar_pad": pad,
"cbar_label_pad": lpad,
"cbar_tick_direction": "out",
"vertical_tick_rotation": 90,
"figure_width": width,
"figure_size_ratio": ratio,
}
if override_plot_properties is not None:
warnings.warn(
"\n *** Overriding default plot properies: " + str(plot_properties) + " ***"
)
plot_properties = update_dictionary(plot_properties, override_plot_properties)
warnings.warn("\n *** New plot properies: " + str(plot_properties) + " ***")
g_col = "grey" if graticule_color is None else graticule_color
rot_graticule_properties = {
"g_linestyle": "-",
"g_color": g_col,
"g_alpha": 0.75,
"g_linewidth": 0.75,
"t_step": latitude_grid_spacing,
"p_step": longitude_grid_spacing,
}
if override_rot_graticule_properties is not None:
warnings.warn(
"\n *** Overriding rotated graticule properies: "
+ str(rot_graticule_properties)
+ " ***"
)
rot_graticule_properties = update_dictionary(
rot_graticule_properties, override_rot_graticule_properties
)
warnings.warn(
"\n *** New rotated graticule properies: "
+ str(rot_graticule_properties)
+ " ***"
)
# Create the figure, this method is inspired by the Mollview approach
if not return_only_data: # supress figure creation when only dumping the data
if hasattr(sub, "__len__"):
nrows, ncols, idx = sub
else:
nrows, ncols, idx = sub // 100, (sub % 100) // 10, (sub % 10)
if idx < 1 or idx > ncols * nrows:
raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
if not (hold or reuse_axes) and sub == 111:
fig = plt.figure(
figsize=(
plot_properties["figure_width"],
(
plot_properties["figure_width"]
* plot_properties["figure_size_ratio"]
),
)
)
extent = (0.02, 0.05, 0.96, 0.9)
elif hold:
fig = plt.gcf()
left, bottom, right, top = np.array(fig.gca().get_position()).ravel()
extent = (left, bottom, right - left, top - bottom)
fig.delaxes(fig.gca())
elif reuse_axes:
fig = plt.gcf()
else: # using subplot syntax
if not plt.get_fignums():
# Scale height depending on subplots
fig = plt.figure(
figsize=(
plot_properties["figure_width"],
(
plot_properties["figure_width"]
* plot_properties["figure_size_ratio"]
)
* (nrows / ncols),
)
)
else:
fig = plt.gcf()
"""
# Subplot method 1, copied from mollview
c, r = (idx - 1) % ncols, (idx - 1) // ncols
if not margins:
right_adjust = 0.045 if cb_orientation=="vertical" else 0.0
margins = (0.01, 0.0, 0.01-right_adjust, 0.0)
extent = (
c * 1.0 / ncols + margins[0],
1.0 - (r + 1) * 1.0 / nrows + margins[1],
1.0 / ncols - margins[2] - margins[0],
1.0 / nrows - margins[3] - margins[1],
)
extent = (
extent[0] + margins[0],
extent[1] + margins[1],
extent[2] - margins[2] - margins[0],
extent[3] - margins[3] - margins[1],
)
"""
# FIXME: make a more general axes creation that works also with subplots
# ax = fig.add_axes(extent, projection=projection_type)
if projection_type == "cart":
ax = fig.add_subplot(nrows, ncols, idx)
else:
ax = fig.add_subplot(nrows, ncols, idx, projection=projection_type)
# Parameters for subplots
left = 0.02
right = 0.98
top = 0.95
bottom = 0.05
# end if not
if graticule and graticule_labels:
left += 0.02
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]
if not return_only_data:
plt.subplots_adjust(left=left, right=right, top=top, bottom=bottom)
# set property on ax so it can be used in newprojplot
ax.healpy_flip = flip
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=invRot)
THETA, PHI = r(THETA.flatten(), PHI.flatten())
THETA = THETA.reshape(ysize, xsize)
PHI = PHI.reshape(ysize, xsize)
nside = npix2nside(len(m))
if not m is None:
w = ~(np.isnan(m) | np.isinf(m))
if not m is None:
# auto min and max
if min is None:
min = m[w].min()
if max is None:
max = m[w].max()
cm, nn = get_color_table(
min, max, m[w], cmap=cmap, norm=norm, **norm_dict_defaults
)
grid_pix = ang2pix(nside, THETA, PHI, nest=nest)
grid_map = m[grid_pix]
# plot
if return_only_data: # exit here when dumping the data
return [longitude, latitude, grid_map]
if projection_type != "3d": # test for 3d plot
ret = plt.pcolormesh(
longitude,
latitude,
grid_map,
norm=nn,
rasterized=True,
cmap=cm,
shading="auto",
**kwargs,
)
elif projection_type == "3d": # test for 3d plot
LONGITUDE, LATITUDE = np.meshgrid(longitude, latitude)
ret = ax.plot_surface(
LONGITUDE,
LATITUDE,
grid_map,
cmap=cm,
norm=nn,
rasterized=True,
**kwargs,
)
# graticule
if rot_graticule or graticule_coord is not None:
graticule_labels = False
if rot_graticule or graticule_coord is None:
if graticule_color is None:
plt.grid(graticule)
else:
plt.grid(graticule, color=graticule_color)
if graticule:
if projection_type in geographic_projections:
longitude_grid_spacing = longitude_grid_spacing # deg 60
ax.set_longitude_grid(longitude_grid_spacing)
ax.set_latitude_grid(latitude_grid_spacing)
ax.set_longitude_grid_ends(90)
else:
longitude_grid_spacing = longitude_grid_spacing # deg
latitude_grid_spacing = latitude_grid_spacing # deg
ax.xaxis.set_major_locator(
MultipleLocator(np.deg2rad(longitude_grid_spacing))
) # longitude
ax.yaxis.set_major_locator(
MultipleLocator(np.deg2rad(latitude_grid_spacing))
) # lattitude
# labelling
if graticule_labels & graticule:
if phi_convention == "counterclockwise":
xtick_formatter = ThetaFormatterCounterclockwisePhi(longitude_grid_spacing)
elif phi_convention == "clockwise":
xtick_formatter = ThetaFormatterClockwisePhi(longitude_grid_spacing)
elif phi_convention == "symmetrical":
xtick_formatter = ThetaFormatterSymmetricPhi(longitude_grid_spacing)
ax.xaxis.set_major_formatter(xtick_formatter)
ax.yaxis.set_major_formatter(ThetaFormatterTheta(latitude_grid_spacing))
if custom_xtick_labels is not None:
try:
ax.xaxis.set_ticklabels(custom_xtick_labels, fontname=fontname)
except:
warnings.warn(
"Put names for all "
+ str(len(ax.xaxis.get_ticklabels()))
+ " x-tick labels!. No re-labelling done."
)
if custom_ytick_labels is not None:
try:
ax.yaxis.set_ticklabels(custom_ytick_labels, fontname=fontname)
except:
warnings.warn(
"Put names for all "
+ str(len(ax.yaxis.get_ticklabels()))
+ " y-tick labels!. No re-labelling done."
)
if not graticule or not graticule_labels:
# remove longitude and latitude labels
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
ax.tick_params(axis="both", which="both", length=0)
ax.set_title(title, fontsize=fontsize_defaults["title"], fontname=fontname)
# tick font size
ax.tick_params(
axis="x", labelsize=fontsize_defaults["xtick_label"], colors=xtick_label_color
)
ax.tick_params(
axis="y", labelsize=fontsize_defaults["ytick_label"], colors=ytick_label_color
)
# colorbar
if projection_type == "cart":
ax.set_aspect(1)
if cbar:
if cbar_ticks is None:
cbar_ticks = [min, max]
if extend is None:
extend = "neither"
if min > np.min(m):
extend = "min"
if max < np.max(m):
extend = "max"
if min > np.min(m) and max < np.max(m):
extend = "both"
# For preserving automatic tickmarkers
ticks = None if show_tickmarkers else cbar_ticks
# Create colorbar
cb = fig.colorbar(
ret,
orientation=cb_orientation,
shrink=plot_properties["cbar_shrink"],
pad=plot_properties["cbar_pad"],
ticks=ticks,
extend=extend,
)
# Hide all tickslabels not in tick variable. Do not delete tick-markers
if show_tickmarkers:
ticks = list(set(cb.get_ticks()) | set(cbar_ticks))
ticks = np.sort(ticks)
ticks = ticks[ticks >= min]
ticks = ticks[ticks <= max]
labels = [format % tick if tick in cbar_ticks else "" for tick in ticks]
try:
cb.set_ticks(ticks, labels)
except TypeError:
cb.set_ticks(ticks)
cb.set_ticklabels(labels)
else:
labels = [format % tick for tick in cbar_ticks]
if cb_orientation == "horizontal":
# labels = cb.ax.get_xticklabels() if norm is not None else labels
cb.ax.set_xticklabels(labels, fontname=fontname)
cb.ax.xaxis.set_label_text(
unit, fontsize=fontsize_defaults["cbar_label"], fontname=fontname
)
cb.ax.tick_params(
axis="x",
labelsize=fontsize_defaults["cbar_tick_label"],
direction=plot_properties["cbar_tick_direction"],
)
cb.ax.xaxis.labelpad = plot_properties["cbar_label_pad"]
if cb_orientation == "vertical":
# labels = cb.ax.get_yticklabels() if norm is not None else labels
cb.ax.set_yticklabels(
labels,
rotation=plot_properties["vertical_tick_rotation"],
va="center",
fontname=fontname,
)
cb.ax.yaxis.set_label_text(
unit,
fontsize=fontsize_defaults["cbar_label"],
rotation=90,
fontname=fontname,
)
cb.ax.tick_params(
axis="y",
labelsize=fontsize_defaults["cbar_tick_label"],
direction=plot_properties["cbar_tick_direction"],
)
cb.ax.yaxis.labelpad = plot_properties["cbar_label_pad"]
# workaround for issue with viewers, see colorbar docstring
cb.solids.set_edgecolor("face")
ax.set_xlabel(xlabel, fontsize=fontsize_defaults["xlabel"], fontname=fontname)
ax.set_ylabel(ylabel, fontsize=fontsize_defaults["ylabel"], fontname=fontname)
# Separate graticule coordinate rotation
if rot_graticule or graticule_coord is not None:
if coord is None:
coord = "G" # TODO: Not implemented coordinate rotation!
rotated_grid_lines, where_zero = CreateRotatedGraticule(
rot,
# coordtransform=coord+graticule_coord,
t_step=rot_graticule_properties["t_step"],
p_step=rot_graticule_properties["p_step"],
)
for i, g_line in enumerate(rotated_grid_lines):
if i in where_zero:
linewidth = rot_graticule_properties["g_linewidth"] * 2.5
else:
linewidth = rot_graticule_properties["g_linewidth"]
plt.plot(
*g_line,
linewidth=linewidth,
linestyle=rot_graticule_properties["g_linestyle"],
color=rot_graticule_properties["g_color"],
alpha=rot_graticule_properties["g_alpha"],
)
# Top right label
if rlabel is not None:
plt.text(
0.975,
0.925,
rlabel,
ha="right",
va="center",
fontsize=fontsize_defaults["cbar_label"],
fontname=fontname,
transform=ax.transAxes,
)
# Top left label
if llabel is not None:
plt.text(
0.025,
0.925,
llabel,
ha="left",
va="center",
fontsize=fontsize_defaults["cbar_label"],
fontname=fontname,
transform=ax.transAxes,
)
plt.draw()
return ret
| (m=None, fig=None, rot=None, coord=None, unit='', xsize=1000, width=None, nest=False, min=None, max=None, flip='astro', format='%g', cbar=True, cmap='viridis', norm=None, norm_dict=None, graticule=False, graticule_labels=False, rot_graticule=False, graticule_coord=None, override_rot_graticule_properties=None, return_only_data=False, projection_type='mollweide', cb_orientation='horizontal', xlabel=None, ylabel=None, longitude_grid_spacing=60, latitude_grid_spacing=30, override_plot_properties=None, title=None, rlabel=None, llabel=None, xtick_label_color='black', ytick_label_color='black', graticule_color=None, fontname=None, fontsize=None, phi_convention='counterclockwise', custom_xtick_labels=None, custom_ytick_labels=None, cbar_ticks=None, show_tickmarkers=False, extend=None, invRot=True, sub=111, reuse_axes=False, margins=None, hold=False, remove_dip=False, remove_mono=False, gal_cut=0, **kwargs) |
37,722 | healpy.fitsfunc | read_alm | Read alm from a fits file.
In the fits file, the alm are written
with explicit index scheme, index = l**2+l+m+1, while healpix cxx
uses index = m*(2*lmax+1-m)/2+l. The conversion is done in this
function.
Parameters
----------
filename : str or HDUList or HDU or pathlib.Path instance
The name of the fits file to read
hdu : int, or tuple of int, optional
The header to read. Start at 0. Default: hdu=1
return_mmax : bool, optional
If true, both the alms and mmax is returned in a tuple. Default: return_mmax=False
Returns
-------
alms[, mmax] : complex array or tuple of a complex array and an int
The alms read from the file and optionally mmax read from the file
| def read_alm(filename, hdu=1, return_mmax=False):
"""Read alm from a fits file.
In the fits file, the alm are written
with explicit index scheme, index = l**2+l+m+1, while healpix cxx
uses index = m*(2*lmax+1-m)/2+l. The conversion is done in this
function.
Parameters
----------
filename : str or HDUList or HDU or pathlib.Path instance
The name of the fits file to read
hdu : int, or tuple of int, optional
The header to read. Start at 0. Default: hdu=1
return_mmax : bool, optional
If true, both the alms and mmax is returned in a tuple. Default: return_mmax=False
Returns
-------
alms[, mmax] : complex array or tuple of a complex array and an int
The alms read from the file and optionally mmax read from the file
"""
alms = []
lmaxtot = None
mmaxtot = None
opened_file = False
if isinstance(filename, allowed_paths):
filename = pf.open(filename)
opened_file = True
for unit in np.atleast_1d(hdu):
idx, almr, almi = [_get_hdu(filename, hdu=unit).data.field(i) for i in range(3)]
l = np.floor(np.sqrt(idx - 1)).astype(int)
m = idx - l ** 2 - l - 1
if (m < 0).any():
raise ValueError("Negative m value encountered !")
lmax = l.max()
mmax = m.max()
if lmaxtot is None:
lmaxtot = lmax
mmaxtot = mmax
else:
if lmaxtot != lmax or mmaxtot != mmax:
raise RuntimeError(
"read_alm: harmonic expansion order in {} HDUs {} does not "
"match".format(filename, unit, hdu)
)
alm = almr * (0 + 0j)
i = Alm.getidx(lmax, l, m)
alm.real[i] = almr
alm.imag[i] = almi
alms.append(alm)
if opened_file:
filename.close()
if len(alms) == 1:
alm = alms[0]
else:
alm = np.array(alms)
if return_mmax:
return alm, mmax
else:
return alm
| (filename, hdu=1, return_mmax=False) |
37,723 | healpy.fitsfunc | read_cl | Reads Cl from a healpix file, as IDL fits2cl.
Parameters
----------
filename : str or HDUList or HDU or pathlib.Path instance
the fits file name
Returns
-------
cl : array
the cl array
| def read_cl(filename):
"""Reads Cl from a healpix file, as IDL fits2cl.
Parameters
----------
filename : str or HDUList or HDU or pathlib.Path instance
the fits file name
Returns
-------
cl : array
the cl array
"""
opened_file = False
if isinstance(filename, allowed_paths):
filename = pf.open(filename)
opened_file = True
fits_hdu = _get_hdu(filename, hdu=1)
cl = np.array([fits_hdu.data.field(n) for n in range(len(fits_hdu.columns))])
if opened_file:
filename.close()
if len(cl) == 1:
return cl[0]
else:
return cl
| (filename) |
37,724 | healpy.fitsfunc | read_map | Read a healpix map from a fits file. Partial-sky files,
if properly identified, are expanded to full size and filled with UNSEEN.
.. warning::
Starting from healpy 1.15.0, if you do not specify `dtype`,
the map will be read in memory with the same precision it is stored on disk.
Previously, by default `healpy` wrote maps in `float32` and then upcast to
`float64` when reading to memory. To reproduce the same behaviour of `healpy`
1.14.0 and below, set `dtype=np.float64` in `read_map`.
Parameters
----------
filename : str or HDU or HDUList or pathlib.Path instance
the fits file name
field : int or tuple of int, or None, 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)
If the fits file is a partial-sky file, field=0 corresponds to the
first column after the pixel index column.
If None, all columns are read in.
dtype : data type or list of data types, optional
Force the conversion to some type. Passing a list allows different
types for each field. In that case, the length of the list must
correspond to the length of the field parameter.
If None, keep the dtype of the input FITS file
Default: Preserve the data types in the file
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.
partial : bool, optional
If True, fits file is assumed to be a partial-sky file with explicit indexing,
if the indexing scheme cannot be determined from the header.
If False, implicit indexing is assumed. Default: False.
A partial sky file is one in which OBJECT=PARTIAL and INDXSCHM=EXPLICIT,
and the first column is then assumed to contain pixel indices.
A full sky file is one in which OBJECT=FULLSKY and INDXSCHM=IMPLICIT.
At least one of these keywords must be set for the indexing
scheme to be properly identified.
hdu : int, optional
the header number to look at (start at 0)
h : bool, optional
If True, return also the header. Default: False.
verbose : bool, deprecated
It has no effect
memmap : bool, optional
Argument passed to astropy.io.fits.open, if True, the map is not read into memory,
but only the required pixels are read when needed. Default: False.
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.
| def write_alm(
filename, alms, out_dtype=None, lmax=-1, mmax=-1, mmax_in=-1, overwrite=False
):
"""Write alms to a fits file.
In the fits file the alms are written
with explicit index scheme, index = l*l + l + m +1, possibly out of order.
By default write_alm makes a table with the same precision as the alms.
If specified, the lmax and mmax parameters truncate the input data to
include only alms for which l <= lmax and m <= mmax.
Parameters
----------
filename : str
The filename of the output fits file
alms : array, complex or list of arrays
A complex ndarray holding the alms, index = m*(2*lmax+1-m)/2+l, see Alm.getidx
lmax : int, optional
The maximum l in the output file
mmax : int, optional
The maximum m in the output file
out_dtype : data type, optional
data type in the output file (must be a numpy dtype). Default: *alms*.real.dtype
mmax_in : int, optional
maximum m in the input array
"""
if not cb.is_seq_of_seq(alms):
alms = [alms]
l2max = Alm.getlmax(len(alms[0]), mmax=mmax_in)
if lmax != -1 and lmax > l2max:
raise ValueError("Too big lmax in parameter")
elif lmax == -1:
lmax = l2max
if mmax_in == -1:
mmax_in = l2max
if mmax == -1:
mmax = lmax
if mmax > mmax_in:
mmax = mmax_in
if out_dtype is None:
out_dtype = alms[0].real.dtype
l, m = Alm.getlm(lmax)
idx = np.where((l <= lmax) * (m <= mmax))
l = l[idx]
m = m[idx]
idx_in_original = Alm.getidx(l2max, l=l, m=m)
index = l ** 2 + l + m + 1
hdulist = pf.HDUList()
for alm in alms:
out_data = np.empty(
len(index), dtype=[("index", "i"), ("real", out_dtype), ("imag", out_dtype)]
)
out_data["index"] = index
out_data["real"] = alm.real[idx_in_original]
out_data["imag"] = alm.imag[idx_in_original]
cindex = pf.Column(
name="index",
format=getformat(np.int32),
unit="l*l+l+m+1",
array=out_data["index"],
)
creal = pf.Column(
name="real",
format=getformat(out_dtype),
unit="unknown",
array=out_data["real"],
)
cimag = pf.Column(
name="imag",
format=getformat(out_dtype),
unit="unknown",
array=out_data["imag"],
)
tbhdu = pf.BinTableHDU.from_columns([cindex, creal, cimag])
hdulist.append(tbhdu)
# Add str to convert pathlib.Path into str
# Due to https://github.com/astropy/astropy/issues/10594
hdulist.writeto(str(filename), overwrite=overwrite)
| (filename, field=0, dtype=None, nest=False, partial=False, hdu=1, h=False, verbose=True, memmap=False) |
37,725 | healpy.pixelfunc | remove_dipole | Fit and subtract the dipole and the monopole from the given map m.
Parameters
----------
m : float, array-like
the map to which a dipole is fitted and subtracted, accepts masked arrays
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] are not taken into account
fitval : bool
whether to return or not the fitted values of monopole and dipole
copy : bool
whether to modify input map or not (by default, make a copy)
verbose : bool
deprecated, no effect
Returns
-------
res : array or tuple of length 3
if fitval is False, returns map with monopole and dipole subtracted,
otherwise, returns map (array, in res[0]), monopole (float, in res[1]),
dipole_vector (array, in res[2])
See Also
--------
fit_dipole, fit_monopole, remove_monopole
| def xyf2pix(nside, x, y, face, nest=False):
"""xyf2pix : nside,x,y,face,nest=False -> ipix (default:RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
pix : int or array of int
The healpix pixel numbers. Scalar if all input are scalar, array otherwise.
Usual numpy broadcasting rules apply.
See Also
--------
pix2xyf
Examples
--------
>>> import healpy as hp
>>> hp.xyf2pix(16, 8, 8, 4)
1440
>>> print(hp.xyf2pix(16, [8, 8, 8, 15, 0], [8, 8, 7, 15, 0], [4, 0, 5, 0, 8]))
[1440 427 1520 0 3068]
"""
check_nside(nside, nest=nest)
if nest:
return pixlib._xyf2pix_nest(nside, x, y, face)
else:
return pixlib._xyf2pix_ring(nside, x, y, face)
| (m, nest=False, bad=-1.6375e+30, gal_cut=0, fitval=False, copy=True, verbose=True) |
37,726 | healpy.pixelfunc | remove_monopole | Fit and subtract the monopole from the given map m.
Parameters
----------
m : float, array-like
the map to which a monopole is fitted and subtracted
nest : bool
if ``False`` m is assumed in RING scheme, otherwise map is NESTED
bad : float
bad values of pixel, default to :const:`UNSEEN`.
gal_cut : float [degrees]
pixels at latitude in [-gal_cut;+gal_cut] are not taken into account
fitval : bool
whether to return or not the fitted value of monopole
copy : bool
whether to modify input map or not (by default, make a copy)
verbose: bool
deprecated, no effect
Returns
-------
res : array or tuple of length 3
if fitval is False, returns map with monopole subtracted,
otherwise, returns map (array, in res[0]) and monopole (float, in res[1])
See Also
--------
fit_dipole, fit_monopole, remove_dipole
| def xyf2pix(nside, x, y, face, nest=False):
"""xyf2pix : nside,x,y,face,nest=False -> ipix (default:RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
pix : int or array of int
The healpix pixel numbers. Scalar if all input are scalar, array otherwise.
Usual numpy broadcasting rules apply.
See Also
--------
pix2xyf
Examples
--------
>>> import healpy as hp
>>> hp.xyf2pix(16, 8, 8, 4)
1440
>>> print(hp.xyf2pix(16, [8, 8, 8, 15, 0], [8, 8, 7, 15, 0], [4, 0, 5, 0, 8]))
[1440 427 1520 0 3068]
"""
check_nside(nside, nest=nest)
if nest:
return pixlib._xyf2pix_nest(nside, x, y, face)
else:
return pixlib._xyf2pix_ring(nside, x, y, face)
| (m, nest=False, bad=-1.6375e+30, gal_cut=0, fitval=False, copy=True, verbose=True) |
37,727 | healpy.pixelfunc | reorder | Reorder a healpix map from RING/NESTED ordering to NESTED/RING
Parameters
----------
map_in : array-like
the input map to reorder, accepts masked arrays
inp, out : ``'RING'`` or ``'NESTED'``
define the input and output ordering
r2n : bool
if True, reorder from RING to NESTED
n2r : bool
if True, reorder from NESTED to RING
Returns
-------
map_out : array-like
the reordered map, as masked array if the input was a
masked array
Notes
-----
if ``r2n`` or ``n2r`` is defined, override ``inp`` and ``out``.
See Also
--------
nest2ring, ring2nest
Examples
--------
>>> import healpy as hp
>>> hp.reorder(np.arange(48), r2n = True)
array([13, 5, 4, 0, 15, 7, 6, 1, 17, 9, 8, 2, 19, 11, 10, 3, 28,
20, 27, 12, 30, 22, 21, 14, 32, 24, 23, 16, 34, 26, 25, 18, 44, 37,
36, 29, 45, 39, 38, 31, 46, 41, 40, 33, 47, 43, 42, 35])
>>> hp.reorder(np.arange(12), n2r = True)
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> hp.reorder(hp.ma(np.arange(12.)), n2r = True)
masked_array(data = [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.],
mask = False,
fill_value = -1.6375e+30)
<BLANKLINE>
>>> m = [np.arange(12.), np.arange(12.), np.arange(12.)]
>>> m[0][2] = hp.UNSEEN
>>> m[1][2] = hp.UNSEEN
>>> m[2][2] = hp.UNSEEN
>>> m = hp.ma(m)
>>> hp.reorder(m, n2r = True)
masked_array(data =
[[0.0 1.0 -- 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0]
[0.0 1.0 -- 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0]
[0.0 1.0 -- 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0]],
mask =
[[False False True False False False False False False False False False]
[False False True False False False False False False False False False]
[False False True False False False False False False False False False]],
fill_value = -1.6375e+30)
<BLANKLINE>
| def accept_ma(f):
"""Wraps a function in order to convert the input map from
a masked to a regular numpy array, and convert back the
output from a regular array to a masked array"""
@wraps(f)
def wrapper(map_in, *args, **kwds):
return_ma = is_ma(map_in)
m = ma_to_array(map_in)
out = f(m, *args, **kwds)
return ma(out) if return_ma else out
return wrapper
| (map_in, inp=None, out=None, r2n=None, n2r=None) |
37,728 | healpy.sphtfunc | resize_alm | Returns a resized copy of the input a_lm, either truncated or
padded with zeros.
Parameters
----------
alm : array or sequence of arrays, complex
A complex array of alm, or a sequence of such arrays.
Size of each array must be of the form mmax*(lmax-mmax+1)/2+lmax
lmax, mmax: int, scalar
maximum l and m multipole moments of the input alm
lmax_out, mmax_out: int, scalar
maximum l and m multipole moments of the output alm
Returns
-------
array or sequence of arrays, complex
A complex array of alm, or a sequence of such arrays.
Size of each array will be of the form mmax_out*(lmax_out-mmax_out+1)/2+lmax_out
| def resize_alm(alm, lmax, mmax, lmax_out, mmax_out):
"""Returns a resized copy of the input a_lm, either truncated or
padded with zeros.
Parameters
----------
alm : array or sequence of arrays, complex
A complex array of alm, or a sequence of such arrays.
Size of each array must be of the form mmax*(lmax-mmax+1)/2+lmax
lmax, mmax: int, scalar
maximum l and m multipole moments of the input alm
lmax_out, mmax_out: int, scalar
maximum l and m multipole moments of the output alm
Returns
-------
array or sequence of arrays, complex
A complex array of alm, or a sequence of such arrays.
Size of each array will be of the form mmax_out*(lmax_out-mmax_out+1)/2+lmax_out
"""
alm = np.array(alm)
if alm.ndim < 1 or alm.ndim > 2:
raise ValueError("incorrect dimensionality of the input a_lm")
if alm.ndim == 2:
return [resize_alm(almi, lmax, mmax, lmax_out, mmax_out) for almi in alm]
# alm is a 1D array
if alm.shape[0] != Alm.getsize(lmax, mmax):
raise ValueError("inconsistent number of input a_lm")
res = np.zeros(Alm.getsize(lmax_out, mmax_out), dtype=alm.dtype)
lmaxmin = min(lmax, lmax_out)
mmaxmin = min(mmax, mmax_out)
ofs_i, ofs_o = 0, 0
for m in range(0, mmaxmin + 1):
nval = lmaxmin - m + 1
res[ofs_o : ofs_o + nval] = alm[ofs_i : ofs_i + nval]
ofs_i += lmax - m + 1
ofs_o += lmax_out - m + 1
return res
| (alm, lmax, mmax, lmax_out, mmax_out) |
37,729 | healpy.pixelfunc | ring2nest | Convert pixel number from RING ordering to NESTED ordering.
Parameters
----------
nside : int, scalar or array-like
the healpix nside parameter
ipix : int, scalar or array-like
the pixel number in RING scheme
Returns
-------
ipix : int, scalar or array-like
the pixel number in NESTED scheme
See Also
--------
nest2ring, reorder
Examples
--------
>>> import healpy as hp
>>> hp.ring2nest(16, 1504)
1130
>>> print(hp.ring2nest(2, np.arange(10)))
[ 3 7 11 15 2 1 6 5 10 9]
>>> print(hp.ring2nest([1, 2, 4, 8], 11))
[ 11 13 61 253]
| def ring2nest(nside, ipix):
"""Convert pixel number from RING ordering to NESTED ordering.
Parameters
----------
nside : int, scalar or array-like
the healpix nside parameter
ipix : int, scalar or array-like
the pixel number in RING scheme
Returns
-------
ipix : int, scalar or array-like
the pixel number in NESTED scheme
See Also
--------
nest2ring, reorder
Examples
--------
>>> import healpy as hp
>>> hp.ring2nest(16, 1504)
1130
>>> print(hp.ring2nest(2, np.arange(10)))
[ 3 7 11 15 2 1 6 5 10 9]
>>> print(hp.ring2nest([1, 2, 4, 8], 11))
[ 11 13 61 253]
"""
check_nside(nside, nest=True)
return pixlib._ring2nest(nside, ipix)
| (nside, ipix) |
37,731 | healpy.zoomtool | set_g_clim | Set min/max value of the gnomview part of a mollzoom. | def set_g_clim(vmin, vmax):
"""Set min/max value of the gnomview part of a mollzoom."""
import pylab
f = pylab.gcf()
if not hasattr(f, "zoomtool"):
raise TypeError("The current figure has no zoomtool")
f.zoomtool.save_min = vmin
f.zoomtool.save_max = vmax
f.zoomtool._range_status = 2
f.zoomtool.draw_gnom()
| (vmin, vmax) |
37,732 | healpy.sphtfunc | smoothalm | Smooth alm with a Gaussian symmetric beam function.
Parameters
----------
alms : array or sequence of 3 arrays
Either an array representing one alm, or a sequence of arrays.
See *pol* parameter.
fwhm : float, optional
The full width half max parameter of the Gaussian. Default:0.0
[in radians]
sigma : float, optional
The sigma of the Gaussian. Override fwhm.
[in radians]
beam_window: array, optional
Custom beam window function. Override fwhm and sigma.
pol : bool, optional
If True, assumes input alms are TEB. Output will be TQU maps.
(input must be 1 or 3 alms)
If False, apply spin 0 harmonic transform to each alm.
(input can be any number of alms)
If there is only one input alm, it has no effect. Default: True.
mmax : None or int, optional
The maximum m for alm. Default: mmax=lmax
inplace : bool, optional
If True, the alm's are modified inplace if they are contiguous arrays
of type complex128. Otherwise, a copy of alm is made. Default: True.
verbose : bool, optional
Deprecated, has not effect.
Returns
-------
alms : array or sequence of 3 arrays
The smoothed alm. If alm[i] is a contiguous array of type complex128,
and *inplace* is True the smoothing is applied inplace.
Otherwise, a copy is made.
| def synalm(cls, lmax=None, mmax=None, new=False, verbose=True):
"""Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
"""
if not cb.is_seq(cls):
raise TypeError("cls must be an array or a sequence of arrays")
if not cb.is_seq_of_seq(cls, True):
# Only one spectrum
if lmax is None or lmax < 0:
lmax = len(cls) - 1
if mmax is None or mmax < 0:
mmax = lmax
cls_list = [np.asarray(cls, dtype=np.float64)]
szalm = Alm.getsize(lmax, mmax)
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list = [alm]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return alm
# From here, we interpret cls as a list of spectra
cls_list = list(cls)
maxsize = max([len(c) for c in cls if c is not None])
if lmax is None or lmax < 0:
lmax = maxsize - 1
if mmax is None or mmax < 0:
mmax = lmax
Nspec = sphtlib._getn(len(cls_list))
if Nspec <= 0:
if len(cls_list) == 4:
if new: ## new input order: TT EE BB TE -> TT EE BB TE 0 0
cls_list = [cls[0], cls[1], cls[2], cls[3], None, None]
else: ## old input order: TT TE EE BB -> TT TE 0 EE 0 BB
cls_list = [cls[0], cls[1], None, cls[2], None, cls[3]]
Nspec = 3
else:
raise TypeError(
"The sequence of arrays must have either 4 elements "
"or n(n+1)/2 elements (some may be None)"
)
szalm = Alm.getsize(lmax, mmax)
alms_list = []
for i in range(Nspec):
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list.append(alm)
if new: # new input order: input given by diagonal, should be given by row
cls_list = new_to_old_spectra_order(cls_list)
# ensure cls are float64
cls_list = [
(np.asarray(cl, dtype=np.float64) if cl is not None else None)
for cl in cls_list
]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return np.array(alms_list)
| (alms, fwhm=0.0, sigma=None, beam_window=None, pol=True, mmax=None, verbose=True, inplace=True) |
37,733 | healpy.sphtfunc | smoothing | Smooth a map with a Gaussian symmetric beam.
No removal of monopole or dipole is performed.
Parameters
----------
map_in : array or sequence of 3 arrays
Either an array representing one map, or a sequence of
3 arrays representing 3 maps, accepts masked arrays
fwhm : float, optional
The full width half max parameter of the Gaussian [in
radians]. Default:0.0
sigma : float, optional
The sigma of the Gaussian [in radians]. Override fwhm.
beam_window: array, optional
Custom beam window function. Override fwhm and sigma.
pol : bool, optional
If True, assumes input maps are TQU. Output will be TQU maps.
(input must be 1 or 3 alms)
If False, each map is assumed to be a spin 0 map and is
treated independently (input can be any number of alms).
If there is only one input map, it has no effect. Default: True.
iter : int, scalar, optional
Number of iteration (default: 3)
lmax : int, scalar, optional
Maximum l of the power spectrum. Default: 3*nside-1
mmax : int, scalar, optional
Maximum m of the alm. Default: lmax
use_weights: bool, scalar, optional
If True, use the ring weighting. Default: False.
use_pixel_weights: bool, optional
If True, use pixel by pixel weighting, healpy will automatically download the weights, if needed
See the map2alm docs for details about weighting
datapath : None or str, optional
If given, the directory where to find the pixel weights data.
See the docstring of `map2alm` for details on how to set it up
verbose : bool, optional
Deprecated, has not effect.
nest : bool, optional
If True, the input map ordering is assumed to be NESTED. Default: False (RING)
This function will temporary reorder the NESTED map into RING to perform the
smoothing and order the output back to NESTED. If the map is in RING ordering
no internal reordering will be performed.
Returns
-------
maps : array or list of 3 arrays
The smoothed map(s)
| def synalm(cls, lmax=None, mmax=None, new=False, verbose=True):
"""Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
"""
if not cb.is_seq(cls):
raise TypeError("cls must be an array or a sequence of arrays")
if not cb.is_seq_of_seq(cls, True):
# Only one spectrum
if lmax is None or lmax < 0:
lmax = len(cls) - 1
if mmax is None or mmax < 0:
mmax = lmax
cls_list = [np.asarray(cls, dtype=np.float64)]
szalm = Alm.getsize(lmax, mmax)
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list = [alm]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return alm
# From here, we interpret cls as a list of spectra
cls_list = list(cls)
maxsize = max([len(c) for c in cls if c is not None])
if lmax is None or lmax < 0:
lmax = maxsize - 1
if mmax is None or mmax < 0:
mmax = lmax
Nspec = sphtlib._getn(len(cls_list))
if Nspec <= 0:
if len(cls_list) == 4:
if new: ## new input order: TT EE BB TE -> TT EE BB TE 0 0
cls_list = [cls[0], cls[1], cls[2], cls[3], None, None]
else: ## old input order: TT TE EE BB -> TT TE 0 EE 0 BB
cls_list = [cls[0], cls[1], None, cls[2], None, cls[3]]
Nspec = 3
else:
raise TypeError(
"The sequence of arrays must have either 4 elements "
"or n(n+1)/2 elements (some may be None)"
)
szalm = Alm.getsize(lmax, mmax)
alms_list = []
for i in range(Nspec):
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list.append(alm)
if new: # new input order: input given by diagonal, should be given by row
cls_list = new_to_old_spectra_order(cls_list)
# ensure cls are float64
cls_list = [
(np.asarray(cl, dtype=np.float64) if cl is not None else None)
for cl in cls_list
]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return np.array(alms_list)
| (map_in, fwhm=0.0, sigma=None, beam_window=None, pol=True, iter=3, lmax=None, mmax=None, use_weights=False, use_pixel_weights=False, datapath=None, verbose=True, nest=False) |
37,735 | healpy.sphtfunc | synalm | Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
| def synalm(cls, lmax=None, mmax=None, new=False, verbose=True):
"""Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
"""
if not cb.is_seq(cls):
raise TypeError("cls must be an array or a sequence of arrays")
if not cb.is_seq_of_seq(cls, True):
# Only one spectrum
if lmax is None or lmax < 0:
lmax = len(cls) - 1
if mmax is None or mmax < 0:
mmax = lmax
cls_list = [np.asarray(cls, dtype=np.float64)]
szalm = Alm.getsize(lmax, mmax)
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list = [alm]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return alm
# From here, we interpret cls as a list of spectra
cls_list = list(cls)
maxsize = max([len(c) for c in cls if c is not None])
if lmax is None or lmax < 0:
lmax = maxsize - 1
if mmax is None or mmax < 0:
mmax = lmax
Nspec = sphtlib._getn(len(cls_list))
if Nspec <= 0:
if len(cls_list) == 4:
if new: ## new input order: TT EE BB TE -> TT EE BB TE 0 0
cls_list = [cls[0], cls[1], cls[2], cls[3], None, None]
else: ## old input order: TT TE EE BB -> TT TE 0 EE 0 BB
cls_list = [cls[0], cls[1], None, cls[2], None, cls[3]]
Nspec = 3
else:
raise TypeError(
"The sequence of arrays must have either 4 elements "
"or n(n+1)/2 elements (some may be None)"
)
szalm = Alm.getsize(lmax, mmax)
alms_list = []
for i in range(Nspec):
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list.append(alm)
if new: # new input order: input given by diagonal, should be given by row
cls_list = new_to_old_spectra_order(cls_list)
# ensure cls are float64
cls_list = [
(np.asarray(cl, dtype=np.float64) if cl is not None else None)
for cl in cls_list
]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return np.array(alms_list)
| (cls, lmax=None, mmax=None, new=False, verbose=True) |
37,736 | healpy.sphtfunc | synfast | Create a map(s) from cl(s).
You can choose a random seed using `numpy.random.seed(SEEDVALUE)`
before calling `synfast`.
Parameters
----------
cls : array or tuple of array
A cl or a list of cl (either 4 or 6, see :func:`synalm`)
nside : int, scalar
The nside of the output map(s)
lmax : int, scalar, optional
Maximum l for alm. Default: min of 3*nside-1 or length of the cls - 1
mmax : int, scalar, optional
Maximum m for alm.
alm : bool, scalar, optional
If True, return also alm(s). Default: False.
pol : bool, optional
If True, assumes input cls are TEB and correlation. Output will be TQU maps.
(input must be 1, 4 or 6 cl's)
If False, fields are assumed to be described by spin 0 spherical harmonics.
(input can be any number of cl's)
If there is only one input cl, it has no effect. Default: True.
pixwin : bool, scalar, optional
If True, convolve the alm by the pixel window function. Default: False.
fwhm : float, scalar, optional
The fwhm of the Gaussian used to smooth the map (applied on alm)
[in radians]
sigma : float, scalar, optional
The sigma of the Gaussian used to smooth the map (applied on alm)
[in radians]
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
maps : array or tuple of arrays
The output map (possibly list of maps if polarized input).
or, if alm is True, a tuple of (map,alm)
(alm possibly a list of alm if polarized input)
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
| def synalm(cls, lmax=None, mmax=None, new=False, verbose=True):
"""Generate a set of alm given cl.
The cl are given as a float array. Corresponding alm are generated.
If lmax is None, it is assumed lmax=cl.size-1
If mmax is None, it is assumed mmax=lmax.
Parameters
----------
cls : float, array or tuple of arrays
Either one cl (1D array) or a tuple of either 4 cl
or of n*(n+1)/2 cl.
Some of the cl may be None, implying no
cross-correlation. See *new* parameter.
lmax : int, scalar, optional
The lmax (if None or <0, the largest size-1 of cls)
mmax : int, scalar, optional
The mmax (if None or <0, =lmax)
new : bool, optional
If True, use the new ordering of cl's, ie by diagonal
(e.g. TT, EE, BB, TE, EB, TB or TT, EE, BB, TE if 4 cl as input).
If False, use the old ordering, ie by row
(e.g. TT, TE, TB, EE, EB, BB or TT, TE, EE, BB if 4 cl as input).
Returns
-------
alms : array or list of arrays
the generated alm if one spectrum is given, or a list of n alms
(with n(n+1)/2 the number of input cl, or n=3 if there are 4 input cl).
Notes
-----
We don't plan to change the default order anymore, that would break old
code in a way difficult to debug.
"""
if not cb.is_seq(cls):
raise TypeError("cls must be an array or a sequence of arrays")
if not cb.is_seq_of_seq(cls, True):
# Only one spectrum
if lmax is None or lmax < 0:
lmax = len(cls) - 1
if mmax is None or mmax < 0:
mmax = lmax
cls_list = [np.asarray(cls, dtype=np.float64)]
szalm = Alm.getsize(lmax, mmax)
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list = [alm]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return alm
# From here, we interpret cls as a list of spectra
cls_list = list(cls)
maxsize = max([len(c) for c in cls if c is not None])
if lmax is None or lmax < 0:
lmax = maxsize - 1
if mmax is None or mmax < 0:
mmax = lmax
Nspec = sphtlib._getn(len(cls_list))
if Nspec <= 0:
if len(cls_list) == 4:
if new: ## new input order: TT EE BB TE -> TT EE BB TE 0 0
cls_list = [cls[0], cls[1], cls[2], cls[3], None, None]
else: ## old input order: TT TE EE BB -> TT TE 0 EE 0 BB
cls_list = [cls[0], cls[1], None, cls[2], None, cls[3]]
Nspec = 3
else:
raise TypeError(
"The sequence of arrays must have either 4 elements "
"or n(n+1)/2 elements (some may be None)"
)
szalm = Alm.getsize(lmax, mmax)
alms_list = []
for i in range(Nspec):
alm = np.zeros(szalm, "D")
alm.real = np.random.standard_normal(szalm)
alm.imag = np.random.standard_normal(szalm)
alms_list.append(alm)
if new: # new input order: input given by diagonal, should be given by row
cls_list = new_to_old_spectra_order(cls_list)
# ensure cls are float64
cls_list = [
(np.asarray(cl, dtype=np.float64) if cl is not None else None)
for cl in cls_list
]
sphtlib._synalm(cls_list, alms_list, lmax, mmax)
return np.array(alms_list)
| (cls, nside, lmax=None, mmax=None, alm=False, pol=True, pixwin=False, fwhm=0.0, sigma=None, new=False, verbose=True) |
37,737 | healpy.pixelfunc | ud_grade | Upgrade or degrade resolution of a map (or list of maps).
in degrading the resolution, ud_grade sets the value of the superpixel
as the mean of the children pixels.
Parameters
----------
map_in : array-like or sequence of array-like
the input map(s) (if a sequence of maps, all must have same size)
nside_out : int
the desired nside of the output map(s)
pess : bool
if ``True``, in degrading, reject pixels which contains
a bad sub_pixel. Otherwise, estimate average with good pixels
order_in, order_out : str
pixel ordering of input and output ('RING' or 'NESTED')
power : float
if non-zero, divide the result by (nside_in/nside_out)**power
Examples:
power=-2 keeps the sum of the map invariant (useful for hitmaps),
power=2 divides the mean by another factor of (nside_in/nside_out)**2
(useful for variance maps)
dtype : type
the type of the output map
Returns
-------
map_out : array-like or sequence of array-like
the upgraded or degraded map(s)
Examples
--------
>>> import healpy as hp
>>> hp.ud_grade(np.arange(48.), 1)
array([ 5.5 , 7.25, 9. , 10.75, 21.75, 21.75, 23.75, 25.75,
36.5 , 38.25, 40. , 41.75])
| def accept_ma(f):
"""Wraps a function in order to convert the input map from
a masked to a regular numpy array, and convert back the
output from a regular array to a masked array"""
@wraps(f)
def wrapper(map_in, *args, **kwds):
return_ma = is_ma(map_in)
m = ma_to_array(map_in)
out = f(m, *args, **kwds)
return ma(out) if return_ma else out
return wrapper
| (map_in, nside_out, pess=False, order_in='RING', order_out=None, power=None, dtype=None) |
37,739 | healpy.pixelfunc | vec2ang | vec2ang: vectors [x, y, z] -> theta[rad], phi[rad]
Parameters
----------
vectors : float, array-like
the vector(s) to convert, shape is (3,) or (N, 3)
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be co-latitude and longitude in radians (default)
Returns
-------
theta, phi : float, tuple of two arrays
the colatitude and longitude in radians
See Also
--------
ang2vec, rotator.vec2dir, rotator.dir2vec
| def vec2ang(vectors, lonlat=False):
"""vec2ang: vectors [x, y, z] -> theta[rad], phi[rad]
Parameters
----------
vectors : float, array-like
the vector(s) to convert, shape is (3,) or (N, 3)
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be co-latitude and longitude in radians (default)
Returns
-------
theta, phi : float, tuple of two arrays
the colatitude and longitude in radians
See Also
--------
ang2vec, rotator.vec2dir, rotator.dir2vec
"""
vectors = vectors.reshape(-1, 3)
dnorm = np.sqrt(np.sum(np.square(vectors), axis=1))
theta = np.arccos(vectors[:, 2] / dnorm)
phi = np.arctan2(vectors[:, 1], vectors[:, 0])
phi[phi < 0] += 2 * np.pi
if lonlat:
return thetaphi2lonlat(theta, phi)
else:
return theta, phi
| (vectors, lonlat=False) |
37,740 | healpy.rotator | vec2dir | Transform a vector to angle given by theta,phi.
Parameters
----------
vec : float, scalar or array-like
The vector to transform (shape (3,) or (3,N)),
or x component (scalar or shape (N,)) if vy and vz are given
vy : float, scalar or array-like, optional
The y component of the vector (scalar or shape (N,))
vz : float, scalar or array-like, optional
The z component of the vector (scalar or shape (N,))
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be longitude and co-latitude in radians (default)
Returns
-------
angles : float, array
The angles (unit depending on *lonlat*) in an array of
shape (2,) (if scalar input) or (2, N)
See Also
--------
:func:`dir2vec`, :func:`pixelfunc.ang2vec`, :func:`pixelfunc.vec2ang`
| def vec2dir(vec, vy=None, vz=None, lonlat=False):
"""Transform a vector to angle given by theta,phi.
Parameters
----------
vec : float, scalar or array-like
The vector to transform (shape (3,) or (3,N)),
or x component (scalar or shape (N,)) if vy and vz are given
vy : float, scalar or array-like, optional
The y component of the vector (scalar or shape (N,))
vz : float, scalar or array-like, optional
The z component of the vector (scalar or shape (N,))
lonlat : bool, optional
If True, return angles will be longitude and latitude in degree,
otherwise, angles will be longitude and co-latitude in radians (default)
Returns
-------
angles : float, array
The angles (unit depending on *lonlat*) in an array of
shape (2,) (if scalar input) or (2, N)
See Also
--------
:func:`dir2vec`, :func:`pixelfunc.ang2vec`, :func:`pixelfunc.vec2ang`
"""
if np.any(np.isnan(vec)):
return np.nan, np.nan
if vy is None and vz is None:
vx, vy, vz = vec
elif vy is not None and vz is not None:
vx = vec
else:
raise TypeError("You must either give both vy and vz or none of them")
r = np.sqrt(vx ** 2 + vy ** 2 + vz ** 2)
ang = np.empty((2, r.size))
ang[0, :] = np.arccos(vz / r)
ang[1, :] = np.arctan2(vy, vx)
if lonlat:
ang = np.degrees(ang)
np.negative(ang[0, :], ang[0, :])
ang[0, :] += 90.0
return ang[::-1, :].squeeze()
else:
return ang.squeeze()
| (vec, vy=None, vz=None, lonlat=False) |
37,741 | healpy.pixelfunc | vec2pix | vec2pix : nside,x,y,z,nest=False -> ipix (default:RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
x,y,z : floats or array-like
vector coordinates defining point on the sphere
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
ipix : int, scalar or array-like
The healpix pixel number corresponding to input vector. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, pix2ang, pix2vec
Examples
--------
>>> import healpy as hp
>>> hp.vec2pix(16, 1, 0, 0)
1504
>>> print(hp.vec2pix(16, [1, 0], [0, 1], [0, 0]))
[1504 1520]
>>> print(hp.vec2pix([1, 2, 4, 8], 1, 0, 0))
[ 4 20 88 368]
| def vec2pix(nside, x, y, z, nest=False):
"""vec2pix : nside,x,y,z,nest=False -> ipix (default:RING)
Parameters
----------
nside : int or array-like
The healpix nside parameter, must be a power of 2, less than 2**30
x,y,z : floats or array-like
vector coordinates defining point on the sphere
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
ipix : int, scalar or array-like
The healpix pixel number corresponding to input vector. Scalar if all input
are scalar, array otherwise. Usual numpy broadcasting rules apply.
See Also
--------
ang2pix, pix2ang, pix2vec
Examples
--------
>>> import healpy as hp
>>> hp.vec2pix(16, 1, 0, 0)
1504
>>> print(hp.vec2pix(16, [1, 0], [0, 1], [0, 0]))
[1504 1520]
>>> print(hp.vec2pix([1, 2, 4, 8], 1, 0, 0))
[ 4 20 88 368]
"""
if nest:
return pixlib._vec2pix_nest(nside, x, y, z)
else:
return pixlib._vec2pix_ring(nside, x, y, z)
| (nside, x, y, z, nest=False) |
37,744 | healpy.fitsfunc | write_alm | Write alms to a fits file.
In the fits file the alms are written
with explicit index scheme, index = l*l + l + m +1, possibly out of order.
By default write_alm makes a table with the same precision as the alms.
If specified, the lmax and mmax parameters truncate the input data to
include only alms for which l <= lmax and m <= mmax.
Parameters
----------
filename : str
The filename of the output fits file
alms : array, complex or list of arrays
A complex ndarray holding the alms, index = m*(2*lmax+1-m)/2+l, see Alm.getidx
lmax : int, optional
The maximum l in the output file
mmax : int, optional
The maximum m in the output file
out_dtype : data type, optional
data type in the output file (must be a numpy dtype). Default: *alms*.real.dtype
mmax_in : int, optional
maximum m in the input array
| def write_alm(
filename, alms, out_dtype=None, lmax=-1, mmax=-1, mmax_in=-1, overwrite=False
):
"""Write alms to a fits file.
In the fits file the alms are written
with explicit index scheme, index = l*l + l + m +1, possibly out of order.
By default write_alm makes a table with the same precision as the alms.
If specified, the lmax and mmax parameters truncate the input data to
include only alms for which l <= lmax and m <= mmax.
Parameters
----------
filename : str
The filename of the output fits file
alms : array, complex or list of arrays
A complex ndarray holding the alms, index = m*(2*lmax+1-m)/2+l, see Alm.getidx
lmax : int, optional
The maximum l in the output file
mmax : int, optional
The maximum m in the output file
out_dtype : data type, optional
data type in the output file (must be a numpy dtype). Default: *alms*.real.dtype
mmax_in : int, optional
maximum m in the input array
"""
if not cb.is_seq_of_seq(alms):
alms = [alms]
l2max = Alm.getlmax(len(alms[0]), mmax=mmax_in)
if lmax != -1 and lmax > l2max:
raise ValueError("Too big lmax in parameter")
elif lmax == -1:
lmax = l2max
if mmax_in == -1:
mmax_in = l2max
if mmax == -1:
mmax = lmax
if mmax > mmax_in:
mmax = mmax_in
if out_dtype is None:
out_dtype = alms[0].real.dtype
l, m = Alm.getlm(lmax)
idx = np.where((l <= lmax) * (m <= mmax))
l = l[idx]
m = m[idx]
idx_in_original = Alm.getidx(l2max, l=l, m=m)
index = l ** 2 + l + m + 1
hdulist = pf.HDUList()
for alm in alms:
out_data = np.empty(
len(index), dtype=[("index", "i"), ("real", out_dtype), ("imag", out_dtype)]
)
out_data["index"] = index
out_data["real"] = alm.real[idx_in_original]
out_data["imag"] = alm.imag[idx_in_original]
cindex = pf.Column(
name="index",
format=getformat(np.int32),
unit="l*l+l+m+1",
array=out_data["index"],
)
creal = pf.Column(
name="real",
format=getformat(out_dtype),
unit="unknown",
array=out_data["real"],
)
cimag = pf.Column(
name="imag",
format=getformat(out_dtype),
unit="unknown",
array=out_data["imag"],
)
tbhdu = pf.BinTableHDU.from_columns([cindex, creal, cimag])
hdulist.append(tbhdu)
# Add str to convert pathlib.Path into str
# Due to https://github.com/astropy/astropy/issues/10594
hdulist.writeto(str(filename), overwrite=overwrite)
| (filename, alms, out_dtype=None, lmax=-1, mmax=-1, mmax_in=-1, overwrite=False) |
37,745 | healpy.fitsfunc | write_cl | Writes Cl into a healpix file, as IDL cl2fits.
Parameters
----------
filename : str
the fits file name
cl : array
the cl array to write to file
dtype : np.dtype (optional)
The datatype in which the columns will be stored. If not supplied,
the dtype of the input cl will be used. This changed in `healpy` 1.15.0,
in previous versions, cl by default were saved in `float64`.
overwrite : bool, optional
If True, existing file is silently overwritten. Otherwise trying to write
an existing file raises an OSError.
| def write_cl(filename, cl, dtype=None, overwrite=False):
"""Writes Cl into a healpix file, as IDL cl2fits.
Parameters
----------
filename : str
the fits file name
cl : array
the cl array to write to file
dtype : np.dtype (optional)
The datatype in which the columns will be stored. If not supplied,
the dtype of the input cl will be used. This changed in `healpy` 1.15.0,
in previous versions, cl by default were saved in `float64`.
overwrite : bool, optional
If True, existing file is silently overwritten. Otherwise trying to write
an existing file raises an OSError.
"""
if dtype is None:
dtype = cl.dtype if isinstance(cl, np.ndarray) else cl[0].dtype
# check the dtype and convert it
fitsformat = getformat(dtype)
column_names = ["TEMPERATURE", "GRADIENT", "CURL", "G-T", "C-T", "C-G"]
if len(np.shape(cl)) == 2:
cols = [
pf.Column(name=column_name, format="%s" % fitsformat, array=column_cl)
for column_name, column_cl in zip(column_names[: len(cl)], cl)
]
elif len(np.shape(cl)) == 1:
# we write only TT
cols = [pf.Column(name="TEMPERATURE", format="%s" % fitsformat, array=cl)]
else:
raise RuntimeError("write_cl: Expected one or more vectors of equal length")
tbhdu = pf.BinTableHDU.from_columns(cols)
# add needed keywords
tbhdu.header["CREATOR"] = "healpy"
# Add str to convert pathlib.Path into str
# Due to https://github.com/astropy/astropy/issues/10594
tbhdu.writeto(str(filename), overwrite=overwrite)
| (filename, cl, dtype=None, overwrite=False) |
37,746 | healpy.fitsfunc | write_map | Writes a healpix map into a healpix FITS file.
.. warning::
Starting from healpy 1.15.0, if you do not specify `dtype`,
the map will be written to disk with the same precision it is stored in memory.
Previously, by default `healpy` wrote maps in `float32`.
To reproduce the same behaviour of `healpy` 1.14.0 and below, set `dtype=np.float32`.
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)
partial : bool, optional
If True, fits file is written as a partial-sky file with explicit indexing.
Otherwise, implicit indexing is used. Default: False.
column_names : str or list
Column name or list of column names, if None here the default column names based on
the number of columns:
1 : "TEMPERATURE",
2 : ["Q_POLARISATION", "U_POLARISATION"],
3 : ["TEMPERATURE", "Q_POLARISATION", "U_POLARISATION"],
6 : ["II", "IQ", "IU", "QQ", "QU", "UU"]
COLUMN_1, COLUMN_2... otherwise (FITS is 1-based)
column_units : str or list
Units for each column, or same units for all columns.
extra_header : list
Extra records to add to FITS header.
dtype: np.dtype or list of np.dtypes, optional
The datatype in which the columns will be stored. Will be converted
internally from the numpy datatype to the fits convention. If a list,
the length must correspond to the number of map arrays.
Default: use the data type of the input array(s)
.. note::
this changed in 1.15.0, previous versions saved in float32
by default
overwrite : bool, optional
If True, existing file is silently overwritten. Otherwise trying to write
an existing file raises an OSError (IOError for Python 2).
| def write_map(
filename,
m,
nest=False,
dtype=None,
fits_IDL=True,
coord=None,
partial=False,
column_names=None,
column_units=None,
extra_header=(),
overwrite=False,
):
"""Writes a healpix map into a healpix FITS file.
.. warning::
Starting from healpy 1.15.0, if you do not specify `dtype`,
the map will be written to disk with the same precision it is stored in memory.
Previously, by default `healpy` wrote maps in `float32`.
To reproduce the same behaviour of `healpy` 1.14.0 and below, set `dtype=np.float32`.
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)
partial : bool, optional
If True, fits file is written as a partial-sky file with explicit indexing.
Otherwise, implicit indexing is used. Default: False.
column_names : str or list
Column name or list of column names, if None here the default column names based on
the number of columns:
1 : "TEMPERATURE",
2 : ["Q_POLARISATION", "U_POLARISATION"],
3 : ["TEMPERATURE", "Q_POLARISATION", "U_POLARISATION"],
6 : ["II", "IQ", "IU", "QQ", "QU", "UU"]
COLUMN_1, COLUMN_2... otherwise (FITS is 1-based)
column_units : str or list
Units for each column, or same units for all columns.
extra_header : list
Extra records to add to FITS header.
dtype: np.dtype or list of np.dtypes, optional
The datatype in which the columns will be stored. Will be converted
internally from the numpy datatype to the fits convention. If a list,
the length must correspond to the number of map arrays.
Default: use the data type of the input array(s)
.. note::
this changed in 1.15.0, previous versions saved in float32
by default
overwrite : bool, optional
If True, existing file is silently overwritten. Otherwise trying to write
an existing file raises an OSError (IOError for Python 2).
"""
if not hasattr(m, "__len__"):
raise TypeError("The map must be a sequence")
m = pixelfunc.ma_to_array(m)
if pixelfunc.maptype(m) == 0: # a single map is converted to a list
m = [m]
# check the dtype and convert it
if dtype is None:
dtype = [x.dtype for x in m]
log.warning("setting the output map dtype to %s" % str(dtype))
try:
fitsformat = []
for curr_dtype in dtype:
fitsformat.append(getformat(curr_dtype))
except TypeError:
# dtype is not iterable
fitsformat = [getformat(dtype)] * len(m)
if column_names is None:
column_names = standard_column_names.get(
len(m), ["COLUMN_%d" % n for n in range(1, len(m) + 1)]
)
else:
assert len(column_names) == len(m), "Length column_names != number of maps"
if column_units is None or isinstance(column_units, str):
column_units = [column_units] * len(m)
# 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 = []
if partial:
fits_IDL = False
mask = pixelfunc.mask_good(m[0])
pix = np.where(mask)[0]
if len(pix) == 0:
raise ValueError("Invalid healpix map : empty partial map")
m = [mm[mask] for mm in m]
ff = getformat(np.min_scalar_type(-pix.max()))
if ff is None:
ff = "I"
cols.append(pf.Column(name="PIXEL", format=ff, array=pix, unit=None))
for cn, cu, mm, curr_fitsformat in zip(column_names, column_units, m, fitsformat):
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" % curr_fitsformat,
array=mm2.reshape(mm2.size // 1024, 1024),
unit=cu,
)
)
else:
cols.append(
pf.Column(name=cn, format="%s" % curr_fitsformat, array=mm, unit=cu)
)
tbhdu = pf.BinTableHDU.from_columns(cols)
# add needed keywords
tbhdu.header["PIXTYPE"] = ("HEALPIX", "HEALPIX pixelisation")
if nest:
ordering = "NESTED"
else:
ordering = "RING"
tbhdu.header["ORDERING"] = (
ordering,
"Pixel ordering scheme, either RING or NESTED",
)
if coord:
tbhdu.header["COORDSYS"] = (
coord,
"Ecliptic, Galactic or Celestial (equatorial)",
)
tbhdu.header["EXTNAME"] = ("xtension", "name of this binary table extension")
tbhdu.header["NSIDE"] = (nside, "Resolution parameter of HEALPIX")
if not partial:
tbhdu.header["FIRSTPIX"] = (0, "First pixel # (0 based)")
tbhdu.header["LASTPIX"] = (
pixelfunc.nside2npix(nside) - 1,
"Last pixel # (0 based)",
)
tbhdu.header["INDXSCHM"] = (
"EXPLICIT" if partial else "IMPLICIT",
"Indexing: IMPLICIT or EXPLICIT",
)
tbhdu.header["OBJECT"] = (
"PARTIAL" if partial else "FULLSKY",
"Sky coverage, either FULLSKY or PARTIAL",
)
# FIXME: In modern versions of Pyfits, header.update() understands a
# header as an argument, and headers can be concatenated with the `+'
# operator.
for args in extra_header:
tbhdu.header[args[0]] = args[1:]
# Add str to convert pathlib.Path into str
# Due to https://github.com/astropy/astropy/issues/10594
tbhdu.writeto(str(filename), overwrite=overwrite)
| (filename, m, nest=False, dtype=None, fits_IDL=True, coord=None, partial=False, column_names=None, column_units=None, extra_header=(), overwrite=False) |
37,747 | healpy.pixelfunc | xyf2pix | xyf2pix : nside,x,y,face,nest=False -> ipix (default:RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
pix : int or array of int
The healpix pixel numbers. Scalar if all input are scalar, array otherwise.
Usual numpy broadcasting rules apply.
See Also
--------
pix2xyf
Examples
--------
>>> import healpy as hp
>>> hp.xyf2pix(16, 8, 8, 4)
1440
>>> print(hp.xyf2pix(16, [8, 8, 8, 15, 0], [8, 8, 7, 15, 0], [4, 0, 5, 0, 8]))
[1440 427 1520 0 3068]
| def xyf2pix(nside, x, y, face, nest=False):
"""xyf2pix : nside,x,y,face,nest=False -> ipix (default:RING)
Parameters
----------
nside : int, scalar or array-like
The healpix nside parameter, must be a power of 2
x, y : int, scalars or array-like
Pixel indices within face
face : int, scalars or array-like
Face number
nest : bool, optional
if True, assume NESTED pixel ordering, otherwise, RING pixel ordering
Returns
-------
pix : int or array of int
The healpix pixel numbers. Scalar if all input are scalar, array otherwise.
Usual numpy broadcasting rules apply.
See Also
--------
pix2xyf
Examples
--------
>>> import healpy as hp
>>> hp.xyf2pix(16, 8, 8, 4)
1440
>>> print(hp.xyf2pix(16, [8, 8, 8, 15, 0], [8, 8, 7, 15, 0], [4, 0, 5, 0, 8]))
[1440 427 1520 0 3068]
"""
check_nside(nside, nest=nest)
if nest:
return pixlib._xyf2pix_nest(nside, x, y, face)
else:
return pixlib._xyf2pix_ring(nside, x, y, face)
| (nside, x, y, face, nest=False) |
37,749 | salesforce_bulk.salesforce_bulk | BulkApiError | null | class BulkApiError(Exception):
def __init__(self, message, status_code=None):
super(BulkApiError, self).__init__(message)
self.status_code = status_code
def __reduce__(self):
return BulkApiError, (self.args[0], self.status_code)
| (message, status_code=None) |
37,750 | salesforce_bulk.salesforce_bulk | __init__ | null | def __init__(self, message, status_code=None):
super(BulkApiError, self).__init__(message)
self.status_code = status_code
| (self, message, status_code=None) |
37,751 | salesforce_bulk.salesforce_bulk | __reduce__ | null | def __reduce__(self):
return BulkApiError, (self.args[0], self.status_code)
| (self) |
37,752 | salesforce_bulk.csv_adapter | CsvDictsAdapter | Provide a DataChange generator and it provides a file-like object which returns csv data | class CsvDictsAdapter(object):
"""Provide a DataChange generator and it provides a file-like object which returns csv data"""
def __init__(self, source_generator):
self.source = source_generator
self.buffer = StringIO()
self.csv = None
self.add_header = False
def __iter__(self):
return self
def write_header(self):
self.add_header = True
def next(self):
row = next(self.source)
self.buffer.truncate(0)
self.buffer.seek(0)
if not self.csv:
self.csv = csv.DictWriter(self.buffer, list(row.keys()), quoting=csv.QUOTE_NONNUMERIC)
self.add_header = True
if self.add_header:
if hasattr(self.csv, 'writeheader'):
self.csv.writeheader()
else:
self.csv.writerow(dict((fn, fn) for fn in self.csv.fieldnames))
self.add_header = False
self.csv.writerow(row)
self.buffer.seek(0)
return self.buffer.read()
def __next__(self):
return self.next()
| (source_generator) |
37,753 | salesforce_bulk.csv_adapter | __init__ | null | def __init__(self, source_generator):
self.source = source_generator
self.buffer = StringIO()
self.csv = None
self.add_header = False
| (self, source_generator) |
37,755 | salesforce_bulk.csv_adapter | __next__ | null | def __next__(self):
return self.next()
| (self) |
37,756 | salesforce_bulk.csv_adapter | next | null | def next(self):
row = next(self.source)
self.buffer.truncate(0)
self.buffer.seek(0)
if not self.csv:
self.csv = csv.DictWriter(self.buffer, list(row.keys()), quoting=csv.QUOTE_NONNUMERIC)
self.add_header = True
if self.add_header:
if hasattr(self.csv, 'writeheader'):
self.csv.writeheader()
else:
self.csv.writerow(dict((fn, fn) for fn in self.csv.fieldnames))
self.add_header = False
self.csv.writerow(row)
self.buffer.seek(0)
return self.buffer.read()
| (self) |
37,757 | salesforce_bulk.csv_adapter | write_header | null | def write_header(self):
self.add_header = True
| (self) |
37,758 | salesforce_bulk.salesforce_bulk | SalesforceBulk | null | class SalesforceBulk(object):
def __init__(self, sessionId=None, host=None, username=None, password=None,
API_version=DEFAULT_API_VERSION, sandbox=False,
security_token=None, organizationId=None, client_id=None, domain=None):
if not sessionId and not username:
raise RuntimeError(
"Must supply either sessionId/instance_url or username/password")
if not sessionId:
sessionId, host = SalesforceBulk.login_to_salesforce(
username, password, sandbox=sandbox, security_token=security_token,
organizationId=organizationId, API_version=API_version, client_id=client_id,
domain=domain)
if host[0:4] == 'http':
self.endpoint = host
else:
self.endpoint = "https://" + host
self.endpoint += "/services/async/%s" % API_version
self.sessionId = sessionId
self.jobNS = 'http://www.force.com/2009/06/asyncapi/dataload'
self.jobs = {} # dict of job_id => job_id
self.batches = {} # dict of batch_id => job_id
self.job_content_types = {} # dict of job_id => contentType
self.batch_statuses = {}
self.API_version = API_version
@staticmethod
def login_to_salesforce(username, password, sandbox=False, security_token=None,
organizationId=None, client_id=None, API_version=DEFAULT_API_VERSION,
# domain is passed directly to SalesforceLogin and should be 'test' or
# 'login' or 'something.my'
domain=None):
if client_id:
client_id = "{prefix}/{app_name}".format(
prefix=DEFAULT_CLIENT_ID_PREFIX,
app_name=client_id)
else:
client_id = DEFAULT_CLIENT_ID_PREFIX
if domain is None and sandbox:
domain = 'test'
if all(arg is not None for arg in (
username, password, security_token)):
# Pass along the username/password to our login helper
return SalesforceLogin(
username=username,
password=password,
security_token=security_token,
domain=domain,
sf_version=API_version,
client_id=client_id)
elif all(arg is not None for arg in (
username, password, organizationId)):
# Pass along the username/password to our login helper
return SalesforceLogin(
username=username,
password=password,
organizationId=organizationId,
domain=domain,
sf_version=API_version,
client_id=client_id)
else:
raise TypeError(
'You must provide login information or an instance and token'
)
def headers(self, values={}, content_type='application/xml'):
default = {
"X-SFDC-Session": self.sessionId,
"Content-Type": "{}; charset=UTF-8".format(content_type),
'Accept-Encoding': "gzip",
}
default.update(values)
return default
# Register a new Bulk API job - returns the job id
def create_query_job(self, object_name, **kwargs):
return self.create_job(object_name, "query", **kwargs)
def create_queryall_job(self, object_name, **kwargs):
""" only supported since version 39.0 """
return self.create_job(object_name, "queryAll", **kwargs)
def create_insert_job(self, object_name, **kwargs):
return self.create_job(object_name, "insert", **kwargs)
def create_upsert_job(self, object_name, external_id_name, **kwargs):
return self.create_job(object_name, "upsert", external_id_name=external_id_name, **kwargs)
def create_update_job(self, object_name, **kwargs):
return self.create_job(object_name, "update", **kwargs)
def create_delete_job(self, object_name, **kwargs):
return self.create_job(object_name, "delete", **kwargs)
def create_job(self, object_name=None, operation=None, contentType='CSV',
concurrency=None, external_id_name=None, pk_chunking=False):
assert(object_name is not None)
assert(operation is not None)
extra_headers = {}
if pk_chunking:
if pk_chunking is True:
pk_chunking = u'true'
elif isinstance(pk_chunking, int):
pk_chunking = u'chunkSize=%d;' % pk_chunking
else:
pk_chunking = text_type(pk_chunking)
extra_headers['Sforce-Enable-PKChunking'] = pk_chunking
doc = self.create_job_doc(object_name=object_name,
operation=operation,
contentType=contentType,
concurrency=concurrency,
external_id_name=external_id_name)
resp = requests.post(self.endpoint + "/job",
headers=self.headers(extra_headers),
data=doc)
self.check_status(resp)
tree = ET.fromstring(resp.content)
job_id = tree.findtext("{%s}id" % self.jobNS)
self.jobs[job_id] = job_id
self.job_content_types[job_id] = contentType
return job_id
def check_status(self, resp):
if resp.status_code >= 400:
msg = "Bulk API HTTP Error result: {0}".format(resp.text)
self.raise_error(msg, resp.status_code)
def get_batch_list(self, job_id):
url = self.endpoint + "/job/{}/batch".format(job_id)
resp = requests.get(url, headers=self.headers())
self.check_status(resp)
results = self.parse_response(resp)
if isinstance(results, dict):
return results['batchInfo']
return results
def get_query_batch_request(self, batch_id, job_id=None):
""" Fetch the request sent for the batch. Note should only used for query batches """
if not job_id:
job_id = self.lookup_job_id(batch_id)
url = self.endpoint + "/job/{}/batch/{}/request".format(job_id, batch_id)
resp = requests.get(url, headers=self.headers())
self.check_status(resp)
return resp.text
def close_job(self, job_id):
doc = self.create_close_job_doc()
url = self.endpoint + "/job/%s" % job_id
resp = requests.post(url, headers=self.headers(), data=doc)
self.check_status(resp)
def abort_job(self, job_id):
"""Abort a given bulk job"""
doc = self.create_abort_job_doc()
url = self.endpoint + "/job/%s" % job_id
resp = requests.post(
url,
headers=self.headers(),
data=doc
)
self.check_status(resp)
def create_job_doc(self, object_name=None, operation=None,
contentType='CSV', concurrency=None, external_id_name=None):
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
op = ET.SubElement(root, "operation")
op.text = operation
obj = ET.SubElement(root, "object")
obj.text = object_name
if external_id_name:
ext = ET.SubElement(root, 'externalIdFieldName')
ext.text = external_id_name
if concurrency:
con = ET.SubElement(root, "concurrencyMode")
con.text = concurrency
ct = ET.SubElement(root, "contentType")
ct.text = contentType
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
def create_close_job_doc(self):
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
state = ET.SubElement(root, "state")
state.text = "Closed"
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
def create_abort_job_doc(self):
"""Create XML doc for aborting a job"""
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
state = ET.SubElement(root, "state")
state.text = "Aborted"
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
# Add a BulkQuery to the job - returns the batch id
def query(self, job_id, soql, contentType='CSV'):
if job_id is None:
job_id = self.create_job(
re.search(re.compile(r"from (\w+)", re.I), soql).group(1),
"query", contentType=contentType)
job_content_type = self.job_content_types.get(job_id, contentType)
http_content_type = job_to_http_content_type[job_content_type]
headers = self.headers(content_type=http_content_type)
uri = self.endpoint + "/job/%s/batch" % job_id
resp = requests.post(uri, data=soql, headers=headers)
self.check_status(resp)
result = self.parse_response(resp)
batch_id = result['id']
self.batches[batch_id] = job_id
return batch_id
def raise_error(self, message, status_code=None):
if status_code:
message = "[{0}] {1}".format(status_code, message)
raise BulkApiError(message, status_code=status_code)
def post_batch(self, job_id, data_generator):
job_content_type = self.job_content_types[job_id]
http_content_type = job_to_http_content_type[job_content_type]
uri = self.endpoint + "/job/%s/batch" % job_id
headers = self.headers(content_type=http_content_type)
resp = requests.post(uri, data=data_generator, headers=headers)
self.check_status(resp)
result = self.parse_response(resp)
batch_id = result['id']
self.batches[batch_id] = job_id
return batch_id
def post_mapping_file(self, job_id, mapping_data):
job_content_type = 'CSV'
http_content_type = job_to_http_content_type[job_content_type]
uri = self.endpoint + "/job/%s/spec" % job_id
headers = self.headers(content_type=http_content_type)
resp = requests.post(uri, data=mapping_data, headers=headers)
self.check_status(resp)
if resp.status_code != 201:
raise Exception("Unable to upload mapping file")
def lookup_job_id(self, batch_id):
try:
return self.batches[batch_id]
except KeyError:
raise Exception(
"Batch id '%s' is uknown, can't retrieve job_id" % batch_id)
def job_status(self, job_id=None):
job_id = job_id
uri = urlparse.urljoin(self.endpoint + "/", 'job/{0}'.format(job_id))
response = requests.get(uri, headers=self.headers())
self.check_status(response)
tree = ET.fromstring(response.content)
result = {}
for child in tree:
result[nsclean.sub("", child.tag)] = child.text
return result
def job_state(self, job_id):
status = self.job_status(job_id)
if 'state' in status:
return status['state']
else:
return None
def parse_response(self, resp):
if resp.headers['Content-Type'] == 'application/json':
return resp.json()
tree = ET.fromstring(resp.content)
if nsclean.sub("", tree.tag) == 'batchInfoList':
results = []
for subtree in tree:
result = {}
results.append(result)
for child in subtree:
result[nsclean.sub("", child.tag)] = child.text
return results
result = {}
for child in tree:
result[nsclean.sub("", child.tag)] = child.text
return result
def batch_status(self, batch_id=None, job_id=None, reload=False):
if not reload and batch_id in self.batch_statuses:
return self.batch_statuses[batch_id]
job_id = job_id or self.lookup_job_id(batch_id)
uri = self.endpoint + \
"/job/%s/batch/%s" % (job_id, batch_id)
resp = requests.get(uri, headers=self.headers())
self.check_status(resp)
result = self.parse_response(resp)
self.batch_statuses[batch_id] = result
return result
def batch_state(self, batch_id, job_id=None, reload=False):
status = self.batch_status(batch_id, job_id, reload=reload)
if 'state' in status:
return status['state']
else:
return None
def is_batch_done(self, batch_id, job_id=None):
batch_state = self.batch_state(batch_id, job_id=job_id, reload=True)
if batch_state in bulk_states.ERROR_STATES:
status = self.batch_status(batch_id, job_id)
raise BulkBatchFailed(job_id, batch_id, status.get('stateMessage'), batch_state)
return batch_state == bulk_states.COMPLETED
# Wait for the given batch to complete, waiting at most timeout seconds
# (defaults to 10 minutes).
def wait_for_batch(self, job_id, batch_id, timeout=60 * 10,
sleep_interval=10):
waited = 0
while not self.is_batch_done(batch_id, job_id) and waited < timeout:
time.sleep(sleep_interval)
waited += sleep_interval
def get_query_batch_result_ids(self, batch_id, job_id=None):
job_id = job_id or self.lookup_job_id(batch_id)
if not self.is_batch_done(batch_id, job_id):
return False
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result".format(
job_id, batch_id),
)
resp = requests.get(uri, headers=self.headers())
self.check_status(resp)
if resp.headers['Content-Type'] == 'application/json':
return resp.json()
tree = ET.fromstring(resp.content)
find_func = getattr(tree, 'iterfind', tree.findall)
return [str(r.text) for r in
find_func("{{{0}}}result".format(self.jobNS))]
def get_all_results_for_query_batch(self, batch_id, job_id=None, chunk_size=2048):
"""
Gets result ids and generates each result set from the batch and returns it
as an generator fetching the next result set when needed
Args:
batch_id: id of batch
job_id: id of job, if not provided, it will be looked up
"""
result_ids = self.get_query_batch_result_ids(batch_id, job_id=job_id)
if not result_ids:
raise RuntimeError('Batch is not complete')
for result_id in result_ids:
yield self.get_query_batch_results(
batch_id,
result_id,
job_id=job_id,
chunk_size=chunk_size
)
def get_query_batch_results(self, batch_id, result_id, job_id=None, chunk_size=2048, raw=False):
job_id = job_id or self.lookup_job_id(batch_id)
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result/{2}".format(
job_id, batch_id, result_id),
)
resp = requests.get(uri, headers=self.headers(), stream=True)
self.check_status(resp)
if raw:
return resp.raw
iter = (x.replace(b'\0', b'') for x in resp.iter_content(chunk_size=chunk_size))
return util.IteratorBytesIO(iter)
def get_batch_results(self, batch_id, job_id=None):
job_id = job_id or self.lookup_job_id(batch_id)
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result".format(
job_id, batch_id),
)
resp = requests.get(uri, headers=self.headers(), stream=True)
self.check_status(resp)
iter = (x.replace(b'\0', b'') for x in resp.iter_content())
fd = util.IteratorBytesIO(iter)
if resp.headers['Content-Type'] == 'application/json':
result = json.load(io.TextIOWrapper(fd, 'utf-8'))
getter = itemgetter('id', 'success', 'created', 'errors')
return [UploadResult(*getter(row)) for row in result]
elif resp.headers['Content-Type'] == 'text/csv':
reader = unicodecsv.reader(
fd, encoding='utf-8'
)
results = islice(reader, 1, None)
results = [
UploadResult(*row)
for row in results
]
return results
elif resp.headers['Content-Type'] == 'application/xml':
tree = ET.parse(fd)
def getid(x):
x is not None and x.text
results = [
UploadResult(
getid(result.find('{%s}id' % self.jobNS)),
result.find('{%s}success' % self.jobNS).text == 'true',
result.find('{%s}created' % self.jobNS).text == 'true',
[
self.parse_error_result_xml(x)
for x in result.findall('{%s}errors' % self.jobNS)
]
)
for result in tree.getroot()
]
return results
# NOTE raise exception if we get here
def parse_error_result_xml(self, error_xml):
return {
'fields': [x.text for x in error_xml.findall('{%s}fields' % self.jobNS)],
'message': error_xml.find('{%s}message' % self.jobNS).text,
'statusCode': error_xml.find('{%s}statusCode' % self.jobNS).text,
}
| (sessionId=None, host=None, username=None, password=None, API_version='40.0', sandbox=False, security_token=None, organizationId=None, client_id=None, domain=None) |
37,759 | salesforce_bulk.salesforce_bulk | __init__ | null | def __init__(self, sessionId=None, host=None, username=None, password=None,
API_version=DEFAULT_API_VERSION, sandbox=False,
security_token=None, organizationId=None, client_id=None, domain=None):
if not sessionId and not username:
raise RuntimeError(
"Must supply either sessionId/instance_url or username/password")
if not sessionId:
sessionId, host = SalesforceBulk.login_to_salesforce(
username, password, sandbox=sandbox, security_token=security_token,
organizationId=organizationId, API_version=API_version, client_id=client_id,
domain=domain)
if host[0:4] == 'http':
self.endpoint = host
else:
self.endpoint = "https://" + host
self.endpoint += "/services/async/%s" % API_version
self.sessionId = sessionId
self.jobNS = 'http://www.force.com/2009/06/asyncapi/dataload'
self.jobs = {} # dict of job_id => job_id
self.batches = {} # dict of batch_id => job_id
self.job_content_types = {} # dict of job_id => contentType
self.batch_statuses = {}
self.API_version = API_version
| (self, sessionId=None, host=None, username=None, password=None, API_version='40.0', sandbox=False, security_token=None, organizationId=None, client_id=None, domain=None) |
37,760 | salesforce_bulk.salesforce_bulk | abort_job | Abort a given bulk job | def abort_job(self, job_id):
"""Abort a given bulk job"""
doc = self.create_abort_job_doc()
url = self.endpoint + "/job/%s" % job_id
resp = requests.post(
url,
headers=self.headers(),
data=doc
)
self.check_status(resp)
| (self, job_id) |
37,761 | salesforce_bulk.salesforce_bulk | batch_state | null | def batch_state(self, batch_id, job_id=None, reload=False):
status = self.batch_status(batch_id, job_id, reload=reload)
if 'state' in status:
return status['state']
else:
return None
| (self, batch_id, job_id=None, reload=False) |
37,762 | salesforce_bulk.salesforce_bulk | batch_status | null | def batch_status(self, batch_id=None, job_id=None, reload=False):
if not reload and batch_id in self.batch_statuses:
return self.batch_statuses[batch_id]
job_id = job_id or self.lookup_job_id(batch_id)
uri = self.endpoint + \
"/job/%s/batch/%s" % (job_id, batch_id)
resp = requests.get(uri, headers=self.headers())
self.check_status(resp)
result = self.parse_response(resp)
self.batch_statuses[batch_id] = result
return result
| (self, batch_id=None, job_id=None, reload=False) |
37,763 | salesforce_bulk.salesforce_bulk | check_status | null | def check_status(self, resp):
if resp.status_code >= 400:
msg = "Bulk API HTTP Error result: {0}".format(resp.text)
self.raise_error(msg, resp.status_code)
| (self, resp) |
37,764 | salesforce_bulk.salesforce_bulk | close_job | null | def close_job(self, job_id):
doc = self.create_close_job_doc()
url = self.endpoint + "/job/%s" % job_id
resp = requests.post(url, headers=self.headers(), data=doc)
self.check_status(resp)
| (self, job_id) |
37,765 | salesforce_bulk.salesforce_bulk | create_abort_job_doc | Create XML doc for aborting a job | def create_abort_job_doc(self):
"""Create XML doc for aborting a job"""
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
state = ET.SubElement(root, "state")
state.text = "Aborted"
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
| (self) |
37,766 | salesforce_bulk.salesforce_bulk | create_close_job_doc | null | def create_close_job_doc(self):
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
state = ET.SubElement(root, "state")
state.text = "Closed"
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
| (self) |
37,767 | salesforce_bulk.salesforce_bulk | create_delete_job | null | def create_delete_job(self, object_name, **kwargs):
return self.create_job(object_name, "delete", **kwargs)
| (self, object_name, **kwargs) |
37,768 | salesforce_bulk.salesforce_bulk | create_insert_job | null | def create_insert_job(self, object_name, **kwargs):
return self.create_job(object_name, "insert", **kwargs)
| (self, object_name, **kwargs) |
37,769 | salesforce_bulk.salesforce_bulk | create_job | null | def create_job(self, object_name=None, operation=None, contentType='CSV',
concurrency=None, external_id_name=None, pk_chunking=False):
assert(object_name is not None)
assert(operation is not None)
extra_headers = {}
if pk_chunking:
if pk_chunking is True:
pk_chunking = u'true'
elif isinstance(pk_chunking, int):
pk_chunking = u'chunkSize=%d;' % pk_chunking
else:
pk_chunking = text_type(pk_chunking)
extra_headers['Sforce-Enable-PKChunking'] = pk_chunking
doc = self.create_job_doc(object_name=object_name,
operation=operation,
contentType=contentType,
concurrency=concurrency,
external_id_name=external_id_name)
resp = requests.post(self.endpoint + "/job",
headers=self.headers(extra_headers),
data=doc)
self.check_status(resp)
tree = ET.fromstring(resp.content)
job_id = tree.findtext("{%s}id" % self.jobNS)
self.jobs[job_id] = job_id
self.job_content_types[job_id] = contentType
return job_id
| (self, object_name=None, operation=None, contentType='CSV', concurrency=None, external_id_name=None, pk_chunking=False) |
37,770 | salesforce_bulk.salesforce_bulk | create_job_doc | null | def create_job_doc(self, object_name=None, operation=None,
contentType='CSV', concurrency=None, external_id_name=None):
root = ET.Element("jobInfo")
root.set("xmlns", self.jobNS)
op = ET.SubElement(root, "operation")
op.text = operation
obj = ET.SubElement(root, "object")
obj.text = object_name
if external_id_name:
ext = ET.SubElement(root, 'externalIdFieldName')
ext.text = external_id_name
if concurrency:
con = ET.SubElement(root, "concurrencyMode")
con.text = concurrency
ct = ET.SubElement(root, "contentType")
ct.text = contentType
buf = StringIO()
tree = ET.ElementTree(root)
tree.write(buf, encoding="UTF-8")
return buf.getvalue()
| (self, object_name=None, operation=None, contentType='CSV', concurrency=None, external_id_name=None) |
37,771 | salesforce_bulk.salesforce_bulk | create_query_job | null | def create_query_job(self, object_name, **kwargs):
return self.create_job(object_name, "query", **kwargs)
| (self, object_name, **kwargs) |
37,772 | salesforce_bulk.salesforce_bulk | create_queryall_job | only supported since version 39.0 | def create_queryall_job(self, object_name, **kwargs):
""" only supported since version 39.0 """
return self.create_job(object_name, "queryAll", **kwargs)
| (self, object_name, **kwargs) |
37,773 | salesforce_bulk.salesforce_bulk | create_update_job | null | def create_update_job(self, object_name, **kwargs):
return self.create_job(object_name, "update", **kwargs)
| (self, object_name, **kwargs) |
37,774 | salesforce_bulk.salesforce_bulk | create_upsert_job | null | def create_upsert_job(self, object_name, external_id_name, **kwargs):
return self.create_job(object_name, "upsert", external_id_name=external_id_name, **kwargs)
| (self, object_name, external_id_name, **kwargs) |
37,775 | salesforce_bulk.salesforce_bulk | get_all_results_for_query_batch |
Gets result ids and generates each result set from the batch and returns it
as an generator fetching the next result set when needed
Args:
batch_id: id of batch
job_id: id of job, if not provided, it will be looked up
| def get_all_results_for_query_batch(self, batch_id, job_id=None, chunk_size=2048):
"""
Gets result ids and generates each result set from the batch and returns it
as an generator fetching the next result set when needed
Args:
batch_id: id of batch
job_id: id of job, if not provided, it will be looked up
"""
result_ids = self.get_query_batch_result_ids(batch_id, job_id=job_id)
if not result_ids:
raise RuntimeError('Batch is not complete')
for result_id in result_ids:
yield self.get_query_batch_results(
batch_id,
result_id,
job_id=job_id,
chunk_size=chunk_size
)
| (self, batch_id, job_id=None, chunk_size=2048) |
37,776 | salesforce_bulk.salesforce_bulk | get_batch_list | null | def get_batch_list(self, job_id):
url = self.endpoint + "/job/{}/batch".format(job_id)
resp = requests.get(url, headers=self.headers())
self.check_status(resp)
results = self.parse_response(resp)
if isinstance(results, dict):
return results['batchInfo']
return results
| (self, job_id) |
37,777 | salesforce_bulk.salesforce_bulk | get_batch_results | null | def get_batch_results(self, batch_id, job_id=None):
job_id = job_id or self.lookup_job_id(batch_id)
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result".format(
job_id, batch_id),
)
resp = requests.get(uri, headers=self.headers(), stream=True)
self.check_status(resp)
iter = (x.replace(b'\0', b'') for x in resp.iter_content())
fd = util.IteratorBytesIO(iter)
if resp.headers['Content-Type'] == 'application/json':
result = json.load(io.TextIOWrapper(fd, 'utf-8'))
getter = itemgetter('id', 'success', 'created', 'errors')
return [UploadResult(*getter(row)) for row in result]
elif resp.headers['Content-Type'] == 'text/csv':
reader = unicodecsv.reader(
fd, encoding='utf-8'
)
results = islice(reader, 1, None)
results = [
UploadResult(*row)
for row in results
]
return results
elif resp.headers['Content-Type'] == 'application/xml':
tree = ET.parse(fd)
def getid(x):
x is not None and x.text
results = [
UploadResult(
getid(result.find('{%s}id' % self.jobNS)),
result.find('{%s}success' % self.jobNS).text == 'true',
result.find('{%s}created' % self.jobNS).text == 'true',
[
self.parse_error_result_xml(x)
for x in result.findall('{%s}errors' % self.jobNS)
]
)
for result in tree.getroot()
]
return results
# NOTE raise exception if we get here
| (self, batch_id, job_id=None) |
37,778 | salesforce_bulk.salesforce_bulk | get_query_batch_request | Fetch the request sent for the batch. Note should only used for query batches | def get_query_batch_request(self, batch_id, job_id=None):
""" Fetch the request sent for the batch. Note should only used for query batches """
if not job_id:
job_id = self.lookup_job_id(batch_id)
url = self.endpoint + "/job/{}/batch/{}/request".format(job_id, batch_id)
resp = requests.get(url, headers=self.headers())
self.check_status(resp)
return resp.text
| (self, batch_id, job_id=None) |
37,779 | salesforce_bulk.salesforce_bulk | get_query_batch_result_ids | null | def get_query_batch_result_ids(self, batch_id, job_id=None):
job_id = job_id or self.lookup_job_id(batch_id)
if not self.is_batch_done(batch_id, job_id):
return False
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result".format(
job_id, batch_id),
)
resp = requests.get(uri, headers=self.headers())
self.check_status(resp)
if resp.headers['Content-Type'] == 'application/json':
return resp.json()
tree = ET.fromstring(resp.content)
find_func = getattr(tree, 'iterfind', tree.findall)
return [str(r.text) for r in
find_func("{{{0}}}result".format(self.jobNS))]
| (self, batch_id, job_id=None) |
37,780 | salesforce_bulk.salesforce_bulk | get_query_batch_results | null | def get_query_batch_results(self, batch_id, result_id, job_id=None, chunk_size=2048, raw=False):
job_id = job_id or self.lookup_job_id(batch_id)
uri = urlparse.urljoin(
self.endpoint + "/",
"job/{0}/batch/{1}/result/{2}".format(
job_id, batch_id, result_id),
)
resp = requests.get(uri, headers=self.headers(), stream=True)
self.check_status(resp)
if raw:
return resp.raw
iter = (x.replace(b'\0', b'') for x in resp.iter_content(chunk_size=chunk_size))
return util.IteratorBytesIO(iter)
| (self, batch_id, result_id, job_id=None, chunk_size=2048, raw=False) |
37,781 | salesforce_bulk.salesforce_bulk | headers | null | def headers(self, values={}, content_type='application/xml'):
default = {
"X-SFDC-Session": self.sessionId,
"Content-Type": "{}; charset=UTF-8".format(content_type),
'Accept-Encoding': "gzip",
}
default.update(values)
return default
| (self, values={}, content_type='application/xml') |
37,782 | salesforce_bulk.salesforce_bulk | is_batch_done | null | def is_batch_done(self, batch_id, job_id=None):
batch_state = self.batch_state(batch_id, job_id=job_id, reload=True)
if batch_state in bulk_states.ERROR_STATES:
status = self.batch_status(batch_id, job_id)
raise BulkBatchFailed(job_id, batch_id, status.get('stateMessage'), batch_state)
return batch_state == bulk_states.COMPLETED
| (self, batch_id, job_id=None) |
37,783 | salesforce_bulk.salesforce_bulk | job_state | null | def job_state(self, job_id):
status = self.job_status(job_id)
if 'state' in status:
return status['state']
else:
return None
| (self, job_id) |
37,784 | salesforce_bulk.salesforce_bulk | job_status | null | def job_status(self, job_id=None):
job_id = job_id
uri = urlparse.urljoin(self.endpoint + "/", 'job/{0}'.format(job_id))
response = requests.get(uri, headers=self.headers())
self.check_status(response)
tree = ET.fromstring(response.content)
result = {}
for child in tree:
result[nsclean.sub("", child.tag)] = child.text
return result
| (self, job_id=None) |
37,785 | salesforce_bulk.salesforce_bulk | login_to_salesforce | null | @staticmethod
def login_to_salesforce(username, password, sandbox=False, security_token=None,
organizationId=None, client_id=None, API_version=DEFAULT_API_VERSION,
# domain is passed directly to SalesforceLogin and should be 'test' or
# 'login' or 'something.my'
domain=None):
if client_id:
client_id = "{prefix}/{app_name}".format(
prefix=DEFAULT_CLIENT_ID_PREFIX,
app_name=client_id)
else:
client_id = DEFAULT_CLIENT_ID_PREFIX
if domain is None and sandbox:
domain = 'test'
if all(arg is not None for arg in (
username, password, security_token)):
# Pass along the username/password to our login helper
return SalesforceLogin(
username=username,
password=password,
security_token=security_token,
domain=domain,
sf_version=API_version,
client_id=client_id)
elif all(arg is not None for arg in (
username, password, organizationId)):
# Pass along the username/password to our login helper
return SalesforceLogin(
username=username,
password=password,
organizationId=organizationId,
domain=domain,
sf_version=API_version,
client_id=client_id)
else:
raise TypeError(
'You must provide login information or an instance and token'
)
| (username, password, sandbox=False, security_token=None, organizationId=None, client_id=None, API_version='40.0', domain=None) |
37,786 | salesforce_bulk.salesforce_bulk | lookup_job_id | null | def lookup_job_id(self, batch_id):
try:
return self.batches[batch_id]
except KeyError:
raise Exception(
"Batch id '%s' is uknown, can't retrieve job_id" % batch_id)
| (self, batch_id) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.