correlated_fields.py 29.5 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-2020 Max-Planck-Society
Philipp Arras's avatar
Philipp Arras committed
15
# Authors: Philipp Frank, Philipp Arras, Philipp Haim
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

19 20 21
from functools import reduce
from operator import mul

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

Philipp Arras's avatar
Philipp Arras committed
24
from .. import utilities
Philipp Arras's avatar
Philipp Arras committed
25
from ..domain_tuple import DomainTuple
Philipp Arras's avatar
Philipp Arras committed
26 27
from ..domains.power_space import PowerSpace
from ..domains.unstructured_domain import UnstructuredDomain
Philipp Arras's avatar
Philipp Arras committed
28
from ..field import Field
29
from ..logger import logger
Philipp Arras's avatar
Philipp Arras committed
30
from ..multi_field import MultiField
Philipp Arras's avatar
Philipp Arras committed
31
from ..operators.adder import Adder
32
from ..operators.contraction_operator import ContractionOperator
Philipp Arras's avatar
Philipp Arras committed
33
from ..operators.diagonal_operator import DiagonalOperator
Philipp Arras's avatar
Philipp Arras committed
34
from ..operators.distributors import PowerDistributor
Philipp Arras's avatar
Philipp Arras committed
35
from ..operators.endomorphic_operator import EndomorphicOperator
Martin Reinecke's avatar
Martin Reinecke committed
36
from ..operators.harmonic_operators import HarmonicTransformOperator
Philipp Arras's avatar
Philipp Arras committed
37
from ..operators.linear_operator import LinearOperator
Philipp Arras's avatar
Philipp Arras committed
38
from ..operators.operator import Operator
Philipp Arras's avatar
Philipp Arras committed
39
from ..operators.simple_linear_operators import ducktape
40
from ..operators.normal_operators import NormalTransform, LognormalTransform
41
from ..probing import StatCalculator
Philipp Arras's avatar
Philipp Arras committed
42
from ..sugar import full, makeDomain, makeField, makeOp
43

44

Philipp Arras's avatar
Philipp Arras committed
45
def _log_k_lengths(pspace):
Philipp Arras's avatar
Philipp Arras committed
46
    """Log(k_lengths) without zeromode"""
Philipp Arras's avatar
Philipp Arras committed
47 48 49
    return np.log(pspace.k_lengths[1:])


Philipp Arras's avatar
Philipp Arras committed
50
def _relative_log_k_lengths(power_space):
Philipp Arras's avatar
Philipp Arras committed
51 52
    """Log-distance to first bin
    logkl.shape==power_space.shape, logkl[0]=logkl[1]=0"""
Philipp Arras's avatar
Philipp Arras committed
53 54 55 56 57 58
    power_space = DomainTuple.make(power_space)
    assert isinstance(power_space[0], PowerSpace)
    assert len(power_space) == 1
    logkl = _log_k_lengths(power_space[0])
    assert logkl.shape[0] == power_space[0].shape[0] - 1
    logkl -= logkl[0]
Philipp Arras's avatar
Philipp Arras committed
59
    return np.insert(logkl, 0, 0)
Philipp Arras's avatar
Philipp Arras committed
60 61


Philipp Arras's avatar
Philipp Arras committed
62
def _log_vol(power_space):
63
    power_space = makeDomain(power_space)
Philipp Arras's avatar
Philipp Arras committed
64 65 66 67 68
    assert isinstance(power_space[0], PowerSpace)
    logk_lengths = _log_k_lengths(power_space[0])
    return logk_lengths[1:] - logk_lengths[:-1]


Philipp Haim's avatar
Philipp Haim committed
69 70 71 72 73 74
def _structured_spaces(domain):
    if isinstance(domain[0], UnstructuredDomain):
        return np.arange(1, len(domain))
    return np.arange(len(domain))


Philipp Haim's avatar
Philipp Haim committed
75
def _total_fluctuation_realized(samples):
Philipp Haim's avatar
Philipp Haim committed
76 77 78
    spaces = _structured_spaces(samples[0].domain)
    co = ContractionOperator(samples[0].domain, spaces)
    size = co.domain.size/co.target.size
79 80
    res = 0.
    for s in samples:
Philipp Haim's avatar
Philipp Haim committed
81 82
        res = res + (s - co.adjoint(co(s)/size))**2
    res = res.mean(spaces)/len(samples)
Philipp Haim's avatar
Philipp Haim committed
83
    return np.sqrt(res if np.isscalar(res) else res.val)
84 85


Philipp Frank's avatar
Philipp Frank committed
86
class _SlopeRemover(EndomorphicOperator):
Martin Reinecke's avatar
Martin Reinecke committed
87
    def __init__(self, domain, space=0):
Philipp Frank's avatar
Philipp Frank committed
88
        self._domain = makeDomain(domain)
89 90
        assert isinstance(self._domain[space], PowerSpace)
        logkl = _relative_log_k_lengths(self._domain[space])
91
        self._sc = logkl/float(logkl[-1])
Philipp Arras's avatar
Philipp Arras committed
92

93
        self._space = space
Philipp Haim's avatar
Philipp Haim committed
94 95 96
        axis = self._domain.axes[space][0]
        self._last = (slice(None),)*axis + (-1,) + (None,)
        self._extender = (None,)*(axis) + (slice(None),) + (None,)*(self._domain.axes[-1][-1]-axis)
