-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtest_op.py
More file actions
1479 lines (1249 loc) · 54 KB
/
Copy pathtest_op.py
File metadata and controls
1479 lines (1249 loc) · 54 KB
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 itertools
import numpy as np
import pytest
import graphblas as gb
from graphblas import (
agg,
backend,
binary,
config,
dtypes,
indexunary,
monoid,
op,
select,
semiring,
unary,
)
from graphblas.core import _supports_udfs as supports_udfs
from graphblas.core import lib, operator
from graphblas.core.operator import (
BinaryOp,
IndexUnaryOp,
Monoid,
SelectOp,
Semiring,
UnaryOp,
get_semiring,
)
from graphblas.dtypes import (
BOOL,
FP32,
FP64,
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
)
from graphblas.exceptions import DomainMismatch, UdfParseError
from .conftest import shouldhave
if dtypes._supports_complex:
from graphblas.dtypes import FC32, FC64
from graphblas import Matrix, Vector # isort:skip (for dask-graphblas)
suitesparse = backend == "suitesparse"
def orig_types(op):
return op.types.keys() - op.coercions.keys()
def test_operator_initialized():
assert operator.UnaryOp._initialized
assert operator.BinaryOp._initialized
assert operator.Monoid._initialized
assert operator.Semiring._initialized
def test_op_repr():
assert repr(unary.ainv) == "unary.ainv"
assert repr(binary.plus) == "binary.plus"
assert repr(monoid.times) == "monoid.times"
assert repr(semiring.plus_times) == "semiring.plus_times"
def test_unaryop():
assert unary.ainv["INT32"].gb_obj == lib.GrB_AINV_INT32
assert unary.ainv[dtypes.UINT16].gb_obj == lib.GrB_AINV_UINT16
if suitesparse:
assert orig_types(unary.ss.positioni) == {INT32, INT64}
assert orig_types(unary.ss.positionj1) == {INT32, INT64}
def test_binaryop():
assert binary.plus["INT32"].gb_obj == lib.GrB_PLUS_INT32
assert binary.plus[dtypes.UINT16].gb_obj == lib.GrB_PLUS_UINT16
if suitesparse:
assert orig_types(binary.ss.firsti) == {INT32, INT64}
assert orig_types(binary.ss.secondj1) == {INT32, INT64}
def test_monoid():
assert monoid.max["INT32"].gb_obj == lib.GrB_MAX_MONOID_INT32
assert monoid.max[dtypes.UINT16].gb_obj == lib.GrB_MAX_MONOID_UINT16
def test_semiring():
assert semiring.min_plus["INT32"].gb_obj == lib.GrB_MIN_PLUS_SEMIRING_INT32
assert semiring.min_plus[dtypes.UINT16].gb_obj == lib.GrB_MIN_PLUS_SEMIRING_UINT16
if suitesparse:
assert orig_types(semiring.ss.min_firsti) == {INT32, INT64}
def test_agg():
assert repr(agg.count) == "agg.count"
assert repr(agg.count["INT32"]) == "agg.count[INT32]"
if suitesparse:
assert repr(agg.ss.first) == "agg.ss.first"
assert "INT64" in agg.sum_of_inverses
assert agg.sum_of_inverses["INT64"].return_type == FP64
assert "BOOL" not in agg.sum_of_inverses
with pytest.raises(KeyError, match="BOOL"):
agg.sum_of_inverses["BOOL"]
assert agg.varp["INT64"].return_type == "FP64"
assert set(dir(agg)).issuperset({"count", "mean", "ss"})
def test_find_opclass_unaryop():
assert operator.find_opclass(unary.minv)[1] == "UnaryOp"
# assert operator.find_opclass(lib.GrB_MINV_INT64)[1] == 'UnaryOp'
def test_find_opclass_binaryop():
assert operator.find_opclass(binary.times)[1] == "BinaryOp"
# assert operator.find_opclass(lib.GrB_TIMES_INT64)[1] == 'BinaryOp'
def test_find_opclass_monoid():
assert operator.find_opclass(monoid.max)[1] == "Monoid"
# assert operator.find_opclass(lib.GxB_MAX_INT64_MONOID)[1] == 'Monoid'
def test_find_opclass_semiring():
assert operator.find_opclass(semiring.plus_plus)[1] == "Semiring"
# assert operator.find_opclass(lib.GxB_PLUS_PLUS_INT64)[1] == 'Semiring'
def test_find_opclass_invalid():
assert operator.find_opclass("foobar")[1] == operator.UNKNOWN_OPCLASS
# assert operator.find_opclass(lib.GrB_INP0)[1] == operator.UNKNOWN_OPCLASS
def test_get_typed_op():
assert operator.get_typed_op(binary.bor, dtypes.INT64) is binary.bor[dtypes.INT64]
with pytest.raises(KeyError, match="bor does not work with FP64"):
operator.get_typed_op(binary.bor, dtypes.FP64)
with pytest.raises(TypeError, match="Unable to get typed operator"):
operator.get_typed_op(object(), dtypes.INT64)
assert operator.get_typed_op("<", dtypes.INT64, kind="binary") is binary.lt["INT64"]
assert operator.get_typed_op("-", dtypes.INT64, kind="unary") is unary.ainv["INT64"]
assert operator.get_typed_op("+", dtypes.FP64, kind="monoid") is monoid.plus["FP64"]
assert operator.get_typed_op("+[int64]", dtypes.FP64, kind="monoid") is monoid.plus["INT64"]
assert operator.get_typed_op("+.*", dtypes.FP64, kind="semiring") is semiring.plus_times["FP64"]
assert operator.get_typed_op("row<=", dtypes.INT64, kind="select") is select.rowle["INT64"]
with pytest.raises(ValueError, match="Unable to get op from string"):
operator.get_typed_op("+", dtypes.FP64)
assert (
operator.get_typed_op("+", dtypes.INT64, kind="binary|aggregator") is binary.plus["INT64"]
)
assert (
operator.get_typed_op("count", dtypes.INT64, kind="binary|aggregator") is agg.count["INT64"]
)
with pytest.raises(ValueError, match="Unknown binary or aggregator"):
operator.get_typed_op("bad_op_name", dtypes.INT64, kind="binary|aggregator")
with pytest.raises(AttributeError):
# get_typed_op expects dtypes to already be dtypes
operator.get_typed_op(binary.plus, dtypes.INT64, "bad dtype")
@pytest.mark.skipif("supports_udfs")
def test_udf_mentions_numba():
with pytest.raises(AttributeError, match="install numba"):
binary.rfloordiv
assert "rfloordiv" not in dir(binary)
with pytest.raises(AttributeError, match="install numba"):
semiring.any_rfloordiv
assert "any_rfloordiv" not in dir(semiring)
with pytest.raises(AttributeError, match="install numba"):
op.absfirst
assert "absfirst" not in dir(op)
with pytest.raises(AttributeError, match="install numba"):
op.plus_rpow
assert "plus_rpow" not in dir(op)
with pytest.raises(AttributeError, match="install numba"):
binary.numpy.gcd
assert "gcd" not in dir(binary.numpy)
assert "gcd" not in dir(op.numpy)
@pytest.mark.skipif("supports_udfs")
def test_unaryop_udf_no_support():
def plus_one(x): # pragma: no cover (numba)
return x + 1
with pytest.raises(RuntimeError, match="UnaryOp.register_new.* unavailable"):
unary.register_new("plus_one", plus_one)
@pytest.mark.skipif("not supports_udfs")
def test_unaryop_udf():
def plus_one(x):
return x + 1 # pragma: no cover (numba)
unary.register_new("plus_one", plus_one)
assert hasattr(unary, "plus_one")
assert unary.plus_one.orig_func is plus_one
assert unary.plus_one[int].orig_func is plus_one
assert unary.plus_one[int]._numba_func(1) == 2
comp_set = {
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
FP32,
FP64,
BOOL,
}
if dtypes._supports_complex:
comp_set.update({FC32, FC64})
assert set(unary.plus_one.types) == comp_set
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v << v.apply(unary.plus_one)
result = Vector.from_coo([0, 1, 3], [2, 3, -3], dtype=dtypes.INT32)
assert v.isequal(result)
assert "INT8" in unary.plus_one
assert INT8 in unary.plus_one.types
del unary.plus_one["INT8"]
assert "INT8" not in unary.plus_one
assert INT8 not in unary.plus_one.types
with pytest.raises(TypeError, match="UDF argument must be a function"):
UnaryOp.register_new("bad", object())
assert not hasattr(unary, "bad")
with pytest.raises(UdfParseError, match="Unable to parse function using Numba"):
UnaryOp.register_new("bad", lambda x: v) # pragma: no branch (numba)
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_unaryop_parameterized():
def plus_x(x=0):
def inner(val):
return val + x # pragma: no cover (numba)
return inner
op = UnaryOp.register_anonymous(plus_x, parameterized=True)
assert not op.is_positional
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v0 = v.apply(op).new()
assert v.isequal(v0, check_dtype=True)
v0 = v.apply(op(0)).new()
assert v.isequal(v0, check_dtype=True)
v10 = v.apply(op(x=10)).new()
r10 = Vector.from_coo([0, 1, 3], [11, 12, 6], dtype=dtypes.INT32)
assert r10.isequal(v10, check_dtype=True)
UnaryOp._initialize() # no-op
UnaryOp.register_new("plus_x_parameterized", plus_x, parameterized=True)
op = unary.plus_x_parameterized
v11 = v.apply(op(x=10)["INT32"]).new()
assert r10.isequal(v11, check_dtype=True)
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_binaryop_parameterized():
def plus_plus_x(x=0):
def inner(left, right):
return left + right + x # pragma: no cover (numba)
return inner
op = binary.register_anonymous(plus_plus_x, parameterized=True)
assert not op.is_positional
assert op.monoid is None
assert op(1).monoid is None
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v0 = v.ewise_mult(v, op).new()
r0 = Vector.from_coo([0, 1, 3], [2, 4, -8], dtype=dtypes.INT32)
assert v0.isequal(r0, check_dtype=True)
v1 = v.ewise_add(v, op(1)).new()
r1 = Vector.from_coo([0, 1, 3], [3, 5, -7], dtype=dtypes.INT32)
assert v1.isequal(r1, check_dtype=True)
w = Vector.from_coo([0, 0, 1, 3], [1, 0, 2, -4], dtype=dtypes.INT32, dup_op=op)
assert v.isequal(w, check_dtype=True)
with pytest.raises(TypeError, match="Monoid"):
assert v.reduce(op).new() == -1
v(op) << v
assert v.isequal(r0)
v(accum=op) << v
x = r0.ewise_mult(r0, op).new()
assert v.isequal(x)
v(op(1)) << v
x = x.ewise_mult(x, op(1)).new()
assert v.isequal(x)
v(accum=op(1)) << v
x = x.ewise_mult(x, op(1)).new()
assert v.isequal(x)
assert v.isequal(Vector.from_coo([0, 1, 3], [19, 35, -61], dtype=dtypes.INT32))
v11 = v.apply(op(1), left=10).new()
r11 = Vector.from_coo([0, 1, 3], [30, 46, -50], dtype=dtypes.INT32)
# Should we check for dtype here?
# Is it okay if the literal scalar is an INT64, which causes the output to default to INT64?
assert v11.isequal(r11, check_dtype=False)
with pytest.raises(TypeError, match="UDF argument must be a function"):
BinaryOp.register_new("bad", object())
assert not hasattr(binary, "bad")
def bad(x, y): # pragma: no cover (numba)
return v
with pytest.raises(UdfParseError, match="Unable to parse function using Numba"):
BinaryOp.register_new("bad", bad)
def my_add(x, y):
return x + y # pragma: no cover (numba)
op = BinaryOp.register_anonymous(my_add)
assert op.name == "my_add"
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_monoid_parameterized():
def plus_plus_x(x=0):
def inner(left, right):
return left + right + x # pragma: no cover (numba)
return inner
bin_op = BinaryOp.register_anonymous(plus_plus_x, parameterized=True)
# signatures must match
with pytest.raises(ValueError, match="Signatures"):
Monoid.register_anonymous(bin_op, lambda x: -x) # pragma: no branch (numba)
with pytest.raises(ValueError, match="Signatures"):
Monoid.register_anonymous(bin_op, lambda y=0: -y) # pragma: no branch (numba)
with pytest.raises(TypeError, match="binaryop must be parameterized"):
operator.ParameterizedMonoid("bad_monoid", binary.plus, 0)
def plus_plus_x_identity(x=0):
return -x
assert bin_op.monoid is None
bin_op1 = bin_op(1)
assert bin_op1.monoid is None
monoid = Monoid.register_anonymous(bin_op, plus_plus_x_identity, name="my_monoid")
assert not monoid.is_positional
assert bin_op.monoid is monoid
assert bin_op(1).monoid is monoid(1)
assert monoid(2) is bin_op(2).monoid
assert not monoid.is_idempotent
assert not monoid(1).is_idempotent
# However, this still fails.
# For this to work, we would need `bin_op1` to know it was created from a
# ParameterizedBinaryOp. It would then need to check to see if the parameterized
# parent has been associated with a monoid since the creation of `bin_op1`.
assert bin_op1.monoid is None
assert monoid.name == "my_monoid"
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v0 = v.ewise_add(v, monoid).new()
r0 = Vector.from_coo([0, 1, 3], [2, 4, -8], dtype=dtypes.INT32)
assert v0.isequal(r0, check_dtype=True)
v1 = v.ewise_mult(v, monoid(1)).new()
r1 = Vector.from_coo([0, 1, 3], [3, 5, -7], dtype=dtypes.INT32)
assert v1.isequal(r1, check_dtype=True)
assert v.reduce(monoid).new() == -1
assert v.reduce(monoid(1)).new() == 1
# with pytest.raises(TypeError, match="BinaryOp"): # NOW OKAY
w1 = Vector.from_coo([0, 0, 1, 3], [1, 0, 2, -4], dtype=dtypes.INT32, dup_op=monoid)
w2 = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
assert w1.isequal(w2)
# identity may be a value
def logaddexp(base):
def inner(x, y):
return np.log(base**x + base**y) / np.log(base) # pragma: no cover (numba)
return inner
fv = v.apply(unary.identity).new(dtype=dtypes.FP64)
bin_op = BinaryOp.register_anonymous(logaddexp, parameterized=True)
Monoid.register_new("_user_defined_monoid", bin_op, -np.inf)
monoid = gb.monoid._user_defined_monoid
fv2 = fv.ewise_mult(fv, monoid(2)).new()
def plus1(x): # pragma: no cover (numba)
return x + 1
plus1 = UnaryOp.register_anonymous(plus1)
expected = fv.apply(plus1).new()
assert fv2.isclose(expected, check_dtype=True)
with pytest.raises(TypeError, match="must be a BinaryOp"):
Monoid.register_anonymous(monoid, 0)
def plus_times_x(x=0):
def inner(left, right):
return (left + right) * x # pragma: no cover (numba)
return inner
bin_op = BinaryOp.register_anonymous(plus_times_x, parameterized=True)
def bad_identity(x=0):
raise ValueError("hahaha!")
assert bin_op.monoid is None
monoid = Monoid.register_anonymous(
bin_op, bad_identity, is_idempotent=True, name="broken_monoid"
)
assert bin_op.monoid is monoid
assert bin_op(1).monoid is None
assert monoid.is_idempotent
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_semiring_parameterized():
def plus_plus_x(x=0):
def inner(left, right):
return left + right + x # pragma: no cover (numba)
return inner
def plus_plus_x_identity(x=0):
return -x
assert semiring.register_anonymous(monoid.min, binary.plus).name == "min_plus"
bin_op = BinaryOp.register_anonymous(plus_plus_x, parameterized=True)
mymonoid = monoid.register_anonymous(bin_op, plus_plus_x_identity)
# monoid and binaryop are both parameterized
mysemiring = Semiring.register_anonymous(mymonoid, bin_op, name="my_semiring")
assert not mysemiring.is_positional
assert mysemiring.name == "my_semiring"
A = Matrix.from_coo([0, 0, 1, 1], [0, 1, 0, 1], [1, 2, 3, 4])
x = Vector.from_coo([0, 1], [10, 20])
y = A.mxv(x, mysemiring).new()
assert y.isequal(A.mxv(x, semiring.plus_plus).new())
assert y.isequal(x.vxm(A.T, semiring.plus_plus).new())
assert y.isequal(Vector.from_coo([0, 1], [33, 37]))
y = A.mxv(x, mysemiring(1)).new()
assert y.isequal(Vector.from_coo([0, 1], [36, 40])) # three extra pluses
y = x.vxm(A.T, mysemiring(1)).new() # same as previous
assert y.isequal(Vector.from_coo([0, 1], [36, 40]))
y = x.vxm(A.T, mysemiring).new()
assert y.isequal(Vector.from_coo([0, 1], [33, 37]))
B = A.mxm(A, mysemiring).new()
assert B.isequal(A.mxm(A, semiring.plus_plus).new())
assert B.isequal(Matrix.from_coo([0, 0, 1, 1], [0, 1, 0, 1], [7, 9, 11, 13]))
B = A.mxm(A, mysemiring(1)).new() # three extra pluses
assert B.isequal(Matrix.from_coo([0, 0, 1, 1], [0, 1, 0, 1], [10, 12, 14, 16]))
with pytest.raises(TypeError, match="Expected type: BinaryOp, Monoid"):
A.ewise_add(A, mysemiring)
# mismatched signatures.
def other_binary(y=0): # pragma: no cover (numba)
def inner(left, right):
return left + right - y
return inner
def other_identity(y=0):
return x # pragma: no cover (numba)
other_op = BinaryOp.register_anonymous(other_binary, parameterized=True)
other_monoid = Monoid.register_anonymous(other_op, other_identity)
with pytest.raises(ValueError, match="Signatures"):
Monoid.register_anonymous(other_op, plus_plus_x_identity)
with pytest.raises(ValueError, match="Signatures"):
Monoid.register_anonymous(bin_op, other_identity)
with pytest.raises(ValueError, match="Signatures"):
Semiring.register_anonymous(other_monoid, bin_op)
with pytest.raises(ValueError, match="Signatures"):
Semiring.register_anonymous(mymonoid, other_op)
# only monoid is parameterized
Semiring.register_new("my_special_semiring", mymonoid, binary.plus)
mysemiring = semiring.my_special_semiring
B0 = A.mxm(A, semiring.plus_plus).new()
B1 = A.mxm(A, mysemiring).new()
B2 = A.mxm(A, mysemiring(0)).new()
assert B0.isequal(B1)
assert B0.isequal(B2)
# only binaryop is parameterized
mysemiring = Semiring.register_anonymous(monoid.plus, bin_op)
B0 = A.mxm(A, semiring.plus_plus).new()
B1 = A.mxm(A, mysemiring).new()
B2 = A.mxm(A, mysemiring(0)).new()
assert B0.isequal(B1)
assert B0.isequal(B2)
with pytest.raises(TypeError, match="must be a Monoid"):
Semiring.register_anonymous(binary.plus, binary.plus)
with pytest.raises(TypeError, match="must be a BinaryOp"):
Semiring.register_anonymous(monoid.plus, monoid.plus)
with pytest.raises(TypeError, match="At least one of"):
operator.ParameterizedSemiring("bad_semiring", monoid.plus, binary.plus)
with pytest.raises(TypeError, match="monoid must be of type"):
operator.ParameterizedSemiring("bad_semiring", binary.plus, binary.plus)
with pytest.raises(TypeError, match="binaryop must be of"):
operator.ParameterizedSemiring("bad_semiring", monoid.plus, monoid.plus)
# While we're here, let's check misc Matrix operations
Adup = Matrix.from_coo([0, 0, 0, 1, 1], [0, 0, 1, 0, 1], [100, 1, 2, 3, 4], dup_op=bin_op)
Adup2 = Matrix.from_coo([0, 0, 0, 1, 1], [0, 0, 1, 0, 1], [100, 1, 2, 3, 4], dup_op=binary.plus)
assert Adup.isequal(Adup2)
def plus_x(x=0):
def inner(y):
return x + y # pragma: no cover (numba)
return inner
unaryop = UnaryOp.register_anonymous(plus_x, parameterized=True)
B = A.apply(unaryop).new()
assert B.isequal(A)
# SuiteSparse 4.0.1 no longer supports reduce with user-defined binary op
# But, we can associate this to a monoid!
x = A.reduce_rowwise(bin_op).new()
assert x.isequal(A.reduce_rowwise(binary.plus).new())
x = A.reduce_columnwise(bin_op).new()
assert x.isequal(A.reduce_columnwise(binary.plus).new())
s = A.reduce_scalar(mymonoid).new()
assert s.value == A.reduce_scalar(monoid.plus).new()
assert A.reduce_scalar(bin_op).new() == A.reduce_scalar(binary.plus).new()
B = A.kronecker(A, bin_op).new()
assert B.isequal(A.kronecker(A, binary.plus).new())
@pytest.mark.skipif("not supports_udfs")
def test_unaryop_udf_bool_result():
# numba has trouble compiling this, but we have a work-around
def is_positive(x):
return x > 0 # pragma: no cover (numba)
UnaryOp.register_new("is_positive", is_positive)
assert hasattr(unary, "is_positive")
assert set(unary.is_positive.types) == {
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
FP32,
FP64,
BOOL,
}
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
w = v.apply(unary.is_positive).new()
result = Vector.from_coo([0, 1, 3], [True, True, False], dtype=dtypes.BOOL)
assert w.isequal(result)
@pytest.mark.skipif("not supports_udfs")
def test_binaryop_udf():
def times_minus_sum(x, y):
return x * y - (x + y) # pragma: no cover (numba)
BinaryOp.register_new("bin_test_func", times_minus_sum)
assert hasattr(binary, "bin_test_func")
assert binary.bin_test_func[int].orig_func is times_minus_sum
comp_set = {
BOOL, # goes to INT64
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
FP32,
FP64,
}
if dtypes._supports_complex:
comp_set.update({FC32, FC64})
assert set(binary.bin_test_func.types) == comp_set
v1 = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v2 = Vector.from_coo([0, 2, 3], [2, 3, 7], dtype=dtypes.INT32)
w = v1.ewise_add(v2, binary.bin_test_func).new()
result = Vector.from_coo([0, 1, 2, 3], [-1, 2, 3, -31], dtype=dtypes.INT32)
assert w.isequal(result)
@pytest.mark.skipif("not supports_udfs")
def test_monoid_udf():
def plus_plus_one(x, y):
return x + y + 1 # pragma: no cover (numba)
BinaryOp.register_new("plus_plus_one", plus_plus_one)
Monoid.register_new("plus_plus_one", binary.plus_plus_one, -1)
assert hasattr(monoid, "plus_plus_one")
comp_set = {
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
FP32,
FP64,
}
if dtypes._supports_complex:
comp_set.update({FC32, FC64})
assert set(monoid.plus_plus_one.types) == comp_set
v1 = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v2 = Vector.from_coo([0, 2, 3], [2, 3, 7], dtype=dtypes.INT32)
w = v1.ewise_add(v2, monoid.plus_plus_one).new()
result = Vector.from_coo([0, 1, 2, 3], [4, 2, 3, 4], dtype=dtypes.INT32)
assert w.isequal(result)
with pytest.raises(DomainMismatch):
Monoid.register_anonymous(binary.plus_plus_one, {"BOOL": True})
with pytest.raises(DomainMismatch):
Monoid.register_anonymous(binary.plus_plus_one, {"BOOL": -1})
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_semiring_udf():
def plus_plus_two(x, y):
return x + y + 2 # pragma: no cover (numba)
BinaryOp.register_new("plus_plus_two", plus_plus_two)
Semiring.register_new("extra_twos", monoid.plus, binary.plus_plus_two)
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
A = Matrix.from_coo(
[0, 0, 0, 0, 3, 3, 3, 3],
[0, 1, 2, 3, 0, 1, 2, 3],
[2, 3, 4, 5, 6, 7, 8, 9],
dtype=dtypes.INT32,
)
w = v.vxm(A, semiring.extra_twos).new()
result = Vector.from_coo([0, 1, 2, 3], [9, 11, 13, 15], dtype=dtypes.INT32)
assert w.isequal(result)
def test_binary_updates():
assert not hasattr(binary, "div")
assert binary.cdiv["INT64"].gb_obj == lib.GrB_DIV_INT64
vec1 = Vector.from_coo([0], [1], dtype=dtypes.INT64)
vec2 = Vector.from_coo([0], [2], dtype=dtypes.INT64)
result = vec1.ewise_mult(vec2, binary.truediv).new()
assert result.isclose(Vector.from_coo([0], [0.5], dtype=dtypes.FP64), check_dtype=True)
vec4 = Vector.from_coo([0], [-3], dtype=dtypes.INT64)
result2 = vec4.ewise_mult(vec2, binary.cdiv).new()
assert result2.isequal(Vector.from_coo([0], [-1], dtype=dtypes.INT64), check_dtype=True)
if shouldhave(binary, "floordiv"):
result3 = vec4.ewise_mult(vec2, binary.floordiv).new()
assert result3.isequal(Vector.from_coo([0], [-2], dtype=dtypes.INT64), check_dtype=True)
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_nested_names():
def plus_three(x):
return x + 3 # pragma: no cover (numba)
UnaryOp.register_new("incrementers.plus_three", plus_three)
assert hasattr(unary, "incrementers")
assert type(unary.incrementers) is operator.OpPath
assert hasattr(unary.incrementers, "plus_three")
comp_set = {
INT8,
INT16,
INT32,
INT64,
UINT8,
UINT16,
UINT32,
UINT64,
FP32,
FP64,
BOOL,
}
if dtypes._supports_complex:
comp_set.update({FC32, FC64})
assert set(unary.incrementers.plus_three.types) == comp_set
v = Vector.from_coo([0, 1, 3], [1, 2, -4], dtype=dtypes.INT32)
v << v.apply(unary.incrementers.plus_three)
result = Vector.from_coo([0, 1, 3], [4, 5, -1], dtype=dtypes.INT32)
assert v.isequal(result), v
def plus_four(x):
return x + 4 # pragma: no cover (numba)
UnaryOp.register_new("incrementers.plus_four", plus_four)
assert hasattr(unary.incrementers, "plus_four")
assert hasattr(op.incrementers, "plus_four") # Also save it to `graphblas.op`!
v << v.apply(unary.incrementers.plus_four) # this is in addition to the plus_three earlier
result2 = Vector.from_coo([0, 1, 3], [8, 9, 3], dtype=dtypes.INT32)
assert v.isequal(result2), v
def bad_will_overwrite_path(x):
return x + 7 # pragma: no cover (numba)
with pytest.raises(AttributeError):
UnaryOp.register_new("incrementers", bad_will_overwrite_path)
with pytest.raises(AttributeError, match="already defined"):
UnaryOp.register_new("identity.newfunc", bad_will_overwrite_path)
with pytest.raises(AttributeError, match="already defined"):
UnaryOp.register_new("incrementers.plus_four", bad_will_overwrite_path)
@pytest.mark.slow
def test_op_namespace():
assert op.abs is unary.abs
assert op.minus is binary.minus
assert op.plus is binary.plus
assert op.plus_times is semiring.plus_times
if shouldhave(unary.numpy, "fabs"):
assert op.numpy.fabs is unary.numpy.fabs
if shouldhave(binary.numpy, "subtract"):
assert op.numpy.subtract is binary.numpy.subtract
if shouldhave(binary.numpy, "add"):
assert op.numpy.add is binary.numpy.add
if shouldhave(semiring.numpy, "add_add"):
assert op.numpy.add_add is semiring.numpy.add_add
assert len(dir(op)) > 300
if supports_udfs:
assert len(dir(op.numpy)) > 500
with pytest.raises(
AttributeError, match="module 'graphblas.op.numpy' has no attribute 'bad_attr'"
):
op.numpy.bad_attr
# Make sure all have been initialized so `vars` below works
for key in list(op._delayed): # pragma: no cover (safety)
getattr(op, key)
opnames = {
key
for key, val in vars(op).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
unarynames = {
key
for key, val in vars(unary).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
binarynames = {
key
for key, val in vars(binary).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
monoidnames = {
key
for key, val in vars(monoid).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
semiringnames = {
key
for key, val in vars(semiring).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
indexunarynames = {
key
for key, val in vars(indexunary).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
selectnames = {
key
for key, val in vars(select).items()
if isinstance(val, (operator.OpBase, operator.ParameterizedUdf))
}
extra_unary = unarynames - opnames - unary._deprecated.keys()
assert not extra_unary
extra_binary = binarynames - opnames - binary._deprecated.keys()
assert not extra_binary
assert not monoidnames - opnames, monoidnames - opnames
extra_semiring = semiringnames - opnames - semiring._deprecated.keys()
assert not extra_semiring
extra_ops = (
opnames - (unarynames | binarynames | monoidnames | semiringnames) - op._deprecated.keys()
)
assert not extra_ops
# These are not part of the `op` namespace
assert indexunarynames - opnames == indexunarynames, indexunarynames - opnames
assert selectnames - opnames == selectnames, selectnames - opnames
@pytest.mark.slow
def test_binaryop_attributes_numpy():
# Some coverage from this test depends on order of tests
if shouldhave(monoid.numpy, "add"):
assert binary.numpy.add[int].monoid is monoid.numpy.add[int]
assert binary.numpy.add.monoid is monoid.numpy.add
if shouldhave(binary.numpy, "subtract"):
assert binary.numpy.subtract[int].monoid is None
assert binary.numpy.subtract.monoid is None
@pytest.mark.skipif("not supports_udfs")
@pytest.mark.slow
def test_binaryop_monoid_numpy():
assert gb.binary.numpy.minimum[int].monoid is gb.monoid.numpy.minimum[int]
@pytest.mark.slow
def test_binaryop_attributes():
assert binary.plus[int].monoid is monoid.plus[int]
assert binary.minus[int].monoid is None
assert binary.plus.monoid is monoid.plus
assert binary.minus.monoid is None
def plus(x, y):
return x + y # pragma: no cover (numba)
if supports_udfs:
op = BinaryOp.register_anonymous(plus, name="plus")
assert op.monoid is None
assert op[int].monoid is None
assert op[int].parent is op
assert binary.plus[int].parent is binary.plus
if shouldhave(binary.numpy, "add"):
assert binary.numpy.add[int].parent is binary.numpy.add
# bad type
assert binary.plus[bool].monoid is None
if shouldhave(binary.numpy, "equal"):
assert binary.numpy.equal[int].monoid is None
assert binary.numpy.equal[bool].monoid is monoid.numpy.equal[bool] # sanity
for attr, val in vars(binary).items():
if not isinstance(val, BinaryOp):
continue
print(attr)
if hasattr(monoid, attr):
assert val.monoid is not None
assert any(val[type_].monoid is not None for type_ in val.types)
else:
assert val.monoid is None or val.monoid.name != attr
assert all(
val[type_].monoid is None or val[type_].monoid.name != attr for type_ in val.types
)
@pytest.mark.slow
def test_monoid_attributes():
assert monoid.plus[int].binaryop is binary.plus[int]
assert monoid.plus[int].identity == 0
assert monoid.plus.binaryop is binary.plus
assert monoid.plus.identities == dict.fromkeys(monoid.plus.types, 0)
if shouldhave(monoid.numpy, "add"):
assert monoid.numpy.add[int].binaryop is binary.numpy.add[int]
assert monoid.numpy.add[int].identity == 0
assert monoid.numpy.add.binaryop is binary.numpy.add
assert monoid.numpy.add.identities == dict.fromkeys(monoid.numpy.add.types, 0)
def plus(x, y): # pragma: no cover (numba)
return x + y
if supports_udfs:
binop = BinaryOp.register_anonymous(plus, name="plus")
op = Monoid.register_anonymous(binop, 0, name="plus")
assert op.binaryop is binop
assert op[int].binaryop is binop[int]
assert op[int].parent is op
assert monoid.plus[int].parent is monoid.plus
if shouldhave(monoid.numpy, "add"):
assert monoid.numpy.add[int].parent is monoid.numpy.add
for attr, val in vars(monoid).items():
if not isinstance(val, Monoid):
continue
print(attr)
assert val.binaryop is not None
assert val.identities is not None
for type_ in val.types:
x = val[type_]
assert x.binaryop is not None
assert x.identity is not None
@pytest.mark.slow
def test_semiring_attributes():
assert semiring.min_plus[int].monoid is monoid.min[int]
assert semiring.min_plus[int].binaryop is binary.plus[int]
assert semiring.min_plus.monoid is monoid.min
assert semiring.min_plus.binaryop is binary.plus
if shouldhave(semiring.numpy, "add_subtract"):
assert semiring.numpy.add_subtract[int].monoid is monoid.numpy.add[int]
assert semiring.numpy.add_subtract[int].binaryop is binary.numpy.subtract[int]
assert semiring.numpy.add_subtract.monoid is monoid.numpy.add
assert semiring.numpy.add_subtract.binaryop is binary.numpy.subtract
assert semiring.numpy.add_subtract[int].parent is semiring.numpy.add_subtract
def plus(x, y):
return x + y # pragma: no cover (numba)
if supports_udfs:
binop = BinaryOp.register_anonymous(plus, name="plus")
mymonoid = Monoid.register_anonymous(binop, 0, name="plus")
op = Semiring.register_anonymous(mymonoid, binop, name="plus_plus")
assert op.binaryop is binop
assert op.binaryop[int] is binop[int]
assert op.monoid is mymonoid
assert op.monoid[int] is mymonoid[int]
assert op[int].parent is op
assert semiring.min_plus[int].parent is semiring.min_plus
for attr, val in vars(semiring).items():
if not isinstance(val, Semiring):
continue
print(attr)
assert val.binaryop is not None
assert val.monoid is not None
for type_ in val.types:
x = val[type_]
assert x.binaryop is not None
assert x.monoid is not None
def test_binaryop_superset_monoids():
ignore = {"udt_any", "lazy2", "monoid_pickle", "monoid_pickle_par"}
monoid_names = {x for x in dir(monoid) if not x.startswith("_")} - ignore
binary_names = {x for x in dir(binary) if not x.startswith("_")} - ignore
diff = monoid_names - binary_names
assert not diff
extras = {x for x in set(dir(monoid.numpy)) - set(dir(binary.numpy)) if not x.startswith("_")}
extras -= ignore
assert not extras, ", ".join(sorted(extras))
def test_div_semirings():
assert not hasattr(semiring, "plus_div")
A1 = Matrix.from_coo([0, 1], [0, 0], [-1, -3])
A2 = Matrix.from_coo([0, 1], [0, 0], [2, 2])
result = A1.T.mxm(A2, semiring.plus_cdiv).new()
assert result[0, 0].new() == -1
assert result.dtype == dtypes.INT64
result = A1.T.mxm(A2, semiring.plus_truediv).new()
assert result[0, 0].new() == -2
assert result.dtype == dtypes.FP64
if shouldhave(semiring, "plus_floordiv"):
result = A1.T.mxm(A2, semiring.plus_floordiv).new()
assert result[0, 0].new() == -3
assert result.dtype == dtypes.INT64
@pytest.mark.slow
def test_get_semiring():
sr = get_semiring(monoid.plus, binary.times)
assert sr is semiring.plus_times
# Be somewhat forgiving
sr = get_semiring(monoid.plus, monoid.times)
assert sr is semiring.plus_times
sr = get_semiring(binary.plus, binary.times)
assert sr is semiring.plus_times
# But not if switched
with pytest.raises(TypeError, match="switch"):
get_semiring(binary.plus, monoid.times)
def myplus(x, y):
return x + y # pragma: no cover (numba)
if supports_udfs:
binop = BinaryOp.register_anonymous(myplus, name="myplus")
st = get_semiring(monoid.plus, binop)
assert st.monoid is monoid.plus
assert st.binaryop is binop
binop = BinaryOp.register_new("myplus", myplus)
assert binop is binary.myplus
st = get_semiring(monoid.plus, binop)