test_distributed_data_object.py 80.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# D2O
# Copyright (C) 2016  Theo Steininger
#
# Author: Theo Steininger
#
# 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/>.
theos's avatar
theos committed
18

19
20
21
from __future__ import division
from __future__ import print_function

Theo Steininger's avatar
Theo Steininger committed
22
23
24
25
26
from builtins import str
from builtins import range

from future.standard_library import PY2, PY3

theos's avatar
theos committed
27
28
from numpy.testing import assert_equal,\
    assert_almost_equal,\
29
30
    assert_raises,\
    assert_allclose
theos's avatar
theos committed
31
32
33
34
35
36
37
38
39
40

from nose_parameterized import parameterized
import unittest

import itertools
import os
import numpy as np
import warnings
import tempfile

theos's avatar
theos committed
41
from d2o import distributed_data_object,\
theos's avatar
theos committed
42
43
                STRATEGIES,\
                arange
theos's avatar
theos committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

from distutils.version import LooseVersion as lv

FOUND = {}
try:
    import h5py
    FOUND['h5py'] = True
    FOUND['h5py_parallel'] = h5py.get_config().mpi
except(ImportError):
    FOUND['h5py'] = False
    FOUND['h5py_parallel'] = False

try:
    from mpi4py import MPI
    FOUND['MPI'] = True
except(ImportError):
    import mpi_dummy as MPI
    FOUND['MPI'] = False


###############################################################################

comm = MPI.COMM_WORLD
rank = comm.rank
size = comm.size

###############################################################################

np.random.seed(123)

###############################################################################

# all_datatypes = [np.bool_, np.int16, np.uint16, np.uint32, np.int32, np.int_,
#             np.int, np.int64, np.uint64, np.float32, np.float_, np.float,
#             np.float64, np.float128, np.complex64, np.complex_,
#             np.complex, np.complex128]
80
all_datatypes = [np.dtype('bool'), np.dtype('int8'), np.dtype('int16'), np.dtype('uint16'),
theos's avatar
theos committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
                 np.dtype('uint32'), np.dtype('int32'), np.dtype('int'),
                 np.dtype('int64'), np.dtype('uint'), np.dtype('uint64'),
                 np.dtype('float32'), np.dtype(
                     'float64'), np.dtype('float128'),
                 np.dtype('complex64'), np.dtype('complex128')]

###############################################################################

all_distribution_strategies = STRATEGIES['all']
global_distribution_strategies = STRATEGIES['global']
local_distribution_strategies = STRATEGIES['local']
hdf5_distribution_strategies = STRATEGIES['hdf5']

###############################################################################

binary_non_inplace_operators = ['__add__', '__radd__', '__sub__', '__rsub__',
Theo Steininger's avatar
Theo Steininger committed
97
                                '__truediv__', '__rtruediv__', '__floordiv__',
theos's avatar
theos committed
98
99
                                '__rfloordiv__', '__mul__', '__rmul__',
                                '__pow__', '__rpow__']
Theo Steininger's avatar
Theo Steininger committed
100
101
102
103
104

if PY2:
    binary_non_inplace_operators += ['__div__', '__rdiv__']

binary_inplace_operators = ['__iadd__', '__isub__', '__itruediv__',
theos's avatar
theos committed
105
                            '__ifloordiv__', '__imul__', '__ipow__']
Theo Steininger's avatar
Theo Steininger committed
106
107
108
109
if PY2:
    binary_inplace_operators += ['__idiv__']


theos's avatar
theos committed
110
111
112
113
114
115
comparison_operators = ['__ne__', '__lt__', '__le__', '__eq__', '__ge__',
                        '__gt__', ]

###############################################################################

hdf5_test_paths = [  # ('hdf5_init_test.hdf5', None),
theos's avatar
theos committed
116
117
    ('hdf5_init_test.hdf5', 'test/hdf5_init_test.hdf5'),
    ('hdf5_init_test.hdf5', 'test/hdf5_test_folder/hdf5_init_test.hdf5')]
theos's avatar
theos committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

###############################################################################


def custom_name_func(testcase_func, param_num, param):
    return "%s_%s" % (
        testcase_func.__name__,
        parameterized.to_safe_name("_".join(str(x) for x in param.args)),
    )


###############################################################################
###############################################################################

def generate_data(global_shape, dtype, distribution_strategy,
                  strictly_positive=False):
134
135
136
137
138
    if global_shape == ():
        obj = distributed_data_object(global_shape=(), global_data=42.,
                                      distribution_strategy='not')
        global_a = np.array(42)
    elif distribution_strategy in global_distribution_strategies:
theos's avatar
theos committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        a = np.arange(np.prod(global_shape))
        a -= np.prod(global_shape) // 2

        a = a * (1 + 1j)
        if strictly_positive:
            a = abs(a)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            a = a.reshape(global_shape).astype(dtype)
        obj = distributed_data_object(
                                a, distribution_strategy=distribution_strategy)
        global_a = a

    elif distribution_strategy in local_distribution_strategies:
        local_shape = list(global_shape)
        if rank % 2 == 1:
            local_shape[0] = 0
        else:
            local_shape[0] = global_shape[0] // np.ceil(size / 2.)
159
160
161
            number_of_extras = (global_shape[0] -
                                local_shape[0] * np.ceil(size / 2.))
            if number_of_extras > rank//2:
theos's avatar
theos committed
162
                local_shape[0] += 1
163
            local_shape[0] = int(local_shape[0])
theos's avatar
theos committed
164
165
166
167
168
169
170
171
172
        local_shape = tuple(local_shape)

        a = np.arange(np.prod(local_shape))
        a -= np.prod(local_shape) // 2

        a = a * (1 + 1j)
        if strictly_positive:
            a = abs(a)

theos's avatar
theos committed
173
174
        a *= (rank + 1)

theos's avatar
theos committed
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
210
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            a = a.reshape(local_shape).astype(dtype)
        obj = distributed_data_object(
                    local_data=a, distribution_strategy=distribution_strategy)
        a_list = comm.allgather(a)
        global_a = np.concatenate(a_list)

    return (global_a, obj)


###############################################################################
###############################################################################


