nifty_mpi_data.py 72.8 KB
Newer Older
ultimanet's avatar
ultimanet committed
1
# -*- coding: utf-8 -*-
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2015 Max-Planck-Society
##
## Author: Theo Steininger
## Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
##
## 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/>.


ultimanet's avatar
ultimanet committed
24
25
26

##initialize the 'found-packages'-dictionary 

27
28

found = {}
ultimanet's avatar
ultimanet committed
29
import numpy as np
Ultimanet's avatar
Ultimanet committed
30
from nifty_about import about
ultimanet's avatar
ultimanet committed
31
32

try:
33
    from mpi4py import MPI
ultimanet's avatar
ultimanet committed
34
35
    found[MPI] = True
except(ImportError): 
36
    import mpi_dummy as MPI
ultimanet's avatar
ultimanet committed
37
38
39
40
41
42
43
44
45
    found[MPI] = False

try:
    import pyfftw
    found['pyfftw'] = True
except(ImportError):       
    found['pyfftw'] = False

try:
46
    import h5py
ultimanet's avatar
ultimanet committed
47
48
49
50
51
52
53
    found['h5py'] = True
    found['h5py_parallel'] = h5py.get_config().mpi
except(ImportError):
    found['h5py'] = False
    found['h5py_parallel'] = False


54

ultimanet's avatar
ultimanet committed
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
95
96
97
98
class distributed_data_object(object):
    """

        NIFTY class for distributed data

        Parameters
        ----------
        global_data : {tuple, list, numpy.ndarray} *at least 1-dimensional*
            Initial data which will be casted to a numpy.ndarray and then 
            stored according to the distribution strategy. The global_data's
            shape overwrites global_shape.
        global_shape : tuple of ints, *optional*
            If no global_data is supplied, global_shape can be used to
            initialize an empty distributed_data_object
        dtype : type, *optional*
            If an explicit dtype is supplied, the given global_data will be 
            casted to it.            
        distribution_strategy : {'fftw' (default), 'not'}, *optional*
            Specifies the way, how global_data will be distributed to the 
            individual nodes. 
            'fftw' follows the distribution strategy of pyfftw.
            'not' does not distribute the data at all. 
            

        Attributes
        ----------
        data : numpy.ndarray
            The numpy.ndarray in which the individual node's data is stored.
        dtype : type
            Data type of the data object.
        distribution_strategy : string
            Name of the used distribution_strategy
        distributor : distributor
            The distributor object which takes care of all distribution and 
            consolidation of the data. 
        shape : tuple of int
            The global shape of the data
            
        Raises
        ------
        TypeError : 
            If the supplied distribution strategy is not known. 
        
    """
Ultimanet's avatar
Ultimanet committed
99
100
101
    def __init__(self,  global_data=None, global_shape=None, dtype=None, 
                 distribution_strategy='fftw', hermitian=False, 
                 *args, **kwargs):
ultimanet's avatar
ultimanet committed
102
        if global_data != None:
Ultimanet's avatar
Ultimanet committed
103
            if np.isscalar(global_data):
104
105
106
107
                global_data_input = None
                dtype = np.array(global_data).dtype.type
            else:
                global_data_input = np.array(global_data, copy=True, order='C')
ultimanet's avatar
ultimanet committed
108
109
        else:
            global_data_input = None
110

Ultimanet's avatar
Ultimanet committed
111
112
113
114
115
116
        self.hermitian = False

        self.distributor = self._get_distributor(distribution_strategy)(
                            global_data=global_data_input, 
                            global_shape=global_shape, 
                            dtype=dtype, **kwargs)
Ultimanet's avatar
Ultimanet committed
117

Ultimanet's avatar
Ultimanet committed
118
119
        self.set_full_data(data=global_data_input, hermitian=hermitian, 
                           **kwargs)
ultimanet's avatar
ultimanet committed
120
        
121
            
ultimanet's avatar
ultimanet committed
122
123
124
125
        self.distribution_strategy = distribution_strategy
        self.dtype = self.distributor.dtype
        self.shape = self.distributor.global_shape
        
126
127
        self.init_args = args 
        self.init_kwargs = kwargs
128
129
        
        ## If the input data was a scalar, set the whole array to this value
Ultimanet's avatar
Ultimanet committed
130
        if global_data != None and np.isscalar(global_data):
Ultimanet's avatar
Ultimanet committed
131
132
133
            temp = np.empty(self.distributor.local_shape)
            temp.fill(global_data)
            self.set_local_data(temp)
134
            self.hermitian = True
135
        
Ultimanet's avatar
Ultimanet committed
136
137
138
139
140
141
142
143
144
    def copy(self, dtype=None, distribution_strategy=None, **kwargs):
        temp_d2o = self.copy_empty(dtype=dtype, 
                                   distribution_strategy=distribution_strategy, 
                                   **kwargs)     
        if distribution_strategy == None or \
            distribution_strategy == self.distribution_strategy:
            temp_d2o.set_local_data(self.get_local_data(), copy=True)
        else:
            temp_d2o.set_full_data(self.get_full_data())
145
        temp_d2o.hermitian = self.hermitian
146
147
        return temp_d2o
    
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    def copy_empty(self, global_shape=None, dtype=None, 
                   distribution_strategy=None, **kwargs):
        if global_shape == None:
            global_shape = self.shape
        if dtype == None:
            dtype = self.dtype
        if distribution_strategy == None:
            distribution_strategy = self.distribution_strategy

        kwargs.update(self.init_kwargs)
        
        temp_d2o = distributed_data_object(global_shape=global_shape,
                                           dtype=dtype,
                                           distribution_strategy=distribution_strategy,
162
                                           *self.init_args,
163
                                           **kwargs)
164
165
        return temp_d2o
    
166
    def apply_scalar_function(self, function, inplace=False, dtype=None):
167
168
        remember_hermitianQ = self.hermitian
        
Ultimanet's avatar
Ultimanet committed
169
170
        if inplace == True:        
            temp = self
171
172
173
174
            if dtype != None and self.dtype != dtype:
                about.warnings.cprint(\
            "WARNING: Inplace dtype conversion is not possible!")
                
Ultimanet's avatar
Ultimanet committed
175
        else:
176
            temp = self.copy_empty(dtype=dtype)
Ultimanet's avatar
Ultimanet committed
177
178
179
180
181

        try: 
            temp.data[:] = function(self.data)
        except:
            temp.data[:] = np.vectorize(function)(self.data)
182
        
183
184
185
186
        if function in (np.exp, np.log):
            temp.hermitian = remember_hermitianQ
        else:
            temp.hermitian = False
Ultimanet's avatar
Ultimanet committed
187
188
189
190
191
192
        return temp
    
    def apply_generator(self, generator):
        self.set_local_data(generator(self.distributor.local_shape))
        self.hermitian = False
            
ultimanet's avatar
ultimanet committed
193
194
195
196
197
198
    def __str__(self):
        return self.data.__str__()
    
    def __repr__(self):
        return '<distributed_data_object>\n'+self.data.__repr__()
    
Ultimanet's avatar
Ultimanet committed
199
    def __eq__(self, other):
Ultimanet's avatar
Ultimanet committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        result = self.copy_empty(dtype = np.bool)
        ## Case 1: 'other' is a scalar
        ## -> make point-wise comparison
        if np.isscalar(other):
            result.set_local_data(self.get_local_data(copy = False) == other)
            return result        

        ## Case 2: 'other' is a numpy array or a distributed_data_object
        ## -> extract the local data and make point-wise comparison
        elif isinstance(other, np.ndarray) or\
        isinstance(other, distributed_data_object):
            temp_data = self.distributor.extract_local_data(other)
            result.set_local_data(self.get_local_data(copy=False) == temp_data)
            return result
        
        ## Case 3: 'other' is None
        elif other == None:
            return False
        
        ## Case 4: 'other' is something different
