correlated_fields.py 13.1 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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/>.
#
14
# Copyright(C) 2013-2019 Max-Planck-Society
Philipp Arras's avatar
Philipp Arras committed
15
# Authors: Philipp Frank, Philipp Arras
Martin Reinecke's avatar
Martin Reinecke committed
16
#
17
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
Philipp Arras's avatar
Philipp Arras committed
18

Philipp Arras's avatar
Philipp Arras committed
19
import numpy as np
20
from functools import reduce
Philipp Arras's avatar
Philipp Arras committed
21
from numpy.testing import assert_allclose
22

Philipp Arras's avatar
Philipp Arras committed
23
from ..domain_tuple import DomainTuple
Philipp Arras's avatar
Philipp Arras committed
24 25
from ..domains.power_space import PowerSpace
from ..domains.unstructured_domain import UnstructuredDomain
Philipp Arras's avatar
Philipp Arras committed
26
from ..extra import check_jacobian_consistency, consistency_check
27
from ..field import Field
Philipp Arras's avatar
Philipp Arras committed
28
from ..multi_domain import MultiDomain
Philipp Arras's avatar
Philipp Arras committed
29
from ..operators.adder import Adder
30
from ..operators.contraction_operator import ContractionOperator
Philipp Arras's avatar
Philipp Arras committed
31
from ..operators.distributors import PowerDistributor
Philipp Arras's avatar
Philipp Arras committed
32
from ..operators.endomorphic_operator import EndomorphicOperator
Martin Reinecke's avatar
Martin Reinecke committed
33
from ..operators.harmonic_operators import HarmonicTransformOperator
Philipp Arras's avatar
Philipp Arras committed
34
from ..operators.linear_operator import LinearOperator
35
from ..operators.diagonal_operator import DiagonalOperator
Philipp Arras's avatar
Philipp Arras committed
36 37
from ..operators.operator import Operator
from ..operators.simple_linear_operators import VdotOperator, ducktape
Philipp Arras's avatar
Philipp Arras committed
38
from ..operators.value_inserter import ValueInserter
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
from ..sugar import from_global_data, from_random, full, makeDomain, get_default_codomain

def _reshaper(domain, x, space):
    shape = reduce(lambda x,y: x+y,
            (domain[i].shape for i in range(len(domain)) if i != space),())
    x = np.array(x)
    if x.shape == shape:
        return np.asfarray(x)
    elif x.shape in [(), (1,)]:
        return np.full(shape, x, dtype=np.float)
    else:
        raise TypeError("Shape of parameters cannot be interpreted")

def _lognormal_moment_matching(mean, sig, key,
        domain = DomainTuple.scalar_domain(), space = 0):
    domain = makeDomain(domain)
    mean, sig = (_reshaper(domain, param, space) for param in (mean, sig))
    key = str(key)
    assert np.all(mean > 0)
    assert np.all(sig > 0)
Philipp Arras's avatar
Philipp Arras committed
59 60
    logsig = np.sqrt(np.log((sig/mean)**2 + 1))
    logmean = np.log(mean) - logsig**2/2
61
    return _normal(logmean, logsig, key, domain).exp()
Philipp Arras's avatar
Philipp Arras committed
62 63


64 65 66 67 68 69 70
def _normal(mean, sig, key,
        domain = DomainTuple.scalar_domain(), space = 0):
    domain = makeDomain(domain)
    mean, sig = (_reshaper(domain, param, space) for param in (mean, sig))
    assert np.all(sig > 0)
    return Adder(from_global_data(domain, mean)) @ (
        sig*ducktape(domain, None, key))
Philipp Arras's avatar
Philipp Arras committed
71 72


Philipp Frank's avatar
Philipp Frank committed
73
class _SlopeRemover(EndomorphicOperator):
74
    def __init__(self, domain, cooridinates, space = 0):
Philipp Frank's avatar
Philipp Frank committed
75
        self._domain = makeDomain(domain)
76
        self._sc = cooridinates / float(cooridinates[-1])
Philipp Arras's avatar
Philipp Arras committed
77

78 79
        self._space = space
        self._last = (slice(None),)*self._domain.axes[space][0] + (-1,)
Philipp Frank's avatar
Philipp Frank committed
80
        self._capability = self.TIMES | self.ADJOINT_TIMES
Philipp Arras's avatar
Philipp Arras committed
81