class Test_Globaltype_Initialization(unittest.TestCase):

    @parameterized.expand(
        itertools.product([(1,), (7,), (78, 11), (256, 256)],
                          all_datatypes,
                          global_distribution_strategies,
                          [True, False]),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_global_shape_and_dtype(self,
                                                        global_shape,
                                                        dtype,
                                                        distribution_strategy,
                                                        hermitian):
        obj = distributed_data_object(
                                  global_shape=global_shape,
                                  dtype=dtype,
                                  distribution_strategy=distribution_strategy,
                                  hermitian=hermitian)

        assert_equal(obj.dtype, dtype)
        assert_equal(obj.shape, global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)
        assert_equal(obj.hermitian, hermitian)
        assert_equal(obj.data.dtype, np.dtype(dtype))


###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (77, 11), (256, 256)],
                          all_datatypes,
                          global_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_global_data(self,
                                             global_shape,
                                             dtype,
                                             distribution_strategy):

        a = (np.random.rand(*global_shape) * 100 - 50).astype(dtype)
        obj = distributed_data_object(
                                  global_data=a,
                                  distribution_strategy=distribution_strategy)
        assert_equal(obj.dtype, np.dtype(dtype))
        assert_equal(obj.shape, global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)
        assert_equal(obj.data.dtype, np.dtype(dtype))

###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (77, 11), (256, 256)],
                          ['tuple', 'list'],
                          all_datatypes,
                          global_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_tuple_and_list(self,
                                                global_shape,
                                                global_data_type,
                                                dtype,
                                                distribution_strategy):

        a = (np.random.rand(*global_shape) * 100 - 50).astype(dtype)
        if global_data_type == 'list':
            a = a.tolist()
        elif global_data_type == 'tuple':
            a = tuple(a.tolist())

        obj = distributed_data_object(
                                global_data=a,
                                distribution_strategy=distribution_strategy)
        assert_equal(obj.shape, global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)

###############################################################################

    @parameterized.expand(itertools.product([
        [1, (13, 7), np.dtype('float64'),
         (13, 7), np.dtype('float64')],
        [np.array([1]), (13, 7), np.dtype('float64'),
         (1,), np.dtype('float64')],
        [np.array([[1., 2.], [3., 4.]]), (13, 7), np.dtype('int'),
         (2, 2), np.dtype('int')],
        [None, (10, 10), None,
         (10, 10), np.dtype('float64')],
274
275
276
277
        [1., None, None,
         (), np.dtype('float64')],
        [None, (), None,
         (), np.dtype('float64')],
theos's avatar
theos committed
278
279
    ], global_distribution_strategies),
        testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
280
281
282
283
284
285
    def test_special_init_cases(self, para, distribution_strategy):
        (global_data,
         global_shape,
         dtype,
         expected_shape,
         expected_dtype) = para
theos's avatar
theos committed
286
287
288
289
290
291
292
293
294
295
        obj = distributed_data_object(
                                  global_data=global_data,
                                  global_shape=global_shape,
                                  dtype=dtype,
                                  distribution_strategy=distribution_strategy)
        assert_equal(obj.shape, expected_shape)
        assert_equal(obj.dtype, expected_dtype)

###############################################################################

296
    if FOUND['h5py']:
theos's avatar
theos committed
297
298
299
        @parameterized.expand(itertools.product(hdf5_test_paths,
                                                hdf5_distribution_strategies),
                              testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
300
301
        def test_hdf5_init(self, para, distribution_strategy):
            (alias, path) = para
theos's avatar
theos committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
            obj = distributed_data_object(
                                  global_data=1.,
                                  global_shape=(12, 6),
                                  alias=alias,
                                  path=path,
                                  distribution_strategy=distribution_strategy)
            assert_equal(obj.dtype, np.complex128)
            assert_equal(obj.shape, (13, 7))

###############################################################################

    @parameterized.expand(
        itertools.product(
            [(None, None, None, None, None),
             (None, None, np.int_, None, None),
             (None, None, None, np.array([1, 2, 3]), (3,)),
                (None, None, np.int_, None, (3,))],
            global_distribution_strategies),
        testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
321
    def test_failed_init_on_unsufficient_parameters(self, para,
theos's avatar
theos committed
322
                                                    distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
323
324
325
326
        (global_data,
         global_shape,
         dtype,
         local_data, local_shape) = para
theos's avatar
theos committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        assert_raises(ValueError,
                      lambda: distributed_data_object(
                          global_data=global_data,
                          global_shape=global_shape,
                          dtype=dtype,
                          local_data=local_data,
                          local_shape=local_shape,
                          distribution_strategy=distribution_strategy))

###############################################################################

    if size > 1:
        @parameterized.expand(
            itertools.product(
                [(None, (10, rank, 10), np.dtype('int'), None, None),
                 (None, (2, 2),
                  np.dtype('int') if (rank == 0) else np.dtype('float'),
                  None, None), ],
                global_distribution_strategies),
            testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
347
        def test_failed_init_unsufficient_params_mpi(self, para,
theos's avatar
theos committed
348
                                                     distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
349
350
351
352
353
            (global_data,
             global_shape,
             dtype,
             local_data,
             local_shape) = para
theos's avatar
theos committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
496
497
498
            assert_raises(ValueError,
                          lambda: distributed_data_object(
                              global_data=global_data,
                              global_shape=global_shape,
                              dtype=dtype,
                              local_data=local_data,
                              local_shape=local_shape,
                              distribution_strategy=distribution_strategy))


###############################################################################

    @parameterized.expand(
        itertools.product([(0,), (1, 0), (0, 1), (25, 0, 10), (0, 0)],
                          global_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_init_with_zero_type_shape(self, global_shape,
                                       distribution_strategy):
        obj = distributed_data_object(
                                  global_shape=global_shape,
                                  dtype=np.int,
                                  distribution_strategy=distribution_strategy)
        assert_equal(obj.shape, global_shape)


###############################################################################
###############################################################################

class Test_Localtype_Initialization(unittest.TestCase):

    ##########################################################################
    @parameterized.expand(
        itertools.product([(1,), (7,), (78, 11), (256, 256)],
                          [False, True],
                          all_datatypes,
                          local_distribution_strategies,
                          [True, False]),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_local_shape_and_dtype(self,
                                                       local_shape,
                                                       different_shapes,
                                                       dtype,
                                                       distribution_strategy,
                                                       hermitian):

        if different_shapes is True:
            expected_global_shape = np.array(local_shape)
            expected_global_shape[0] *= size * (size - 1) / 2
            expected_global_shape = tuple(expected_global_shape)
            local_shape = list(local_shape)
            local_shape[0] *= rank
            local_shape = tuple(local_shape)
        else:
            expected_global_shape = np.array(local_shape)
            expected_global_shape[0] *= size
            expected_global_shape = tuple(expected_global_shape)

        obj = distributed_data_object(
                                  local_shape=local_shape,
                                  dtype=dtype,
                                  distribution_strategy=distribution_strategy,
                                  hermitian=hermitian)

        assert_equal(obj.dtype, dtype)
        assert_equal(obj.shape, expected_global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)
        assert_equal(obj.hermitian, hermitian)
        assert_equal(obj.data.dtype, np.dtype(dtype))


###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (77, 11), (256, 256)],
                          [False, True],
                          all_datatypes,
                          local_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_local_data(self,
                                            local_shape,
                                            different_shapes,
                                            dtype,
                                            distribution_strategy):
        if different_shapes is True:
            expected_global_shape = np.array(local_shape)
            expected_global_shape[0] *= size * (size - 1) / 2
            expected_global_shape = tuple(expected_global_shape)
            local_shape = list(local_shape)
            local_shape[0] *= rank
            local_shape = tuple(local_shape)
        else:
            expected_global_shape = np.array(local_shape)
            expected_global_shape[0] *= size
            expected_global_shape = tuple(expected_global_shape)

        a = (np.random.rand(*local_shape) * 100 - 50).astype(dtype)
        obj = distributed_data_object(
                                  local_data=a,
                                  distribution_strategy=distribution_strategy)

        assert_equal(obj.dtype, np.dtype(dtype))
        assert_equal(obj.shape, expected_global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)
        assert_equal(obj.data.dtype, np.dtype(dtype))

###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (77, 11)],
                          ['tuple', 'list'],
                          all_datatypes,
                          local_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_successful_init_via_tuple_and_list(self,
                                                local_shape,
                                                local_data_type,
                                                dtype,
                                                distribution_strategy):

        a = (np.random.rand(*local_shape) * 100).astype(dtype)
        if local_data_type == 'list':
            a = a.tolist()
        elif local_data_type == 'tuple':
            a = tuple(a.tolist())
        obj = distributed_data_object(
                                local_data=a,
                                distribution_strategy=distribution_strategy)

        expected_global_shape = np.array(local_shape)
        expected_global_shape[0] *= size
        expected_global_shape = tuple(expected_global_shape)

        assert_equal(obj.shape, expected_global_shape)
        assert_equal(obj.distribution_strategy, distribution_strategy)


###############################################################################

    @parameterized.expand(itertools.product([
        [1, (13, 7), np.float64, (13 * size, 7), np.float64],
        [np.array([1]), (13, 7), np.float64, (1 * size,), np.float64],
        [np.array([[1., 2.], [3., 4.]]), (13, 7),
         np.int, (2 * size, 2), np.int]
    ], local_distribution_strategies),
        testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
499
    def test_special_init_cases(self, para,
theos's avatar
theos committed
500
                                distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
501
502
503
504
505
        (local_data,
         local_shape,
         dtype,
         expected_shape,
         expected_dtype) = para
theos's avatar
theos committed
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
538
539
540
541
542
543
544
545
546
547
548
549
        obj = distributed_data_object(
                                  local_data=local_data,
                                  local_shape=local_shape,
                                  dtype=dtype,
                                  distribution_strategy=distribution_strategy)

        assert_equal(obj.shape, expected_shape)
        assert_equal(obj.dtype, expected_dtype)

###############################################################################

    def test_special_init_from_d2o_cases(self):
        global_shape = (8, 8)
        dtype = np.dtype('int')
        (a, obj) = generate_data(global_shape, dtype, 'equal')
        # Given dtype overwrites the one from data
        p = distributed_data_object(global_data=obj,
                                    dtype=np.dtype('float'),
                                    distribution_strategy='freeform')
        assert_equal(p.dtype, np.dtype('float'))
        # Global d2o overwrites local data
        p = distributed_data_object(global_data=obj,
                                    local_data=np.array([1, 2, 3]),
                                    distribution_strategy='freeform')
        assert_equal(obj.get_full_data(), p.get_full_data())
        # Global d2o overwrites local shapes
        p = distributed_data_object(global_data=obj,
                                    local_shape=(4, 4),
                                    distribution_strategy='freeform')
        assert_equal(obj.get_full_data(), p.get_full_data())


###############################################################################

    @parameterized.expand(
        itertools.product(
            [(None, None, None, None, None),
             (None, (8, 8), None, None, None),
                (None, None, np.int_, None, None),
                (1, None, None, None, None),
             (np.array([1, 2, 3]), (3,), None, None, None),
                (None, (4, 4), np.int_, None, None)],
            local_distribution_strategies),
        testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
550
    def test_failed_init_on_unsufficient_parameters(self, para,
theos's avatar
theos committed
551
                                                    distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
552
553
554
555
556
        (global_data,
         global_shape,
         dtype,
         local_data,
         local_shape) = para
theos's avatar
theos committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
        assert_raises(ValueError,
                      lambda: distributed_data_object(
                          global_data=global_data,
                          global_shape=global_shape,
                          dtype=dtype,
                          local_data=local_data,
                          local_shape=local_shape,
                          distribution_strategy=distribution_strategy))

###############################################################################

    if size > 1:
        @parameterized.expand(
            itertools.product(
                [(None, None, np.dtype('int'), None, (2, rank, 3)),
                 (None, None, None, np.arange(2 * rank).reshape((2, rank)),
                  None),
                 (None, None,
                  np.dtype('int') if (rank == 0) else np.dtype('float'),
                  None, (2, 2))],
                local_distribution_strategies),
            testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
579
        def test_failed_init_unsufficient_params_mpi(self, para,
theos's avatar
theos committed
580
                                                     distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
581
582
583
584
585
            (global_data,
             global_shape,
             dtype,
             local_data,
             local_shape) = para
theos's avatar
theos committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
            assert_raises(ValueError,
                          lambda: distributed_data_object(
                              global_data=global_data,
                              global_shape=global_shape,
                              dtype=dtype,
                              local_data=local_data,
                              local_shape=local_shape,
                              distribution_strategy=distribution_strategy))

##########################################################################

    @parameterized.expand(
        itertools.product([(0,), (1, 0), (0, 1), (25, 0, 10), (0, 0)],
                          local_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_init_with_zero_type_shape(self, local_shape,
                                       distribution_strategy):

        obj = distributed_data_object(
                                   local_shape=local_shape,
                                   dtype=np.int,
                                   distribution_strategy=distribution_strategy)

        expected_global_shape = np.array(local_shape)
        expected_global_shape[0] *= size
        expected_global_shape = tuple(expected_global_shape)

        assert_equal(obj.shape, expected_global_shape)


###############################################################################
###############################################################################

class Test_init_from_existing_d2o(unittest.TestCase):

    @parameterized.expand(
        itertools.product(all_distribution_strategies,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_simple_init_from_existing_d2o(self, old_strat, new_strat):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype, old_strat)
        p = distributed_data_object(global_data=obj,
                                    distribution_strategy=new_strat)
        if old_strat == 'not' and new_strat in local_distribution_strategies:
            old_blown_up = np.concatenate([obj.get_full_data(), ] * size)
            assert_equal(old_blown_up, p.get_full_data())
        else:
            assert_equal(obj.get_full_data(), p.get_full_data())
        assert_equal(obj.distribution_strategy, old_strat)
        assert_equal(p.distribution_strategy, new_strat)


###############################################################################
###############################################################################

class Test_set_get_full_and_local_data(unittest.TestCase):

    @parameterized.expand(
        itertools.product([(1,), (7,), (2, 7), (77, 11), (256, 256)],
                          all_datatypes,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_init_data_and_get_full_and_local_data(self,
                                                   global_shape,
                                                   dtype,
                                                   distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.get_full_data(), a)

###############################################################################

    if FOUND['h5py']:
        @parameterized.expand(
            itertools.product(hdf5_test_paths, hdf5_distribution_strategies),
            testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
664
665
        def test_loading_hdf5_file(self, para, distribution_strategy):
            (alias, path) = para
theos's avatar
theos committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
            a = np.arange(13 * 7).reshape((13, 7)).astype(np.float)
            b = a[::-1, ::-1]
            a = a + 1j * b
            obj = distributed_data_object(
                                  alias=alias,
                                  path=path,
                                  distribution_strategy=distribution_strategy)
            assert_equal(obj.get_full_data(), a)

###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (2, 7), (77, 11), (256, 256)],
                          all_datatypes,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_set_get_full_data(self,
                               global_shape,
                               dtype,
                               distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        new_a = np.array(5 * a, copy=True, dtype=dtype)
        obj.set_full_data(new_a)
        assert_equal(obj.get_full_data(), new_a)

###############################################################################

    @parameterized.expand(
        itertools.product([(1,), (7,), (2, 7), (77, 11), (256, 256)],
                          all_datatypes,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_get_set_local_data(self,
                                global_shape,
                                dtype,
                                distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        b = obj.get_local_data()
        c = (np.random.random(b.shape) * 100).astype(np.dtype(dtype))
        obj.set_local_data(data=c)
        assert_equal(obj.get_local_data(), c)


##########################################################################
##########################################################################

class Test_slicing_get_set_data(unittest.TestCase):

    @parameterized.expand(
        itertools.product(
            [(4, 4, 4)],  # (20,21), (256,256)],
            [np.dtype('uint'), np.dtype('int'), np.dtype('float')],
            # all_datatypes,
            all_distribution_strategies,
            [slice(None, None, None),
             slice(5, 18),
             slice(5, 18, 4),
             slice(18, 5, -3),
             slice(6, 14),
             slice(6, 14, 4),
             slice(14, 6, -4),
             slice(5, None),
             slice(5, None, 3),
             slice(None, 5, -2),
             slice(None, 10),
             slice(None, 10, 3),
             slice(10, None, -2),
             slice(None, None, 3),
             slice(None, None, -3),
             slice(2, 2),
             slice(2, 2, 4),
             slice(2, 2, -1),
             slice(2, 2, -4),
             slice(-5, -2),
             slice(-1000, 300),
             slice(5, 300),
             slice(1000, -300, -1),
             slice(1000, -300, -3),
             (3,),
             (2, slice(5, 18)),
             (slice(None), 2),
             (slice(5, 18), slice(18, 5, -1))],
            all_distribution_strategies + ['np']),
        testcase_func_name=custom_name_func)
    def test_get_set_slicing_data(self,
                                  global_shape,
                                  dtype,
                                  distribution_strategy,
                                  slice_tuple,
                                  from_distribution_strategy):

        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)

        assert_equal(obj[slice_tuple].get_full_data(), a[slice_tuple])

        if from_distribution_strategy == 'np':
            b = a.copy() * 100
            obj[slice_tuple] = b[slice_tuple]
            a[slice_tuple] = b[slice_tuple]
        else:
            (b, p) = generate_data(global_shape, dtype,
                                   from_distribution_strategy)
            b *= 100
            p *= 100
            obj[slice_tuple] = p[slice_tuple]
            a[slice_tuple] = b[slice_tuple]

        assert_equal(obj.get_full_data(), a)

        a[slice_tuple] = 111
        obj[slice_tuple] = 111

        assert_equal(obj.get_full_data(), a)


###############################################################################

    @parameterized.expand(all_distribution_strategies,
                          testcase_func_name=custom_name_func)
    def test_get_single_value_from_d2o(self, distribution_strategy):
        (a, obj) = generate_data((4,), np.dtype('float'),
                                 distribution_strategy)
        assert_equal(obj[0], a[0])


###############################################################################

    @parameterized.expand(
        itertools.product(all_distribution_strategies,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_single_row_from_d2o(self, distribution_strategy1,
                                 distribution_strategy2):
        (a, obj) = generate_data((8, 8), np.dtype('float'),
                                 distribution_strategy1)
        (b, p) = generate_data((8,), np.dtype('float'),
                               distribution_strategy2)
        a[4] = b
        obj[4] = p
        assert_equal(obj.get_full_data(), a)


###############################################################################
###############################################################################

class Test_boolean_get_set_data(unittest.TestCase):

    @parameterized.expand(
        itertools.product(
            [(4, 4)],  # (20,21)],
            all_datatypes,
            all_distribution_strategies,
            all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_boolean_get_data(self,
                              global_shape,
                              dtype,
                              distribution_strategy_1,
                              distribution_strategy_2):

        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy_1)

        b = ((a < -5) + (a > 4))

        p = obj.copy_empty(dtype=np.dtype('bool'),
                           distribution_strategy=distribution_strategy_2)
        p[:] = b

        assert_equal(obj[b].get_full_data(), a[b])
        assert_equal(obj[p].get_full_data(), a[b])

###############################################################################

    @parameterized.expand(
        itertools.product(
            [(4, 4), (20, 21)],
            all_datatypes,
            all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_boolean_set_data(self,
                              global_shape,
                              dtype,
                              distribution_strategy):

        (a, obj_mem) = generate_data(global_shape, dtype,
                                     distribution_strategy)

        p = ((obj_mem < -5) + (obj_mem > 4))
        b = ((a < -5) + (a > 4))
        c = a[b] * 100
        q = obj_mem[p] * 100

        a[b] = c

        obj = obj_mem.copy()
        obj[b] = c
        assert_equal(obj.get_full_data(), a)

        obj = obj_mem.copy()
        obj[b] = q
        assert_equal(obj.get_full_data(), a)

        obj = obj_mem.copy()
        obj[p] = q
        assert_equal(obj.get_full_data(), a)

###############################################################################

    @parameterized.expand(all_distribution_strategies)
    def test_boolean_set_data_of_a_scalar(self, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)

        b = a.copy()
        b[a < 3] = 14

        p = obj.copy()
        p[obj < 3] = 14
        assert_equal(p.get_full_data(), b)

        p = obj.copy()
        p[a < 3] = 14
        assert_equal(p.get_full_data(), b)


###############################################################################
###############################################################################

class Test_list_get_set_data(unittest.TestCase):

    @parameterized.expand(
        itertools.product(
            [(4, 4, 4)],
            all_datatypes,
            all_distribution_strategies,
            all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_list_get_data(self,
                           global_shape,
                           dtype,
                           distribution_strategy_1,
                           distribution_strategy_2):

        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy_1)
        w = np.where(a > 28)
        p = obj.copy(distribution_strategy=distribution_strategy_2)
        wo = (p > 28).where()

        assert_equal(obj[w].get_full_data(), a[w])
        assert_equal(obj[wo].get_full_data(), a[w])

        w0 = 3
        w1 = np.array([0, 1, 3])
        w1o = distributed_data_object(global_data=w1,
                                      distribution_strategy='equal')

        w = [w0, w1, w1]
        wo = [w0, w1, w1o]
        assert_equal(obj[w].get_full_data(), a[w])
        assert_equal(obj[wo].get_full_data(), a[w])

        w = [w1, w0, w1]
        wo = [w1, w0, w1o]
        assert_equal(obj[w].get_full_data(), a[w])
        assert_equal(obj[wo].get_full_data(), a[w])

        w = [w1, w0, w1]
        wo = [w1o, w0, w1]
        assert_equal(obj[w].get_full_data(), a[w])
        assert_equal(obj[wo].get_full_data(), a[w])


#############################################################################

    @parameterized.expand(
        itertools.product(
            [(4, 4), (20, 21)],
            all_datatypes,
            all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_list_set_data(self,
                           global_shape,
                           dtype,
                           distribution_strategy):

        (a, obj_mem) = generate_data(global_shape, dtype,
                                     distribution_strategy)

        p = ((obj_mem < -5) + (obj_mem > 4)).where()
        b = np.where((a < -5) + (a > 4))
        c = a[b] * 100
        q = obj_mem[p] * 100

        a[b] = c

        obj = obj_mem.copy()
        obj[b] = c
        assert_equal(obj.get_full_data(), a)

        obj = obj_mem.copy()
        obj[b] = q
        assert_equal(obj.get_full_data(), a)

        obj = obj_mem.copy()
        obj[p] = q
        assert_equal(obj.get_full_data(), a)

###############################################################################

    @parameterized.expand(all_distribution_strategies)
    def test_list_set_data_of_a_scalar(self, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)

        b = a.copy()
        b[np.where(a < 3)] = 14

        p = obj.copy()
        p[(obj < 3).where()] = 14
        assert_equal(p.get_full_data(), b)

        p = obj.copy()
        p[np.where(a < 3)] = 14
        assert_equal(p.get_full_data(), b)


###############################################################################
###############################################################################

class Test_non_local_keys(unittest.TestCase):

    @parameterized.expand(all_distribution_strategies)
    def test_get_from_non_local_keys(self, distribution_strategy):
        global_shape = (2 * size, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        local_scalar = rank
        p = obj.get_data(local_scalar, local_keys=True)
        assert_equal(p.get_local_data(), a[local_scalar])

        local_slice = (slice(0, rank),)
        p = obj.get_data(local_slice, local_keys=True)
        assert_equal(p.get_local_data(), a[local_slice])

        local_bool = (obj < rank)
        p = obj.get_data(local_bool, local_keys=True)
        assert_equal(p.get_local_data(), a[local_bool.get_full_data()])

        local_list = (np.array([rank, 2 * rank]), np.array([1, 3]))
        p = obj.get_data(local_list, local_keys=True)
        assert_equal(p.get_local_data(), a[local_list])

###############################################################################

    @parameterized.expand(all_distribution_strategies)
    def test_set_from_non_local_keys(self, distribution_strategy):
        global_shape = (2 * size, 8)
        dtype = np.dtype('float')
        (a_backup, obj_backup) = generate_data(global_shape, dtype,
                                               distribution_strategy)

        local_scalar_key = rank

        a = a_backup.copy()
        b = np.expand_dims(np.arange(size), axis=1).repeat(8, axis=1)**2
        a[np.arange(size)] = b

        local_data_update = rank**2
        obj = obj_backup.copy()
        obj.set_data(local_data_update, local_scalar_key, local_keys=True)
        assert_equal(obj.get_full_data(), a)

        local_data_update = np.ones((8,)) * (rank**2)
        obj = obj_backup.copy()
        obj.set_data(local_data_update, local_scalar_key, local_keys=True)
        assert_equal(obj.get_full_data(), a)

Theo Steininger's avatar
Theo Steininger committed
1053
1054
1055
1056
        local_data_update_list = [np.ones((8,)) * (z**2) for z in range(size)]
        local_data_update_list = \
            [distributed_data_object(z, distribution_strategy='equal')
             for z in local_data_update_list]
theos's avatar
theos committed
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
        obj = obj_backup.copy()
        obj.set_data(local_data_update_list[rank], local_scalar_key,
                     local_keys=True)
        assert_equal(obj.get_full_data(), a)

###############################################################################


###############################################################################
###############################################################################

class Test_set_data_via_injection(unittest.TestCase):

    @parameterized.expand(
        itertools.product([
            ((10, 10), (slice(2, 8), slice(3, 5)),
             (9, 11), (slice(1, 7), slice(4, 6))),
            ((10, 10), (slice(8, 2, -1), slice(3, 5)),
             (9, 11), (slice(1, 7), slice(4, 6))),
            ((10, 10), (slice(2, 8), slice(3, 5)),
             (9, 11), (slice(7, 1, -1), slice(4, 6))),
            ((10, 10), (slice(2, 8, 3), slice(3, 5)),
             (9, 11), (slice(1, 5, 2), slice(4, 6))),
            ((10, 10), (slice(8, 2, -3), slice(3, 5)),
             (9, 11), (slice(1, 5, 2), slice(4, 6))),
            ((10, 10), (slice(2, 8, 3), slice(3, 5)),
             (9, 11), (slice(5, 1, -2), slice(4, 6))),
            ((10, 10), (slice(None, None, 3), slice(3, 5)),
             (9, 11), (slice(None, 4), slice(4, 6))),
            ((10, 10), (slice(None, None, -3), slice(3, 5)),
             (9, 11), (slice(3, None, -1), slice(4, 6)))
        ],
            all_distribution_strategies
        ), testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
1091
    def test_set_data_via_injection(self, para,
theos's avatar
theos committed
1092
                                    distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
1093
1094
1095
1096
        (global_shape_1,
         slice_tuple_1,
         global_shape_2,
         slice_tuple_2) = para
theos's avatar
theos committed
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
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape_1, dtype,
                                 distribution_strategy)

        (b, p) = generate_data(global_shape_2, dtype,
                               distribution_strategy)

        obj.set_data(to_key=slice_tuple_1,
                     data=p,
                     from_key=slice_tuple_2)
        a[slice_tuple_1] = b[slice_tuple_2]
        assert_equal(obj.get_full_data(), a)


###############################################################################
###############################################################################

def scalar_only_square(x):
    if np.isscalar(x):
        return x * x
    else:
        raise ValueError


class Test_copy_and_copy_empty(unittest.TestCase):

    @parameterized.expand(
        itertools.chain(
            itertools.product([None, (8, 7)],
                              [None],
                              [None],
                              global_distribution_strategies,
                              global_distribution_strategies),

            itertools.product([None],
                              all_datatypes,
                              all_datatypes,
                              global_distribution_strategies,
                              global_distribution_strategies)),
        testcase_func_name=custom_name_func)
    def test_copy_empty(self,
                        new_shape,
                        old_dtype,
                        new_dtype,
                        new_distribution_strategy,
                        old_distribution_strategy):
        old_shape = (10, 10)
        (a, obj) = generate_data(old_shape, old_dtype,
                                 old_distribution_strategy)

        if new_distribution_strategy in global_distribution_strategies:
            p = obj.copy_empty(global_shape=new_shape,
                               dtype=new_dtype,
                               distribution_strategy=new_distribution_strategy)
            if new_shape is not None:
                assert_equal(p.shape, new_shape)
        elif new_distribution_strategy in local_distribution_strategies:
            p = obj.copy_empty(local_shape=new_shape,
                               dtype=new_dtype,
                               distribution_strategy=new_distribution_strategy)
            if new_shape is not None:
                assert_equal(p.local_shape, new_shape)
        else:
            raise ValueError(
                "ERROR: distribution_strategy neither in local nor global.")

        if new_dtype is not None:
            assert_equal(p.dtype, new_dtype)
        if new_distribution_strategy is not None:
            assert_equal(p.distribution_strategy, new_distribution_strategy)

    def test_copy_empty_from_not_to_freeform(self):
        global_shape = (10, 10)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype, 'not')
        p = obj.copy_empty(distribution_strategy='freeform')
        assert_equal(p.shape, global_shape)


###############################################################################

    @parameterized.expand([
        (np.float_, None),
        (None, 'freeform')
    ], testcase_func_name=custom_name_func)
    def test_copy(self,
                  new_dtype,
                  new_distribution_strategy):
        old_shape = (2, 2)
        old_dtype = np.int
        old_distribution_strategy = 'equal'
        obj = distributed_data_object(
                              global_shape=old_shape,
                              dtype=old_dtype,
                              distribution_strategy=old_distribution_strategy)
        p = obj.copy(dtype=new_dtype,
                     distribution_strategy=new_distribution_strategy)
        if new_dtype is not None:
            assert_equal(p.dtype, new_dtype)
        if new_distribution_strategy is not None:
            assert_equal(p.distribution_strategy, new_distribution_strategy)

        assert_equal(p.get_full_data(), obj.get_full_data())

###############################################################################

    @parameterized.expand(
        itertools.product([
            (scalar_only_square, False, None),
            (lambda x: x * x, False, None),
            (lambda x: x * x, True, None),
            (lambda x: x * x, True, np.int),
        ], all_distribution_strategies), testcase_func_name=custom_name_func)
Theo Steininger's avatar
Theo Steininger committed
1210
    def test_apply_scalar_function(self, para,
theos's avatar
theos committed
1211
                                   distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
1212
        (square_function, inplace, dtype) = para
theos's avatar
theos committed
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
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
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
        global_shape = (8, 8)
        old_dtype = np.float64
        (a, obj) = generate_data(global_shape, old_dtype,
                                 distribution_strategy)
        p = obj.apply_scalar_function(function=square_function,
                                      inplace=inplace,
                                      dtype=dtype)

        if inplace is True:
            assert_equal(p.get_full_data(), a * a)
            assert_equal(id(p), id(obj))
            assert_equal(p.dtype, old_dtype)
        else:
            assert_equal(p.get_full_data(), (a * a).astype(dtype))
            if dtype is not None:
                assert_equal(p.dtype, dtype)
            assert_raises(AssertionError,
                          lambda: assert_equal(id(p), id(obj)))

###############################################################################

    def test_conserve_hermitianity_apply_scalar(self):
        obj = distributed_data_object(global_shape=(2, 2),
                                      dtype=np.dtype('float'),
                                      hermitian=True,
                                      distribution_strategy='equal')
        obj.apply_scalar_function(np.exp, inplace=True)
        assert_equal(obj.hermitian, True)
        obj.apply_scalar_function(np.log, inplace=True)
        assert_equal(obj.hermitian, True)

###############################################################################
    @parameterized.expand(all_distribution_strategies)
    def test_apply_generator(self, distribution_strategy):
        global_shape = (7, 5)
        start_dtype = np.dtype('complex')
        generator_dtype = np.dtype('int')
        (a, obj) = generate_data(global_shape, start_dtype,
                                 distribution_strategy)
        obj.apply_generator(lambda shape: np.ones(shape=shape,
                                                  dtype=generator_dtype))
        assert_equal(obj.get_full_data(), np.ones(shape=global_shape))
        assert_equal(obj.dtype, start_dtype)

###############################################################################
###############################################################################


class Test_unary_and_binary_operations(unittest.TestCase):

    @parameterized.expand(
        itertools.product(['__pos__', '__neg__', '__abs__'],
                          [np.dtype('int'), np.dtype('complex64'),
                           np.dtype('complex128')],
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_unary_operations(self, function, dtype, distribution_strategy):
        global_shape = (8, 8)
        a, obj = generate_data(global_shape, dtype, distribution_strategy)
        p = getattr(obj, function)()
        b = getattr(a, function)()
        assert_equal(p.get_full_data(), b)
        assert_equal(p.dtype, b.dtype)

###############################################################################

    def test_len(self):
        temp_shape = (7, 13)
        a = np.arange(np.prod(temp_shape)).reshape(temp_shape)
        obj = distributed_data_object(a,
                                      distribution_strategy='equal')
        assert_equal(len(obj), len(a))

##############################################################################

    def test_conjugate(self):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        obj = distributed_data_object(a,
                                      distribution_strategy='equal')
        assert_equal(obj.conjugate().get_full_data(), np.conjugate(a))
        assert_equal(obj.conj().get_full_data(), np.conj(a))

###############################################################################

    @parameterized.expand(all_distribution_strategies)
    def test_is_real_is_complex(self, distribution_strategy):
        if distribution_strategy in local_distribution_strategies:
            stored_distribution_strategy = distribution_strategy
            distribution_strategy = 'equal'
        else:
            stored_distribution_strategy = None

        global_shape = (8, 7)
        a = np.arange(np.prod(global_shape)).reshape(global_shape)
        a = a + ((-1)**a + 1) * 1j
        obj = distributed_data_object(
                                a, distribution_strategy=distribution_strategy)

        if stored_distribution_strategy is not None:
            (b, p) = generate_data(
                            global_shape,
                            np.dtype('complex'),
                            distribution_strategy=stored_distribution_strategy)
            p.set_data(from_key=(slice(None),), data=a, to_key=(slice(None),))
            obj = p

        assert_equal(obj.isreal().get_full_data(), np.isreal(a))
        assert_equal(obj.iscomplex().get_full_data(), np.iscomplex(a))

###############################################################################

    @parameterized.expand(all_distribution_strategies)
    def test_is_nan_inf(self, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype, distribution_strategy)
        a[0, 0] = np.nan
        a[0, 1] = np.inf
        obj[0, 0] = np.nan
        obj[0, 1] = np.inf

        assert_equal(obj.isnan().get_full_data(), np.isnan(a))
        assert_equal(obj.isinf().get_full_data(), np.isinf(a))
        assert_equal(obj.isfinite().get_full_data(), np.isfinite(a))
        assert_equal(obj.nan_to_num().get_full_data(), np.nan_to_num(a))

###############################################################################

    @parameterized.expand(
        itertools.product(binary_non_inplace_operators,
                          all_distribution_strategies,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_binary_operations_with_d2o(self, function, strat1, strat2):
        global_shape = (8, 8)
        (a, obj) = generate_data(global_shape, np.dtype('float'), strat1)
        (b, p) = generate_data(global_shape, np.dtype('float'), strat2)

        b **= 3
        p **= 3
        assert_equal(getattr(obj, function)(p).get_full_data(),
                     getattr(a, function)(b))

###############################################################################

    @parameterized.expand(binary_non_inplace_operators,
                          testcase_func_name=custom_name_func)
    def test_binary_operations_with_nparray(self, function):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        b = a**3
        obj = distributed_data_object(a, distribution_strategy='equal')

        assert_equal(getattr(obj, function)(b).get_full_data(),
                     getattr(a, function)(b))

###############################################################################

    @parameterized.expand(binary_non_inplace_operators,
                          testcase_func_name=custom_name_func)
    def test_binary_operations_with_scalar(self, function):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        b = 2 + 0.5j
        obj = distributed_data_object(a, distribution_strategy='equal')

        assert_equal(getattr(obj, function)(b).get_full_data(),
                     getattr(a, function)(b))

1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
###############################################################################

    @parameterized.expand(
        itertools.product(binary_non_inplace_operators,
                          all_distribution_strategies,
                          all_distribution_strategies,
                          [(1, 8, 9), (7, 1, 9), (1, 1, 1)]),
        testcase_func_name=custom_name_func)
    def test_binary_operations_with_subslice_d2o(self, function, strat1,
                                                 strat2, reduced_shape):
        full_shape = (7, 8, 9)
        (a, obj) = generate_data(full_shape, np.dtype('float'), strat1)
        (b, p) = generate_data(reduced_shape, np.dtype('float'), strat2)

        b **= 3
        p **= 3
        assert_equal(getattr(obj, function)(p).get_full_data(),
                     getattr(a, function)(b))

theos's avatar
theos committed
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
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
###############################################################################

    def test_binary_operation_with_dtype_conversion(self):
        temp_shape = (8, 8)
        a = np.arange(np.prod(temp_shape)).reshape(temp_shape)
        obj = distributed_data_object(a, distribution_strategy='equal')
        assert_equal((obj + 1j).get_full_data(), a + 1j)

###############################################################################

    @parameterized.expand(binary_non_inplace_operators,
                          testcase_func_name=custom_name_func)
    def test_binary_operations_with_one_dimensional_d2o(self, function):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        b = distributed_data_object(global_data=[2 + 0.5j],
                                    distribution_strategy='not')
        obj = distributed_data_object(a, distribution_strategy='equal')

        assert_equal(getattr(obj, function)(b).get_full_data(),
                     getattr(a, function)(b))

###############################################################################

    @parameterized.expand(binary_non_inplace_operators,
                          testcase_func_name=custom_name_func)
    def test_binary_operations_with_one_dimensional_nparray(self, function):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        b = np.array([2 + 0.5j, ])
        obj = distributed_data_object(a, distribution_strategy='equal')

        assert_equal(getattr(obj, function)(b).get_full_data(),
                     getattr(a, function)(b))

###############################################################################

    @parameterized.expand(binary_inplace_operators,
                          testcase_func_name=custom_name_func)
    def test_inplace_binary_operations_with_d2o(self, function):
        temp_shape = (8, 8)
        a = ((np.arange(np.prod(temp_shape)).reshape(temp_shape) + 1) * 2 -
             (np.prod(temp_shape) + 1)) / 3
        a = a + 2 * a * 1j
        b = a**3
        obj = distributed_data_object(a, distribution_strategy='equal')
        old_id = id(obj)
        p = distributed_data_object(b)

        assert_equal(getattr(obj, function)(p).get_full_data(),
                     getattr(a, function)(b))
        assert_equal(old_id, id(obj))

###############################################################################

    def test_mod(sel):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        distribution_strategy = 'equal'
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        a[a == 0] = 1
        obj[obj == 0] = 1

        b = a / 3
        p = obj / 3

        assert_almost_equal((obj % b).get_full_data(), a % b)
        assert_almost_equal((obj % p).get_full_data(), a % b)
        assert_almost_equal((obj % 4).get_full_data(), a % 4)

        assert_almost_equal(p.__rmod__(obj).get_full_data(), a % b)
        assert_almost_equal((4 % obj).get_full_data(), 4 % a)

        q = obj.__imod__(p)
        assert_almost_equal(q, a % b)
        assert_equal(id(q), id(obj))


###############################################################################

    def test_double_underscore_equal(self):
        temp_shape = (8, 8)
        a = np.arange(np.prod(temp_shape)).reshape(temp_shape)
        obj = distributed_data_object(a)
        # Check with scalar
        assert_equal((obj == 0).get_full_data(), a == 0)
        # Check with numpy array
        b = np.copy(a)
        b[0, 0] = 111
        assert_equal((obj == b).get_full_data(), a == b)
        # Check with None
        assert_equal(obj is None, a is None)
        # Check with something different, e.g. a list
        t = [[3, ] * temp_shape[1], ] * temp_shape[0]
        assert_equal((obj == t).get_full_data(), a == t)

###############################################################################

    def test_equal(self):
        temp_shape = (8, 8)
        a = np.arange(np.prod(temp_shape)).reshape(temp_shape)
        obj = distributed_data_object(a)
        p = obj.copy()
        assert_equal(obj.equal(p), True)
        assert_equal(obj.equal(p + 1), False)
        assert_equal(obj.equal(None), False)

###############################################################################
    @parameterized.expand(all_distribution_strategies)
    def test_shape_casting(self, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal((obj + a.flatten()).get_full_data(), 2 * a)


###############################################################################
###############################################################################

class Test_contractions(unittest.TestCase):

    @parameterized.expand(
        itertools.product([np.dtype('int'), np.dtype('float'),
                           np.dtype('complex')],
1538
                          [(), (0,), (4, 4)],
theos's avatar
theos committed
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_vdot(self, dtype, global_shape, distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.vdot(2 * obj), np.vdot(a, 2 * a))
        assert_equal(obj.vdot(2 * a), np.vdot(a, 2 * a))

###############################################################################

    @parameterized.expand(
        itertools.product(['sum', 'prod', 'mean', 'var', 'std', 'median'],
                          all_datatypes,
                          [(0,), (6, 6)],
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_compatible_contractions_with_zeros(self, function, dtype,
                                                global_shape,
                                                distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
1561
1562
1563
        if dtype is np.dtype('int8'):
            a[a > 8] = 0
            obj[obj > 8] = 0
1564
1565
        assert_allclose(getattr(obj, function)(), getattr(np, function)(a),
                        rtol=1e-4)
theos's avatar
theos committed
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580

###############################################################################

    @parameterized.expand(
        itertools.product(['min', 'amin', 'nanmin', 'max', 'amax', 'nanmax'],
                          all_datatypes,
                          [(6, 6)],
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_compatible_contractions_without_zeros(self, function, dtype,
                                                   global_shape,
                                                   distribution_strategy):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
1581
1582
        assert_allclose(getattr(obj, function)(), getattr(np, function)(a),
                        rtol=1e-4)
theos's avatar
theos committed
1583
1584
1585
1586
1587
1588
1589
1590

###############################################################################

    @parameterized.expand(
        itertools.product(all_datatypes,
                          all_distribution_strategies
                          ))
    def test_argmin_argmax(self, dtype, distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
1591
        print((dtype, distribution_strategy))
theos's avatar
theos committed
1592
1593
        global_shape = (8, 8)
        (a, obj) = generate_data(global_shape, dtype,
1594
1595
1596
                                 distribution_strategy,
                                 strictly_positive=True)
        o_full = obj.get_full_data()
Theo Steininger's avatar
Theo Steininger committed
1597
        print((a, o_full))
theos's avatar
theos committed
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
        assert_equal(obj.argmax(), np.argmax(a))
        assert_equal(obj.argmin(), np.argmin(a))
        assert_equal(obj.argmin_nonflat(),
                     np.unravel_index(np.argmin(a), global_shape))
        assert_equal(obj.argmax_nonflat(),
                     np.unravel_index(np.argmax(a), global_shape))


###############################################################################

    @parameterized.expand([(lambda x: x + ((-1)**x + 1) * 1j,),
                           (lambda x: x,),
                           (lambda x: x * 1j,)],
                          testcase_func_name=custom_name_func)
    def test_any_all(self, function):
        shape = (8, 7)
        a = np.arange(np.prod(shape)).reshape(shape)
        a = function(a)
        obj = distributed_data_object(a)
        assert_equal(obj.isreal().all(),
                     np.all(np.isreal(a)))
        assert_equal(obj.isreal().any(),
                     np.any(np.isreal(a)))


###############################################################################
###############################################################################

class Test_comparisons(unittest.TestCase):

    @parameterized.expand(
        itertools.product(comparison_operators, all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_comparison_with_scalar(self, comp, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        scalar = 1
        assert_equal(getattr(obj, comp)(1).get_full_data(),
                     getattr(a, comp)(scalar))

    @parameterized.expand(
        itertools.product(comparison_operators, all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_comparison_with_ndarray(self, comp, distribution_strategy):
        global_shape = (7, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        b = a[::-1]
        assert_equal(getattr(obj, comp)(b).get_full_data(),
                     getattr(a, comp)(b))
        assert_equal(getattr(b, comp)(obj),
                     getattr(b, comp)(a))

    @parameterized.expand(
        itertools.product(comparison_operators, all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_comparison_with_d2o(self, comp, distribution_strategy):
        global_shape = (7, 8)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        b = a[::-1]
        p = obj[::-1]
        assert_equal(getattr(obj, comp)(p).get_full_data(),
                     getattr(a, comp)(b))


###############################################################################
###############################################################################

class Test_special_methods(unittest.TestCase):

    @parameterized.expand(
        itertools.product(all_distribution_strategies,
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_bincount(self, distribution_strategy_1, distribution_strategy_2):
        global_shape = (10,)
        dtype = np.dtype('int')
        dtype_weights = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy_1)
        a = abs(a)
        obj = abs(obj)

        (b, p) = generate_data(global_shape, dtype_weights,
                               distribution_strategy_2)
        b **= 2
        p **= 2
        assert_equal(obj.bincount(weights=p),
                     np.bincount(a, weights=b))

###############################################################################

    @parameterized.expand(all_distribution_strategies,
                          testcase_func_name=custom_name_func)
    def Test_unique(self, distribution_strategy):
        global_shape = (40, 40)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.unique(), np.unique(a))

###############################################################################

    @parameterized.expand(
1707
        itertools.product([(), (4,), (8, 8), (0, 4), (4, 0, 8)],
theos's avatar
theos committed
1708
1709
1710
1711
1712
1713
1714
1715
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_flatten(self, global_shape, distribution_strategy):
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.flatten().get_full_data(), a.flatten())
        p = obj.flatten(inplace=True)
1716
        if np.prod(global_shape) != 0 and global_shape != ():
theos's avatar
theos committed
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
            p[0] = 2222
            assert_equal(obj[(0,) * len(global_shape)], 2222)


###############################################################################

    @parameterized.expand(
        itertools.product([(4,), (8, 8)],
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_where(self, global_shape, distribution_strategy):
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)

        b = ((a < 4) + (a > 30))
        p = ((obj < 4) + (obj > 30))

Theo Steininger's avatar
Theo Steininger committed
1735
        assert_equal([z.get_full_data() for z in p.where()], np.where(b))
theos's avatar
theos committed
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766

###############################################################################

    @parameterized.expand(all_distribution_strategies,
                          testcase_func_name=custom_name_func)
    def test_real_imag(self, distribution_strategy):
        global_shape = (8, 8)
        dtype = np.dtype('complex')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.real.get_full_data(), a.real)
        assert_equal(obj.imag.get_full_data(), a.imag)

###############################################################################

    @parameterized.expand(
        itertools.product([None, 0, 1, 2],
                          all_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_cumsum(self, axis, distribution_strategy):
        global_shape = (3, 4, 5)
        dtype = np.dtype('float')
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy)
        assert_equal(obj.cumsum(axis=axis).get_full_data(),
                     a.cumsum(axis=axis))

###############################################################################
###############################################################################


1767
if FOUND['h5py']:
theos's avatar
theos committed
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
    class Test_load_save(unittest.TestCase):

        @parameterized.expand(
            itertools.product(all_datatypes,
                              all_distribution_strategies),
            testcase_func_name=custom_name_func)
        def test_load_save(self, dtype, distribution_strategy):
            if dtype == np.dtype('float128'):
                dtype = np.dtype('float')

            global_shape = (8, 8)
            (a, obj) = generate_data(global_shape, dtype,
                                     distribution_strategy)
            alias = 'test_alias'

            path = os.path.join(tempfile.gettempdir(),
                                'temp_hdf5_file.hdf5')
1785
            if size > 1 and not FOUND['h5py_parallel']:
theos's avatar
theos committed
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
                assert_raises(RuntimeError,
                              lambda: obj.save(alias=alias, path=path))
            else:
                obj.save(alias=alias, path=path)
                p = distributed_data_object(alias=alias,
                                            path=path)
                assert_equal(obj.get_full_data(), p.get_full_data())

                assert_raises(ValueError,
                              lambda: obj.save(alias=alias,
                                               path=path,
                                               overwriteQ=False))

theos's avatar
theos committed
1799
                obj = obj*3
theos's avatar
theos committed
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
                obj.save(alias=alias, path=path)
                p = distributed_data_object(alias=alias,
                                            path=path)
                assert_equal(obj.get_full_data(), p.get_full_data())
                if rank == 0:
                    os.remove(path)


# Todo: Assert that data is copied, when copy flag is set
# Todo: Assert that set, get and injection work, if there is different data
# on the nodes

class Test_axis(unittest.TestCase):

    @parameterized.expand(
        itertools.product(['sum', 'prod', 'mean', 'var', 'std', 'all', 'any',
                           'min', 'amin', 'nanmin', 'argmin', 'argmin_nonflat',
theos's avatar
theos committed
1817
1818
                           'max', 'amax', 'nanmax', 'argmax',
                           'argmax_nonflat'],
theos's avatar
theos committed
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
                          all_datatypes[1:],
                          [(0,), (4, 0, 3)],
                          all_distribution_strategies,
                          [None, (0, ), (1, ), (0, 1)]),
        testcase_func_name=custom_name_func)
    def test_axis_with_operations_0_dimension(self, function, dtype,
                                              global_shape,
                                              distribution_strategy, axis):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
        if function in ['min', 'amin', 'nanmin', 'argmin', 'argmin_nonflat',
                        'max', 'amax', 'nanmax', 'argmax', 'argmax_nonflat']:
            if not (function in ['min', 'amin', 'nanmin', 'max', 'amax',
                    'nanmax'] and axis == (0, ) and global_shape == (4, 0, 3)):
                assert_raises(ValueError, lambda: getattr(obj, function)
                              (axis=axis))
        else:
            if axis in [(1, ), (0, 1)] and global_shape == (0,):
Theo Steininger's avatar
Theo Steininger committed
1838
                assert_raises(Exception, lambda: getattr(obj, function)
theos's avatar
theos committed
1839
                              (axis=axis))
1840
1841
1842
            elif function in ['all', 'any']:
                assert_equal(getattr(obj, function)(axis=axis),
                             getattr(np, function)(a, axis=axis))
theos's avatar
theos committed
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
            else:
                assert_almost_equal(getattr(obj, function)(axis=axis),
                                    getattr(np, function)(a, axis=axis),
                                    decimal=4)

    @parameterized.expand(
        itertools.product(['sum', 'prod', 'mean', 'var', 'std', 'all', 'any',
                           'min', 'amin', 'nanmin', 'argmin', 'max', 'amax',
                           'nanmax', 'argmax'],
                          all_datatypes[1:],
1853
                          [(), (1,), (2, 3)],
theos's avatar
theos committed
1854
1855
1856
1857
1858
                          all_distribution_strategies,
                          [None, 0, (1, ), (0, 1)]),
        testcase_func_name=custom_name_func)
    def test_axis_with_operations(self, function, dtype, global_shape,
                                  distribution_strategy, axis):
theos's avatar
theos committed
1859

theos's avatar
theos committed
1860
1861
1862
1863
1864
1865
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
        if function in ['argmin', 'argmax'] and axis is not None:
            assert_raises(NotImplementedError, lambda: getattr(obj, function)
                          (axis=axis))
1866
1867
1868
1869
1870
1871
1872
        elif (global_shape == (2, 3) or
              (global_shape == (1,) and axis in [None, 0, (0,)]) or
              (global_shape == () and axis is None)):
            if function in ['all', 'any']:
                assert_equal(getattr(obj, function)(axis=axis),
                             getattr(np, function)(a, axis=axis))
            else:
theos's avatar
theos committed
1873
1874
1875
1876
1877
1878
1879
1880
1881
                assert_almost_equal(getattr(obj, function)(axis=axis),
                                    getattr(np, function)(a, axis=axis),
                                    decimal=4)

    @parameterized.expand(
        itertools.product(['sum', 'prod', 'mean', 'var', 'std', 'all', 'any',
                           'min', 'amin', 'nanmin', 'argmin', 'max', 'amax',
                           'nanmax', 'argmax'],
                          all_datatypes[1:],
1882
                          [(3, 2, 2)],
theos's avatar
theos committed
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
                          all_distribution_strategies,
                          [(0, 1), (1, 2), (0, 1, 2)]),
        testcase_func_name=custom_name_func)
    def test_axis_with_operations_many_dimentions(self, function, dtype,
                                                  global_shape,
                                                  distribution_strategy,
                                                  axis):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
1893
1894
1895
        if dtype is np.dtype('int8'):
            a[a > 8] = 0
            obj[obj > 8] = 0
theos's avatar
theos committed
1896
1897
1898
1899
1900
1901
1902
1903
        if function in ['argmin', 'argmax'] and axis is not None:
            assert_raises(NotImplementedError, lambda: getattr(obj, function)
                          (axis=axis))
        else:
            if function in ['min', 'amin', 'nanmin', 'max', 'amax', 'nanmax']\
                    and 0 in global_shape:
                    assert_raises(ValueError, lambda: getattr(obj, function)
                                  (axis=axis))
1904
1905
1906
            elif function in ['all', 'any']:
                assert_equal(getattr(obj, function)(axis=axis),
                             getattr(np, function)(a, axis=axis))
theos's avatar
theos committed
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
            else:
                assert_almost_equal(getattr(obj, function)(axis=axis),
                                    getattr(np, function)(a, axis=axis),
                                    decimal=4)

    @parameterized.expand(
        itertools.product(all_datatypes[1:],
                          [(0,), (1,), (4, 4, 3), (4, 0, 3)],
                          all_distribution_strategies,
                          [None, 0, (1, ), (0, 1), (1, 2)]),
        testcase_func_name=custom_name_func)
    def test_axis_for_median(self, dtype, global_shape,
                             distribution_strategy, axis):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
        if global_shape != (0,) and global_shape != (1,) and lv("1.9.0Z") < \
                lv(np.__version__):
            assert_almost_equal(getattr(obj, 'median')(axis=axis),
                                getattr(np, 'median')(a, axis=axis),
                                decimal=4)
        else:
            if axis is None or axis == 0 or axis == (0,):
                assert_almost_equal(getattr(obj, 'median')(axis=axis),
                                    getattr(np, 'median')(a, axis=axis),
                                    decimal=4)

    @parameterized.expand(
        itertools.product([('argmin_nonflat', 'argmin'),
                           ('argmax_nonflat', 'argmax')],
                          all_datatypes[1:],
1938
                          [(), (0,), (1,), (4, 4, 3), (4, 0, 3)],
theos's avatar
theos committed
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
                          all_distribution_strategies,
                          [None, (1, ), (1, 2)]),
        testcase_func_name=custom_name_func)
    def test_axis_for_nonflats(self, function_pair, dtype, global_shape,
                               distribution_strategy, axis):
        (a, obj) = generate_data(global_shape, dtype,
                                 distribution_strategy,
                                 strictly_positive=True)
        if 0 in global_shape:
            assert_raises(ValueError,
                          lambda: getattr(obj, function_pair[0])(axis=axis))
        else:
1951
            if axis is not None and global_shape != ():
theos's avatar
theos committed
1952
                assert_raises(NotImplementedError,
theos's avatar
theos committed
1953
1954
                              lambda: getattr(obj,
                                              function_pair[0])(axis=axis))
theos's avatar
theos committed
1955
1956
            else:

1957
                if len(global_shape) > 1:
theos's avatar
theos committed
1958
1959
1960
1961
1962
1963
                    assert_almost_equal(
                        getattr(obj, function_pair[0])(axis=axis),
                        np.unravel_index(getattr(np, function_pair[1])
                                         (a, axis=axis),
                                         dims=global_shape),
                        decimal=4)
1964
                elif len(global_shape) == 1:
theos's avatar
theos committed
1965
1966
1967
1968
1969
1970
1971
                    assert_almost_equal(getattr(obj, function_pair[0])
                                        (axis=axis),
                                        np.unravel_index(
                                            getattr(np, function_pair[1])
                                            (a, axis=axis),
                                            dims=global_shape),
                                        decimal=4)
1972
1973
1974
                else:
                    assert_almost_equal(getattr(obj, function_pair[0])
                                        (axis=axis), (0,))
theos's avatar
theos committed
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991


class Test_arange(unittest.TestCase):
    @parameterized.expand(
        itertools.product(all_datatypes[1:],
                          [(11, None, None),
                           (1, 23, None),
                           (2, 20, 2),
                           (2, 21, 2)],
                          global_distribution_strategies),
        testcase_func_name=custom_name_func)
    def test_arange(self, dtype, sss, distribution_strategy):
        obj = arange(start=sss[0], stop=sss[1], step=sss[2], dtype=dtype,
                     distribution_strategy=distribution_strategy)
        a = np.arange(start=sss[0], stop=sss[1], step=sss[2], dtype=dtype)
        assert_equal(obj.get_full_data(), a)
        assert_equal(obj.dtype, a.dtype)