-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy patharray_api.py
More file actions
2019 lines (1452 loc) · 63.6 KB
/
array_api.py
File metadata and controls
2019 lines (1452 loc) · 63.6 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
"""
## Lists
Lists have two main constructors:
- `List(length, idx_fn)`
- `List.EMPTY` / `initial.append(last)`
This is so that they can be defined either with a known fixed integer length (the cons list type) or a symbolic
length that could not be resolved to an integer.
There are rewrites to convert between these constructors in both directions. The only limitation however is that
`length` has to a real i64 in order to be converted to a cons list.
When you are writing a function that uses ints, feel free to the `__getitem__` or `length()` methods or match
directly on `List()` constructor. If you can write your function using that interface please do. But for some other
methods whether the resulting length/index function is dependent on the rest of it, you can only define it with a known
length, so you can then use the const list constructors.
We also support creating lists from vectors. These can be converted one to one to the snoc list representation.
It is troublesome to have to redefine lists for every type. It would be nice to have generic types, but they are not implemented yet.
We are gauranteed that all lists with known lengths will be represented as cons/empty. To safely use lists, use
the `.length` and `.__getitem__` methods, unles you want to to depend on it having known length, in which
case you can match directly on the cons list.
To be a list, you must implement two methods:
* `l.length() -> Int`
* `l.__getitem__(i: Int) -> T`
There are three main types of constructors for lists which all implement these methods:
* Functional `List(length, idx_fn)`
* cons (well reversed cons) lists `List.EMPTY` and `l.append(x)`
* Vectors `List.from_vec(vec)`
Also all lists constructors must be converted to the functional representation, so that we can match on it
and convert lists with known lengths into cons lists and into vectors.
This is neccessary so that known length lists are properly materialized during extraction.
Q: Why are they implemented as SNOC lists instead of CONS lists?
A: So that when converting from functional to lists we can use the same index function by starting at the end and folding
that way recursively.
"""
# mypy: disable-error-code="empty-body"
from __future__ import annotations
import contextlib
import itertools
import math
import numbers
import os
import sys
from collections.abc import Callable
from copy import copy
from types import EllipsisType
from typing import TYPE_CHECKING, Any, ClassVar, TypeAlias, cast
import numpy as np
from egglog import *
from egglog.runtime import RuntimeExpr
from .program_gen import *
if TYPE_CHECKING:
from collections.abc import Iterator
from types import ModuleType
# Pretend that exprs are numbers b/c sklearn does isinstance checks
numbers.Integral.register(RuntimeExpr)
# Set this to 1 before scipy is ever imported
# https://docs.scipy.org/doc/scipy/dev/api-dev/array_api.html#using-array-api-standard-support
os.environ["SCIPY_ARRAY_API"] = "1"
array_api_ruleset = ruleset(name="array_api_ruleset")
class Boolean(Expr, ruleset=array_api_ruleset):
def __init__(self, value: BoolLike) -> None: ...
@method(preserve=True)
def __bool__(self) -> bool:
return self.eval()
@method(preserve=True)
def eval(self) -> bool:
return try_evaling(_get_current_egraph(), array_api_schedule, self, self.to_bool)
@property
def to_bool(self) -> Bool: ...
def __or__(self, other: BooleanLike) -> Boolean: ...
def __and__(self, other: BooleanLike) -> Boolean: ...
def __invert__(self) -> Boolean: ...
def __eq__(self, other: BooleanLike) -> Boolean: ... # type: ignore[override]
BooleanLike = Boolean | BoolLike
TRUE = Boolean(True)
FALSE = Boolean(False)
converter(Bool, Boolean, Boolean)
@array_api_ruleset.register
def _bool(x: Boolean, i: Int, j: Int, b: Bool):
return [
rule(eq(x).to(Boolean(b))).then(set_(x.to_bool).to(b)),
rewrite(TRUE | x).to(TRUE),
rewrite(FALSE | x).to(x),
rewrite(TRUE & x).to(x),
rewrite(FALSE & x).to(FALSE),
rewrite(~TRUE).to(FALSE),
rewrite(~FALSE).to(TRUE),
rule(eq(FALSE).to(TRUE)).then(panic("False cannot equal True")),
rewrite(x == x).to(TRUE), # noqa: PLR0124
rewrite(FALSE == TRUE).to(FALSE),
rewrite(TRUE == FALSE).to(FALSE),
]
class Int(Expr, ruleset=array_api_ruleset):
# a never int is that should not exist. It could represent for example indexing into an array a value that is out of bounds
# https://en.wikipedia.org/wiki/Bottom_type
NEVER: ClassVar[Int]
@classmethod
def var(cls, name: StringLike) -> Int: ...
def __init__(self, value: i64Like) -> None: ...
def __invert__(self) -> Int: ...
def __lt__(self, other: IntLike) -> Boolean: ...
def __le__(self, other: IntLike) -> Boolean: ...
def __eq__(self, other: IntLike) -> Boolean: # type: ignore[override]
...
# add a hash so that this test can pass
# https://github.com/scikit-learn/scikit-learn/blob/6fd23fca53845b32b249f2b36051c081b65e2fab/sklearn/utils/validation.py#L486-L487
@method(preserve=True)
def __hash__(self) -> int:
egraph = _get_current_egraph()
egraph.register(self)
egraph.run(array_api_schedule)
simplified = egraph.extract(self)
return hash(cast("RuntimeExpr", simplified).__egg_typed_expr__)
def __round__(self, ndigits: OptionalIntLike = None) -> Int: ...
# TODO: Fix this?
# Make != always return a Bool, so that numpy.unique works on a tuple of ints
# In _unique1d
@method(preserve=True)
def __ne__(self, other: Int) -> bool: # type: ignore[override]
return not (self == other)
def __gt__(self, other: IntLike) -> Boolean: ...
def __ge__(self, other: IntLike) -> Boolean: ...
def __add__(self, other: IntLike) -> Int: ...
def __sub__(self, other: IntLike) -> Int: ...
def __mul__(self, other: IntLike) -> Int: ...
def __truediv__(self, other: IntLike) -> Int: ...
def __floordiv__(self, other: IntLike) -> Int: ...
def __mod__(self, other: IntLike) -> Int: ...
def __divmod__(self, other: IntLike) -> Int: ...
def __pow__(self, other: IntLike) -> Int: ...
def __lshift__(self, other: IntLike) -> Int: ...
def __rshift__(self, other: IntLike) -> Int: ...
def __and__(self, other: IntLike) -> Int: ...
def __xor__(self, other: IntLike) -> Int: ...
def __or__(self, other: IntLike) -> Int: ...
def __radd__(self, other: IntLike) -> Int: ...
def __rsub__(self, other: IntLike) -> Int: ...
def __rmul__(self, other: IntLike) -> Int: ...
def __rmatmul__(self, other: IntLike) -> Int: ...
def __rtruediv__(self, other: IntLike) -> Int: ...
def __rfloordiv__(self, other: IntLike) -> Int: ...
def __rmod__(self, other: IntLike) -> Int: ...
def __rpow__(self, other: IntLike) -> Int: ...
def __rlshift__(self, other: IntLike) -> Int: ...
def __rrshift__(self, other: IntLike) -> Int: ...
def __rand__(self, other: IntLike) -> Int: ...
def __rxor__(self, other: IntLike) -> Int: ...
def __ror__(self, other: IntLike) -> Int: ...
@property
def to_i64(self) -> i64: ...
@method(preserve=True)
def eval(self) -> int:
return try_evaling(_get_current_egraph(), array_api_schedule, self, self.to_i64)
@method(preserve=True)
def __index__(self) -> int:
return self.eval()
@method(preserve=True)
def __int__(self) -> int:
return self.eval()
@method(preserve=True)
def __float__(self) -> float:
return float(self.eval())
@method(preserve=True)
def __bool__(self) -> bool:
return bool(self.eval())
@classmethod
def if_(cls, b: BooleanLike, i: IntLike, j: IntLike) -> Int: ...
@array_api_ruleset.register
def _int(i: i64, j: i64, r: Boolean, o: Int, b: Int):
yield rewrite(Int(i) == Int(i)).to(TRUE)
yield rule(eq(r).to(Int(i) == Int(j)), ne(i).to(j)).then(union(r).with_(FALSE))
yield rewrite(Int(i) >= Int(i)).to(TRUE)
yield rule(eq(r).to(Int(i) >= Int(j)), i > j).then(union(r).with_(TRUE))
yield rule(eq(r).to(Int(i) >= Int(j)), i < j).then(union(r).with_(FALSE))
yield rewrite(Int(i) < Int(i)).to(FALSE)
yield rule(eq(r).to(Int(i) < Int(j)), i < j).then(union(r).with_(TRUE))
yield rule(eq(r).to(Int(i) < Int(j)), i > j).then(union(r).with_(FALSE))
yield rewrite(Int(i) > Int(i)).to(FALSE)
yield rule(eq(r).to(Int(i) > Int(j)), i > j).then(union(r).with_(TRUE))
yield rule(eq(r).to(Int(i) > Int(j)), i < j).then(union(r).with_(FALSE))
yield rule(eq(o).to(Int(j))).then(set_(o.to_i64).to(j))
yield rule(eq(Int(i)).to(Int(j)), ne(i).to(j)).then(panic("Real ints cannot be equal to different ints"))
yield rewrite(Int(i) + Int(j)).to(Int(i + j))
yield rewrite(Int(i) - Int(j)).to(Int(i - j))
yield rewrite(Int(i) * Int(j)).to(Int(i * j))
yield rewrite(Int(i) // Int(j)).to(Int(i / j))
yield rewrite(Int(i) % Int(j)).to(Int(i % j))
yield rewrite(Int(i) & Int(j)).to(Int(i & j))
yield rewrite(Int(i) | Int(j)).to(Int(i | j))
yield rewrite(Int(i) ^ Int(j)).to(Int(i ^ j))
yield rewrite(Int(i) << Int(j)).to(Int(i << j))
yield rewrite(Int(i) >> Int(j)).to(Int(i >> j))
yield rewrite(~Int(i)).to(Int(~i))
yield rewrite(Int.if_(TRUE, o, b), subsume=True).to(o)
yield rewrite(Int.if_(FALSE, o, b), subsume=True).to(b)
yield rewrite(o.__round__(OptionalInt.none)).to(o)
# Never cannot be equal to anything real
yield rule(eq(Int.NEVER).to(Int(i))).then(panic("Int.NEVER cannot be equal to any real int"))
converter(i64, Int, Int)
IntLike: TypeAlias = Int | i64Like
@function(ruleset=array_api_ruleset)
def check_index(length: IntLike, idx: IntLike) -> Int:
"""
Returns the index if 0 <= idx < length, otherwise returns Int.NEVER
"""
length = cast("Int", length)
idx = cast("Int", idx)
return Int.if_(((idx >= 0) & (idx < length)), idx, Int.NEVER)
# @array_api_ruleset.register
# def _check_index(i: i64, j: i64, x: Int):
# yield rewrite(
# check_index(Int(i), Int(j)),
# ).to(
# Int(j),
# i >= 0,
# i < j,
# )
# yield rewrite(
# check_index(x, Int(i)),
# ).to(
# Int.NEVER,
# i < 0,
# )
# yield rewrite(
# check_index(Int(i), Int(j)),
# ).to(
# Int.NEVER,
# i >= j,
# )
class Float(Expr, ruleset=array_api_ruleset):
# Differentiate costs of three constructors so extraction is deterministic if all three are present
@method(cost=3)
def __init__(self, value: f64Like) -> None: ...
@property
def to_f64(self) -> f64: ...
@method(preserve=True)
def eval(self) -> float:
return try_evaling(_get_current_egraph(), array_api_schedule, self, self.to_f64)
def abs(self) -> Float: ...
@method(cost=2)
@classmethod
def rational(cls, r: BigRat) -> Float: ...
@classmethod
def from_int(cls, i: IntLike) -> Float: ...
def __truediv__(self, other: FloatLike) -> Float: ...
def __mul__(self, other: FloatLike) -> Float: ...
def __add__(self, other: FloatLike) -> Float: ...
def __sub__(self, other: FloatLike) -> Float: ...
def __pow__(self, other: FloatLike) -> Float: ...
def __round__(self, ndigits: OptionalIntLike = None) -> Float: ...
def __eq__(self, other: FloatLike) -> Boolean: ... # type: ignore[override]
def __ne__(self, other: FloatLike) -> Boolean: ... # type: ignore[override]
def __lt__(self, other: FloatLike) -> Boolean: ...
def __le__(self, other: FloatLike) -> Boolean: ...
def __gt__(self, other: FloatLike) -> Boolean: ...
def __ge__(self, other: FloatLike) -> Boolean: ...
converter(float, Float, Float)
converter(Int, Float, Float.from_int)
FloatLike: TypeAlias = Float | float | IntLike
@array_api_ruleset.register
def _float(fl: Float, f: f64, f2: f64, i: i64, r: BigRat, r1: BigRat, i_: Int):
return [
rule(eq(fl).to(Float(f))).then(set_(fl.to_f64).to(f)),
rewrite(Float.from_int(Int(i))).to(Float(f64.from_i64(i))),
rewrite(Float(f).abs()).to(Float(f), f >= 0.0),
rewrite(Float(f).abs()).to(Float(-f), f < 0.0),
# Convert from float to rationl, if its a whole number i.e. can be converted to int
rewrite(Float(f)).to(Float.rational(BigRat(f.to_i64(), 1)), eq(f64.from_i64(f.to_i64())).to(f)),
# always convert from int to rational
rewrite(Float.from_int(Int(i))).to(Float.rational(BigRat(i, 1))),
rewrite(Float(f) + Float(f2)).to(Float(f + f2)),
rewrite(Float(f) - Float(f2)).to(Float(f - f2)),
rewrite(Float(f) * Float(f2)).to(Float(f * f2)),
rewrite(Float.rational(r) / Float.rational(r1)).to(Float.rational(r / r1)),
rewrite(Float.rational(r) + Float.rational(r1)).to(Float.rational(r + r1)),
rewrite(Float.rational(r) - Float.rational(r1)).to(Float.rational(r - r1)),
rewrite(Float.rational(r) * Float.rational(r1)).to(Float.rational(r * r1)),
rewrite(Float(f) ** Float(f2)).to(Float(f**f2)),
# comparisons
rewrite(Float(f) == Float(f)).to(TRUE),
rewrite(Float(f) == Float(f2)).to(FALSE, ne(f).to(f2)),
rewrite(Float(f) != Float(f2)).to(TRUE, f != f2),
rewrite(Float(f) != Float(f)).to(FALSE),
rewrite(Float(f) >= Float(f2)).to(TRUE, f >= f2),
rewrite(Float(f) >= Float(f2)).to(FALSE, f < f2),
rewrite(Float(f) <= Float(f2)).to(TRUE, f <= f2),
rewrite(Float(f) <= Float(f2)).to(FALSE, f > f2),
rewrite(Float(f) > Float(f2)).to(TRUE, f > f2),
rewrite(Float(f) > Float(f2)).to(FALSE, f <= f2),
rewrite(Float(f) < Float(f2)).to(TRUE, f < f2),
rewrite(Float.rational(r) == Float.rational(r)).to(TRUE),
rewrite(Float.rational(r) == Float.rational(r1)).to(FALSE, ne(r).to(r1)),
# round
rewrite(Float.rational(r).__round__()).to(Float.rational(r.round())),
]
class TupleInt(Expr, ruleset=array_api_ruleset):
"""
Should act like a tuple[int, ...]
All constructors should be rewritten to the functional semantics in the __init__ method.
"""
@classmethod
def var(cls, name: StringLike) -> TupleInt: ...
def __init__(self, length: IntLike, idx_fn: Callable[[Int], Int]) -> None: ...
EMPTY: ClassVar[TupleInt]
NEVER: ClassVar[TupleInt]
def append(self, i: IntLike) -> TupleInt: ...
@classmethod
def single(cls, i: Int) -> TupleInt:
return TupleInt(Int(1), lambda _: i)
@method(subsume=True)
@classmethod
def range(cls, stop: IntLike) -> TupleInt:
return TupleInt(stop, lambda i: i)
@classmethod
def from_vec(cls, vec: VecLike[Int, IntLike]) -> TupleInt: ...
def __add__(self, other: TupleIntLike) -> TupleInt:
other = cast("TupleInt", other)
return TupleInt(
self.length() + other.length(), lambda i: Int.if_(i < self.length(), self[i], other[i - self.length()])
)
def length(self) -> Int: ...
def __getitem__(self, i: IntLike) -> Int: ...
@method(preserve=True)
def __len__(self) -> int:
return self.length().eval()
@method(preserve=True)
def __iter__(self) -> Iterator[Int]:
return iter(self.eval())
@property
def to_vec(self) -> Vec[Int]: ...
@method(preserve=True)
def eval(self) -> tuple[Int, ...]:
return try_evaling(_get_current_egraph(), array_api_schedule, self, self.to_vec)
def foldl(self, f: Callable[[Int, Int], Int], init: Int) -> Int: ...
def foldl_boolean(self, f: Callable[[Boolean, Int], Boolean], init: Boolean) -> Boolean: ...
def foldl_tuple_int(self, f: Callable[[TupleInt, Int], TupleInt], init: TupleIntLike) -> TupleInt: ...
@method(subsume=True)
def contains(self, i: Int) -> Boolean:
return self.foldl_boolean(lambda acc, j: acc | (i == j), FALSE)
@method(subsume=True)
def filter(self, f: Callable[[Int], Boolean]) -> TupleInt:
return self.foldl_tuple_int(
lambda acc, v: TupleInt.if_(f(v), acc.append(v), acc),
TupleInt.EMPTY,
)
@method(subsume=True)
def map(self, f: Callable[[Int], Int]) -> TupleInt:
return TupleInt(self.length(), lambda i: f(self[i]))
@classmethod
def if_(cls, b: BooleanLike, i: TupleIntLike, j: TupleIntLike) -> TupleInt: ...
def drop(self, n: Int) -> TupleInt:
return TupleInt(self.length() - n, lambda i: self[i + n])
def product(self) -> Int:
return self.foldl(lambda acc, i: acc * i, Int(1))
def map_tuple_int(self, f: Callable[[Int], TupleInt]) -> TupleTupleInt:
return TupleTupleInt(self.length(), lambda i: f(self[i]))
def select(self, indices: TupleIntLike) -> TupleInt:
"""
Return a new tuple with the elements at the given indices
"""
indices = cast("TupleInt", indices)
return indices.map(lambda i: self[i])
def deselect(self, indices: TupleIntLike) -> TupleInt:
"""
Return a new tuple with the elements not at the given indices
"""
indices = cast("TupleInt", indices)
return TupleInt.range(self.length()).filter(lambda i: ~indices.contains(i)).map(lambda i: self[i])
converter(Vec[Int], TupleInt, TupleInt.from_vec)
TupleIntLike: TypeAlias = TupleInt | VecLike[Int, IntLike]
@array_api_ruleset.register
def _tuple_int(
i: Int,
i2: Int,
f: Callable[[Int, Int], Int],
bool_f: Callable[[Boolean, Int], Boolean],
idx_fn: Callable[[Int], Int],
tuple_int_f: Callable[[TupleInt, Int], TupleInt],
vs: Vec[Int],
b: Boolean,
ti: TupleInt,
ti2: TupleInt,
k: i64,
):
return [
rule(eq(ti).to(TupleInt.from_vec(vs))).then(set_(ti.to_vec).to(vs)),
# Functional access
rewrite(TupleInt(i, idx_fn).length()).to(i),
rewrite(TupleInt(i, idx_fn)[i2]).to(idx_fn(check_index(i, i2))),
# cons access
rewrite(TupleInt.EMPTY.length()).to(Int(0)),
rewrite(TupleInt.EMPTY[i]).to(Int.NEVER),
rewrite(ti.append(i).length()).to(ti.length() + 1),
rewrite(ti.append(i)[i2]).to(Int.if_(i2 == ti.length(), i, ti[i2])),
# cons to functional (removed this so that there is not infinite replacements between the,)
# rewrite(TupleInt.EMPTY).to(TupleInt(0, lambda _: Int.NEVER)),
# rewrite(TupleInt(i, idx_fn).append(i2)).to(TupleInt(i + 1, lambda j: Int.if_(j == i, i2, idx_fn(j)))),
# functional to cons
rewrite(TupleInt(0, idx_fn), subsume=True).to(TupleInt.EMPTY),
rewrite(TupleInt(Int(k), idx_fn), subsume=True).to(TupleInt(k - 1, idx_fn).append(idx_fn(Int(k - 1))), k > 0),
# cons to vec
rewrite(TupleInt.EMPTY).to(TupleInt.from_vec(Vec[Int]())),
rewrite(TupleInt.from_vec(vs).append(i)).to(TupleInt.from_vec(vs.append(Vec(i)))),
# fold
rewrite(TupleInt.EMPTY.foldl(f, i), subsume=True).to(i),
rewrite(ti.append(i2).foldl(f, i), subsume=True).to(f(ti.foldl(f, i), i2)),
# fold boolean
rewrite(TupleInt.EMPTY.foldl_boolean(bool_f, b), subsume=True).to(b),
rewrite(ti.append(i2).foldl_boolean(bool_f, b), subsume=True).to(bool_f(ti.foldl_boolean(bool_f, b), i2)),
# fold tuple_int
rewrite(TupleInt.EMPTY.foldl_tuple_int(tuple_int_f, ti), subsume=True).to(ti),
rewrite(ti.append(i2).foldl_tuple_int(tuple_int_f, ti2), subsume=True).to(
tuple_int_f(ti.foldl_tuple_int(tuple_int_f, ti2), i2)
),
# if_
rewrite(TupleInt.if_(TRUE, ti, ti2), subsume=True).to(ti),
rewrite(TupleInt.if_(FALSE, ti, ti2), subsume=True).to(ti2),
# unify append
rule(eq(ti.append(i)).to(ti2.append(i2))).then(union(ti).with_(ti2), union(i).with_(i2)),
]
class TupleTupleInt(Expr, ruleset=array_api_ruleset):
@classmethod
def var(cls, name: StringLike) -> TupleTupleInt: ...
EMPTY: ClassVar[TupleTupleInt]
def __init__(self, length: IntLike, idx_fn: Callable[[Int], TupleInt]) -> None: ...
@method(subsume=True)
@classmethod
def single(cls, i: TupleIntLike) -> TupleTupleInt:
i = cast("TupleInt", i)
return TupleTupleInt(1, lambda _: i)
@method(subsume=True)
@classmethod
def from_vec(cls, vec: Vec[TupleInt]) -> TupleTupleInt: ...
def append(self, i: TupleIntLike) -> TupleTupleInt: ...
def __add__(self, other: TupleTupleIntLike) -> TupleTupleInt:
other = cast("TupleTupleInt", other)
return TupleTupleInt(
self.length() + other.length(),
lambda i: TupleInt.if_(i < self.length(), self[i], other[i - self.length()]),
)
def length(self) -> Int: ...
def __getitem__(self, i: IntLike) -> TupleInt: ...
@method(preserve=True)
def __len__(self) -> int:
return self.length().eval()
@method(preserve=True)
def __iter__(self) -> Iterator[TupleInt]:
return iter(self.eval())
@property
def to_vec(self) -> Vec[TupleInt]: ...
@method(preserve=True)
def eval(self) -> tuple[TupleInt, ...]:
return try_evaling(_get_current_egraph(), array_api_schedule, self, self.to_vec)
def drop(self, n: Int) -> TupleTupleInt:
return TupleTupleInt(self.length() - n, lambda i: self[i + n])
def map_int(self, f: Callable[[TupleInt], Int]) -> TupleInt:
return TupleInt(self.length(), lambda i: f(self[i]))
def foldl_value(self, f: Callable[[Value, TupleInt], Value], init: ValueLike) -> Value: ...
@method(subsume=True)
def product(self) -> TupleTupleInt:
"""
Cartesian product of inputs
https://docs.python.org/3/library/itertools.html#itertools.product
https://github.com/saulshanabrook/saulshanabrook/discussions/39
"""
return TupleTupleInt(
self.map_int(lambda x: x.length()).product(),
lambda i: TupleInt(
self.length(),
lambda j: self[j][(i // self.drop(j + 1).map_int(lambda x: x.length()).product()) % self[j].length()],
),
)
converter(Vec[TupleInt], TupleTupleInt, TupleTupleInt.from_vec)
TupleTupleIntLike: TypeAlias = TupleTupleInt | VecLike[TupleInt, TupleIntLike]
@array_api_ruleset.register
def _tuple_tuple_int(
length: Int,
fn: Callable[[TupleInt], Int],
idx_fn: Callable[[Int], TupleInt],
f: Callable[[Value, TupleInt], Value],
i: Value,
k: i64,
idx: Int,
vs: Vec[TupleInt],
ti: TupleInt,
ti1: TupleInt,
tti: TupleTupleInt,
tti1: TupleTupleInt,
):
yield rule(eq(tti).to(TupleTupleInt.from_vec(vs))).then(set_(tti.to_vec).to(vs))
yield rewrite(TupleTupleInt(length, idx_fn).length()).to(length)
yield rewrite(TupleTupleInt(length, idx_fn)[idx]).to(idx_fn(check_index(idx, length)))
# cons access
yield rewrite(TupleTupleInt.EMPTY.length()).to(Int(0))
yield rewrite(TupleTupleInt.EMPTY[idx]).to(TupleInt.NEVER)
yield rewrite(tti.append(ti).length()).to(tti.length() + 1)
yield rewrite(tti.append(ti)[idx]).to(TupleInt.if_(idx == tti.length(), ti, tti[idx]))
# functional to cons
yield rewrite(TupleTupleInt(0, idx_fn), subsume=True).to(TupleTupleInt.EMPTY)
yield rewrite(TupleTupleInt(Int(k), idx_fn), subsume=True).to(
TupleTupleInt(k - 1, idx_fn).append(idx_fn(Int(k - 1))), k > 0
)
# cons to vec
yield rewrite(TupleTupleInt.EMPTY).to(TupleTupleInt.from_vec(Vec[TupleInt]()))
yield rewrite(TupleTupleInt.from_vec(vs).append(ti)).to(TupleTupleInt.from_vec(vs.append(Vec(ti))))
# fold value
yield rewrite(TupleTupleInt.EMPTY.foldl_value(f, i), subsume=True).to(i)
yield rewrite(tti.append(ti).foldl_value(f, i), subsume=True).to(f(tti.foldl_value(f, i), ti))
# unify append
yield rule(eq(tti.append(ti)).to(tti1.append(ti1))).then(union(tti).with_(tti1), union(ti).with_(ti1))
class OptionalInt(Expr, ruleset=array_api_ruleset):
none: ClassVar[OptionalInt]
@classmethod
def some(cls, value: Int) -> OptionalInt: ...
OptionalIntLike: TypeAlias = OptionalInt | IntLike | None
converter(type(None), OptionalInt, lambda _: OptionalInt.none)
converter(Int, OptionalInt, OptionalInt.some)
class DType(Expr, ruleset=array_api_ruleset):
float64: ClassVar[DType]
float32: ClassVar[DType]
int64: ClassVar[DType]
int32: ClassVar[DType]
object: ClassVar[DType]
bool: ClassVar[DType]
def __eq__(self, other: DType) -> Boolean: # type: ignore[override]
...
float64 = DType.float64
float32 = DType.float32
int32 = DType.int32
int64 = DType.int64
_DTYPES = [float64, float32, int32, int64, DType.object]
converter(type, DType, lambda x: convert(np.dtype(x), DType))
converter(np.dtype, DType, lambda x: getattr(DType, x.name))
@array_api_ruleset.register
def _():
for l, r in itertools.product(_DTYPES, repeat=2):
yield rewrite(l == r).to(TRUE if l is r else FALSE)
class IsDtypeKind(Expr, ruleset=array_api_ruleset):
NULL: ClassVar[IsDtypeKind]
@classmethod
def string(cls, s: StringLike) -> IsDtypeKind: ...
@classmethod
def dtype(cls, d: DType) -> IsDtypeKind: ...
@method(cost=10)
def __or__(self, other: IsDtypeKind) -> IsDtypeKind: ...
# TODO: Make kind more generic to support tuples.
@function
def isdtype(dtype: DType, kind: IsDtypeKind) -> Boolean: ...
converter(DType, IsDtypeKind, IsDtypeKind.dtype)
converter(str, IsDtypeKind, IsDtypeKind.string)
converter(
tuple, IsDtypeKind, lambda x: convert(x[0], IsDtypeKind) | convert(x[1:], IsDtypeKind) if x else IsDtypeKind.NULL
)
@array_api_ruleset.register
def _isdtype(d: DType, k1: IsDtypeKind, k2: IsDtypeKind):
return [
rewrite(isdtype(DType.float32, IsDtypeKind.string("integral"))).to(FALSE),
rewrite(isdtype(DType.float64, IsDtypeKind.string("integral"))).to(FALSE),
rewrite(isdtype(DType.object, IsDtypeKind.string("integral"))).to(FALSE),
rewrite(isdtype(DType.int64, IsDtypeKind.string("integral"))).to(TRUE),
rewrite(isdtype(DType.int32, IsDtypeKind.string("integral"))).to(TRUE),
rewrite(isdtype(DType.float32, IsDtypeKind.string("real floating"))).to(TRUE),
rewrite(isdtype(DType.float64, IsDtypeKind.string("real floating"))).to(TRUE),
rewrite(isdtype(DType.object, IsDtypeKind.string("real floating"))).to(FALSE),
rewrite(isdtype(DType.int64, IsDtypeKind.string("real floating"))).to(FALSE),
rewrite(isdtype(DType.int32, IsDtypeKind.string("real floating"))).to(FALSE),
rewrite(isdtype(DType.float32, IsDtypeKind.string("complex floating"))).to(FALSE),
rewrite(isdtype(DType.float64, IsDtypeKind.string("complex floating"))).to(FALSE),
rewrite(isdtype(DType.object, IsDtypeKind.string("complex floating"))).to(FALSE),
rewrite(isdtype(DType.int64, IsDtypeKind.string("complex floating"))).to(FALSE),
rewrite(isdtype(DType.int32, IsDtypeKind.string("complex floating"))).to(FALSE),
rewrite(isdtype(d, IsDtypeKind.NULL)).to(FALSE),
rewrite(isdtype(d, IsDtypeKind.dtype(d))).to(TRUE),
rewrite(isdtype(d, k1 | k2)).to(isdtype(d, k1) | isdtype(d, k2)),
rewrite(k1 | IsDtypeKind.NULL).to(k1),
]
# TODO: Add pushdown for math on scalars to values
# and add replacements
class Value(Expr, ruleset=array_api_ruleset):
NEVER: ClassVar[Value]
@classmethod
def int(cls, i: IntLike) -> Value: ...
@classmethod
def float(cls, f: FloatLike) -> Value: ...
@classmethod
def bool(cls, b: BooleanLike) -> Value: ...
def isfinite(self) -> Boolean: ...
def __lt__(self, other: ValueLike) -> Value: ...
def __truediv__(self, other: ValueLike) -> Value: ...
def __mul__(self, other: ValueLike) -> Value: ...
def __add__(self, other: ValueLike) -> Value: ...
def astype(self, dtype: DType) -> Value: ...
# TODO: Add all operations
@property
def dtype(self) -> DType:
"""
Default dtype for this scalar value
"""
@property
def to_bool(self) -> Boolean: ...
@property
def to_int(self) -> Int: ...
@property
def to_truthy_value(self) -> Value:
"""
Converts the value to a bool, based on if its truthy.
https://data-apis.org/array-api/2022.12/API_specification/generated/array_api.any.html
"""
def conj(self) -> Value: ...
def real(self) -> Value: ...
def sqrt(self) -> Value: ...
@classmethod
def if_(cls, b: BooleanLike, i: ValueLike, j: ValueLike) -> Value: ...
def __eq__(self, other: ValueLike) -> Boolean: ... # type: ignore[override]
ValueLike: TypeAlias = Value | IntLike | FloatLike | BooleanLike
converter(Int, Value, Value.int)
converter(Float, Value, Value.float)
converter(Boolean, Value, Value.bool)
converter(Value, Int, lambda x: x.to_int, 10)
@array_api_ruleset.register
def _value(i: Int, f: Float, b: Boolean, v: Value, v1: Value, i1: Int, f1: Float, b1: Boolean):
# Default dtypes
# https://data-apis.org/array-api/latest/API_specification/data_types.html?highlight=dtype#default-data-types
yield rewrite(Value.int(i).dtype).to(DType.int64)
yield rewrite(Value.float(f).dtype).to(DType.float64)
yield rewrite(Value.bool(b).dtype).to(DType.bool)
yield rewrite(Value.bool(b).to_bool).to(b)
yield rewrite(Value.int(i).to_int).to(i)
yield rewrite(Value.bool(b).to_truthy_value).to(Value.bool(b))
# TODO: Add more rules for to_bool_value
yield rewrite(Value.float(f).conj()).to(Value.float(f))
yield rewrite(Value.float(f).real()).to(Value.float(f))
yield rewrite(Value.int(i).real()).to(Value.int(i))
yield rewrite(Value.int(i).conj()).to(Value.int(i))
yield rewrite(Value.float(f).sqrt()).to(Value.float(f ** (0.5)))
yield rewrite(Value.float(Float.rational(BigRat(0, 1))) + v).to(v)
yield rewrite(Value.if_(TRUE, v, v1)).to(v)
yield rewrite(Value.if_(FALSE, v, v1)).to(v1)
# ==
yield rewrite(Value.int(i) == Value.int(i1)).to(i == i1)
yield rewrite(Value.float(f) == Value.float(f1)).to(f == f1)
yield rewrite(Value.bool(b) == Value.bool(b1)).to(b == b1)
class TupleValue(Expr, ruleset=array_api_ruleset):
EMPTY: ClassVar[TupleValue]
def __init__(self, length: IntLike, idx_fn: Callable[[Int], Value]) -> None: ...
def append(self, i: ValueLike) -> TupleValue: ...
@classmethod
def from_vec(cls, vec: Vec[Value]) -> TupleValue: ...
def __add__(self, other: TupleValueLike) -> TupleValue:
other = cast("TupleValue", other)
return TupleValue(
self.length() + other.length(),
lambda i: Value.if_(i < self.length(), self[i], other[i - self.length()]),
)
def length(self) -> Int: ...
def __getitem__(self, i: Int) -> Value: ...
def foldl_boolean(self, f: Callable[[Boolean, Value], Boolean], init: BooleanLike) -> Boolean: ...
def contains(self, value: ValueLike) -> Boolean:
value = cast("Value", value)
return self.foldl_boolean(lambda acc, j: acc | (value == j), FALSE)
@method(subsume=True)
@classmethod
def from_tuple_int(cls, ti: TupleIntLike) -> TupleValue:
ti = cast("TupleInt", ti)
return TupleValue(ti.length(), lambda i: Value.int(ti[i]))
converter(Vec[Value], TupleValue, TupleValue.from_vec)
converter(TupleInt, TupleValue, TupleValue.from_tuple_int)
TupleValueLike: TypeAlias = TupleValue | VecLike[Value, ValueLike] | TupleIntLike
@array_api_ruleset.register
def _tuple_value(
length: Int,
idx_fn: Callable[[Int], Value],
k: i64,
idx: Int,
vs: Vec[Value],
v: Value,
v1: Value,
tv: TupleValue,
tv1: TupleValue,
bool_f: Callable[[Boolean, Value], Boolean],
b: Boolean,
):
yield rewrite(TupleValue(length, idx_fn).length()).to(length)
yield rewrite(TupleValue(length, idx_fn)[idx]).to(idx_fn(check_index(idx, length)))
# cons access
yield rewrite(TupleValue.EMPTY.length()).to(Int(0))
yield rewrite(TupleValue.EMPTY[idx]).to(Value.NEVER)
yield rewrite(tv.append(v).length()).to(tv.length() + 1)
yield rewrite(tv.append(v)[idx]).to(Value.if_(idx == tv.length(), v, tv[idx]))
# functional to cons
yield rewrite(TupleValue(0, idx_fn), subsume=True).to(TupleValue.EMPTY)
yield rewrite(TupleValue(Int(k), idx_fn), subsume=True).to(
TupleValue(k - 1, idx_fn).append(idx_fn(Int(k - 1))), k > 0
)
# cons to vec
yield rewrite(TupleValue.EMPTY).to(TupleValue.from_vec(Vec[Value]()))
yield rewrite(TupleValue.from_vec(vs).append(v)).to(TupleValue.from_vec(vs.append(Vec(v))))
# fold boolean
yield rewrite(TupleValue.EMPTY.foldl_boolean(bool_f, b), subsume=True).to(b)
yield rewrite(tv.append(v).foldl_boolean(bool_f, b), subsume=True).to(bool_f(tv.foldl_boolean(bool_f, b), v))
# unify append
yield rule(eq(tv.append(v)).to(tv1.append(v1))).then(union(tv).with_(tv1), union(v).with_(v1))
@function
def possible_values(values: Value) -> TupleValue:
"""
All possible values in the input value.
"""
class Slice(Expr, ruleset=array_api_ruleset):
def __init__(
self,
start: OptionalInt = OptionalInt.none,
stop: OptionalInt = OptionalInt.none,
step: OptionalInt = OptionalInt.none,
) -> None: ...
converter(
slice,
Slice,
lambda x: Slice(convert(x.start, OptionalInt), convert(x.stop, OptionalInt), convert(x.step, OptionalInt)),
)
SliceLike: TypeAlias = Slice | slice
class MultiAxisIndexKeyItem(Expr, ruleset=array_api_ruleset):
ELLIPSIS: ClassVar[MultiAxisIndexKeyItem]
NONE: ClassVar[MultiAxisIndexKeyItem]