220
        ## -> make a numpy casting and make a recursive call
Ultimanet's avatar
Ultimanet committed
221
222
223
224
225
226
227
228
        else:
            temp_other = np.array(other)
            return self.__eq__(temp_other)
            
            
        
    
    def equal(self, other):
Ultimanet's avatar
Ultimanet committed
229
230
231
232
233
234
235
236
237
        if other is None:
            return False
        try:
            assert(self.dtype == other.dtype)
            assert(self.shape == other.shape)
            assert(self.init_args == other.init_args)
            assert(self.init_kwargs == other.init_kwargs)
            assert(self.distribution_strategy == other.distribution_strategy)
            assert(np.all(self.data == other.data))
Ultimanet's avatar
Ultimanet committed
238
        except(AssertionError, AttributeError):
Ultimanet's avatar
Ultimanet committed
239
240
241
242
243
244
245
            return False
        else:
            return True
        

            
    
246
    def __pos__(self):
247
        temp_d2o = self.copy_empty()
248
249
250
        temp_d2o.set_local_data(data = self.get_local_data())
        return temp_d2o
        
ultimanet's avatar
ultimanet committed
251
    def __neg__(self):
252
        temp_d2o = self.copy_empty()
ultimanet's avatar
ultimanet committed
253
254
255
        temp_d2o.set_local_data(data = self.get_local_data().__neg__()) 
        return temp_d2o
    
256
    def __abs__(self):
Ultimanet's avatar
Ultimanet committed
257
258
259
260
261
262
263
264
265
266
267
268
        ## translate complex dtypes
        if self.dtype == np.complex64:
            new_dtype = np.float32
        elif self.dtype == np.complex128:
            new_dtype = np.float64
        elif self.dtype == np.complex:
            new_dtype = np.float
        elif issubclass(self.dtype, np.complexfloating):
            new_dtype = np.float
        else:
            new_dtype = self.dtype
        temp_d2o = self.copy_empty(dtype = new_dtype)
269
270
        temp_d2o.set_local_data(data = self.get_local_data().__abs__()) 
        return temp_d2o
ultimanet's avatar
ultimanet committed
271
            
272
    def __builtin_helper__(self, operator, other, inplace=False):
Ultimanet's avatar
Ultimanet committed
273
274
275
276
277
        ## Case 1: other is not a scalar
        if not (np.isscalar(other) or np.shape(other) == (1,)):
##            if self.shape != other.shape:            
##                raise AttributeError(about._errors.cstring(
##                    "ERROR: Shapes do not match!")) 
278
279
280
281
            try:            
                hermitian_Q = other.hermitian
            except(AttributeError):
                hermitian_Q = False
Ultimanet's avatar
Ultimanet committed
282
283
284
            ## extract the local data from the 'other' object
            temp_data = self.distributor.extract_local_data(other)
            temp_data = operator(temp_data)
Ultimanet's avatar
Ultimanet committed
285
            
286
287
288
289
        ## Case 2: other is a real scalar -> preserve hermitianity
        elif np.isreal(other) or (self.dtype not in (np.complex, np.complex128,
                                                np.complex256)):
            hermitian_Q = self.hermitian
ultimanet's avatar
ultimanet committed
290
            temp_data = operator(other)
291
292
293
294
        ## Case 3: other is complex
        else:
            hermitian_Q = False
            temp_data = operator(other)        
Ultimanet's avatar
Ultimanet committed
295
        ## write the new data into a new distributed_data_object        
296
297
298
299
        if inplace == True:
            temp_d2o = self
        else:
            temp_d2o = self.copy_empty()        
ultimanet's avatar
ultimanet committed
300
        temp_d2o.set_local_data(data=temp_data)
301
        temp_d2o.hermitian = hermitian_Q
ultimanet's avatar
ultimanet committed
302
        return temp_d2o
303
    """
Ultimanet's avatar
Ultimanet committed
304
    def __inplace_builtin_helper__(self, operator, other):
305
        ## Case 1: other is not a scalar
Ultimanet's avatar
Ultimanet committed
306
307
308
        if not (np.isscalar(other) or np.shape(other) == (1,)):        
            temp_data = self.distributor.extract_local_data(other)
            temp_data = operator(temp_data)
309
310
311
        ## Case 2: other is a real scalar -> preserve hermitianity
        elif np.isreal(other):
            hermitian_Q = self.hermitian
Ultimanet's avatar
Ultimanet committed
312
            temp_data = operator(other)
313
314
315
        ## Case 3: other is complex
        else:
            temp_data = operator(other)        
Ultimanet's avatar
Ultimanet committed
316
        self.set_local_data(data=temp_data)
317
        self.hermitian = hermitian_Q
Ultimanet's avatar
Ultimanet committed
318
        return self
319
    """ 
Ultimanet's avatar
Ultimanet committed
320
    
ultimanet's avatar
ultimanet committed
321
322
323
324
325
    def __add__(self, other):
        return self.__builtin_helper__(self.get_local_data().__add__, other)

    def __radd__(self, other):
        return self.__builtin_helper__(self.get_local_data().__radd__, other)
Ultimanet's avatar
Ultimanet committed
326
327

    def __iadd__(self, other):
328
329
330
        return self.__builtin_helper__(self.get_local_data().__iadd__, 
                                               other,
                                               inplace = True)
Ultimanet's avatar
Ultimanet committed
331

ultimanet's avatar
ultimanet committed
332
333
334
335
336
337
338
    def __sub__(self, other):
        return self.__builtin_helper__(self.get_local_data().__sub__, other)
    
    def __rsub__(self, other):
        return self.__builtin_helper__(self.get_local_data().__rsub__, other)
    
    def __isub__(self, other):
339
340
341
        return self.__builtin_helper__(self.get_local_data().__isub__, 
                                               other,
                                               inplace = True)
ultimanet's avatar
ultimanet committed
342
343
344
345
        
    def __div__(self, other):
        return self.__builtin_helper__(self.get_local_data().__div__, other)
    
346
347
348
    def __truediv__(self, other):
        return self.__div__(other)
        
ultimanet's avatar
ultimanet committed
349
350
    def __rdiv__(self, other):
        return self.__builtin_helper__(self.get_local_data().__rdiv__, other)
351
352
353
    
    def __rtruediv__(self, other):
        return self.__rdiv__(other)
ultimanet's avatar
ultimanet committed
354

Ultimanet's avatar
Ultimanet committed
355
    def __idiv__(self, other):
356
357
358
        return self.__builtin_helper__(self.get_local_data().__idiv__, 
                                               other,
                                               inplace = True)
359
360
361
    def __itruediv(self, other):
        return self.__idiv__(other)
                                               
ultimanet's avatar
ultimanet committed
362
    def __floordiv__(self, other):
Ultimanet's avatar
Ultimanet committed
363
364
        return self.__builtin_helper__(self.get_local_data().__floordiv__, 
                                       other)    
ultimanet's avatar
ultimanet committed
365
    def __rfloordiv__(self, other):
Ultimanet's avatar
Ultimanet committed
366
367
368
        return self.__builtin_helper__(self.get_local_data().__rfloordiv__, 
                                       other)
    def __ifloordiv__(self, other):
369
370
371
        return self.__builtin_helper__(
                    self.get_local_data().__ifloordiv__, other,
                                               inplace = True)
ultimanet's avatar
ultimanet committed
372
373
374
375
376
377
378
379
    
    def __mul__(self, other):
        return self.__builtin_helper__(self.get_local_data().__mul__, other)
    
    def __rmul__(self, other):
        return self.__builtin_helper__(self.get_local_data().__rmul__, other)

    def __imul__(self, other):