Philipp Frank's avatar
Philipp Frank committed
97
        self._capability = self.TIMES | self.ADJOINT_TIMES
Philipp Arras's avatar
Philipp Arras committed
98

99 100
    def apply(self, x, mode):
        self._check_input(x, mode)
Martin Reinecke's avatar
stage 3  
Martin Reinecke committed
101
        x = x.val
Philipp Frank's avatar
Philipp Frank committed
102
        if mode == self.TIMES:
Philipp Haim's avatar
Philipp Haim committed
103
            res = x - x[self._last]*self._sc[self._extender]
Philipp Frank's avatar
Philipp Frank committed
104
        else:
105 106
            res = x.copy()
            res[self._last] -= (x*self._sc[self._extender]).sum(
Philipp Arras's avatar
Philipp Arras committed
107
                axis=self._space, keepdims=True)
Martin Reinecke's avatar
Martin Reinecke committed
108
        return makeField(self._tgt(mode), res)
Philipp Frank's avatar
Philipp Frank committed
109

Philipp Arras's avatar
Philipp Arras committed
110 111

class _TwoLogIntegrations(LinearOperator):
Martin Reinecke's avatar
Martin Reinecke committed
112
    def __init__(self, target, space=0):
Philipp Arras's avatar
Philipp Arras committed
113
        self._target = makeDomain(target)
114 115 116 117 118
        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
119
        self._log_vol = _log_vol(self._target[space])
Philipp Arras's avatar
Philipp Arras committed
120 121 122 123
        self._capability = self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_input(x, mode)
124

Martin Reinecke's avatar
Martin Reinecke committed
125
        # Maybe make class properties
126 127
        axis = self._target.axes[self._space][0]
        sl = (slice(None),)*axis
Philipp Haim's avatar
Fixes  
Philipp Haim committed
128
        extender_sl = (None,)*axis + (slice(None),) + (None,)*(self._target.axes[-1][-1] - axis)
129 130
        first = sl + (0,)
        second = sl + (1,)
Martin Reinecke's avatar
Martin Reinecke committed
131 132 133
        from_third = sl + (slice(2, None),)
        no_border = sl + (slice(1, -1),)
        reverse = sl + (slice(None, None, -1),)
134

Philipp Arras's avatar
Philipp Arras committed
135
        if mode == self.TIMES:
Martin Reinecke's avatar
stage 3  
Martin Reinecke committed
136
            x = x.val
Philipp Arras's avatar
Philipp Arras committed
137
            res = np.empty(self._target.shape)
138
            res[first] = res[second] = 0
Martin Reinecke's avatar
Martin Reinecke committed
139
            res[from_third] = np.cumsum(x[second], axis=axis)
140
            res[from_third] = (res[from_third] + res[no_border])/2*self._log_vol[extender_sl] + x[first]
Martin Reinecke's avatar
Martin Reinecke committed
141
            res[from_third] = np.cumsum(res[from_third], axis=axis)
Philipp Arras's avatar
Philipp Arras committed
142
        else:
Martin Reinecke's avatar
Martin Reinecke committed
143
            x = x.val_rw()
Philipp Arras's avatar
Philipp Arras committed
144
            res = np.zeros(self._domain.shape)
Martin Reinecke's avatar
Martin Reinecke committed
145
            x[from_third] = np.cumsum(x[from_third][reverse], axis=axis)[reverse]
146
            res[first] += x[from_third]
147
            x[from_third] *= (self._log_vol/2.)[extender_sl]
148
            x[no_border] += x[from_third]
Martin Reinecke's avatar
Martin Reinecke committed
149
            res[second] += np.cumsum(x[from_third][reverse], axis=axis)[reverse]
Martin Reinecke's avatar
Martin Reinecke committed
150
        return makeField(self._tgt(mode), res)
Philipp Arras's avatar
Philipp Arras committed
151 152 153


class _Normalization(Operator):
Martin Reinecke's avatar
Martin Reinecke committed
154
    def __init__(self, domain, space=0):
Philipp Arras's avatar
Philipp Arras committed
155
        self._domain = self._target = DomainTuple.make(domain)
156
        assert isinstance(self._domain[space], PowerSpace)
157 158 159
        hspace = list(self._domain)
        hspace[space] = hspace[space].harmonic_partner
        hspace = makeDomain(hspace)
Philipp Arras's avatar
Philipp Arras committed
160 161 162
        pd = PowerDistributor(hspace,
                              power_space=self._domain[space],
                              space=space)
Martin Reinecke's avatar
Martin Reinecke committed
163
        mode_multiplicity = pd.adjoint(full(pd.target, 1.)).val_rw()
164
        zero_mode = (slice(None),)*self._domain.axes[space][0] + (0,)
Philipp Haim's avatar
Philipp Haim committed
165
        mode_multiplicity[zero_mode] = 0
Philipp Arras's avatar
Philipp Arras committed
166
        self._mode_multiplicity = makeOp(makeField(self._domain, mode_multiplicity))
167
        self._specsum = _SpecialSum(self._domain, space)
Philipp Arras's avatar
Philipp Arras committed
168 169 170

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


class _SpecialSum(EndomorphicOperator):
Martin Reinecke's avatar
Martin Reinecke committed
179
    def __init__(self, domain, space=0):
Philipp Arras's avatar
Philipp Arras committed
180 181
        self._domain = makeDomain(domain)
        self._capability = self.TIMES | self.ADJOINT_TIMES
