test_power.py 10.7 KB
Newer Older
Philipp Arras's avatar
Philipp Arras committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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/>.
#
# 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.

import unittest
import nifty4 as ift
import numpy as np
from itertools import product
from test.common import expand
from numpy.testing import assert_allclose


# TODO Add also other space types


30
class Energy_Tests(unittest.TestCase):
Philipp Arras's avatar
Philipp Arras committed
31
    @expand(product([ift.RGSpace(64, distances=.789),
32
33
34
35
                     ift.RGSpace([32, 32], distances=.789)],
                    [132, 42, 3]))
    def testLinearPower(self, space, seed):
        np.random.seed(seed)
Philipp Arras's avatar
Philipp Arras committed
36
37
38
39
40
41
42
43
        dim = len(space.shape)
        hspace = space.get_default_codomain()
        ht = ift.HarmonicTransformOperator(hspace, space)
        binbounds = ift.PowerSpace.useful_binbounds(hspace, logarithmic=True)
        pspace = ift.PowerSpace(hspace, binbounds=binbounds)
        P = ift.PowerProjectionOperator(domain=hspace, power_space=pspace)
        xi = ift.Field.from_random(domain=hspace, random_type='normal')

44
45
46
47
48
49
50
        # TODO Power spectrum abhängig von Anzahl der Pixel
        def pspec(k): return 64 / (1 + k**2)**dim
        pspec = ift.PS_field(pspace, pspec)
        tau0 = ift.log(pspec)
        A = P.adjoint_times(ift.sqrt(pspec))
        n = ift.Field.from_random(domain=space, random_type='normal', std=.01)
        N = ift.DiagonalOperator(n**2)
Philipp Arras's avatar
Philipp Arras committed
51
        s = xi * A
52
        diag = ift.Field.ones(space)
Philipp Arras's avatar
Philipp Arras committed
53
54
55
56
57
58
        Instrument = ift.DiagonalOperator(diag)
        R = Instrument * ht
        d = R(s) + n

        direction = ift.Field.from_random('normal', pspace)
        direction /= np.sqrt(direction.var())
59
        eps = 1e-7
Philipp Arras's avatar
Philipp Arras committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        tau1 = tau0 + eps * direction

        IC = ift.GradientNormController(
            name='IC',
            verbose=False,
            iteration_limit=100,
            tol_abs_gradnorm=1e-5)
        inverter = ift.ConjugateGradient(IC)

        S = ift.create_power_operator(hspace, power_spectrum=lambda k: 1.)

        D = ift.library.WienerFilterEnergy(position=s, d=d, R=R, N=N, S=S,
                                           inverter=inverter).curvature

74
75
76
77
78
79
80
        w = ift.Field.zeros_like(tau0)
        Nsamples = 10
        for i in range(Nsamples):
            sample = D.generate_posterior_sample() + s
            w += P(abs(sample)**2)
        w /= Nsamples

Philipp Arras's avatar
Philipp Arras committed
81
        energy0 = ift.library.CriticalPowerEnergy(
82
            position=tau0, m=s, inverter=inverter, w=w)
Philipp Arras's avatar
Philipp Arras committed
83
        energy1 = ift.library.CriticalPowerEnergy(
84
            position=tau1, m=s, inverter=inverter, w=w)
Philipp Arras's avatar
Philipp Arras committed
85
86
87

        a = (energy1.value - energy0.value) / eps
        b = energy0.gradient.vdot(direction)
88
        tol = 1e-4
Philipp Arras's avatar
Philipp Arras committed
89
90
91
92
        assert_allclose(a, b, rtol=tol, atol=tol)

    @expand(product([ift.RGSpace(64, distances=.789),
                     ift.RGSpace([32, 32], distances=.789)],
93
94
95
96
                    [ift.library.Exponential, ift.library.Linear],
                    [132, 42, 3]))
    def testNonlinearPower(self, space, nonlinearity, seed):
        np.random.seed(seed)
Philipp Arras's avatar
Philipp Arras committed
97
98
        f = nonlinearity()
        dim = len(space.shape)
99
100
        hspace = space.get_default_codomain()
        ht = ift.HarmonicTransformOperator(hspace, space)
