test_power_space.py 8.23 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
Theo Steininger's avatar
Theo Steininger committed
13
14
15
16
17
#
# Copyright(C) 2013-2017 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

19
20
21
22
23
24
25
26
from __future__ import division

import unittest
import numpy as np

from d2o import distributed_data_object
from numpy.testing import assert_, assert_equal, assert_almost_equal,\
        assert_raises
27
from nifty import PowerSpace, RGSpace, Space, LMSpace
28
29
from types import NoneType
from test.common import expand
Reimar H Leike's avatar
Reimar H Leike committed
30
from itertools import product, chain
Martin Reinecke's avatar
Martin Reinecke committed
31
# needed to check wether fftw is available
Theo Steininger's avatar
Theo Steininger committed
32
from nifty import dependency_injector as gdi
Martin Reinecke's avatar
Martin Reinecke committed
33
from nose.plugins.skip import SkipTest
34

35
HARMONIC_SPACES = [RGSpace((8,), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
36
                   RGSpace((7,), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
37
                   RGSpace((7, 8), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
38
39
                   RGSpace((6, 6), harmonic=True),
                   RGSpace((7, 5), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
40
41
42
43
44
45
                   RGSpace((5, 5), harmonic=True),
                   RGSpace((4, 5, 7), harmonic=True),
                   LMSpace(6),
                   LMSpace(9)]


46
#Try all sensible kinds of combinations of spaces, distributuion strategy and
47
#binning parameters
48
49
_maybe_fftw = ["fftw"] if ('pyfftw' in gdi) else []

Martin Reinecke's avatar
Martin Reinecke committed
50
51
52
53
54
55
56
57
CONSISTENCY_CONFIGS_IMPLICIT = product(HARMONIC_SPACES,
                                       ["not", "equal", "fftw"],
                                       [None], [None, 3, 4], [True, False])
CONSISTENCY_CONFIGS_EXPLICIT = product(HARMONIC_SPACES,
                                       ["not", "equal", "fftw"],
                                       [[0., 1.3]], [None], [False])
CONSISTENCY_CONFIGS = chain(CONSISTENCY_CONFIGS_IMPLICIT,
                            CONSISTENCY_CONFIGS_EXPLICIT)
58

Theo Steininger's avatar
Theo Steininger committed
59
# [harmonic_partner, distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
60
#  logarithmic, nbin, binbounds, expected]
61
CONSTRUCTOR_CONFIGS = [
Martin Reinecke's avatar
Martin Reinecke committed
62
63
64
    [1, 'not', False, None, None, {'error': ValueError}],
    [RGSpace((8,)), 'not', False, None, None, {'error': ValueError}],
    [RGSpace((8,), harmonic=True), 'not', False, None, None, {
65
66
67
68
        'harmonic': True,
        'shape': (5,),
        'dim': 5,
        'total_volume': 8.0,
Theo Steininger's avatar
Theo Steininger committed
69
        'harmonic_partner': RGSpace((8,), harmonic=True),
Theo Steininger's avatar
Theo Steininger committed
70
        'config': {'logarithmic': False, 'nbin': None, 'binbounds': None},
71
72
73
74
75
76
        'pindex': distributed_data_object([0, 1, 2, 3, 4, 3, 2, 1]),
        'kindex': np.array([0., 1., 2., 3., 4.]),
        'rho': np.array([1, 2, 2, 2, 1]),
        'pundex': np.array([0, 1, 2, 3, 4]),
        'k_array': np.array([0., 1., 2., 3., 4., 3., 2., 1.]),
        }],
Martin Reinecke's avatar
Martin Reinecke committed
77
    [RGSpace((8,), harmonic=True), 'not', True, None, None, {
78
79
80
81
        'harmonic': True,
        'shape': (2,),
        'dim': 2,
        'total_volume': 8.0,
Theo Steininger's avatar
Theo Steininger committed
82
        'harmonic_partner': RGSpace((8,), harmonic=True),
Theo Steininger's avatar
Theo Steininger committed
83
        'config': {'logarithmic': True, 'nbin': None, 'binbounds': None},
84
85
86
87
88
89
90
91
92
93
94
        'pindex': distributed_data_object([0, 1, 1, 1, 1, 1, 1, 1]),
        'kindex': np.array([0., 2.28571429]),
        'rho': np.array([1, 7]),
        'pundex': np.array([0, 1]),
        'k_array': np.array([0., 2.28571429, 2.28571429, 2.28571429,
                             2.28571429, 2.28571429, 2.28571429, 2.28571429]),
        }],
    ]


def get_distance_array_configs():
Martin Reinecke's avatar
Martin Reinecke committed
95
    da_0 = np.array([0, 1.0, 1.41421356, 2., 2.23606798, 2.82842712])
96
    return [
Martin Reinecke's avatar
Martin Reinecke committed
97
        [RGSpace((4, 4), harmonic=True),  da_0],
98
99
100
101
        ]


def get_weight_configs():
Martin Reinecke's avatar
Martin Reinecke committed
102
103
104
105
106
107
108
109
110
    np.random.seed(42)

    # power 1
    w_0_x = np.random.rand(32, 16, 6)
    # RGSpace((4, 4), harmonic=True)
    # using rho directly
    weight_0 = np.array([1, 4, 4, 2, 4, 1])
    weight_0 = weight_0.reshape([1, 1, 6])
    w_0_res = w_0_x * weight_0
111
112
    return [
        [RGSpace((4, 4), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
113
            w_0_x, 1, (2,), False, w_0_res],
114
        [RGSpace((4, 4), harmonic=True),
Martin Reinecke's avatar
Martin Reinecke committed
115
            w_0_x.copy(), 1, (2,), True, w_0_res],
116
117
118
119
120
        ]


class PowerSpaceInterfaceTest(unittest.TestCase):
    @expand([
Theo Steininger's avatar
Theo Steininger committed
121
        ['harmonic_partner', Space],
Theo Steininger's avatar
Theo Steininger committed
122
        ['config', dict],
123
124
125
126
127
128
129
130
131
132
133
        ['pindex', distributed_data_object],
        ['kindex', np.ndarray],
        ['rho', np.ndarray],
        ['pundex', np.ndarray],
        ['k_array', distributed_data_object],
        ])
    def test_property_ret_type(self, attribute, expected_type):
        r = RGSpace((4, 4), harmonic=True)
        p = PowerSpace(r)
        assert_(isinstance(getattr(p, attribute), expected_type))

Martin Reinecke's avatar
Martin Reinecke committed
134

135
class PowerSpaceConsistencyCheck(unittest.TestCase):
136
    @expand(CONSISTENCY_CONFIGS)
137
    def test_pipundexInversion(self, harmonic_partner, distribution_strategy,
138
139
140
141
142
143
144
145
146
147
                               binbounds, nbin, logarithmic):
        if distribution_strategy == "fftw":
            if not hasattr(gdi.get('fftw'), 'FFTW_MPI'):
                raise SkipTest
        p = PowerSpace(harmonic_partner=harmonic_partner,
                       distribution_strategy=distribution_strategy,
                       logarithmic=logarithmic, nbin=nbin,
                       binbounds=binbounds)
        assert_equal(p.pindex.flatten()[p.pundex], np.arange(p.dim),
                     err_msg='pundex is not right-inverse of pindex!')
Martin Reinecke's avatar
Martin Reinecke committed
148

149
    @expand(CONSISTENCY_CONFIGS)
Martin Reinecke's avatar
Martin Reinecke committed
150
151
152
    def test_rhopindexConsistency(self, harmonic_partner,
                                  distribution_strategy, binbounds, nbin,
                                  logarithmic):
Theo Steininger's avatar
Theo Steininger committed
153
154
155
156
        if distribution_strategy == "fftw":
            if not hasattr(gdi.get('fftw'), 'FFTW_MPI'):
                print (gdi.get('fftw'), "blub \n\n\n")
                raise SkipTest
Martin Reinecke's avatar
Martin Reinecke committed
157
        p = PowerSpace(harmonic_partner=harmonic_partner,
158
159
160
                           distribution_strategy=distribution_strategy,
                           logarithmic=logarithmic, nbin=nbin,
                           binbounds=binbounds)
161
162
        assert_equal(p.pindex.flatten()[p.pundex],np.arange(p.dim),
            err_msg='pundex is not right-inverse of pindex!')
Martin Reinecke's avatar
Martin Reinecke committed
163

164
165
        assert_equal(p.pindex.flatten().bincount(), p.rho,
            err_msg='rho is not equal to pindex degeneracy')
Martin Reinecke's avatar
Martin Reinecke committed
166

167
class PowerSpaceFunctionalityTest(unittest.TestCase):
Martin Reinecke's avatar
Martin Reinecke committed
168
    @expand(CONSTRUCTOR_CONFIGS)
Theo Steininger's avatar
Theo Steininger committed
169
    def test_constructor(self, harmonic_partner, distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
170
                         logarithmic, nbin, binbounds, expected):
Theo Steininger's avatar
Theo Steininger committed
171
172
173
        if distribution_strategy == "fftw":
            if not hasattr(gdi.get('fftw'), 'FFTW_MPI'):
                raise SkipTest
Martin Reinecke's avatar
Martin Reinecke committed
174
            raise SkipTest
175
176
        if 'error' in expected:
            with assert_raises(expected['error']):
Theo Steininger's avatar
Theo Steininger committed
177
                PowerSpace(harmonic_partner=harmonic_partner,
178
                           distribution_strategy=distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
179
180
                           logarithmic=logarithmic, nbin=nbin,
                           binbounds=binbounds)
181
        else:
Theo Steininger's avatar
Theo Steininger committed
182
            p = PowerSpace(harmonic_partner=harmonic_partner,
183
                           distribution_strategy=distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
184
185
                           logarithmic=logarithmic, nbin=nbin,
                           binbounds=binbounds)
186
187
188
189
190
191
192
            for key, value in expected.iteritems():
                if isinstance(value, np.ndarray):
                    assert_almost_equal(getattr(p, key), value)
                else:
                    assert_equal(getattr(p, key), value)

    @expand(get_distance_array_configs())
Theo Steininger's avatar
Theo Steininger committed
193
194
    def test_distance_array(self, harmonic_partner, expected):
        p = PowerSpace(harmonic_partner=harmonic_partner)
195
196
197
        assert_almost_equal(p.get_distance_array('not'), expected)

    @expand(get_weight_configs())
Theo Steininger's avatar
Theo Steininger committed
198
    def test_weight(self, harmonic_partner, x, power, axes,
199
                    inplace, expected):
Theo Steininger's avatar
Theo Steininger committed
200
        p = PowerSpace(harmonic_partner=harmonic_partner)
201
202
203
204
        res = p.weight(x, power, axes, inplace)
        assert_almost_equal(res, expected)
        if inplace:
            assert_(x is res)