nifty_random.py 13.1 KB
Newer Older
1
2
# NIFTY (Numerical Information Field Theory) has been developed at the
# Max-Planck-Institute for Astrophysics.
Ultimanet's avatar
Ultimanet committed
3
##
4
# Copyright (C) 2013 Max-Planck-Society
Ultimanet's avatar
Ultimanet committed
5
##
6
7
# Author: Marco Selig
# Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
Ultimanet's avatar
Ultimanet committed
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.
Ultimanet's avatar
Ultimanet committed
13
##
14
15
16
17
# 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.
Ultimanet's avatar
Ultimanet committed
18
##
19
20
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Ultimanet's avatar
Ultimanet committed
21
22

import numpy as np
23
from keepers import about
Ultimanet's avatar
Ultimanet committed
24
25
from nifty_mpi_data import distributed_data_object

26
27
# -----------------------------------------------------------------------------

Ultimanet's avatar
Ultimanet committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

class random(object):
    """
        ..                                          __
        ..                                        /  /
        ..       _____   ____ __   __ ___    ____/  /  ______    __ ____ ___
        ..     /   __/ /   _   / /   _   | /   _   / /   _   | /   _    _   |
        ..    /  /    /  /_/  / /  / /  / /  /_/  / /  /_/  / /  / /  / /  /
        ..   /__/     \______| /__/ /__/  \______|  \______/ /__/ /__/ /__/  class

        NIFTY (static) class for pseudo random number generators.

    """
    __init__ = None

43
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ultimanet's avatar
Ultimanet committed
44
45

    @staticmethod
46
    def parse_arguments(domain, **kwargs):
Ultimanet's avatar
Ultimanet committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        """
            Analyses the keyword arguments for supported or necessary ones.

            Parameters
            ----------
            domain : space
                Space wherein the random field values live.
            random : string, *optional*
                Specifies a certain distribution to be drawn from using a
                pseudo random number generator. Supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given
                    standard deviation or variance)
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

            dev : {scalar, list, ndarray, field}, *optional*
                Standard deviation of the normal distribution if
                ``random == "gau"`` (default: None).
            var : {scalar, list, ndarray, field}, *optional*
                Variance of the normal distribution (outranks the standard
                deviation) if ``random == "gau"`` (default: None).
            spec : {scalar, list, array, field, function}, *optional*
                Power spectrum for ``random == "syn"`` (default: 1).
            size : integer, *optional*
                Number of irreducible bands for ``random == "syn"``
                (default: None).
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each irreducible band (default: None).
            vmax : {scalar, list, ndarray, field}, *optional*
                Upper limit of the uniform distribution if ``random == "uni"``
                (default: 1).

            Returns
            -------
            arg : list
                Ordered list of arguments (to be processed in
                ``get_random_values`` of the domain).

            Other Parameters
            ----------------
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
95
96
                Flag specifying if the spectral binning is performed on
                logarithmic
Ultimanet's avatar
Ultimanet committed
97
98
99
100
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
101
102
                Number of used spectral bins; if given `log` is set to
                ``False``;
Ultimanet's avatar
Ultimanet committed
103
104
105
106
107
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
108
109
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).

            Raises
            ------
            KeyError
                If the `random` key is not supporrted.

        """
        if "random" in kwargs:
            key = kwargs.get("random")
        else:
            return None

        if key == "pm1":
            return [key]

        elif key == "gau":
            mean = kwargs.get('mean', None)
            dev = kwargs.get('dev', None)
            var = kwargs.get('var', None)
131
            return [key, mean, dev, var]
Ultimanet's avatar
Ultimanet committed
132
133
134

        elif key == "syn":
            pindex = kwargs.get('pindex', None)
135
            kindex = kwargs.get('kindex', None)
Ultimanet's avatar
Ultimanet committed
136
137
138
139
140
141
            size = kwargs.get('size', None)
            log = kwargs.get('log', False)
            nbin = kwargs.get('nbin', None)
            binbounds = kwargs.get('binbounds', None)
            spec = kwargs.get('spec', 1)
            codomain = kwargs.get('codomain', None)
142

