amplitude_model.py 7.87 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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-2018 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

19
from __future__ import absolute_import, division, print_function
Philipp Arras's avatar
Philipp Arras committed
20

21
import numpy as np
Philipp Arras's avatar
Philipp Arras committed
22
23

from ..compat import *
Martin Reinecke's avatar
Martin Reinecke committed
24
25
from ..domains.power_space import PowerSpace
from ..domains.unstructured_domain import UnstructuredDomain
26
from ..field import Field
Martin Reinecke's avatar
Martin Reinecke committed
27
from ..multi.multi_field import MultiField
Martin Reinecke's avatar
Martin Reinecke committed
28
from ..multi.multi_domain import MultiDomain
29
from ..sugar import makeOp, sqrt
Martin Reinecke's avatar
Martin Reinecke committed
30
from ..operator import Operator
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48


def _ceps_kernel(dof_space, k, a, k0):
    return a**2/(1+(k/(k0*dof_space.bindistances[0]))**2)**2


def make_amplitude_model(s_space, Npixdof, ceps_a, ceps_k, sm, sv, im, iv,
                         keys=['tau', 'phi']):
    '''
    Method for construction of amplitude model
    Computes a smooth power spectrum.
    Output lives in PowerSpace.

    Parameters
    ----------

    Npixdof : #pix in dof_space

Martin Reinecke's avatar
Martin Reinecke committed
49
    ceps_a, ceps_k0 : Smoothness parameters in ceps_kernel
50
51
52
                        eg. ceps_kernel(k) = (a/(1+(k/k0)**2))**2
                        a = ceps_a,  k0 = ceps_k0

Martin Reinecke's avatar
Martin Reinecke committed
53
    sm, sv : slope_mean = expected exponent of power law (e.g. -4),
54
55
56
57
                slope_variance (default=1)

    im, iv : y-intercept_mean, y-intercept_variance  of power_slope
    '''
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
58
59
60
61
62
63
64
    from ..operators.exp_transform import ExpTransform
    from ..operators.qht_operator import QHTOperator
    from ..operators.slope_operator import SlopeOperator
    from ..operators.symmetrizing_operator import SymmetrizingOperator
    from ..models.variable import Variable
    from ..models.constant import Constant
    from ..models.local_nonlinearity import PointwiseExponential
65

66
67
68
69
    h_space = s_space.get_default_codomain()
    p_space = PowerSpace(h_space)
    exp_transform = ExpTransform(p_space, Npixdof)
    logk_space = exp_transform.domain[0]
Martin Reinecke's avatar
Martin Reinecke committed
70
71
    qht = QHTOperator(target=logk_space)
    dof_space = qht.domain[0]
72
73
74
75
76
77
78
    param_space = UnstructuredDomain(2)
    sym = SymmetrizingOperator(logk_space)

    phi_mean = np.array([sm, im])
    phi_sig = np.array([sv, iv])

    slope = SlopeOperator(param_space, logk_space, phi_sig)
79
    norm_phi_mean = Field.from_global_data(param_space, phi_mean/phi_sig)
80
81
82
83

    fields = {keys[0]: Field.from_random('normal', dof_space),
              keys[1]: Field.from_random('normal', param_space)}

Martin Reinecke's avatar
Martin Reinecke committed
84
    position = MultiField.from_dict(fields)
85
86
87
88
89
90
91
92

    dof_space = position[keys[0]].domain[0]
    kern = lambda k: _ceps_kernel(dof_space, k, ceps_a, ceps_k)
    cepstrum = create_cepstrum_amplitude_field(dof_space, kern)

    ceps = makeOp(sqrt(cepstrum))
    smooth_op = sym * qht * ceps
    smooth_spec = smooth_op(Variable(position)[keys[0]])
93
    phi = Variable(position)[keys[1]] + Constant(position, norm_phi_mean)
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    linear_spec = slope(phi)
    loglog_spec = smooth_spec + linear_spec
    xlog_ampl = PointwiseExponential(0.5*loglog_spec)

    internals = {'loglog_spec': loglog_spec,
                 'qht': qht,
                 'ceps': ceps,
                 'norm_phi_mean': norm_phi_mean}
    return exp_transform(xlog_ampl), internals


def create_cepstrum_amplitude_field(domain, cepstrum):
    """Creates a ...
    Writes the sum of all modes into the zero-mode.

    Parameters
    ----------
    domain: ???
        ???
    cepstrum: Callable
        ???
    """

    dim = len(domain.shape)
    dist = domain.bindistances
    shape = domain.shape

    # Prepare q_array
    q_array = np.zeros((dim,) + shape)
    if dim == 1:
