pyrefly-numpy-stubs 1.4.0.dev3__tar.gz → 1.4.0.dev4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyrefly-numpy-stubs
3
- Version: 1.4.0.dev3
3
+ Version: 1.4.0.dev4
4
4
  Summary: NumPy type stubs with array-shape tracking, maintained by Pyrefly
5
5
  Project-URL: homepage, https://pyrefly.org
6
6
  Project-URL: documentation, https://pyrefly.org/en/docs/
@@ -33,7 +33,8 @@ Classifier: Programming Language :: Python
33
33
  Classifier: Programming Language :: Python :: 3
34
34
  Classifier: Typing :: Stubs Only
35
35
  Requires-Python: >=3.12
36
- Requires-Dist: pyrefly-shape-extensions==1.4.0.dev3
36
+ Requires-Dist: numpy
37
+ Requires-Dist: pyrefly-shape-extensions==1.4.0.dev4
37
38
  Description-Content-Type: text/markdown
38
39
 
39
40
  # pyrefly-numpy-stubs
@@ -45,7 +46,9 @@ This package is a PEP 561 stub-only distribution. It installs the
45
46
  runtime `numpy` package without replacing or shadowing NumPy itself.
46
47
 
47
48
  The package is versioned in lockstep with Pyrefly and depends on the matching
48
- `pyrefly-shape-extensions` package.
49
+ `pyrefly-shape-extensions` package. Installing it also installs `numpy`, which
50
+ provides upstream modules used by these partial stubs. The `numpy` dependency is
51
+ unpinned, so projects can choose their own NumPy version.
49
52
 
50
53
  Static checks use NumPy's installed stubs for APIs that this package re-exports:
51
54
 
@@ -7,7 +7,9 @@ This package is a PEP 561 stub-only distribution. It installs the
7
7
  runtime `numpy` package without replacing or shadowing NumPy itself.
8
8
 
9
9
  The package is versioned in lockstep with Pyrefly and depends on the matching
10
- `pyrefly-shape-extensions` package.
10
+ `pyrefly-shape-extensions` package. Installing it also installs `numpy`, which
11
+ provides upstream modules used by these partial stubs. The `numpy` dependency is
12
+ unpinned, so projects can choose their own NumPy version.
11
13
 
12
14
  Static checks use NumPy's installed stubs for APIs that this package re-exports:
13
15
 
@@ -6,7 +6,7 @@
6
6
  from builtins import bool as py_bool
7
7
  from collections.abc import Iterator, Sequence
8
8
  from types import EllipsisType
9
- from typing import Any, Final, Literal, overload, SupportsIndex
9
+ from typing import Any, Final, Literal, Never, overload, SupportsIndex
10
10
 
11
11
  import shape_extensions
