/
__init__.py
752 lines (442 loc) · 14.2 KB
/
__init__.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import operator
from collections import Iterable
from ...compat import reduce, builtins
from .array import SparseNDArray
from .matrix import SparseMatrix
from .vector import SparseVector
from .core import issparse, get_sparse_module
from .coo import COONDArray
def asarray(x, shape=None):
from .core import issparse
if issparse(x):
return SparseNDArray(x, shape=shape)
return x
def add(a, b, **_):
try:
return a + b
except TypeError:
if hasattr(b, '__radd__'):
return b.__radd__(a)
raise
def subtract(a, b, **_):
try:
return a - b
except TypeError:
if hasattr(b, '__rsub__'):
return b.__rsub__(a)
raise
def multiply(a, b, **_):
try:
return a * b
except TypeError:
if hasattr(b, '__rmul__'):
return b.__rmul__(a)
raise
def divide(a, b, **_):
try:
return a / b
except TypeError:
if hasattr(b, '__rdiv__'):
return b.__rdiv__(a)
raise
def true_divide(a, b, **_):
try:
return a / b
except TypeError:
if hasattr(b, '__rtruediv__'):
return b.__rtruediv__(a)
raise
def floor_divide(a, b, **_):
try:
return a // b
except TypeError:
if hasattr(b, '__rfloordiv__'):
return b.__rfloordiv__(a)
raise
def power(a, b, **_):
try:
return a ** b
except TypeError:
if hasattr(b, '__rpow__'):
return b.__rpow__(a)
raise
def mod(a, b, **_):
try:
return a % b
except TypeError:
if hasattr(b, '__rmod__'):
return b.__rmod__(a)
raise
def _call_bin(method, a, b, **kwargs):
from .core import get_array_module, cp, issparse
if hasattr(a, method):
res = getattr(a, method)(b, **kwargs)
else:
assert get_array_module(a) == get_array_module(b)
xp = get_array_module(a)
try:
res = getattr(xp, method)(a, b, **kwargs)
except TypeError:
if xp is cp and issparse(b):
res = getattr(xp, method)(a, b.toarray(), **kwargs)
else:
raise
if res is NotImplemented:
raise NotImplementedError
return res
def _call_unary(method, x, *args, **kwargs):
from .core import get_array_module
if hasattr(x, method):
res = getattr(x, method)(*args, **kwargs)
else:
xp = get_array_module(x)
res = getattr(xp, method)(x, *args, **kwargs)
if res is NotImplemented:
raise NotImplementedError
return res
def float_power(a, b, **kw):
return _call_bin('float_power', a, b, **kw)
def fmod(a, b, **kw):
return _call_bin('fmod', a, b, **kw)
def logaddexp(a, b, **kw):
return _call_bin('logaddexp', a, b, **kw)
def logaddexp2(a, b, **kw):
return _call_bin('logaddexp2', a, b, **kw)
def negative(x, **_):
return -x
def positive(x, **_):
return operator.pos(x)
def absolute(x, **_):
return builtins.abs(x)
abs = absolute
def fabs(x, **kw):
return _call_unary('fabs', x, **kw)
def rint(x, **kw):
return _call_unary('rint', x, **kw)
def sign(x, **kw):
return _call_unary('sign', x, **kw)
def conj(x, **kw):
return _call_unary('conj', x, **kw)
def exp(x, **kw):
return _call_unary('exp', x, **kw)
def exp2(x, **kw):
return _call_unary('exp2', x, **kw)
def log(x, **kw):
return _call_unary('log', x, **kw)
def log2(x, **kw):
return _call_unary('log2', x, **kw)
def log10(x, **kw):
return _call_unary('log10', x, **kw)
def expm1(x, **kw):
return _call_unary('expm1', x, **kw)
def log1p(x, **kw):
return _call_unary('log1p', x, **kw)
def sqrt(x, **kw):
return _call_unary('sqrt', x, **kw)
def square(x, **kw):
return _call_unary('square', x, **kw)
def cbrt(x, **kw):
return _call_unary('cbrt', x, **kw)
def reciprocal(x, **kw):
return _call_unary('reciprocal', x, **kw)
def equal(a, b, **_):
try:
return a == b
except TypeError:
return b == a
def not_equal(a, b, **_):
try:
return a != b
except TypeError:
return b != a
def less(a, b, **_):
try:
return a < b
except TypeError:
return b > a
def less_equal(a, b, **_):
try:
return a <= b
except TypeError:
return b >= a
def greater(a, b, **_):
try:
return a > b
except TypeError:
return b < a
def greater_equal(a, b, **_):
try:
return a >= b
except TypeError:
return b <= a
def logical_and(a, b, **kw):
return _call_bin('logical_and', a, b, **kw)
def logical_or(a, b, **kw):
return _call_bin('logical_or', a, b, **kw)
def logical_xor(a, b, **kw):
return _call_bin('logical_xor', a, b, **kw)
def logical_not(x, **kw):
return _call_unary('logical_not', x, **kw)
def isclose(a, b, **kw):
return _call_bin('isclose', a, b, **kw)
def bitwise_and(a, b, **_):
try:
return a & b
except TypeError:
return b & a
def bitwise_or(a, b, **_):
try:
return a | b
except TypeError:
return b | a
def bitwise_xor(a, b, **_):
try:
return operator.xor(a, b)
except TypeError:
return operator.xor(b, a)
def invert(x, **_):
return ~x
def left_shift(a, b, **_):
return a << b
def right_shift(a, b, **_):
return a >> b
def sin(x, **kw):
return _call_unary('sin', x, **kw)
def cos(x, **kw):
return _call_unary('cos', x, **kw)
def tan(x, **kw):
return _call_unary('tan', x, **kw)
def arcsin(x, **kw):
return _call_unary('arcsin', x, **kw)
def arccos(x, **kw):
return _call_unary('arccos', x, **kw)
def arctan(x, **kw):
return _call_unary('arctan', x, **kw)
def arctan2(a, b, **kw):
return _call_bin('arctan2', a, b, **kw)
def hypot(a, b, **kw):
return _call_bin('hypot', a, b, **kw)
def sinh(x, **kw):
return _call_unary('sinh', x, **kw)
def cosh(x, **kw):
return _call_unary('cosh', x, **kw)
def tanh(x, **kw):
return _call_unary('tanh', x, **kw)
def arcsinh(x, **kw):
return _call_unary('arcsinh', x, **kw)
def arccosh(x, **kw):
return _call_unary('arccosh', x, **kw)
def around(x, **kw):
return _call_unary('around', x, **kw)
def arctanh(x, **kw):
return _call_unary('arctanh', x, **kw)
def deg2rad(x, **kw):
return _call_unary('deg2rad', x, **kw)
def rad2deg(x, **kw):
return _call_unary('rad2deg', x, **kw)
def angle(x, **kw):
return _call_unary('angle', x, **kw)
def isinf(x, **kw):
return _call_unary('isinf', x, **kw)
def isnan(x, **kw):
return _call_unary('isnan', x, **kw)
def signbit(x, **kw):
return _call_unary('signbit', x, **kw)
def dot(a, b, sparse=True, **_):
from .core import issparse
if not issparse(a):
return a.dot(b)
return a.dot(b, sparse=sparse)
def tensordot(a, b, axes=2, sparse=True):
if isinstance(axes, Iterable):
a_axes, b_axes = axes
else:
a_axes = tuple(range(a.ndim - 1, a.ndim - axes - 1, -1))
b_axes = tuple(range(0, axes))
if isinstance(a_axes, Iterable):
a_axes = tuple(a_axes)
else:
a_axes = (a_axes,)
if isinstance(b_axes, Iterable):
b_axes = tuple(b_axes)
else:
b_axes = (b_axes,)
if a_axes == (a.ndim - 1,) and b_axes == (b.ndim - 2,):
return dot(a, b, sparse=sparse)
if a.ndim == b.ndim == 2:
if a_axes == (a.ndim - 1,) and b_axes == (b.ndim - 1,):
# inner product of multiple dims
return dot(a, b.T, sparse=sparse)
if a.ndim == 1 or b.ndim == 1:
return dot(a, b, sparse=sparse)
raise NotImplementedError
def matmul(a, b, sparse=True, **_):
return dot(a, b, sparse=sparse)
def concatenate(tensors, axis=0):
has_sparse = any(issparse(t) for t in tensors)
if has_sparse:
tensors = [asarray(get_sparse_module(t).csr_matrix(t), t.shape) for t in tensors]
return reduce(lambda a, b: _call_bin('concatenate', a, b, axis=axis), tensors)
def transpose(tensor, axes=None):
return _call_unary('transpose', tensor, axes=axes)
def swapaxes(tensor, axis1, axis2):
return _call_unary('swapaxes', tensor, axis1, axis2)
def sum(tensor, axis=None, **kw):
return _call_unary('sum', tensor, axis=axis, **kw)
def prod(tensor, axis=None, **kw):
return _call_unary('prod', tensor, axis=axis, **kw)
def amax(tensor, axis=None, **kw):
return _call_unary('amax', tensor, axis=axis, **kw)
max = amax
def amin(tensor, axis=None, **kw):
return _call_unary('amin', tensor, axis=axis, **kw)
min = amin
def all(tensor, axis=None, **kw):
return _call_unary('all', tensor, axis=axis, **kw)
def any(tensor, axis=None, **kw):
return _call_unary('all', tensor, axis=axis, **kw)
def mean(tensor, axis=None, **kw):
return _call_unary('mean', tensor, axis=axis, **kw)
def nansum(tensor, axis=None, **kw):
return _call_unary('nansum', tensor, axis=axis, **kw)
def nanprod(tensor, axis=None, **kw):
return _call_unary('nanprod', tensor, axis=axis, **kw)
def nanmax(tensor, axis=None, **kw):
return _call_unary('nanmax', tensor, axis=axis, **kw)
def nanmin(tensor, axis=None, **kw):
return _call_unary('nanmin', tensor, axis=axis, **kw)
def argmax(tensor, axis=None, **kw):
return _call_unary('argmax', tensor, axis=axis, **kw)
def nanargmax(tensor, axis=None, **kw):
return _call_unary('nanargmax', tensor, axis=axis, **kw)
def argmin(tensor, axis=None, **kw):
return _call_unary('argmin', tensor, axis=axis, **kw)
def nanargmin(tensor, axis=None, **kw):
return _call_unary('nanargmin', tensor, axis=axis, **kw)
def var(tensor, axis=None, **kw):
return _call_unary('var', tensor, axis=axis, **kw)
def cumsum(tensor, axis=None, **kw):
return _call_unary('cumsum', tensor, axis=axis, **kw)
def cumprod(tensor, axis=None, **kw):
return _call_unary('cumprod', tensor, axis=axis, **kw)
def nancumsum(tensor, axis=None, **kw):
return _call_unary('nancumsum', tensor, axis=axis, **kw)
def nancumprod(tensor, axis=None, **kw):
return _call_unary('nancumprod', tensor, axis=axis, **kw)
def count_nonzero(tensor, axis=None, **kw):
return _call_unary('count_nonzero', tensor, axis=axis, **kw)
def maximum(a, b, **kw):
return _call_bin('maximum', a, b, **kw)
def minimum(a, b, **kw):
return _call_bin('minimum', a, b, **kw)
def fmax(a, b, **kw):
return _call_bin('fmax', a, b, **kw)
def fmin(a, b, **kw):
return _call_bin('fmin', a, b, **kw)
def floor(x, **kw):
return _call_unary('floor', x, **kw)
def ceil(x, **kw):
return _call_unary('ceil', x, **kw)
def trunc(x, **kw):
return _call_unary('trunc', x, **kw)
def degrees(x, **kw):
return _call_unary('degrees', x, **kw)
def radians(x, **kw):
return _call_unary('radians', x, **kw)
def clip(a, a_max, a_min, **kw):
from .core import get_array_module
if hasattr(a, 'clip'):
res = getattr(a, 'clip')(a_max, a_min, **kw)
else:
xp = get_array_module(a)
res = getattr(xp, 'clip')(a, a_max, a_min **kw)
if res is NotImplemented:
raise NotImplementedError
return res
def iscomplex(x, **kw):
return _call_unary('iscomplex', x, **kw)
def real(x, **_):
return x.real
def imag(x, **_):
return x.imag
def fix(x, **kw):
return _call_unary('fix', x, **kw)
def i0(x, **kw):
return _call_unary('i0', x, **kw)
def nan_to_num(x, **kw):
return _call_unary('nan_to_num', x, **kw)
def copysign(a, b, **kw):
return _call_bin('copysign', a, b, **kw)
def nextafter(a, b, **kw):
return _call_bin('nextafter', a, b, **kw)
def spacing(x, **kw):
return _call_unary('spacing', x, **kw)
def ldexp(a, b, **kw):
return _call_bin('ldexp', a, b, **kw)
def frexp(x, **kw):
return _call_unary('frexp', x, **kw)
def modf(x, **kw):
return _call_unary('modf', x, **kw)
def sinc(x, **kw):
return _call_unary('sinc', x, **kw)
def isfinite(x, **kw):
return _call_unary('isfinite', x, **kw)
def isreal(x, **kw):
return _call_unary('isreal', x, **kw)
def where(cond, x, y):
if any([i.ndim != 2 for i in (cond, x, y)]):
raise NotImplementedError
from .matrix import where as matrix_where
return matrix_where(cond, x, y)
def digitize(x, bins, right=False):
return _call_unary('digitize', x, bins, right)
def repeat(a, repeats, axis=None):
return _call_unary('repeat', a, repeats, axis=axis)
def zeros(shape, dtype=float, gpu=False):
if len(shape) == 2:
from .matrix import zeros_sparse_matrix
return zeros_sparse_matrix(shape, dtype=dtype, gpu=gpu)
raise NotImplementedError
def ones_like(x):
from .core import get_array_module
return get_array_module(x).ones(x.shape)
def diag(v, k=0, gpu=False):
if v.ndim == 2:
raise NotImplementedError
assert v.ndim == 1
from .matrix import diag_sparse_matrix
return diag_sparse_matrix(v, k=k, gpu=gpu)
def eye(N, M=None, k=0, dtype=float, gpu=False):
from .matrix import eye_sparse_matrix
return eye_sparse_matrix(N, M=M, k=k, dtype=dtype, gpu=gpu)
def triu(m, k=0, gpu=False):
if m.ndim == 2:
from .matrix import triu_sparse_matrix
return triu_sparse_matrix(m, k=k, gpu=gpu)
raise NotImplementedError
def tril(m, k=0, gpu=False):
if m.ndim == 2:
from .matrix import tril_sparse_matrix
return tril_sparse_matrix(m, k=k, gpu=gpu)
raise NotImplementedError
def lu(m):
from .matrix import lu_sparse_matrix
return lu_sparse_matrix(m)
def solve_triangular(a, b, lower=False):
from .matrix import solve_triangular_sparse_matrix
return solve_triangular_sparse_matrix(a, b, lower=lower)