demo_excaliwir.py 8.09 KB
Newer Older
Marco Selig's avatar
Marco Selig 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
30
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2013 Max-Planck-Society
##
## Author: Marco Selig
## Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
##
## 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/>.

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  demo
    ..                               /______/

Marco Selig's avatar
Marco Selig committed
31
    NIFTY demo for (extended) critical Wiener filtering of Gaussian random signals.
Marco Selig's avatar
Marco Selig committed
32
33
34
35
36
37

"""
from __future__ import division
from nifty import *


Marco Selig's avatar
Marco Selig committed
38
##=============================================================================
Marco Selig's avatar
Marco Selig committed
39

Marco Selig's avatar
Marco Selig committed
40
class problem(object):
Marco Selig's avatar
Marco Selig committed
41

Marco Selig's avatar
Marco Selig committed
42
43
44
45
46
47
48
49
50
51
    def __init__(self, x_space, s2n=2, **kwargs):
        """
            Sets up a Wiener filter problem.

            Parameters
            ----------
            x_space : space
                Position space the signal lives in.
            s2n : float, *optional*
                Signal-to-noise ratio (default: 2).
Marco Selig's avatar
Marco Selig committed
52
53

        """
Marco Selig's avatar
Marco Selig committed
54
55
56
57
        ## set signal space
        self.z = x_space
        ## set conjugate space
        self.k = self.z.get_codomain()
58
        #self.k.set_power_indices(**kwargs)
Marco Selig's avatar
Marco Selig committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

        ## set some power spectrum
        self.power = (lambda k: 42 / (k + 1) ** 3)

        ## define signal covariance
        self.S = power_operator(self.k, spec=self.power, bare=True)
        ## define projector to spectral bands
        self.Sk = self.S.get_projection_operator()
        ## generate signal
        self.s = self.S.get_random_field(domain=self.z)

        ## define response
        self.R = response_operator(self.z, sigma=0.0, mask=1.0)
        ## get data space
        d_space = self.R.target

        ## define noise covariance
        self.N = diagonal_operator(d_space, diag=abs(s2n) * self.s.var(), bare=True)
        ## define (plain) projector
        self.Nj = projection_operator(d_space)
        ## generate noise
        n = self.N.get_random_field(domain=d_space)

        ## compute data
        self.d = self.R(self.s) + n

        ## define information source
86
87
        #self.j = self.R.adjoint_times(self.N.inverse_times(self.d), target=self.k)
        self.j = self.R.adjoint_times(self.N.inverse_times(self.d))
Marco Selig's avatar
Marco Selig committed
88
89
90
91
92
93
94
95
96
        ## define information propagator
        self.D = propagator_operator(S=self.S, N=self.N, R=self.R)

        ## reserve map
        self.m = None

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def solve(self, newspec=None):
Marco Selig's avatar
Marco Selig committed
97
        """
Marco Selig's avatar
Marco Selig committed
98
99
            Solves the Wiener filter problem for a given power spectrum
            reconstructing a signal estimate.
Marco Selig's avatar
Marco Selig committed
100

Marco Selig's avatar
Marco Selig committed
101
102
103
104
            Parameters
            ----------
            newspace : {scalar, list, array, field, function}, *optional*
                Assumed power spectrum (default: k ** -2).
Marco Selig's avatar
Marco Selig committed
105

Marco Selig's avatar
Marco Selig committed
106
107
108
109
110
111
112
        """
        ## set (given) power spectrum
        if(newspec is None):
            newspec = np.r_[1, 1 / self.k.power_indices["kindex"][1:] ** 2] ## Laplacian
        elif(newspec is False):
            newspec = self.power ## assumed to be known
        self.S.set_power(newspec, bare=True)
Marco Selig's avatar
Marco Selig committed
113

Marco Selig's avatar
Marco Selig committed
114
115
        ## reconstruct map
        self.m = self.D(self.j, W=self.S, tol=1E-3, note=False)
Marco Selig's avatar
Marco Selig committed
116

Marco Selig's avatar
Marco Selig committed
117
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
118

Marco Selig's avatar
Marco Selig committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    def solve_critical(self, newspec=None, q=0, alpha=1, delta=1, epsilon=0):
        """
            Solves the (generalised) Wiener filter problem
            reconstructing a signal estimate and a power spectrum.

            Parameters
            ----------
            newspace : {scalar, list, array, field, function}, *optional*
                Initial power spectrum (default: k ** -2).
            q : {scalar, list, array}, *optional*
                Spectral scale parameter of the assumed inverse-Gamme prior
                (default: 0).
            alpha : {scalar, list, array}, *optional*
                Spectral shape parameter of the assumed inverse-Gamme prior
                (default: 1).
            delta : float, *optional*
                First filter perception parameter (default: 1).
            epsilon : float, *optional*
                Second filter perception parameter (default: 0).

            See Also
            --------
            infer_power