Philipp Frank's avatar
Philipp Frank committed
82 83 84 85
    def apply(self,x,mode):
        self._check_input(x,mode)
        x = x.to_global_data()
        if mode == self.TIMES:
86
            res = x - x[self._last] * self._sc
Philipp Frank's avatar
Philipp Frank committed
87
        else:
88
            #NOTE Why not x.copy()?
Philipp Frank's avatar
Philipp Frank committed
89
            res = np.zeros(x.shape,dtype=x.dtype)
Philipp Frank's avatar
Philipp Frank committed
90
            res += x
91
            res[self._last] -= (x*self._sc).sum(axis = self._space)
Philipp Frank's avatar
Philipp Frank committed
92 93
        return from_global_data(self._tgt(mode),res)

94
def _make_slope_Operator(smooth,loglogavgslope, space = 0):
Philipp Frank's avatar
Philipp Frank committed
95
    tg = smooth.target
96
    logkl = _log_k_lengths(tg[space])
Philipp Frank's avatar
Philipp Frank committed
97 98
    logkl -= logkl[0]
    logkl = np.insert(logkl, 0, 0)
99
    noslope = _SlopeRemover(tg,logkl, space) @ smooth
Philipp Frank's avatar
Philipp Frank committed
100 101 102
    # FIXME Move to tests
    consistency_check(_SlopeRemover(tg,logkl))

103 104 105
    expander = ContractionOperator(tg, spaces = space).adjoint
    _t = DiagonalOperator(from_global_data(tg, logkl), tg, spaces = space)
    return _t @ expander @ loglogavgslope + noslope
Philipp Arras's avatar
Philipp Arras committed
106 107 108 109 110

def _log_k_lengths(pspace):
    return np.log(pspace.k_lengths[1:])

class _TwoLogIntegrations(LinearOperator):
111
    def __init__(self, target, space = None):
Philipp Arras's avatar
Philipp Arras committed
112
        self._target = makeDomain(target)
113 114 115 116 117
        assert isinstance(self.target[space], PowerSpace)
        dom = list(self._target)
        dom[space] = UnstructuredDomain((2, self.target[space].shape[0]-2))
        self._domain = makeDomain(dom)
        self._space = space
Philipp Arras's avatar
Philipp Arras committed
118
        self._capability = self.TIMES | self.ADJOINT_TIMES
119
        logk_lengths = _log_k_lengths(self._target[space])
Philipp Arras's avatar
Philipp Arras committed
120 121 122 123
        self._logvol = logk_lengths[1:] - logk_lengths[:-1]

    def apply(self, x, mode):
        self._check_input(x, mode)
124 125 126 127 128 129 130 131 132

        #Maybe make class properties
        axis = self._target.axes[self._space][0]
        sl = (slice(None),)*axis
        first = sl + (0,)
        second = sl + (1,)
        from_third = sl + (slice(2,None),)
        no_border = sl + (slice(1,-1),)
        reverse = sl + (slice(None,None,-1),)
Philipp Arras's avatar
Philipp Arras committed
133 134 135
        if mode == self.TIMES:
            x = x.to_global_data()
            res = np.empty(self._target.shape)
136 137 138 139 140
            res[first] = 0
            res[second] = 0
            res[from_third] = np.cumsum(x[second], axis = axis)
            res[from_third] = (res[from_third] + res[no_border])/2*self._logvol + x[first]
            res[from_third] = np.cumsum(res[from_third], axis = axis)
Philipp Arras's avatar
Philipp Arras committed
141 142 143
        else:
            x = x.to_global_data_rw()
            res = np.zeros(self._domain.shape)
144 145 146 147 148 149
            x[from_third] = np.cumsum(x[from_third][reverse], axis = axis)[reverse]
            res[first] += x[from_third]
            x[from_third] *= self._logvol/2.
            x[no_border] += x[from_third]
            res[second] += np.cumsum(x[from_third][reverse], axis = axis)[reverse]
        return from_global_data(self._tgt(mode), res)
Philipp Arras's avatar
Philipp Arras committed
150 151 152


class _Normalization(Operator):
153
    def __init__(self, domain, space = 0):
Philipp Arras's avatar
Philipp Arras committed
154
        self._domain = self._target = makeDomain(domain)
155 156 157 158
        hspace = list(self._domain)
        hspace[space] = hspace[space].harmonic_partner
        hspace = makeDomain(hspace)
        pd = PowerDistributor(hspace, power_space=self._domain[space], space = space)
Philipp Arras's avatar
Philipp Arras committed
159
        # TODO Does not work on sphere yet