Philipp Arras's avatar
Philipp Arras committed
101
102
103
104
105
106
107
108
109
        binbounds = ift.PowerSpace.useful_binbounds(hspace, logarithmic=True)
        pspace = ift.PowerSpace(hspace, binbounds=binbounds)
        P = ift.PowerProjectionOperator(domain=hspace, power_space=pspace)
        xi = ift.Field.from_random(domain=hspace, random_type='normal')

        def pspec(k): return 1 / (1 + k**2)**dim
        tau0 = ift.PS_field(pspace, pspec)
        A = P.adjoint_times(ift.sqrt(tau0))
        n = ift.Field.from_random(domain=space, random_type='normal')
110
        s = ht(xi * A)
Philipp Arras's avatar
Philipp Arras committed
111
112
113
114
115
116
117
118
        diag = ift.Field.ones(space) * 10
        R = ift.DiagonalOperator(diag)
        diag = ift.Field.ones(space)
        N = ift.DiagonalOperator(diag)
        d = R(f(s)) + n

        direction = ift.Field.from_random('normal', pspace)
        direction /= np.sqrt(direction.var())
119
        eps = 1e-7
Philipp Arras's avatar
Philipp Arras committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        tau1 = tau0 + eps * direction

        IC = ift.GradientNormController(
            name='IC',
            verbose=False,
            iteration_limit=100,
            tol_abs_gradnorm=1e-5)
        inverter = ift.ConjugateGradient(IC)

        S = ift.create_power_operator(hspace, power_spectrum=lambda k: 1.)
        D = ift.library.NonlinearWienerFilterEnergy(
            position=xi,
            d=d,
            Instrument=R,
            nonlinearity=f,
            power=A,
            N=N,
            S=S,
138
            ht=ht,
Philipp Arras's avatar
Philipp Arras committed
139
            inverter=inverter).curvature
140
141
        Nsamples = 10
        sample_list = [D.generate_posterior_sample() + xi for _ in range(Nsamples)]
Philipp Arras's avatar
Philipp Arras committed
142
143
144
145
146
147
148
149
150

        energy0 = ift.library.NonlinearPowerEnergy(
            position=tau0,
            d=d,
            m=xi,
            D=D,
            Instrument=R,
            Projection=P,
            nonlinearity=f,
151
            ht=ht,
Philipp Arras's avatar
Philipp Arras committed
152
            N=N,
153
            sample_list=sample_list)
Philipp Arras's avatar
Philipp Arras committed
154
155
156
157
158
159
160
161
        energy1 = ift.library.NonlinearPowerEnergy(
            position=tau1,
            d=d,
            m=xi,
            D=D,
            Instrument=R,
            Projection=P,
            nonlinearity=f,
162
            ht=ht,
Philipp Arras's avatar
Philipp Arras committed
163
            N=N,
164
            sample_list=sample_list)
Philipp Arras's avatar
Philipp Arras committed
165
166
167

        a = (energy1.value - energy0.value) / eps
        b = energy0.gradient.vdot(direction)
168
        tol = 1e-4
Philipp Arras's avatar
Philipp Arras committed
169
        assert_allclose(a, b, rtol=tol, atol=tol)
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304


