pyrefly-numpy-stubs 1.4.0.dev3__tar.gz → 1.4.1__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.1
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.1
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,16 +183,30 @@ 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
  )
194
- from numpy._typing import ArrayLike
209
+ from numpy._typing import _ArrayLikeInt_co, ArrayLike
195
210
  from numpy._typing._extended_precision import (
196
211
  complex256 as complex256,
197
212
  float128 as float128,
@@ -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,23 +433,60 @@ 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
430
480
  | _IndexScalar
431
481
  | _IndexSequence
482
+ | _ArrayLikeInt_co
432
483
  | ndarray
433
- | tuple[_BasicIndex | _IndexScalar | _IndexSequence | ndarray, ...]
484
+ | tuple[
485
+ _BasicIndex | _IndexScalar | _IndexSequence | _ArrayLikeInt_co | ndarray,
486
+ ...,
487
+ ]
434
488
  )
435
- type _ArrayScalar = None | bool | int | float | complex | str | bytes | generic
489
+ type _ArrayScalar = None | py_bool | int | float | complex | str | bytes | generic
436
490
 
437
491
  __version__: Final[str]
438
492
  e: Final[float]
@@ -578,6 +632,7 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
578
632
  ) -> ndarray[_broadcast_shape(Shape, OtherShape), DType]: ...
579
633
  def __neg__(self) -> ndarray[Shape, DType]: ...
580
634
  def __pos__(self) -> ndarray[Shape, DType]: ...
635
+ def __abs__(self, /) -> ndarray[Shape]: ...
581
636
  def __pow__[OtherShape: _Shape = []](
582
637
  self, other: ndarray[[*OtherShape]] | int | float
583
638
  ) -> ndarray[_broadcast_shape(Shape, OtherShape), DType]: ...
@@ -847,8 +902,13 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
847
902
  ) -> None: ...
848
903
  def put(self, indices: Any, values: Any, mode: str = "raise") -> None: ...
849
904
  def ravel(self, order: str = "C") -> ndarray[[int], DType]: ...
850
- # TODO(stroxler): Model receiver invalidation for shape-changing mutation.
851
- resize: Any
905
+ def resize(self, *, not_usable_with_shape_types: Never) -> None:
906
+ """Unsupported: resizing changes the receiver's shape in place.
907
+
908
+ A statically typed array cannot acquire a new shape type after a method call.
909
+ Create a new array instead of resizing an existing one.
910
+ """
911
+ ...
852
912
  def round(self, decimals: int = 0, out: Any = None) -> ndarray[Shape, DType]: ...
853
913
  def setfield(self, val: Any, dtype: Any, offset: int = 0) -> None: ...