Marco Selig's avatar
Marco Selig committed
142

Marco Selig's avatar
Marco Selig committed
143
144
145
146
147
148
149
        """
        ## set (initial) power spectrum
        if(newspec is None):
            newspec = np.r_[1, 1 / self.k.power_indices["kindex"][1:] ** 2] ## Laplacian
        elif(newspec is False):
            newspec = self.power ## assumed to be known
        self.S.set_power(newspec, bare=True)
Marco Selig's avatar
Marco Selig committed
150

Marco Selig's avatar
Marco Selig committed
151
152
        ## pre-compute denominator
        denominator = self.k.power_indices["rho"] + 2 * (alpha - 1 + abs(epsilon))
Marco Selig's avatar
Marco Selig committed
153

Marco Selig's avatar
Marco Selig committed
154
155
156
157
158
        ## iterate
        iterating = True
        while(iterating):

            ## reconstruct map
159
            self.m = self.D(self.j, W=self.S, tol=1E-3, note=True)
Marco Selig's avatar
Marco Selig committed
160
161
            if(self.m is None):
                break
162
            print 'Reconstructed m'
Marco Selig's avatar
Marco Selig committed
163
164
            ## reconstruct power spectrum
            tr_B1 = self.Sk.pseudo_tr(self.m) ## == Sk(m).pseudo_dot(m)
165
166
            print 'Calculated trace B1'
            print ('tr_b1', tr_B1)
Marco Selig's avatar
Marco Selig committed
167
            tr_B2 = self.Sk.pseudo_tr(self.D, loop=True)
168
169
170
            print 'Calculated trace B2'
            print ('tr_B2', tr_B2)
            numerator = 2 * q + tr_B1 +  tr_B2 * abs(delta)  ## non-bare(!)
Marco Selig's avatar
Marco Selig committed
171
            power = numerator / denominator
172
173
174
175
176
            print ('numerator', numerator)
            print ('denominator', denominator)
            print ('power', power)
            print 'Calculated power'
            power = np.clip(power, 0.1, np.max(power))
Marco Selig's avatar
Marco Selig committed
177
            ## check convergence
Marco Selig's avatar
Marco Selig committed
178
            dtau = log(power / self.S.get_power(), base=self.S.get_power())
Marco Selig's avatar
Marco Selig committed
179
            iterating = (np.max(np.abs(dtau)) > 2E-2)
Marco Selig's avatar
Marco Selig committed
180
            print max(np.abs(dtau))
Marco Selig's avatar
Marco Selig committed
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

            ## update signal covariance
            self.S.set_power(power, bare=False) ## auto-updates D

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def plot(self):
        """
            Produces plots.

        """
        ## plot signal
        self.s.plot(title="signal")
        ## plot data
        try:
            d_ = field(self.z, val=self.d.val, target=self.k)
            d_.plot(title="data", vmin=self.s.min(), vmax=self.s.max())
        except:
            pass
        ## plot map
        if(self.m is None):
            self.s.plot(power=True, mono=False, other=self.power)
        else:
            self.m.plot(title="reconstructed map", vmin=self.s.min(), vmax=self.s.max())
            self.m.plot(power=True, mono=False, other=(self.power, self.S.get_power()))
Marco Selig's avatar
Marco Selig committed
206
207
208
209

##=============================================================================

##-----------------------------------------------------------------------------
210
#
Marco Selig's avatar
Marco Selig committed
211
if(__name__=="__main__"):
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
    x = rg_space((128,))
    p = problem(x, log = False)
    about.warnings.off()
##    pl.close("all")
#
#    ## define signal space
#    x_space = rg_space(128)
#
#    ## setup problem
#    p = problem(x_space, log=True)
#    ## solve problem given some power spectrum
#    p.solve()
#    ## solve problem
#    p.solve_critical()
#
#    p.plot()
#
#    ## retrieve objects
#    k_space = p.k
#    power = p.power
#    S = p.S
#    Sk = p.Sk
#    s = p.s
#    R = p.R
#    d_space = p.R.target
#    N = p.N
#    Nj = p.Nj
#    d = p.d
#    j = p.j
#    D = p.D
#    m = p.m
Marco Selig's avatar
Marco Selig committed
243
244
245

##-----------------------------------------------------------------------------