sugar.py 4.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
# 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/>.
13 14 15 16 17
#
# Copyright(C) 2013-2017 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

19 20
from nifty import Space,\
                  PowerSpace,\
21
                  Field,\
22
                  ComposedOperator,\
23
                  DiagonalOperator,\
24
                  FFTOperator,\
25 26 27
                  sqrt,\
                  nifty_configuration

28 29 30
__all__ = ['create_power_operator',
           'generate_posterior_sample',
           'create_composed_fft_operator']
31 32


Jakob Knollmueller's avatar
Jakob Knollmueller committed
33
def create_power_operator(domain, power_spectrum, dtype=None,
34
                          distribution_strategy=None):
35
    """ Creates a diagonal operator with the given power spectrum.
36

37
    Constructs a diagonal operator that lives over the specified domain.
38

39 40 41
    Parameters
    ----------
    domain : DomainObject
42
        Domain over which the power operator shall live.
43
    power_spectrum : (array-like, method)
44 45
        An array-like object, or a method that implements the square root
        of a power spectrum as a function of k.
46
    dtype : type *optional*
47
        dtype that the field holding the power spectrum shall use
48 49 50
        (default : None).
        if dtype == None: the dtype of `power_spectrum` will be used.
    distribution_strategy : string *optional*
51
        Distributed strategy to be used by the underlying d2o objects.
52 53
        (default : 'not')

54 55
    Returns
    -------
56
    DiagonalOperator : An operator that implements the given power spectrum.
57

58
    """
59

60 61 62 63
    if distribution_strategy is None:
        distribution_strategy = \
            nifty_configuration['default_distribution_strategy']

Jakob Knollmueller's avatar
Jakob Knollmueller committed
64 65
    if isinstance(power_spectrum, Field):
        power_domain = power_spectrum.domain
66
    else:
Jakob Knollmueller's avatar
Jakob Knollmueller committed
67
        power_domain = PowerSpace(domain,
68
                                  distribution_strategy=distribution_strategy)
Jakob Knollmueller's avatar
Jakob Knollmueller committed
69

70
    fp = Field(power_domain, val=power_spectrum, dtype=dtype,
71 72 73
               distribution_strategy='not')
    f = fp.power_synthesize(mean=1, std=0, real_signal=False,
                            distribution_strategy=distribution_strategy)
74 75 76
    # MR FIXME: we need the real part here. Could this also be achieved
    # by setting real_signal=True in the call above?
    f = f.real
Jakob Knollmueller's avatar
Jakob Knollmueller committed
77
    f **= 2
78
    return DiagonalOperator(domain, diagonal=f, bare=True)
79

80

81 82 83
def generate_posterior_sample(mean, covariance):
    """ Generates a posterior sample from a Gaussian distribution with given
    mean and covariance
84

85 86 87
    This method generates samples by setting up the observation and
    reconstruction of a mock signal in order to obtain residuals of the right
    correlation which are added to the given mean.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

    Parameters
    ----------
    mean : Field
        the mean of the posterior Gaussian distribution
    covariance : WienerFilterCurvature
        The posterior correlation structure consisting of a
        response operator, noise covariance and prior signal covariance

    Returns
    -------
    sample : Field
        Returns the a sample from the Gaussian of given mean and covariance.

    """

104 105 106
    S = covariance.S
    R = covariance.R
    N = covariance.N
107

108
    power = S.diagonal().power_analyze()**.5
109 110
    mock_signal = power.power_synthesize(real_signal=True)

Jakob Knollmueller's avatar
Jakob Knollmueller committed
111
    noise = N.diagonal(bare=True).val
112

113
    mock_noise = Field.from_random(random_type="normal", domain=N.domain,
114
                                   std=sqrt(noise), dtype=noise.dtype)
Jakob Knollmueller's avatar
Jakob Knollmueller committed
115
    mock_data = R(mock_signal) + mock_noise
116

Jakob Knollmueller's avatar
Jakob Knollmueller committed
117
    mock_j = R.adjoint_times(N.inverse_times(mock_data))
118 119 120
    mock_m = covariance.inverse_times(mock_j)
    sample = mock_signal - mock_m + mean
    return sample
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140


def create_composed_fft_operator(domain, codomain=None, all_to='other'):
    fft_op_list = []
    space_index_list = []

    if codomain is None:
        codomain = [None]*len(domain)
    for i in range(len(domain)):
        space = domain[i]
        cospace = codomain[i]
        if not isinstance(space, Space):
            continue
        if (all_to == 'other' or
                (all_to == 'position' and space.harmonic) or
                (all_to == 'harmonic' and not space.harmonic)):
            fft_op_list += [FFTOperator(domain=space, target=cospace)]
            space_index_list += [i]
    result = ComposedOperator(fft_op_list, default_spaces=space_index_list)
    return result