160 161 162 163
        mode_multiplicity = pd.adjoint(full(pd.target, 1.)).to_global_data_rw()
        mode_multiplicity[0] = 0
        self._mode_multiplicity = from_global_data(self._domain, mode_multiplicity)
        self._specsum = _SpecialSum(self._domain, space)
Philipp Arras's avatar
Philipp Arras committed
164 165
        # FIXME Move to tests
        consistency_check(self._specsum)
Philipp Arras's avatar
Philipp Arras committed
166 167 168 169 170 171 172

    def apply(self, x):
        self._check_input(x)
        amp = x.exp()
        spec = (2*x).exp()
        # FIXME This normalizes also the zeromode which is supposed to be left
        # untouched by this operator
173
        return self._specsum(self._mode_multiplicity*spec)**(-0.5)*amp
Philipp Arras's avatar
Philipp Arras committed
174 175 176


class _SpecialSum(EndomorphicOperator):
177
    def __init__(self, domain, space = 0):
Philipp Arras's avatar
Philipp Arras committed
178 179
        self._domain = makeDomain(domain)
        self._capability = self.TIMES | self.ADJOINT_TIMES
180 181
        self._contractor = ContractionOperator(domain, space)
        self._zero_mode = (slice(None),)*domain.axes[space][0] + (0,)
Philipp Arras's avatar
Philipp Arras committed
182 183 184

    def apply(self, x, mode):
        self._check_input(x, mode)
185
        return self._contractor.adjoint(self._contractor(x))
Philipp Arras's avatar
Philipp Arras committed
186 187 188 189 190 191 192


class CorrelatedFieldMaker:
    def __init__(self):
        self._amplitudes = []

    def add_fluctuations_from_ops(self, target, fluctuations, flexibility,
193
                                  asperity, loglogavgslope, key, space = 0):
Philipp Arras's avatar
Philipp Arras committed
194 195 196 197 198 199 200 201 202 203 204
        """
        fluctuations > 0
        flexibility > 0
        asperity > 0
        loglogavgslope probably negative
        """
        assert isinstance(fluctuations, Operator)
        assert isinstance(flexibility, Operator)
        assert isinstance(asperity, Operator)
        assert isinstance(loglogavgslope, Operator)
        target = makeDomain(target)
205
        assert isinstance(target[space], PowerSpace)
Philipp Arras's avatar
Philipp Arras committed
206

207
        twolog = _TwoLogIntegrations(target, space)
208 209 210 211 212 213 214 215 216 217 218 219
        dt = twolog._logvol
        sl = (slice(None),)*target.axes[space][0]
        first = sl + (0,)
        second = sl + (1,)
        expander = ContractionOperator(twolog.domain, spaces = space).adjoint
        
        sqrt_t = np.zeros(twolog.domain.shape)
        sqrt_t[first] = sqrt_t[second] = np.sqrt(dt)
        sqrt_t = from_global_data(twolog.domain, sqrt_t)
        sqrt_t = DiagonalOperator(sqrt_t, twolog.domain, spaces = space)
        sigmasq = sqrt_t @ expander @ flexibility

Philipp Arras's avatar
Philipp Arras committed
220
        dist = np.zeros(twolog.domain.shape)
221
        dist[first] += 1.
Philipp Arras's avatar
Philipp Arras committed
222
        dist = from_global_data(twolog.domain, dist)
223
        dist = DiagonalOperator(dist, twolog.domain, spaces = space)
Philipp Arras's avatar
Philipp Arras committed
224

225 226 227 228
        shift = np.ones(twolog.domain.shape)
        shift[first] = dt**2/12.
        shift = from_global_data(twolog.domain, shift)
        scale = sigmasq*(Adder(shift) @ dist @ expander @ asperity).sqrt()
Philipp Arras's avatar
Philipp Arras committed
229 230

        smooth = twolog @ (scale*ducktape(scale.target, None, key))
Philipp Frank's avatar
Philipp Frank committed
231 232
        smoothslope = _make_slope_Operator(smooth,loglogavgslope)
        
Philipp Arras's avatar
Philipp Arras committed
233 234 235
        # move to tests
        assert_allclose(
            smooth(from_random('normal', smooth.domain)).val[0:2], 0)
Philipp Arras's avatar
Philipp Arras committed
236
        consistency_check(twolog)
Philipp Arras's avatar
Philipp Arras committed
237 238
        check_jacobian_consistency(smooth, from_random('normal',
                                                       smooth.domain))
