/
array.py
2201 lines (1777 loc) · 73.2 KB
/
array.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
import operator
from collections import defaultdict, deque
from math import ceil
import dislib
import numpy as np
from pycompss.api.api import compss_wait_on, compss_delete_object
from pycompss.api.constraint import constraint
from pycompss.api.parameter import Type, COLLECTION_IN, Depth, \
COLLECTION_OUT, INOUT
from pycompss.api.task import task
from scipy import sparse as sp
from scipy.sparse import issparse, csr_matrix
from sklearn.utils import check_random_state
import math
class Array(object):
""" A distributed 2-dimensional array divided in blocks.
Normally, this class should not be instantiated directly, but created
using one of the array creation routines provided.
Apart from the different methods provided, this class also supports
the following types of indexing:
- ``A[i]`` : returns a single row
- ``A[i, j]`` : returns a single element
- ``A[i:j]`` : returns a set of rows (with ``i`` and ``j`` optional)
- ``A[:, i:j]`` : returns a set of columns (with ``i`` and ``j``
optional)
- ``A[[i,j,k]]`` : returns a set of non-consecutive rows. Rows are
returned ordered by their index in the input array.
- ``A[:, [i,j,k]]`` : returns a set of non-consecutive columns.
Columns are returned ordered by their index in the input array.
- ``A[i:j, k:m]`` : returns a set of elements (with ``i``, ``j``,
``k``, and ``m`` optional)
Parameters
----------
blocks : list
List of lists of nd-array or spmatrix.
top_left_shape : tuple
A single tuple indicating the shape of the top-left block.
reg_shape : tuple
A single tuple indicating the shape of the regular block.
shape : tuple (int, int)
Total number of elements in the array.
sparse : boolean, optional (default=False)
Whether this array stores sparse data.
delete : boolean, optional (default=True)
Whether to call compss_delete_object on the blocks when the garbage
collector deletes this ds-array.
Attributes
----------
shape : tuple (int, int)
Total number of elements in the array.
"""
def __init__(self, blocks, top_left_shape, reg_shape, shape, sparse,
delete=True):
self._validate_blocks(blocks)
self._blocks = blocks
self._top_left_shape = top_left_shape
self._reg_shape = reg_shape
self._n_blocks = (len(blocks), len(blocks[0]))
self._shape = shape
self._sparse = sparse
self._delete = delete
def __del__(self):
if self._delete:
[compss_delete_object(b) for r_block in self._blocks for b in
r_block]
def __str__(self):
return "ds-array(blocks=(...), top_left_shape=%r, reg_shape=%r, " \
"shape=%r, sparse=%r)" % (
self._top_left_shape, self._reg_shape, self.shape,
self._sparse)
def __repr__(self):
return "ds-array(blocks=(...), top_left_shape=%r, reg_shape=%r, " \
"shape=%r, sparse=%r)" % (
self._top_left_shape, self._reg_shape, self.shape,
self._sparse)
def __matmul__(self, x):
if self.shape[1] != x.shape[0]:
raise ValueError(
"Cannot multiply ds-arrays of shapes %r and %r" % (
self.shape, x.shape))
if self._n_blocks[1] != x._n_blocks[0] or \
self._reg_shape[1] != x._reg_shape[0] or \
self._top_left_shape[1] != x._top_left_shape[0]:
raise ValueError("Cannot multiply ds-arrays with incompatible "
"number of blocks or different block shapes.")
if self._sparse != x._sparse:
raise ValueError("Cannot multiply sparse and dense ds-arrays.")
n_blocks = (self._n_blocks[0], x._n_blocks[1])
blocks = Array._get_out_blocks(n_blocks)
for i in range(n_blocks[0]):
for j in range(n_blocks[1]):
hblock = self._blocks[i]
vblock = [x._blocks[k][j] for k in range(len(x._blocks))]
blocks[i][j] = _multiply_block_groups(hblock, vblock)
shape = (self.shape[0], x.shape[1])
tl_shape = (self._top_left_shape[0], x._top_left_shape[1])
reg_shape = (self._reg_shape[0], x._reg_shape[1])
return Array(blocks=blocks, top_left_shape=tl_shape,
reg_shape=reg_shape, shape=shape, sparse=self._sparse)
def __getitem__(self, arg):
# return a single row
if isinstance(arg, int):
return self._get_by_lst_rows(rows=[arg])
# list of indices for rows
elif isinstance(arg, list) or isinstance(arg, np.ndarray):
return self._get_by_lst_rows(rows=arg)
# slicing only rows
elif isinstance(arg, slice):
return self._get_slice(rows=arg, cols=slice(None, None))
# we have indices for both dimensions
if not isinstance(arg, tuple):
raise IndexError("Invalid indexing information: %s" % arg)
rows, cols = arg # unpack 2-arguments
# returning a single element
if isinstance(rows, int) and isinstance(cols, int):
return self._get_single_element(i=rows, j=cols)
# all rows (slice : for rows) and list of indices for columns
elif isinstance(rows, slice) and \
(isinstance(cols, list) or isinstance(cols, np.ndarray)):
return self._get_by_lst_cols(cols=cols)
# slicing both dimensions
elif isinstance(rows, slice) and isinstance(cols, slice):
return self._get_slice(rows, cols)
elif isinstance(rows, slice) and isinstance(cols, int):
raise NotImplementedError("Single column indexing not supported.")
raise IndexError("Invalid indexing information: %s" % str(arg))
def __setitem__(self, key, value):
if isinstance(key, tuple) and all(isinstance(v, int) for v in key):
if np.isscalar(value):
if key[0] >= self.shape[0] or key[1] >= self.shape[1] or \
key[0] < 0 or key[1] < 0:
raise IndexError("Index %r is out of bounds for ds-array "
"with shape %r." % (key, self.shape))
bi, bj = self._get_containing_block(*key)
vi, vj = self._coords_in_block(bi, bj, *key)
_set_value(self._blocks[bi][bj], vi, vj, value)
else:
raise ValueError("Scalar value is required when "
"indexing by two integers.")
elif isinstance(key, tuple) and isinstance(key[0], slice)\
and isinstance(key[1], int):
rows, cols = key
r_start, r_stop = rows.start, rows.stop
r_start = 0 if r_start is None else r_start
r_stop = self.shape[0] if r_stop is None else r_stop
if r_stop - r_start != value.shape[0]:
raise IndexError("Incorrect shape of the "
f"given array: {value.shape}")
dims = len(value.shape)
if dims == 2 and value.shape[1] != 1:
raise IndexError("A column vector is required"
"for setting a column.")
if dims > 2:
raise IndexError("Arrays of dimensions > 2 are not accepted.")
if dims == 1:
value = value.reshape((value.shape[0], 1))
self._set_column((r_start, r_stop), cols, value)
else:
raise NotImplementedError(
f"Provided indexing by {type(key)} is not implemented."
)
def __pow__(self, power, modulo=None):
if not np.isscalar(power):
raise NotImplementedError("Power is only supported for scalars")
return _apply_elementwise(Array._power, self, power)
def __sub__(self, other):
if self.shape[1] != other.shape[1] or other.shape[0] != 1:
raise NotImplementedError("Subtraction not implemented for the "
"given objects")
# matrix - vector
blocks = []
for hblock in self._iterator("rows"):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, other._blocks,
Array._subtract, out_blocks)
blocks.append(out_blocks)
return Array(blocks, self._top_left_shape, self._reg_shape,
self.shape, self._sparse)
def __isub__(self, other):
if self.shape[1] != other.shape[1] or (other.shape[0] != 1 and
(other.shape[0] != self.shape[0]
or other._reg_shape[0] !=
self._reg_shape[0])):
raise NotImplementedError("Reverse subtraction not "
"implemented for the "
"given objects")
if other.shape[0] == self.shape[0] and other._reg_shape[0]\
== self._reg_shape[0]:
if other.shape[0] == self.shape[0] and \
other._reg_shape[0] == self._reg_shape[0]:
if self._reg_shape[1] != other._reg_shape[1]:
raise ValueError("incorrect block sizes for the requested "
f"subtraction ("
f"{self._reg_shape[0]}"", "
f"{self._reg_shape[1]} !="
f"{other._reg_shape[0]}"", "
f"{other._reg_shape[1]})")
if self._top_left_shape != other._top_left_shape:
raise ValueError("Incompatible block sizes of the "
"top left block of the matrices"
"b._top_left_shape != b._top_left_shape")
# matrix - matrix
blocks = []
for hblock, others in zip(self._iterator("rows"),
other._iterator("rows")):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, others._blocks,
Array._subtract, out_blocks)
blocks.append(out_blocks)
compss_delete_object(self._blocks)
self._blocks = blocks
return self
# matrix - vector
blocks = []
for hblock in self._iterator("rows"):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, other._blocks,
Array._subtract, out_blocks)
blocks.append(out_blocks)
compss_delete_object(self._blocks)
self._blocks = blocks
return self
def __add__(self, other):
if self.shape[1] != other.shape[1] or other.shape[0] != 1:
raise NotImplementedError("Addition not implemented for the "
"given objects")
# matrix + vector
blocks = []
for hblock in self._iterator("rows"):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, other._blocks,
Array._add, out_blocks)
blocks.append(out_blocks)
return Array(blocks, self._top_left_shape, self._reg_shape,
self.shape, self._sparse)
def __iadd__(self, other):
if self.shape[1] != other.shape[1] or (other.shape[0] != 1 and
(other.shape[0] != self.shape[0]
or other._reg_shape[0] !=
self._reg_shape[0])):
raise NotImplementedError("Self addition not implemented for the "
"given objects")
if other.shape[0] == self.shape[0] and \
other._reg_shape[0] == self._reg_shape[0]:
if self._reg_shape[1] != other._reg_shape[1]:
raise ValueError("incorrect block sizes for the requested "
f"addition ("
f"{self._reg_shape[0]}"", "
f"{self._reg_shape[1]} !="
f"{other._reg_shape[0]}"", "
f"{other._reg_shape[1]})")
if self._top_left_shape != other._top_left_shape:
raise ValueError("Incompatible block sizes of the "
"top left block of the matrices"
"b._top_left_shape != b._top_left_shape")
# matrix + matrix
blocks = []
for hblock, others in zip(self._iterator("rows"),
other._iterator("rows")):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, others._blocks,
Array._add, out_blocks)
blocks.append(out_blocks)
compss_delete_object(self._blocks)
self._blocks = blocks
return self
# matrix + vector
blocks = []
for hblock in self._iterator("rows"):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, other._blocks,
Array._add, out_blocks)
blocks.append(out_blocks)
compss_delete_object(self._blocks)
self._blocks = blocks
return self
def __truediv__(self, other):
if not np.isscalar(other):
raise NotImplementedError("Non scalar division not supported")
return _apply_elementwise(operator.truediv, self, other)
def __mul__(self, other):
if self.shape[1] != other.shape[1] or other.shape[0] != 1:
raise NotImplementedError("Multiplication not implemented for the "
"given arrays")
# matrix * vector
blocks = []
for hblock in self._iterator("rows"):
out_blocks = [object() for _ in range(hblock._n_blocks[1])]
_combine_blocks(hblock._blocks, other._blocks,
operator.mul, out_blocks)
blocks.append(out_blocks)
return Array(blocks, self._top_left_shape, self._reg_shape,
self.shape, self._sparse)
@property
def shape(self):
"""
Total shape of the ds-array
"""
return self._shape
@property
def T(self):
""" Returns the transpose of this ds-array """
return self.transpose()
@staticmethod
def _subtract(a, b):
sparse = issparse(a)
# needed because subtract with scipy.sparse does not support
# broadcasting
if sparse:
a = a.toarray()
if issparse(b):
b = b.toarray()
if sparse:
return csr_matrix(a - b)
else:
return a - b
@staticmethod
def _add(a, b):
sparse = issparse(a)
# needed because subtract with scipy.sparse does not support
# broadcasting
if sparse:
a = a.toarray()
if issparse(b):
b = b.toarray()
if sparse:
return csr_matrix(a + b)
else:
return a + b
@staticmethod
def _power(x_np, power):
if issparse(x_np):
return sp.csr_matrix.power(x_np, power)
else:
return x_np ** power
@staticmethod
def _validate_blocks(blocks):
if len(blocks) == 0 or len(blocks[0]) == 0:
raise AttributeError('Blocks must a list of lists, with at least'
' an empty numpy/scipy matrix.')
row_length = len(blocks[0])
for i in range(1, len(blocks)):
if len(blocks[i]) != row_length:
raise AttributeError(
'All rows must contain the same number of blocks.')
@staticmethod
def _merge_blocks(blocks):
"""
Helper function that merges the _blocks attribute of a ds-array into
a single ndarray / sparse matrix.
"""
sparse = None
b0 = blocks[0][0]
if sparse is None:
sparse = issparse(b0)
if sparse:
ret = sp.bmat(blocks, format=b0.getformat(), dtype=b0.dtype)
else:
ret = np.block(blocks)
return ret
@staticmethod
def _get_out_blocks(n_blocks):
"""
Helper function that builds empty lists of lists to be filled as
parameter of type COLLECTION_OUT
"""
return [[object() for _ in range(n_blocks[1])]
for _ in range(n_blocks[0])]
@staticmethod
def _get_block_shape_static(i, j, x):
reg_blocks = (max(0, x._n_blocks[0] - 2),
max(0, x._n_blocks[1] - 2))
remain_shape = (x.shape[0] - x._top_left_shape[0] -
reg_blocks[0] * x._reg_shape[0],
x.shape[1] - x._top_left_shape[1] -
reg_blocks[1] * x._reg_shape[1])
if i == 0:
shape0 = x._top_left_shape[0]
elif i < x._n_blocks[0] - 1:
shape0 = x._reg_shape[0]
else:
shape0 = remain_shape[0]
if j == 0:
shape1 = x._top_left_shape[1]
elif j < x._n_blocks[1] - 1:
shape1 = x._reg_shape[1]
else:
shape1 = remain_shape[1]
return (shape0, shape1)
@staticmethod
def _rechunk(blocks, shape, block_size, shape_f, *args, **kwargs):
""" Re-partitions a set of blocks into a new ds-array of the given
block size.
shape_f is a function that returns the shape of the (i,j) block. It
has to take at least two indices as arguments. This function is
needed to rechunk an irregular set of blocks such as in the ds.kron
operation, where the shape of a block is not trivial to compute.
"""
if shape[0] < block_size[0] or shape[1] < block_size[1]:
raise ValueError("Block size is greater than the array")
cur_element = [0, 0]
tl_shape = list(block_size)
n_blocks = (ceil(shape[0] / block_size[0]),
ceil(shape[1] / block_size[1]))
tmp_blocks = [[[] for _ in range(n_blocks[1])] for _ in
range(n_blocks[0])]
# iterate over each block, split it if necessary, and place each
# part into a new list of blocks to form the output blocks later
for i in range(len(blocks)):
cur_element[1] = 0
tl_shape[1] = block_size[1]
for j in range(len(blocks[i])):
bshape = shape_f(i, j, *args, **kwargs)
out_n_blocks = (ceil((bshape[0] - tl_shape[0]) /
block_size[0]) + 1,
ceil((bshape[1] - tl_shape[1]) /
block_size[1]) + 1)
out_blocks = Array._get_out_blocks(out_n_blocks)
_split_block(blocks[i][j], list(tl_shape), block_size,
out_blocks)
cur_block = (int(cur_element[0] / block_size[0]),
int(cur_element[1] / block_size[1]))
# distribute each part of the original block into the
# corresponding new blocks. cur_block keeps track of the new
# block that we are generating, but some parts of the
# original block might go to neighbouring new blocks
for m in range(len(out_blocks)):
for n in range(len(out_blocks[m])):
bi = cur_block[0] + m
bj = cur_block[1] + n
tmp_blocks[bi][bj].append(out_blocks[m][n])
tl_shape[1] = block_size[1] - ((bshape[1] - tl_shape[1])
% block_size[1])
cur_element[1] += bshape[1]
tl_shape[0] = block_size[0] - ((bshape[0] - tl_shape[0]) %
block_size[0])
cur_element[0] += bshape[0]
final_blocks = Array._get_out_blocks(n_blocks)
irr_shape = (shape[0] - (n_blocks[0] - 1) * block_size[0],
shape[1] - (n_blocks[1] - 1) * block_size[1])
# merges the different parts of each original block into new blocks
# of the given block size
for i in range(n_blocks[0]):
bs0 = block_size[0] if i < n_blocks[0] - 1 else irr_shape[0]
for j in range(n_blocks[1]):
bs1 = block_size[1] if j < n_blocks[1] - 1 else irr_shape[1]
# if there is more than one part, merge them, otherwise the
# block is already of the wanted block size
if len(tmp_blocks[i][j]) > 1:
final_blocks[i][j] = _assemble_blocks(tmp_blocks[i][j],
(bs0, bs1))
[compss_delete_object(block) for block in tmp_blocks[i][j]]
else:
final_blocks[i][j] = tmp_blocks[i][j][0]
return Array(final_blocks, block_size, block_size, shape, False)
def _is_regular(self):
return self._reg_shape == self._top_left_shape
def _get_row_shape(self, row_idx):
if row_idx == 0:
return self._top_left_shape[0], self.shape[1]
if row_idx < self._n_blocks[0] - 1:
return self._reg_shape[0], self.shape[1]
# this is the last chunk of rows, number of rows might be smaller
reg_blocks = self._n_blocks[0] - 2
if reg_blocks < 0:
reg_blocks = 0
n_r = \
self.shape[0] - self._top_left_shape[0] - reg_blocks * \
self._reg_shape[0]
return n_r, self.shape[1]
def _get_col_shape(self, col_idx):
if col_idx == 0:
return self.shape[0], self._top_left_shape[1]
if col_idx < self._n_blocks[1] - 1:
return self.shape[0], self._reg_shape[1]
# this is the last chunk of cols, number of cols might be smaller
reg_blocks = self._n_blocks[1] - 2
if reg_blocks < 0:
reg_blocks = 0
n_c = \
self.shape[1] - self._top_left_shape[1] - \
reg_blocks * self._reg_shape[1]
return self.shape[0], n_c
def _get_block_shape(self, i, j):
return Array._get_block_shape_static(i, j, self)
def _get_row_block(self, i):
row_shape = self._get_row_shape(i)
return Array(blocks=[self._blocks[i]],
top_left_shape=(row_shape[0], self._top_left_shape[1]),
reg_shape=self._reg_shape, shape=row_shape,
sparse=self._sparse, delete=False)
def _get_col_block(self, i):
col_shape = self._get_col_shape(i)
col_blocks = [[self._blocks[j][i]] for j in range(self._n_blocks[0])]
return Array(blocks=col_blocks,
top_left_shape=(self._top_left_shape[0], col_shape[1]),
reg_shape=self._reg_shape, shape=col_shape,
sparse=self._sparse, delete=False)
def _iterator(self, axis=0):
# iterate through rows
if axis == 0 or axis == 'rows':
for i in range(self._n_blocks[0]):
yield self._get_row_block(i)
# iterate through columns
elif axis == 1 or axis == 'columns':
for j in range(self._n_blocks[1]):
yield self._get_col_block(j)
else:
raise Exception(
"Axis must be [0|'rows'] or [1|'columns']. Got: %s" % axis)
def _get_containing_block(self, i, j):
"""
Returns the indices of the block containing coordinate (i, j)
"""
bi0, bj0 = self._top_left_shape
bn, bm = self._reg_shape
# If first block is irregular, we need to add an offset to compute the
# containing block indices
offset_i, offset_j = bn - bi0, bm - bj0
block_i = (i + offset_i) // bn
block_j = (j + offset_j) // bm
# if blocks are out of bounds, assume the element belongs to last block
if block_i >= self._n_blocks[0]:
block_i = self._n_blocks[0] - 1
if block_j >= self._n_blocks[1]:
block_j = self._n_blocks[1] - 1
return block_i, block_j
def _set_column(self, i: tuple, j: int, value_array):
"""
Sets rows of a particular column of the whole array
"""
k = i[0]
array_offset = 0
j_block = None
while k < i[1]:
row, col = self._get_containing_block(k, j)
add_offset = min(i[1], self._top_left_shape[0]) - i[0] \
if row == 0 \
else min(
i[1], self._top_left_shape[0] + row * self._reg_shape[0]) - k
block_row_start = i[0] if row == 0 else\
(k - self._top_left_shape[0]) % self._reg_shape[0]
if j_block is None:
j_block = min(j, self._top_left_shape[1]) if col == 0 \
else (j - self._top_left_shape[1]) % self._reg_shape[1]
_block_set_slice(
self._blocks[row][col],
(block_row_start, block_row_start + add_offset),
(j_block, j_block + 1),
value_array[array_offset:array_offset+add_offset]
)
k += add_offset
array_offset += add_offset
def _coords_in_block(self, block_i, block_j, i, j):
"""
Return the conversion of the coords (i, j) in ds-array space to
coordinates in the given block (block_i, block_j) space.
"""
local_i, local_j = i, j
if block_i > 0:
reg_blocks = (block_i - 1) if (block_i - 1) >= 0 else 0
local_i = \
i - self._top_left_shape[0] - \
reg_blocks * self._reg_shape[0]
if block_j > 0:
reg_blocks = (block_j - 1) if (block_j - 1) >= 0 else 0
local_j = \
j - self._top_left_shape[1] - \
reg_blocks * self._reg_shape[1]
return local_i, local_j
def _get_single_element(self, i, j):
"""
Return the element in (i, j) as a ds-array with a single element.
"""
# we are returning a single element
if i > self.shape[0] or j > self.shape[1]:
raise IndexError("Shape is ", self.shape)
bi, bj = self._get_containing_block(i, j)
local_i, local_j = self._coords_in_block(bi, bj, i, j)
block = self._blocks[bi][bj]
# returns an list containing a single element
element = _get_item(local_i, local_j, block)
return Array(blocks=[[element]], top_left_shape=(1, 1),
reg_shape=(1, 1), shape=(1, 1), sparse=False)
def _get_slice(self, rows, cols):
"""
Returns a slice of the ds-array defined by the slices rows / cols.
Only steps (as defined by slice.step) with value 1 can be used.
"""
if (rows.step is not None and rows.step != 1) or \
(cols.step is not None and cols.step != 1):
raise NotImplementedError("Variable steps not supported, contact"
" the dislib team or open an issue "
"in github.")
# rows and cols are read-only
r_start, r_stop = rows.start, rows.stop
c_start, c_stop = cols.start, cols.stop
if r_start is None:
r_start = 0
if c_start is None:
c_start = 0
if r_stop is None or r_stop > self.shape[0]:
r_stop = self.shape[0]
if c_stop is None or c_stop > self.shape[1]:
c_stop = self.shape[1]
if r_start < 0 or r_stop < 0 or c_start < 0 or c_stop < 0:
raise NotImplementedError("Negative indexes not supported, contact"
" the dislib team or open an issue "
"in github.")
n_rows = r_stop - r_start
n_cols = c_stop - c_start
# If the slice is empty (no rows or no columns), return a ds-array with
# a single empty block. This empty block is required by the Array
# constructor.
if n_rows <= 0 or n_cols <= 0:
n_rows = max(0, n_rows)
n_cols = max(0, n_cols)
if self._sparse:
empty_block = csr_matrix((0, 0))
else:
empty_block = np.empty((0, 0))
res = Array(blocks=[[empty_block]], top_left_shape=self._reg_shape,
reg_shape=self._reg_shape, shape=(n_rows, n_cols),
sparse=self._sparse)
return res
# get the coordinates of top-left and bot-right corners
i_0, j_0 = self._get_containing_block(r_start, c_start)
i_n, j_n = self._get_containing_block(r_stop - 1, c_stop - 1)
# Number of blocks to be returned
n_blocks = i_n - i_0 + 1
m_blocks = j_n - j_0 + 1
out_blocks = self._get_out_blocks((n_blocks, m_blocks))
i_indices = range(i_0, i_n + 1)
j_indices = range(j_0, j_n + 1)
for out_i, i in enumerate(i_indices):
for out_j, j in enumerate(j_indices):
top, left, bot, right = None, None, None, None
if out_i == 0:
top, _ = self._coords_in_block(i_0, j_0, r_start, c_start)
if out_i == len(i_indices) - 1:
bot, _ = self._coords_in_block(i_n, j_n, r_stop, c_stop)
if out_j == 0:
_, left = self._coords_in_block(i_0, j_0, r_start, c_start)
if out_j == len(j_indices) - 1:
_, right = self._coords_in_block(i_n, j_n, r_stop, c_stop)
boundaries = (top, left, bot, right)
fb = _filter_block(block=self._blocks[i][j],
boundaries=boundaries)
out_blocks[out_i][out_j] = fb
# The shape of the top left block of the sliced array depends on the
# slice. To compute it, we need the shape of the block of
# the original array where the sliced array starts. This block can
# be regular or irregular (i.e., the block is on the edges).
b0, b1 = self._reg_shape
if i_0 == 0:
# block is at the top
b0 = self._top_left_shape[0]
elif i_0 == self._n_blocks[0] - 1:
# block is at the bottom (can be regular or irregular)
b0 = (self.shape[0] - self._top_left_shape[0]) % self._reg_shape[0]
if b0 == 0:
b0 = self._reg_shape[0]
if j_0 == 0:
# block is leftmost
b1 = self._top_left_shape[1]
elif j_0 == self._n_blocks[1] - 1:
# block is rightmost (can be regular or irregular)
b1 = (self.shape[1] - self._top_left_shape[1]) % self._reg_shape[1]
if b1 == 0:
b1 = self._reg_shape[1]
block_shape = (b0, b1)
top, left = self._coords_in_block(i_0, j_0, r_start, c_start)
bi0 = min(n_rows, block_shape[0] - (top % block_shape[0]))
bj0 = min(n_cols, block_shape[1] - (left % block_shape[1]))
# Regular blocks shape is the same
bn, bm = self._reg_shape
out_shape = n_rows, n_cols
res = Array(blocks=out_blocks, top_left_shape=(bi0, bj0),
reg_shape=(bn, bm), shape=out_shape,
sparse=self._sparse, delete=False)
return res
def _get_by_lst_rows(self, rows):
"""
Returns a slice of the ds-array defined by the lists of indices in
rows.
"""
# create dict where each key contains the adjusted row indices for that
# block of rows
adj_row_idxs = defaultdict(list)
for row_idx in rows:
containing_block = self._get_containing_block(row_idx, 0)[0]
adj_idx = self._coords_in_block(containing_block, 0, row_idx, 0)[0]
adj_row_idxs[containing_block].append(adj_idx)
row_blocks = []
total_rows = 0
for rowblock_idx, row in enumerate(self._iterator(axis='rows')):
# create an empty list for the filtered row (single depth)
rows_in_block = len(adj_row_idxs[rowblock_idx])
total_rows += rows_in_block
# only launch the task if we are selecting rows from that block
if rows_in_block > 0:
row_block = _filter_rows(blocks=row._blocks,
rows=adj_row_idxs[rowblock_idx])
row_blocks.append((rows_in_block, [row_block]))
# now we need to merge the rowblocks until they have as much rows as
# self._reg_shape[0] (i.e. number of rows per block)
n_rows = 0
to_merge = []
final_blocks = []
skip = 0
for rows_in_block, row in row_blocks:
to_merge.append(row)
n_rows += rows_in_block
# enough rows to merge into a row_block
if n_rows >= self._reg_shape[0]:
n_blocks = ceil(self.shape[1] / self._reg_shape[1])
out_blocks = [object() for _ in range(n_blocks)]
_merge_rows(to_merge, out_blocks, self._reg_shape, skip)
final_blocks.append(out_blocks)
# if we didn't take all rows, we keep the last block and
# remember to skip the rows that have been merged
if n_rows > self._reg_shape[0]:
to_merge = [row]
n_rows = n_rows - self._reg_shape[0]
skip = rows_in_block - n_rows
else:
to_merge = []
n_rows = 0
skip = 0
if n_rows > 0:
n_blocks = ceil(self.shape[1] / self._reg_shape[1])
out_blocks = [object() for _ in range(n_blocks)]
_merge_rows(to_merge, out_blocks, self._reg_shape, skip)
final_blocks.append(out_blocks)
top_left_shape = (min(total_rows, self._reg_shape[0]),
self._reg_shape[1])
return Array(blocks=final_blocks, top_left_shape=top_left_shape,
reg_shape=self._reg_shape,
shape=(len(rows), self._shape[1]), sparse=self._sparse)
def _get_by_lst_cols(self, cols):
"""
Returns a slice of the ds-array defined by the lists of indices in
cols.
"""
# create dict where each key contains the adjusted row indices for that
# block of rows
adj_col_idxs = defaultdict(list)
for col_idx in cols:
containing_block = self._get_containing_block(0, col_idx)[1]
adj_idx = self._coords_in_block(0, containing_block, 0, col_idx)[1]
adj_col_idxs[containing_block].append(adj_idx)
col_blocks = []
total_cols = 0
for colblock_idx, col in enumerate(self._iterator(axis='columns')):
# create an empty list for the filtered row (single depth)
cols_in_block = len(adj_col_idxs[colblock_idx])
total_cols += cols_in_block
# only launch the task if we are selecting rows from that block
if cols_in_block > 0:
col_block = _filter_cols(blocks=col._blocks,
cols=adj_col_idxs[colblock_idx])
col_blocks.append((cols_in_block, col_block))
# now we need to merge the rowblocks until they have as much rows as
# self._reg_shape[0] (i.e. number of rows per block)
n_cols = 0
to_merge = []
final_blocks = []
skip = 0
for cols_in_block, col in col_blocks:
to_merge.append(col)
n_cols += cols_in_block
# enough cols to merge into a col_block
if n_cols >= self._reg_shape[1]:
n_blocks = ceil(self.shape[0] / self._reg_shape[0])
out_blocks = [object() for _ in range(n_blocks)]
_merge_cols([to_merge], out_blocks, self._reg_shape, skip)
final_blocks.append(out_blocks)
# if we didn't take all cols, we keep the last block and
# remember to skip the cols that have been merged
if n_cols > self._reg_shape[1]:
to_merge = [col]
n_cols = n_cols - self._reg_shape[1]
skip = cols_in_block - n_cols
else:
to_merge = []
n_cols = 0
skip = 0
if n_cols > 0:
n_blocks = ceil(self.shape[0] / self._reg_shape[0])
out_blocks = [object() for _ in range(n_blocks)]
_merge_cols([to_merge], out_blocks, self._reg_shape, skip)
final_blocks.append(out_blocks)
# list are in col-order transpose them for the correct ordering
final_blocks = list(map(list, zip(*final_blocks)))
top_left_shape = (self._reg_shape[0],
min(total_cols, self._reg_shape[1]))
return Array(blocks=final_blocks, top_left_shape=top_left_shape,
reg_shape=self._reg_shape,
shape=(self._shape[0], len(cols)), sparse=self._sparse)
def transpose(self, mode='rows'):
"""
Returns the transpose of the ds-array following the method indicated by
mode. 'All' uses a single task to transpose all the blocks (slow with
high number of blocks). 'rows' and 'columns' transpose each block of
rows or columns independently (i.e. a task per row/col block).
Parameters
----------
mode : string, optional (default=rows)
Array of samples.
Returns
-------
dsarray : ds-array
A transposed ds-array.
"""
if mode == 'all':
n, m = self._n_blocks[0], self._n_blocks[1]