380
381
382
        return self.__builtin_helper__(self.get_local_data().__imul__, 
                                               other,
                                               inplace = True)
Ultimanet's avatar
Ultimanet committed
383

ultimanet's avatar
ultimanet committed
384
385
386
387
388
389
390
    def __pow__(self, other):
        return self.__builtin_helper__(self.get_local_data().__pow__, other)
 
    def __rpow__(self, other):
        return self.__builtin_helper__(self.get_local_data().__rpow__, other)

    def __ipow__(self, other):
391
392
393
        return self.___builtin_helper__(self.get_local_data().__ipow__, 
                                               other,
                                               inplace = True)
Ultimanet's avatar
Ultimanet committed
394
   
395
396
    def __len__(self):
        return self.shape[0]
397
    
398
399
400
    def dim(self):
        return np.prod(self.shape)
        
401
402
403
404
405
406
407
408
    def vdot(self, other):
        if isinstance(other, distributed_data_object):        
            other = other.get_local_data()
        local_vdot = np.vdot(self.get_local_data(), other)
        local_vdot_list = self.distributor._allgather(local_vdot)
        global_vdot = np.sum(local_vdot_list)
        return global_vdot
            
Ultimanet's avatar
Ultimanet committed
409

410
    
ultimanet's avatar
ultimanet committed
411
    def __getitem__(self, key):
Ultimanet's avatar
Ultimanet committed
412
413
414
415
416
417
418
419
420
421
422
        ## Case 1: key is a boolean array.
        ## -> take the local data portion from key, use this for data 
        ## extraction, and then merge the result in a flat numpy array
        if isinstance(key, np.ndarray):
            found = 'ndarray'
            found_boolean = (key.dtype.type == np.bool)
        elif isinstance(key, distributed_data_object):
            found = 'd2o'
            found_boolean = (key.dtype == np.bool)
        else:
            found = 'other'
Ultima's avatar
Ultima committed
423
        ## TODO: transfer this into distributor:
Ultimanet's avatar
Ultimanet committed
424
425
426
427
428
429
430
431
432
433
        if (found == 'ndarray' or found == 'd2o') and found_boolean == True:
            ## extract the data of local relevance
            local_bool_array = self.distributor.extract_local_data(key)
            local_results = self.get_local_data(copy=False)[local_bool_array]
            global_results = self.distributor._allgather(local_results)
            global_results = np.concatenate(global_results)
            return global_results            
            
        else:
            return self.get_data(key)
ultimanet's avatar
ultimanet committed
434
435
436
437
    
    def __setitem__(self, key, data):
        self.set_data(data, key)
        
438
    def _contraction_helper(self, function, **kwargs):
439
440
441
442
443
444
        local = function(self.data, **kwargs)
        local_list = self.distributor._allgather(local)
        global_ = function(local_list, axis=0)
        return global_
        
    def amin(self, **kwargs):
445
        return self._contraction_helper(np.amin, **kwargs)
446
447

    def nanmin(self, **kwargs):
448
        return self._contraction_helper(np.nanmin, **kwargs)
449
450
        
    def amax(self, **kwargs):
451
        return self._contraction_helper(np.amax, **kwargs)
452
453
    
    def nanmax(self, **kwargs):
454
        return self._contraction_helper(np.nanmax, **kwargs)
Ultimanet's avatar
Ultimanet committed
455
    
456
457
458
459
460
461
    def sum(self, **kwargs):
        return self._contraction_helper(np.sum, **kwargs)

    def prod(self, **kwargs):
        return self._contraction_helper(np.prod, **kwargs)        
        
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
    def mean(self, power=1):
        ## compute the local means and the weights for the mean-mean. 
        local_mean = np.mean(self.data**power)
        local_weight = np.prod(self.data.shape)
        ## collect the local means and cast the result to a ndarray
        local_mean_weight_list = self.distributor._allgather((local_mean, 
                                                              local_weight))
        local_mean_weight_list =np.array(local_mean_weight_list)   
        ## compute the denominator for the weighted mean-mean                                                           
        global_weight = np.sum(local_mean_weight_list[:,1])
        ## compute the numerator
        numerator = np.sum(local_mean_weight_list[:,0]*\
            local_mean_weight_list[:,1])
        global_mean = numerator/global_weight
        return global_mean

    def var(self):
        mean_of_the_square = self.mean(power=2)
        square_of_the_mean = self.mean()**2
        return mean_of_the_square - square_of_the_mean
    
    def std(self):
        return np.sqrt(self.var())
        
    def _argmin_argmax_flat_helper(self, function):
        local_argmin = function(self.data)
        local_argmin_value = self.data[np.unravel_index(local_argmin, 
                                                        self.data.shape)]
        globalized_local_argmin = self.distributor.globalize_flat_index(local_argmin)                                                       
        local_argmin_list = self.distributor._allgather((local_argmin_value, 
                                                         globalized_local_argmin))
        local_argmin_list = np.array(local_argmin_list, dtype=[('value', int),
                                                               ('index', int)])    
        return local_argmin_list
        
    def argmin_flat(self):
        local_argmin = np.argmin(self.data)
        local_argmin_value = self.data[np.unravel_index(local_argmin, 
                                                        self.data.shape)]
        globalized_local_argmin = self.distributor.globalize_flat_index(local_argmin)                                                       
        local_argmin_list = self.distributor._allgather((local_argmin_value, 
                                                         globalized_local_argmin))
        local_argmin_list = np.array(local_argmin_list, dtype=[('value', int),
                                                               ('index', int)])    
        local_argmin_list = np.sort(local_argmin_list, order=['value', 'index'])        
        return local_argmin_list[0][1]
    
    def argmax_flat(self):
        local_argmax = np.argmax(self.data)
        local_argmax_value = -self.data[np.unravel_index(local_argmax, 
                                                        self.data.shape)]
        globalized_local_argmax = self.distributor.globalize_flat_index(local_argmax)                                                       
        local_argmax_list = self.distributor._allgather((local_argmax_value, 
                                                         globalized_local_argmax))
        local_argmax_list = np.array(local_argmax_list, dtype=[('value', int),
                                                               ('index', int)])         
        return local_argmax_list[0][1]
        

    def argmin(self):    
        return np.unravel_index(self.argmin_flat(), self.shape)
    
    def argmax(self):
        return np.unravel_index(self.argmax_flat(), self.shape)
    
    def conjugate(self):
        temp_d2o = self.copy_empty()
        temp_data = np.conj(self.get_local_data())
        temp_d2o.set_local_data(temp_data)
        return temp_d2o

    
    def conj(self):
        return self.conjugate()      
        
    def median(self):
Ultimanet's avatar
Ultimanet committed
538
        about.warnings.cprint(\
539
540
541
542
            "WARNING: The current implementation of median is very expensive!")
        median = np.median(self.get_full_data())
        return median
        
543
544
545
546
547
548
549
550
551
552
553
    def iscomplex(self):
        temp_d2o = self.copy_empty(dtype=bool)
        temp_d2o.set_local_data(np.iscomplex(self.data))
        return temp_d2o
    
    def isreal(self):
        temp_d2o = self.copy_empty(dtype=bool)
        temp_d2o.set_local_data(np.isreal(self.data))
        return temp_d2o
    
    def is_completely_real(self):
554
        local_realiness = np.all(self.isreal().get_local_data())
555
556
557
        global_realiness = self.distributor._allgather(local_realiness)
        return np.all(global_realiness)
    
558
559
560
561
562
563
564
565
566
567
568
569
    def all(self):
        local_all = np.all(self.get_local_data())
        global_all = self.distributor._allgather(local_all)
        return np.all(global_all)

    def any(self):
        local_any = np.any(self.get_local_data())
        global_any = self.distributor._allgather(local_any)
        return np.all(global_any)
        
    
    
