nifty_fft.py 17.7 KB
Newer Older
1
2
3
# -*- coding: utf-8 -*-

import numpy as np
4
5
from d2o import distributed_data_object
from nifty.config import dependency_injector as gdi
6
import os
Ultima's avatar
Ultima committed
7
8
9
10
pyfftw = gdi.get('pyfftw')
gfft = gdi.get('gfft')
gfft_dummy = gdi.get('gfft_dummy')

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# Try to import pyfftw. If this fails fall back to gfft.
# If this fails fall back to local gfft_rg

# try:
#    import pyfftw
#    fft_machine='pyfftw'
# except(ImportError):
#    try:
#        import gfft
#        fft_machine='gfft'
#        about.infos.cprint('INFO: Using gfft')
#    except(ImportError):
#        import gfft_rg as gfft
#        fft_machine='gfft_fallback'
#        about.infos.cprint('INFO: Using builtin "plain" gfft version 0.1.0')


Ultima's avatar
Ultima committed
29
def fft_factory(fft_module_name):
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    """
        A factory for fast-fourier-transformation objects.

        Parameters
        ----------
        None

        Returns
        -----
        fft: Returns a fft_object depending on the available packages.
        Hierarchy: pyfftw -> gfft -> built in gfft.

    """
    if fft_module_name == 'pyfftw':
        return fft_fftw()
    elif fft_module_name == 'gfft' or 'gfft_dummy':
Ultima's avatar
Ultima committed
46
47
48
49
        return fft_gfft(fft_module_name)
    else:
        raise ValueError('Given fft_module_name not known: ' +
                         str(fft_module_name))
50
51
52
53
54
55
56
57
58
59


class fft(object):
    """
        A generic fft object without any implementation.

        Parameters
        ----------
        None
    """
Ultima's avatar
Ultima committed
60
61
    def __init__(self):
        pass
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    def transform(self, val, domain, codomain, **kwargs):
        """
            A generic ff-transform function.

            Parameters
            ----------
            field_val : distributed_data_object
                The value-array of the field which is supposed to
                be transformed.

            domain : nifty.rg.nifty_rg.rg_space
                The domain of the space which should be transformed.

            codomain : nifty.rg.nifty_rg.rg_space
                The taget into which the field should be transformed.
        """
        return None


Ultima's avatar
Ultima committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class fft_fftw(fft):
    """
        The pyfftw pendant of a fft object.

        Parameters
        ----------
        None

    """

    def __init__(self):
        if 'pyfftw' not in gdi:
            raise ImportError("The module pyfftw is needed but not available.")

96
        self.name = 'pyfftw'
Ultima's avatar
Ultima committed
97
98
99
100
101
102
103
104
105
106
        # The plan_dict stores the plan_and_info objects which correspond
        # to a certain set of (field_val, domain, codomain) sets.
        self.plan_dict = {}

        # initialize the dictionary which stores the values from
        # get_centering_mask
        self.centering_mask_dict = {}

    def get_centering_mask(self, to_center_input, dimensions_input,
                           offset_input=0):
107
        """
Ultima's avatar
Ultima committed
108
109
            Computes the mask, used to (de-)zerocenter domain and target
            fields.
110
111
112

            Parameters
            ----------
Ultima's avatar
Ultima committed
113
114
115
            to_center_input : tuple, list, numpy.ndarray
                A tuple of booleans which dimensions should be
                zero-centered.
116

Ultima's avatar
Ultima committed
117
118
            dimensions_input : tuple, list, numpy.ndarray
                A tuple containing the masks desired shape.
119

Ultima's avatar
Ultima committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            offset_input : int, boolean
                Specifies whether the zero-th dimension starts with an odd
                or and even index, i.e. if it is shifted.

            Returns
            -------
            result : np.ndarray
                A 1/-1-alternating mask.
        """
        # cast input
        to_center = np.array(to_center_input)
        dimensions = np.array(dimensions_input)

        # if none of the dimensions are zero centered, return a 1
        if np.all(to_center == 0):
            return 1

        if np.all(dimensions == np.array(1)) or \
                np.all(dimensions == np.array([1])):
            return dimensions
        # The dimensions of size 1 must be sorted out for computing the
        # centering_mask. The depth of the array will be restored in the
        # end.
        size_one_dimensions = []
        temp_dimensions = []
        temp_to_center = []
        for i in range(len(dimensions)):
            if dimensions[i] == 1:
                size_one_dimensions += [True]
