rg_space.py 13.3 KB
Newer Older
1
2
3
4
5
# NIFTy
# Copyright (C) 2017  Theo Steininger
#
# Author: Theo Steininger
#
6
7
8
9
# 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.
10
#
11
12
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
14
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
Marco Selig's avatar
Marco Selig committed
18
19
20
21
22
23
24
25
26
27

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  rg
    ..                               /______/

Marco Selig's avatar
Marco Selig committed
28
    NIFTY submodule for regular Cartesian grids.
Marco Selig's avatar
Marco Selig committed
29
30
31

"""
from __future__ import division
Ultimanet's avatar
Ultimanet committed
32

Marco Selig's avatar
Marco Selig committed
33
import numpy as np
Ultimanet's avatar
Ultimanet committed
34

35
36
from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES
37

38
from nifty.spaces.space import Space
csongor's avatar
csongor committed
39

Marco Selig's avatar
Marco Selig committed
40

Theo Steininger's avatar
Theo Steininger committed
41
class RGSpace(Space):
Marco Selig's avatar
Marco Selig committed
42
43
44
45
46
47
48
49
50
51
52
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  space class
        ..          /______/

        NIFTY subclass for spaces of regular Cartesian grids.

        Attributes
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
53
        harmonic : bool
Marco Selig's avatar
Marco Selig committed
54
            Whether or not the grid represents a Fourier basis.
55
        zerocenter : {bool, numpy.ndarray}
Martin Reinecke's avatar
Martin Reinecke committed
56
            Whether the Fourier zero-mode is located in the center of the grid
57
58
59
            (or the center of each axis speparately) or not.
            MR FIXME: this also does something if the space is not harmonic!
        distances : {float, numpy.ndarray}
Martin Reinecke's avatar
Martin Reinecke committed
60
            Distance between two grid points along each axis (default: None).
Marco Selig's avatar
Marco Selig committed
61
62
    """

63
64
    # ---Overwritten properties and methods---

65
    def __init__(self, shape, zerocenter=False, distances=None,
Martin Reinecke's avatar
Martin Reinecke committed
66
                 harmonic=False):
Marco Selig's avatar
Marco Selig committed
67
        """
68
            Sets the attributes for an RGSpace class instance.
Marco Selig's avatar
Marco Selig committed
69
70
71

            Parameters
            ----------
Martin Reinecke's avatar
Martin Reinecke committed
72
            shape : {int, numpy.ndarray}
73
                Number of grid points or numbers of gridpoints along each axis.
Marco Selig's avatar
Marco Selig committed
74
75
76
            zerocenter : {bool, numpy.ndarray}, *optional*
                Whether the Fourier zero-mode is located in the center of the
                grid (or the center of each axis speparately) or not
77
                MR FIXME: this also does something if the space is not harmonic!
Ultimanet's avatar
Ultimanet committed
78
                (default: False).
Martin Reinecke's avatar
Martin Reinecke committed
79
            distances : {float, numpy.ndarray}, *optional*
Marco Selig's avatar
Marco Selig committed
80
81
                Distance between two grid points along each axis
                (default: None).
82
83
84
85
                If distances==None:
                    if harmonic==True, all distances will be set to 1
                    if harmonic==False, the distance along each axis will be
                      set to the inverse of the number of points along that axis
Martin Reinecke's avatar
Martin Reinecke committed
86
            harmonic : bool, *optional*
Marco Selig's avatar
Marco Selig committed
87
88
89
90
91
92
93
                Whether the space represents a Fourier or a position grid
                (default: False).

            Returns
            -------
            None
        """
94
95
        self._harmonic = bool(harmonic)

Martin Reinecke's avatar
Martin Reinecke committed
96
        super(RGSpace, self).__init__()
97

98
99
100
        self._shape = self._parse_shape(shape)
        self._distances = self._parse_distances(distances)
        self._zerocenter = self._parse_zerocenter(zerocenter)
Marco Selig's avatar
Marco Selig committed
101

102
103
    def hermitian_decomposition(self, x, axes=None,
                                preserve_gaussian_variance=False):
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        """Separates the hermitian and antihermitian part of a field.
        
        This is a function which is called by the field in order to separate itself for 
        each of its domains. 
        
        Parameters
        ----------
        x: Field
            Field to be decomposed.
        axes: {int, tuple}, *optional*
            Specifies which indices of the field belongs to this RGSpace. If None, it 
            takes the first dimensions of the field.
            (default: None)
        preserve_gaussian_variance: bool, *optional*
            
            (default: False)
        
        """