143
144
145
146
147
            # check which domain should be taken for powerindexing
            if domain.check_codomain(codomain) and codomain.harmonic:
                harmonic_domain = codomain
            elif domain.harmonic:
                harmonic_domain = domain
Ultimanet's avatar
Ultimanet committed
148
            else:
149
                harmonic_domain = domain.get_codomain()
150

151
152
            # building kpack
            if pindex is not None and kindex is not None:
153
                pindex = distributed_data_object(pindex,
Ultimanet's avatar
Ultimanet committed
154
155
156
157
                                                 distribution_strategy='fftw')
                kpack = [pindex, kindex]
            else:
                kpack = None
158

159
160
161
162
163
            # simply put size and kindex into enforce_power
            # if one or both are None, enforce power will fix that
            spec = harmonic_domain.enforce_power(spec,
                                                 size=size,
                                                 kindex=kindex)
Ultimanet's avatar
Ultimanet committed
164

165
            return [key, spec, kpack, harmonic_domain, log, nbin, binbounds]
Ultimanet's avatar
Ultimanet committed
166
167

        elif key == "uni":
168
169
170
            vmin = domain.dtype(kwargs.get('vmin', 0))
            vmax = domain.dtype(kwargs.get('vmax', 1))
            return [key, vmin, vmax]
Ultimanet's avatar
Ultimanet committed
171
172

        else:
173
174
            raise KeyError(about._errors.cstring(
                "ERROR: unsupported random key '" + str(key) + "'."))
Ultimanet's avatar
Ultimanet committed
175

176
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ultimanet's avatar
Ultimanet committed
177
178

    @staticmethod
179
    def pm1(dtype=np.dtype('int'), shape=1):
Ultimanet's avatar
Ultimanet committed
180
181
182
183
184
185
        """
            Generates random field values according to an uniform distribution
            over {+1,-1} or {+1,+i,-1,-i}, respectively.

            Parameters
            ----------
186
187
            dtype : type, *optional*
                Data type of the field values (default: int).
Ultimanet's avatar
Ultimanet committed
188
189
190
191
192
193
194
195
196
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

        """
197
        size = np.prod(shape, axis=0, dtype=np.dtype('int'), out=None)
Ultimanet's avatar
Ultimanet committed
198

199
200
201
202
203
        if(issubclass(dtype.type, np.complexfloating)):
            x = np.array([1 + 0j, 0 + 1j, -1 + 0j, 0 - 1j],
                         dtype=dtype)[np.random.randint(4,
                                                        high=None,
                                                        size=size)]
Ultimanet's avatar
Ultimanet committed
204
        else:
205
            x = 2 * np.random.randint(2, high=None, size=size) - 1
Ultimanet's avatar
Ultimanet committed
206

207
        return x.astype(dtype).reshape(shape, order='C')
Ultimanet's avatar
Ultimanet committed
208

209
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ultimanet's avatar
Ultimanet committed
210
211

    @staticmethod
212
    def gau(dtype=np.dtype('float64'), shape=1, mean=None, dev=None, var=None):
Ultimanet's avatar
Ultimanet committed
213
214
215
216
217
        """
            Generates random field values according to a normal distribution.

            Parameters
            ----------
218
219
            dtype : type, *optional*
                Data type of the field values (default: float64).
Ultimanet's avatar
Ultimanet committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).
            mean : {scalar, ndarray}, *optional*
                Mean of the normal distribution (default: 0).
            dev : {scalar, ndarray}, *optional*
                Standard deviation of the normal distribution (default: 1).
            var : {scalar, ndarray}, *optional*
                Variance of the normal distribution (outranks the standard
                deviation) (default: None).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

            Raises
            ------
            ValueError
                If the array dimension of `mean`, `dev` or `var` mismatch with
                `shape`.

        """
242
        size = np.prod(shape, axis=0, dtype=np.dtype('int'), out=None)
Ultimanet's avatar
Ultimanet committed
243

244
245
246
247
        if(issubclass(dtype.type, np.complexfloating)):
            x = np.empty(size, dtype=dtype, order='C')
            x.real = np.random.normal(loc=0, scale=np.sqrt(0.5), size=size)
            x.imag = np.random.normal(loc=0, scale=np.sqrt(0.5), size=size)
