-
Notifications
You must be signed in to change notification settings - Fork 1
/
localarray.py
1755 lines (1323 loc) · 54 KB
/
localarray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
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
664
665
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
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
from __future__ import print_function, division
from distarray import metadata_utils
# ---------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------
import math
import operator
from functools import reduce
from collections import Mapping
from numbers import Integral
import numpy as np
from distarray.externals import six
from distarray.externals.six import next
from distarray.externals.six.moves import zip
from distarray.mpiutils import MPI
from distarray.utils import _raise_nie
from distarray.local import construct, format, maps
from distarray.local.error import InvalidDimensionError, IncompatibleArrayError
def _start_stop_block(size, proc_grid_size, proc_grid_rank):
nelements = size // proc_grid_size
if size % proc_grid_size != 0:
nelements += 1
start = proc_grid_rank * nelements
if start > size:
start = size
stop = size
stop = start + nelements
if stop > size:
stop = size
return start, stop
# Register numpy integer types with numbers.Integral ABC.
Integral.register(np.signedinteger)
Integral.register(np.unsignedinteger)
def _sanitize_indices(indices):
if isinstance(indices, Integral) or isinstance(indices, slice):
return (indices,)
elif all(isinstance(i, Integral) or isinstance(i, slice) for i in indices):
return indices
else:
raise TypeError("Index must be a sequence of ints and slices")
def distribute_indices(dim_data):
"""Fill in missing index related keys...
for supported dist_types.
"""
distribute_fn = {
'n': lambda dd: None,
'b': distribute_block_indices,
'c': distribute_cyclic_indices,
'u': lambda dd: None,
}
for dim in dim_data:
distribute_fn[dim['dist_type']](dim)
def distribute_cyclic_indices(dd):
"""Fill in `start` given dimdict `dd`."""
if 'start' in dd:
return
else:
dd['start'] = dd['proc_grid_rank']
def distribute_block_indices(dd):
"""Fill in `start` and `stop` in dimdict `dd`."""
if ('start' in dd) and ('stop' in dd):
return
nelements = dd['size'] // dd['proc_grid_size']
if dd['size'] % dd['proc_grid_size'] != 0:
nelements += 1
dd['start'] = dd['proc_grid_rank'] * nelements
if dd['start'] > dd['size']:
dd['start'] = dd['size']
dd['stop'] = dd['size']
dd['stop'] = dd['start'] + nelements
if dd['stop'] > dd['size']:
dd['stop'] = dd['size']
def _normalize_dim_data(dim_data):
''' Adds `proc_grid_size` and `proc_grid_rank` for 'n' disttype.'''
for dd in dim_data:
if dd['dist_type'] == 'n':
dd['proc_grid_size'] = 1
dd['proc_grid_rank'] = 0
return dim_data
def make_partial_dim_data(shape, dist=None, grid_shape=None):
"""Create an (incomplete) dim_data structure from simple parameters.
Parameters
----------
shape : tuple of int
Number of elements in each dimension.
dist : dict mapping int -> str, default is {0: 'b'}
Keys are dimension number, values are dist_type, e.g 'b', 'c', or 'n'.
grid_shape : tuple of int, optional
Size of process grid in each dimension
Returns
-------
dim_data : tuple of dict
Partial dim_data structure as outlined in the Distributed Array
Protocol.
"""
supported_dist_types = ('n', 'b', 'c')
if dist is None:
dist = {0: 'b'}
dist_tuple = metadata_utils.normalize_dist(dist, len(shape))
if grid_shape: # if None, LocalArray will initialize
grid_gen = iter(grid_shape)
dim_data = []
for size, dist_type in zip(shape, dist_tuple):
if dist_type not in supported_dist_types:
msg = "dist_type {} not supported. Try `from_dim_data`."
raise TypeError(msg.format(dist_type))
dimdict = dict(dist_type=dist_type, size=size)
if grid_shape is not None and dist_type != 'n':
dimdict["proc_grid_size"] = next(grid_gen)
dim_data.append(dimdict)
return tuple(dim_data)
class GlobalIndex(object):
"""Object which provides access to global indexing on
LocalArrays.
"""
def __init__(self, maps, ndarray):
self.maps = maps
self.local_array = ndarray
def checked_getitem(self, global_inds):
try:
return self.__getitem__(global_inds)
except IndexError:
return None
def checked_setitem(self, global_inds, value):
try:
self.__setitem__(global_inds, value)
return True
except IndexError:
return None
def global_to_local(self, *global_ind):
return self.maps.local_from_global(*global_ind)
def local_to_global(self, *local_ind):
return self.maps.global_from_local(*local_ind)
def __getitem__(self, global_inds):
global_inds = _sanitize_indices(global_inds)
try:
local_inds = self.global_to_local(*global_inds)
return self.local_array[local_inds]
except KeyError as err:
raise IndexError(err)
def __setitem__(self, global_inds, value):
global_inds = _sanitize_indices(global_inds)
try:
local_inds = self.global_to_local(*global_inds)
self.local_array[local_inds] = value
except KeyError as err:
raise IndexError(err)
class LocalArray(object):
"""Distributed memory Python arrays."""
__array_priority__ = 20.0
#-------------------------------------------------------------------------
# Methods used for initialization
#-------------------------------------------------------------------------
def _init(self, dim_data, grid_shape, dtype=None, buf=None, comm=None):
"""Private init method."""
self.dim_data = _normalize_dim_data(dim_data)
self.base_comm = construct.init_base_comm(comm)
self._init_grid_shape(grid_shape)
self.comm = construct.init_comm(self.base_comm, self.grid_shape)
self._cache_proc_grid_rank()
distribute_indices(self.dim_data)
self.maps = maps.MDMap.from_dim_data(dim_data)
self.local_array = self._make_local_array(buf=buf, dtype=dtype)
# We pass a view of self.local_array because we want the
# GlobalIndex object to be able to change the LocalArray
# object's data.
self.global_index = GlobalIndex(self.maps, self.local_array.view())
self.base = None # mimic numpy.ndarray.base
self.ctypes = None # mimic numpy.ndarray.ctypes
def _init_grid_shape(self, grid_shape):
if grid_shape is None:
grid_shape = metadata_utils.make_grid_shape(self.global_shape,
self.dist,
self.comm_size)
metadata_utils.validate_grid_shape(grid_shape,
self.dist,
self.comm_size)
for gs, dd in zip(grid_shape, self.dim_data):
dd['proc_grid_size'] = gs
@classmethod
def from_dim_data(cls, dim_data, dtype=None, buf=None, comm=None):
"""Make a LocalArray from a `dim_data` tuple.
Parameters
----------
dim_data : tuple of dictionaries
A dict for each dimension, with the data described here:
https://github.com/enthought/distributed-array-protocol
dtype : numpy dtype, optional
If both `dtype` and `buf` are provided, `buf` will be
encapsulated and interpreted with the given dtype. If neither
are, an empty array will be created with a dtype of 'float'. If
only `dtype` is given, an empty array of that dtype will be
created.
buf : buffer object, optional
If both `dtype` and `buf` are provided, `buf` will be
encapsulated and interpreted with the given dtype. If neither
are, an empty array will be created with a dtype of 'float'. If
only `buf` is given, `self.dtype` will be set to its dtype.
comm : MPI comm object, optional
Returns
-------
LocalArray
A LocalArray encapsulating `buf`, or else an empty
(uninitialized) LocalArray.
"""
self = cls.__new__(cls)
def fill_empty_dim_dict(dim_dict, i):
"""Empty dim_dict alias -- requires a buffer object.
See DAP v0.10.0 section 1.6.3.1.
"""
if buf is None:
msg = "Must provide `buf` to use the empty dictionary alias."
raise TypeError(msg)
default = {'dist_type': 'b',
'proc_grid_rank': 0,
'proc_grid_size': 1,
'start': 0,
'stop': buf.shape[i],
'size': buf.shape[i]}
dim_dict.update(default)
# Expand empty dim_dicts
for i, dim_dict in enumerate(dim_data):
if not dim_dict: # empty dict
fill_empty_dim_dict(dim_dict, i)
# Extract grid_shape from dim_data.
grid_shape = tuple(1 if dd['dist_type'] == 'n' else dd['proc_grid_size']
for dd in dim_data)
self._init(dim_data=dim_data, dtype=dtype,
buf=buf, comm=comm, grid_shape=grid_shape)
return self
def __init__(self, shape, dtype=None, dist=None, grid_shape=None,
comm=None, buf=None):
"""Create a LocalArray from a simple set of parameters.
This initializer restricts you to 'b' and 'c' dist_types and evenly
distributed data. See `LocalArray.from_dim_data` for a more general
method.
Parameters
----------
shape : tuple of int
Number of elements in each dimension.
dtype : numpy dtype, optional
dist : dict mapping int -> str, default is {0: 'b'}, optional
Keys are dimension number, values are dist_type, e.g 'b', 'c', or
'n'.
grid_shape : tuple of int, optional
A size of each dimension of the process grid.
There should be a dimension size for each distributed
dimension in `dist`.
comm : MPI communicator object, optional
buf : buffer object, optional
If not given, an empty array is created.
See also
--------
LocalArray.from_dim_data
"""
dim_data = make_partial_dim_data(shape=shape, dist=dist,
grid_shape=grid_shape)
self._init(dim_data=dim_data, grid_shape=grid_shape,
dtype=dtype, buf=buf, comm=comm)
def __del__(self):
# If the __init__ method fails, we may not have a valid comm
# attribute and this needs to be protected against.
if hasattr(self, 'comm'):
if self.comm is not None:
try:
self.comm.Free()
except:
pass
@property
def local_shape(self):
return self.maps.local_shape
@property
def grid_shape(self):
return tuple(dd['proc_grid_size'] for dd in self.dim_data)
@property
def global_shape(self):
return tuple(dd['size'] for dd in self.dim_data)
@property
def ndim(self):
return len(self.dim_data)
@property
def global_size(self):
return reduce(operator.mul, self.global_shape)
@property
def comm_size(self):
return self.base_comm.Get_size()
@property
def comm_rank(self):
return self.base_comm.Get_rank()
@property
def dist(self):
return tuple(dd['dist_type'] for dd in self.dim_data)
@property
def cart_coords(self):
rval = tuple(dd['proc_grid_rank'] for dd in self.dim_data)
assert rval == tuple(self.comm.Get_coords(self.comm_rank))
return rval
@property
def local_size(self):
return self.local_array.size
@property
def local_data(self):
return self.local_array.data
@property
def dtype(self):
return self.local_array.dtype
@property
def itemsize(self):
return self.dtype.itemsize
@property
def nbytes(self):
return self.global_size * self.itemsize
def _cache_proc_grid_rank(self):
cart_coords = self.comm.Get_coords(self.comm_rank)
assert len(cart_coords) == len(self.dim_data)
for dim, cart_rank in zip(self.dim_data, cart_coords):
dim['proc_grid_rank'] = cart_rank
def _make_local_array(self, buf=None, dtype=None):
"""Encapsulate `buf` or create an empty local array.
Returns
-------
local_array : numpy array
"""
if buf is None:
return np.empty(self.local_shape, dtype=dtype)
else:
mv = memoryview(buf)
return np.asarray(mv, dtype=dtype)
def compatibility_hash(self):
return hash((self.global_shape, self.dist, self.grid_shape, True))
#-------------------------------------------------------------------------
# Distributed Array Protocol
#-------------------------------------------------------------------------
@classmethod
def from_distarray(cls, obj, comm=None):
"""Make a LocalArray from Distributed Array Protocol data structure.
An object that supports the Distributed Array Protocol will have
a `__distarray__` method that returns the data structure
described here:
https://github.com/enthought/distributed-array-protocol
Parameters
----------
obj : an object with a `__distarray__` method or a dict
If a dict, it must conform to the structure defined by the
distributed array protocol.
Returns
-------
LocalArray
A LocalArray encapsulating the buffer of the original data.
No copy is made.
"""
if isinstance(obj, Mapping):
distbuffer = obj
else:
distbuffer = obj.__distarray__()
buf = np.asarray(distbuffer['buffer'])
dim_data = distbuffer['dim_data']
return cls.from_dim_data(dim_data=dim_data, buf=buf, comm=comm)
def __distarray__(self):
"""Returns the data structure required by the DAP.
DAP = Distributed Array Protocol
See the project's documentation for the Protocol's specification.
"""
# the DAP doesn't have an 'n' dist_type
translated_dim_data = tuple(dim_dict.copy() for dim_dict in
self.dim_data)
def b_from_n(dd):
"""Take a dimension dictionary (`dd`) with dist_type 'n' and make
it the equivalent 'b'.
"""
dd['dist_type'] = 'b'
dd['start'] = 0
dd['stop'] = dd['size']
dd['proc_grid_rank'] = 0
dd['proc_grid_size'] = 1
for dim_dict in translated_dim_data:
if dim_dict['dist_type'] == 'n':
b_from_n(dim_dict)
distbuffer = {
"__version__": "0.10.0",
"buffer": self.local_array,
"dim_data": translated_dim_data,
}
return distbuffer
#-------------------------------------------------------------------------
# Methods related to distributed indexing
#-------------------------------------------------------------------------
def get_localarray(self):
return self.local_view()
def set_localarray(self, a):
arr = np.asarray(a, dtype=self.dtype, order='C')
if arr.shape == self.local_shape:
self.local_array = arr
else:
raise ValueError("Incompatible local array shape")
def coords_from_rank(self, rank):
return self.comm.Get_coords(rank)
def rank_from_coords(self, coords):
return self.comm.Get_cart_rank(coords)
def local_from_global(self, *global_ind):
return self.maps.local_from_global(*global_ind)
def global_from_local(self, *local_ind):
return self.maps.global_from_local(*local_ind)
def global_limits(self, dim):
if dim < 0 or dim >= self.ndim:
raise InvalidDimensionError("Invalid dimension: %r" % dim)
lower_local = self.ndim * [0]
lower_global = self.global_from_local(*lower_local)
upper_local = [shape-1 for shape in self.local_shape]
upper_global = self.global_from_local(*upper_local)
return lower_global[dim], upper_global[dim]
#-------------------------------------------------------------------------
# 3.2 ndarray methods
#-------------------------------------------------------------------------
# 3.2.1 Array conversion
#-------------------------------------------------------------------------
def astype(self, newdtype):
"""Return a copy of this LocalArray with a new underlying dtype."""
if newdtype is None:
return self.copy()
else:
local_copy = self.local_array.astype(newdtype)
new_da = self.__class__.from_dim_data(dim_data=self.dim_data,
dtype=newdtype,
comm=self.base_comm,
buf=local_copy)
return new_da
def copy(self):
"""Return a copy of this LocalArray."""
local_copy = self.local_array.copy()
return self.__class__.from_dim_data(dim_data=self.dim_data,
dtype=self.dtype,
comm=self.base_comm,
buf=local_copy)
def local_view(self, dtype=None):
if dtype is None:
return self.local_array.view()
else:
return self.local_array.view(dtype)
def view(self, dtype=None):
"""Return a new LocalArray whose underlying `local_array` is a view on
`self.local_array`.
Note
----
Currently unimplemented for ``dtype is not None``.
"""
if dtype is None:
new_da = self.__class__.from_dim_data(dim_data=self.dim_data,
dtype=self.dtype,
comm=self.base_comm,
buf=self.local_array)
else:
_raise_nie()
#TODO: to implement this properly, a new dim_data will need to
# generated that reflects the size and shape of the new dtype.
#new_da = self.__class__.from_dim_data(dim_data=self.dim_data,
# dtype=dtype,
# comm=self.base_comm,
# buf=self.local_array)
return new_da
def __array__(self, dtype=None):
if dtype is None:
return self.local_array
elif np.dtype(dtype) == self.dtype:
return self.local_array
else:
return self.local_array.astype(dtype)
def __array_wrap__(self, obj, context=None):
"""
Return a LocalArray based on obj.
This method constructs a new LocalArray object using (shape, dist,
grid_shape and base_comm) from self and dtype, buffer from obj.
This is used to construct return arrays for ufuncs.
"""
return self.__class__(self.global_shape, obj.dtype, self.dist,
self.grid_shape, self.base_comm, buf=obj)
def fill(self, scalar):
self.local_array.fill(scalar)
#-------------------------------------------------------------------------
# 3.2.2 Array shape manipulation
#-------------------------------------------------------------------------
def reshape(self, newshape):
_raise_nie()
def redist(self, newshape, newdist={0: 'b'}, newgrid_shape=None):
_raise_nie()
def resize(self, newshape, refcheck=1, order='C'):
_raise_nie()
def transpose(self, axes=None):
_raise_nie()
def swapaxes(self, axis1, axis2):
_raise_nie()
def flatten(self, order='C'):
_raise_nie()
def ravel(self, order='C'):
_raise_nie()
def squeeze(self):
_raise_nie()
def asdist(self, shape, dist={0: 'b'}, grid_shape=None):
pass
# new_da = LocalArray(shape, self.dtype, dist, grid_shape,
# self.base_comm)
# base_comm = self.base_comm
# local_array = self.local_array
# new_local_array = da.local_array
# recv_counts = np.zeros(self.comm_size, dtype=int)
#
# status = MPI.Status()
# MPI.Attach_buffer(np.empty(128+MPI.BSEND_OVERHEAD,dtype=float))
# done_count = 0
#
# for old_local_inds, item in np.ndenumerate(local_array):
#
# # Compute the new owner
# global_inds = self.global_from_local(new_da.comm_rank,
# old_local_inds)
# new_owner = new_da.owner_rank(global_inds)
# if new_owner==self.owner_rank:
# pass
# # Just move the data to the right place in new_local_array
# else:
# # Send to the new owner with default tag
# # Bsend is probably best, but Isend is also a possibility.
# request = comm.Isend(item, dest=new_owner)
#
# # Recv
# incoming = comm.Iprobe(MPI.ANY_SOURCE, MPI.ANY_TAG, status)
# if incoming:
# old_owner = status.Get_source()
# tag = status.Get_tag()
# data = comm.Recv(old_owner, tag)
# if tag==2:
# done_count += 1
# # Figure out where new location of old_owner, tag
# new_local_ind = local_ind_by_owner_and_location(old_owner,
# location)
# new_local_array[new_local_ind] = y
# recv_counts[old_owner] = recv_counts[old_owner]+1
#
# while done_count < self.comm_size:
# pass
#
#
# MPI.Detach_buffer()
def asdist_like(self, other):
"""
Return a version of self that has shape, dist and grid_shape like
other.
"""
if arecompatible(self, other):
return self
else:
raise IncompatibleArrayError("DistArrays have incompatible shape,"
"dist or grid_shape")
#-------------------------------------------------------------------------
# 3.2.3 Array item selection and manipulation
#-------------------------------------------------------------------------
def take(self, indices, axis=None, out=None, mode='raise'):
_raise_nie()
def put(self, indices, values, mode='raise'):
_raise_nie()
def putmask(self, mask, values):
_raise_nie()
def repeat(self, repeats, axis=None):
_raise_nie()
def choose(self, choices, out=None, mode='raise'):
_raise_nie()
def sort(self, axis=-1, kind='quick'):
_raise_nie()
def argsort(self, axis=-1, kind='quick'):
_raise_nie()
def searchsorted(self, values):
_raise_nie()
def nonzero(self):
_raise_nie()
def compress(self, condition, axis=None, out=None):
_raise_nie()
def diagonal(self, offset=0, axis1=0, axis2=1):
_raise_nie()
#-------------------------------------------------------------------------
# 3.2.4 Array item selection and manipulation
#-------------------------------------------------------------------------
def max(self, axis=None, out=None):
_raise_nie()
def argmax(self, axis=None, out=None):
_raise_nie()
def min(axis=None, out=None):
_raise_nie()
def argmin(self, axis=None, out=None):
_raise_nie()
def ptp(self, axis=None, out=None):
_raise_nie()
def clip(self, min, max, out=None):
_raise_nie()
def conj(self, out=None):
_raise_nie()
conjugate = conj
def round(self, decimals=0, out=None):
_raise_nie()
def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
_raise_nie()
#TODO FIXME: implement axis and out kwargs.
def sum(self, axis=None, dtype=None, out=None):
if axis or out is not None:
_raise_nie()
return sum(self, dtype=dtype)
def mean(self, axis=None, dtype=float, out=None):
if axis or out is not None:
_raise_nie()
elif dtype is not None:
dtype = np.dtype(dtype)
return dtype.type((np.divide(self.sum(dtype=dtype),
self.global_size)))
else:
return np.divide(self.sum(dtype=dtype), self.global_size)
def var(self, axis=None, dtype=None, out=None):
if axis or out is not None:
_raise_nie()
mu = self.mean()
temp = (self - mu)**2
return temp.mean(dtype=dtype)
def std(self, axis=None, dtype=None, out=None):
if axis or out is not None:
_raise_nie()
elif dtype is not None:
dtype = np.dtype(dtype)
return dtype.type((math.sqrt(self.var())))
else:
return math.sqrt(self.var())
def cumsum(self, axis=None, dtype=None, out=None):
_raise_nie()
def prod(self, axis=None, dtype=None, out=None):
_raise_nie()
def cumprod(self, axis=None, dtype=None, out=None):
_raise_nie()
def all(self, axis=None, out=None):
_raise_nie()
def any(self, axis=None, out=None):
_raise_nie()
#-------------------------------------------------------------------------
# 3.3 Array special methods
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# 3.3.1 Methods for standard library functions
#-------------------------------------------------------------------------
def __copy__(self):
_raise_nie()
def __deepcopy__(self):
_raise_nie()
#-------------------------------------------------------------------------
# 3.3.2 Basic customization
#-------------------------------------------------------------------------
def __lt__(self, other):
return self._binary_op_from_ufunc(other, less, '__lt__')
def __le__(self, other):
return self._binary_op_from_ufunc(other, less_equal, '__le__')
def __eq__(self, other):
return self._binary_op_from_ufunc(other, equal, '__eq__')
def __ne__(self, other):
return self._binary_op_from_ufunc(other, not_equal, '__ne__')
def __gt__(self, other):
return self._binary_op_from_ufunc(other, greater, '__gt__')
def __ge__(self, other):
return self._binary_op_from_ufunc(other, greater_equal, '__ge__')
def __str__(self):
return str(self.local_array)
def __repr__(self):
return str(self.local_array)
def __nonzero__(self):
_raise_nie()
#-------------------------------------------------------------------------
# 3.3.3 Container customization
#-------------------------------------------------------------------------
def __len__(self):
return self.global_shape[0]
def checked_getitem(self, global_inds):
try:
return self.global_index[global_inds]
except IndexError:
return None
def checked_setitem(self, global_inds, value):
try:
self.global_index[global_inds] = value
return True
except IndexError:
return None
def __getitem__(self, index):
"""Get a local item."""
return self.local_array[index]
def __setitem__(self, index, value):
"""Set a local item."""
self.local_array[index] = value
def sync(self):
raise NotImplementedError("`sync` not yet implemented.")
def __contains__(self, item):
return item in self.local_array
def pack_index(self, inds):
inds_array = np.array(inds)
strides_array = np.cumprod([1] + list(self.global_shape)[:0:-1])[::-1]
return np.sum(inds_array*strides_array)
def unpack_index(self, packed_ind):
if packed_ind > np.prod(self.global_shape)-1 or packed_ind < 0:
raise ValueError("Invalid index, must be 0 <= x <= number of"
"elements.")
strides_array = np.cumprod([1] + list(self.global_shape)[:0:-1])[::-1]
return tuple(packed_ind//strides_array % self.global_shape)
#--------------------------------------------------------------------------
# 3.3.4 Arithmetic customization - binary
#--------------------------------------------------------------------------
# Binary
def _binary_op_from_ufunc(self, other, func, rop_str=None):
if hasattr(other, '__array_priority__') and hasattr(other, rop_str):
if other.__array_priority__ > self.__array_priority__:
rop = getattr(other, rop_str)
return rop(self)
return func(self, other)
def _rbinary_op_from_ufunc(self, other, func, lop_str):
if hasattr(other, '__array_priority__') and hasattr(other, lop_str):
if other.__array_priority__ > self.__array_priority__:
lop = getattr(other, lop_str)
return lop(self)
return func(other, self)
def __add__(self, other):
return self._binary_op_from_ufunc(other, add, '__radd__')
def __sub__(self, other):
return self._binary_op_from_ufunc(other, subtract, '__rsub__')
def __mul__(self, other):
return self._binary_op_from_ufunc(other, multiply, '__rmul__')
def __div__(self, other):
return self._binary_op_from_ufunc(other, divide, '__rdiv__')
def __truediv__(self, other):
return self._binary_op_from_ufunc(other, true_divide, '__rtruediv__')
def __floordiv__(self, other):
return self._binary_op_from_ufunc(other, floor_divide, '__rfloordiv__')
def __mod__(self, other):
return self._binary_op_from_ufunc(other, mod, '__rdiv__')
def __divmod__(self, other):
_raise_nie()
def __pow__(self, other, modulo=None):
return self._binary_op_from_ufunc(other, power, '__rpower__')
def __lshift__(self, other):
return self._binary_op_from_ufunc(other, left_shift, '__rlshift__')
def __rshift__(self, other):
return self._binary_op_from_ufunc(other, right_shift, '__rrshift__')
def __and__(self, other):
return self._binary_op_from_ufunc(other, bitwise_and, '__rand__')
def __or__(self, other):
return self._binary_op_from_ufunc(other, bitwise_or, '__ror__')
def __xor__(self, other):
return self._binary_op_from_ufunc(other, bitwise_xor, '__rxor__')
# Binary - right versions
def __radd__(self, other):
return self._rbinary_op_from_ufunc(other, add, '__add__')
def __rsub__(self, other):
return self._rbinary_op_from_ufunc(other, subtract, '__sub__')
def __rmul__(self, other):
return self._rbinary_op_from_ufunc(other, multiply, '__mul__')
def __rdiv__(self, other):
return self._rbinary_op_from_ufunc(other, divide, '__div__')
def __rtruediv__(self, other):
return self._rbinary_op_from_ufunc(other, true_divide, '__truediv__')
def __rfloordiv__(self, other):
return self._rbinary_op_from_ufunc(other, floor_divide, '__floordiv__')
def __rmod__(self, other):
return self._rbinary_op_from_ufunc(other, mod, '__mod__')
def __rdivmod__(self, other):
_raise_nie()
def __rpow__(self, other, modulo=None):
return self._rbinary_op_from_ufunc(other, power, '__pow__')
def __rlshift__(self, other):
return self._rbinary_op_from_ufunc(other, left_shift, '__lshift__')
def __rrshift__(self, other):
return self._rbinary_op_from_ufunc(other, right_shift, '__rshift__')
def __rand__(self, other):
return self._rbinary_op_from_ufunc(other, bitwise_and, '__and__')
def __ror__(self, other):
return self._rbinary_op_from_ufunc(other, bitwise_or, '__or__')
def __rxor__(self, other):