182
        self._contractor = ContractionOperator(domain, space)
Philipp Arras's avatar
Philipp Arras committed
183 184 185

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


Philipp Haim's avatar
Philipp Haim committed
189
class _Distributor(LinearOperator):
Lukas Platz's avatar
Lukas Platz committed
190
    def __init__(self, dofdex, domain, target):
191 192 193
        self._dofdex = np.array(dofdex)
        self._target = DomainTuple.make(target)
        self._domain = DomainTuple.make(domain)
Philipp Haim's avatar
Philipp Haim committed
194 195 196 197
        self._capability = self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_input(x, mode)
Martin Reinecke's avatar
stage 3  
Martin Reinecke committed
198
        x = x.val
Philipp Haim's avatar
Philipp Haim committed
199 200 201
        if mode == self.TIMES:
            res = x[self._dofdex]
        else:
202
            res = np.zeros(self._tgt(mode).shape, dtype=x.dtype)
203
            res = utilities.special_add_at(res, 0, self._dofdex, x)
Martin Reinecke's avatar
Martin Reinecke committed
204
        return makeField(self._tgt(mode), res)
Martin Reinecke's avatar
Martin Reinecke committed
205

206

207 208
class _Amplitude(Operator):
    def __init__(self, target, fluctuations, flexibility, asperity,
209
                 loglogavgslope, azm, totvol, key, dofdex):
Philipp Arras's avatar
Philipp Arras committed
210 211
        """
        fluctuations > 0
212 213
        flexibility > 0 or None
        asperity > 0 or None
Philipp Arras's avatar
Philipp Arras committed
214 215 216
        loglogavgslope probably negative
        """
        assert isinstance(fluctuations, Operator)
217 218
        assert isinstance(flexibility, Operator) or flexibility is None
        assert isinstance(asperity, Operator) or asperity is None
Philipp Arras's avatar
Philipp Arras committed
219 220
        assert isinstance(loglogavgslope, Operator)

Philipp Haim's avatar
Philipp Haim committed
221 222
        if len(dofdex) > 0:
            N_copies = max(dofdex) + 1
Philipp Haim's avatar
Philipp Haim committed
223
            space = 1
Philipp Frank's avatar
cleanup  
Philipp Frank committed
224 225
            distributed_tgt = makeDomain((UnstructuredDomain(len(dofdex)),
                                          target))
Philipp Haim's avatar
Philipp Haim committed
226
            target = makeDomain((UnstructuredDomain(N_copies), target))
Lukas Platz's avatar
Lukas Platz committed
227
            Distributor = _Distributor(dofdex, target, distributed_tgt)
Philipp Haim's avatar
Philipp Haim committed
228
        else:
Philipp Haim's avatar
Philipp Haim committed
229
            N_copies = 0
Philipp Haim's avatar
Philipp Haim committed
230
            space = 0
Philipp Haim's avatar
Philipp Haim committed
231
            distributed_tgt = target = makeDomain(target)
Martin Reinecke's avatar
Martin Reinecke committed
232
        azm_expander = ContractionOperator(distributed_tgt, spaces=space).adjoint
Philipp Haim's avatar
Philipp Haim committed
233
        assert isinstance(target[space], PowerSpace)
Martin Reinecke's avatar
Martin Reinecke committed
234

235
        twolog = _TwoLogIntegrations(target, space)
Philipp Arras's avatar
Philipp Arras committed
236
        dom = twolog.domain
237

238
        shp = dom[space].shape
Martin Reinecke's avatar
Martin Reinecke committed
239 240
        expander = ContractionOperator(dom, spaces=space).adjoint
        ps_expander = ContractionOperator(twolog.target, spaces=space).adjoint
Philipp Arras's avatar
Philipp Arras committed
241 242

        # Prepare constant fields
243 244 245
        vflex = np.zeros(shp)
        vflex[0] = vflex[1] = np.sqrt(_log_vol(target[space]))
        vflex = DiagonalOperator(makeField(dom[space], vflex), dom, space)
Philipp Arras's avatar
Philipp Arras committed
246

247 248 249
        vasp = np.zeros(shp, dtype=np.float64)
        vasp[0] += 1
        vasp = DiagonalOperator(makeField(dom[space], vasp), dom, space)
Philipp Arras's avatar
Philipp Arras committed
250

251 252 253 254
        shift = np.ones(shp)
        shift[0] = _log_vol(target[space])**2 / 12.
        shift = DiagonalOperator(makeField(dom[space], shift), dom, space)
        shift = shift(full(shift.domain, 1))
Martin Reinecke's avatar
Martin Reinecke committed
255

256
        vslope = DiagonalOperator(
Philipp Arras's avatar
Philipp Arras committed
257
            makeField(target[space], _relative_log_k_lengths(target[space])),
Martin Reinecke's avatar
Martin Reinecke committed
258
            target, space)
259

260 261
        vol0, vol1 = [np.zeros(target[space].shape) for _ in range(2)]
        vol1[1:] = vol0[0] = totvol
Philipp Arras's avatar
Philipp Arras committed
262 263
        vol0, vol1 = [
            DiagonalOperator(makeField(target[space], aa), target, space)
264
            for aa in (vol0, vol1)
Philipp Arras's avatar
Philipp Arras committed
265
        ]
266
        vol0 = vol0(full(vol0.domain, 1))
Philipp Arras's avatar
Philipp Arras committed
267 268
        # End prepare constant fields

269
        slope = vslope @ ps_expander @ loglogavgslope
270 271
        sig_flex = vflex @ expander @ flexibility if flexibility is not None else None
        sig_asp = vasp @ expander @ asperity if asperity is not None else None
272
        sig_fluc = vol1 @ ps_expander @ fluctuations
Philipp Haim's avatar
Philipp Haim committed
273
        sig_fluc = vol1 @ ps_expander @ fluctuations
Philipp Arras's avatar
Philipp Arras committed
274

275 276 277 278 279 280 281
        if sig_asp is None and sig_flex is None:
            op = _Normalization(target, space) @ slope
        elif sig_asp is None:
            xi = ducktape(dom, None, key)
            sigma = DiagonalOperator(shift.ptw("sqrt"), dom, space) @ sig_flex
            smooth = _SlopeRemover(target, space) @ twolog @ (sigma * xi)
            op = _Normalization(target, space) @ (slope + smooth)
282 283
        elif sig_flex is None:
            raise ValueError("flexibility may not be disabled on its own")
284 285 286 287 288 289
        else:
            xi = ducktape(dom, None, key)
            sigma = sig_flex * (Adder(shift) @ sig_asp).ptw("sqrt")
            smooth = _SlopeRemover(target, space) @ twolog @ (sigma * xi)
            op = _Normalization(target, space) @ (slope + smooth)

Philipp Haim's avatar
Philipp Haim committed
290
        if N_copies > 0:
Philipp Haim's avatar
Philipp Haim committed
291 292
            op = Distributor @ op
            sig_fluc = Distributor @ sig_fluc
Martin Reinecke's avatar
Martin Reinecke committed
293
            op = Adder(Distributor(vol0)) @ (sig_fluc*(azm_expander @ azm.ptw("reciprocal"))*op)
Philipp Arras's avatar
Philipp Arras committed
294 295
            self._fluc = (_Distributor(dofdex, fluctuations.target,
                                       distributed_tgt[0]) @ fluctuations)
Philipp Haim's avatar
Philipp Haim committed
296
        else:
Martin Reinecke's avatar
Martin Reinecke committed
297
            op = Adder(vol0) @ (sig_fluc*(azm_expander @ azm.ptw("reciprocal"))*op)
Philipp Frank's avatar
fixup  
Philipp Frank committed
298
            self._fluc = fluctuations
Philipp Arras's avatar
Philipp Arras committed
299

Philipp Arras's avatar
Philipp Arras committed
300 301
        self.apply = op.apply
        self._domain, self._target = op.domain, op.target
302
        self._space = space
303
        self._repr_str = "_Amplitude: " + op.__repr__()
Philipp Arras's avatar
Philipp Arras committed
304

Philipp Arras's avatar
Philipp Arras committed
305 306 307 308
    @property
    def fluctuation_amplitude(self):
        return self._fluc

309 310 311
    def __repr__(self):
        return self._repr_str

312 313

class CorrelatedFieldMaker:
314
    """Construction helper for hierarchical correlated field models.
Lukas Platz's avatar
Lukas Platz committed
315 316

    The correlated field models are parametrized by creating
317 318
    power spectrum operators ("amplitudes") via calls to
    :func:`add_fluctuations` that act on the targeted field subdomains.
Lukas Platz's avatar
Lukas Platz committed
319
    During creation of the :class:`CorrelatedFieldMaker` via
320 321 322
    :func:`make`, a global offset from zero of the field model
    can be defined and an operator applying fluctuations
    around this offset is parametrized.
Lukas Platz's avatar
Lukas Platz committed
323 324

    The resulting correlated field model operator has a
Martin Reinecke's avatar
Martin Reinecke committed
325
    :class:`~nifty7.multi_domain.MultiDomain` as its domain and
Lukas Platz's avatar
Lukas Platz committed
326 327 328
    expects its input values to be univariately gaussian.

    The target of the constructed operator will be a
Martin Reinecke's avatar
merge  
Martin Reinecke committed
329
    :class:`~nifty7.domain_tuple.DomainTuple` containing the
330 331
    `target_subdomains` of the added fluctuations in the order of
    the `add_fluctuations` calls.
Lukas Platz's avatar
Lukas Platz committed
332

333
    Creation of the model operator is completed by calling the method
Lukas Platz's avatar
Lukas Platz committed
334 335
    :func:`finalize`, which returns the configured operator.

336 337 338 339 340 341 342 343 344 345
    An operator representing an array of correlated field models
    can be constructed by setting the `total_N` parameter of
    :func:`make`. It will have an
    :class:`~nifty.domains.unstructucture_domain.UnstructureDomain`
    of shape `(total_N,)` prepended to its target domain and represent
    `total_N` correlated fields simulataneously.
    The degree of information sharing between the correlated field
    models can be configured via the `dofdex` parameters
    of :func:`make` and :func:`add_fluctuations`.

Lukas Platz's avatar
Lukas Platz committed
346
    See the methods :func:`make`, :func:`add_fluctuations`
347
    and :func:`finalize` for further usage information."""
348 349 350
    def __init__(self, offset_mean, offset_fluctuations_op, prefix, total_N):
        if not isinstance(offset_fluctuations_op, Operator):
            raise TypeError("offset_fluctuations_op needs to be an operator")
351
        self._a = []
352
        self._target_subdomains = []
Philipp Arras's avatar
Formats  
Philipp Arras committed
353

354 355
        self._offset_mean = offset_mean
        self._azm = offset_fluctuations_op
356
        self._prefix = prefix
Philipp Haim's avatar
Philipp Haim committed
357
        self._total_N = total_N
Philipp Arras's avatar
Formats  
Philipp Arras committed
358

359
    @staticmethod
360
    def make(offset_mean, offset_std, prefix, total_N=0, dofdex=None):
Lukas Platz's avatar
Lukas Platz committed
361 362 363 364 365 366
        """Returns a CorrelatedFieldMaker object.

        Parameters
        ----------
        offset_mean : float
            Mean offset from zero of the correlated field to be made.
367 368 369
        offset_std : tuple of float
            Mean standard deviation and standard deviation of the standard
            deviation of the offset. No, this is not a word duplication.
Lukas Platz's avatar
Lukas Platz committed
370 371
        prefix : string
            Prefix to the names of the domains of the cf operator to be made.
Lukas Platz's avatar
Lukas Platz committed
372
            This determines the names of the operator domain.
373 374
        total_N : integer, optional
            Number of field models to create.
Lukas Platz's avatar
Lukas Platz committed
375 376 377
            If not 0, the first entry of the operators target will be an
            :class:`~nifty.domains.unstructured_domain.UnstructuredDomain`
            with length `total_N`.
378
        dofdex : np.array of integers, optional
Philipp Arras's avatar
Philipp Arras committed
379 380 381
            An integer array specifying the zero mode models used if
            total_N > 1. It needs to have length of total_N. If total_N=3 and
            dofdex=[0,0,1], that means that two models for the zero mode are
382
            instantiated; the first one is used for the first and second
383 384 385
            field model and the second is used for the third field model.
            *If not specified*, use the same zero mode model for all
            constructed field models.
Lukas Platz's avatar
Lukas Platz committed
386
        """
Philipp Frank's avatar
Philipp Frank committed
387 388
        if dofdex is None:
            dofdex = np.full(total_N, 0)
389 390
        elif len(dofdex) != total_N:
            raise ValueError("length of dofdex needs to match total_N")
Philipp Frank's avatar
Philipp Frank committed
391
        N = max(dofdex) + 1 if total_N > 0 else 0
392 393 394
        if len(offset_std) != 2:
            raise TypeError
        zm = LognormalTransform(*offset_std, prefix + 'zeromode', N)
Philipp Frank's avatar
fixup  
Philipp Frank committed
395
        if total_N > 0:
Martin Reinecke's avatar
Martin Reinecke committed
396
            zm = _Distributor(dofdex, zm.target, UnstructuredDomain(total_N)) @ zm
397
        return CorrelatedFieldMaker(offset_mean, zm, prefix, total_N)
398 399

    def add_fluctuations(self,
400
                         target_subdomain,
401 402 403 404
                         fluctuations,
                         flexibility,
                         asperity,
                         loglogavgslope,
Martin Reinecke's avatar
Martin Reinecke committed
405 406 407 408
                         prefix='',
                         index=None,
                         dofdex=None,
                         harmonic_partner=None):
Lukas Platz's avatar
Lukas Platz committed
409 410 411 412 413 414
        """Function to add correlation structures to the field to be made.

        Correlations are described by their power spectrum and the subdomain
        on which they apply.

        The parameters `fluctuations`, `flexibility`, `asperity` and
415 416
        `loglogavgslope` configure the power spectrum model ("amplitude")
        used on the target field subdomain `target_subdomain`.
Lukas Platz's avatar
Lukas Platz committed
417 418
        It is assembled as the sum of a power law component
        (linear slope in log-log power-frequency-space),
Martin Reinecke's avatar
Martin Reinecke committed
419 420
        a smooth varying component (integrated Wiener process) and
        a ragged component (un-integrated Wiener process).
Lukas Platz's avatar
Lukas Platz committed
421 422 423 424 425 426 427

        Multiple calls to `add_fluctuations` are possible, in which case
        the constructed field will have the outer product of the individual
        power spectra as its global power spectrum.

        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
428 429
        target_subdomain : :class:`~nifty7.domain.Domain`, \
                           :class:`~nifty7.domain_tuple.DomainTuple`
Lukas Platz's avatar
Lukas Platz committed
430 431
            Target subdomain on which the correlation structure defined
            in this call should hold.
Lukas Platz's avatar
Lukas Platz committed
432
        fluctuations : tuple of float (mean, std)
Lukas Platz's avatar
Lukas Platz committed
433
            Total spectral energy -> Amplitude of the fluctuations
Lukas Platz's avatar
Lukas Platz committed
434
            LogNormal distribution
Lukas Platz's avatar
Lukas Platz committed
435
        flexibility : tuple of float (mean, std) or None
436
            Amplitude of the non-power-law power spectrum component
Lukas Platz's avatar
Lukas Platz committed
437
            LogNormal distribution
Lukas Platz's avatar
Lukas Platz committed
438
        asperity : tuple of float (mean, std) or None
439
            Roughness of the non-power-law power spectrum component
440
            Used to accommodate single frequency peaks
Lukas Platz's avatar
Lukas Platz committed
441
            LogNormal distribution
Lukas Platz's avatar
Lukas Platz committed
442
        loglogavgslope : tuple of float (mean, std)
Lukas Platz's avatar
Lukas Platz committed
443
            Power law component exponent
Lukas Platz's avatar
Lukas Platz committed
444
            Normal distribution
Lukas Platz's avatar
Lukas Platz committed
445 446
        prefix : string
            prefix of the power spectrum parameter domain names
Philipp Arras's avatar
Philipp Arras committed
447 448 449
        index : int
            Position target_subdomain in the final total domain of the
            correlated field operator.
450 451
        dofdex : np.array, optional
            An integer array specifying the power spectrum models used if
Philipp Arras's avatar
Philipp Arras committed
452
            total_N > 1. It needs to have length of total_N. If total_N=3 and
453
            dofdex=[0,0,1], that means that two power spectrum models are
454
            instantiated; the first one is used for the first and second
455 456 457
            field model and the second one is used for the third field model.
            *If not given*, use the same power spectrum model for all
            constructed field models.
Martin Reinecke's avatar
Martin Reinecke committed
458 459
        harmonic_partner : :class:`~nifty7.domain.Domain`, \
                           :class:`~nifty7.domain_tuple.DomainTuple`
Lukas Platz's avatar
Lukas Platz committed
460 461
            In which harmonic space to define the power spectrum
        """
Philipp Frank's avatar
Philipp Frank committed
462
        if harmonic_partner is None:
463
            harmonic_partner = target_subdomain.get_default_codomain()
Philipp Frank's avatar
Fixup  
Philipp Frank committed
464
        else:
465 466
            target_subdomain.check_codomain(harmonic_partner)
            harmonic_partner.check_codomain(target_subdomain)
467

Philipp Haim's avatar
Philipp Haim committed
468 469
        if dofdex is None:
            dofdex = np.full(self._total_N, 0)
470 471
        elif len(dofdex) != self._total_N:
            raise ValueError("length of dofdex needs to match total_N")
Philipp Haim's avatar
Philipp Haim committed
472

Philipp Haim's avatar
Philipp Haim committed
473 474
        if self._total_N > 0:
            N = max(dofdex) + 1
475
            target_subdomain = makeDomain((UnstructuredDomain(N), target_subdomain))
Philipp Haim's avatar
Philipp Haim committed
476
        else:
Philipp Haim's avatar
Philipp Haim committed
477
            N = 0
478
            target_subdomain = makeDomain(target_subdomain)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        # assert isinstance(target_subdomain[space], (RGSpace, HPSpace, GLSpace))

        for arg in [fluctuations, loglogavgslope]:
            if len(arg) != 2:
                raise TypeError
        for kw, arg in [("flexibility", flexibility), ("asperity", asperity)]:
            if arg is None:
                continue
            if len(arg) != 2:
                raise TypeError
            if len(arg) == 2 and (arg[0] <= 0. or arg[1] <= 0.):
                ve = "{0} must be strictly positive (or None)"
                raise ValueError(ve.format(kw))
        if flexibility is None and asperity is not None:
            raise ValueError("flexibility may not be disabled on its own")
Philipp Arras's avatar
Philipp Arras committed
494

495 496 497 498
        pre = self._prefix + str(prefix)
        fluct = LognormalTransform(*fluctuations, pre + 'fluctuations', N)
        if flexibility is not None:
            flex = LognormalTransform(*flexibility, pre + 'flexibility', N)
499
        else:
500
            flex = None
501 502
        if asperity is not None:
            asp = LognormalTransform(*asperity, pre + 'asperity', N)
503
        else:
504
            asp = None
505
        avgsl = NormalTransform(*loglogavgslope, pre + 'loglogavgslope', N)
506

Philipp Arras's avatar
Philipp Arras committed
507
        amp = _Amplitude(PowerSpace(harmonic_partner), fluct, flex, asp, avgsl,
508
                         self._azm, target_subdomain[-1].total_volume,
509
                         pre + 'spectrum', dofdex)
Philipp Haim's avatar
Philipp Haim committed
510

511 512
        if index is not None:
            self._a.insert(index, amp)
513
            self._target_subdomains.insert(index, target_subdomain)
514 515
        else:
            self._a.append(amp)
516
            self._target_subdomains.append(target_subdomain)
517

Philipp Arras's avatar
Philipp Arras committed
518 519 520 521 522 523 524 525 526 527
    def finalize(self, prior_info=100):
        """Finishes model construction process and returns the constructed
        operator.

        Parameters
        ----------
        prior_info : integer
            How many prior samples to draw for property verification statistics
            If zero, skips calculating and displaying statistics.
        """
Philipp Haim's avatar
Philipp Haim committed
528
        n_amplitudes = len(self._a)
Philipp Haim's avatar
Philipp Haim committed
529
        if self._total_N > 0:
Philipp Arras's avatar
Philipp Arras committed
530 531 532
            hspace = makeDomain(
                [UnstructuredDomain(self._total_N)] +
                [dd.target[-1].harmonic_partner for dd in self._a])
Philipp Haim's avatar
Philipp Haim committed
533 534
            spaces = tuple(range(1, n_amplitudes + 1))
            amp_space = 1
Philipp Haim's avatar
Philipp Haim committed
535 536
        else:
            hspace = makeDomain(
Philipp Arras's avatar
Philipp Arras committed
537
                [dd.target[0].harmonic_partner for dd in self._a])
Philipp Haim's avatar
Philipp Haim committed
538
            spaces = tuple(range(n_amplitudes))
Philipp Haim's avatar
Philipp Haim committed
539
            amp_space = 0
540

Martin Reinecke's avatar
Martin Reinecke committed
541
        expander = ContractionOperator(hspace, spaces=spaces).adjoint
Philipp Frank's avatar
fixup  
Philipp Frank committed
542
        azm = expander @ self._azm
543

544
        ht = HarmonicTransformOperator(hspace,
545
                                       self._target_subdomains[0][amp_space],
Martin Reinecke's avatar
Martin Reinecke committed
546
                                       space=spaces[0])
547
        for i in range(1, n_amplitudes):
548
            ht = HarmonicTransformOperator(ht.target,
549
                                           self._target_subdomains[i][amp_space],
550 551 552 553 554
                                           space=spaces[i]) @ ht
        a = []
        for ii in range(n_amplitudes):
            co = ContractionOperator(hspace, spaces[:ii] + spaces[ii + 1:])
            pp = self._a[ii].target[amp_space]
Philipp Haim's avatar
Philipp Haim committed
555
            pd = PowerDistributor(co.target, pp, amp_space)
556 557
            a.append(co.adjoint @ pd @ self._a[ii])
        corr = reduce(mul, a)
Philipp Arras's avatar
Philipp Arras committed
558
        op = ht(azm*corr*ducktape(hspace, None, self._prefix + 'xi'))
Philipp Arras's avatar
Philipp Arras committed
559

560 561
        if self._offset_mean is not None:
            offset = self._offset_mean
562 563 564 565 566 567 568
            # Deviations from this offset must not be considered here as they
            # are learned by the zeromode
            if isinstance(offset, (Field, MultiField)):
                op = Adder(offset) @ op
            else:
                offset = float(offset)
                op = Adder(full(op.target, offset)) @ op
569
        self.statistics_summary(prior_info)
570 571
        return op

572 573 574 575 576 577
    def statistics_summary(self, prior_info):
        from ..sugar import from_random

        if prior_info == 0:
            return

578 579
        lst = [('Offset amplitude', self.amplitude_total_offset),
               ('Total fluctuation amplitude', self.total_fluctuation)]
580
        namps = len(self._a)
581 582 583 584 585 586 587 588
        if namps > 1:
            for ii in range(namps):
                lst.append(('Slice fluctuation (space {})'.format(ii),
                            self.slice_fluctuation(ii)))
                lst.append(('Average fluctuation (space {})'.format(ii),
                            self.average_fluctuation(ii)))

        for kk, op in lst:
589 590
            sc = StatCalculator()
            for _ in range(prior_info):
591
                sc.add(op(from_random(op.domain, 'normal')))
Martin Reinecke's avatar
merge  
Martin Reinecke committed
592
            mean = sc.mean.val
Martin Reinecke's avatar
Martin Reinecke committed
593
            stddev = sc.var.ptw("sqrt").val
594
            for m, s in zip(mean.flatten(), stddev.flatten()):
595
                logger.info('{}: {:.02E} ± {:.02E}'.format(kk, m, s))
596 597 598

    def moment_slice_to_average(self, fluctuations_slice_mean, nsamples=1000):
        fluctuations_slice_mean = float(fluctuations_slice_mean)
599 600 601
        if not fluctuations_slice_mean > 0:
            msg = "fluctuations_slice_mean must be greater zero; got {!r}"
            raise ValueError(msg.format(fluctuations_slice_mean))
602
        from ..sugar import from_random
603 604
        scm = 1.
        for a in self._a:
Martin Reinecke's avatar
Martin Reinecke committed
605
            op = a.fluctuation_amplitude*self._azm.ptw("reciprocal")
606
            res = np.array([op(from_random(op.domain, 'normal')).val
607 608
                            for _ in range(nsamples)])
            scm *= res**2 + 1.
609
        return fluctuations_slice_mean/np.mean(np.sqrt(scm))
610

Philipp Arras's avatar
Philipp Arras committed
611
    @property
Philipp Haim's avatar
Philipp Haim committed
612
    def normalized_amplitudes(self):
613
        """Returns the power spectrum operators used in the model"""
614
        return self._a
Philipp Arras's avatar
Philipp Arras committed
615

Philipp Haim's avatar
Philipp Haim committed
616 617 618 619 620 621 622
    @property
    def amplitude(self):
        if len(self._a) > 1:
            s = ('If more than one spectrum is present in the model,',
                 ' no unique set of amplitudes exist because only the',
                 ' relative scale is determined.')
            raise NotImplementedError(s)
Philipp Haim's avatar
Fix  
Philipp Haim committed
623 624
        dom = self._a[0].target
        expand = ContractionOperator(dom, len(dom)-1).adjoint
Philipp Haim's avatar
Philipp Haim committed
625 626
        return self._a[0]*(expand @ self.amplitude_total_offset)

627 628 629
    @property
    def amplitude_total_offset(self):
        return self._azm
Philipp Arras's avatar
Philipp Arras committed
630 631

    @property
632
    def total_fluctuation(self):
633
        """Returns operator which acts on prior or posterior samples"""
634
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
635
            raise NotImplementedError
636
        if len(self._a) == 1:
637
            return self.average_fluctuation(0)
638 639
        q = 1.
        for a in self._a:
Martin Reinecke's avatar
Martin Reinecke committed
640
            fl = a.fluctuation_amplitude*self._azm.ptw("reciprocal")
Philipp Arras's avatar
Philipp Arras committed
641
            q = q*(Adder(full(fl.target, 1.)) @ fl**2)
Martin Reinecke's avatar
Martin Reinecke committed
642
        return (Adder(full(q.target, -1.)) @ q).ptw("sqrt")*self._azm
643

Philipp Arras's avatar
Philipp Arras committed
644
    def slice_fluctuation(self, space):
645
        """Returns operator which acts on prior or posterior samples"""
646
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
647
            raise NotImplementedError
648
        if space >= len(self._a):
649
            raise ValueError("invalid space specified; got {!r}".format(space))
650
        if len(self._a) == 1:
651
            return self.average_fluctuation(0)
652 653
        q = 1.
        for j in range(len(self._a)):
Martin Reinecke's avatar
Martin Reinecke committed
654
            fl = self._a[j].fluctuation_amplitude*self._azm.ptw("reciprocal")
655
            if j == space:
Philipp Arras's avatar
Philipp Arras committed
656
                q = q*fl**2
657
            else:
Philipp Arras's avatar
Philipp Arras committed
658
                q = q*(Adder(full(fl.target, 1.)) @ fl**2)
Martin Reinecke's avatar
Martin Reinecke committed
659
        return q.ptw("sqrt")*self._azm
Philipp Arras's avatar
Philipp Arras committed
660 661

    def average_fluctuation(self, space):
662
        """Returns operator which acts on prior or posterior samples"""
663
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
664
            raise NotImplementedError
665
        if space >= len(self._a):
666
            raise ValueError("invalid space specified; got {!r}".format(space))
667
        if len(self._a) == 1:
Philipp Haim's avatar
Philipp Haim committed
668 669
            return self._a[0].fluctuation_amplitude
        return self._a[space].fluctuation_amplitude
670

671 672
    @staticmethod
    def offset_amplitude_realized(samples):
Philipp Haim's avatar
Philipp Haim committed
673
        spaces = _structured_spaces(samples[0].domain)
674 675
        res = 0.
        for s in samples:
Philipp Haim's avatar
Philipp Haim committed
676
            res = res + s.mean(spaces)**2
Philipp Haim's avatar
Philipp Haim committed
677 678
        res = res/len(samples)
        return np.sqrt(res if np.isscalar(res) else res.val)
Philipp Arras's avatar
Philipp Arras committed
679

680 681 682 683 684 685 686 687
    @staticmethod
    def total_fluctuation_realized(samples):
        return _total_fluctuation_realized(samples)

    @staticmethod
    def slice_fluctuation_realized(samples, space):
        """Computes slice fluctuations from collection of field (defined in signal
        space) realizations."""
Philipp Haim's avatar
Philipp Haim committed
688 689
        spaces = _structured_spaces(samples[0].domain)
        if space >= len(spaces):
690
            raise ValueError("invalid space specified; got {!r}".format(space))
Philipp Haim's avatar
Philipp Haim committed
691
        if len(spaces) == 1:
692
            return _total_fluctuation_realized(samples)
Philipp Haim's avatar
Philipp Haim committed
693
        space = space + spaces[0]
Philipp Arras's avatar
Philipp Arras committed
694
        res1, res2 = 0., 0.
695
        for s in samples:
Philipp Frank's avatar
fixes  
Philipp Frank committed
696 697 698 699
            res1 = res1 + s**2
            res2 = res2 + s.mean(space)**2
        res1 = res1/len(samples)
        res2 = res2/len(samples)
Philipp Haim's avatar
Philipp Haim committed
700
        res = res1.mean(spaces) - res2.mean(spaces[:-1])
Philipp Haim's avatar
Philipp Haim committed
701
        return np.sqrt(res if np.isscalar(res) else res.val)
Philipp Frank's avatar
fixes  
Philipp Frank committed
702

Philipp Arras's avatar
Philipp Arras committed
703
    @staticmethod
704 705 706
    def average_fluctuation_realized(samples, space):
        """Computes average fluctuations from collection of field (defined in signal
        space) realizations."""
Philipp Haim's avatar
Philipp Haim committed
707 708
        spaces = _structured_spaces(samples[0].domain)
        if space >= len(spaces):
709
            raise ValueError("invalid space specified; got {!r}".format(space))
Philipp Haim's avatar
Philipp Haim committed
710
        if len(spaces) == 1:
711
            return _total_fluctuation_realized(samples)
Philipp Haim's avatar
Philipp Haim committed
712 713 714
        space = space + spaces[0]
        sub_spaces = set(spaces)
        sub_spaces.remove(space)
Philipp Arras's avatar
Philipp Arras committed
715
        # Domain containing domain[space] and domain[0] iff total_N>0
Philipp Haim's avatar
Philipp Haim committed
716
        sub_dom = makeDomain([samples[0].domain[ind]
Philipp Arras's avatar
Philipp Arras committed
717
                              for ind in (set([0])-set(spaces)) | set([space])])
Philipp Haim's avatar
Philipp Haim committed
718
        co = ContractionOperator(sub_dom, len(sub_dom)-1)
719
        size = co.domain.size/co.target.size
Philipp Arras's avatar
Philipp Arras committed
720 721
        res = 0.
        for s in samples:
Philipp Haim's avatar
Philipp Haim committed
722
            r = s.mean(sub_spaces)
723
            res = res + (r - co.adjoint(co(r)/size))**2
Philipp Haim's avatar
Philipp Haim committed
724
        res = res.mean(spaces[0])/len(samples)
Philipp Haim's avatar
Philipp Haim committed
725
        return np.sqrt(res if np.isscalar(res) else res.val)