Ultimanet's avatar
Ultimanet committed
570
    def set_local_data(self, data, hermitian=False, copy=False):
ultimanet's avatar
ultimanet committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
        """
            Stores data directly in the local data attribute. No distribution 
            is done. The shape of the data must fit the local data attributes
            shape.

            Parameters
            ----------
            data : tuple, list, numpy.ndarray 
                The data which should be stored in the local data attribute.
            
            Returns
            -------
            None
        
        """
Ultimanet's avatar
Ultimanet committed
586
587
        self.hermitian = hermitian
        self.data = np.array(data, dtype=self.dtype, copy=copy, order='C')
ultimanet's avatar
ultimanet committed
588
    
Ultimanet's avatar
Ultimanet committed
589
    def set_data(self, data, key, hermitian=False, *args, **kwargs):
ultimanet's avatar
ultimanet committed
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        """
            Stores the supplied data in the region which is specified by key. 
            The data is distributed according to the distribution strategy. If
            the individual nodes get different key-arguments. Their data is 
            processed one-by-one.
            
            Parameters
            ----------
            data : tuple, list, numpy.ndarray 
                The data which should be distributed.
            key : int, slice, tuple of int or slice
                The key is the object which specifies the region, where data 
                will be stored in.                
            
            Returns
            -------
            None
        
        """
Ultimanet's avatar
Ultimanet committed
609
        self.hermitian = hermitian
ultimanet's avatar
ultimanet committed
610
        (slices, sliceified) = self.__sliceify__(key)        
Ultimanet's avatar
Ultimanet committed
611
612
613
614
        self.distributor.disperse_data(data=self.data, 
                        to_slices = slices,
                        data_update = self.__enfold__(data, sliceified), 
                        *args, **kwargs)        
ultimanet's avatar
ultimanet committed
615
    
Ultimanet's avatar
Ultimanet committed
616
    def set_full_data(self, data, hermitian=False, **kwargs):
ultimanet's avatar
ultimanet committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
        """
            Distributes the supplied data to the nodes. The shape of data must 
            match the shape of the distributed_data_object.
            
            Parameters
            ----------
            data : tuple, list, numpy.ndarray 
                The data which should be distributed.
            
            Notes
            -----
            set_full_data(foo) is equivalent to set_data(foo,slice(None)) but 
            faster.
        
            Returns
            -------
            None
        
        """
Ultimanet's avatar
Ultimanet committed
636
        self.hermitian = hermitian
637
        self.data = self.distributor.distribute_data(data=data, **kwargs)
ultimanet's avatar
ultimanet committed
638
639
    

Ultimanet's avatar
Ultimanet committed
640
    def get_local_data(self, key=(slice(None),), copy=True):
ultimanet's avatar
ultimanet committed
641
642
643
644
645
646
647
648
649
650
651
652
653
        """
            Loads data directly from the local data attribute. No consolidation 
            is done. 

            Parameters
            ----------
            key : int, slice, tuple of int or slice
                The key which will be used to access the data. 
            
            Returns
            -------
            self.data[key] : numpy.ndarray
        
Ultimanet's avatar
Ultimanet committed
654
        """
Ultimanet's avatar
Ultimanet committed
655
656
657
658
        if copy == True:
            return self.data[key]        
        if copy == False:
            return self.data
ultimanet's avatar
ultimanet committed
659
        
660
    def get_data(self, key, **kwargs):
ultimanet's avatar
ultimanet committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
        """
            Loads data from the region which is specified by key. The data is 
            consolidated according to the distribution strategy. If the 
            individual nodes get different key-arguments, they get individual
            data. 
            
            Parameters
            ----------
        
            key : int, slice, tuple of int or slice
                The key is the object which specifies the region, where data 
                will be loaded from.                 
            
            Returns
            -------
            global_data[key] : numpy.ndarray
        
        """
679
680
        (slices, sliceified) = self.__sliceify__(key)
        result = self.distributor.collect_data(self.data, slices, **kwargs)        
ultimanet's avatar
ultimanet committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
        return self.__defold__(result, sliceified)
        
    
    
    def get_full_data(self, target_rank='all'):
        """
            Fully consolidates the distributed data. 
            
            Parameters
            ----------
            target_rank : 'all' (default), int *optional*
                If only one node should recieve the full data, it can be 
                specified here.
            
            Notes
            -----
            get_full_data() is equivalent to get_data(slice(None)) but 
            faster.
        
            Returns
            -------
            None
        """

        return self.distributor.consolidate_data(self.data, target_rank)

Ultimanet's avatar
Ultimanet committed
707
708
709
710
711
712
713
    def inject(self, to_slices=(slice(None),), data=None, 
               from_slices=(slice(None),)):
        if data == None:
            return self
        
        self.distributor.inject(self.data, to_slices, data, from_slices)
        
714
715
716
717
718
719
720
721
722
723
724
    def flatten(self, inplace = False):
        flat_shape = (np.prod(self.shape),)
        temp_d2o = self.copy_empty(global_shape = flat_shape)
        flat_data = self.distributor.flatten(self.data, inplace = inplace)
        temp_d2o.set_local_data(data = flat_data)
        if inplace == True:
            self = temp_d2o
            return self
        else:
            return temp_d2o
        
Ultimanet's avatar
Ultimanet committed
725
        
ultimanet's avatar
ultimanet committed
726
727
728
729
730
731
    def _get_distributor(self, distribution_strategy):
        '''
            Comments:
              - The distributor's get_data and set_data functions MUST be 
                supplied with a tuple of slice objects. In case that there was 
                a direct integer involved, the unfolding will be done by the
732
                helper functions __sliceify__, __enfold__ and __defold__.
ultimanet's avatar
ultimanet committed
733
734
735
736
        '''
        
        distributor_dict={
            'fftw':     _fftw_distributor,
737
            'equal':    _equal_distributor,
ultimanet's avatar
ultimanet committed
738
739
740
            'not':      _not_distributor
        }
        if not distributor_dict.has_key(distribution_strategy):
Ultimanet's avatar
Ultimanet committed
741
            raise TypeError(about._errors.cstring("ERROR: Unknown distribution strategy supplied."))
ultimanet's avatar
ultimanet committed
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
        return distributor_dict[distribution_strategy]
      
    def save(self, alias, path=None, overwriteQ=True):
        
        """
            Saves a distributed_data_object to disk utilizing h5py.
            
            Parameters
            ----------
            alias : string
                The name for the dataset which is saved within the hdf5 file.
         
            path : string *optional*
                The path to the hdf5 file. If no path is given, the alias is 
                taken as filename in the current path.
            
            overwriteQ : Boolean *optional*
                Specifies whether a dataset may be overwritten if it is already
                present in the given hdf5 file or not.
        """
        self.distributor.save_data(self.data, alias, path, overwriteQ)

    def load(self, alias, path=None):
        """
            Loads a distributed_data_object from disk utilizing h5py.
            
            Parameters
            ----------
            alias : string
                The name of the dataset which is loaded from the hdf5 file.
 
            path : string *optional*
                The path to the hdf5 file. If no path is given, the alias is 
                taken as filename in the current path.
        """
        self.data = self.distributor.load_data(alias, path)
           
    def __sliceify__(self, inp):
        sliceified = []
        result = []
        if isinstance(inp, tuple):
            x = inp
Ultimanet's avatar
Ultimanet committed
784
785
        elif isinstance(inp, list):
            x = tuple(inp)