122
123
124
125
126
127
128
129
130
        # compute the hermitian part
        flipped_x = self._hermitianize_inverter(x, axes=axes)
        flipped_x = flipped_x.conjugate()
        # average x and flipped_x.
        hermitian_part = x + flipped_x
        hermitian_part /= 2.

        # use subtraction since it is faster than flipping another time
        anti_hermitian_part = (x-hermitian_part)/1j
131
132
133
134
135
136
137

        if preserve_gaussian_variance:
            hermitian_part, anti_hermitian_part = \
                self._hermitianize_correct_variance(hermitian_part,
                                                    anti_hermitian_part,
                                                    axes=axes)

138
139
        return (hermitian_part, anti_hermitian_part)

140
141
142
143
144
145
    def _hermitianize_correct_variance(self, hermitian_part,
                                       anti_hermitian_part, axes):
        # Correct the variance by multiplying sqrt(2)
        hermitian_part = hermitian_part * np.sqrt(2)
        anti_hermitian_part = anti_hermitian_part * np.sqrt(2)

Martin Reinecke's avatar
Martin Reinecke committed
146
        # The fixed points of the point inversion must not be averaged.
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
        # Hence one must divide out the sqrt(2) again
        # -> Get the middle index of the array
        mid_index = np.array(hermitian_part.shape, dtype=np.int) // 2
        dimensions = mid_index.size
        # Use ndindex to iterate over all combinations of zeros and the
        # mid_index in order to correct all fixed points.
        if axes is None:
            axes = xrange(dimensions)

        ndlist = [2 if i in axes else 1 for i in xrange(dimensions)]
        ndlist = tuple(ndlist)
        for i in np.ndindex(ndlist):
            temp_index = tuple(i * mid_index)
            hermitian_part[temp_index] /= np.sqrt(2)
            anti_hermitian_part[temp_index] /= np.sqrt(2)
        return hermitian_part, anti_hermitian_part

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    def _hermitianize_inverter(self, x, axes):
        # calculate the number of dimensions the input array has
        dimensions = len(x.shape)
        # prepare the slicing object which will be used for mirroring
        slice_primitive = [slice(None), ] * dimensions
        # copy the input data
        y = x.copy()

        if axes is None:
            axes = xrange(dimensions)

        # flip in the desired directions
        for i in axes:
            slice_picker = slice_primitive[:]
            slice_picker[i] = slice(1, None, None)
            slice_picker = tuple(slice_picker)

            slice_inverter = slice_primitive[:]
            slice_inverter[i] = slice(None, 0, -1)
            slice_inverter = tuple(slice_inverter)

            try:
                y.set_data(to_key=slice_picker, data=y,
                           from_key=slice_inverter)
            except(AttributeError):
                y[slice_picker] = y[slice_inverter]
        return y

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    # ---Mandatory properties and methods---

    @property
    def harmonic(self):
        return self._harmonic

    @property
    def shape(self):
        return self._shape

    @property
    def dim(self):
        return reduce(lambda x, y: x*y, self.shape)

    @property
    def total_volume(self):
        return self.dim * reduce(lambda x, y: x*y, self.distances)

    def copy(self):
211
212
213
214
215
216
        """Returns a copied version of this RGSpace.
			
        Returns
        -------
		RGSpace : A copy of this object.
        """
217
218
219
        return self.__class__(shape=self.shape,
                              zerocenter=self.zerocenter,
                              distances=self.distances,
Martin Reinecke's avatar
Martin Reinecke committed
220
                              harmonic=self.harmonic)
221
222

    def weight(self, x, power=1, axes=None, inplace=False):
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        """ Weights a field living on this space with a specified amount of volume-weights.

		Weights hereby refer to integration weights, as they appear in discretized integrals.
		Per default, this function mutliplies each bin of the field x by its volume, which lets
		it behave like a density (top form). However, different powers of the volume can be applied
		with the power parameter. If only certain axes are specified via the axes parameter,
		the weights are only applied with respect to these dimensions, yielding an object that
		behaves like a lower degree form.
        Parameters
        ----------
        x : Field
            A field with this space as domain to be weighted.
        power : int, *optional*
            The power to which the volume-weight is raised.
            (default: 1).
        axes : {int, tuple}, *optional*
            Specifies for which axes the weights should be applied.
            (default: None).
            If axes==None:
                weighting is applied with respect to all axes
        inplace : bool, *optional*
            If this is True, the weighting is done on the values of x,
			if it is False, x is not modified and this method returns a 
			weighted copy of x
            (default: False).

        Returns
        -------
		Field
			A weighted version of x, with volume-weights raised to power.
            
        """
255
256
257
258
259
260
261
262
        weight = reduce(lambda x, y: x*y, self.distances)**power
        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x*weight
        return result_x