149
            else:
Ultima's avatar
Ultima committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
                size_one_dimensions += [False]
                temp_dimensions += [dimensions[i]]
                temp_to_center += [to_center[i]]
        dimensions = np.array(temp_dimensions)
        to_center = np.array(temp_to_center)
        # cast the offset_input into the shape of to_center
        offset = np.zeros(to_center.shape, dtype=int)
        offset[0] = int(offset_input)
        # check for dimension match
        if to_center.size != dimensions.size:
            raise TypeError(
                'The length of the supplied lists does not match.')

        # build up the value memory
        # compute an identifier for the parameter set
        temp_id = tuple(
            (tuple(to_center), tuple(dimensions), tuple(offset)))
        if temp_id not in self.centering_mask_dict:
            # use np.tile in order to stack the core alternation scheme
            # until the desired format is constructed.
            core = np.fromfunction(
                lambda *args: (-1) **
                (np.tensordot(to_center,
                              args +
                              offset.reshape(offset.shape +
                                             (1,) *
                                             (np.array(args).ndim - 1)),
                              1)),
                (2,) * to_center.size)
            # Cast the core to the smallest integers we can get
            core = core.astype(np.int8)

            centering_mask = np.tile(core, dimensions // 2)
            # for the dimensions of odd size corresponding slices must be
            # added
            for i in range(centering_mask.ndim):
                # check if the size of the certain dimension is odd or even
                if (dimensions % 2)[i] == 0:
                    continue
                # prepare the slice object
                temp_slice = (slice(None),) * i + (slice(-2, -1, 1),) +\
                             (slice(None),) * (centering_mask.ndim - 1 - i)
                # append the slice to the centering_mask
                centering_mask = np.append(centering_mask,
                                           centering_mask[temp_slice],
                                           axis=i)
            # Add depth to the centering_mask where the length of a
            # dimension was one
            temp_slice = ()
            for i in range(len(size_one_dimensions)):
                if size_one_dimensions[i] == True:
                    temp_slice += (None,)
                else:
                    temp_slice += (slice(None),)
            centering_mask = centering_mask[temp_slice]
            self.centering_mask_dict[temp_id] = centering_mask
        return self.centering_mask_dict[temp_id]

    def _get_plan_and_info(self, domain, codomain, **kwargs):
        # generate a id-tuple which identifies the domain-codomain setting
Ultima's avatar
Ultima committed
210
        temp_id = domain.__hash__() ^ (101*codomain.__hash__())
Ultima's avatar
Ultima committed
211
212
213
214
215
216
217
218
219
220
221
222
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
        # generate the plan_and_info object if not already there
        if temp_id not in self.plan_dict:
            self.plan_dict[temp_id] = _fftw_plan_and_info(domain, codomain,
                                                          self, **kwargs)
        return self.plan_dict[temp_id]

    def transform(self, val, domain, codomain, **kwargs):
        """
            The pyfftw transform function.

            Parameters
            ----------
            val : distributed_data_object or numpy.ndarray
                The value-array of the field which is supposed to
                be transformed.

            domain : nifty.rg.nifty_rg.rg_space
                The domain of the space which should be transformed.

            codomain : nifty.rg.nifty_rg.rg_space
                The taget into which the field should be transformed.

            **kwargs : *optional*
                Further kwargs are passed to the create_mpi_plan routine.

            Returns
            -------
            result : np.ndarray
                Fourier-transformed pendant of the input field.
        """
        current_plan_and_info = self._get_plan_and_info(domain, codomain,
                                                        **kwargs)
        # Prepare the environment variables
        local_size = current_plan_and_info.fftw_local_size
        local_start = local_size[2]
        local_end = local_start + local_size[1]

        # Prepare the input data
        # Case 1: val is a distributed_data_object
        if isinstance(val, distributed_data_object):
251
252
            return_val = val.copy_empty(
                        global_shape=current_plan_and_info.global_output_shape,
Ultima's avatar
Ultima committed
253
                        dtype=codomain.dtype)
Ultima's avatar
Ultima committed
254
255
256
257
            # If the distribution strategy of the d2o is fftw, extract
            # the data directly
            if val.distribution_strategy == 'fftw':
                local_val = val.get_local_data()
258
            else:
259
260
                local_val = val.get_data(slice(local_start, local_end),
                                         local_keys=True).get_local_data()
Ultima's avatar
Ultima committed
261
262
263
264
265
266
267
268
269
270
271
272
273
        # Case 2: val is a numpy array carrying the full data
        else:
            local_val = val[slice(local_start, local_end)]

        local_val *= current_plan_and_info.get_codomain_centering_mask()

        # Define a abbreviation for the fftw plan
        p = current_plan_and_info.get_plan()
        # load the field into the plan
        if p.has_input:
            p.input_array[:] = local_val
        # execute the plan
        p()
274

275
276
277
        if p.has_output:
            result = p.output_array * current_plan_and_info.\
                get_domain_centering_mask()
Ultima's avatar
Ultima committed
278
        else:
279
280
            result = local_val
            assert(result.shape[0] == 0)
Ultima's avatar
Ultima committed
281
282
283
284
285

        # build the return object according to the input val
        # TODO: Check if comm is the same, too!
        try:
            if return_val.distribution_strategy == 'fftw':
286
                return_val.set_local_data(data=result)
Ultima's avatar
Ultima committed
287
288
            else:
                return_val.set_data(data=result,
289
290
                                    to_key=slice(local_start, local_end),
                                    local_keys=True)
Ultima's avatar
Ultima committed
291
292
293
294
295
296
297
298
299
300

            # If the values living in domain are purely real, the
            # result of the fft is hermitian
            if domain.paradict['complexity'] == 0:
                return_val.hermitian = True

        # In case the input val was not a distributed data obect, the try
        # will produce a NameError
        except(NameError):
            return_val = distributed_data_object(
301
                global_shape=current_plan_and_info.global_output_shape,
Ultima's avatar
Ultima committed
302
                dtype=codomain.dtype,
Ultima's avatar
Ultima committed
303
304
305
306
                distribution_strategy='fftw')
            return_val.set_local_data(data=result)
            return_val = return_val.get_full_data()

307
308
309
310
311
        # The +-1 magic has a caveat: if a dimension was zero-centered
        # in the harmonic as well as in position space, the result gets
        # a global minus. The following multiplitcation compensates that.
        return_val *= current_plan_and_info.overall_sign

Ultima's avatar
Ultima committed
312
        return return_val
313

Ultima's avatar
Ultima committed
314

Ultima's avatar
Ultima committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# The instances of plan_and_info store the fftw plan and all
# other information needed in order to perform a mpi-fftw transformation
class _fftw_plan_and_info(object):

    def __init__(self, domain, codomain, fft_fftw_context, **kwargs):
        if pyfftw is None:
            raise ImportError("The module pyfftw is needed but not available.")
        self.compute_plan_and_info(domain, codomain, fft_fftw_context,
                                   **kwargs)

    def set_plan(self, x):
        self.plan = x

    def get_plan(self):
        return self.plan

    def set_domain_centering_mask(self, x):
        self.domain_centering_mask = x

    def get_domain_centering_mask(self):
        return self.domain_centering_mask

    def set_codomain_centering_mask(self, x):
        self.codomain_centering_mask = x

    def get_codomain_centering_mask(self):
        return self.codomain_centering_mask

    def compute_plan_and_info(self, domain, codomain, fft_fftw_context,
                              **kwargs):

        self.input_dtype = 'complex128'
        self.output_dtype = 'complex128'

        self.global_input_shape = domain.get_shape()
        self.global_output_shape = codomain.get_shape()
        self.fftw_local_size = pyfftw.local_size(self.global_input_shape)

        self.in_zero_centered_dimensions = domain.paradict['zerocenter']
        self.out_zero_centered_dimensions = codomain.paradict['zerocenter']

        self.overall_sign = (-1)**np.sum(
                                np.array(self.in_zero_centered_dimensions) *
Ultima's avatar
Ultima committed
358
359
360
                                np.array(self.out_zero_centered_dimensions) *
                                (np.array(self.global_input_shape)//2 % 2)
                                )
Ultima's avatar
Ultima committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383

        self.local_node_dimensions = np.append((self.fftw_local_size[1],),
                                               self.global_input_shape[1:])
        self.offsetQ = self.fftw_local_size[2] % 2

        if codomain.harmonic:
            self.direction = 'FFTW_FORWARD'
        else:
            self.direction = 'FFTW_BACKWARD'

        # compute the centering masks
        self.set_domain_centering_mask(
            fft_fftw_context.get_centering_mask(
                self.in_zero_centered_dimensions,
                self.local_node_dimensions,
                self.offsetQ))

        self.set_codomain_centering_mask(
            fft_fftw_context.get_centering_mask(
                self.out_zero_centered_dimensions,
                self.local_node_dimensions,
                self.offsetQ))

384
385
386
387
388
        try:
            threads = int(os.environ['NIFTY_FFTW_THREADS'])
        except(KeyError):
            threads = 1

Ultima's avatar
Ultima committed
389
390
391
392
393
394
395
        self.set_plan(
            pyfftw.create_mpi_plan(
                input_shape=self.global_input_shape,
                input_dtype=self.input_dtype,
                output_dtype=self.output_dtype,
                direction=self.direction,
                flags=["FFTW_ESTIMATE"],
396
                threads=threads,
Ultima's avatar
Ultima committed
397
398
399
                **kwargs)
        )

400

Ultima's avatar
Ultima committed
401
402
403
404
405
406
407
408
409
410
class fft_gfft(fft):
    """
        The gfft pendant of a fft object.

        Parameters
        ----------
        None

    """
    def __init__(self, fft_module_name):
411
        self.name = fft_module_name
Ultima's avatar
Ultima committed
412
413
414
415
416
417
        self.fft_machine = gdi.get(fft_module_name)
        if self.fft_machine is None:
            raise ImportError(
                "The gfft(_dummy)-module is needed but not available.")

    def transform(self, val, domain, codomain, **kwargs):
418
        """
Ultima's avatar
Ultima committed
419
            The gfft transform function.
420
421
422

            Parameters
            ----------
Ultima's avatar
Ultima committed
423
424
425
            val : numpy.ndarray or distributed_data_object
                The value-array of the field which is supposed to
                be transformed.
426

Ultima's avatar
Ultima committed
427
428
            domain : nifty.rg.nifty_rg.rg_space
                The domain of the space which should be transformed.
429

Ultima's avatar
Ultima committed
430
431
            codomain : nifty.rg.nifty_rg.rg_space
                The taget into which the field should be transformed.
432

Ultima's avatar
Ultima committed
433
434
435
436
437
438
439
440
            **kwargs : *optional*
                Further kwargs are not processed.

            Returns
            -------
            result : np.ndarray
                Fourier-transformed pendant of the input field.
        """
441
442
        naxes = len(domain.get_shape())
        if codomain.harmonic:
Ultima's avatar
Ultima committed
443
444
445
446
447
448
449
450
            ftmachine = "fft"
        else:
            ftmachine = "ifft"
        # if the input is a distributed_data_object, extract the data
        if isinstance(val, distributed_data_object):
            d2oQ = True
            temp = val.get_full_data()
        else:
451
            d2oQ = False
Ultima's avatar
Ultima committed
452
453
            temp = val
        # transform and return
454
        if(domain.dtype == np.float64):
Ultima's avatar
Ultima committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
            temp = self.fft_machine.gfft(
                                     temp.astype(np.complex128),
                                     in_ax=[],
                                     out_ax=[],
                                     ftmachine=ftmachine,
                                     in_zero_center=domain.para[-naxes:].
                                     astype(np.bool).tolist(),
                                     out_zero_center=codomain.para[-naxes:].
                                     astype(np.bool).tolist(),
                                     enforce_hermitian_symmetry=bool(
                                         codomain.para[naxes] == 1),
                                     W=-1,
                                     alpha=-1,
                                     verbose=False)
        else:
            temp = self.fft_machine.gfft(
                                     temp,
                                     in_ax=[],
                                     out_ax=[],
                                     ftmachine=ftmachine,
                                     in_zero_center=domain.para[-naxes:].
                                     astype(np.bool).tolist(),
                                     out_zero_center=codomain.para[-naxes:].
                                     astype(np.bool).tolist(),
                                     enforce_hermitian_symmetry=bool(
                                         codomain.para[naxes] == 1),
                                     W=-1,
                                     alpha=-1,
                                     verbose=False)
        if d2oQ:
            new_val = val.copy_empty(dtype=np.complex128)
            new_val.set_full_data(temp)
            # If the values living in domain are purely real, the
            # result of the fft is hermitian
            if domain.paradict['complexity'] == 0:
                new_val.hermitian = True
            val = new_val
        else:
            val = temp

        return val