ultimanet's avatar
ultimanet committed
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
        else:
            x = (inp, )
        
        for i in range(len(x)):
            if isinstance(x[i], slice):
                result += [x[i], ]
                sliceified += [False, ]
            else:
                result += [slice(x[i], x[i]+1), ]
                sliceified += [True, ]
    
        return (tuple(result), sliceified)
                
                
    def __enfold__(self, in_data, sliceified):
        data = np.array(in_data, copy=False)    
        temp_shape = ()
        j=0
        for i in sliceified:
            if i == True:
                temp_shape += (1,)
807
808
809
810
811
                try:
                    if data.shape[j] == 1:
                        j +=1
                except(IndexError):
                    pass
ultimanet's avatar
ultimanet committed
812
            else:
813
814
815
816
                try:
                    temp_shape += (data.shape[j],)
                except(IndexError):
                    temp_shape += (1,)
ultimanet's avatar
ultimanet committed
817
818
819
820
821
822
                j += 1
        ## take into account that the sliceified tuple may be too short, because 
        ## of a non-exaustive list of slices
        for i in range(len(data.shape)-j):
            temp_shape += (data.shape[j],)
            j += 1
Ultimanet's avatar
Ultimanet committed
823
        
ultimanet's avatar
ultimanet committed
824
825
826
827
828
829
830
831
832
833
834
835
836
837
        return data.reshape(temp_shape)
    
    def __defold__(self, data, sliceified):
        temp_slice = ()
        for i in sliceified:
            if i == True:
                temp_slice += (0,)
            else:
                temp_slice += (slice(None),)
        return data[temp_slice]

    

   
838
839
class _slicing_distributor(object):
    def __init__(self, slicer, global_data=None, global_shape=None, dtype=None, 
840
                 comm=MPI.COMM_WORLD, alias=None, path=None):
ultimanet's avatar
ultimanet committed
841
842
843
844
845
846
847
848
849
850
851
        
        if alias != None:
            file_path = path if path != None else alias 
            if found['h5py_parallel']:
                f = h5py.File(file_path, 'r', driver='mpio', comm=comm)
            else:
                f= h5py.File(file_path, 'r')        
            dset = f[alias]        

        
        if comm.rank == 0:        
Ultimanet's avatar
Ultimanet committed
852
            ## Case 1: hdf5 path supplied
ultimanet's avatar
ultimanet committed
853
854
            if alias != None:
                self.global_shape = dset.shape
Ultimanet's avatar
Ultimanet committed
855
856
857
858
            ## Case 2: no hdf5 path supplied
            else:           
                ## subcase 1: input data is scalar or None
                if global_data == None or np.isscalar(global_data):
ultimanet's avatar
ultimanet committed
859
                    if global_shape == None:
Ultimanet's avatar
Ultimanet committed
860
                        raise TypeError(about._errors.\
Ultimanet's avatar
Ultimanet committed
861
                cstring("ERROR: Neither non-scalar data nor shape supplied!"))
ultimanet's avatar
ultimanet committed
862
863
                    else:
                        self.global_shape = global_shape
Ultimanet's avatar
Ultimanet committed
864
865
                ## subcase 2: input data is non-scalar 
                ## -> Take the shape of the input data
ultimanet's avatar
ultimanet committed
866
867
868
869
                else:
                    self.global_shape = global_data.shape
        else:
            self.global_shape = None
Ultimanet's avatar
Ultimanet committed
870
            
ultimanet's avatar
ultimanet committed
871
872
873
874
875
876
877
878
879
880
881
882
        self.global_shape = comm.bcast(self.global_shape, root = 0)
        self.global_shape = tuple(self.global_shape)
        
        if comm.rank == 0:        
            if alias != None:
                self.dtype = dset.dtype.type
            else:    
                if dtype != None:        
                    self.dtype = dtype
                elif global_data != None:
                    self.dtype = np.array(global_data).dtype.type
                else:
Ultimanet's avatar
Ultimanet committed
883
                    raise TypeError(about._errors.\
884
885
                    cstring("ERROR: Failed setting datatype. Neither data, "+\
                     "nor datatype supplied."))
ultimanet's avatar
ultimanet committed
886
887
888
889
890
891
892
893
894
        else:
            self.dtype=None
        self.dtype = comm.bcast(self.dtype, root=0)
        if alias != None:        
            f.close()        
        
        self._my_dtype_converter = dtype_converter()
        
        if not self._my_dtype_converter.known_np_Q(self.dtype):
Ultimanet's avatar
Ultimanet committed
895
            raise TypeError(about._errors.cstring(\
896
            "ERROR: The datatype "+str(self.dtype)+" is not known to mpi4py."))
ultimanet's avatar
ultimanet committed
897
898
899

        self.mpi_dtype  = self._my_dtype_converter.to_mpi(self.dtype)
        
900
901
902
903
904
905
906
907
        #self._local_size = pyfftw.local_size(self.global_shape)
        #self.local_start = self._local_size[2]
        #self.local_end = self.local_start + self._local_size[1]
        self.slicer = lambda global_shape: slicer(global_shape, comm = comm)
        self._local_size = self.slicer(self.global_shape)
        self.local_start = self._local_size[0]
        self.local_end = self._local_size[1] 
        
ultimanet's avatar
ultimanet committed
908
909
910
911
        self.local_length = self.local_end-self.local_start        
        self.local_shape = (self.local_length,) + tuple(self.global_shape[1:])
        self.local_dim = np.product(self.local_shape)
        self.local_dim_list = np.empty(comm.size, dtype=np.int)
912
913
        comm.Allgather([np.array(self.local_dim,dtype=np.int), MPI.INT],\
            [self.local_dim_list, MPI.INT])
ultimanet's avatar
ultimanet committed
914
915
        self.local_dim_offset = np.sum(self.local_dim_list[0:comm.rank])
        
916
917
918
        self.local_slice = np.array([self.local_start, self.local_end,\
            self.local_length, self.local_dim, self.local_dim_offset],\
            dtype=np.int)
ultimanet's avatar
ultimanet committed
919
920
921
        ## collect all local_slices 
        ## [start, stop, length=stop-start, dimension, dimension_offset]
        self.all_local_slices = np.empty((comm.size,5),dtype=np.int)
922
923
        comm.Allgather([np.array((self.local_slice,),dtype=np.int), MPI.INT],\
            [self.all_local_slices, MPI.INT])
ultimanet's avatar
ultimanet committed
924
        
925
        self.comm = comm
ultimanet's avatar
ultimanet committed
926
        
927
928
929
930
931
932
    def globalize_flat_index(self, index):
        return int(index)+self.local_dim_offset
        
    def globalize_index(self, index):
        index = np.array(index, dtype=np.int).flatten()
        if index.shape != (len(self.global_shape),):