263
    def get_distance_array(self, distribution_strategy):
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
        """Returns the distance of the bins to zero.
        
        Calculates an n-dimensional array with its entries being the
        lengths of the k-vectors from the zero point of the grid.
        MR FIXME: Since this is about k-vectors, it might make sense to
        throw NotImplementedError if harmonic==False.

        Parameters
        ----------
        None : All information is taken from the parent object.

        Returns
        -------
        nkdict : distributed_data_object
        
        Raises
        ------
        ValueError
            The distribution_strategy is neither slicing nor not.
theos's avatar
theos committed
283
284
285
286
        """
        shape = self.shape
        # prepare the distributed_data_object
        nkdict = distributed_data_object(
Martin Reinecke's avatar
Martin Reinecke committed
287
                        global_shape=shape, dtype=np.float64,
theos's avatar
theos committed
288
289
290
291
292
293
294
295
296
                        distribution_strategy=distribution_strategy)

        if distribution_strategy in DISTRIBUTION_STRATEGIES['slicing']:
            # get the node's individual slice of the first dimension
            slice_of_first_dimension = slice(
                                    *nkdict.distributor.local_slice[0:2])
        elif distribution_strategy in DISTRIBUTION_STRATEGIES['not']:
            slice_of_first_dimension = slice(0, shape[0])
        else:
297
298
            raise ValueError(
                "Unsupported distribution strategy")
theos's avatar
theos committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
        dists = self._distance_array_helper(slice_of_first_dimension)
        nkdict.set_local_data(dists)

        return nkdict

    def _distance_array_helper(self, slice_of_first_dimension):
        dk = self.distances
        shape = self.shape

        inds = []
        for a in shape:
            inds += [slice(0, a)]

        cords = np.ogrid[inds]

Theo Steininger's avatar
Theo Steininger committed
314
        dists = ((cords[0] - shape[0]//2)*dk[0])**2
theos's avatar
theos committed
315
        # apply zerocenterQ shift
316
317
        if not self.zerocenter[0]:
            dists = np.fft.ifftshift(dists)
theos's avatar
theos committed
318
319
320
321
        # only save the individual slice
        dists = dists[slice_of_first_dimension]
        for ii in range(1, len(shape)):
            temp = ((cords[ii] - shape[ii] // 2) * dk[ii])**2
322
            if not self.zerocenter[ii]:
Martin Reinecke's avatar
Martin Reinecke committed
323
                temp = np.fft.ifftshift(temp)
theos's avatar
theos committed
324
325
326
327
            dists = dists + temp
        dists = np.sqrt(dists)
        return dists

328
329
    def get_fft_smoothing_kernel_function(self, sigma): 
    
theos's avatar
theos committed
330
331
332
        if sigma is None:
            sigma = np.sqrt(2) * np.max(self.distances)

333
        return lambda x: np.exp(-0.5 * np.pi**2 * x**2 * sigma**2)
theos's avatar
theos committed
334

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    # ---Added properties and methods---

    @property
    def distances(self):
        return self._distances

    @property
    def zerocenter(self):
        return self._zerocenter

    def _parse_shape(self, shape):
        if np.isscalar(shape):
            shape = (shape,)
        temp = np.empty(len(shape), dtype=np.int)
        temp[:] = shape
        return tuple(temp)

    def _parse_distances(self, distances):
        if distances is None:
            if self.harmonic:
Martin Reinecke's avatar
Martin Reinecke committed
355
                temp = np.ones_like(self.shape, dtype=np.float64)
356
            else:
Martin Reinecke's avatar
Martin Reinecke committed
357
                temp = 1 / np.array(self.shape, dtype=np.float64)
358
        else:
Martin Reinecke's avatar
Martin Reinecke committed
359
            temp = np.empty(len(self.shape), dtype=np.float64)
360
361
362
363
364
365
366
            temp[:] = distances
        return tuple(temp)

    def _parse_zerocenter(self, zerocenter):
        temp = np.empty(len(self.shape), dtype=bool)
        temp[:] = zerocenter
        return tuple(temp)
367
368
369
370

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Jait Dixit's avatar
Jait Dixit committed
371
372
373
        hdf5_group['shape'] = self.shape
        hdf5_group['zerocenter'] = self.zerocenter
        hdf5_group['distances'] = self.distances
374
        hdf5_group['harmonic'] = self.harmonic
Jait Dixit's avatar
Jait Dixit committed
375

376
377
378
        return None

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
379
    def _from_hdf5(cls, hdf5_group, repository):
380
        result = cls(
Jait Dixit's avatar
Jait Dixit committed
381
382
383
            shape=hdf5_group['shape'][:],
            zerocenter=hdf5_group['zerocenter'][:],
            distances=hdf5_group['distances'][:],
384
            harmonic=hdf5_group['harmonic'][()],
Jait Dixit's avatar
Jait Dixit committed
385
            )
386
        return result