Ultimanet's avatar
Ultimanet committed
248
        else:
249
            x = np.random.normal(loc=0, scale=1, size=size)
Ultimanet's avatar
Ultimanet committed
250
251

        if(var is not None):
252
            if(np.size(var) == 1):
Ultimanet's avatar
Ultimanet committed
253
                x *= np.sqrt(np.abs(var))
254
            elif(np.size(var) == size):
Ultimanet's avatar
Ultimanet committed
255
256
                x *= np.sqrt(np.absolute(var).flatten(order='C'))
            else:
257
258
259
                raise ValueError(about._errors.cstring(
                    "ERROR: dimension mismatch ( " + str(np.size(var)) +
                    " <> " + str(size) + " )."))
Ultimanet's avatar
Ultimanet committed
260
        elif(dev is not None):
261
            if(np.size(dev) == 1):
Ultimanet's avatar
Ultimanet committed
262
                x *= np.abs(dev)
263
            elif(np.size(dev) == size):
Ultimanet's avatar
Ultimanet committed
264
265
                x *= np.absolute(dev).flatten(order='C')
            else:
266
267
268
                raise ValueError(about._errors.cstring(
                    "ERROR: dimension mismatch ( " + str(np.size(dev)) +
                    " <> " + str(size) + " )."))
Ultimanet's avatar
Ultimanet committed
269
        if(mean is not None):
270
            if(np.size(mean) == 1):
Ultimanet's avatar
Ultimanet committed
271
                x += mean
272
            elif(np.size(mean) == size):
Ultimanet's avatar
Ultimanet committed
273
274
                x += np.array(mean).flatten(order='C')
            else:
275
276
277
                raise ValueError(about._errors.cstring(
                    "ERROR: dimension mismatch ( " + str(np.size(mean)) +
                    " <> " + str(size) + " )."))
Ultimanet's avatar
Ultimanet committed
278

279
        return x.astype(dtype).reshape(shape, order='C')
Ultimanet's avatar
Ultimanet committed
280

281
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ultimanet's avatar
Ultimanet committed
282
283

    @staticmethod
284
    def uni(dtype=np.dtype('float64'), shape=1, vmin=0, vmax=1):
Ultimanet's avatar
Ultimanet committed
285
286
287
288
289
290
        """
            Generates random field values according to an uniform distribution
            over [vmin,vmax[.

            Parameters
            ----------
291
292
            dtype : type, *optional*
                Data type of the field values (default: float64).
Ultimanet's avatar
Ultimanet committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).

            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution (default: 0).
            vmax : {scalar, list, ndarray, field}, *optional*
                Upper limit of the uniform distribution (default: 1).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

        """
307
308
        size = np.prod(shape, axis=0, dtype=np.dtype('int'), out=None)
        if(np.size(vmin) > 1):
Ultimanet's avatar
Ultimanet committed
309
            vmin = np.array(vmin).flatten(order='C')
310
        if(np.size(vmax) > 1):
Ultimanet's avatar
Ultimanet committed
311
312
            vmax = np.array(vmax).flatten(order='C')

313
314
315
316
317
318
319
320
        if(dtype in [np.dtype('complex64'), np.dtype('complex128')]):
            x = np.empty(size, dtype=dtype, order='C')
            x.real = (vmax - vmin) * np.random.random(size=size) + vmin
            x.imag = (vmax - vmin) * np.random.random(size=size) + vmin
        elif(dtype in [np.dtype('int8'), np.dtype('int16'), np.dtype('int32'),
                       np.dtype('int64')]):
            x = np.random.randint(
                min(vmin, vmax), high=max(vmin, vmax), size=size)
Ultimanet's avatar
Ultimanet committed
321
        else:
322
            x = (vmax - vmin) * np.random.random(size=size) + vmin
Ultimanet's avatar
Ultimanet committed
323

324
        return x.astype(dtype).reshape(shape, order='C')
Ultimanet's avatar
Ultimanet committed
325

326
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ultimanet's avatar
Ultimanet committed
327
328
329
330

    def __repr__(self):
        return "<nifty_core.random>"

331
# -----------------------------------------------------------------------------