854
914
  def setflags(
@@ -872,24 +932,270 @@ class ndarray[Shape: _Shape = _Shape, DType = Any]:
872
932
  def tofile(self, fid: Any, sep: str = "", format: str = "%s") -> None: ...
873
933
  def tolist(self) -> Any: ...
874
934
 
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
935
+ # TODO(stroxler): Model broadcast choices and condition-dependent compress lengths.
936
+ @overload
937
+ def choose(
938
+ self,
939
+ choices: ArrayLike,
940
+ out: None = None,
941
+ mode: Literal["raise", "wrap", "clip"] = "raise",
942
+ ) -> ndarray[IntTuple]: ...
943
+ @overload
944
+ def choose[Out: ndarray](
945
+ self,
946
+ choices: ArrayLike,
947
+ out: Out,
948
+ mode: Literal["raise", "wrap", "clip"] = "raise",
949
+ ) -> Out: ...
950
+ @overload
951
+ def compress[Axis: Flag[int | None]](
952
+ self, condition: Sequence[int] | ndarray, axis: Axis = None, out: None = None
953
+ ) -> ndarray[compress_shape(Shape, Axis), DType]: ...
954
+ @overload
955
+ def compress[Out: ndarray](
956
+ self,
957
+ condition: Sequence[int] | ndarray,
958
+ axis: int | None,
959
+ out: Out,
960
+ ) -> Out: ...
961
+ @overload
962
+ def compress[Out: ndarray](
963
+ self,
964
+ condition: Sequence[int] | ndarray,
965
+ axis: int | None = None,
966
+ *,
967
+ out: Out,
968
+ ) -> Out: ...
969
+ @property
970
+ def ctypes(self) -> _ctypes[int]: ...
971
+ def diagonal[Offset: Flag[int], First: Flag[int], Second: Flag[int]](
972
+ self, offset: Offset = 0, axis1: First = 0, axis2: Second = 1
973
+ ) -> ndarray[diagonal_shape(Shape, First, Second, True, Offset), DType]: ...
974
+ @overload
975
+ def dot[N: IntVar](
976
+ self: ndarray[[N], DType], b: ndarray[[N]], /, out: None = None
977
+ ) -> generic: ...
978
+ @overload
979
+ def dot(self: ndarray[[]], b: _ArrayScalar, /, out: None = None) -> generic: ...
980
+ @overload
981
+ def dot[Right: IntTuple](
982
+ self, b: ndarray[Right], /, out: None = None
983
+ ) -> ndarray[dot_shape(Shape, Right)]: ...
984
+ @overload
985
+ def dot[Right: IntTuple](
986
+ self,
987
+ b: RegularNestedList[Right, _ArrayScalar],
988
+ /,
989
+ out: None = None,
990
+ ) -> ndarray[dot_shape(Shape, Right)]: ...
991
+ @overload
992
+ def dot(
993
+ self, b: int | float | complex | generic, /, out: None = None
994
+ ) -> ndarray[Shape]: ...
995
+ @overload
996
+ def dot[Out: ndarray](self, b: ArrayLike, /, out: Out) -> Out: ...
997
+ # TODO(stroxler): Infer scalar dtype promotion for vector inner products.
998
+ @property
999
+ def flat(self) -> flatiter[ndarray[Shape, DType]]: ...
1000
+ @property
1001
+ def mT(self) -> ndarray[swapaxes_shape(Shape, -1, -2), DType]: ...
1002
+ def nonzero(
1003
+ self,
1004
+ ) -> MapIntTuples[lambda S: ndarray[S, dtype[intp]], nonzero_shapes(Shape)]: ...
1005
+ @overload
1006
+ def repeat[Repeats: Int, Axis: Flag[int | None]](
1007
+ self, repeats: Repeats, /, axis: Axis = None
1008
+ ) -> ndarray[repeat_shape(Shape, Repeats, Axis), DType]: ...
1009
+ @overload
1010
+ def repeat[Repeats: IntTuple, Axis: Flag[int | None]](
1011
+ self, repeats: Repeats | IntListLiteral[Repeats], /, axis: Axis = None
1012
+ ) -> ndarray[repeat_sequence_shape(Shape, Repeats, Axis), DType]: ...
1013
+ @overload
1014
+ def repeat[Axis: Flag[int | None]](
1015
+ self, repeats: Sequence[int] | ndarray, /, axis: Axis = None
1016
+ ) -> ndarray[repeat_shape(Shape, Int, Axis), DType]: ...
1017
+ @overload
1018
+ def reshape(
1019
+ self,
1020
+ shape: None,
1021
+ /,
1022
+ *,
1023
+ order: Literal["C", "F", "A"] = "C",
1024
+ copy: py_bool | None = None,
1025
+ ) -> ndarray[Shape, DType]: ...
1026
+ @overload
1027
+ def reshape[Target: IntTuple](
1028
+ self,
1029
+ shape: IntTupleOrList[Target],
1030
+ /,
1031
+ *,
1032
+ order: Literal["C", "F", "A"] = "C",
1033
+ copy: py_bool | None = None,
1034
+ ) -> ndarray[reshape_shape(Shape, Target), DType]: ...
1035
+ @overload
1036
+ def reshape[Target: IntTuple](
1037
+ self,
1038
+ /,
1039
+ *shape: *Target,
1040
+ order: Literal["C", "F", "A"] = "C",
1041
+ copy: py_bool | None = None,
1042
+ ) -> ndarray[reshape_varargs_shape(Shape, Target), DType]: ...
1043
+ @overload
1044
+ def searchsorted[N: IntVar](
1045
+ self: ndarray[[N]],
1046
+ v: _ArrayScalar | ndarray[[]],
1047
+ /,
1048
+ side: Literal["left", "right"] = "left",
1049
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1050
+ ) -> intp: ...
1051
+ @overload
1052
+ def searchsorted[N: IntVar, Values: _Shape](
1053
+ self: ndarray[[N]],
1054
+ v: ndarray[Values],
1055
+ /,
1056
+ side: Literal["left", "right"] = "left",
1057
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1058
+ ) -> ndarray[Values, _dtype[intp]]: ...
1059
+ @overload
1060
+ def searchsorted[N: IntVar, Values: _Shape](
1061
+ self: ndarray[[N]],
1062
+ v: RegularNestedList[Values, _ArrayScalar],
1063
+ /,
1064
+ side: Literal["left", "right"] = "left",
1065
+ sorter: ndarray[[N], _dtype[intp]] | Sequence[int] | None = None,
1066
+ ) -> ndarray[Values, _dtype[intp]]: ...
1067
+ def squeeze[Axis: Flag[_Axis]](
1068
+ self, axis: Axis = None
1069
+ ) -> ndarray[squeeze_shape(Shape, Axis), DType]: ...
1070
+ def swapaxes[First: Flag[int], Second: Flag[int]](
1071
+ self, axis1: First, axis2: Second, /
1072
+ ) -> ndarray[swapaxes_shape(Shape, First, Second), DType]: ...
1073
+ @overload
1074
+ def take(
1075
+ self,
1076
+ indices: int | int32 | int64 | intp,
1077
+ /,
1078
+ axis: None = None,
1079
+ out: None = None,
1080
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1081
+ ) -> generic: ...
1082
+ @overload
1083
+ def take[Axis: Flag[int]](
1084
+ self,
1085
+ indices: int | int32 | int64 | intp,
1086
+ /,
1087
+ axis: Axis,
1088
+ out: None = None,
1089
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1090
+ ) -> ndarray[take_shape(Shape, IntTuple[()], Axis), DType]: ...
1091
+ @overload
1092
+ def take[Indices: IntTuple](
1093
+ self,
1094
+ indices: ndarray[Indices],
1095
+ /,
1096
+ axis: None = None,
1097
+ out: None = None,
1098
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1099
+ ) -> ndarray[Indices, DType]: ...
1100
+ @overload
1101
+ def take(
1102
+ self,
1103
+ indices: Sequence[int],
1104
+ /,
1105
+ axis: None = None,
1106
+ out: None = None,
1107
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1108
+ ) -> ndarray[[int], DType]: ...
1109
+ @overload
1110
+ def take[Axis: Flag[int]](
1111
+ self,
1112
+ indices: Sequence[int],
1113
+ /,
1114
+ axis: Axis,
1115
+ out: None = None,
1116
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1117
+ ) -> ndarray[take_shape(Shape, IntTuple[int], Axis), DType]: ...
1118
+ @overload
1119
+ def take[Indices: IntTuple, Axis: Flag[int]](
1120
+ self,
1121
+ indices: ndarray[Indices],
1122
+ /,
1123
+ axis: Axis,
1124
+ out: None = None,
1125
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1126
+ ) -> ndarray[take_shape(Shape, Indices, Axis), DType]: ...
1127
+ @overload
1128
+ def take[Out: ndarray](
1129
+ self,
1130
+ indices: int | Sequence[int] | ndarray,
1131
+ /,
1132
+ axis: int | None,
1133
+ out: Out,
1134
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1135
+ ) -> Out: ...
1136
+ @overload
1137
+ def take[Out: ndarray](
1138
+ self,
1139
+ indices: int | Sequence[int] | ndarray,
1140
+ /,
1141
+ axis: int | None = None,
1142
+ *,
1143
+ out: Out,
1144
+ mode: Literal["raise", "wrap", "clip"] = "raise",
1145
+ ) -> Out: ...
1146
+ # TODO(stroxler): Restrict index-array dtypes to valid index types.
1147
+ @overload
1148
+ def trace[M: IntVar, N: IntVar](
1149
+ self: ndarray[[M, N], DType],
1150
+ offset: int = 0,
1151
+ axis1: int = 0,
1152
+ axis2: int = 1,
1153
+ dtype: Any = None,
1154
+ out: None = None,
1155
+ ) -> generic: ...
1156
+ @overload
1157
+ def trace[First: Flag[int], Second: Flag[int]](
1158
+ self,
1159
+ offset: int = 0,
1160
+ axis1: First = 0,
1161
+ axis2: Second = 1,
1162
+ dtype: Any = None,
1163
+ out: None = None,
1164
+ ) -> ndarray[diagonal_shape(Shape, First, Second, False, 0)]: ...
1165
+ @overload
1166
+ def trace[Out: ndarray](
1167
+ self,
1168
+ offset: int = 0,
1169
+ axis1: int = 0,
1170
+ axis2: int = 1,
1171
+ dtype: Any = None,
1172
+ *,
1173
+ out: Out,
1174
+ ) -> Out: ...
1175
+ # TODO(stroxler): Validate 2-D axes and infer scalar dtype promotion.
1176
+ @overload
1177
+ def transpose(
1178
+ self, axes: None = None, /
1179
+ ) -> ndarray[reverse_shape(Shape), DType]: ...
1180
+ @overload
1181
+ def transpose[Axes: IntTuple](
1182
+ self, axes: Axes, /
1183
+ ) -> ndarray[transpose_shape(Shape, Axes), DType]: ...
1184
+ @overload
1185
+ def transpose[Axes: IntTuple](
1186
+ self, *axes: *Axes
1187
+ ) -> ndarray[transpose_shape(Shape, Axes), DType]: ...
1188
+ # TODO(stroxler): Reinterpretation can change the final dimension's size.
1189
+ @overload
1190
+ def view(self, /) -> ndarray[Shape, DType]: ...
1191
+ @overload
1192
+ def view[ArrayT: ndarray](self, /, *, type: type[ArrayT]) -> ArrayT: ...
1193
+ @overload
1194
+ def view[ScalarT: generic](
1195
+ self, dtype: type[ScalarT] | _dtype[ScalarT], /
1196
+ ) -> ndarray[IntTuple, _dtype[ScalarT]]: ...
1197
+ @overload
1198
+ def view(self, dtype: str, /) -> ndarray[IntTuple]: ...
893
1199
 
894
1200
  class ufunc:
895
1201
  __name__: str
@@ -910,8 +1216,8 @@ class ufunc:
910
1216
  def at(self, a: ndarray, indices: Any, b: Any = None, /) -> None: ...
911
1217
 
912
1218
  permute_dims = transpose
913
- # TODO(stroxler): Make this precise when `concatenate` accepts overlay ndarrays.
914
- concat: Any = concatenate
1219
+ # TODO(stroxler): Model concatenation of overlay ndarrays with a shape rule.
1220
+ concat = concatenate
915
1221
 
916
1222
  @overload
917
1223
  def stack[Shapes: IntTuples, Axis: Flag[int]](
@@ -1208,9 +1514,9 @@ def array[Shape: _Shape, DType](
1208
1514
  object: ndarray[Shape, DType],
1209
1515
  dtype: None = None,
1210
1516
  *,
1211
- copy: bool | None = ...,
1517
+ copy: py_bool | None = ...,
1212
1518
  order: str | None = None,
1213
- subok: bool = ...,
1519
+ subok: py_bool = ...,
1214
1520
  ndmin: Literal[0] = 0,
1215
1521
  like: None = None,
1216
1522
  ) -> ndarray[Shape, DType]: ...
@@ -1219,9 +1525,9 @@ def array[Shape: _Shape](
1219
1525
  object: ndarray[Shape, Any],
1220
1526
  dtype: Any,
1221
1527
  *,
1222
- copy: bool | None = ...,
1528
+ copy: py_bool | None = ...,
1223
1529
  order: str | None = None,
1224
- subok: bool = ...,
1530
+ subok: py_bool = ...,
1225
1531
  ndmin: Literal[0] = 0,
1226
1532
  like: None = None,
1227
1533
  ) -> ndarray[Shape]: ...
@@ -1230,9 +1536,9 @@ def array[Shape: _Shape = []](
1230
1536
  object: _ArrayScalar | RegularNestedList[Shape, _ArrayScalar],
1231
1537
  dtype: Any = ...,
1232
1538
  *,
1233
- copy: bool | None = ...,
1539
+ copy: py_bool | None = ...,
1234
1540
  order: str | None = None,
1235
- subok: bool = ...,
1541
+ subok: py_bool = ...,
1236
1542
  ndmin: Literal[0] = 0,
1237
1543
  like: None = None,
1238
1544
  ) -> ndarray[Shape]: ...
@@ -1241,9 +1547,9 @@ def array(
1241
1547
  object: Any,
1242
1548
  dtype: Any = ...,
1243
1549
  *,
1244
- copy: bool | None = ...,
1550
+ copy: py_bool | None = ...,
1245
1551
  order: str | None = None,
1246
- subok: bool = ...,
1552
+ subok: py_bool = ...,
1247
1553
  ndmin: int = ...,
1248
1554
  like: None = None,
1249
1555
  ) -> ndarray[IntTuple]: ...
@@ -1252,9 +1558,9 @@ def array(
1252
1558
  object: Any,
1253
1559
  dtype: Any = ...,
1254
1560
  *,
1255
- copy: bool | None = ...,
1561
+ copy: py_bool | None = ...,
1256
1562
  order: str | None = None,
1257
- subok: bool = ...,
1563
+ subok: py_bool = ...,
1258
1564
  ndmin: int = ...,
1259
1565
  like: Any,
1260
1566
  ) -> Any: ...
@@ -1265,7 +1571,7 @@ def asarray[Shape: _Shape, DType](
1265
1571
  order: str | None = None,
1266
1572
  *,
1267
1573
  device: Any = ...,
1268
- copy: bool | None = ...,
1574
+ copy: py_bool | None = ...,
1269
1575
  like: None = None,
1270
1576
  ) -> ndarray[Shape, DType]: ...
1271
1577
  @overload
@@ -1275,7 +1581,7 @@ def asarray[Shape: _Shape](
1275
1581
  order: str | None = None,
1276
1582
  *,
1277
1583
  device: Any = ...,
1278
- copy: bool | None = ...,
1584
+ copy: py_bool | None = ...,
1279
1585
  like: None = None,
1280
1586
  ) -> ndarray[Shape]: ...
1281
1587
  @overload
@@ -1285,7 +1591,7 @@ def asarray[Shape: _Shape = []](
1285
1591
  order: str | None = None,
1286
1592
  *,
1287
1593
  device: Any = ...,
1288
- copy: bool | None = ...,
1594
+ copy: py_bool | None = ...,
1289
1595
  like: None = None,
1290
1596
  ) -> ndarray[Shape]: ...
1291
1597
  @overload
@@ -1295,7 +1601,7 @@ def asarray(
1295
1601
  order: str | None = None,
1296
1602
  *,
1297
1603
  device: Any = ...,
1298
- copy: bool | None = ...,
1604
+ copy: py_bool | None = ...,
1299
1605
  like: None = None,
1300
1606
  ) -> ndarray[IntTuple]: ...
1301
1607
  @overload
@@ -1305,7 +1611,7 @@ def asarray(
1305
1611
  order: str | None = None,
1306
1612
  *,
1307
1613
  device: Any = ...,
1308
- copy: bool | None = ...,
1614
+ copy: py_bool | None = ...,
1309
1615
  like: Any,
1310
1616
  ) -> Any: ...
1311
1617
  def round[Shape: _Shape](x: ndarray[Shape]) -> ndarray[Shape]: ...
@@ -1321,20 +1627,19 @@ def fill_diagonal[N: IntVar, DType](
1321
1627
  wrap: py_bool = False,
1322
1628
  ) -> None: ...
1323
1629
  @overload
1324
- def diag[N: IntVar, DType, K: Flag[int] = 0](
1630
+ def diag[N: IntVar, DType, K: Int = 0](
1325
1631
  v: ndarray[[N], DType], k: K = 0
1326
1632
  ) -> 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
1633
  @overload
1330
- def diag[M: IntVar, N: IntVar, DType](
1331
- v: ndarray[[M, N], DType], k: int = 0
1332
- ) -> ndarray[[int], DType]: ...
1634
+ def diag[M: IntVar, N: IntVar, DType, K: Flag[int] = 0](
1635
+ v: ndarray[[M, N], DType], k: K = 0
1636
+ ) -> ndarray[diag_matrix_shape(Int[M], Int[N], K), DType]: ...
1333
1637
 
1334
1638
  # Trailing fallback for ranks the precise overloads do not model, so their dtype survives
1335
1639
  # instead of degrading to `Any`. The parameter shape is a type variable rather than
1336
1640
  # `IntTuple`: a gradual parameter shape would also match known-rank arguments whose dtype is
1337
1641
  # gradual, and that ambiguity collapses their precise result to a gradual shape.
1642
+ # TODO(stroxler): Reject known-invalid ranks without losing unknown-rank dtype information.
1338
1643
  @overload
1339
1644
  def diag[S: _Shape, DType](
1340
1645
  v: ndarray[S, DType], k: int = 0
@@ -1572,51 +1877,34 @@ def identity[N: IntVar](
1572
1877
  n: Int[N], dtype: Any, *, like: Any = ...
1573
1878
  ) -> ndarray[[N, N]]: ...
1574
1879
 
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): ...
1880
+ bool = bool_
1881
+
1882
+ class broadcast:
1883
+ def __new__(cls, *args: ArrayLike) -> broadcast: ...
1884
+ def __init__(self, *args: ArrayLike) -> None: ...
1885
+ index: int
1886
+ iters: tuple[flatiter[Any], ...]
1887
+ nd: int
1888
+ ndim: int
1889
+ numiter: int
1890
+ shape: tuple[int, ...]
1891
+ size: int
1892
+ def __iter__(self) -> broadcast: ...
1893
+ def __next__(self) -> tuple[Any, ...]: ...
1894
+ def reset(self) -> None: ...
1580
1895
 
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
1896
+ byte = int8
1897
+ cdouble = complex128
1898
+ csingle = complex64
1899
+ double = float64
1900
+ half = float16
1901
+ int_ = intp
1902
+ intc = int32
1903
+ long = int64
1904
+ short = int16
1905
+ single = float32
1906
+ ubyte = uint8
1907
+ uint = uintp
1908
+ uintc = uint32
1909
+ ulong = uint64
1910
+ 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.1"
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.1",
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
- )