Commit 6f9030f6 authored by Theo Steininger's avatar Theo Steininger
Browse files

Merge remote-tracking branch 'remotes/origin/master' into 'docu_power_space'

# Conflicts:
#	nifty/spaces/lm_space/lm_space.py
#	nifty/spaces/power_space/power_space.py
parents f32f5d5f 61a68dca
Pipeline #12255 failed with stage
in 5 minutes and 30 seconds
......@@ -41,6 +41,20 @@ class DomainObject(Versionable, Loggable, object):
return result_hash
def __eq__(self, x):
""" Checks if two domain_objects are equal.
Parameters
----------
x: domain_object
The domain_object `self` is compared to.
Returns
-------
bool
True if `self` and x describe the same manifold.
"""
if isinstance(x, type(self)):
for key in vars(self).keys():
item1 = vars(self)[key]
......@@ -58,23 +72,137 @@ class DomainObject(Versionable, Loggable, object):
@abc.abstractproperty
def shape(self):
""" Returns the shape of the underlying array-like object.
Returns
-------
tuple of ints
The shape of the underlying array-like object.
Raises
------
NotImplementedError
If called for this abstract class.
"""
raise NotImplementedError(
"There is no generic shape for DomainObject.")
@abc.abstractproperty
def dim(self):
""" Returns the number of pixel-dimensions the object has.
Returns
-------
int
An Integer representing the number of pixels the discretized
manifold has.
Raises
------
NotImplementedError
If called for this abstract class.
"""
raise NotImplementedError(
"There is no generic dim for DomainObject.")
@abc.abstractmethod
def weight(self, x, power=1, axes=None, inplace=False):
""" Weights the field on this domain with the space's volume-weights.
Weights hereby refer to integration weights, as they appear in
discretized integrals. Per default, this function mutliplies each bin
of the field x by its volume, which lets it behave like a density
(top form). However, different powers of the volume can be applied
with the power parameter. The axes parameter specifies which of the
field array's indices correspond to this domain.
Parameters
----------
x : distributed_data_object
The fields data array.
power : int, *optional*
The power to which the volume-weight is raised (default: 1).
axes : {int, tuple}, *optional*
Specifies the axes of x which represent this domain
(default: None).
If axes==None:
weighting is applied with respect to all axes
inplace : bool, *optional*
If this is True, the weighting is done on the values of x,
if it is False, x is not modified and this method returns a
weighted copy of x (default: False).
Returns
-------
distributed_data_object
A weighted version of x, with volume-weights raised to the
given power.
Raises
------
NotImplementedError
If called for this abstract class.
"""
raise NotImplementedError(
"There is no generic weight-method for DomainObject.")
def pre_cast(self, x, axes=None):
def pre_cast(self, x, axes):
""" Casts input for Field.val before Field performs the cast.
Parameters
----------
x : {array-like, castable}
an array-like object or anything that can be cast to arrays.
axes : tuple of ints
Specifies the axes of x which correspond to this domain.
Returns
-------
{array-like, castable}
Processed input where casting that needs Space-specific knowledge
(for example location of pixels on the manifold) was performed.
See Also
--------
post_cast
Notes
-----
Usually returns x, except if a power spectrum is given to a
PowerSpace, where this spectrum is evaluated at the power indices.
"""
return x
def post_cast(self, x, axes=None):
def post_cast(self, x, axes):
""" Performs casting operations that are done after Field's cast.
Parameters
----------
x : {array-like, castable}
an array-like object or anything that can be cast to arrays.
axes : tuple of ints
Specifies the axes of x which correspond to this domain.
See Also
--------
pre_cast
Returns
-------
distributed_data_object
Processed input where casting that needs Space-specific knowledge
(for example location of pixels on the manifold) was performed.
"""
return x
# ---Serialization---
......
......@@ -174,7 +174,7 @@ class FFTOperator(LinearOperator):
result_field = x.copy_empty(domain=result_domain,
dtype=self.target_dtype)
result_field.set_val(new_val=new_val, copy=False)
result_field.set_val(new_val=new_val, copy=True)
return result_field
......@@ -198,7 +198,7 @@ class FFTOperator(LinearOperator):
result_field = x.copy_empty(domain=result_domain,
dtype=self.domain_dtype)
result_field.set_val(new_val=new_val, copy=False)
result_field.set_val(new_val=new_val, copy=True)
return result_field
......
......@@ -43,8 +43,15 @@ class GLSpace(Space):
----------
nlat : int
Number of latitudinal bins, or rings.
nlon : int
Number of longitudinal bins.
nlon : int, *optional*
Number of longitudinal bins (default: ``2*nlat - 1``).
Raises
------
ValueError
If input `nlat` or `nlon` is invalid.
ImportError
If the pyHealpix module is not available
See Also
--------
......@@ -65,28 +72,6 @@ class GLSpace(Space):
# ---Overwritten properties and methods---
def __init__(self, nlat, nlon=None):
"""
Sets the attributes for a gl_space class instance.
Parameters
----------
nlat : int
Number of latitudinal bins, or rings.
nlon : int, *optional*
Number of longitudinal bins (default: ``2*nlat - 1``).
Returns
-------
None
Raises
------
ValueError
If input `nlat` is invalid.
ImportError
If the pyHealpix module is not available
"""
if 'pyHealpix' not in gdi:
raise ImportError(
"The module pyHealpix is needed but not available.")
......@@ -150,10 +135,17 @@ class GLSpace(Space):
@property
def nlat(self):
""" Number of latitudinal bins (or rings) that are used for this
pixelization.
"""
return self._nlat
@property
def nlon(self):
""" Number of longditudinal bins that are used for this pixelization.
"""
return self._nlon
def _parse_nlat(self, nlat):
......
......@@ -39,6 +39,11 @@ class HPSpace(Space):
Resolution parameter for the HEALPix discretization, resulting in
``12*nside**2`` pixels. Must be positive.
Raises
------
ValueError
If given `nside` < 1.
See Also
--------
gl_space : A class for the Gauss-Legendre discretization of the
......@@ -59,26 +64,6 @@ class HPSpace(Space):
# ---Overwritten properties and methods---
def __init__(self, nside):
"""
Sets the attributes for a HPSpace class instance.
Parameters
----------
nside : int
Resolution parameter for the HEALPix discretization, resulting
in ``12*nside**2`` pixels. Must be positive.
Returns
-------
None
Raises
------
ValueError
If input `nside` is invalid.
"""
super(HPSpace, self).__init__()
self._nside = self._parse_nside(nside)
......@@ -105,6 +90,7 @@ class HPSpace(Space):
return self.__class__(nside=self.nside)
def weight(self, x, power=1, axes=None, inplace=False):
weight = ((4 * np.pi) / (12 * self.nside**2))**power
if inplace:
......@@ -125,6 +111,9 @@ class HPSpace(Space):
@property
def nside(self):
""" Returns the nside of the corresponding HEALPix pixelization.
The total number of pixels is 12*nside**2
"""
return self._nside
def _parse_nside(self, nside):
......
......@@ -43,17 +43,21 @@ class LMSpace(Space):
Maximum :math:`\ell`-value up to which the spherical harmonics
coefficients are to be used.
Notes:
------
This implementation implicitly sets the mmax parameter to lmax.
See Also
--------
hp_space : A class for the HEALPix discretization of the sphere [#]_.
gl_space : A class for the Gauss-Legendre discretization of the
sphere [#]_.
Raises
------
ValueError
If given lmax is negative.
Notes
-----
This implementation implicitly sets the mmax parameter to lmax.
References
----------
.. [#] K.M. Gorski et al., 2005, "HEALPix: A Framework for
......@@ -65,21 +69,6 @@ class LMSpace(Space):
"""
def __init__(self, lmax):
"""
Sets the attributes for a lm_space class instance.
Parameters
----------
lmax : int
Maximum :math:`\ell`-value up to which the spherical harmonics
coefficients are to be used.
Returns
-------
None.
"""
super(LMSpace, self).__init__()
self._lmax = self._parse_lmax(lmax)
......@@ -144,16 +133,32 @@ class LMSpace(Space):
return res
def get_fft_smoothing_kernel_function(self, sigma):
# FIXME why x(x+1) ? add reference to paper!
return lambda x: np.exp(-0.5 * x * (x + 1) * sigma**2)
# ---Added properties and methods---
@property
def lmax(self):
""" Returns the maximal :math:`l` value of any spherical harmonics
:math:`Y_{lm}` that is represented in this Space.
"""
return self._lmax
@property
def mmax(self):
""" Returns the maximal :math:`m` value of any spherical harmonic
:math:`Y_{lm}` that is represented in this Space. As :math:`m` goes
from :math:`-l` to :math:`l` for every :math:`l` this just returns the
same as lmax.
See Also
--------
lmax : Returns the maximal :math:`l`-value of the spherical harmonics
being used.
"""
return self._lmax
def _parse_lmax(self, lmax):
......
......@@ -96,7 +96,7 @@ class PowerSpace(Space):
self._pundex = power_index['pundex']
self._k_array = power_index['k_array']
def pre_cast(self, x, axes=None):
def pre_cast(self, x, axes):
"""Casts power spectra to discretized power spectra.
This function takes an array or a function. If it is an array it does nothing,
......
......@@ -48,16 +48,36 @@ class RGSpace(Space):
NIFTY subclass for spaces of regular Cartesian grids.
Parameters
----------
shape : {int, numpy.ndarray}
Number of grid points or numbers of gridpoints along each axis.
zerocenter : {bool, numpy.ndarray}, *optional*
Whether x==0 (or k==0, respectively) is located in the center of
the grid (or the center of each axis speparately) or not.
(default: False).
distances : {float, numpy.ndarray}, *optional*
Distance between two grid points along each axis
(default: None).
If distances==None:
if harmonic==True, all distances will be set to 1
if harmonic==False, the distance along each axis will be
set to the inverse of the number of points along that
axis.
harmonic : bool, *optional*
Whether the space represents a grid in position or harmonic space.
(default: False).
Attributes
----------
harmonic : bool
Whether or not the grid represents a Fourier basis.
zerocenter : {bool, numpy.ndarray}
Whether the Fourier zero-mode is located in the center of the grid
(or the center of each axis speparately) or not.
MR FIXME: this also does something if the space is not harmonic!
distances : {float, numpy.ndarray}
Distance between two grid points along each axis (default: None).
Whether or not the grid represents a position or harmonic space.
zerocenter : tuple of bool
Whether x==0 (or k==0, respectively) is located in the center of
the grid (or the center of each axis speparately) or not.
distances : tuple of floats
Distance between two grid points along the correpsonding axis.
"""
# ---Overwritten properties and methods---
......@@ -67,24 +87,7 @@ class RGSpace(Space):
"""
Sets the attributes for an RGSpace class instance.
Parameters
----------
shape : {int, numpy.ndarray}
Number of grid points or numbers of gridpoints along each axis.
zerocenter : {bool, numpy.ndarray}, *optional*
Whether the Fourier zero-mode is located in the center of the
grid (or the center of each axis speparately) or not
distances : {float, numpy.ndarray}, *optional*
Distance between two grid points along each axis
(default: None).
If distances==None:
if harmonic==True, all distances will be set to 1
if harmonic==False, the distance along each axis will be
set to the inverse of the number of points along that
axis.
harmonic : bool, *optional*
Whether the space represents a Fourier or a position grid
(default: False).
Returns
-------
......@@ -204,20 +207,21 @@ class RGSpace(Space):
return result_x
def get_distance_array(self, distribution_strategy):
"""
Calculates an n-dimensional array with its entries being the
lengths of the k-vectors from the zero point of the grid.
MR FIXME: Since this is about k-vectors, it might make sense to
throw NotImplementedError if harmonic==False.
""" Calculates an n-dimensional array with its entries being the
lengths of the vectors from the zero point of the grid.
Parameters
----------
None : All information is taken from the parent object.
Returns
-------
nkdict : distributed_data_object
Parameters
----------
distribution_strategy : str
The distribution_strategy which shall be used the returned
distributed_data_object.
Returns
-------
distributed_data_object
A d2o containing the distances
"""
shape = self.shape
# prepare the distributed_data_object
nkdict = distributed_data_object(
......@@ -263,19 +267,36 @@ class RGSpace(Space):
return dists
def get_fft_smoothing_kernel_function(self, sigma):
if sigma is None:
sigma = np.sqrt(2) * np.max(self.distances)
return lambda x: np.exp(-2. * np.pi**2 * x**2 * sigma**2)
return lambda x: np.exp(-0.5 * np.pi**2 * x**2 * sigma**2)
# ---Added properties and methods---
@property
def distances(self):
"""Distance between two grid points along each axis. It is a tuple
of positive floating point numbers with the n-th entry giving the
distances of grid points along the n-th dimension.
"""
return self._distances
@property
def zerocenter(self):
"""Returns True if grid points lie symmetrically around zero
Returns
-------
bool
True if the grid points are centered around the 0 grid point. This
option is most common for harmonic spaces (where both conventions
are used) but may be used for position spaces, too.
"""
return self._zerocenter
def _parse_shape(self, shape):
......
......@@ -22,68 +22,182 @@ from nifty.domain_object import DomainObject
class Space(DomainObject):
"""The abstract base class for all NIFTy spaces.
An instance of a space contains information about the manifolds geometry
and enhances the functionality of DomainObject by methods that are needed
for powerspectrum analysis and smoothing.
Parameters
----------
None
Attributes
----------
dim : np.int
Total number of dimensionality, i.e. the number of pixels.
harmonic : bool
Specifies whether the space is a signal or harmonic space.
total_volume : np.float
The total volume of the space.
shape : tuple of np.ints
The shape of the space's data array.
Raises
------
TypeError
Raised if instantiated directly.
Notes
-----
`Space` is an abstract base class. In order to allow for instantiation the
methods `get_distance_array`, `total_volume` and `copy` must be implemented
as well as the abstract methods inherited from `DomainObject`.
See Also
--------
distributor
"""
def __init__(self):
""" The abstract base class for all NIFTy spaces.
An instance of a space contains information about the manifolds
geometry and enhances the functionality of DomainObject by methods that
are needed for powerspectrum analysis and smoothing.
Parameters
----------
None
Attributes
----------
dim : np.int
Total number of dimensionality, i.e. the number of pixels.
harmonic : bool
Specifies whether the space is a signal or harmonic space.
total_volume : np.float
The total volume of the space.
shape : tuple of np.ints
The shape of the space's data array.
Raises
------
TypeError
Raised if instantiated directly.
Notes
-----
`Space` is an abstract base class. In order to allow for instantiation
the methods `get_distance_array`, `total_volume` and `copy` must be
implemented as well as the abstract methods inherited from
`DomainObject`.
"""
super(Space, self).__init__()
@abc.abstractproperty
def harmonic(self):
""" Returns True if this space is a harmonic space.
Raises
------
NotImplementedError
If called for this abstract class.
"""
raise NotImplementedError
@abc.abstractproperty
def total_volume(self):
""" Returns the total volume of the space.
Returns
-------
float
A real number representing the sum of all pixel volumes.
Raises
------
NotImplementedError
If called for this abstract class.
"""
raise NotImplementedError(
"There is no generic volume for the Space base class.")