Commit 54f203dd authored by Theo Steininger's avatar Theo Steininger
Browse files

Merge branch ''docu_power_space'' into 'master'

added all the docstrings for PowerSpace and changed PowerSpace.log to PowerSpace…

See merge request !95
parents 61a68dca 4e08ce82
Pipeline #12260 passed with stages
in 12 minutes and 27 seconds
......@@ -167,7 +167,7 @@ class Field(Loggable, Versionable, object):
# ---Powerspectral methods---
def power_analyze(self, spaces=None, log=False, nbin=None, binbounds=None,
def power_analyze(self, spaces=None, logarithmic=False, nbin=None, binbounds=None,
decompose_power=False):
# check if all spaces in `self.domain` are either harmonic or
# power_space instances
......@@ -210,10 +210,10 @@ class Field(Loggable, Versionable, object):
self.val.get_axes_local_distribution_strategy(
self.domain_axes[space_index])
harmonic_domain = self.domain[space_index]
power_domain = PowerSpace(harmonic_domain=harmonic_domain,
harmonic_partner = self.domain[space_index]
power_domain = PowerSpace(harmonic_partner=harmonic_partner,
distribution_strategy=distribution_strategy,
log=log, nbin=nbin, binbounds=binbounds)
logarithmic=logarithmic, nbin=nbin, binbounds=binbounds)
# extract pindex and rho from power_domain
pindex = power_domain.pindex
......@@ -221,7 +221,7 @@ class Field(Loggable, Versionable, object):
if decompose_power:
hermitian_part, anti_hermitian_part = \
harmonic_domain.hermitian_decomposition(
harmonic_partner.hermitian_decomposition(
self.val,
axes=self.domain_axes[space_index])
......@@ -322,8 +322,8 @@ class Field(Loggable, Versionable, object):
result_domain = list(self.domain)
for power_space_index in spaces:
power_space = self.domain[power_space_index]
harmonic_domain = power_space.harmonic_domain
result_domain[power_space_index] = harmonic_domain
harmonic_partner = power_space.harmonic_partner
result_domain[power_space_index] = harmonic_partner
# create random samples: one or two, depending on whether the
# power spectrum is real or complex
......@@ -365,8 +365,8 @@ class Field(Loggable, Versionable, object):
if real_signal:
for power_space_index in spaces:
harmonic_domain = result_domain[power_space_index]
result_val_list = [harmonic_domain.hermitian_decomposition(
harmonic_partner = result_domain[power_space_index]
result_val_list = [harmonic_partner.hermitian_decomposition(
result_val,
axes=result.domain_axes[power_space_index],
preserve_gaussian_variance=True)[0]
......
......@@ -24,15 +24,17 @@ class _PowerIndexFactory(object):
self.power_indices_storage = {}
def get_power_index(self, domain, distribution_strategy,
log=False, nbin=None, binbounds=None):
logarithmic=False, nbin=None, binbounds=None):
key = (domain, distribution_strategy)
if key not in self.power_indices_storage:
self.power_indices_storage[key] = \
PowerIndices(domain, distribution_strategy,
log=log, nbin=nbin, binbounds=binbounds)
logarithmic=logarithmic,
nbin=nbin,
binbounds=binbounds)
power_indices = self.power_indices_storage[key]
power_index = power_indices.get_index_dict(log=log,
power_index = power_indices.get_index_dict(logarithmic=logarithmic,
nbin=nbin,
binbounds=binbounds)
return power_index
......
......@@ -26,7 +26,7 @@ from d2o.config import configuration as d2o_config
class PowerIndices(object):
def __init__(self, domain, distribution_strategy,
log=False, nbin=None, binbounds=None):
logarithmic=False, nbin=None, binbounds=None):
"""
Returns an instance of the PowerIndices class. Given the shape and
the density of a underlying rectangular grid it provides the user
......@@ -42,7 +42,7 @@ class PowerIndices(object):
dgrid : tuple, list, ndarray
Array-like object which specifies the step-width of the
underlying grid
log : bool *optional*
logarithmic : bool *optional*
Flag specifying if the binning of the default indices is
performed on logarithmic scale.
nbin : integer *optional*
......@@ -59,7 +59,7 @@ class PowerIndices(object):
# Initialize the dictionary which stores all individual index-dicts
self.global_dict = {}
# Set self.default_parameters
self.set_default(config_dict={'log': log,
self.set_default(config_dict={'logarithmic': logarithmic,
'nbin': nbin,
'binbounds': binbounds})
......@@ -88,7 +88,7 @@ class PowerIndices(object):
Parameters
----------
log : bool
logarithmic : bool
Flag specifying if the binning is performed on logarithmic
scale.
nbin : integer
......@@ -113,24 +113,25 @@ class PowerIndices(object):
return self._cast_config_helper(**temp_config_dict)
else:
defaults = self.default_parameters
temp_log = kwargs.get("log", defaults['log'])
temp_logarithmic = kwargs.get("logarithmic",
defaults['logarithmic'])
temp_nbin = kwargs.get("nbin", defaults['nbin'])
temp_binbounds = kwargs.get("binbounds", defaults['binbounds'])
return self._cast_config_helper(log=temp_log,
return self._cast_config_helper(logarithmic=temp_logarithmic,
nbin=temp_nbin,
binbounds=temp_binbounds)
def _cast_config_helper(self, log, nbin, binbounds):
def _cast_config_helper(self, logarithmic, nbin, binbounds):
"""
internal helper function which sets the defaults for the
_cast_config function
"""
try:
temp_log = bool(log)
temp_logarithmic = bool(logarithmic)
except(TypeError):
temp_log = False
temp_logarithmic = False
try:
temp_nbin = int(nbin)
......@@ -142,7 +143,7 @@ class PowerIndices(object):
except(TypeError):
temp_binbounds = None
temp_dict = {"log": temp_log,
temp_dict = {"logarithmic": temp_logarithmic,
"nbin": temp_nbin,
"binbounds": temp_binbounds}
return temp_dict
......@@ -158,7 +159,7 @@ class PowerIndices(object):
store : bool
Flag specifying if the calculated index dictionary should be
stored in the global_dict for future use.
log : bool
logarithmic : bool
Flag specifying if the binning is performed on logarithmic
scale.
nbin : integer
......@@ -210,7 +211,7 @@ class PowerIndices(object):
"""
# if no binning is requested, compute the indices, build the dict,
# and return it straight.
if not config_dict["log"] and config_dict["nbin"] is None and \
if not config_dict["logarithmic"] and config_dict["nbin"] is None and \
config_dict["binbounds"] is None:
(temp_pindex, temp_kindex, temp_rho, temp_pundex) =\
self._compute_indices(self.k_array)
......@@ -222,7 +223,7 @@ class PowerIndices(object):
# Get the unbinned indices
temp_unbinned_indices = self.get_index_dict(nbin=None,
binbounds=None,
log=False,
logarithmic=False,
store=False)
# Bin them
(temp_pindex, temp_kindex, temp_rho, temp_pundex) = \
......@@ -344,7 +345,7 @@ class PowerIndices(object):
Array of all k-vector lengths.
rho : ndarray
Degeneracy factor of the individual k-vectors.
log : bool
logarithmic : bool
Flag specifying if the binning is performed on logarithmic
scale.
nbin : integer
......@@ -361,7 +362,7 @@ class PowerIndices(object):
"""
# Cast the given config
temp_config_dict = self._cast_config(**kwargs)
log = temp_config_dict['log']
logarithmic = temp_config_dict['logarithmic']
nbin = temp_config_dict['nbin']
binbounds = temp_config_dict['binbounds']
......@@ -375,9 +376,9 @@ class PowerIndices(object):
binbounds = np.sort(binbounds)
# equal binning
else:
if(log is None):
log = False
if(log):
if(logarithmic is None):
logarithmic = False
if(logarithmic):
k = np.r_[0, np.log(kindex[1:])]
else:
k = kindex
......@@ -391,7 +392,7 @@ class PowerIndices(object):
dk = (k[-1] - 0.5 * (k[2] + k[1])) / (nbin - 2.5)
binbounds = np.r_[0.5 * (3 * k[1] - k[2]),
0.5 * (k[1] + k[2]) + dk * np.arange(nbin - 2)]
if(log):
if(logarithmic):
binbounds = np.exp(binbounds)
# reordering
reorder = np.searchsorted(binbounds, kindex)
......
......@@ -27,34 +27,76 @@ from nifty.spaces.rg_space import RGSpace
class PowerSpace(Space):
""" NIFTY class for spaces of power spectra.
Parameters
----------
harmonic_partner : Space
The harmonic Space of which this is the power space.
distribution_strategy : str *optional*
The distribution strategy used for the distributed_data_objects
derived from this PowerSpace, e.g. the pindex.
(default : 'not')
logarithmic : bool *optional*
True if logarithmic binning should be used (default : False).
nbin : {int, None} *optional*
The number of bins that should be used for power spectrum binning
(default : None).
if nbin == None, then nbin is set to the length of kindex.
binbounds : {list, array-like} *optional*
Array-like inner boundaries of the used bins of the default
indices.
(default : None)
if binbounds == None :
Calculates the bounds from the kindex while applying the
logarithmic and nbin keywords.
Attributes
----------
pindex : distributed_data_object
TODO add description
kindex : numpy.ndarray
TODO add description
pundex : numpy.ndarray
TODO add description
rho : numpy.ndarray
The amount of k-modes that get mapped to one power bin is given by
rho.
Notes
-----
A power space is the result of a projection of a harmonic space where
k-modes of equal length get mapped to one power index.
"""
# ---Overwritten properties and methods---
def __init__(self, harmonic_domain=RGSpace((1,)),
def __init__(self, harmonic_partner=RGSpace((1,)),
distribution_strategy='not',
log=False, nbin=None, binbounds=None):
logarithmic=False, nbin=None, binbounds=None):
super(PowerSpace, self).__init__()
self._ignore_for_hash += ['_pindex', '_kindex', '_rho', '_pundex',
'_k_array']
if not isinstance(harmonic_domain, Space):
if not isinstance(harmonic_partner, Space):
raise ValueError(
"harmonic_domain must be a Space.")
if not harmonic_domain.harmonic:
"harmonic_partner must be a Space.")
if not harmonic_partner.harmonic:
raise ValueError(
"harmonic_domain must be a harmonic space.")
self._harmonic_domain = harmonic_domain
"harmonic_partner must be a harmonic space.")
self._harmonic_partner = harmonic_partner
power_index = PowerIndexFactory.get_power_index(
domain=self.harmonic_domain,
domain=self.harmonic_partner,
distribution_strategy=distribution_strategy,
log=log,
logarithmic=logarithmic,
nbin=nbin,
binbounds=binbounds)
config = power_index['config']
self._log = config['log']
self._logarithmic = config['logarithmic']
self._nbin = config['nbin']
self._binbounds = config['binbounds']
......@@ -65,6 +107,28 @@ class PowerSpace(Space):
self._k_array = power_index['k_array']
def pre_cast(self, x, axes):
""" Casts power spectrum functions to discretized power spectra.
This function takes an array or a function. If it is an array it does
nothing, otherwise it interpretes the function as power spectrum and
evaluates it at every k-mode.
Parameters
----------
x : {array-like, function array-like -> array-like}
power spectrum given either in discretized form or implicitly as a
function
axes : tuple of ints
Specifies the axes of x which correspond to this space. For
explicifying the power spectrum function, this is ignored.
Returns
-------
array-like
discretized power spectrum
"""
if callable(x):
return x(self.kindex)
else:
......@@ -91,9 +155,9 @@ class PowerSpace(Space):
def copy(self):
distribution_strategy = self.pindex.distribution_strategy
return self.__class__(harmonic_domain=self.harmonic_domain,
return self.__class__(harmonic_partner=self.harmonic_partner,
distribution_strategy=distribution_strategy,
log=self.log,
logarithmic=self.logarithmic,
nbin=self.nbin,
binbounds=self.binbounds)
......@@ -127,39 +191,61 @@ class PowerSpace(Space):
# ---Added properties and methods---
@property
def harmonic_domain(self):
return self._harmonic_domain
def harmonic_partner(self):
""" Returns the Space of which this is the power space.
"""
return self._harmonic_partner
@property
def log(self):
return self._log
def logarithmic(self):
""" Returns True if logarithmic binning is used.
"""
return self._logarithmic
@property
def nbin(self):
""" Returns the number of power bins if specfied during initialization.
"""
return self._nbin
@property
def binbounds(self):
""" Inner boundaries of the used bins if specfied during initialization.
"""
return self._binbounds
@property
def pindex(self):
""" A distributed_data_objects having the shape of the harmonic partner
space containing the indices of the power bin a pixel belongs to.
"""
return self._pindex
@property
def kindex(self):
""" Sorted array of all k-modes.
"""
return self._kindex
@property
def rho(self):
"""Degeneracy factor of the individual k-vectors.
"""
return self._rho
@property
def pundex(self):
""" An array for which the n-th entry gives the flat index of the
first occurence of a k-vector with length==kindex[n] in the
k_array.
"""
return self._pundex
@property
def k_array(self):
""" An array containing distances to the grid center (i.e. zero-mode)
for every k-mode in the grid of the harmonic partner space.
"""
return self._k_array
# ---Serialization---
......@@ -168,13 +254,13 @@ class PowerSpace(Space):
hdf5_group['kindex'] = self.kindex
hdf5_group['rho'] = self.rho
hdf5_group['pundex'] = self.pundex
hdf5_group['log'] = self.log
hdf5_group['logarithmic'] = self.logarithmic
# Store nbin as string, since it can be None
hdf5_group.attrs['nbin'] = str(self.nbin)
hdf5_group.attrs['binbounds'] = str(self.binbounds)
return {
'harmonic_domain': self.harmonic_domain,
'harmonic_partner': self.harmonic_partner,
'pindex': self.pindex,
'k_array': self.k_array
}
......@@ -188,8 +274,9 @@ class PowerSpace(Space):
# call instructor so that classes are properly setup
super(PowerSpace, new_ps).__init__()
# set all values
new_ps._harmonic_domain = repository.get('harmonic_domain', hdf5_group)
new_ps._log = hdf5_group['log'][()]
new_ps._harmonic_partner = repository.get('harmonic_partner',
hdf5_group)
new_ps._logarithmic = hdf5_group['logarithmic'][()]
exec('new_ps._nbin = ' + hdf5_group.attrs['nbin'])
exec('new_ps._binbounds = ' + hdf5_group.attrs['binbounds'])
......
......@@ -28,8 +28,8 @@ from nifty import PowerSpace, RGSpace, Space
from types import NoneType
from test.common import expand
# [harmonic_domain, distribution_strategy,
# log, nbin, binbounds, expected]
# [harmonic_partner, distribution_strategy,
# logarithmic, nbin, binbounds, expected]
CONSTRUCTOR_CONFIGS = [
[1, 'not', False, None, None, {'error': ValueError}],
[RGSpace((8,)), 'not', False, None, None, {'error': ValueError}],
......@@ -38,8 +38,8 @@ CONSTRUCTOR_CONFIGS = [
'shape': (5,),
'dim': 5,
'total_volume': 8.0,
'harmonic_domain': RGSpace((8,), harmonic=True),
'log': False,
'harmonic_partner': RGSpace((8,), harmonic=True),
'logarithmic': False,
'nbin': None,
'binbounds': None,
'pindex': distributed_data_object([0, 1, 2, 3, 4, 3, 2, 1]),
......@@ -53,8 +53,8 @@ CONSTRUCTOR_CONFIGS = [
'shape': (2,),
'dim': 2,
'total_volume': 8.0,
'harmonic_domain': RGSpace((8,), harmonic=True),
'log': True,
'harmonic_partner': RGSpace((8,), harmonic=True),
'logarithmic': True,
'nbin': None,
'binbounds': None,
'pindex': distributed_data_object([0, 1, 1, 1, 1, 1, 1, 1]),
......@@ -94,8 +94,8 @@ def get_weight_configs():
class PowerSpaceInterfaceTest(unittest.TestCase):
@expand([
['harmonic_domain', Space],
['log', bool],
['harmonic_partner', Space],
['logarithmic', bool],
['nbin', (int, NoneType)],
['binbounds', (list, NoneType)],
['pindex', distributed_data_object],
......@@ -112,17 +112,19 @@ class PowerSpaceInterfaceTest(unittest.TestCase):
class PowerSpaceFunctionalityTest(unittest.TestCase):
@expand(CONSTRUCTOR_CONFIGS)
def test_constructor(self, harmonic_domain, distribution_strategy, log,
nbin, binbounds, expected):
def test_constructor(self, harmonic_partner, distribution_strategy,
logarithmic, nbin, binbounds, expected):
if 'error' in expected:
with assert_raises(expected['error']):
PowerSpace(harmonic_domain=harmonic_domain,
PowerSpace(harmonic_partner=harmonic_partner,
distribution_strategy=distribution_strategy,
log=log, nbin=nbin, binbounds=binbounds)
logarithmic=logarithmic, nbin=nbin,
binbounds=binbounds)
else:
p = PowerSpace(harmonic_domain=harmonic_domain,
p = PowerSpace(harmonic_partner=harmonic_partner,
distribution_strategy=distribution_strategy,
log=log, nbin=nbin, binbounds=binbounds)
logarithmic=logarithmic, nbin=nbin,
binbounds=binbounds)
for key, value in expected.iteritems():
if isinstance(value, np.ndarray):
assert_almost_equal(getattr(p, key), value)
......@@ -130,14 +132,14 @@ class PowerSpaceFunctionalityTest(unittest.TestCase):
assert_equal(getattr(p, key), value)
@expand(get_distance_array_configs())
def test_distance_array(self, harmonic_domain, expected):
p = PowerSpace(harmonic_domain=harmonic_domain)
def test_distance_array(self, harmonic_partner, expected):
p = PowerSpace(harmonic_partner=harmonic_partner)
assert_almost_equal(p.get_distance_array('not'), expected)
@expand(get_weight_configs())
def test_weight(self, harmonic_domain, x, power, axes,
def test_weight(self, harmonic_partner, x, power, axes,
inplace, expected):
p = PowerSpace(harmonic_domain=harmonic_domain)
p = PowerSpace(harmonic_partner=harmonic_partner)
res = p.weight(x, power, axes, inplace)
assert_almost_equal(res, expected)
if inplace:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment