correlated_fields.py 17.4 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

Philipp Arras's avatar
Philipp Arras committed
21
from ..domain_tuple import DomainTuple
Philipp Arras's avatar
Philipp Arras committed
22
23
from ..domains.power_space import PowerSpace
from ..domains.unstructured_domain import UnstructuredDomain
24
from ..field import Field
Philipp Arras's avatar
Philipp Arras committed
25
from ..operators.adder import Adder
26
from ..operators.contraction_operator import ContractionOperator
Philipp Arras's avatar
Philipp Arras committed
27
from ..operators.distributors import PowerDistributor
Philipp Arras's avatar
Philipp Arras committed
28
from ..operators.endomorphic_operator import EndomorphicOperator
Martin Reinecke's avatar
Martin Reinecke committed
29
from ..operators.harmonic_operators import HarmonicTransformOperator
Philipp Arras's avatar
Philipp Arras committed
30
from ..operators.linear_operator import LinearOperator
Philipp Arras's avatar
Philipp Arras committed
31
32
from ..operators.operator import Operator
from ..operators.simple_linear_operators import VdotOperator, ducktape
Philipp Arras's avatar
Philipp Arras committed
33
from ..operators.value_inserter import ValueInserter
34
from ..probing import StatCalculator
Philipp Arras's avatar
Philipp Arras committed
35
from ..sugar import from_global_data, full, makeDomain
36

Philipp Arras's avatar
Philipp Arras committed
37

38
39
def _lognormal_moments(mean, sig):
    mean, sig = float(mean), float(sig)
Philipp Arras's avatar
Philipp Arras committed
40
41
42
    assert sig > 0
    logsig = np.sqrt(np.log((sig/mean)**2 + 1))
    logmean = np.log(mean) - logsig**2/2
43
44
    return logmean, logsig

Philipp Arras's avatar
Philipp Arras committed
45

Philipp Arras's avatar
Philipp Arras committed
46
47
48
49
50
def _normal(mean, sig, key):
    return Adder(Field.scalar(mean)) @ (
        sig*ducktape(DomainTuple.scalar_domain(), None, key))


Philipp Arras's avatar
Philipp Arras committed
51
def _log_k_lengths(pspace):
Philipp Arras's avatar
Philipp Arras committed
52
    """Log(k_lengths) without zeromode"""
Philipp Arras's avatar
Philipp Arras committed
53
54
55
    return np.log(pspace.k_lengths[1:])


Philipp Arras's avatar
Philipp Arras committed
56
def _relative_log_k_lengths(power_space):
Philipp Arras's avatar
Philipp Arras committed
57
58
    """Log-distance to first bin
    logkl.shape==power_space.shape, logkl[0]=logkl[1]=0"""
Philipp Arras's avatar
Philipp Arras committed
59
60
61
62
63
64
    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
65
    return np.insert(logkl, 0, 0)
Philipp Arras's avatar
Philipp Arras committed
66
67


Philipp Arras's avatar
Philipp Arras committed
68
69
70
71
72
73
74
75
def _log_vol(power_space):
    power_space = DomainTuple.make(power_space)
    assert isinstance(power_space[0], PowerSpace)
    assert len(power_space) == 1
    logk_lengths = _log_k_lengths(power_space[0])
    return logk_lengths[1:] - logk_lengths[:-1]


76
77
78
79
80
81
82
83
84
85
86
87
88
89
def _total_fluctuation_realized(samples):
    res = 0.
    for s in samples:
        res = res + (s - s.mean())**2
    return np.sqrt((res/len(samples)).mean())


def _stats(op, samples):
    sc = StatCalculator()
    for s in samples:
        sc.add(op(s.extract(op.domain)))
    return sc.mean.to_global_data(), sc.var.sqrt().to_global_data()


Philipp Arras's avatar
Philipp Arras committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class _LognormalMomentMatching(Operator):
    def __init__(self, mean, sig, key):
        key = str(key)
        logmean, logsig = _lognormal_moments(mean, sig)
        self._mean = mean
        self._sig = sig
        op = _normal(logmean, logsig, key).exp()
        self._domain, self._target = op.domain, op.target
        self.apply = op.apply

    @property
    def mean(self):
        return self._mean

    @property
    def std(self):
        return self._sig


Philipp Frank's avatar
Philipp Frank committed
109
class _SlopeRemover(EndomorphicOperator):
Philipp Arras's avatar
Philipp Arras committed
110
    def __init__(self, domain):
Philipp Frank's avatar
Philipp Frank committed
111
        self._domain = makeDomain(domain)
Philipp Arras's avatar
Philipp Arras committed
112
113
        assert len(self._domain) == 1
        assert isinstance(self._domain[0], PowerSpace)
Philipp Arras's avatar
Philipp Arras committed
114
        logkl = _relative_log_k_lengths(self._domain)
115
        self._sc = logkl/float(logkl[-1])
Philipp Frank's avatar
Philipp Frank committed
116
        self._capability = self.TIMES | self.ADJOINT_TIMES
Philipp Arras's avatar
Philipp Arras committed
117

118
119
    def apply(self, x, mode):
        self._check_input(x, mode)
Philipp Frank's avatar
Philipp Frank committed
120
121
        x = x.to_global_data()
        if mode == self.TIMES:
122
            res = x - x[-1]*self._sc
Philipp Frank's avatar
Philipp Frank committed
123
        else:
124
            res = np.zeros(x.shape, dtype=x.dtype)
Philipp Frank's avatar
Philipp Frank committed
125
126
            res += x
            res[-1] -= (x*self._sc).sum()
127
        return from_global_data(self._tgt(mode), res)
Philipp Frank's avatar
Philipp Frank committed
128

129

Philipp Arras's avatar
Philipp Arras committed
130
131
132
class _TwoLogIntegrations(LinearOperator):
    def __init__(self, target):
        self._target = makeDomain(target)
Philipp Arras's avatar
Philipp Arras committed
133
134
        assert len(self._target) == 1
        assert isinstance(self._target[0], PowerSpace)
Philipp Arras's avatar
Philipp Arras committed
135
136
137
138
139
        self._domain = makeDomain(
            UnstructuredDomain((2, self.target.shape[0] - 2)))
        self._capability = self.TIMES | self.ADJOINT_TIMES
        if not isinstance(self._target[0], PowerSpace):
            raise TypeError
Philipp Arras's avatar
Philipp Arras committed
140
        self._log_vol = _log_vol(self._target[0])
Philipp Arras's avatar
Philipp Arras committed
141
142
143
144
145
146

    def apply(self, x, mode):
        self._check_input(x, mode)
        if mode == self.TIMES:
            x = x.to_global_data()
            res = np.empty(self._target.shape)
Philipp Arras's avatar
Philipp Arras committed
147
            res[0] = res[1] = 0
Philipp Arras's avatar
Philipp Arras committed
148
            res[2:] = np.cumsum(x[1])
Philipp Arras's avatar
Philipp Arras committed
149
            res[2:] = (res[2:] + res[1:-1])/2*self._log_vol + x[0]
Philipp Arras's avatar
Philipp Arras committed
150
151
152
153
154
155
156
            res[2:] = np.cumsum(res[2:])
            return from_global_data(self._target, res)
        else:
            x = x.to_global_data_rw()
            res = np.zeros(self._domain.shape)
            x[2:] = np.cumsum(x[2:][::-1])[::-1]
            res[0] += x[2:]
Philipp Arras's avatar
Philipp Arras committed
157
            x[2:] *= self._log_vol/2.
158
159
            x[1:-1] += x[2:]
            res[1] += np.cumsum(x[2:][::-1])[::-1]
Philipp Arras's avatar
Philipp Arras committed
160
161
162
163
164
165
            return from_global_data(self._domain, res)


class _Normalization(Operator):
    def __init__(self, domain):
        self._domain = self._target = makeDomain(domain)
Philipp Arras's avatar
Philipp Arras committed
166
        assert len(self._domain) == 1
Philipp Arras's avatar
Philipp Arras committed
167
        assert isinstance(self._domain[0], PowerSpace)
Philipp Arras's avatar
Philipp Arras committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        hspace = self._domain[0].harmonic_partner
        pd = PowerDistributor(hspace, power_space=self._domain[0])
        cst = pd.adjoint(full(pd.target, 1.)).to_global_data_rw()
        cst[0] = 0
        self._cst = from_global_data(self._domain, cst)
        self._specsum = _SpecialSum(self._domain)

    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
        return self._specsum(self._cst*spec)**(-0.5)*amp


class _SpecialSum(EndomorphicOperator):
    def __init__(self, domain):
        self._domain = makeDomain(domain)
Philipp Arras's avatar
Philipp Arras committed
187
        assert len(self._domain) == 1
Philipp Arras's avatar
Philipp Arras committed
188
189
190
191
192
193
194
        self._capability = self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_input(x, mode)
        return full(self._tgt(mode), x.sum())


195
196
197
class _Amplitude(Operator):
    def __init__(self, target, fluctuations, flexibility, asperity,
                 loglogavgslope, key):
Philipp Arras's avatar
Philipp Arras committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        """
        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)
        assert len(target) == 1
        assert isinstance(target[0], PowerSpace)

        twolog = _TwoLogIntegrations(target)
Philipp Arras's avatar
Philipp Arras committed
213
214
215
216
217
218
219
        dom = twolog.domain
        shp = dom.shape
        totvol = target[0].harmonic_partner.get_default_codomain().total_volume

        # Prepare constant fields
        foo = np.zeros(shp)
        foo[0] = foo[1] = np.sqrt(_log_vol(target))
Philipp Arras's avatar
Philipp Arras committed
220
        vflex = from_global_data(dom, foo)
Philipp Arras's avatar
Philipp Arras committed
221
222
223

        foo = np.zeros(shp, dtype=np.float64)
        foo[0] += 1
Philipp Arras's avatar
Philipp Arras committed
224
        vasp = from_global_data(dom, foo)
Philipp Arras's avatar
Philipp Arras committed
225
226
227
228
229

        foo = np.ones(shp)
        foo[0] = _log_vol(target)**2/12.
        shift = from_global_data(dom, foo)

Philipp Arras's avatar
Philipp Arras committed
230
        vslope = from_global_data(target, _relative_log_k_lengths(target))
Philipp Arras's avatar
Philipp Arras committed
231

Philipp Frank's avatar
fixup  
Philipp Frank committed
232
        foo, bar = [np.zeros(target.shape) for _ in range(2)]
Philipp Arras's avatar
Philipp Arras committed
233
234
        bar[1:] = foo[0] = totvol
        vol0, vol1 = [from_global_data(target, aa) for aa in (foo, bar)]
Philipp Arras's avatar
Philipp Arras committed
235
236
        # End prepare constant fields

Philipp Arras's avatar
Philipp Arras committed
237
238
239
        slope = VdotOperator(vslope).adjoint @ loglogavgslope
        sig_flex = VdotOperator(vflex).adjoint @ flexibility
        sig_asp = VdotOperator(vasp).adjoint @ asperity
Philipp Arras's avatar
Philipp Arras committed
240
241
242
        sig_fluc = VdotOperator(vol1).adjoint @ fluctuations

        xi = ducktape(dom, None, key)
Philipp Arras's avatar
Philipp Arras committed
243
        sigma = sig_flex*(Adder(shift) @ sig_asp).sqrt()
Philipp Arras's avatar
Philipp Arras committed
244
245
246
247
        smooth = _SlopeRemover(target) @ twolog @ (sigma*xi)
        op = _Normalization(target) @ (slope + smooth)
        op = Adder(vol0) @ (sig_fluc*op)

Philipp Arras's avatar
Philipp Arras committed
248
        self.apply = op.apply
Philipp Arras's avatar
Philipp Arras committed
249
        self._fluc = fluctuations
Philipp Arras's avatar
Philipp Arras committed
250
        self._domain, self._target = op.domain, op.target
Philipp Arras's avatar
Philipp Arras committed
251

Philipp Arras's avatar
Philipp Arras committed
252
253
254
255
    @property
    def fluctuation_amplitude(self):
        return self._fluc

256
257
258
259

class CorrelatedFieldMaker:
    def __init__(self):
        self._a = []
260
        self._azm = None
261
        self._position_spaces = []
262
263

    def add_fluctuations(self,
264
                         position_space,
265
266
267
268
269
270
271
272
                         fluctuations_mean,
                         fluctuations_stddev,
                         flexibility_mean,
                         flexibility_stddev,
                         asperity_mean,
                         asperity_stddev,
                         loglogavgslope_mean,
                         loglogavgslope_stddev,
273
                         prefix='',
Philipp Arras's avatar
Philipp Arras committed
274
                         index=None):
Philipp Arras's avatar
Philipp Arras committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
        fluctuations_mean = float(fluctuations_mean)
        fluctuations_stddev = float(fluctuations_stddev)
        flexibility_mean = float(flexibility_mean)
        flexibility_stddev = float(flexibility_stddev)
        asperity_mean = float(asperity_mean)
        asperity_stddev = float(asperity_stddev)
        loglogavgslope_mean = float(loglogavgslope_mean)
        loglogavgslope_stddev = float(loglogavgslope_stddev)
        prefix = str(prefix)
        assert fluctuations_stddev > 0
        assert fluctuations_mean > 0
        assert flexibility_stddev > 0
        assert flexibility_mean > 0
        assert asperity_stddev > 0
        assert asperity_mean > 0
        assert loglogavgslope_stddev > 0

Philipp Arras's avatar
Philipp Arras committed
292
293
294
295
296
297
298
        fluct = _LognormalMomentMatching(fluctuations_mean,
                                         fluctuations_stddev,
                                         prefix + 'fluctuations')
        flex = _LognormalMomentMatching(flexibility_mean, flexibility_stddev,
                                        prefix + 'flexibility')
        asp = _LognormalMomentMatching(asperity_mean, asperity_stddev,
                                       prefix + 'asperity')
299
        avgsl = _normal(loglogavgslope_mean, loglogavgslope_stddev,
Philipp Arras's avatar
Philipp Arras committed
300
                        prefix + 'loglogavgslope')
301
302
        amp = _Amplitude(PowerSpace(position_space.get_default_codomain()),
                         fluct, flex, asp, avgsl, prefix + 'spectrum')
303
304
        if index is not None:
            self._a.insert(index, amp)
305
            self._position_spaces.insert(index, position_space)
306
307
        else:
            self._a.append(amp)
308
            self._position_spaces.append(position_space)
309
310
311

    def finalize_from_op(self, zeromode, prefix=''):
        assert isinstance(zeromode, Operator)
312
        self._azm = zeromode
313
314
        hspace = makeDomain([dd.get_default_codomain()
                             for dd in self._position_spaces])
315
316
317
318
319
320
321
        foo = np.ones(hspace.shape)
        zeroind = len(hspace.shape)*(0,)
        foo[zeroind] = 0
        azm = Adder(from_global_data(hspace, foo)) @ ValueInserter(
            hspace, zeroind) @ zeromode

        n_amplitudes = len(self._a)
322
323
        ht = HarmonicTransformOperator(hspace, self._position_spaces[0],
                                       space=0)
324
        for i in range(1, n_amplitudes):
325
326
327
            ht = (HarmonicTransformOperator(ht.target,
                                            self._position_spaces[i],
                                            space=i) @ ht)
328
329
330
331
332
333
334
335
336
337
338

        pd = PowerDistributor(hspace, self._a[0].target[0], 0)
        for i in range(1, n_amplitudes):
            foo = PowerDistributor(pd.domain, self._a[i].target[0], space=i)
            pd = pd @ foo

        spaces = tuple(range(n_amplitudes))
        a = ContractionOperator(pd.domain, spaces[1:]).adjoint @ self._a[0]
        for i in range(1, n_amplitudes):
            co = ContractionOperator(pd.domain, spaces[:i] + spaces[(i + 1):])
            a = a*(co.adjoint @ self._a[i])
Philipp Arras's avatar
Philipp Arras committed
339

340
        return ht(azm*(pd @ a)*ducktape(hspace, None, prefix + 'xi'))
Philipp Arras's avatar
Philipp Arras committed
341
342
343
344

    def finalize(self,
                 offset_amplitude_mean,
                 offset_amplitude_stddev,
345
                 prefix='',
346
347
                 offset=None,
                 prior_info=100):
Philipp Arras's avatar
Philipp Arras committed
348
349
350
351
352
353
354
355
        """
        offset vs zeromode: volume factor
        """
        offset_amplitude_stddev = float(offset_amplitude_stddev)
        offset_amplitude_mean = float(offset_amplitude_mean)
        assert offset_amplitude_stddev > 0
        assert offset_amplitude_mean > 0
        if offset is not None:
356
            raise NotImplementedError
Philipp Arras's avatar
Philipp Arras committed
357
            offset = float(offset)
Philipp Arras's avatar
Philipp Arras committed
358
359
360
        azm = _LognormalMomentMatching(offset_amplitude_mean,
                                       offset_amplitude_stddev,
                                       prefix + 'zeromode')
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        op = self.finalize_from_op(azm, prefix)
        if prior_info > 0:
            from ..sugar import from_random
            samps = [
                from_random('normal', op.domain) for _ in range(prior_info)
            ]
            self.statistics_summary(samps)
        return op

    def statistics_summary(self, samples):
        lst = [('Offset amplitude', self.amplitude_total_offset),
               ('Total fluctuation amplitude', self.total_fluctuation)]

        namps = len(self.amplitudes)
        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:
            mean, stddev = _stats(op, samples)
            print('{}: {:.02E} ± {:.02E}'.format(kk, mean, stddev))

    def moment_slice_to_average(self, fluctuations_slice_mean, nsamples=1000):
        fluctuations_slice_mean = float(fluctuations_slice_mean)
        assert fluctuations_slice_mean > 0
        scm = 1.
        for a in self._a:
            m, std = a.fluctuation_amplitude.mean, a.fluctuation_amplitude.std
            mu, sig = _lognormal_moments(m, std)
            flm = np.exp(mu + sig*np.random.normal(size=nsamples))
            scm *= flm**2 + 1.
        return fluctuations_slice_mean/np.mean(np.sqrt(scm))
Philipp Arras's avatar
Philipp Arras committed
396
397
398

    @property
    def amplitudes(self):
399
        return self._a
400

401
402
403
404
405
406
    @property
    def amplitude_total_offset(self):
        return self._azm

    @property
    def total_fluctuation(self):
407
        """Returns operator which acts on prior or posterior samples"""
408
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
409
            raise NotImplementedError
410
411
412
413
414
        if len(self._a) == 1:
            return self._a[0].fluctuation_amplitude
        q = 1.
        for a in self._a:
            fl = a.fluctuation_amplitude
Philipp Arras's avatar
Philipp Arras committed
415
416
            q = q*(Adder(full(fl.target, 1.)) @ fl**2)
        return (Adder(full(q.target, -1.)) @ q).sqrt()
417

Philipp Arras's avatar
Philipp Arras committed
418
    def slice_fluctuation(self, space):
419
        """Returns operator which acts on prior or posterior samples"""
420
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
421
            raise NotImplementedError
422
423
424
425
426
427
428
        assert space < len(self._a)
        if len(self._a) == 1:
            return self._a[0].fluctuation_amplitude
        q = 1.
        for j in range(len(self._a)):
            fl = self._a[j].fluctuation_amplitude
            if j == space:
Philipp Arras's avatar
Philipp Arras committed
429
                q = q*fl**2
430
            else:
Philipp Arras's avatar
Philipp Arras committed
431
                q = q*(Adder(full(fl.target, 1.)) @ fl**2)
432
        return q.sqrt()
Philipp Arras's avatar
Philipp Arras committed
433
434

    def average_fluctuation(self, space):
435
        """Returns operator which acts on prior or posterior samples"""
436
        if len(self._a) == 0:
Philipp Arras's avatar
Philipp Arras committed
437
            raise NotImplementedError
438
439
440
441
442
        assert space < len(self._a)
        if len(self._a) == 1:
            return self._a[0].fluctuation_amplitude
        return self._a[space].fluctuation_amplitude

443
444
    @staticmethod
    def offset_amplitude_realized(samples):
445
446
        res = 0.
        for s in samples:
Philipp Frank's avatar
fixes  
Philipp Frank committed
447
            res = res + s.mean()**2
448
        return np.sqrt(res/len(samples))
Philipp Arras's avatar
Philipp Arras committed
449

450
451
452
453
454
455
456
457
    @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."""
458
459
460
        ldom = len(samples[0].domain)
        assert space < ldom
        if ldom == 1:
461
            return _total_fluctuation_realized(samples)
Philipp Arras's avatar
Philipp Arras committed
462
        res1, res2 = 0., 0.
463
        for s in samples:
Philipp Frank's avatar
fixes  
Philipp Frank committed
464
465
466
467
468
469
470
            res1 = res1 + s**2
            res2 = res2 + s.mean(space)**2
        res1 = res1/len(samples)
        res2 = res2/len(samples)
        res = res1.mean() - res2.mean()
        return np.sqrt(res)

471

Philipp Arras's avatar
Philipp Arras committed
472
    @staticmethod
473
474
475
476
477
478
479
480
481
482
483
    def average_fluctuation_realized(samples, space):
        """Computes average fluctuations from collection of field (defined in signal
        space) realizations."""
        ldom = len(samples[0].domain)
        assert space < ldom
        if ldom == 1:
            return _total_fluctuation_realized(samples)
        spaces = ()
        for i in range(ldom):
            if i != space:
                spaces += (i,)
Philipp Arras's avatar
Philipp Arras committed
484
485
        res = 0.
        for s in samples:
486
487
488
489
            r = s.mean(spaces)
            res = res + (r - r.mean())**2
        res = res/len(samples)
        return np.sqrt(res.mean())