Ultimanet's avatar
Ultimanet committed
933
            raise TypeError(about._errors.cstring("ERROR: Length\
934
935
936
937
938
939
940
941
942
                of index tuple does not match the array's shape!"))                 
        globalized_index = index
        globalized_index[0] = index[0] + self.local_start
        ## ensure that the globalized index list is within the bounds
        global_index_memory = globalized_index
        globalized_index = np.clip(globalized_index, 
                                   -np.array(self.global_shape),
                                    np.array(self.global_shape)-1)
        if np.any(global_index_memory != globalized_index):
Ultimanet's avatar
Ultimanet committed
943
            about.warnings.cprint("WARNING: Indices were clipped!")
944
945
946
947
948
949
950
951
952
953
954
        globalized_index = tuple(globalized_index)
        return globalized_index
    
    def _allgather(self, thing, comm=None):
        if comm == None:
            comm = self.comm            
        gathered_things = comm.allgather(thing)
        return gathered_things
    
    def distribute_data(self, data=None, comm = None, alias=None,
                        path=None, **kwargs):
ultimanet's avatar
ultimanet committed
955
956
957
958
959
        '''
        distribute data checks 
        - whether the data is located on all nodes or only on node 0
        - that the shape of 'data' matches the global_shape
        '''
960
961
        if comm == None:
            comm = self.comm            
962
963
964
965
        rank = comm.Get_rank()
        size = comm.Get_size()        
        local_data_available_Q = np.array((int(data != None), ))
        data_available_Q = np.empty(size,dtype=int)
966
967
        comm.Allgather([local_data_available_Q, MPI.INT], 
                       [data_available_Q, MPI.INT])        
968
969
        
        if data_available_Q[0]==False and found['h5py']:
ultimanet's avatar
ultimanet committed
970
971
972
973
974
975
976
            try: 
                file_path = path if path != None else alias 
                if found['h5py_parallel']:
                    f = h5py.File(file_path, 'r', driver='mpio', comm=comm)
                else:
                    f= h5py.File(file_path, 'r')        
                dset = f[alias]
977
978
                if dset.shape == self.global_shape and \
                 dset.dtype.type == self.dtype:
ultimanet's avatar
ultimanet committed
979
980
981
982
                    temp_data = dset[self.local_start:self.local_end]
                    f.close()
                    return temp_data
                else:
Ultimanet's avatar
Ultimanet committed
983
                    raise TypeError(about._errors.cstring("ERROR: \
984
                    Input data has the wrong shape or wrong dtype!"))                 
ultimanet's avatar
ultimanet committed
985
986
987
            except(IOError, AttributeError):
                pass
            
988
        if np.all(data_available_Q==False):
Ultimanet's avatar
Ultimanet committed
989
            return np.empty(self.local_shape, dtype=self.dtype, order='C')
ultimanet's avatar
ultimanet committed
990
        ## if all nodes got data, we assume that it is the right data and 
991
992
        ## store it individually. If not, take the data on node 0 and scatter 
        ## it...
ultimanet's avatar
ultimanet committed
993
        if np.all(data_available_Q):
994
995
            return data[self.local_start:self.local_end].astype(self.dtype,\
                copy=False)    
996
997
        ## ... but only if node 0 has actually data!
        elif data_available_Q[0] == False:# or np.all(data_available_Q==False):
Ultimanet's avatar
Ultimanet committed
998
            return np.empty(self.local_shape, dtype=self.dtype, order='C')
999
        
ultimanet's avatar
ultimanet committed
1000
1001
1002
1003
1004
        else:
            if data == None:
                data = np.empty(self.global_shape)            
            if rank == 0:
                if np.all(data.shape != self.global_shape):
Ultimanet's avatar
Ultimanet committed
1005
                    raise TypeError(about._errors.cstring(\
1006
                        "ERROR: Input data has the wrong shape!"))
ultimanet's avatar
ultimanet committed
1007
            ## Scatter the data!            
Ultimanet's avatar
Ultimanet committed
1008
            _scattered_data = np.empty(self.local_shape, dtype = self.dtype)
ultimanet's avatar
ultimanet committed
1009
1010
            _dim_list = self.all_local_slices[:,3]
            _dim_offset_list = self.all_local_slices[:,4]
1011
1012
            comm.Scatterv([data, _dim_list, _dim_offset_list, self.mpi_dtype],\
                [_scattered_data, self.mpi_dtype], root=0)
ultimanet's avatar
ultimanet committed
1013
1014
1015
            return _scattered_data
        return None
    
Ultimanet's avatar
Ultimanet committed
1016
1017
    def _disperse_data_primitive(self, data, to_slices, data_update, 
                                 from_slices, source_rank='all', comm=None):
1018
1019
        if comm == None:
            comm = self.comm            
1020
1021
        ## compute the part of the slice which is relevant for the 
        ## individual node      
ultimanet's avatar
ultimanet committed
1022
        localized_start, localized_stop = self._backshift_and_decycle(
Ultimanet's avatar
Ultimanet committed
1023
            to_slices[0], self.local_start, self.local_end,\
1024
1025
                self.global_shape[0])
        local_slice = (slice(localized_start, localized_stop,\
Ultimanet's avatar
Ultimanet committed
1026
                        to_slices[0].step),) + to_slices[1:]
ultimanet's avatar
ultimanet committed
1027
1028
1029
1030
1031
        
        ## compute the parameter sets and list for the data splitting
        local_slice_shape = data[local_slice].shape        
        local_affected_data_length = local_slice_shape[0]
        local_affected_data_length_list=np.empty(comm.size, dtype=np.int)        
1032
1033
1034
1035
1036
        comm.Allgather(\
            [np.array(local_affected_data_length, dtype=np.int), MPI.INT],\
            [local_affected_data_length_list, MPI.INT])        
        local_affected_data_length_offset_list = np.append([0],\
                            np.cumsum(local_affected_data_length_list)[:-1])
ultimanet's avatar
ultimanet committed
1037
1038
1039
1040
1041
1042
1043
1044
        
        
        if source_rank == 'all':
            ## only take the relevant part out of data_update and plug it into 
            ## data[local_slice]
            r = comm.rank
            o = local_affected_data_length_offset_list
            l = local_affected_data_length
Ultimanet's avatar
Ultimanet committed
1045
1046
1047
1048
1049
1050
            
            ## if the from_slices object is not None, i.e. only a part from
            ## the data source is used, form the update_slice accordingly
            if from_slices == None:
                update_slice = (slice(o[r], o[r]+l),)
            else:
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
                ## Determine the part of the source array, which is relevant
                ## for the target rank
                if (from_slices[0].step > 0) or (from_slices[0].step is None):
                    ## f_relative_start: index of start of source data in 
                    ## source array
                    f_lower_end = from_slices[0].start
                    if f_lower_end is None:
                        f_lower_end = 0
                    ## f_start: index of start of specific source data in 
                    ## source array
                    f_start = f_lower_end + o[r]
                    ## f_stop: index of stop of specific source data
                    f_stop = f_start + l
                  
                                        
                elif from_slices[0].step < 0:
                    ## f_relative_start: index of start of source data in 
                    ## source array
                    f_upper_end = from_slices[0].start
                    if f_upper_end is None:
                        f_upper_end = data_update.shape[0] - 1
                    ## f_start: index of start of specific source data in 
                    ## source array
                    f_start = f_upper_end - o[r] 
                    ## f_stop: index of stop of specific source data
                    f_stop = f_start - l
Ultimanet's avatar
Ultimanet committed
1077
1078
                    
                else:
1079
1080
1081
1082
1083
1084
1085
                    raise ValueError(about._errors.cstring(\
                        "ERROR: step size == 0!")) 
                        
                update_slice = (slice(f_start, 
                                          f_stop, 
                                          from_slices[0].step),)
            
Ultimanet's avatar
Ultimanet committed
1086
                update_slice += from_slices[1:]
1087
1088
            data[local_slice] = np.array(data_update[update_slice],\
                                    copy=False).astype(self.dtype)
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
                
#                ## TODO: Fallunterscheidung, ob direction positiv oder negativ!!
#                if from_slices[0].step > 0:
#                    f_relative_start = from_slices[0].start
#                else:
#                    f_relative_start = from_slices[0].stop + 1
#
#                if f_relative_start is None:
#                    f_relative_start = 0
#                    
#                local_start = f_relative_start + o[r]
#                print ('rank', rank, 
#                       'f_relative_start', f_relative_start,
#                       'local_start', local_start,
#                       'o[r]', o[r])
#                       
#                
#                update_slice = self._backshift_and_decycle(
#                                        slice_object = from_slices[0],
#                                        shifted_start = local_start,
#                                        shifted_stop = local_start+l,
#                                        global_length = data_update.shape[0])
#                                        
#                print ('rank', rank, update_slice)
#                f_step = from_slices[0].step
#                if f_step == None:
#                    f_step = 1
#                    
#                f_direction = np.sign(f_step)
#
#                f_relative_start = from_slices[0].start
#
#                ## Case 1: f_direction is positive
#                if f_direction > 0:
#                    if f_relative_start != None:
#                        f_start = f_relative_start + o[r]
#                
#                
#                
#                
#                if f_relative_start != None:
#                    f_start = f_relative_start + f_direction*o[r]
#                else:
#                    f_start = None
#                    f_relative_start = self.local_start + l - 1
#                
#                
#                f_stop = f_relative_start + f_direction*(o[r]+l*np.abs(f_step))
#                print (rank, 
#                'f_start', f_start, 
#                'offset', self.local_start, 
#                'f_relative_start', f_relative_start,
#                'f_stop', f_stop)
#                if f_stop < 0:
#                    f_stop = None
#
#
#                ## combine the slicing for the first dimension 
#                update_slice = (slice(f_start,
#                                      f_stop,
#                                      f_step),
#                                )
#                ## add the rest of the from_slicing
#                update_slice += from_slices[1:]
#
#            data[local_slice] = np.array(data_update[update_slice],\
#                                    copy=False).astype(self.dtype)
#                
ultimanet's avatar
ultimanet committed
1157
1158
1159
        else:
            ## Scatterv the relevant part from the source_rank to the others 
            ## and plug it into data[local_slice]
1160
1161
1162
            
            ## if the first slice object has a negative step size, the ordering 
            ## of the Scatterv function must be reversed         
Ultimanet's avatar
Ultimanet committed
1163
            order = to_slices[0].step
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
            if order == None:
                order = 1
            else:
                order = np.sign(order)

            local_affected_data_dim_list = \
                np.array(local_affected_data_length_list) *\
                    np.product(local_slice_shape[1:])                    

            local_affected_data_dim_offset_list = np.append([0],\
                np.cumsum(local_affected_data_dim_list[::order])[:-1])[::order]
                
            local_dispersed_data = np.zeros(local_slice_shape,\
                dtype=self.dtype)
            comm.Scatterv(\
Ultimanet's avatar
Ultimanet committed
1179
1180
                [np.array(data_update[from_slices],copy=False).\
                                                        astype(self.dtype),\
1181
1182
                    local_affected_data_dim_list,\
                    local_affected_data_dim_offset_list, self.mpi_dtype],
ultimanet's avatar
ultimanet committed
1183
1184
1185
1186
1187
1188
1189
                          [local_dispersed_data, self.mpi_dtype], 
                          root=source_rank)                            
            data[local_slice] = local_dispersed_data
        return None
        
    
    
Ultimanet's avatar
Ultimanet committed
1190
1191
    def disperse_data(self, data, to_slices, data_update, from_slices=None,
                      comm=None, **kwargs):
1192
1193
        if comm == None:
            comm = self.comm            
Ultimanet's avatar
Ultimanet committed
1194
        to_slices_list = comm.allgather(to_slices)
ultimanet's avatar
ultimanet committed
1195
        ## check if all slices are the same. 
Ultimanet's avatar
Ultimanet committed
1196
        if all(x == to_slices_list[0] for x in to_slices_list):
ultimanet's avatar
ultimanet committed
1197
1198
            ## in this case, the _disperse_data_primitive can simply be called 
            ##with target_rank = 'all'
Ultimanet's avatar
Ultimanet committed
1199
1200
1201
1202
1203
1204
            self._disperse_data_primitive(data = data, 
                                          to_slices = to_slices,
                                          data_update=data_update,
                                          from_slices=from_slices, 
                                          source_rank='all', 
                                          comm=comm)
1205
1206
        ## if the different nodes got different slices, disperse the data 
        ## individually
ultimanet's avatar
ultimanet committed
1207
1208
        else:
            i = 0        
Ultimanet's avatar
Ultimanet committed
1209
            for temp_to_slices in to_slices_list:
ultimanet's avatar
ultimanet committed
1210
                ## make the collect_data call on all nodes            
Ultimanet's avatar
Ultimanet committed
1211
1212
1213
1214
1215
1216
                self._disperse_data_primitive(data=data,
                                              to_slices=temp_to_slices,
                                              data_update=data_update,
                                              from_slices=from_slices,
                                              source_rank=i, 
                                              comm=comm)
ultimanet's avatar
ultimanet committed
1217
1218
1219
                i += 1
                 
        
1220
1221
1222
1223
    def _collect_data_primitive(self, data, slice_objects, target_rank='all', comm=None):
        if comm == None:
            comm = self.comm            
            
ultimanet's avatar
ultimanet committed
1224
        localized_start, localized_stop = self._backshift_and_decycle(
1225
            slice_objects[0], self.local_start, self.local_end, self.global_shape[0])
ultimanet's avatar
ultimanet committed
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
        local_slice = (slice(localized_start,localized_stop,slice_objects[0].step),)+slice_objects[1:]
        local_collected_data = np.ascontiguousarray(data[local_slice])

        local_collected_data_length = local_collected_data.shape[0]
        local_collected_data_length_list=np.empty(comm.size, dtype=np.int)        
        comm.Allgather([np.array(local_collected_data_length, dtype=np.int), MPI.INT], [local_collected_data_length_list, MPI.INT])        
             
        collected_data_length = np.sum(local_collected_data_length_list) 
        collected_data_shape = (collected_data_length,)+local_collected_data.shape[1:]
        local_collected_data_dim_list= np.array(local_collected_data_length_list) * np.product(local_collected_data.shape[1:])        
        
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
        ## if the first slice object has a negative step size, the ordering 
        ## of the Gatherv functions must be reversed         
        order = slice_objects[0].step
        if order == None:
            order = 1
        else:
            order = np.sign(order)
            
        local_collected_data_dim_offset_list = np.append([0],np.cumsum(local_collected_data_dim_list[::order])[:-1])[::order]

        local_collected_data_dim_offset_list = local_collected_data_dim_offset_list
ultimanet's avatar
ultimanet committed
1248
        collected_data = np.empty(collected_data_shape, dtype=self.dtype)
1249
        
ultimanet's avatar
ultimanet committed
1250
1251
1252
1253
1254
1255
1256
1257
1258

        if target_rank == 'all':
            comm.Allgatherv([local_collected_data, self.mpi_dtype], 
                         [collected_data, local_collected_data_dim_list, local_collected_data_dim_offset_list, self.mpi_dtype])                
        else:
            comm.Gatherv([local_collected_data, self.mpi_dtype], 
                         [collected_data, local_collected_data_dim_list, local_collected_data_dim_offset_list, self.mpi_dtype], root=target_rank)                            
        return collected_data

1259
1260
1261
    def collect_data(self, data, slice_objects, comm=None, **kwargs):
        if comm == None:
            comm = self.comm                    
ultimanet's avatar
ultimanet committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
        slice_objects_list = comm.allgather(slice_objects)
        ## check if all slices are the same. 
        if all(x == slice_objects_list[0] for x in slice_objects_list):
            ## in this case, the _collect_data_primitive can simply be called 
            ##with target_rank = 'all'
            return self._collect_data_primitive(data=data, slice_objects=slice_objects, target_rank='all', comm=comm)
        
        ## if the different nodes got different slices, collect the data individually
        i = 0        
        for temp_slices in slice_objects_list:
            ## make the collect_data call on all nodes            
            temp_data = self._collect_data_primitive(data=data, slice_objects=temp_slices, target_rank=i, comm=comm)
            ## save the result only on the pulling node            
            if comm.rank == i:
                individual_data = temp_data
            i += 1
        return individual_data
        
    
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    def _backshift_and_decycle(self, slice_object, shifted_start, shifted_stop, global_length):
        ## Crop the start value
        if slice_object.start > global_length-1:
            slice_object = slice(global_length-1, slice_object.stop,
                                 slice_object.step)
                                 
        ## Reformulate negative indices                                  
        if slice_object.start < 0 and slice_object.start != None:
            temp_start = slice_object.start + global_length
            if temp_start < 0:
Ultimanet's avatar
Ultimanet committed
1291
                raise ValueError(about._errors.cstring(\
1292
1293
1294
1295
1296
1297
1298
                "ERROR: Index is out of bounds!"))
            slice_object = slice(temp_start, slice_object.stop,\
            slice_object.step) 

        if slice_object.stop < 0 and slice_object.stop != None:
            temp_stop = slice_object.stop + global_length
            if temp_stop < 0:
Ultimanet's avatar
Ultimanet committed
1299
                raise ValueError(about._errors.cstring(\
1300
1301
1302
1303
1304
                "ERROR: Index is out of bounds!"))
            slice_object = slice(slice_object.start, temp_stop,\
            slice_object.step) 
                
        ## initialize the step
ultimanet's avatar
ultimanet committed
1305
1306
1307
1308
        if slice_object.step == None:
            step = 1
        else:
            step = slice_object.step
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
        
        if step > 0:
            shift = shifted_start
            ## calculate the start index
            if slice_object.start == None:
                local_start = (-shift)%step ## step size compensation
            else:
                local_start = slice_object.start - shift
                ## if the local_start is negative, pull it up to zero
                local_start = local_start%step if local_start < 0 else local_start
            ## calculate the stop index
            if slice_object.stop == None:
                local_stop = None
            else:
                local_stop = slice_object.stop - shift
                ## if local_stop is negative, pull it up to zero
                local_stop = 0 if local_stop < 0 else local_stop
                
        else: # if step < 0
            step = -step
            local_length = shifted_stop - shifted_start
            ## calculate the start index. (Here, local_start > local_stop!)
            if slice_object.start == None:
                local_start = (local_length-1) -\
                    (global_length-shifted_stop)%step #stepsize compensation
            else:
                local_start = slice_object.start - shifted_start
1336
1337
1338
1339
1340
                ## if the local_start is negative, immediately return the 
                ## values for an empty slice
                if local_start < 0:
                    return 0, 0
                                
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
                ## if the local_start is greater than the local length, pull
                ## it down 
                if local_start > local_length-1:
                    overhead = local_start - (local_length-1)
                    overhead = overhead - overhead%(-step)
                    local_start = local_start - overhead
            ## calculate the stop index
            if slice_object.stop == None:
                local_stop = None
            else:
                local_stop = slice_object.stop - shifted_start
1352
1353
                ## if local_stop is negative, pull it up to None
                local_stop = None if local_stop < 0 else local_stop    
1354
        ## Note: if start or stop are greater than the array length,
ultimanet's avatar
ultimanet committed
1355
        ## numpy will automatically cut the index value down into the 
1356
        ## array's range
ultimanet's avatar
ultimanet committed
1357
        return local_start, local_stop        
1358
    
Ultimanet's avatar
Ultimanet committed
1359
1360
    def inject(self, data, to_slices, data_update, from_slices, comm=None, 
               **kwargs):
Ultimanet's avatar
Ultimanet committed
1361
        ## check if to_key and from_key are completely built of slices 
Ultimanet's avatar
Ultimanet committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
        if not np.all(
            np.vectorize(lambda x: isinstance(x, slice))(to_slices)):
            raise ValueError(about._errors.cstring(
            "ERROR: The to_slices argument must be a list or tuple of slices!")
            )

        if not np.all(
            np.vectorize(lambda x: isinstance(x, slice))(from_slices)):
            raise ValueError(about._errors.cstring(
            "ERROR: The from_slices argument must be a list or tuple of slices!")
            )
            
        to_slices = tuple(to_slices)
        from_slices = tuple(from_slices)
        self.disperse_data(data = data, 
                           to_slices = to_slices,
                           data_update = data_update,
                           from_slices = from_slices,
                           comm=comm,
                           **kwargs)
Ultimanet's avatar
Ultimanet committed
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392

    def extract_local_data(self, data_object):
        ## if data_object is not a ndarray or a d2o, cast it to a ndarray
        if not (isinstance(data_object, np.ndarray) or 
                isinstance(data_object, distributed_data_object)):
            data_object = np.array(data_object)
        ## check if the shapes are remotely compatible, reshape if possible
        ## and determine which dimensions match only via broadcasting
        try:
            (data_object, matching_dimensions) = \
                self._reshape_foreign_data(data_object)
1393
        ## if the shape-casting fails, try to fix things via local data
Ultimanet's avatar
Ultimanet committed
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
        ## matching
        except(ValueError):
            ## Check if all the local shapes match the supplied data
            local_matchQ = (self.local_shape == data_object.shape)
            global_matchQ = self._allgather(local_matchQ)            
            ## if the local shapes match, simply return the data_object            
            if np.all(global_matchQ):
                extracted_data = data_object[:] 
            ## if not, allgather the local data pieces and extract from this
            else:
                allgathered_data = self._allgather(data_object)
                allgathered_data = np.concatenate(allgathered_data)
                if allgathered_data.shape != self.global_shape:
                    raise ValueError(
                            about._errors.cstring(
            "ERROR: supplied shapes do neither match globally nor locally"))
                return self.extract_local_data(allgathered_data)
            
        ## if shape-casting was successfull, extract the data
        else:
            ## If the first dimension matches only via broadcasting...
            ## Case 1: ...do broadcasting. This procedure does not depend on the
            ## array type (ndarray or d2o)
            if matching_dimensions[0] == False:
                extracted_data = data_object[0:1]
    
    
            ## Case 2: First dimension fits directly and data_object is a d2o
            elif isinstance(data_object, distributed_data_object):
                ## Check if the distribution_strategy and the comm match 
                ## the own ones.            
                if type(self) == type(data_object.distributor) and\
                    self.comm == data_object.distributor.comm:
                    ## Case 1: yes. Simply take the local data
                    extracted_data = data_object.data
                else:            
                    ## Case 2: no. All nodes extract their local slice from the 
                    ## data_object
                    extracted_data =\
                        data_object[self.local_start:self.local_end]
            
            ## Case 3: First dimension fits directly and data_object is an generic
            ## array        
            else:
                extracted_data =\
                    data_object[self.local_start:self.local_end]
            
        return extracted_data

    def _reshape_foreign_data(self, foreign):
        ## Case 1:        
        ## check if the shapes match directly 
        if self.global_shape == foreign.shape:
            matching_dimensions = [True,]*len(self.global_shape)            
            return (foreign, matching_dimensions)
        ## Case 2:
        ## if not, try to reshape the input data
        ## in particular, this will fail when foreign is a d2o as long as 
        ## reshaping is not implemented
        try:
            output = foreign.reshape(self.global_shape)
            matching_dimensions = [True,]*len(self.global_shape)
            return (output, matching_dimensions)
        except(ValueError, AttributeError):
            pass
        ## Case 3:
        ## if this does not work, try to broadcast the shape
        ## check if the dimensions match
        if len(self.global_shape) != len(foreign.shape):
           raise ValueError(
               about._errors.cstring("ERROR: unequal number of dimensions!")) 
        ## check direct matches
        direct_match = (np.array(self.global_shape) == np.array(foreign.shape))
        ## check broadcast compatibility
        broadcast_match = (np.ones(len(self.global_shape), dtype=int) ==\
                            np.array(foreign.shape))
        ## combine the matches and assert that all are true
        combined_match = (direct_match | broadcast_match)
        if not np.all(combined_match):
            raise ValueError(
                about._errors.cstring("ERROR: incompatible shapes!")) 
        matching_dimensions = tuple(direct_match)
        return (foreign, matching_dimensions)