12
12
  from numpy.__config__ import (
@@ -18,6 +18,7 @@ from numpy._array_api_info import (
18
18
  from numpy._core._asarray import (
19
19
  require as require,
20
20
  )
21
+ from numpy._core._internal import _ctypes
21
22
  from numpy._core._type_aliases import (
22
23
  sctypeDict as sctypeDict,
23
24
  )
@@ -182,12 +183,26 @@ from numpy._core.shape_base import (
182
183
  )
183
184
  from numpy._pytesttester import PytestTester
184
185
  from numpy._shapes import (
186
+ compress_shape,
185
187
  diag_extent,
188
+ diag_matrix_shape,
189
+ diagonal_shape,
190
+ dot_shape,
186
191
  expand_dims_shape,
187
192
  matmul_shape,
188
193
  matvec_shape,
194
+ nonzero_shapes,
189
195
  reduce_shape,
196
+ repeat_sequence_shape,
197
+ repeat_shape,
198
+ reshape_shape,
199
+ reshape_varargs_shape,
200
+ reverse_shape,
201
+ squeeze_shape,
190
202
  stack_shape,
203
+ swapaxes_shape,
204
+ take_shape,
205
+ transpose_shape,
191
206
  vecdot_shape,
192
207
  vecmat_shape,
193
208
  )
@@ -381,7 +396,9 @@ from shape_extensions import (
381
396
  Index,
382
397
  index_shape,
383
398
  Int,
399
+ IntListLiteral,
384
400
  IntTuple,
401
+ IntTupleOrList,
385
402
  IntTuples,
386
403
  IntVar,
387
404
  MapIntTuples,
@@ -416,14 +433,47 @@ type _BasicIndex = int | slice | list[int] | None | EllipsisType
416
433
  class generic:
417
434
  def astype(self, dtype: Any, **kwargs: Any) -> Any: ...
418
435
 
436
+ class number(generic): ...
437
+ class integer(number): ...
438
+
439
+ class signedinteger(integer):
440
+ # TODO(stroxler): Sequence inputs to scalar constructors can produce arrays.
441
+ def __init__(self, value: object = ...) -> None: ...
442
+
443
+ class unsignedinteger(integer): ...
444
+ class inexact(number): ...
445
+ class floating(inexact): ...
446
+ class complexfloating(inexact): ...
419
447
  class bool_(generic): ...
420
- class float32(generic): ...
421
- class float64(generic): ...
422
- class int32(generic): ...
423
- class int64(generic): ...
424
- class intp(generic): ...
448
+ class float16(floating): ...
449
+ class float32(floating): ...
450
+ class float64(floating): ...
451
+ class longdouble(floating): ...
452
+ class complex64(complexfloating): ...
453
+ class complex128(complexfloating): ...
454
+ class clongdouble(complexfloating): ...
455
+ class flexible(generic): ...
456
+ class character(flexible): ...
457
+ class bytes_(character, bytes): ...
458
+ class str_(character, str): ...
459
+ class void(flexible): ...
460
+ class object_(generic): ...
461
+ class datetime64(generic): ...
462
+ class timedelta64(signedinteger): ...
463
+ class int8(signedinteger): ...
464
+ class int16(signedinteger): ...
465
+ class int32(signedinteger): ...
466
+ class int64(signedinteger): ...
467
+ class intp(signedinteger): ...
468
+ class longlong(signedinteger): ...
469
+ class uint8(unsignedinteger): ...
470
+ class uint16(unsignedinteger): ...
471
+ class uint32(unsignedinteger): ...
472
+ class uint64(unsignedinteger): ...
473
+ class uintp(unsignedinteger): ...
474
+ class ulonglong(unsignedinteger): ...
425
475
 
426
- type _IndexScalar = int | bool_ | int32 | int64 | intp
476
+ type _IndexScalar = int | bool_ | integer
427
477
  type _IndexSequence = Sequence[_IndexScalar] | Sequence[Sequence[_IndexScalar]]
428
478
  type _ArrayIndex = (
429
479
  _BasicIndex
@@ -432,7 +482,7 @@ type _ArrayIndex = (
432
482
  | ndarray
433
483
  | tuple[_BasicIndex | _IndexScalar | _IndexSequence | ndarray, ...]
434
484
  )
435
- type _ArrayScalar = None | bool | int | float | complex | str | bytes | generic
485
+ type _ArrayScalar = None | py_bool | int | float | complex | str | bytes | generic
436
486
 
437
487
  __version__: Final[str]
438
488
  e: Final[float]
@@ -578,6 +628,7 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
578
628
  ) -> ndarray[_broadcast_shape(Shape, OtherShape), DType]: ...
579
629
  def __neg__(self) -> ndarray[Shape, DType]: ...
580
630
  def __pos__(self) -> ndarray[Shape, DType]: ...
631
+ def __abs__(self, /) -> ndarray[Shape]: ...
581
632
  def __pow__[OtherShape: _Shape = []](
582
633
  self, other: ndarray[[*OtherShape]] | int | float
583
634
  ) -> ndarray[_broadcast_shape(Shape, OtherShape), DType]: ...
@@ -847,8 +898,13 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
847
898
  ) -> None: ...
848
899
  def put(self, indices: Any, values: Any, mode: str = "raise") -> None: ...
849
900
  def ravel(self, order: str = "C") -> ndarray[[int], DType]: ...
850
- # TODO(stroxler): Model receiver invalidation for shape-changing mutation.
851
- resize: Any
901
+ def resize(self, *, not_usable_with_shape_types: Never) -> None:
902
+ """Unsupported: resizing changes the receiver's shape in place.
903
+
904
+ A statically typed array cannot acquire a new shape type after a method call.
905
+ Create a new array instead of resizing an existing one.
906
+ """
907
+ ...
852
908
  def round(self, decimals: int = 0, out: Any = None) -> ndarray[Shape, DType]: ...
853
909
  def setfield(self, val: Any, dtype: Any, offset: int = 0) -> None: ...
854
910
  def setflags(
@@ -872,24 +928,270 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
872
928
  def tofile(self, fid: Any, sep: str = "", format: str = "%s") -> None: ...
873
929
  def tolist(self) -> Any: ...
874
930
 
875
- # TODO(stroxler): Replace these placeholders with shape-aware declarations.
876
- choose: Any
877
- compress: Any
878
- ctypes: Any
879
- diagonal: Any
880
- dot: Any
881
- flat: Any
882
- mT: Any
883
- nonzero: Any
884
- repeat: Any
885
- reshape: Any
886
- searchsorted: Any
887
- squeeze: Any
888
- swapaxes: Any
889
- take: Any
890
- trace: Any
891
- transpose: Any
892
- view: Any
931
+ # TODO(stroxler): Model broadcast choices and condition-dependent compress lengths.
932
+ @overload
933
+ def choose(
934
+ self,
935
+ choices: ArrayLike,
936
+ out: None = None,
937
+ mode: Literal["raise", "wrap", "clip"] = "raise",
938
+ ) -> ndarray[IntTuple]: ...
939
+ @overload
940
+ def choose[Out: ndarray](
941
+ self,
942
+ choices: ArrayLike,
943
+ out: Out,
944
+ mode: Literal["raise", "wrap", "clip"] = "raise",
945
+ ) -> Out: ...
946
+ @overload
947
+ def compress[Axis: Flag[int | None]](
948
+ self, condition: Sequence[int] | ndarray, axis: Axis = None, out: None = None
949
+ ) -> ndarray[compress_shape(Shape, Axis), DType]: ...
950
+ @overload
951
+ def compress[Out: ndarray](
952
+ self,
953
+ condition: Sequence[int] | ndarray,
954
+ axis: int | None,
955
+ out: Out,
956
+ ) -> Out: ...
957
+ @overload
958
+ def compress[Out: ndarray](
959
+ self,
960
+ condition: Sequence[int] | ndarray,
961
+ axis: int | None = None,
962
+ *,
963
+ out: Out,
964
+ ) -> Out: ...
965
+ @property
966
+ def ctypes(self) -> _ctypes[int]: ...
967
+ def diagonal[Offset: Flag[int], First: Flag[int], Second: Flag[int]](
968
+ self, offset: Offset = 0, axis1: First = 0, axis2: Second = 1
969
+ ) -> ndarray[diagonal_shape(Shape, First, Second, True, Offset), DType]: ...
970
+ @overload
971
+ def dot[N: IntVar](
972
+ self: ndarray[[N], DType], b: ndarray[[N]], /, out: None = None
973
+ ) -> generic: ...
974
+ @overload
975
+ def dot(self: ndarray[[]], b: _ArrayScalar, /, out: None = None) -> generic: ...
976
+ @overload
977
+ def dot[Right: IntTuple](
978
+ self, b: ndarray[Right], /, out: None = None
979
+ ) -> ndarray[dot_shape(Shape, Right)]: ...
980
+ @overload
981
+ def dot[Right: IntTuple](
982
+ self,
983
+ b: RegularNestedList[Right, _ArrayScalar],
984
+ /,
985
+ out: None = None,
986
+ ) -> ndarray[dot_shape(Shape, Right)]: ...
987
+ @overload
988
+ def dot(
989
+ self, b: int | float | complex | generic, /, out: None = None
990
+ ) -> ndarray[Shape]: ...
991
+ @overload
992
+ def dot[Out: ndarray](self, b: ArrayLike, /, out: Out) -> Out: ...
993
+ # TODO(stroxler): Infer scalar dtype promotion for vector inner products.
994
+ @property
995
+ def flat(self) -> flatiter[ndarray[Shape, DType]]: ...
996
+ @property
997
+ def mT(self) -> ndarray[swapaxes_shape(Shape, -1, -2), DType]: ...
998
+ def nonzero(
999
+ self,
1000
+ ) -> MapIntTuples[lambda S: ndarray[S, dtype[intp]], nonzero_shapes(Shape)]: ...
1001
+ @overload
1002
+ def repeat[Repeats: Int, Axis: Flag[int | None]](
1003
+ self, repeats: Repeats, /, axis: Axis = None
1004
+ ) -> ndarray[repeat_shape(Shape, Repeats, Axis), DType]: ...
1005
+ @overload
1006
+ def repeat[Repeats: IntTuple, Axis: Flag[int | None]](
1007
+ self, repeats: Repeats | IntListLiteral[Repeats], /, axis: Axis = None
1008
+ ) -> ndarray[repeat_sequence_shape(Shape, Repeats, Axis), DType]: ...
1009
+ @overload
1010
+ def repeat[Axis: Flag[int | None]](
1011
+ self, repeats: Sequence[int] | ndarray, /, axis: Axis = None
1012
+ ) -> ndarray[repeat_shape(Shape, Int, Axis), DType]: ...
1013
+ @overload
1014
+ def reshape(
1015
+ self,
1016
+ shape: None,
1017
+ /,
1018
+ *,
1019
+ order: Literal["C", "F", "A"] = "C",
1020
+ copy: py_bool | None = None,
1021
+ ) -> ndarray[Shape, DType]: ...
1022
+ @overload
1023
+ def reshape[Target: IntTuple](
1024
+ self,
1025
+ shape: IntTupleOrList[Target],
1026
+ /,
1027
+ *,
1028
+ order: Literal["C", "F", "A"] = "C",
1029
+ copy: py_bool | None = None,
1030
+ ) -> ndarray[reshape_shape(Shape, Target), DType]: ...
1031
+ @overload
1032
+ def reshape[Target: IntTuple](
1033
+ self,
1034
+ /,
1035
+ *shape: *Target,
1036
+ order: Literal["C", "F", "A"] = "C",
1037
+ copy: py_bool | None = None,
1038
+ ) -> ndarray[reshape_varargs_shape(Shape, Target), DType]: ...
1039
+ @overload
1040
+ def searchsorted[N: IntVar](
1041
+ self: ndarray[[N]],
1042
+ v: _ArrayScalar | ndarray[[]],
1043
+ /,
1044
+ side: Literal["left", "right"] = "left",
1045
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1046
+ ) -> intp: ...
1047
+ @overload
1048
+ def searchsorted[N: IntVar, Values: _Shape](
1049
+ self: ndarray[[N]],
1050
+ v: ndarray[Values],
1051
+ /,
1052
+ side: Literal["left", "right"] = "left",
1053
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1054
+ ) -> ndarray[Values, _dtype[intp]]: ...
1055
+ @overload
1056
+ def searchsorted[N: IntVar, Values: _Shape](
1057
+ self: ndarray[[N]],
1058
+ v: RegularNestedList[Values, _ArrayScalar],
1059
+ /,
1060
+ side: Literal["left", "right"] = "left",
1061
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1062
+ ) -> ndarray[Values, _dtype[intp]]: ...
1063
+ def squeeze[Axis: Flag[_Axis]](
1064
+ self, axis: Axis = None
1065
+ ) -> ndarray[squeeze_shape(Shape, Axis), DType]: ...
1066
+ def swapaxes[First: Flag[int], Second: Flag[int]](
1067
+ self, axis1: First, axis2: Second, /
1068
+ ) -> ndarray[swapaxes_shape(Shape, First, Second), DType]: ...
1069
+ @overload
1070
+ def take(
1071
+ self,
1072
+ indices: int | int32 | int64 | intp,
1073
+ /,
1074
+ axis: None = None,
1075
+ out: None = None,
1076
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1077
+ ) -> generic: ...
1078
+ @overload
1079
+ def take[Axis: Flag[int]](
1080
+ self,
1081
+ indices: int | int32 | int64 | intp,
1082
+ /,
1083
+ axis: Axis,
1084
+ out: None = None,
1085
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1086
+ ) -> ndarray[take_shape(Shape, IntTuple[()], Axis), DType]: ...
1087
+ @overload
1088
+ def take[Indices: IntTuple](
1089
+ self,
1090
+ indices: ndarray[Indices],
1091
+ /,
1092
+ axis: None = None,
1093
+ out: None = None,
1094
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1095
+ ) -> ndarray[Indices, DType]: ...
1096
+ @overload
1097
+ def take(
1098
+ self,
1099
+ indices: Sequence[int],
1100
+ /,
1101
+ axis: None = None,
1102
+ out: None = None,
1103
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1104
+ ) -> ndarray[[int], DType]: ...
1105
+ @overload
1106
+ def take[Axis: Flag[int]](
1107
+ self,
1108
+ indices: Sequence[int],
1109
+ /,
1110
+ axis: Axis,
1111
+ out: None = None,
1112
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1113
+ ) -> ndarray[take_shape(Shape, IntTuple[int], Axis), DType]: ...
1114
+ @overload
1115
+ def take[Indices: IntTuple, Axis: Flag[int]](
1116
+ self,
1117
+ indices: ndarray[Indices],
1118
+ /,
1119
+ axis: Axis,
1120
+ out: None = None,
1121
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1122
+ ) -> ndarray[take_shape(Shape, Indices, Axis), DType]: ...
1123
+ @overload
1124
+ def take[Out: ndarray](
1125
+ self,
1126
+ indices: int | Sequence[int] | ndarray,
1127
+ /,
1128
+ axis: int | None,
1129
+ out: Out,
1130
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1131
+ ) -> Out: ...
1132
+ @overload
1133
+ def take[Out: ndarray](
1134
+ self,
1135
+ indices: int | Sequence[int] | ndarray,
1136
+ /,
1137
+ axis: int | None = None,
1138
+ *,
1139
+ out: Out,
1140
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1141
+ ) -> Out: ...
1142
+ # TODO(stroxler): Restrict index-array dtypes to valid index types.
1143
+ @overload
1144
+ def trace[M: IntVar, N: IntVar](
1145
+ self: ndarray[[M, N], DType],
1146
+ offset: int = 0,
1147
+ axis1: int = 0,
1148
+ axis2: int = 1,
1149
+ dtype: Any = None,
1150
+ out: None = None,
1151
+ ) -> generic: ...
1152
+ @overload
1153
+ def trace[First: Flag[int], Second: Flag[int]](
1154
+ self,
1155
+ offset: int = 0,
1156
+ axis1: First = 0,
1157
+ axis2: Second = 1,
1158
+ dtype: Any = None,
1159
+ out: None = None,
1160
+ ) -> ndarray[diagonal_shape(Shape, First, Second, False, 0)]: ...
1161
+ @overload
1162
+ def trace[Out: ndarray](
1163
+ self,
1164
+ offset: int = 0,
1165
+ axis1: int = 0,
1166
+ axis2: int = 1,
1167
+ dtype: Any = None,
1168
+ *,
1169
+ out: Out,
1170
+ ) -> Out: ...
1171
+ # TODO(stroxler): Validate 2-D axes and infer scalar dtype promotion.
1172
+ @overload
1173
+ def transpose(
1174
+ self, axes: None = None, /
1175
+ ) -> ndarray[reverse_shape(Shape), DType]: ...
1176
+ @overload
1177
+ def transpose[Axes: IntTuple](
1178
+ self, axes: Axes, /
1179
+ ) -> ndarray[transpose_shape(Shape, Axes), DType]: ...
1180
+ @overload
1181
+ def transpose[Axes: IntTuple](
1182
+ self, *axes: *Axes
1183
+ ) -> ndarray[transpose_shape(Shape, Axes), DType]: ...
1184
+ # TODO(stroxler): Reinterpretation can change the final dimension's size.
1185
+ @overload
1186
+ def view(self, /) -> ndarray[Shape, DType]: ...
1187
+ @overload
1188
+ def view[ArrayT: ndarray](self, /, *, type: type[ArrayT]) -> ArrayT: ...
1189
+ @overload
1190
+ def view[ScalarT: generic](
1191
+ self, dtype: type[ScalarT] | _dtype[ScalarT], /
1192
+ ) -> ndarray[IntTuple, _dtype[ScalarT]]: ...
1193
+ @overload
1194
+ def view(self, dtype: str, /) -> ndarray[IntTuple]: ...
893
1195
 
894
1196
  class ufunc:
895
1197
  __name__: str
@@ -910,8 +1212,8 @@ class ufunc:
910
1212
  def at(self, a: ndarray, indices: Any, b: Any = None, /) -> None: ...
911
1213
 
912
1214
  permute_dims = transpose
913
- # TODO(stroxler): Make this precise when `concatenate` accepts overlay ndarrays.
914
- concat: Any = concatenate
1215
+ # TODO(stroxler): Model concatenation of overlay ndarrays with a shape rule.
1216
+ concat = concatenate
915
1217
 
916
1218
  @overload
917
1219
  def stack[Shapes: IntTuples, Axis: Flag[int]](
@@ -1208,9 +1510,9 @@ def array[Shape: _Shape, DType](
1208
1510
  object: ndarray[Shape, DType],
1209
1511
  dtype: None = None,
1210
1512
  *,
1211
- copy: bool | None = ...,
1513
+ copy: py_bool | None = ...,
1212
1514
  order: str | None = None,
1213
- subok: bool = ...,
1515
+ subok: py_bool = ...,
1214
1516
  ndmin: Literal[0] = 0,
1215
1517
  like: None = None,
1216
1518
  ) -> ndarray[Shape, DType]: ...
@@ -1219,9 +1521,9 @@ def array[Shape: _Shape](
1219
1521
  object: ndarray[Shape, Any],
1220
1522
  dtype: Any,
1221
1523
  *,
1222
- copy: bool | None = ...,
1524
+ copy: py_bool | None = ...,
1223
1525
  order: str | None = None,
1224
- subok: bool = ...,
1526
+ subok: py_bool = ...,
1225
1527
  ndmin: Literal[0] = 0,
1226
1528
  like: None = None,
1227
1529
  ) -> ndarray[Shape]: ...
@@ -1230,9 +1532,9 @@ def array[Shape: _Shape = []](
1230
1532
  object: _ArrayScalar | RegularNestedList[Shape, _ArrayScalar],
1231
1533
  dtype: Any = ...,
1232
1534
  *,
1233
- copy: bool | None = ...,
1535
+ copy: py_bool | None = ...,
1234
1536
  order: str | None = None,
1235
- subok: bool = ...,
1537
+ subok: py_bool = ...,
1236
1538
  ndmin: Literal[0] = 0,
1237
1539
  like: None = None,
1238
1540
  ) -> ndarray[Shape]: ...
@@ -1241,9 +1543,9 @@ def array(
1241
1543
  object: Any,
1242
1544
  dtype: Any = ...,
1243
1545
  *,
1244
- copy: bool | None = ...,
1546
+ copy: py_bool | None = ...,
1245
1547
  order: str | None = None,
1246
- subok: bool = ...,
1548
+ subok: py_bool = ...,
1247
1549
  ndmin: int = ...,
1248
1550
  like: None = None,
1249
1551
  ) -> ndarray[IntTuple]: ...
@@ -1252,9 +1554,9 @@ def array(
1252
1554
  object: Any,
1253
1555
  dtype: Any = ...,
1254
1556
  *,
1255
- copy: bool | None = ...,
1557
+ copy: py_bool | None = ...,
1256
1558
  order: str | None = None,
1257
- subok: bool = ...,
1559
+ subok: py_bool = ...,
1258
1560
  ndmin: int = ...,
1259
1561
  like: Any,
1260
1562
  ) -> Any: ...
@@ -1265,7 +1567,7 @@ def asarray[Shape: _Shape, DType](
1265
1567
  order: str | None = None,
1266
1568
  *,
1267
1569
  device: Any = ...,
1268
- copy: bool | None = ...,
1570
+ copy: py_bool | None = ...,
1269
1571
  like: None = None,
1270
1572
  ) -> ndarray[Shape, DType]: ...
1271
1573
  @overload
@@ -1275,7 +1577,7 @@ def asarray[Shape: _Shape](
1275
1577
  order: str | None = None,
1276
1578
  *,
1277
1579
  device: Any = ...,
1278
- copy: bool | None = ...,
1580
+ copy: py_bool | None = ...,
1279
1581
  like: None = None,
1280
1582
  ) -> ndarray[Shape]: ...
1281
1583
  @overload
@@ -1285,7 +1587,7 @@ def asarray[Shape: _Shape = []](
1285
1587
  order: str | None = None,
1286
1588
  *,
1287
1589
  device: Any = ...,
1288
- copy: bool | None = ...,
1590
+ copy: py_bool | None = ...,
1289
1591
  like: None = None,
1290
1592
  ) -> ndarray[Shape]: ...
1291
1593
  @overload
@@ -1295,7 +1597,7 @@ def asarray(
1295
1597
  order: str | None = None,
1296
1598
  *,
1297
1599
  device: Any = ...,
1298
- copy: bool | None = ...,
1600
+ copy: py_bool | None = ...,
1299
1601
  like: None = None,
1300
1602
  ) -> ndarray[IntTuple]: ...
1301
1603
  @overload
@@ -1305,7 +1607,7 @@ def asarray(
1305
1607
  order: str | None = None,
1306
1608
  *,
1307
1609
  device: Any = ...,
1308
- copy: bool | None = ...,
1610
+ copy: py_bool | None = ...,
1309
1611
  like: Any,
1310
1612
  ) -> Any: ...
1311
1613
  def round[Shape: _Shape](x: ndarray[Shape]) -> ndarray[Shape]: ...
@@ -1321,20 +1623,19 @@ def fill_diagonal[N: IntVar, DType](
1321
1623
  wrap: py_bool = False,
1322
1624
  ) -> None: ...
1323
1625
  @overload
1324
- def diag[N: IntVar, DType, K: Flag[int] = 0](
1626
+ def diag[N: IntVar, DType, K: Int = 0](
1325
1627
  v: ndarray[[N], DType], k: K = 0
1326
1628
  ) -> ndarray[[diag_extent(Int[N], K), diag_extent(Int[N], K)], DType]: ...
1327
-
1328
- # TODO(stroxler): Model the shape arithmetic here; we can do better than `int`.
1329
1629
  @overload
1330
- def diag[M: IntVar, N: IntVar, DType](
1331
- v: ndarray[[M, N], DType], k: int = 0
1332
- ) -> ndarray[[int], DType]: ...
1630
+ def diag[M: IntVar, N: IntVar, DType, K: Flag[int] = 0](
1631
+ v: ndarray[[M, N], DType], k: K = 0
1632
+ ) -> ndarray[diag_matrix_shape(Int[M], Int[N], K), DType]: ...
1333
1633
 
1334
1634
  # Trailing fallback for ranks the precise overloads do not model, so their dtype survives
1335
1635
  # instead of degrading to `Any`. The parameter shape is a type variable rather than
1336
1636
  # `IntTuple`: a gradual parameter shape would also match known-rank arguments whose dtype is
1337
1637
  # gradual, and that ambiguity collapses their precise result to a gradual shape.
1638
+ # TODO(stroxler): Reject known-invalid ranks without losing unknown-rank dtype information.
1338
1639
  @overload
1339
1640
  def diag[S: _Shape, DType](
1340
1641
  v: ndarray[S, DType], k: int = 0
@@ -1572,51 +1873,34 @@ def identity[N: IntVar](
1572
1873
  n: Int[N], dtype: Any, *, like: Any = ...
1573
1874
  ) -> ndarray[[N, N]]: ...
1574
1875
 
1575
- # TODO(stroxler): Replace the remaining placeholders with NumPy's scalar hierarchy.
1576
- class number(generic): ...
1577
- class inexact(number): ...
1578
- class floating(inexact): ...
1579
- class integer(number): ...
1876
+ bool = bool_
1877
+
1878
+ class broadcast:
1879
+ def __new__(cls, *args: ArrayLike) -> broadcast: ...
1880
+ def __init__(self, *args: ArrayLike) -> None: ...
1881
+ index: int
1882
+ iters: tuple[flatiter[Any], ...]
1883
+ nd: int
1884
+ ndim: int
1885
+ numiter: int
1886
+ shape: tuple[int, ...]
1887
+ size: int
1888
+ def __iter__(self) -> broadcast: ...
1889
+ def __next__(self) -> tuple[Any, ...]: ...
1890
+ def reset(self) -> None: ...
1580
1891
 
1581
- bool: Any
1582
- broadcast: Any
1583
- byte: Any
1584
- bytes_: Any
1585
- cdouble: Any
1586
- character: Any
1587
- clongdouble: Any
1588
- complex128: Any
1589
- complex64: Any
1590
- complexfloating: Any
1591
- csingle: Any
1592
- datetime64: Any
1593
- double: Any
1594
- flexible: Any
1595
- float16: Any
1596
- half: Any
1597
- int16: Any
1598
- int8: Any
1599
- int_: Any
1600
- intc: Any
1601
- long: Any
1602
- longdouble: Any
1603
- longlong: Any
1604
- object_: Any
1605
- short: Any
1606
- signedinteger: Any
1607
- single: Any
1608
- str_: Any
1609
- timedelta64: Any
1610
- ubyte: Any
1611
- uint: Any
1612
- uint16: Any
1613
- uint32: Any
1614
- uint64: Any
1615
- uint8: Any
1616
- uintc: Any
1617
- uintp: Any
1618
- ulong: Any
1619
- ulonglong: Any
1620
- unsignedinteger: Any
1621
- ushort: Any
1622
- void: Any
1892
+ byte = int8
1893
+ cdouble = complex128
1894
+ csingle = complex64
1895
+ double = float64
1896
+ half = float16
1897
+ int_ = intp
1898
+ intc = int32
1899
+ long = int64
1900
+ short = int16
1901
+ single = float32
1902
+ ubyte = uint8
1903
+ uint = uintp
1904
+ uintc = uint32
1905
+ ulong = uint64
1906
+ ushort = uint16
@@ -0,0 +1,442 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import shape_extensions.dsl as dsl
7
+ from shape_extensions import (
8
+ gufunc_broadcast,
9
+ Int,
10
+ IntTuple,
11
+ IntTuples,
12
+ type_shape_dsl_function,
13
+ )
14
+
15
+ @type_shape_dsl_function
16
+ def int_min(a: Int, b: Int) -> Int:
17
+ if a == b:
18
+ return a
19
+ if dsl.is_concrete_int(a) and dsl.is_concrete_int(b):
20
+ if a < b:
21
+ return a
22
+ return b
23
+ return dsl.Int.gradual()
24
+
25
+ @type_shape_dsl_function
26
+ def diag_extent(n: Int, k: Int) -> Int:
27
+ return n + abs(k)
28
+
29
+ @type_shape_dsl_function
30
+ def repeat_shape(shape: IntTuple, repeats: Int, axis: int | None) -> IntTuple:
31
+ if dsl.is_concrete_int(repeats) and repeats < 0:
32
+ return dsl.Invalid("repeats may not contain negative values")
33
+ if axis is None:
34
+ return dsl.IntTuple((dsl.prod(shape) * repeats,))
35
+ if dsl.is_int_value(axis):
36
+ if len(shape) == 0:
37
+ if axis == 0 or axis == -1:
38
+ return dsl.IntTuple((repeats,))
39
+ return dsl.Invalid("axis is out of bounds")
40
+ rank = len(shape)
41
+ if axis < 0 - rank or axis >= rank:
42
+ return dsl.Invalid("axis is out of bounds")
43
+ if axis < 0:
44
+ normalized_axis = axis + rank
45
+ else:
46
+ normalized_axis = axis + 0
47
+ return dsl.IntTuple(
48
+ (
49
+ shape[index] * repeats if index == normalized_axis else shape[index]
50
+ for index in range(rank)
51
+ )
52
+ )
53
+ return dsl.Invalid("axis must be an integer or None")
54
+
55
+ @type_shape_dsl_function
56
+ def repeat_sequence_shape(
57
+ shape: IntTuple, repeats: IntTuple, axis: int | None
58
+ ) -> IntTuple:
59
+ if axis is None:
60
+ source = dsl.IntTuple((dsl.prod(shape),))
61
+ normalized_axis = 0
62
+ elif dsl.is_int_value(axis):
63
+ if len(shape) == 0:
64
+ if axis != 0 and axis != -1:
65
+ return dsl.Invalid("axis is out of bounds")
66
+ source = dsl.IntTuple((1,))
67
+ else:
68
+ source = shape
69
+ rank = len(source)
70
+ if axis < 0 - rank or axis >= rank:
71
+ return dsl.Invalid("axis is out of bounds")
72
+ if axis < 0:
73
+ normalized_axis = axis + rank
74
+ else:
75
+ normalized_axis = axis + 0
76
+ else:
77
+ return dsl.Invalid("axis must be an integer or None")
78
+ extent = source[normalized_axis]
79
+ if any(dsl.is_concrete_int(value) and value < 0 for value in repeats):
80
+ return dsl.Invalid("repeats may not contain negative values")
81
+ if len(repeats) == 1:
82
+ repeated = extent * repeats[0]
83
+ else:
84
+ if dsl.is_concrete_int(extent) and len(repeats) != extent:
85
+ return dsl.Invalid("repeats must match the selected axis")
86
+ repeated = dsl.sum(repeats)
87
+ return dsl.IntTuple(
88
+ (
89
+ repeated if index == normalized_axis else source[index]
90
+ for index in range(len(source))
91
+ )
92
+ )
93
+
94
+ @type_shape_dsl_function
95
+ def take_shape(shape: IntTuple, indices: IntTuple, axis: int | None) -> IntTuple:
96
+ if axis is None:
97
+ return indices
98
+ if dsl.is_int_value(axis):
99
+ rank = len(shape)
100
+ if axis < 0 - rank or axis >= rank:
101
+ return dsl.Invalid("axis out of bounds")
102
+ if axis < 0:
103
+ normalized_axis = axis + rank
104
+ else:
105
+ normalized_axis = axis + 0
106
+ return dsl.concat(
107
+ dsl.concat(shape[:normalized_axis], indices),
108
+ shape[normalized_axis + 1 :],
109
+ )
110
+ return dsl.Invalid("axis must be an integer or None")
111
+
112
+ @type_shape_dsl_function
113
+ def compress_shape(shape: IntTuple, axis: int | None) -> IntTuple:
114
+ indices = dsl.IntTuple((dsl.Int.gradual(),))
115
+ if axis is None:
116
+ return indices
117
+ if dsl.is_int_value(axis):
118
+ if len(shape) == 0 and (axis == 0 or axis == -1):
119
+ return indices
120
+ return take_shape(shape, indices, axis)
121
+
122
+ @type_shape_dsl_function
123
+ def diagonal_shape(
124
+ shape: IntTuple, axis1: int, axis2: int, keep_diagonal: bool, offset: int
125
+ ) -> IntTuple:
126
+ if len(shape) < 2:
127
+ return dsl.Invalid("diagonal requires at least two dimensions")
128
+ if (
129
+ axis1 < 0 - len(shape)
130
+ or axis1 >= len(shape)
131
+ or axis2 < 0 - len(shape)
132
+ or axis2 >= len(shape)
133
+ ):
134
+ return dsl.Invalid("diagonal axis out of bounds")
135
+ if axis1 < 0:
136
+ first = axis1 + len(shape)
137
+ else:
138
+ first = axis1 + 0
139
+ if axis2 < 0:
140
+ second = axis2 + len(shape)
141
+ else:
142
+ second = axis2 + 0
143
+ if first == second:
144
+ return dsl.Invalid("diagonal axes must be distinct")
145
+ outer = dsl.IntTuple(
146
+ (
147
+ shape[index]
148
+ for index in range(len(shape))
149
+ if index != first and index != second
150
+ )
151
+ )
152
+ if not keep_diagonal:
153
+ return outer
154
+
155
+ first_extent = shape[first]
156
+ second_extent = shape[second]
157
+ zero_tuple = dsl.IntTuple((0,))
158
+ zero = zero_tuple[0]
159
+ offset_tuple = dsl.IntTuple((offset + 0,))
160
+ offset_extent = offset_tuple[0]
161
+ if offset == 0:
162
+ if first_extent == second_extent:
163
+ return dsl.concat(outer, dsl.IntTuple((first_extent,)))
164
+ if dsl.is_concrete_int(first_extent) and dsl.is_concrete_int(second_extent):
165
+ if first_extent < second_extent:
166
+ return dsl.concat(outer, dsl.IntTuple((first_extent,)))
167
+ return dsl.concat(outer, dsl.IntTuple((second_extent,)))
168
+ return dsl.concat(outer, dsl.IntTuple((dsl.Int.gradual(),)))
169
+ if offset > 0:
170
+ limit = second_extent - offset_extent
171
+ if first_extent == limit:
172
+ return dsl.concat(outer, dsl.IntTuple((first_extent,)))
173
+ if dsl.is_concrete_int(first_extent) and dsl.is_concrete_int(limit):
174
+ if limit < zero:
175
+ return dsl.concat(outer, dsl.IntTuple((zero,)))
176
+ if first_extent < limit:
177
+ return dsl.concat(outer, dsl.IntTuple((first_extent,)))
178
+ return dsl.concat(outer, dsl.IntTuple((limit,)))
179
+ return dsl.concat(outer, dsl.IntTuple((dsl.Int.gradual(),)))
180
+ limit = first_extent + offset_extent
181
+ if limit == second_extent:
182
+ return dsl.concat(outer, dsl.IntTuple((second_extent,)))
183
+ if dsl.is_concrete_int(limit) and dsl.is_concrete_int(second_extent):
184
+ if limit < zero:
185
+ return dsl.concat(outer, dsl.IntTuple((zero,)))
186
+ if limit < second_extent:
187
+ return dsl.concat(outer, dsl.IntTuple((limit,)))
188
+ return dsl.concat(outer, dsl.IntTuple((second_extent,)))
189
+ return dsl.concat(outer, dsl.IntTuple((dsl.Int.gradual(),)))
190
+
191
+ @type_shape_dsl_function
192
+ def diag_matrix_shape(m: Int, n: Int, k: int) -> IntTuple:
193
+ shape = dsl.IntTuple((m, n))
194
+ axis1 = 0
195
+ axis2 = 1
196
+ keep_diagonal = True
197
+ return diagonal_shape(shape, axis1, axis2, keep_diagonal, k)
198
+
199
+ @type_shape_dsl_function
200
+ def matmul_shape(left: IntTuple, right: IntTuple) -> IntTuple:
201
+ if len(left) == 0 or len(right) == 0:
202
+ return dsl.Invalid("matmul expects at least 1-D arrays")
203
+ operands = dsl.IntTuples((left, right))
204
+ if len(right) == 1:
205
+ spec = "(n),(n)->()"
206
+ return gufunc_broadcast(spec, operands)
207
+ if len(left) == 1:
208
+ spec = "(n),(n,p)->(p)"
209
+ return gufunc_broadcast(spec, operands)
210
+ spec = "(m,n),(n,p)->(m,p)"
211
+ return gufunc_broadcast(spec, operands)
212
+
213
+ @type_shape_dsl_function
214
+ def dot_shape(left: IntTuple, right: IntTuple) -> IntTuple:
215
+ if len(left) == 0:
216
+ return right
217
+ if len(right) == 0:
218
+ return left
219
+ if len(right) == 1:
220
+ if left[-1] != right[0]:
221
+ return dsl.Invalid("dot contraction dimensions must agree")
222
+ return left[:-1]
223
+ if left[-1] != right[-2]:
224
+ return dsl.Invalid("dot contraction dimensions must agree")
225
+ return dsl.concat(dsl.concat(left[:-1], right[:-2]), right[-1:])
226
+
227
+ @type_shape_dsl_function
228
+ def matvec_shape(left: IntTuple, right: IntTuple) -> IntTuple:
229
+ spec = "(m,n),(n)->(m)"
230
+ operands = dsl.IntTuples((left, right))
231
+ return gufunc_broadcast(spec, operands)
232
+
233
+ @type_shape_dsl_function
234
+ def vecdot_shape(left: IntTuple, right: IntTuple) -> IntTuple:
235
+ spec = "(n),(n)->()"
236
+ operands = dsl.IntTuples((left, right))
237
+ return gufunc_broadcast(spec, operands)
238
+
239
+ @type_shape_dsl_function
240
+ def vecmat_shape(left: IntTuple, right: IntTuple) -> IntTuple:
241
+ spec = "(n),(n,m)->(m)"
242
+ operands = dsl.IntTuples((left, right))
243
+ return gufunc_broadcast(spec, operands)
244
+
245
+ @type_shape_dsl_function
246
+ def reduce_shape(
247
+ shape: IntTuple,
248
+ axis: int | tuple[int, ...] | None,
249
+ keepdims: bool,
250
+ ) -> IntTuple:
251
+ return dsl.axis_reduce(shape, axis, keepdims, False, True, False)
252
+
253
+ @type_shape_dsl_function
254
+ def stack_shape(shapes: IntTuples, axis: int) -> IntTuple:
255
+ if len(shapes) == 0:
256
+ return dsl.Invalid("stack expects a non-empty sequence of arrays")
257
+ first = shapes[0]
258
+ output_rank = len(first) + 1
259
+ # Unary minus is not supported by the type-level DSL.
260
+ if axis < 0 - output_rank or axis >= output_rank:
261
+ return dsl.Invalid("stack axis out of range")
262
+ if axis < 0:
263
+ norm_axis = axis + output_rank
264
+ else:
265
+ norm_axis = axis + 0
266
+ rank_mismatches = dsl.IntTuple(
267
+ (0 if len(shape) == len(first) else 1 for shape in shapes)
268
+ )
269
+ if any(mismatch == 1 for mismatch in rank_mismatches):
270
+ return dsl.Invalid("stack expects all arrays to have the same rank")
271
+ # Equal ranks are established above, so indexing every member by an index of
272
+ # `first` is in bounds.
273
+ mismatches = dsl.IntTuple(
274
+ (
275
+ 1 if any(shape[index] != first[index] for index in range(len(first))) else 0
276
+ for shape in shapes
277
+ )
278
+ )
279
+ if any(mismatch == 1 for mismatch in mismatches):
280
+ return dsl.Invalid("stack expects all arrays to have the same shape")
281
+ return dsl.IntTuple(
282
+ (
283
+ len(shapes)
284
+ if index == norm_axis
285
+ else first[index if index < norm_axis else index - 1]
286
+ for index in range(output_rank)
287
+ )
288
+ )
289
+
290
+ @type_shape_dsl_function
291
+ def expand_dims_shape(shape: IntTuple, axis: int) -> IntTuple:
292
+ output_rank = len(shape) + 1
293
+ # Unary minus is not supported by the type-level DSL.
294
+ if axis < 0 - output_rank or axis >= output_rank:
295
+ return dsl.Invalid("expand_dims axis out of bounds")
296
+ if axis < 0:
297
+ norm_axis = axis + output_rank
298
+ else:
299
+ norm_axis = axis + 0
300
+ return dsl.IntTuple(
301
+ (
302
+ 1
303
+ if index == norm_axis
304
+ else shape[index if index < norm_axis else index - 1]
305
+ for index in range(output_rank)
306
+ )
307
+ )
308
+
309
+ @type_shape_dsl_function
310
+ def swapaxes_shape(shape: IntTuple, axis1: int, axis2: int) -> IntTuple:
311
+ rank = len(shape)
312
+ if axis1 < 0 - rank or axis1 >= rank or axis2 < 0 - rank or axis2 >= rank:
313
+ return dsl.Invalid("swapaxes axis out of bounds")
314
+ if axis1 < 0:
315
+ first = axis1 + rank
316
+ else:
317
+ first = axis1 + 0
318
+ if axis2 < 0:
319
+ second = axis2 + rank
320
+ else:
321
+ second = axis2 + 0
322
+ return dsl.IntTuple(
323
+ (
324
+ shape[second]
325
+ if index == first
326
+ else shape[first]
327
+ if index == second
328
+ else shape[index]
329
+ for index in range(rank)
330
+ )
331
+ )
332
+
333
+ @type_shape_dsl_function
334
+ def reverse_shape(shape: IntTuple) -> IntTuple:
335
+ rank = len(shape)
336
+ return dsl.IntTuple((shape[rank - index - 1] for index in range(rank)))
337
+
338
+ @type_shape_dsl_function
339
+ def transpose_shape(shape: IntTuple, axes: IntTuple) -> IntTuple:
340
+ if len(axes) != len(shape):
341
+ return dsl.Invalid("transpose axes must match the array rank")
342
+ if any(axis < 0 - len(shape) or axis >= len(shape) for axis in axes):
343
+ return dsl.Invalid("transpose axis out of bounds")
344
+ normalized = dsl.IntTuple(
345
+ (axis + len(shape) if axis < 0 else axis for axis in axes)
346
+ )
347
+ duplicates = dsl.IntTuple(
348
+ (
349
+ 1
350
+ if any(normalized[index] == normalized[other] for other in range(index))
351
+ else 0
352
+ for index in range(len(shape))
353
+ )
354
+ )
355
+ if any(duplicate == 1 for duplicate in duplicates):
356
+ return dsl.Invalid("transpose axes must be unique")
357
+ return dsl.IntTuple((shape[axis] for axis in normalized))
358
+
359
+ @type_shape_dsl_function
360
+ def nonzero_shapes(shape: IntTuple) -> IntTuples:
361
+ if len(shape) == 0:
362
+ return dsl.Invalid("nonzero requires at least one dimension")
363
+ return dsl.IntTuples(
364
+ (dsl.IntTuple((dsl.Int.gradual(),)) for _ in range(len(shape)))
365
+ )
366
+
367
+ @type_shape_dsl_function
368
+ def squeeze_shape(shape: IntTuple, axis: int | tuple[int, ...] | None) -> IntTuple:
369
+ if axis is None:
370
+ return dsl.IntTuple((extent for extent in shape if extent != 1))
371
+ if dsl.is_int_value(axis):
372
+ if axis == -2:
373
+ tail = shape[-2:]
374
+ if len(tail) < 2:
375
+ return dsl.Invalid("squeeze axis out of bounds")
376
+ extent = shape[-2]
377
+ if extent == 1:
378
+ return dsl.concat(shape[:-2], shape[-1:])
379
+ if dsl.is_concrete_int(extent):
380
+ return dsl.Invalid("squeeze axis must have length 1")
381
+ if axis == 0 or axis == -1:
382
+ if len(shape) == 0:
383
+ return shape
384
+ axes = (axis,)
385
+ else:
386
+ axes = axis
387
+ if any(item < 0 - len(shape) or item >= len(shape) for item in axes):
388
+ return dsl.Invalid("squeeze axis out of bounds")
389
+ normalized = tuple(item + len(shape) if item < 0 else item for item in axes)
390
+ if any(normalized.count(item) > 1 for item in normalized):
391
+ return dsl.Invalid("squeeze axes must be unique")
392
+ if any(shape[item] != 1 for item in normalized):
393
+ return dsl.Invalid("squeeze axis must have length 1")
394
+ return dsl.IntTuple(
395
+ (shape[index] for index in range(len(shape)) if index not in normalized)
396
+ )
397
+
398
+ @type_shape_dsl_function
399
+ def reshape_shape(shape: IntTuple, target: IntTuple) -> IntTuple:
400
+ inferred = tuple(
401
+ (
402
+ 1
403
+ for dimension in target
404
+ if dsl.is_concrete_int(dimension) and dimension == -1
405
+ )
406
+ )
407
+ if len(inferred) > 1:
408
+ return dsl.Invalid("reshape allows only one inferred dimension")
409
+ if any(dsl.is_concrete_int(dimension) and dimension < -1 for dimension in target):
410
+ return dsl.Invalid("reshape dimensions must be at least -1")
411
+ known_shape = dsl.IntTuple(
412
+ (
413
+ dimension
414
+ for dimension in target
415
+ if not (dsl.is_concrete_int(dimension) and dimension == -1)
416
+ )
417
+ )
418
+ known = dsl.prod(known_shape)
419
+ total = dsl.prod(shape)
420
+ if len(inferred) == 0:
421
+ if dsl.is_concrete_int(total) and dsl.is_concrete_int(known) and total != known:
422
+ return dsl.Invalid("reshape target element count does not match the input")
423
+ return target
424
+ if dsl.is_concrete_int(known):
425
+ if known == 0:
426
+ return dsl.Invalid("reshape cannot infer a dimension from zero elements")
427
+ if dsl.is_concrete_int(total) and total % known != 0:
428
+ return dsl.Invalid("reshape cannot infer an integral dimension")
429
+ return dsl.IntTuple(
430
+ (
431
+ total // known
432
+ if dsl.is_concrete_int(dimension) and dimension == -1
433
+ else dimension
434
+ for dimension in target
435
+ )
436
+ )
437
+
438
+ @type_shape_dsl_function
439
+ def reshape_varargs_shape(shape: IntTuple, target: IntTuple) -> IntTuple:
440
+ if len(target) == 0:
441
+ return dsl.Invalid("reshape expects at least one dimension")
442
+ return reshape_shape(shape, target)
@@ -3,9 +3,10 @@
3
3
  # This source code is licensed under the MIT license found in the
4
4
  # LICENSE file in the root directory of this source tree.
5
5
 
6
+ from collections.abc import Sequence
6
7
  from typing import Any, Literal, overload
7
8
 
8
- from numpy._shapes import int_min
9
+ from numpy._shapes import int_min, reduce_shape
9
10
 
10
11
  # Preserve NumPy's canonical re-exports before local shape-aware declarations.
11
12
  from numpy.linalg._linalg import (
@@ -37,7 +38,7 @@ from numpy.linalg._linalg import (
37
38
  vecdot as vecdot,
38
39
  vector_norm as vector_norm,
39
40
  )
40
- from shape_extensions import Int, IntVar
41
+ from shape_extensions import Flag, Int, IntTuple, IntVar
41
42
 
42
43
  from .. import floating, ndarray
43
44
 
@@ -78,13 +79,19 @@ def norm(
78
79
  **kwargs: Any,
79
80
  ) -> floating: ...
80
81
  @overload
82
+ def norm[Shape: IntTuple, Axis: Flag[int | tuple[int, ...] | None], Keep: Flag[bool]](
83
+ x: ndarray[Shape],
84
+ ord: int | float | Literal["fro", "nuc"] | None = None,
85
+ axis: Axis = None,
86
+ keepdims: Keep = False,
87
+ ) -> ndarray[reduce_shape(Shape, Axis, Keep)]: ...
88
+ @overload
81
89
  def norm(
82
- x: Any,
83
- ord: Any = None,
84
- axis: Any = None,
85
- keepdims: bool = False,
86
- **kwargs: Any,
87
- ) -> Any: ...
90
+ x: Sequence[int | float | complex],
91
+ ord: int | float | None = None,
92
+ axis: None = None,
93
+ keepdims: Literal[False] = False,
94
+ ) -> floating: ...
88
95
  def eigh[N: IntVar, DType](
89
96
  a: ndarray[[N, N], DType],
90
97
  ) -> tuple[ndarray[[N], DType], ndarray[[N, N], DType]]: ...
@@ -8,7 +8,7 @@ description = "NumPy type stubs with array-shape tracking, maintained by Pyrefly
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.12"
10
10
  license = { file = "LICENSE" }
11
- version = "1.4.0.dev3"
11
+ version = "1.4.0.dev4"
12
12
  keywords = ["typechecker", "typechecking", "stubs", "numpy"]
13
13
  classifiers = [
14
14
  "Development Status :: 4 - Beta",
@@ -18,7 +18,8 @@ classifiers = [
18
18
  "Typing :: Stubs Only",
19
19
  ]
20
20
  dependencies = [
21
- "pyrefly-shape-extensions==1.4.0.dev3",
21
+ "pyrefly-shape-extensions==1.4.0.dev4",
22
+ "numpy",
22
23
  ]
23
24
 
24
25
  [project.urls]
@@ -1,144 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- #
3
- # This source code is licensed under the MIT license found in the
4
- # LICENSE file in the root directory of this source tree.
5
-
6
- import shape_extensions.dsl as dsl
7
- from shape_extensions import (
8
- gufunc_broadcast,
9
- Int,
10
- IntTuple,
11
- IntTuples,
12
- type_shape_dsl_function,
13
- )
14
-
15
- @type_shape_dsl_function
16
- def int_min(a: Int, b: Int) -> Int:
17
- if a == b:
18
- return a
19
- if dsl.is_concrete_int(a) and dsl.is_concrete_int(b):
20
- if a < b:
21
- return a
22
- return b
23
- return dsl.Int.gradual()
24
-
25
- @type_shape_dsl_function
26
- def diag_extent(n: Int, k: int) -> Int:
27
- # Non-literal Flag arguments become gradual before the DSL body is evaluated.
28
- if k < 0:
29
- return n - k
30
- return n + k
31
-
32
- @type_shape_dsl_function
33
- def matmul_shape(left: IntTuple, right: IntTuple) -> IntTuple:
34
- if len(left) == 0 or len(right) == 0:
35
- return dsl.Invalid("matmul expects at least 1-D arrays")
36
- operands = dsl.IntTuples((left, right))
37
- if len(right) == 1:
38
- spec = "(n),(n)->()"
39
- return gufunc_broadcast(spec, operands)
40
- if len(left) == 1:
41
- spec = "(n),(n,p)->(p)"
42
- return gufunc_broadcast(spec, operands)
43
- spec = "(m,n),(n,p)->(m,p)"
44
- return gufunc_broadcast(spec, operands)
45
-
46
- @type_shape_dsl_function
47
- def matvec_shape(left: IntTuple, right: IntTuple) -> IntTuple:
48
- spec = "(m,n),(n)->(m)"
49
- operands = dsl.IntTuples((left, right))
50
- return gufunc_broadcast(spec, operands)
51
-
52
- @type_shape_dsl_function
53
- def vecdot_shape(left: IntTuple, right: IntTuple) -> IntTuple:
54
- spec = "(n),(n)->()"
55
- operands = dsl.IntTuples((left, right))
56
- return gufunc_broadcast(spec, operands)
57
-
58
- @type_shape_dsl_function
59
- def vecmat_shape(left: IntTuple, right: IntTuple) -> IntTuple:
60
- spec = "(n),(n,m)->(m)"
61
- operands = dsl.IntTuples((left, right))
62
- return gufunc_broadcast(spec, operands)
63
-
64
- @type_shape_dsl_function
65
- def reduce_shape(
66
- shape: IntTuple,
67
- axis: int | tuple[int, ...] | None,
68
- keepdims: bool,
69
- ) -> IntTuple:
70
- if axis is None:
71
- axes = range(len(shape))
72
- elif dsl.is_int_value(axis):
73
- axes = (axis,)
74
- else:
75
- axes = axis
76
- # The DSL does not support unary negation of a Flag integer.
77
- if any(item < 0 - len(shape) or item >= len(shape) for item in axes):
78
- return dsl.Invalid("axis out of bounds")
79
- normalized = tuple(item + len(shape) if item < 0 else item for item in axes)
80
- if any(normalized.count(item) > 1 for item in normalized):
81
- return dsl.Invalid("duplicate axis")
82
- if keepdims:
83
- return dsl.IntTuple(
84
- (1 if index in normalized else shape[index] for index in range(len(shape)))
85
- )
86
- return dsl.IntTuple(
87
- (shape[index] for index in range(len(shape)) if index not in normalized)
88
- )
89
-
90
- @type_shape_dsl_function
91
- def stack_shape(shapes: IntTuples, axis: int) -> IntTuple:
92
- if len(shapes) == 0:
93
- return dsl.Invalid("stack expects a non-empty sequence of arrays")
94
- first = shapes[0]
95
- output_rank = len(first) + 1
96
- # Unary minus is not supported by the type-level DSL.
97
- if axis < 0 - output_rank or axis >= output_rank:
98
- return dsl.Invalid("stack axis out of range")
99
- if axis < 0:
100
- norm_axis = axis + output_rank
101
- else:
102
- norm_axis = axis + 0
103
- rank_mismatches = dsl.IntTuple(
104
- (0 if len(shape) == len(first) else 1 for shape in shapes)
105
- )
106
- if any(mismatch == 1 for mismatch in rank_mismatches):
107
- return dsl.Invalid("stack expects all arrays to have the same rank")
108
- # Equal ranks are established above, so indexing every member by an index of
109
- # `first` is in bounds.
110
- mismatches = dsl.IntTuple(
111
- (
112
- 1 if any(shape[index] != first[index] for index in range(len(first))) else 0
113
- for shape in shapes
114
- )
115
- )
116
- if any(mismatch == 1 for mismatch in mismatches):
117
- return dsl.Invalid("stack expects all arrays to have the same shape")
118
- return dsl.IntTuple(
119
- (
120
- len(shapes)
121
- if index == norm_axis
122
- else first[index if index < norm_axis else index - 1]
123
- for index in range(output_rank)
124
- )
125
- )
126
-
127
- @type_shape_dsl_function
128
- def expand_dims_shape(shape: IntTuple, axis: int) -> IntTuple:
129
- output_rank = len(shape) + 1
130
- # Unary minus is not supported by the type-level DSL.
131
- if axis < 0 - output_rank or axis >= output_rank:
132
- return dsl.Invalid("expand_dims axis out of bounds")
133
- if axis < 0:
134
- norm_axis = axis + output_rank
135
- else:
136
- norm_axis = axis + 0
137
- return dsl.IntTuple(
138
- (
139
- 1
140
- if index == norm_axis
141
- else shape[index if index < norm_axis else index - 1]
142
- for index in range(output_rank)
143
- )
144
- )