124
        ks = domain.get_k_length_array().to_global_data()
125
126
127
128
129
        q_array = np.array([ks])
    else:
        for i in range(dim):
            ks = np.minimum(shape[i] - np.arange(shape[i]) +
                            1, np.arange(shape[i])) * dist[i]
Martin Reinecke's avatar
Martin Reinecke committed
130
            q_array[i] += ks.reshape((1,)*i + (shape[i],) + (1,)*(dim-i-1))
131
132
133
134
135
136
137
138
139
140

    # Fill cepstrum field (all non-zero modes)
    no_zero_modes = (slice(1, None),) * dim
    ks = q_array[(slice(None),) + no_zero_modes]
    cepstrum_field = np.zeros(shape)
    cepstrum_field[no_zero_modes] = cepstrum(ks)

    # Fill cepstrum field (zero-mode subspaces)
    for i in range(dim):
        # Prepare indices
Martin Reinecke's avatar
Martin Reinecke committed
141
142
143
        fst_dims = (slice(None),)*i
        sl = fst_dims + (slice(1, None),)
        sl2 = fst_dims + (0,)
144
145
146
147

        # Do summation
        cepstrum_field[sl2] = np.sum(cepstrum_field[sl], axis=i)

148
    return Field.from_global_data(domain, cepstrum_field)
Martin Reinecke's avatar
Martin Reinecke committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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

class AmplitudeModel(Operator):
    '''
    Computes a smooth power spectrum.
    Output lives in PowerSpace.

    Parameters
    ----------

    Npixdof : #pix in dof_space

    ceps_a, ceps_k0 : Smoothness parameters in ceps_kernel
                        eg. ceps_kernel(k) = (a/(1+(k/k0)**2))**2
                        a = ceps_a,  k0 = ceps_k0

    sm, sv : slope_mean = expected exponent of power law (e.g. -4),
                slope_variance (default=1)

    im, iv : y-intercept_mean, y-intercept_variance  of power_slope
    '''
    def __init__(self, s_space, Npixdof, ceps_a, ceps_k, sm, sv, im, iv,
                         keys=['tau', 'phi']):
        from ..operators.exp_transform import ExpTransform
        from ..operators.qht_operator import QHTOperator
        from ..operators.slope_operator import SlopeOperator
        from ..operators.symmetrizing_operator import SymmetrizingOperator
        from ..models.variable import Variable
        from ..models.constant import Constant
        from ..models.local_nonlinearity import PointwiseExponential

        h_space = s_space.get_default_codomain()
        p_space = PowerSpace(h_space)
        self._exp_transform = ExpTransform(p_space, Npixdof)
        logk_space = self._exp_transform.domain[0]
        qht = QHTOperator(target=logk_space)
        dof_space = qht.domain[0]
        param_space = UnstructuredDomain(2)
        sym = SymmetrizingOperator(logk_space)

        phi_mean = np.array([sm, im])
        phi_sig = np.array([sv, iv])

        self._slope = SlopeOperator(param_space, logk_space, phi_sig)
        self._norm_phi_mean = Field.from_global_data(param_space, phi_mean/phi_sig)

        self._domain = MultiDomain.make({keys[0]: dof_space, keys[1]: param_space})
#        fields = {keys[0]: Field.from_random('normal', dof_space),
#                  keys[1]: Field.from_random('normal', param_space)}
#        position = MultiField.from_dict(fields)

#        dof_space = position[keys[0]].domain[0]
        kern = lambda k: _ceps_kernel(dof_space, k, ceps_a, ceps_k)
        cepstrum = create_cepstrum_amplitude_field(dof_space, kern)

        ceps = makeOp(sqrt(cepstrum))
        self._smooth_op = sym * qht * ceps
        self._keys = tuple(keys)

#        smooth_spec = smooth_op(Variable(position)[keys[0]])

#        phi = Variable(position)[keys[1]] + Constant(position, norm_phi_mean)
#        linear_spec = slope(phi)
#        loglog_spec = smooth_spec + linear_spec
#        xlog_ampl = PointwiseExponential(0.5*loglog_spec)

    def __call__(self, x):
        smooth_spec = self._smooth_op(x[self._keys[0]])
        phi = x[self._keys[1]] + self._norm_phi_mean
        linear_spec = self._slope(phi)
        loglog_spec = smooth_spec + linear_spec
        return self._exp_transform((0.5*loglog_spec).exp())

    @property
    def domain(self):
        return self._domain

    @property
    def target(self):
        return self._exp_transform.target