Philipp Arras's avatar
Philipp Arras committed
239 240
        check_jacobian_consistency(smoothslope,
                                   from_random('normal', smoothslope.domain))
Philipp Arras's avatar
Philipp Arras committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        # end move to tests

        normal_ampl = _Normalization(target) @ smoothslope
        vol = target[0].harmonic_partner.get_default_codomain().total_volume
        arr = np.zeros(target.shape)
        arr[1:] = vol
        expander = VdotOperator(from_global_data(target, arr)).adjoint
        mask = np.zeros(target.shape)
        mask[0] = vol
        adder = Adder(from_global_data(target, mask))
        ampl = adder @ ((expander @ fluctuations)*normal_ampl)

        # Move to tests
        # FIXME This test fails but it is not relevant for the final result
        # assert_allclose(
        #     normal_ampl(from_random('normal', normal_ampl.domain)).val[0], 1)
        assert_allclose(ampl(from_random('normal', ampl.domain)).val[0], vol)
Philipp Arras's avatar
Philipp Arras committed
258 259
        op = _Normalization(target)
        check_jacobian_consistency(op, from_random('normal', op.domain))
Philipp Arras's avatar
Philipp Arras committed
260 261 262 263 264 265 266
        # End move to tests

        self._amplitudes.append(ampl)

    def add_fluctuations(self, target, fluctuations_mean, fluctuations_stddev,
                         flexibility_mean, flexibility_stddev, asperity_mean,
                         asperity_stddev, loglogavgslope_mean,
267
                         loglogavgslope_stddev, prefix, space = 0):
Philipp Arras's avatar
Philipp Arras committed
268 269
        prefix = str(prefix)

270 271
        fluct = _lognormal_moment_matching(fluctuations_mean, fluctuations_stddev,
                                           prefix + 'fluctuations', space)
Philipp Arras's avatar
Philipp Arras committed
272
        flex = _lognormal_moment_matching(flexibility_mean, flexibility_stddev,
273
                                          prefix + 'flexibility', space)
Philipp Arras's avatar
Philipp Arras committed
274
        asp = _lognormal_moment_matching(asperity_mean, asperity_stddev,
275
                                         prefix + 'asperity', space)
276
        avgsl = _normal(loglogavgslope_mean, loglogavgslope_stddev,
277
                        prefix + 'loglogavgslope', space)
Philipp Arras's avatar
Philipp Arras committed
278
        self.add_fluctuations_from_ops(target, fluct, flex, asp, avgsl,
279
                                       prefix + 'spectrum', space)
Philipp Arras's avatar
Philipp Arras committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293

    def finalize_from_op(self, zeromode):
        raise NotImplementedError

    def finalize(self,
                 offset_amplitude_mean,
                 offset_amplitude_stddev,
                 prefix,
                 offset=None):
        """
        offset vs zeromode: volume factor
        """
        if offset is not None:
            offset = float(offset)
294
        #TODO correct hspace
Philipp Arras's avatar
Philipp Arras committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        hspace = makeDomain(
            [dd.target[0].harmonic_partner for dd in self._amplitudes])

        azm = _lognormal_moment_matching(offset_amplitude_mean,
                                         offset_amplitude_stddev,
                                         prefix + 'zeromode')
        foo = np.ones(hspace.shape)
        zeroind = len(hspace.shape)*(0,)
        foo[zeroind] = 0
        azm = Adder(from_global_data(hspace, foo)) @ ValueInserter(
            hspace, zeroind) @ azm

        ht = HarmonicTransformOperator(hspace, space=0)
        pd = PowerDistributor(hspace, self._amplitudes[0].target[0], 0)
        for i in range(1, len(self._amplitudes)):
            ht = HarmonicTransformOperator(ht.target, space=i) @ ht
            pd = pd @ PowerDistributor(
                pd.domain, self._amplitudes[i].target[0], space=i)

        spaces = tuple(range(len(self._amplitudes)))
        a = ContractionOperator(pd.domain,
                                spaces[1:]).adjoint(self._amplitudes[0])
        for i in range(1, len(self._amplitudes)):
            a = a*(ContractionOperator(pd.domain, spaces[:i] + spaces[
                (i + 1):]).adjoint(self._amplitudes[i]))

        A = pd @ a
        return ht(azm*A*ducktape(hspace, None, prefix + 'xi'))

    @property
    def amplitudes(self):
        return self._amplitudes