class Curvature_Tests(unittest.TestCase):
    @expand(product([ift.RGSpace(64, distances=.789),
                     ift.RGSpace([32, 32], distances=.789)],
                    [132, 42, 3]))
    def testLinearPowerCurvature(self, space, seed):
        np.random.seed(seed)
        dim = len(space.shape)
        hspace = space.get_default_codomain()
        ht = ift.HarmonicTransformOperator(hspace, space)
        binbounds = ift.PowerSpace.useful_binbounds(hspace, logarithmic=True)
        pspace = ift.PowerSpace(hspace, binbounds=binbounds)
        P = ift.PowerProjectionOperator(domain=hspace, power_space=pspace)
        xi = ift.Field.from_random(domain=hspace, random_type='normal')

        # TODO Power spectrum abhängig von Anzahl der Pixel
        def pspec(k): return 64 / (1 + k**2)**dim
        pspec = ift.PS_field(pspace, pspec)
        tau0 = ift.log(pspec)
        A = P.adjoint_times(ift.sqrt(pspec))
        n = ift.Field.from_random(domain=space, random_type='normal', std=.01)
        N = ift.DiagonalOperator(n**2)
        s = xi * A
        diag = ift.Field.ones(space)
        Instrument = ift.DiagonalOperator(diag)
        R = Instrument * ht
        d = R(s) + n

        direction = ift.Field.from_random('normal', pspace)
        direction /= np.sqrt(direction.var())
        eps = 1e-7
        tau1 = tau0 + eps * direction

        IC = ift.GradientNormController(
            name='IC',
            verbose=False,
            iteration_limit=100,
            tol_abs_gradnorm=1e-5)
        inverter = ift.ConjugateGradient(IC)

        S = ift.create_power_operator(hspace, power_spectrum=lambda k: 1.)

        D = ift.library.WienerFilterEnergy(position=s, d=d, R=R, N=N, S=S,
                                           inverter=inverter).curvature

        w = ift.Field.zeros_like(tau0)
        Nsamples = 10
        for i in range(Nsamples):
            sample = D.generate_posterior_sample() + s
            w += P(abs(sample)**2)
        w /= Nsamples

        energy0 = ift.library.CriticalPowerEnergy(
            position=tau0, m=s, inverter=inverter, w=w)

        gradient0 = energy0.gradient
        gradient1 = energy0.at(tau1).gradient

        a = (gradient1 - gradient0) / eps
        b = energy0.curvature(direction)
        tol = 1e-5
        assert_allclose(a.val, b.val, rtol=tol, atol=tol)

    @expand(product([ift.RGSpace(64, distances=.789),
                     ift.RGSpace([32, 32], distances=.789)],
                    [ift.library.Exponential, ift.library.Linear],
                    [132, 42, 3]))
    def testNonlinearPowerCurvature(self, space, nonlinearity, seed):
        np.random.seed(seed)
        f = nonlinearity()
        dim = len(space.shape)
        hspace = space.get_default_codomain()
        ht = ift.HarmonicTransformOperator(hspace, space)
        binbounds = ift.PowerSpace.useful_binbounds(hspace, logarithmic=True)
        pspace = ift.PowerSpace(hspace, binbounds=binbounds)
        P = ift.PowerProjectionOperator(domain=hspace, power_space=pspace)
        xi = ift.Field.from_random(domain=hspace, random_type='normal')

        def pspec(k): return 1 / (1 + k**2)**dim
        tau0 = ift.PS_field(pspace, pspec)
        A = P.adjoint_times(ift.sqrt(tau0))
        n = ift.Field.from_random(domain=space, random_type='normal')
        s = ht(xi * A)
        diag = ift.Field.ones(space) * 10
        R = ift.DiagonalOperator(diag)
        diag = ift.Field.ones(space)
        N = ift.DiagonalOperator(diag)
        d = R(f(s)) + n

        direction = ift.Field.from_random('normal', pspace)
        direction /= np.sqrt(direction.var())
        eps = 1e-7
        tau1 = tau0 + eps * direction

        IC = ift.GradientNormController(
            name='IC',
            verbose=False,
            iteration_limit=100,
            tol_abs_gradnorm=1e-5)
        inverter = ift.ConjugateGradient(IC)

        S = ift.create_power_operator(hspace, power_spectrum=lambda k: 1.)
        D = ift.library.NonlinearWienerFilterEnergy(
            position=xi,
            d=d,
            Instrument=R,
            nonlinearity=f,
            power=A,
            N=N,
            S=S,
            ht=ht,
            inverter=inverter).curvature
        Nsamples = 10
        sample_list = [D.generate_posterior_sample() + xi for _ in range(Nsamples)]

        energy0 = ift.library.NonlinearPowerEnergy(
            position=tau0,
            d=d,
            m=xi,
            D=D,
            Instrument=R,
            Projection=P,
            nonlinearity=f,
            ht=ht,
            N=N,
            sample_list=sample_list)

        gradient0 = energy0.gradient
        gradient1 = energy0.at(tau1).gradient

        a = (gradient1 - gradient0) / eps
        b = energy0.curvature(direction)
        tol = 1e-1
        assert_allclose(a.val, b.val, rtol=tol, atol=tol)