applied-ai-018 commited on
Commit
1db021e
·
verified ·
1 Parent(s): 6a35e09

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/mp_rank_00_model_states.pt +3 -0
  2. ckpts/universal/global_step40/mp_rank_01_model_states.pt +3 -0
  3. ckpts/universal/global_step40/mp_rank_02_model_states.pt +3 -0
  4. ckpts/universal/global_step40/mp_rank_03_model_states.pt +3 -0
  5. ckpts/universal/global_step40/mp_rank_04_model_states.pt +3 -0
  6. ckpts/universal/global_step40/mp_rank_05_model_states.pt +3 -0
  7. ckpts/universal/global_step40/mp_rank_06_model_states.pt +3 -0
  8. ckpts/universal/global_step40/mp_rank_07_model_states.pt +3 -0
  9. ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  10. venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/__init__.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_pep440.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/numpy/matrixlib/__init__.py +11 -0
  13. venv/lib/python3.10/site-packages/numpy/matrixlib/__init__.pyi +15 -0
  14. venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/numpy/matrixlib/defmatrix.py +1114 -0
  17. venv/lib/python3.10/site-packages/numpy/matrixlib/defmatrix.pyi +16 -0
  18. venv/lib/python3.10/site-packages/numpy/matrixlib/setup.py +12 -0
  19. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__init__.py +0 -0
  20. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_defmatrix.py +453 -0
  21. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_interaction.py +354 -0
  22. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_matrix_linalg.py +93 -0
  23. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_multiarray.py +16 -0
  24. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_numeric.py +17 -0
  25. venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_regression.py +31 -0
  26. venv/lib/python3.10/site-packages/numpy/typing/__init__.py +175 -0
  27. venv/lib/python3.10/site-packages/numpy/typing/mypy_plugin.py +196 -0
  28. venv/lib/python3.10/site-packages/numpy/typing/setup.py +11 -0
  29. venv/lib/python3.10/site-packages/numpy/typing/tests/__init__.py +0 -0
  30. venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_isfile.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_runtime.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_typing.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arithmetic.pyi +121 -0
  35. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_constructors.pyi +33 -0
  36. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_like.pyi +16 -0
  37. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  38. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arrayprint.pyi +14 -0
  39. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  40. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/bitwise_ops.pyi +20 -0
  41. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/char.pyi +66 -0
  42. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/chararray.pyi +62 -0
  43. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  44. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/constants.pyi +7 -0
  45. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/datasource.pyi +15 -0
  46. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/dtype.pyi +20 -0
  47. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  48. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/flatiter.pyi +25 -0
  49. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/fromnumeric.pyi +161 -0
  50. venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/histograms.pyi +12 -0
ckpts/universal/global_step40/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b7d35b36f77067fc43080d60dd3ef746bc7cf3392e64b745bb189df6d181803
3
+ size 4230084
ckpts/universal/global_step40/mp_rank_01_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f15d2ad8b9c13e89266a02d8334fbd0dffe08e6327b0d1e62dbc8a5f98d8887
3
+ size 4230020
ckpts/universal/global_step40/mp_rank_02_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:993e4f3b1663d6b7feeb5f0a573c122d4cffef1ae58a090d53c1a3d38232e32d
3
+ size 4230020
ckpts/universal/global_step40/mp_rank_03_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:950695f4903c0daf2607beba21d30a9ba630f0344037c93569e79ce4bc4e0b83
3
+ size 4230020
ckpts/universal/global_step40/mp_rank_04_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10234e7ac599d8a5d5f21852832c76f968cda22e0f99cb4b769646bb76c364f4
3
+ size 4230084
ckpts/universal/global_step40/mp_rank_05_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce135a01f4c2defcf6a168ec5fb8291faaf7c966cfeb92ba648b6f7404507ad8
3
+ size 4230084
ckpts/universal/global_step40/mp_rank_06_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73eb5f72b6bb9868c1a608707fdfa8674fbc30bb44351016675e89949cab7920
3
+ size 4230084
ckpts/universal/global_step40/mp_rank_07_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc249171ab7e29645b27c09175560c00640839f21402776edcf487d6695fa8a7
3
+ size 4230084
ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d507ceadfd0c8d1bb6fc106ccf3a723668faeebe4c271070786ff2b86ef084aa
3
+ size 33555533
venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_pep440.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
venv/lib/python3.10/site-packages/numpy/matrixlib/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sub-package containing the matrix class and related functions.
2
+
3
+ """
4
+ from . import defmatrix
5
+ from .defmatrix import *
6
+
7
+ __all__ = defmatrix.__all__
8
+
9
+ from numpy._pytesttester import PytestTester
10
+ test = PytestTester(__name__)
11
+ del PytestTester
venv/lib/python3.10/site-packages/numpy/matrixlib/__init__.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy._pytesttester import PytestTester
2
+
3
+ from numpy import (
4
+ matrix as matrix,
5
+ )
6
+
7
+ from numpy.matrixlib.defmatrix import (
8
+ bmat as bmat,
9
+ mat as mat,
10
+ asmatrix as asmatrix,
11
+ )
12
+
13
+ __all__: list[str]
14
+ __path__: list[str]
15
+ test: PytestTester
venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (421 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/defmatrix.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
venv/lib/python3.10/site-packages/numpy/matrixlib/defmatrix.py ADDED
@@ -0,0 +1,1114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['matrix', 'bmat', 'mat', 'asmatrix']
2
+
3
+ import sys
4
+ import warnings
5
+ import ast
6
+
7
+ from .._utils import set_module
8
+ import numpy.core.numeric as N
9
+ from numpy.core.numeric import concatenate, isscalar
10
+ # While not in __all__, matrix_power used to be defined here, so we import
11
+ # it for backward compatibility.
12
+ from numpy.linalg import matrix_power
13
+
14
+
15
+ def _convert_from_string(data):
16
+ for char in '[]':
17
+ data = data.replace(char, '')
18
+
19
+ rows = data.split(';')
20
+ newdata = []
21
+ count = 0
22
+ for row in rows:
23
+ trow = row.split(',')
24
+ newrow = []
25
+ for col in trow:
26
+ temp = col.split()
27
+ newrow.extend(map(ast.literal_eval, temp))
28
+ if count == 0:
29
+ Ncols = len(newrow)
30
+ elif len(newrow) != Ncols:
31
+ raise ValueError("Rows not the same size.")
32
+ count += 1
33
+ newdata.append(newrow)
34
+ return newdata
35
+
36
+
37
+ @set_module('numpy')
38
+ def asmatrix(data, dtype=None):
39
+ """
40
+ Interpret the input as a matrix.
41
+
42
+ Unlike `matrix`, `asmatrix` does not make a copy if the input is already
43
+ a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
44
+
45
+ Parameters
46
+ ----------
47
+ data : array_like
48
+ Input data.
49
+ dtype : data-type
50
+ Data-type of the output matrix.
51
+
52
+ Returns
53
+ -------
54
+ mat : matrix
55
+ `data` interpreted as a matrix.
56
+
57
+ Examples
58
+ --------
59
+ >>> x = np.array([[1, 2], [3, 4]])
60
+
61
+ >>> m = np.asmatrix(x)
62
+
63
+ >>> x[0,0] = 5
64
+
65
+ >>> m
66
+ matrix([[5, 2],
67
+ [3, 4]])
68
+
69
+ """
70
+ return matrix(data, dtype=dtype, copy=False)
71
+
72
+
73
+ @set_module('numpy')
74
+ class matrix(N.ndarray):
75
+ """
76
+ matrix(data, dtype=None, copy=True)
77
+
78
+ .. note:: It is no longer recommended to use this class, even for linear
79
+ algebra. Instead use regular arrays. The class may be removed
80
+ in the future.
81
+
82
+ Returns a matrix from an array-like object, or from a string of data.
83
+ A matrix is a specialized 2-D array that retains its 2-D nature
84
+ through operations. It has certain special operators, such as ``*``
85
+ (matrix multiplication) and ``**`` (matrix power).
86
+
87
+ Parameters
88
+ ----------
89
+ data : array_like or string
90
+ If `data` is a string, it is interpreted as a matrix with commas
91
+ or spaces separating columns, and semicolons separating rows.
92
+ dtype : data-type
93
+ Data-type of the output matrix.
94
+ copy : bool
95
+ If `data` is already an `ndarray`, then this flag determines
96
+ whether the data is copied (the default), or whether a view is
97
+ constructed.
98
+
99
+ See Also
100
+ --------
101
+ array
102
+
103
+ Examples
104
+ --------
105
+ >>> a = np.matrix('1 2; 3 4')
106
+ >>> a
107
+ matrix([[1, 2],
108
+ [3, 4]])
109
+
110
+ >>> np.matrix([[1, 2], [3, 4]])
111
+ matrix([[1, 2],
112
+ [3, 4]])
113
+
114
+ """
115
+ __array_priority__ = 10.0
116
+ def __new__(subtype, data, dtype=None, copy=True):
117
+ warnings.warn('the matrix subclass is not the recommended way to '
118
+ 'represent matrices or deal with linear algebra (see '
119
+ 'https://docs.scipy.org/doc/numpy/user/'
120
+ 'numpy-for-matlab-users.html). '
121
+ 'Please adjust your code to use regular ndarray.',
122
+ PendingDeprecationWarning, stacklevel=2)
123
+ if isinstance(data, matrix):
124
+ dtype2 = data.dtype
125
+ if (dtype is None):
126
+ dtype = dtype2
127
+ if (dtype2 == dtype) and (not copy):
128
+ return data
129
+ return data.astype(dtype)
130
+
131
+ if isinstance(data, N.ndarray):
132
+ if dtype is None:
133
+ intype = data.dtype
134
+ else:
135
+ intype = N.dtype(dtype)
136
+ new = data.view(subtype)
137
+ if intype != data.dtype:
138
+ return new.astype(intype)
139
+ if copy: return new.copy()
140
+ else: return new
141
+
142
+ if isinstance(data, str):
143
+ data = _convert_from_string(data)
144
+
145
+ # now convert data to an array
146
+ arr = N.array(data, dtype=dtype, copy=copy)
147
+ ndim = arr.ndim
148
+ shape = arr.shape
149
+ if (ndim > 2):
150
+ raise ValueError("matrix must be 2-dimensional")
151
+ elif ndim == 0:
152
+ shape = (1, 1)
153
+ elif ndim == 1:
154
+ shape = (1, shape[0])
155
+
156
+ order = 'C'
157
+ if (ndim == 2) and arr.flags.fortran:
158
+ order = 'F'
159
+
160
+ if not (order or arr.flags.contiguous):
161
+ arr = arr.copy()
162
+
163
+ ret = N.ndarray.__new__(subtype, shape, arr.dtype,
164
+ buffer=arr,
165
+ order=order)
166
+ return ret
167
+
168
+ def __array_finalize__(self, obj):
169
+ self._getitem = False
170
+ if (isinstance(obj, matrix) and obj._getitem): return
171
+ ndim = self.ndim
172
+ if (ndim == 2):
173
+ return
174
+ if (ndim > 2):
175
+ newshape = tuple([x for x in self.shape if x > 1])
176
+ ndim = len(newshape)
177
+ if ndim == 2:
178
+ self.shape = newshape
179
+ return
180
+ elif (ndim > 2):
181
+ raise ValueError("shape too large to be a matrix.")
182
+ else:
183
+ newshape = self.shape
184
+ if ndim == 0:
185
+ self.shape = (1, 1)
186
+ elif ndim == 1:
187
+ self.shape = (1, newshape[0])
188
+ return
189
+
190
+ def __getitem__(self, index):
191
+ self._getitem = True
192
+
193
+ try:
194
+ out = N.ndarray.__getitem__(self, index)
195
+ finally:
196
+ self._getitem = False
197
+
198
+ if not isinstance(out, N.ndarray):
199
+ return out
200
+
201
+ if out.ndim == 0:
202
+ return out[()]
203
+ if out.ndim == 1:
204
+ sh = out.shape[0]
205
+ # Determine when we should have a column array
206
+ try:
207
+ n = len(index)
208
+ except Exception:
209
+ n = 0
210
+ if n > 1 and isscalar(index[1]):
211
+ out.shape = (sh, 1)
212
+ else:
213
+ out.shape = (1, sh)
214
+ return out
215
+
216
+ def __mul__(self, other):
217
+ if isinstance(other, (N.ndarray, list, tuple)) :
218
+ # This promotes 1-D vectors to row vectors
219
+ return N.dot(self, asmatrix(other))
220
+ if isscalar(other) or not hasattr(other, '__rmul__') :
221
+ return N.dot(self, other)
222
+ return NotImplemented
223
+
224
+ def __rmul__(self, other):
225
+ return N.dot(other, self)
226
+
227
+ def __imul__(self, other):
228
+ self[:] = self * other
229
+ return self
230
+
231
+ def __pow__(self, other):
232
+ return matrix_power(self, other)
233
+
234
+ def __ipow__(self, other):
235
+ self[:] = self ** other
236
+ return self
237
+
238
+ def __rpow__(self, other):
239
+ return NotImplemented
240
+
241
+ def _align(self, axis):
242
+ """A convenience function for operations that need to preserve axis
243
+ orientation.
244
+ """
245
+ if axis is None:
246
+ return self[0, 0]
247
+ elif axis==0:
248
+ return self
249
+ elif axis==1:
250
+ return self.transpose()
251
+ else:
252
+ raise ValueError("unsupported axis")
253
+
254
+ def _collapse(self, axis):
255
+ """A convenience function for operations that want to collapse
256
+ to a scalar like _align, but are using keepdims=True
257
+ """
258
+ if axis is None:
259
+ return self[0, 0]
260
+ else:
261
+ return self
262
+
263
+ # Necessary because base-class tolist expects dimension
264
+ # reduction by x[0]
265
+ def tolist(self):
266
+ """
267
+ Return the matrix as a (possibly nested) list.
268
+
269
+ See `ndarray.tolist` for full documentation.
270
+
271
+ See Also
272
+ --------
273
+ ndarray.tolist
274
+
275
+ Examples
276
+ --------
277
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
278
+ matrix([[ 0, 1, 2, 3],
279
+ [ 4, 5, 6, 7],
280
+ [ 8, 9, 10, 11]])
281
+ >>> x.tolist()
282
+ [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
283
+
284
+ """
285
+ return self.__array__().tolist()
286
+
287
+ # To preserve orientation of result...
288
+ def sum(self, axis=None, dtype=None, out=None):
289
+ """
290
+ Returns the sum of the matrix elements, along the given axis.
291
+
292
+ Refer to `numpy.sum` for full documentation.
293
+
294
+ See Also
295
+ --------
296
+ numpy.sum
297
+
298
+ Notes
299
+ -----
300
+ This is the same as `ndarray.sum`, except that where an `ndarray` would
301
+ be returned, a `matrix` object is returned instead.
302
+
303
+ Examples
304
+ --------
305
+ >>> x = np.matrix([[1, 2], [4, 3]])
306
+ >>> x.sum()
307
+ 10
308
+ >>> x.sum(axis=1)
309
+ matrix([[3],
310
+ [7]])
311
+ >>> x.sum(axis=1, dtype='float')
312
+ matrix([[3.],
313
+ [7.]])
314
+ >>> out = np.zeros((2, 1), dtype='float')
315
+ >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
316
+ matrix([[3.],
317
+ [7.]])
318
+
319
+ """
320
+ return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
321
+
322
+
323
+ # To update docstring from array to matrix...
324
+ def squeeze(self, axis=None):
325
+ """
326
+ Return a possibly reshaped matrix.
327
+
328
+ Refer to `numpy.squeeze` for more documentation.
329
+
330
+ Parameters
331
+ ----------
332
+ axis : None or int or tuple of ints, optional
333
+ Selects a subset of the axes of length one in the shape.
334
+ If an axis is selected with shape entry greater than one,
335
+ an error is raised.
336
+
337
+ Returns
338
+ -------
339
+ squeezed : matrix
340
+ The matrix, but as a (1, N) matrix if it had shape (N, 1).
341
+
342
+ See Also
343
+ --------
344
+ numpy.squeeze : related function
345
+
346
+ Notes
347
+ -----
348
+ If `m` has a single column then that column is returned
349
+ as the single row of a matrix. Otherwise `m` is returned.
350
+ The returned matrix is always either `m` itself or a view into `m`.
351
+ Supplying an axis keyword argument will not affect the returned matrix
352
+ but it may cause an error to be raised.
353
+
354
+ Examples
355
+ --------
356
+ >>> c = np.matrix([[1], [2]])
357
+ >>> c
358
+ matrix([[1],
359
+ [2]])
360
+ >>> c.squeeze()
361
+ matrix([[1, 2]])
362
+ >>> r = c.T
363
+ >>> r
364
+ matrix([[1, 2]])
365
+ >>> r.squeeze()
366
+ matrix([[1, 2]])
367
+ >>> m = np.matrix([[1, 2], [3, 4]])
368
+ >>> m.squeeze()
369
+ matrix([[1, 2],
370
+ [3, 4]])
371
+
372
+ """
373
+ return N.ndarray.squeeze(self, axis=axis)
374
+
375
+
376
+ # To update docstring from array to matrix...
377
+ def flatten(self, order='C'):
378
+ """
379
+ Return a flattened copy of the matrix.
380
+
381
+ All `N` elements of the matrix are placed into a single row.
382
+
383
+ Parameters
384
+ ----------
385
+ order : {'C', 'F', 'A', 'K'}, optional
386
+ 'C' means to flatten in row-major (C-style) order. 'F' means to
387
+ flatten in column-major (Fortran-style) order. 'A' means to
388
+ flatten in column-major order if `m` is Fortran *contiguous* in
389
+ memory, row-major order otherwise. 'K' means to flatten `m` in
390
+ the order the elements occur in memory. The default is 'C'.
391
+
392
+ Returns
393
+ -------
394
+ y : matrix
395
+ A copy of the matrix, flattened to a `(1, N)` matrix where `N`
396
+ is the number of elements in the original matrix.
397
+
398
+ See Also
399
+ --------
400
+ ravel : Return a flattened array.
401
+ flat : A 1-D flat iterator over the matrix.
402
+
403
+ Examples
404
+ --------
405
+ >>> m = np.matrix([[1,2], [3,4]])
406
+ >>> m.flatten()
407
+ matrix([[1, 2, 3, 4]])
408
+ >>> m.flatten('F')
409
+ matrix([[1, 3, 2, 4]])
410
+
411
+ """
412
+ return N.ndarray.flatten(self, order=order)
413
+
414
+ def mean(self, axis=None, dtype=None, out=None):
415
+ """
416
+ Returns the average of the matrix elements along the given axis.
417
+
418
+ Refer to `numpy.mean` for full documentation.
419
+
420
+ See Also
421
+ --------
422
+ numpy.mean
423
+
424
+ Notes
425
+ -----
426
+ Same as `ndarray.mean` except that, where that returns an `ndarray`,
427
+ this returns a `matrix` object.
428
+
429
+ Examples
430
+ --------
431
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
432
+ >>> x
433
+ matrix([[ 0, 1, 2, 3],
434
+ [ 4, 5, 6, 7],
435
+ [ 8, 9, 10, 11]])
436
+ >>> x.mean()
437
+ 5.5
438
+ >>> x.mean(0)
439
+ matrix([[4., 5., 6., 7.]])
440
+ >>> x.mean(1)
441
+ matrix([[ 1.5],
442
+ [ 5.5],
443
+ [ 9.5]])
444
+
445
+ """
446
+ return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)
447
+
448
+ def std(self, axis=None, dtype=None, out=None, ddof=0):
449
+ """
450
+ Return the standard deviation of the array elements along the given axis.
451
+
452
+ Refer to `numpy.std` for full documentation.
453
+
454
+ See Also
455
+ --------
456
+ numpy.std
457
+
458
+ Notes
459
+ -----
460
+ This is the same as `ndarray.std`, except that where an `ndarray` would
461
+ be returned, a `matrix` object is returned instead.
462
+
463
+ Examples
464
+ --------
465
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
466
+ >>> x
467
+ matrix([[ 0, 1, 2, 3],
468
+ [ 4, 5, 6, 7],
469
+ [ 8, 9, 10, 11]])
470
+ >>> x.std()
471
+ 3.4520525295346629 # may vary
472
+ >>> x.std(0)
473
+ matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
474
+ >>> x.std(1)
475
+ matrix([[ 1.11803399],
476
+ [ 1.11803399],
477
+ [ 1.11803399]])
478
+
479
+ """
480
+ return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
481
+
482
+ def var(self, axis=None, dtype=None, out=None, ddof=0):
483
+ """
484
+ Returns the variance of the matrix elements, along the given axis.
485
+
486
+ Refer to `numpy.var` for full documentation.
487
+
488
+ See Also
489
+ --------
490
+ numpy.var
491
+
492
+ Notes
493
+ -----
494
+ This is the same as `ndarray.var`, except that where an `ndarray` would
495
+ be returned, a `matrix` object is returned instead.
496
+
497
+ Examples
498
+ --------
499
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
500
+ >>> x
501
+ matrix([[ 0, 1, 2, 3],
502
+ [ 4, 5, 6, 7],
503
+ [ 8, 9, 10, 11]])
504
+ >>> x.var()
505
+ 11.916666666666666
506
+ >>> x.var(0)
507
+ matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
508
+ >>> x.var(1)
509
+ matrix([[1.25],
510
+ [1.25],
511
+ [1.25]])
512
+
513
+ """
514
+ return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)
515
+
516
+ def prod(self, axis=None, dtype=None, out=None):
517
+ """
518
+ Return the product of the array elements over the given axis.
519
+
520
+ Refer to `prod` for full documentation.
521
+
522
+ See Also
523
+ --------
524
+ prod, ndarray.prod
525
+
526
+ Notes
527
+ -----
528
+ Same as `ndarray.prod`, except, where that returns an `ndarray`, this
529
+ returns a `matrix` object instead.
530
+
531
+ Examples
532
+ --------
533
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
534
+ matrix([[ 0, 1, 2, 3],
535
+ [ 4, 5, 6, 7],
536
+ [ 8, 9, 10, 11]])
537
+ >>> x.prod()
538
+ 0
539
+ >>> x.prod(0)
540
+ matrix([[ 0, 45, 120, 231]])
541
+ >>> x.prod(1)
542
+ matrix([[ 0],
543
+ [ 840],
544
+ [7920]])
545
+
546
+ """
547
+ return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
548
+
549
+ def any(self, axis=None, out=None):
550
+ """
551
+ Test whether any array element along a given axis evaluates to True.
552
+
553
+ Refer to `numpy.any` for full documentation.
554
+
555
+ Parameters
556
+ ----------
557
+ axis : int, optional
558
+ Axis along which logical OR is performed
559
+ out : ndarray, optional
560
+ Output to existing array instead of creating new one, must have
561
+ same shape as expected output
562
+
563
+ Returns
564
+ -------
565
+ any : bool, ndarray
566
+ Returns a single bool if `axis` is ``None``; otherwise,
567
+ returns `ndarray`
568
+
569
+ """
570
+ return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
571
+
572
+ def all(self, axis=None, out=None):
573
+ """
574
+ Test whether all matrix elements along a given axis evaluate to True.
575
+
576
+ Parameters
577
+ ----------
578
+ See `numpy.all` for complete descriptions
579
+
580
+ See Also
581
+ --------
582
+ numpy.all
583
+
584
+ Notes
585
+ -----
586
+ This is the same as `ndarray.all`, but it returns a `matrix` object.
587
+
588
+ Examples
589
+ --------
590
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
591
+ matrix([[ 0, 1, 2, 3],
592
+ [ 4, 5, 6, 7],
593
+ [ 8, 9, 10, 11]])
594
+ >>> y = x[0]; y
595
+ matrix([[0, 1, 2, 3]])
596
+ >>> (x == y)
597
+ matrix([[ True, True, True, True],
598
+ [False, False, False, False],
599
+ [False, False, False, False]])
600
+ >>> (x == y).all()
601
+ False
602
+ >>> (x == y).all(0)
603
+ matrix([[False, False, False, False]])
604
+ >>> (x == y).all(1)
605
+ matrix([[ True],
606
+ [False],
607
+ [False]])
608
+
609
+ """
610
+ return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
611
+
612
+ def max(self, axis=None, out=None):
613
+ """
614
+ Return the maximum value along an axis.
615
+
616
+ Parameters
617
+ ----------
618
+ See `amax` for complete descriptions
619
+
620
+ See Also
621
+ --------
622
+ amax, ndarray.max
623
+
624
+ Notes
625
+ -----
626
+ This is the same as `ndarray.max`, but returns a `matrix` object
627
+ where `ndarray.max` would return an ndarray.
628
+
629
+ Examples
630
+ --------
631
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
632
+ matrix([[ 0, 1, 2, 3],
633
+ [ 4, 5, 6, 7],
634
+ [ 8, 9, 10, 11]])
635
+ >>> x.max()
636
+ 11
637
+ >>> x.max(0)
638
+ matrix([[ 8, 9, 10, 11]])
639
+ >>> x.max(1)
640
+ matrix([[ 3],
641
+ [ 7],
642
+ [11]])
643
+
644
+ """
645
+ return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
646
+
647
+ def argmax(self, axis=None, out=None):
648
+ """
649
+ Indexes of the maximum values along an axis.
650
+
651
+ Return the indexes of the first occurrences of the maximum values
652
+ along the specified axis. If axis is None, the index is for the
653
+ flattened matrix.
654
+
655
+ Parameters
656
+ ----------
657
+ See `numpy.argmax` for complete descriptions
658
+
659
+ See Also
660
+ --------
661
+ numpy.argmax
662
+
663
+ Notes
664
+ -----
665
+ This is the same as `ndarray.argmax`, but returns a `matrix` object
666
+ where `ndarray.argmax` would return an `ndarray`.
667
+
668
+ Examples
669
+ --------
670
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
671
+ matrix([[ 0, 1, 2, 3],
672
+ [ 4, 5, 6, 7],
673
+ [ 8, 9, 10, 11]])
674
+ >>> x.argmax()
675
+ 11
676
+ >>> x.argmax(0)
677
+ matrix([[2, 2, 2, 2]])
678
+ >>> x.argmax(1)
679
+ matrix([[3],
680
+ [3],
681
+ [3]])
682
+
683
+ """
684
+ return N.ndarray.argmax(self, axis, out)._align(axis)
685
+
686
+ def min(self, axis=None, out=None):
687
+ """
688
+ Return the minimum value along an axis.
689
+
690
+ Parameters
691
+ ----------
692
+ See `amin` for complete descriptions.
693
+
694
+ See Also
695
+ --------
696
+ amin, ndarray.min
697
+
698
+ Notes
699
+ -----
700
+ This is the same as `ndarray.min`, but returns a `matrix` object
701
+ where `ndarray.min` would return an ndarray.
702
+
703
+ Examples
704
+ --------
705
+ >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
706
+ matrix([[ 0, -1, -2, -3],
707
+ [ -4, -5, -6, -7],
708
+ [ -8, -9, -10, -11]])
709
+ >>> x.min()
710
+ -11
711
+ >>> x.min(0)
712
+ matrix([[ -8, -9, -10, -11]])
713
+ >>> x.min(1)
714
+ matrix([[ -3],
715
+ [ -7],
716
+ [-11]])
717
+
718
+ """
719
+ return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
720
+
721
+ def argmin(self, axis=None, out=None):
722
+ """
723
+ Indexes of the minimum values along an axis.
724
+
725
+ Return the indexes of the first occurrences of the minimum values
726
+ along the specified axis. If axis is None, the index is for the
727
+ flattened matrix.
728
+
729
+ Parameters
730
+ ----------
731
+ See `numpy.argmin` for complete descriptions.
732
+
733
+ See Also
734
+ --------
735
+ numpy.argmin
736
+
737
+ Notes
738
+ -----
739
+ This is the same as `ndarray.argmin`, but returns a `matrix` object
740
+ where `ndarray.argmin` would return an `ndarray`.
741
+
742
+ Examples
743
+ --------
744
+ >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
745
+ matrix([[ 0, -1, -2, -3],
746
+ [ -4, -5, -6, -7],
747
+ [ -8, -9, -10, -11]])
748
+ >>> x.argmin()
749
+ 11
750
+ >>> x.argmin(0)
751
+ matrix([[2, 2, 2, 2]])
752
+ >>> x.argmin(1)
753
+ matrix([[3],
754
+ [3],
755
+ [3]])
756
+
757
+ """
758
+ return N.ndarray.argmin(self, axis, out)._align(axis)
759
+
760
+ def ptp(self, axis=None, out=None):
761
+ """
762
+ Peak-to-peak (maximum - minimum) value along the given axis.
763
+
764
+ Refer to `numpy.ptp` for full documentation.
765
+
766
+ See Also
767
+ --------
768
+ numpy.ptp
769
+
770
+ Notes
771
+ -----
772
+ Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
773
+ this returns a `matrix` object.
774
+
775
+ Examples
776
+ --------
777
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
778
+ matrix([[ 0, 1, 2, 3],
779
+ [ 4, 5, 6, 7],
780
+ [ 8, 9, 10, 11]])
781
+ >>> x.ptp()
782
+ 11
783
+ >>> x.ptp(0)
784
+ matrix([[8, 8, 8, 8]])
785
+ >>> x.ptp(1)
786
+ matrix([[3],
787
+ [3],
788
+ [3]])
789
+
790
+ """
791
+ return N.ndarray.ptp(self, axis, out)._align(axis)
792
+
793
+ @property
794
+ def I(self):
795
+ """
796
+ Returns the (multiplicative) inverse of invertible `self`.
797
+
798
+ Parameters
799
+ ----------
800
+ None
801
+
802
+ Returns
803
+ -------
804
+ ret : matrix object
805
+ If `self` is non-singular, `ret` is such that ``ret * self`` ==
806
+ ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
807
+ ``True``.
808
+
809
+ Raises
810
+ ------
811
+ numpy.linalg.LinAlgError: Singular matrix
812
+ If `self` is singular.
813
+
814
+ See Also
815
+ --------
816
+ linalg.inv
817
+
818
+ Examples
819
+ --------
820
+ >>> m = np.matrix('[1, 2; 3, 4]'); m
821
+ matrix([[1, 2],
822
+ [3, 4]])
823
+ >>> m.getI()
824
+ matrix([[-2. , 1. ],
825
+ [ 1.5, -0.5]])
826
+ >>> m.getI() * m
827
+ matrix([[ 1., 0.], # may vary
828
+ [ 0., 1.]])
829
+
830
+ """
831
+ M, N = self.shape
832
+ if M == N:
833
+ from numpy.linalg import inv as func
834
+ else:
835
+ from numpy.linalg import pinv as func
836
+ return asmatrix(func(self))
837
+
838
+ @property
839
+ def A(self):
840
+ """
841
+ Return `self` as an `ndarray` object.
842
+
843
+ Equivalent to ``np.asarray(self)``.
844
+
845
+ Parameters
846
+ ----------
847
+ None
848
+
849
+ Returns
850
+ -------
851
+ ret : ndarray
852
+ `self` as an `ndarray`
853
+
854
+ Examples
855
+ --------
856
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
857
+ matrix([[ 0, 1, 2, 3],
858
+ [ 4, 5, 6, 7],
859
+ [ 8, 9, 10, 11]])
860
+ >>> x.getA()
861
+ array([[ 0, 1, 2, 3],
862
+ [ 4, 5, 6, 7],
863
+ [ 8, 9, 10, 11]])
864
+
865
+ """
866
+ return self.__array__()
867
+
868
+ @property
869
+ def A1(self):
870
+ """
871
+ Return `self` as a flattened `ndarray`.
872
+
873
+ Equivalent to ``np.asarray(x).ravel()``
874
+
875
+ Parameters
876
+ ----------
877
+ None
878
+
879
+ Returns
880
+ -------
881
+ ret : ndarray
882
+ `self`, 1-D, as an `ndarray`
883
+
884
+ Examples
885
+ --------
886
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
887
+ matrix([[ 0, 1, 2, 3],
888
+ [ 4, 5, 6, 7],
889
+ [ 8, 9, 10, 11]])
890
+ >>> x.getA1()
891
+ array([ 0, 1, 2, ..., 9, 10, 11])
892
+
893
+
894
+ """
895
+ return self.__array__().ravel()
896
+
897
+
898
+ def ravel(self, order='C'):
899
+ """
900
+ Return a flattened matrix.
901
+
902
+ Refer to `numpy.ravel` for more documentation.
903
+
904
+ Parameters
905
+ ----------
906
+ order : {'C', 'F', 'A', 'K'}, optional
907
+ The elements of `m` are read using this index order. 'C' means to
908
+ index the elements in C-like order, with the last axis index
909
+ changing fastest, back to the first axis index changing slowest.
910
+ 'F' means to index the elements in Fortran-like index order, with
911
+ the first index changing fastest, and the last index changing
912
+ slowest. Note that the 'C' and 'F' options take no account of the
913
+ memory layout of the underlying array, and only refer to the order
914
+ of axis indexing. 'A' means to read the elements in Fortran-like
915
+ index order if `m` is Fortran *contiguous* in memory, C-like order
916
+ otherwise. 'K' means to read the elements in the order they occur
917
+ in memory, except for reversing the data when strides are negative.
918
+ By default, 'C' index order is used.
919
+
920
+ Returns
921
+ -------
922
+ ret : matrix
923
+ Return the matrix flattened to shape `(1, N)` where `N`
924
+ is the number of elements in the original matrix.
925
+ A copy is made only if necessary.
926
+
927
+ See Also
928
+ --------
929
+ matrix.flatten : returns a similar output matrix but always a copy
930
+ matrix.flat : a flat iterator on the array.
931
+ numpy.ravel : related function which returns an ndarray
932
+
933
+ """
934
+ return N.ndarray.ravel(self, order=order)
935
+
936
+ @property
937
+ def T(self):
938
+ """
939
+ Returns the transpose of the matrix.
940
+
941
+ Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
942
+
943
+ Parameters
944
+ ----------
945
+ None
946
+
947
+ Returns
948
+ -------
949
+ ret : matrix object
950
+ The (non-conjugated) transpose of the matrix.
951
+
952
+ See Also
953
+ --------
954
+ transpose, getH
955
+
956
+ Examples
957
+ --------
958
+ >>> m = np.matrix('[1, 2; 3, 4]')
959
+ >>> m
960
+ matrix([[1, 2],
961
+ [3, 4]])
962
+ >>> m.getT()
963
+ matrix([[1, 3],
964
+ [2, 4]])
965
+
966
+ """
967
+ return self.transpose()
968
+
969
+ @property
970
+ def H(self):
971
+ """
972
+ Returns the (complex) conjugate transpose of `self`.
973
+
974
+ Equivalent to ``np.transpose(self)`` if `self` is real-valued.
975
+
976
+ Parameters
977
+ ----------
978
+ None
979
+
980
+ Returns
981
+ -------
982
+ ret : matrix object
983
+ complex conjugate transpose of `self`
984
+
985
+ Examples
986
+ --------
987
+ >>> x = np.matrix(np.arange(12).reshape((3,4)))
988
+ >>> z = x - 1j*x; z
989
+ matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
990
+ [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
991
+ [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
992
+ >>> z.getH()
993
+ matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
994
+ [ 1. +1.j, 5. +5.j, 9. +9.j],
995
+ [ 2. +2.j, 6. +6.j, 10.+10.j],
996
+ [ 3. +3.j, 7. +7.j, 11.+11.j]])
997
+
998
+ """
999
+ if issubclass(self.dtype.type, N.complexfloating):
1000
+ return self.transpose().conjugate()
1001
+ else:
1002
+ return self.transpose()
1003
+
1004
+ # kept for compatibility
1005
+ getT = T.fget
1006
+ getA = A.fget
1007
+ getA1 = A1.fget
1008
+ getH = H.fget
1009
+ getI = I.fget
1010
+
1011
+ def _from_string(str, gdict, ldict):
1012
+ rows = str.split(';')
1013
+ rowtup = []
1014
+ for row in rows:
1015
+ trow = row.split(',')
1016
+ newrow = []
1017
+ for x in trow:
1018
+ newrow.extend(x.split())
1019
+ trow = newrow
1020
+ coltup = []
1021
+ for col in trow:
1022
+ col = col.strip()
1023
+ try:
1024
+ thismat = ldict[col]
1025
+ except KeyError:
1026
+ try:
1027
+ thismat = gdict[col]
1028
+ except KeyError as e:
1029
+ raise NameError(f"name {col!r} is not defined") from None
1030
+
1031
+ coltup.append(thismat)
1032
+ rowtup.append(concatenate(coltup, axis=-1))
1033
+ return concatenate(rowtup, axis=0)
1034
+
1035
+
1036
+ @set_module('numpy')
1037
+ def bmat(obj, ldict=None, gdict=None):
1038
+ """
1039
+ Build a matrix object from a string, nested sequence, or array.
1040
+
1041
+ Parameters
1042
+ ----------
1043
+ obj : str or array_like
1044
+ Input data. If a string, variables in the current scope may be
1045
+ referenced by name.
1046
+ ldict : dict, optional
1047
+ A dictionary that replaces local operands in current frame.
1048
+ Ignored if `obj` is not a string or `gdict` is None.
1049
+ gdict : dict, optional
1050
+ A dictionary that replaces global operands in current frame.
1051
+ Ignored if `obj` is not a string.
1052
+
1053
+ Returns
1054
+ -------
1055
+ out : matrix
1056
+ Returns a matrix object, which is a specialized 2-D array.
1057
+
1058
+ See Also
1059
+ --------
1060
+ block :
1061
+ A generalization of this function for N-d arrays, that returns normal
1062
+ ndarrays.
1063
+
1064
+ Examples
1065
+ --------
1066
+ >>> A = np.mat('1 1; 1 1')
1067
+ >>> B = np.mat('2 2; 2 2')
1068
+ >>> C = np.mat('3 4; 5 6')
1069
+ >>> D = np.mat('7 8; 9 0')
1070
+
1071
+ All the following expressions construct the same block matrix:
1072
+
1073
+ >>> np.bmat([[A, B], [C, D]])
1074
+ matrix([[1, 1, 2, 2],
1075
+ [1, 1, 2, 2],
1076
+ [3, 4, 7, 8],
1077
+ [5, 6, 9, 0]])
1078
+ >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
1079
+ matrix([[1, 1, 2, 2],
1080
+ [1, 1, 2, 2],
1081
+ [3, 4, 7, 8],
1082
+ [5, 6, 9, 0]])
1083
+ >>> np.bmat('A,B; C,D')
1084
+ matrix([[1, 1, 2, 2],
1085
+ [1, 1, 2, 2],
1086
+ [3, 4, 7, 8],
1087
+ [5, 6, 9, 0]])
1088
+
1089
+ """
1090
+ if isinstance(obj, str):
1091
+ if gdict is None:
1092
+ # get previous frame
1093
+ frame = sys._getframe().f_back
1094
+ glob_dict = frame.f_globals
1095
+ loc_dict = frame.f_locals
1096
+ else:
1097
+ glob_dict = gdict
1098
+ loc_dict = ldict
1099
+
1100
+ return matrix(_from_string(obj, glob_dict, loc_dict))
1101
+
1102
+ if isinstance(obj, (tuple, list)):
1103
+ # [[A,B],[C,D]]
1104
+ arr_rows = []
1105
+ for row in obj:
1106
+ if isinstance(row, N.ndarray): # not 2-d
1107
+ return matrix(concatenate(obj, axis=-1))
1108
+ else:
1109
+ arr_rows.append(concatenate(row, axis=-1))
1110
+ return matrix(concatenate(arr_rows, axis=0))
1111
+ if isinstance(obj, N.ndarray):
1112
+ return matrix(obj)
1113
+
1114
+ mat = asmatrix
venv/lib/python3.10/site-packages/numpy/matrixlib/defmatrix.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence, Mapping
2
+ from typing import Any
3
+ from numpy import matrix as matrix
4
+ from numpy._typing import ArrayLike, DTypeLike, NDArray
5
+
6
+ __all__: list[str]
7
+
8
+ def bmat(
9
+ obj: str | Sequence[ArrayLike] | NDArray[Any],
10
+ ldict: None | Mapping[str, Any] = ...,
11
+ gdict: None | Mapping[str, Any] = ...,
12
+ ) -> matrix[Any, Any]: ...
13
+
14
+ def asmatrix(data: ArrayLike, dtype: DTypeLike = ...) -> matrix[Any, Any]: ...
15
+
16
+ mat = asmatrix
venv/lib/python3.10/site-packages/numpy/matrixlib/setup.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ def configuration(parent_package='', top_path=None):
3
+ from numpy.distutils.misc_util import Configuration
4
+ config = Configuration('matrixlib', parent_package, top_path)
5
+ config.add_subpackage('tests')
6
+ config.add_data_files('*.pyi')
7
+ return config
8
+
9
+ if __name__ == "__main__":
10
+ from numpy.distutils.core import setup
11
+ config = configuration(top_path='').todict()
12
+ setup(**config)
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_defmatrix.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+
3
+ import numpy as np
4
+ from numpy import matrix, asmatrix, bmat
5
+ from numpy.testing import (
6
+ assert_, assert_equal, assert_almost_equal, assert_array_equal,
7
+ assert_array_almost_equal, assert_raises
8
+ )
9
+ from numpy.linalg import matrix_power
10
+ from numpy.matrixlib import mat
11
+
12
+ class TestCtor:
13
+ def test_basic(self):
14
+ A = np.array([[1, 2], [3, 4]])
15
+ mA = matrix(A)
16
+ assert_(np.all(mA.A == A))
17
+
18
+ B = bmat("A,A;A,A")
19
+ C = bmat([[A, A], [A, A]])
20
+ D = np.array([[1, 2, 1, 2],
21
+ [3, 4, 3, 4],
22
+ [1, 2, 1, 2],
23
+ [3, 4, 3, 4]])
24
+ assert_(np.all(B.A == D))
25
+ assert_(np.all(C.A == D))
26
+
27
+ E = np.array([[5, 6], [7, 8]])
28
+ AEresult = matrix([[1, 2, 5, 6], [3, 4, 7, 8]])
29
+ assert_(np.all(bmat([A, E]) == AEresult))
30
+
31
+ vec = np.arange(5)
32
+ mvec = matrix(vec)
33
+ assert_(mvec.shape == (1, 5))
34
+
35
+ def test_exceptions(self):
36
+ # Check for ValueError when called with invalid string data.
37
+ assert_raises(ValueError, matrix, "invalid")
38
+
39
+ def test_bmat_nondefault_str(self):
40
+ A = np.array([[1, 2], [3, 4]])
41
+ B = np.array([[5, 6], [7, 8]])
42
+ Aresult = np.array([[1, 2, 1, 2],
43
+ [3, 4, 3, 4],
44
+ [1, 2, 1, 2],
45
+ [3, 4, 3, 4]])
46
+ mixresult = np.array([[1, 2, 5, 6],
47
+ [3, 4, 7, 8],
48
+ [5, 6, 1, 2],
49
+ [7, 8, 3, 4]])
50
+ assert_(np.all(bmat("A,A;A,A") == Aresult))
51
+ assert_(np.all(bmat("A,A;A,A", ldict={'A':B}) == Aresult))
52
+ assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A':B})
53
+ assert_(
54
+ np.all(bmat("A,A;A,A", ldict={'A':A}, gdict={'A':B}) == Aresult))
55
+ b2 = bmat("A,B;C,D", ldict={'A':A,'B':B}, gdict={'C':B,'D':A})
56
+ assert_(np.all(b2 == mixresult))
57
+
58
+
59
+ class TestProperties:
60
+ def test_sum(self):
61
+ """Test whether matrix.sum(axis=1) preserves orientation.
62
+ Fails in NumPy <= 0.9.6.2127.
63
+ """
64
+ M = matrix([[1, 2, 0, 0],
65
+ [3, 4, 0, 0],
66
+ [1, 2, 1, 2],
67
+ [3, 4, 3, 4]])
68
+ sum0 = matrix([8, 12, 4, 6])
69
+ sum1 = matrix([3, 7, 6, 14]).T
70
+ sumall = 30
71
+ assert_array_equal(sum0, M.sum(axis=0))
72
+ assert_array_equal(sum1, M.sum(axis=1))
73
+ assert_equal(sumall, M.sum())
74
+
75
+ assert_array_equal(sum0, np.sum(M, axis=0))
76
+ assert_array_equal(sum1, np.sum(M, axis=1))
77
+ assert_equal(sumall, np.sum(M))
78
+
79
+ def test_prod(self):
80
+ x = matrix([[1, 2, 3], [4, 5, 6]])
81
+ assert_equal(x.prod(), 720)
82
+ assert_equal(x.prod(0), matrix([[4, 10, 18]]))
83
+ assert_equal(x.prod(1), matrix([[6], [120]]))
84
+
85
+ assert_equal(np.prod(x), 720)
86
+ assert_equal(np.prod(x, axis=0), matrix([[4, 10, 18]]))
87
+ assert_equal(np.prod(x, axis=1), matrix([[6], [120]]))
88
+
89
+ y = matrix([0, 1, 3])
90
+ assert_(y.prod() == 0)
91
+
92
+ def test_max(self):
93
+ x = matrix([[1, 2, 3], [4, 5, 6]])
94
+ assert_equal(x.max(), 6)
95
+ assert_equal(x.max(0), matrix([[4, 5, 6]]))
96
+ assert_equal(x.max(1), matrix([[3], [6]]))
97
+
98
+ assert_equal(np.max(x), 6)
99
+ assert_equal(np.max(x, axis=0), matrix([[4, 5, 6]]))
100
+ assert_equal(np.max(x, axis=1), matrix([[3], [6]]))
101
+
102
+ def test_min(self):
103
+ x = matrix([[1, 2, 3], [4, 5, 6]])
104
+ assert_equal(x.min(), 1)
105
+ assert_equal(x.min(0), matrix([[1, 2, 3]]))
106
+ assert_equal(x.min(1), matrix([[1], [4]]))
107
+
108
+ assert_equal(np.min(x), 1)
109
+ assert_equal(np.min(x, axis=0), matrix([[1, 2, 3]]))
110
+ assert_equal(np.min(x, axis=1), matrix([[1], [4]]))
111
+
112
+ def test_ptp(self):
113
+ x = np.arange(4).reshape((2, 2))
114
+ assert_(x.ptp() == 3)
115
+ assert_(np.all(x.ptp(0) == np.array([2, 2])))
116
+ assert_(np.all(x.ptp(1) == np.array([1, 1])))
117
+
118
+ def test_var(self):
119
+ x = np.arange(9).reshape((3, 3))
120
+ mx = x.view(np.matrix)
121
+ assert_equal(x.var(ddof=0), mx.var(ddof=0))
122
+ assert_equal(x.var(ddof=1), mx.var(ddof=1))
123
+
124
+ def test_basic(self):
125
+ import numpy.linalg as linalg
126
+
127
+ A = np.array([[1., 2.],
128
+ [3., 4.]])
129
+ mA = matrix(A)
130
+ assert_(np.allclose(linalg.inv(A), mA.I))
131
+ assert_(np.all(np.array(np.transpose(A) == mA.T)))
132
+ assert_(np.all(np.array(np.transpose(A) == mA.H)))
133
+ assert_(np.all(A == mA.A))
134
+
135
+ B = A + 2j*A
136
+ mB = matrix(B)
137
+ assert_(np.allclose(linalg.inv(B), mB.I))
138
+ assert_(np.all(np.array(np.transpose(B) == mB.T)))
139
+ assert_(np.all(np.array(np.transpose(B).conj() == mB.H)))
140
+
141
+ def test_pinv(self):
142
+ x = matrix(np.arange(6).reshape(2, 3))
143
+ xpinv = matrix([[-0.77777778, 0.27777778],
144
+ [-0.11111111, 0.11111111],
145
+ [ 0.55555556, -0.05555556]])
146
+ assert_almost_equal(x.I, xpinv)
147
+
148
+ def test_comparisons(self):
149
+ A = np.arange(100).reshape(10, 10)
150
+ mA = matrix(A)
151
+ mB = matrix(A) + 0.1
152
+ assert_(np.all(mB == A+0.1))
153
+ assert_(np.all(mB == matrix(A+0.1)))
154
+ assert_(not np.any(mB == matrix(A-0.1)))
155
+ assert_(np.all(mA < mB))
156
+ assert_(np.all(mA <= mB))
157
+ assert_(np.all(mA <= mA))
158
+ assert_(not np.any(mA < mA))
159
+
160
+ assert_(not np.any(mB < mA))
161
+ assert_(np.all(mB >= mA))
162
+ assert_(np.all(mB >= mB))
163
+ assert_(not np.any(mB > mB))
164
+
165
+ assert_(np.all(mA == mA))
166
+ assert_(not np.any(mA == mB))
167
+ assert_(np.all(mB != mA))
168
+
169
+ assert_(not np.all(abs(mA) > 0))
170
+ assert_(np.all(abs(mB > 0)))
171
+
172
+ def test_asmatrix(self):
173
+ A = np.arange(100).reshape(10, 10)
174
+ mA = asmatrix(A)
175
+ A[0, 0] = -10
176
+ assert_(A[0, 0] == mA[0, 0])
177
+
178
+ def test_noaxis(self):
179
+ A = matrix([[1, 0], [0, 1]])
180
+ assert_(A.sum() == matrix(2))
181
+ assert_(A.mean() == matrix(0.5))
182
+
183
+ def test_repr(self):
184
+ A = matrix([[1, 0], [0, 1]])
185
+ assert_(repr(A) == "matrix([[1, 0],\n [0, 1]])")
186
+
187
+ def test_make_bool_matrix_from_str(self):
188
+ A = matrix('True; True; False')
189
+ B = matrix([[True], [True], [False]])
190
+ assert_array_equal(A, B)
191
+
192
+ class TestCasting:
193
+ def test_basic(self):
194
+ A = np.arange(100).reshape(10, 10)
195
+ mA = matrix(A)
196
+
197
+ mB = mA.copy()
198
+ O = np.ones((10, 10), np.float64) * 0.1
199
+ mB = mB + O
200
+ assert_(mB.dtype.type == np.float64)
201
+ assert_(np.all(mA != mB))
202
+ assert_(np.all(mB == mA+0.1))
203
+
204
+ mC = mA.copy()
205
+ O = np.ones((10, 10), np.complex128)
206
+ mC = mC * O
207
+ assert_(mC.dtype.type == np.complex128)
208
+ assert_(np.all(mA != mB))
209
+
210
+
211
+ class TestAlgebra:
212
+ def test_basic(self):
213
+ import numpy.linalg as linalg
214
+
215
+ A = np.array([[1., 2.], [3., 4.]])
216
+ mA = matrix(A)
217
+
218
+ B = np.identity(2)
219
+ for i in range(6):
220
+ assert_(np.allclose((mA ** i).A, B))
221
+ B = np.dot(B, A)
222
+
223
+ Ainv = linalg.inv(A)
224
+ B = np.identity(2)
225
+ for i in range(6):
226
+ assert_(np.allclose((mA ** -i).A, B))
227
+ B = np.dot(B, Ainv)
228
+
229
+ assert_(np.allclose((mA * mA).A, np.dot(A, A)))
230
+ assert_(np.allclose((mA + mA).A, (A + A)))
231
+ assert_(np.allclose((3*mA).A, (3*A)))
232
+
233
+ mA2 = matrix(A)
234
+ mA2 *= 3
235
+ assert_(np.allclose(mA2.A, 3*A))
236
+
237
+ def test_pow(self):
238
+ """Test raising a matrix to an integer power works as expected."""
239
+ m = matrix("1. 2.; 3. 4.")
240
+ m2 = m.copy()
241
+ m2 **= 2
242
+ mi = m.copy()
243
+ mi **= -1
244
+ m4 = m2.copy()
245
+ m4 **= 2
246
+ assert_array_almost_equal(m2, m**2)
247
+ assert_array_almost_equal(m4, np.dot(m2, m2))
248
+ assert_array_almost_equal(np.dot(mi, m), np.eye(2))
249
+
250
+ def test_scalar_type_pow(self):
251
+ m = matrix([[1, 2], [3, 4]])
252
+ for scalar_t in [np.int8, np.uint8]:
253
+ two = scalar_t(2)
254
+ assert_array_almost_equal(m ** 2, m ** two)
255
+
256
+ def test_notimplemented(self):
257
+ '''Check that 'not implemented' operations produce a failure.'''
258
+ A = matrix([[1., 2.],
259
+ [3., 4.]])
260
+
261
+ # __rpow__
262
+ with assert_raises(TypeError):
263
+ 1.0**A
264
+
265
+ # __mul__ with something not a list, ndarray, tuple, or scalar
266
+ with assert_raises(TypeError):
267
+ A*object()
268
+
269
+
270
+ class TestMatrixReturn:
271
+ def test_instance_methods(self):
272
+ a = matrix([1.0], dtype='f8')
273
+ methodargs = {
274
+ 'astype': ('intc',),
275
+ 'clip': (0.0, 1.0),
276
+ 'compress': ([1],),
277
+ 'repeat': (1,),
278
+ 'reshape': (1,),
279
+ 'swapaxes': (0, 0),
280
+ 'dot': np.array([1.0]),
281
+ }
282
+ excluded_methods = [
283
+ 'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',
284
+ 'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',
285
+ 'searchsorted', 'setflags', 'setfield', 'sort',
286
+ 'partition', 'argpartition',
287
+ 'take', 'tofile', 'tolist', 'tostring', 'tobytes', 'all', 'any',
288
+ 'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',
289
+ 'prod', 'std', 'ctypes', 'itemset',
290
+ ]
291
+ for attrib in dir(a):
292
+ if attrib.startswith('_') or attrib in excluded_methods:
293
+ continue
294
+ f = getattr(a, attrib)
295
+ if isinstance(f, collections.abc.Callable):
296
+ # reset contents of a
297
+ a.astype('f8')
298
+ a.fill(1.0)
299
+ if attrib in methodargs:
300
+ args = methodargs[attrib]
301
+ else:
302
+ args = ()
303
+ b = f(*args)
304
+ assert_(type(b) is matrix, "%s" % attrib)
305
+ assert_(type(a.real) is matrix)
306
+ assert_(type(a.imag) is matrix)
307
+ c, d = matrix([0.0]).nonzero()
308
+ assert_(type(c) is np.ndarray)
309
+ assert_(type(d) is np.ndarray)
310
+
311
+
312
+ class TestIndexing:
313
+ def test_basic(self):
314
+ x = asmatrix(np.zeros((3, 2), float))
315
+ y = np.zeros((3, 1), float)
316
+ y[:, 0] = [0.8, 0.2, 0.3]
317
+ x[:, 1] = y > 0.5
318
+ assert_equal(x, [[0, 1], [0, 0], [0, 0]])
319
+
320
+
321
+ class TestNewScalarIndexing:
322
+ a = matrix([[1, 2], [3, 4]])
323
+
324
+ def test_dimesions(self):
325
+ a = self.a
326
+ x = a[0]
327
+ assert_equal(x.ndim, 2)
328
+
329
+ def test_array_from_matrix_list(self):
330
+ a = self.a
331
+ x = np.array([a, a])
332
+ assert_equal(x.shape, [2, 2, 2])
333
+
334
+ def test_array_to_list(self):
335
+ a = self.a
336
+ assert_equal(a.tolist(), [[1, 2], [3, 4]])
337
+
338
+ def test_fancy_indexing(self):
339
+ a = self.a
340
+ x = a[1, [0, 1, 0]]
341
+ assert_(isinstance(x, matrix))
342
+ assert_equal(x, matrix([[3, 4, 3]]))
343
+ x = a[[1, 0]]
344
+ assert_(isinstance(x, matrix))
345
+ assert_equal(x, matrix([[3, 4], [1, 2]]))
346
+ x = a[[[1], [0]], [[1, 0], [0, 1]]]
347
+ assert_(isinstance(x, matrix))
348
+ assert_equal(x, matrix([[4, 3], [1, 2]]))
349
+
350
+ def test_matrix_element(self):
351
+ x = matrix([[1, 2, 3], [4, 5, 6]])
352
+ assert_equal(x[0][0], matrix([[1, 2, 3]]))
353
+ assert_equal(x[0][0].shape, (1, 3))
354
+ assert_equal(x[0].shape, (1, 3))
355
+ assert_equal(x[:, 0].shape, (2, 1))
356
+
357
+ x = matrix(0)
358
+ assert_equal(x[0, 0], 0)
359
+ assert_equal(x[0], 0)
360
+ assert_equal(x[:, 0].shape, x.shape)
361
+
362
+ def test_scalar_indexing(self):
363
+ x = asmatrix(np.zeros((3, 2), float))
364
+ assert_equal(x[0, 0], x[0][0])
365
+
366
+ def test_row_column_indexing(self):
367
+ x = asmatrix(np.eye(2))
368
+ assert_array_equal(x[0,:], [[1, 0]])
369
+ assert_array_equal(x[1,:], [[0, 1]])
370
+ assert_array_equal(x[:, 0], [[1], [0]])
371
+ assert_array_equal(x[:, 1], [[0], [1]])
372
+
373
+ def test_boolean_indexing(self):
374
+ A = np.arange(6)
375
+ A.shape = (3, 2)
376
+ x = asmatrix(A)
377
+ assert_array_equal(x[:, np.array([True, False])], x[:, 0])
378
+ assert_array_equal(x[np.array([True, False, False]),:], x[0,:])
379
+
380
+ def test_list_indexing(self):
381
+ A = np.arange(6)
382
+ A.shape = (3, 2)
383
+ x = asmatrix(A)
384
+ assert_array_equal(x[:, [1, 0]], x[:, ::-1])
385
+ assert_array_equal(x[[2, 1, 0],:], x[::-1,:])
386
+
387
+
388
+ class TestPower:
389
+ def test_returntype(self):
390
+ a = np.array([[0, 1], [0, 0]])
391
+ assert_(type(matrix_power(a, 2)) is np.ndarray)
392
+ a = mat(a)
393
+ assert_(type(matrix_power(a, 2)) is matrix)
394
+
395
+ def test_list(self):
396
+ assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])
397
+
398
+
399
+ class TestShape:
400
+
401
+ a = np.array([[1], [2]])
402
+ m = matrix([[1], [2]])
403
+
404
+ def test_shape(self):
405
+ assert_equal(self.a.shape, (2, 1))
406
+ assert_equal(self.m.shape, (2, 1))
407
+
408
+ def test_numpy_ravel(self):
409
+ assert_equal(np.ravel(self.a).shape, (2,))
410
+ assert_equal(np.ravel(self.m).shape, (2,))
411
+
412
+ def test_member_ravel(self):
413
+ assert_equal(self.a.ravel().shape, (2,))
414
+ assert_equal(self.m.ravel().shape, (1, 2))
415
+
416
+ def test_member_flatten(self):
417
+ assert_equal(self.a.flatten().shape, (2,))
418
+ assert_equal(self.m.flatten().shape, (1, 2))
419
+
420
+ def test_numpy_ravel_order(self):
421
+ x = np.array([[1, 2, 3], [4, 5, 6]])
422
+ assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
423
+ assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
424
+ assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
425
+ assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
426
+ x = matrix([[1, 2, 3], [4, 5, 6]])
427
+ assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
428
+ assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
429
+ assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
430
+ assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
431
+
432
+ def test_matrix_ravel_order(self):
433
+ x = matrix([[1, 2, 3], [4, 5, 6]])
434
+ assert_equal(x.ravel(), [[1, 2, 3, 4, 5, 6]])
435
+ assert_equal(x.ravel(order='F'), [[1, 4, 2, 5, 3, 6]])
436
+ assert_equal(x.T.ravel(), [[1, 4, 2, 5, 3, 6]])
437
+ assert_equal(x.T.ravel(order='A'), [[1, 2, 3, 4, 5, 6]])
438
+
439
+ def test_array_memory_sharing(self):
440
+ assert_(np.may_share_memory(self.a, self.a.ravel()))
441
+ assert_(not np.may_share_memory(self.a, self.a.flatten()))
442
+
443
+ def test_matrix_memory_sharing(self):
444
+ assert_(np.may_share_memory(self.m, self.m.ravel()))
445
+ assert_(not np.may_share_memory(self.m, self.m.flatten()))
446
+
447
+ def test_expand_dims_matrix(self):
448
+ # matrices are always 2d - so expand_dims only makes sense when the
449
+ # type is changed away from matrix.
450
+ a = np.arange(10).reshape((2, 5)).view(np.matrix)
451
+ expanded = np.expand_dims(a, axis=1)
452
+ assert_equal(expanded.ndim, 3)
453
+ assert_(not isinstance(expanded, np.matrix))
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_interaction.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests of interaction of matrix with other parts of numpy.
2
+
3
+ Note that tests with MaskedArray and linalg are done in separate files.
4
+ """
5
+ import pytest
6
+
7
+ import textwrap
8
+ import warnings
9
+
10
+ import numpy as np
11
+ from numpy.testing import (assert_, assert_equal, assert_raises,
12
+ assert_raises_regex, assert_array_equal,
13
+ assert_almost_equal, assert_array_almost_equal)
14
+
15
+
16
+ def test_fancy_indexing():
17
+ # The matrix class messes with the shape. While this is always
18
+ # weird (getitem is not used, it does not have setitem nor knows
19
+ # about fancy indexing), this tests gh-3110
20
+ # 2018-04-29: moved here from core.tests.test_index.
21
+ m = np.matrix([[1, 2], [3, 4]])
22
+
23
+ assert_(isinstance(m[[0, 1, 0], :], np.matrix))
24
+
25
+ # gh-3110. Note the transpose currently because matrices do *not*
26
+ # support dimension fixing for fancy indexing correctly.
27
+ x = np.asmatrix(np.arange(50).reshape(5, 10))
28
+ assert_equal(x[:2, np.array(-1)], x[:2, -1].T)
29
+
30
+
31
+ def test_polynomial_mapdomain():
32
+ # test that polynomial preserved matrix subtype.
33
+ # 2018-04-29: moved here from polynomial.tests.polyutils.
34
+ dom1 = [0, 4]
35
+ dom2 = [1, 3]
36
+ x = np.matrix([dom1, dom1])
37
+ res = np.polynomial.polyutils.mapdomain(x, dom1, dom2)
38
+ assert_(isinstance(res, np.matrix))
39
+
40
+
41
+ def test_sort_matrix_none():
42
+ # 2018-04-29: moved here from core.tests.test_multiarray
43
+ a = np.matrix([[2, 1, 0]])
44
+ actual = np.sort(a, axis=None)
45
+ expected = np.matrix([[0, 1, 2]])
46
+ assert_equal(actual, expected)
47
+ assert_(type(expected) is np.matrix)
48
+
49
+
50
+ def test_partition_matrix_none():
51
+ # gh-4301
52
+ # 2018-04-29: moved here from core.tests.test_multiarray
53
+ a = np.matrix([[2, 1, 0]])
54
+ actual = np.partition(a, 1, axis=None)
55
+ expected = np.matrix([[0, 1, 2]])
56
+ assert_equal(actual, expected)
57
+ assert_(type(expected) is np.matrix)
58
+
59
+
60
+ def test_dot_scalar_and_matrix_of_objects():
61
+ # Ticket #2469
62
+ # 2018-04-29: moved here from core.tests.test_multiarray
63
+ arr = np.matrix([1, 2], dtype=object)
64
+ desired = np.matrix([[3, 6]], dtype=object)
65
+ assert_equal(np.dot(arr, 3), desired)
66
+ assert_equal(np.dot(3, arr), desired)
67
+
68
+
69
+ def test_inner_scalar_and_matrix():
70
+ # 2018-04-29: moved here from core.tests.test_multiarray
71
+ for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
72
+ sca = np.array(3, dtype=dt)[()]
73
+ arr = np.matrix([[1, 2], [3, 4]], dtype=dt)
74
+ desired = np.matrix([[3, 6], [9, 12]], dtype=dt)
75
+ assert_equal(np.inner(arr, sca), desired)
76
+ assert_equal(np.inner(sca, arr), desired)
77
+
78
+
79
+ def test_inner_scalar_and_matrix_of_objects():
80
+ # Ticket #4482
81
+ # 2018-04-29: moved here from core.tests.test_multiarray
82
+ arr = np.matrix([1, 2], dtype=object)
83
+ desired = np.matrix([[3, 6]], dtype=object)
84
+ assert_equal(np.inner(arr, 3), desired)
85
+ assert_equal(np.inner(3, arr), desired)
86
+
87
+
88
+ def test_iter_allocate_output_subtype():
89
+ # Make sure that the subtype with priority wins
90
+ # 2018-04-29: moved here from core.tests.test_nditer, given the
91
+ # matrix specific shape test.
92
+
93
+ # matrix vs ndarray
94
+ a = np.matrix([[1, 2], [3, 4]])
95
+ b = np.arange(4).reshape(2, 2).T
96
+ i = np.nditer([a, b, None], [],
97
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
98
+ assert_(type(i.operands[2]) is np.matrix)
99
+ assert_(type(i.operands[2]) is not np.ndarray)
100
+ assert_equal(i.operands[2].shape, (2, 2))
101
+
102
+ # matrix always wants things to be 2D
103
+ b = np.arange(4).reshape(1, 2, 2)
104
+ assert_raises(RuntimeError, np.nditer, [a, b, None], [],
105
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
106
+ # but if subtypes are disabled, the result can still work
107
+ i = np.nditer([a, b, None], [],
108
+ [['readonly'], ['readonly'],
109
+ ['writeonly', 'allocate', 'no_subtype']])
110
+ assert_(type(i.operands[2]) is np.ndarray)
111
+ assert_(type(i.operands[2]) is not np.matrix)
112
+ assert_equal(i.operands[2].shape, (1, 2, 2))
113
+
114
+
115
+ def like_function():
116
+ # 2018-04-29: moved here from core.tests.test_numeric
117
+ a = np.matrix([[1, 2], [3, 4]])
118
+ for like_function in np.zeros_like, np.ones_like, np.empty_like:
119
+ b = like_function(a)
120
+ assert_(type(b) is np.matrix)
121
+
122
+ c = like_function(a, subok=False)
123
+ assert_(type(c) is not np.matrix)
124
+
125
+
126
+ def test_array_astype():
127
+ # 2018-04-29: copied here from core.tests.test_api
128
+ # subok=True passes through a matrix
129
+ a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4')
130
+ b = a.astype('f4', subok=True, copy=False)
131
+ assert_(a is b)
132
+
133
+ # subok=True is default, and creates a subtype on a cast
134
+ b = a.astype('i4', copy=False)
135
+ assert_equal(a, b)
136
+ assert_equal(type(b), np.matrix)
137
+
138
+ # subok=False never returns a matrix
139
+ b = a.astype('f4', subok=False, copy=False)
140
+ assert_equal(a, b)
141
+ assert_(not (a is b))
142
+ assert_(type(b) is not np.matrix)
143
+
144
+
145
+ def test_stack():
146
+ # 2018-04-29: copied here from core.tests.test_shape_base
147
+ # check np.matrix cannot be stacked
148
+ m = np.matrix([[1, 2], [3, 4]])
149
+ assert_raises_regex(ValueError, 'shape too large to be a matrix',
150
+ np.stack, [m, m])
151
+
152
+
153
+ def test_object_scalar_multiply():
154
+ # Tickets #2469 and #4482
155
+ # 2018-04-29: moved here from core.tests.test_ufunc
156
+ arr = np.matrix([1, 2], dtype=object)
157
+ desired = np.matrix([[3, 6]], dtype=object)
158
+ assert_equal(np.multiply(arr, 3), desired)
159
+ assert_equal(np.multiply(3, arr), desired)
160
+
161
+
162
+ def test_nanfunctions_matrices():
163
+ # Check that it works and that type and
164
+ # shape are preserved
165
+ # 2018-04-29: moved here from core.tests.test_nanfunctions
166
+ mat = np.matrix(np.eye(3))
167
+ for f in [np.nanmin, np.nanmax]:
168
+ res = f(mat, axis=0)
169
+ assert_(isinstance(res, np.matrix))
170
+ assert_(res.shape == (1, 3))
171
+ res = f(mat, axis=1)
172
+ assert_(isinstance(res, np.matrix))
173
+ assert_(res.shape == (3, 1))
174
+ res = f(mat)
175
+ assert_(np.isscalar(res))
176
+ # check that rows of nan are dealt with for subclasses (#4628)
177
+ mat[1] = np.nan
178
+ for f in [np.nanmin, np.nanmax]:
179
+ with warnings.catch_warnings(record=True) as w:
180
+ warnings.simplefilter('always')
181
+ res = f(mat, axis=0)
182
+ assert_(isinstance(res, np.matrix))
183
+ assert_(not np.any(np.isnan(res)))
184
+ assert_(len(w) == 0)
185
+
186
+ with warnings.catch_warnings(record=True) as w:
187
+ warnings.simplefilter('always')
188
+ res = f(mat, axis=1)
189
+ assert_(isinstance(res, np.matrix))
190
+ assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
191
+ and not np.isnan(res[2, 0]))
192
+ assert_(len(w) == 1, 'no warning raised')
193
+ assert_(issubclass(w[0].category, RuntimeWarning))
194
+
195
+ with warnings.catch_warnings(record=True) as w:
196
+ warnings.simplefilter('always')
197
+ res = f(mat)
198
+ assert_(np.isscalar(res))
199
+ assert_(res != np.nan)
200
+ assert_(len(w) == 0)
201
+
202
+
203
+ def test_nanfunctions_matrices_general():
204
+ # Check that it works and that type and
205
+ # shape are preserved
206
+ # 2018-04-29: moved here from core.tests.test_nanfunctions
207
+ mat = np.matrix(np.eye(3))
208
+ for f in (np.nanargmin, np.nanargmax, np.nansum, np.nanprod,
209
+ np.nanmean, np.nanvar, np.nanstd):
210
+ res = f(mat, axis=0)
211
+ assert_(isinstance(res, np.matrix))
212
+ assert_(res.shape == (1, 3))
213
+ res = f(mat, axis=1)
214
+ assert_(isinstance(res, np.matrix))
215
+ assert_(res.shape == (3, 1))
216
+ res = f(mat)
217
+ assert_(np.isscalar(res))
218
+
219
+ for f in np.nancumsum, np.nancumprod:
220
+ res = f(mat, axis=0)
221
+ assert_(isinstance(res, np.matrix))
222
+ assert_(res.shape == (3, 3))
223
+ res = f(mat, axis=1)
224
+ assert_(isinstance(res, np.matrix))
225
+ assert_(res.shape == (3, 3))
226
+ res = f(mat)
227
+ assert_(isinstance(res, np.matrix))
228
+ assert_(res.shape == (1, 3*3))
229
+
230
+
231
+ def test_average_matrix():
232
+ # 2018-04-29: moved here from core.tests.test_function_base.
233
+ y = np.matrix(np.random.rand(5, 5))
234
+ assert_array_equal(y.mean(0), np.average(y, 0))
235
+
236
+ a = np.matrix([[1, 2], [3, 4]])
237
+ w = np.matrix([[1, 2], [3, 4]])
238
+
239
+ r = np.average(a, axis=0, weights=w)
240
+ assert_equal(type(r), np.matrix)
241
+ assert_equal(r, [[2.5, 10.0/3]])
242
+
243
+
244
+ def test_trapz_matrix():
245
+ # Test to make sure matrices give the same answer as ndarrays
246
+ # 2018-04-29: moved here from core.tests.test_function_base.
247
+ x = np.linspace(0, 5)
248
+ y = x * x
249
+ r = np.trapz(y, x)
250
+ mx = np.matrix(x)
251
+ my = np.matrix(y)
252
+ mr = np.trapz(my, mx)
253
+ assert_almost_equal(mr, r)
254
+
255
+
256
+ def test_ediff1d_matrix():
257
+ # 2018-04-29: moved here from core.tests.test_arraysetops.
258
+ assert(isinstance(np.ediff1d(np.matrix(1)), np.matrix))
259
+ assert(isinstance(np.ediff1d(np.matrix(1), to_begin=1), np.matrix))
260
+
261
+
262
+ def test_apply_along_axis_matrix():
263
+ # this test is particularly malicious because matrix
264
+ # refuses to become 1d
265
+ # 2018-04-29: moved here from core.tests.test_shape_base.
266
+ def double(row):
267
+ return row * 2
268
+
269
+ m = np.matrix([[0, 1], [2, 3]])
270
+ expected = np.matrix([[0, 2], [4, 6]])
271
+
272
+ result = np.apply_along_axis(double, 0, m)
273
+ assert_(isinstance(result, np.matrix))
274
+ assert_array_equal(result, expected)
275
+
276
+ result = np.apply_along_axis(double, 1, m)
277
+ assert_(isinstance(result, np.matrix))
278
+ assert_array_equal(result, expected)
279
+
280
+
281
+ def test_kron_matrix():
282
+ # 2018-04-29: moved here from core.tests.test_shape_base.
283
+ a = np.ones([2, 2])
284
+ m = np.asmatrix(a)
285
+ assert_equal(type(np.kron(a, a)), np.ndarray)
286
+ assert_equal(type(np.kron(m, m)), np.matrix)
287
+ assert_equal(type(np.kron(a, m)), np.matrix)
288
+ assert_equal(type(np.kron(m, a)), np.matrix)
289
+
290
+
291
+ class TestConcatenatorMatrix:
292
+ # 2018-04-29: moved here from core.tests.test_index_tricks.
293
+ def test_matrix(self):
294
+ a = [1, 2]
295
+ b = [3, 4]
296
+
297
+ ab_r = np.r_['r', a, b]
298
+ ab_c = np.r_['c', a, b]
299
+
300
+ assert_equal(type(ab_r), np.matrix)
301
+ assert_equal(type(ab_c), np.matrix)
302
+
303
+ assert_equal(np.array(ab_r), [[1, 2, 3, 4]])
304
+ assert_equal(np.array(ab_c), [[1], [2], [3], [4]])
305
+
306
+ assert_raises(ValueError, lambda: np.r_['rc', a, b])
307
+
308
+ def test_matrix_scalar(self):
309
+ r = np.r_['r', [1, 2], 3]
310
+ assert_equal(type(r), np.matrix)
311
+ assert_equal(np.array(r), [[1, 2, 3]])
312
+
313
+ def test_matrix_builder(self):
314
+ a = np.array([1])
315
+ b = np.array([2])
316
+ c = np.array([3])
317
+ d = np.array([4])
318
+ actual = np.r_['a, b; c, d']
319
+ expected = np.bmat([[a, b], [c, d]])
320
+
321
+ assert_equal(actual, expected)
322
+ assert_equal(type(actual), type(expected))
323
+
324
+
325
+ def test_array_equal_error_message_matrix():
326
+ # 2018-04-29: moved here from testing.tests.test_utils.
327
+ with pytest.raises(AssertionError) as exc_info:
328
+ assert_equal(np.array([1, 2]), np.matrix([1, 2]))
329
+ msg = str(exc_info.value)
330
+ msg_reference = textwrap.dedent("""\
331
+
332
+ Arrays are not equal
333
+
334
+ (shapes (2,), (1, 2) mismatch)
335
+ x: array([1, 2])
336
+ y: matrix([[1, 2]])""")
337
+ assert_equal(msg, msg_reference)
338
+
339
+
340
+ def test_array_almost_equal_matrix():
341
+ # Matrix slicing keeps things 2-D, while array does not necessarily.
342
+ # See gh-8452.
343
+ # 2018-04-29: moved here from testing.tests.test_utils.
344
+ m1 = np.matrix([[1., 2.]])
345
+ m2 = np.matrix([[1., np.nan]])
346
+ m3 = np.matrix([[1., -np.inf]])
347
+ m4 = np.matrix([[np.nan, np.inf]])
348
+ m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
349
+ for assert_func in assert_array_almost_equal, assert_almost_equal:
350
+ for m in m1, m2, m3, m4, m5:
351
+ assert_func(m, m)
352
+ a = np.array(m)
353
+ assert_func(a, m)
354
+ assert_func(m, a)
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_matrix_linalg.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for linalg module using the matrix class."""
2
+ import numpy as np
3
+
4
+ from numpy.linalg.tests.test_linalg import (
5
+ LinalgCase, apply_tag, TestQR as _TestQR, LinalgTestCase,
6
+ _TestNorm2D, _TestNormDoubleBase, _TestNormSingleBase, _TestNormInt64Base,
7
+ SolveCases, InvCases, EigvalsCases, EigCases, SVDCases, CondCases,
8
+ PinvCases, DetCases, LstsqCases)
9
+
10
+
11
+ CASES = []
12
+
13
+ # square test cases
14
+ CASES += apply_tag('square', [
15
+ LinalgCase("0x0_matrix",
16
+ np.empty((0, 0), dtype=np.double).view(np.matrix),
17
+ np.empty((0, 1), dtype=np.double).view(np.matrix),
18
+ tags={'size-0'}),
19
+ LinalgCase("matrix_b_only",
20
+ np.array([[1., 2.], [3., 4.]]),
21
+ np.matrix([2., 1.]).T),
22
+ LinalgCase("matrix_a_and_b",
23
+ np.matrix([[1., 2.], [3., 4.]]),
24
+ np.matrix([2., 1.]).T),
25
+ ])
26
+
27
+ # hermitian test-cases
28
+ CASES += apply_tag('hermitian', [
29
+ LinalgCase("hmatrix_a_and_b",
30
+ np.matrix([[1., 2.], [2., 1.]]),
31
+ None),
32
+ ])
33
+ # No need to make generalized or strided cases for matrices.
34
+
35
+
36
+ class MatrixTestCase(LinalgTestCase):
37
+ TEST_CASES = CASES
38
+
39
+
40
+ class TestSolveMatrix(SolveCases, MatrixTestCase):
41
+ pass
42
+
43
+
44
+ class TestInvMatrix(InvCases, MatrixTestCase):
45
+ pass
46
+
47
+
48
+ class TestEigvalsMatrix(EigvalsCases, MatrixTestCase):
49
+ pass
50
+
51
+
52
+ class TestEigMatrix(EigCases, MatrixTestCase):
53
+ pass
54
+
55
+
56
+ class TestSVDMatrix(SVDCases, MatrixTestCase):
57
+ pass
58
+
59
+
60
+ class TestCondMatrix(CondCases, MatrixTestCase):
61
+ pass
62
+
63
+
64
+ class TestPinvMatrix(PinvCases, MatrixTestCase):
65
+ pass
66
+
67
+
68
+ class TestDetMatrix(DetCases, MatrixTestCase):
69
+ pass
70
+
71
+
72
+ class TestLstsqMatrix(LstsqCases, MatrixTestCase):
73
+ pass
74
+
75
+
76
+ class _TestNorm2DMatrix(_TestNorm2D):
77
+ array = np.matrix
78
+
79
+
80
+ class TestNormDoubleMatrix(_TestNorm2DMatrix, _TestNormDoubleBase):
81
+ pass
82
+
83
+
84
+ class TestNormSingleMatrix(_TestNorm2DMatrix, _TestNormSingleBase):
85
+ pass
86
+
87
+
88
+ class TestNormInt64Matrix(_TestNorm2DMatrix, _TestNormInt64Base):
89
+ pass
90
+
91
+
92
+ class TestQRMatrix(_TestQR):
93
+ array = np.matrix
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_multiarray.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_, assert_equal, assert_array_equal
3
+
4
+ class TestView:
5
+ def test_type(self):
6
+ x = np.array([1, 2, 3])
7
+ assert_(isinstance(x.view(np.matrix), np.matrix))
8
+
9
+ def test_keywords(self):
10
+ x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
11
+ # We must be specific about the endianness here:
12
+ y = x.view(dtype='<i2', type=np.matrix)
13
+ assert_array_equal(y, [[513]])
14
+
15
+ assert_(isinstance(y, np.matrix))
16
+ assert_equal(y.dtype, np.dtype('<i2'))
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_numeric.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_equal
3
+
4
+ class TestDot:
5
+ def test_matscalar(self):
6
+ b1 = np.matrix(np.ones((3, 3), dtype=complex))
7
+ assert_equal(b1*1.0, b1)
8
+
9
+
10
+ def test_diagonal():
11
+ b1 = np.matrix([[1,2],[3,4]])
12
+ diag_b1 = np.matrix([[1, 4]])
13
+ array_b1 = np.array([1, 4])
14
+
15
+ assert_equal(b1.diagonal(), diag_b1)
16
+ assert_equal(np.diagonal(b1), array_b1)
17
+ assert_equal(np.diag(b1), array_b1)
venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_regression.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_, assert_equal, assert_raises
3
+
4
+
5
+ class TestRegression:
6
+ def test_kron_matrix(self):
7
+ # Ticket #71
8
+ x = np.matrix('[1 0; 1 0]')
9
+ assert_equal(type(np.kron(x, x)), type(x))
10
+
11
+ def test_matrix_properties(self):
12
+ # Ticket #125
13
+ a = np.matrix([1.0], dtype=float)
14
+ assert_(type(a.real) is np.matrix)
15
+ assert_(type(a.imag) is np.matrix)
16
+ c, d = np.matrix([0.0]).nonzero()
17
+ assert_(type(c) is np.ndarray)
18
+ assert_(type(d) is np.ndarray)
19
+
20
+ def test_matrix_multiply_by_1d_vector(self):
21
+ # Ticket #473
22
+ def mul():
23
+ np.mat(np.eye(2))*np.ones(2)
24
+
25
+ assert_raises(ValueError, mul)
26
+
27
+ def test_matrix_std_argmax(self):
28
+ # Ticket #83
29
+ x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
30
+ assert_equal(x.std().shape, ())
31
+ assert_equal(x.argmax().shape, ())
venv/lib/python3.10/site-packages/numpy/typing/__init__.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============================
3
+ Typing (:mod:`numpy.typing`)
4
+ ============================
5
+
6
+ .. versionadded:: 1.20
7
+
8
+ Large parts of the NumPy API have :pep:`484`-style type annotations. In
9
+ addition a number of type aliases are available to users, most prominently
10
+ the two below:
11
+
12
+ - `ArrayLike`: objects that can be converted to arrays
13
+ - `DTypeLike`: objects that can be converted to dtypes
14
+
15
+ .. _typing-extensions: https://pypi.org/project/typing-extensions/
16
+
17
+ Mypy plugin
18
+ -----------
19
+
20
+ .. versionadded:: 1.21
21
+
22
+ .. automodule:: numpy.typing.mypy_plugin
23
+
24
+ .. currentmodule:: numpy.typing
25
+
26
+ Differences from the runtime NumPy API
27
+ --------------------------------------
28
+
29
+ NumPy is very flexible. Trying to describe the full range of
30
+ possibilities statically would result in types that are not very
31
+ helpful. For that reason, the typed NumPy API is often stricter than
32
+ the runtime NumPy API. This section describes some notable
33
+ differences.
34
+
35
+ ArrayLike
36
+ ~~~~~~~~~
37
+
38
+ The `ArrayLike` type tries to avoid creating object arrays. For
39
+ example,
40
+
41
+ .. code-block:: python
42
+
43
+ >>> np.array(x**2 for x in range(10))
44
+ array(<generator object <genexpr> at ...>, dtype=object)
45
+
46
+ is valid NumPy code which will create a 0-dimensional object
47
+ array. Type checkers will complain about the above example when using
48
+ the NumPy types however. If you really intended to do the above, then
49
+ you can either use a ``# type: ignore`` comment:
50
+
51
+ .. code-block:: python
52
+
53
+ >>> np.array(x**2 for x in range(10)) # type: ignore
54
+
55
+ or explicitly type the array like object as `~typing.Any`:
56
+
57
+ .. code-block:: python
58
+
59
+ >>> from typing import Any
60
+ >>> array_like: Any = (x**2 for x in range(10))
61
+ >>> np.array(array_like)
62
+ array(<generator object <genexpr> at ...>, dtype=object)
63
+
64
+ ndarray
65
+ ~~~~~~~
66
+
67
+ It's possible to mutate the dtype of an array at runtime. For example,
68
+ the following code is valid:
69
+
70
+ .. code-block:: python
71
+
72
+ >>> x = np.array([1, 2])
73
+ >>> x.dtype = np.bool_
74
+
75
+ This sort of mutation is not allowed by the types. Users who want to
76
+ write statically typed code should instead use the `numpy.ndarray.view`
77
+ method to create a view of the array with a different dtype.
78
+
79
+ DTypeLike
80
+ ~~~~~~~~~
81
+
82
+ The `DTypeLike` type tries to avoid creation of dtype objects using
83
+ dictionary of fields like below:
84
+
85
+ .. code-block:: python
86
+
87
+ >>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
88
+
89
+ Although this is valid NumPy code, the type checker will complain about it,
90
+ since its usage is discouraged.
91
+ Please see : :ref:`Data type objects <arrays.dtypes>`
92
+
93
+ Number precision
94
+ ~~~~~~~~~~~~~~~~
95
+
96
+ The precision of `numpy.number` subclasses is treated as a covariant generic
97
+ parameter (see :class:`~NBitBase`), simplifying the annotating of processes
98
+ involving precision-based casting.
99
+
100
+ .. code-block:: python
101
+
102
+ >>> from typing import TypeVar
103
+ >>> import numpy as np
104
+ >>> import numpy.typing as npt
105
+
106
+ >>> T = TypeVar("T", bound=npt.NBitBase)
107
+ >>> def func(a: "np.floating[T]", b: "np.floating[T]") -> "np.floating[T]":
108
+ ... ...
109
+
110
+ Consequently, the likes of `~numpy.float16`, `~numpy.float32` and
111
+ `~numpy.float64` are still sub-types of `~numpy.floating`, but, contrary to
112
+ runtime, they're not necessarily considered as sub-classes.
113
+
114
+ Timedelta64
115
+ ~~~~~~~~~~~
116
+
117
+ The `~numpy.timedelta64` class is not considered a subclass of
118
+ `~numpy.signedinteger`, the former only inheriting from `~numpy.generic`
119
+ while static type checking.
120
+
121
+ 0D arrays
122
+ ~~~~~~~~~
123
+
124
+ During runtime numpy aggressively casts any passed 0D arrays into their
125
+ corresponding `~numpy.generic` instance. Until the introduction of shape
126
+ typing (see :pep:`646`) it is unfortunately not possible to make the
127
+ necessary distinction between 0D and >0D arrays. While thus not strictly
128
+ correct, all operations are that can potentially perform a 0D-array -> scalar
129
+ cast are currently annotated as exclusively returning an `ndarray`.
130
+
131
+ If it is known in advance that an operation _will_ perform a
132
+ 0D-array -> scalar cast, then one can consider manually remedying the
133
+ situation with either `typing.cast` or a ``# type: ignore`` comment.
134
+
135
+ Record array dtypes
136
+ ~~~~~~~~~~~~~~~~~~~
137
+
138
+ The dtype of `numpy.recarray`, and the `numpy.rec` functions in general,
139
+ can be specified in one of two ways:
140
+
141
+ * Directly via the ``dtype`` argument.
142
+ * With up to five helper arguments that operate via `numpy.format_parser`:
143
+ ``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``.
144
+
145
+ These two approaches are currently typed as being mutually exclusive,
146
+ *i.e.* if ``dtype`` is specified than one may not specify ``formats``.
147
+ While this mutual exclusivity is not (strictly) enforced during runtime,
148
+ combining both dtype specifiers can lead to unexpected or even downright
149
+ buggy behavior.
150
+
151
+ API
152
+ ---
153
+
154
+ """
155
+ # NOTE: The API section will be appended with additional entries
156
+ # further down in this file
157
+
158
+ from numpy._typing import (
159
+ ArrayLike,
160
+ DTypeLike,
161
+ NBitBase,
162
+ NDArray,
163
+ )
164
+
165
+ __all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
166
+
167
+ if __doc__ is not None:
168
+ from numpy._typing._add_docstring import _docstrings
169
+ __doc__ += _docstrings
170
+ __doc__ += '\n.. autoclass:: numpy.typing.NBitBase\n'
171
+ del _docstrings
172
+
173
+ from numpy._pytesttester import PytestTester
174
+ test = PytestTester(__name__)
175
+ del PytestTester
venv/lib/python3.10/site-packages/numpy/typing/mypy_plugin.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A mypy_ plugin for managing a number of platform-specific annotations.
2
+ Its functionality can be split into three distinct parts:
3
+
4
+ * Assigning the (platform-dependent) precisions of certain `~numpy.number`
5
+ subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
6
+ `~numpy.longlong`. See the documentation on
7
+ :ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
8
+ of the affected classes. Without the plugin the precision of all relevant
9
+ classes will be inferred as `~typing.Any`.
10
+ * Removing all extended-precision `~numpy.number` subclasses that are
11
+ unavailable for the platform in question. Most notably this includes the
12
+ likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
13
+ extended-precision types will, as far as mypy is concerned, be available
14
+ to all platforms.
15
+ * Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
16
+ Without the plugin the type will default to `ctypes.c_int64`.
17
+
18
+ .. versionadded:: 1.22
19
+
20
+ Examples
21
+ --------
22
+ To enable the plugin, one must add it to their mypy `configuration file`_:
23
+
24
+ .. code-block:: ini
25
+
26
+ [mypy]
27
+ plugins = numpy.typing.mypy_plugin
28
+
29
+ .. _mypy: http://mypy-lang.org/
30
+ .. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
31
+
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from collections.abc import Iterable
37
+ from typing import Final, TYPE_CHECKING, Callable
38
+
39
+ import numpy as np
40
+
41
+ try:
42
+ import mypy.types
43
+ from mypy.types import Type
44
+ from mypy.plugin import Plugin, AnalyzeTypeContext
45
+ from mypy.nodes import MypyFile, ImportFrom, Statement
46
+ from mypy.build import PRI_MED
47
+
48
+ _HookFunc = Callable[[AnalyzeTypeContext], Type]
49
+ MYPY_EX: None | ModuleNotFoundError = None
50
+ except ModuleNotFoundError as ex:
51
+ MYPY_EX = ex
52
+
53
+ __all__: list[str] = []
54
+
55
+
56
+ def _get_precision_dict() -> dict[str, str]:
57
+ names = [
58
+ ("_NBitByte", np.byte),
59
+ ("_NBitShort", np.short),
60
+ ("_NBitIntC", np.intc),
61
+ ("_NBitIntP", np.intp),
62
+ ("_NBitInt", np.int_),
63
+ ("_NBitLongLong", np.longlong),
64
+
65
+ ("_NBitHalf", np.half),
66
+ ("_NBitSingle", np.single),
67
+ ("_NBitDouble", np.double),
68
+ ("_NBitLongDouble", np.longdouble),
69
+ ]
70
+ ret = {}
71
+ for name, typ in names:
72
+ n: int = 8 * typ().dtype.itemsize
73
+ ret[f'numpy._typing._nbit.{name}'] = f"numpy._{n}Bit"
74
+ return ret
75
+
76
+
77
+ def _get_extended_precision_list() -> list[str]:
78
+ extended_names = [
79
+ "uint128",
80
+ "uint256",
81
+ "int128",
82
+ "int256",
83
+ "float80",
84
+ "float96",
85
+ "float128",
86
+ "float256",
87
+ "complex160",
88
+ "complex192",
89
+ "complex256",
90
+ "complex512",
91
+ ]
92
+ return [i for i in extended_names if hasattr(np, i)]
93
+
94
+
95
+ def _get_c_intp_name() -> str:
96
+ # Adapted from `np.core._internal._getintp_ctype`
97
+ char = np.dtype('p').char
98
+ if char == 'i':
99
+ return "c_int"
100
+ elif char == 'l':
101
+ return "c_long"
102
+ elif char == 'q':
103
+ return "c_longlong"
104
+ else:
105
+ return "c_long"
106
+
107
+
108
+ #: A dictionary mapping type-aliases in `numpy._typing._nbit` to
109
+ #: concrete `numpy.typing.NBitBase` subclasses.
110
+ _PRECISION_DICT: Final = _get_precision_dict()
111
+
112
+ #: A list with the names of all extended precision `np.number` subclasses.
113
+ _EXTENDED_PRECISION_LIST: Final = _get_extended_precision_list()
114
+
115
+ #: The name of the ctypes quivalent of `np.intp`
116
+ _C_INTP: Final = _get_c_intp_name()
117
+
118
+
119
+ def _hook(ctx: AnalyzeTypeContext) -> Type:
120
+ """Replace a type-alias with a concrete ``NBitBase`` subclass."""
121
+ typ, _, api = ctx
122
+ name = typ.name.split(".")[-1]
123
+ name_new = _PRECISION_DICT[f"numpy._typing._nbit.{name}"]
124
+ return api.named_type(name_new)
125
+
126
+
127
+ if TYPE_CHECKING or MYPY_EX is None:
128
+ def _index(iterable: Iterable[Statement], id: str) -> int:
129
+ """Identify the first ``ImportFrom`` instance the specified `id`."""
130
+ for i, value in enumerate(iterable):
131
+ if getattr(value, "id", None) == id:
132
+ return i
133
+ raise ValueError("Failed to identify a `ImportFrom` instance "
134
+ f"with the following id: {id!r}")
135
+
136
+ def _override_imports(
137
+ file: MypyFile,
138
+ module: str,
139
+ imports: list[tuple[str, None | str]],
140
+ ) -> None:
141
+ """Override the first `module`-based import with new `imports`."""
142
+ # Construct a new `from module import y` statement
143
+ import_obj = ImportFrom(module, 0, names=imports)
144
+ import_obj.is_top_level = True
145
+
146
+ # Replace the first `module`-based import statement with `import_obj`
147
+ for lst in [file.defs, file.imports]: # type: list[Statement]
148
+ i = _index(lst, module)
149
+ lst[i] = import_obj
150
+
151
+ class _NumpyPlugin(Plugin):
152
+ """A mypy plugin for handling versus numpy-specific typing tasks."""
153
+
154
+ def get_type_analyze_hook(self, fullname: str) -> None | _HookFunc:
155
+ """Set the precision of platform-specific `numpy.number`
156
+ subclasses.
157
+
158
+ For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.
159
+ """
160
+ if fullname in _PRECISION_DICT:
161
+ return _hook
162
+ return None
163
+
164
+ def get_additional_deps(
165
+ self, file: MypyFile
166
+ ) -> list[tuple[int, str, int]]:
167
+ """Handle all import-based overrides.
168
+
169
+ * Import platform-specific extended-precision `numpy.number`
170
+ subclasses (*e.g.* `numpy.float96`, `numpy.float128` and
171
+ `numpy.complex256`).
172
+ * Import the appropriate `ctypes` equivalent to `numpy.intp`.
173
+
174
+ """
175
+ ret = [(PRI_MED, file.fullname, -1)]
176
+
177
+ if file.fullname == "numpy":
178
+ _override_imports(
179
+ file, "numpy._typing._extended_precision",
180
+ imports=[(v, v) for v in _EXTENDED_PRECISION_LIST],
181
+ )
182
+ elif file.fullname == "numpy.ctypeslib":
183
+ _override_imports(
184
+ file, "ctypes",
185
+ imports=[(_C_INTP, "_c_intp")],
186
+ )
187
+ return ret
188
+
189
+ def plugin(version: str) -> type[_NumpyPlugin]:
190
+ """An entry-point for mypy."""
191
+ return _NumpyPlugin
192
+
193
+ else:
194
+ def plugin(version: str) -> type[_NumpyPlugin]:
195
+ """An entry-point for mypy."""
196
+ raise MYPY_EX
venv/lib/python3.10/site-packages/numpy/typing/setup.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def configuration(parent_package='', top_path=None):
2
+ from numpy.distutils.misc_util import Configuration
3
+ config = Configuration('typing', parent_package, top_path)
4
+ config.add_subpackage('tests')
5
+ config.add_data_dir('tests/data')
6
+ return config
7
+
8
+
9
+ if __name__ == '__main__':
10
+ from numpy.distutils.core import setup
11
+ setup(configuration=configuration)
venv/lib/python3.10/site-packages/numpy/typing/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_isfile.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_runtime.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
venv/lib/python3.10/site-packages/numpy/typing/tests/__pycache__/test_typing.cpython-310.pyc ADDED
Binary file (7.37 kB). View file
 
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arithmetic.pyi ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import numpy as np
3
+
4
+ b_ = np.bool_()
5
+ dt = np.datetime64(0, "D")
6
+ td = np.timedelta64(0, "D")
7
+
8
+ AR_b: np.ndarray[Any, np.dtype[np.bool_]]
9
+ AR_u: np.ndarray[Any, np.dtype[np.uint32]]
10
+ AR_i: np.ndarray[Any, np.dtype[np.int64]]
11
+ AR_f: np.ndarray[Any, np.dtype[np.float64]]
12
+ AR_c: np.ndarray[Any, np.dtype[np.complex128]]
13
+ AR_m: np.ndarray[Any, np.dtype[np.timedelta64]]
14
+ AR_M: np.ndarray[Any, np.dtype[np.datetime64]]
15
+
16
+ ANY: Any
17
+
18
+ AR_LIKE_b: list[bool]
19
+ AR_LIKE_u: list[np.uint32]
20
+ AR_LIKE_i: list[int]
21
+ AR_LIKE_f: list[float]
22
+ AR_LIKE_c: list[complex]
23
+ AR_LIKE_m: list[np.timedelta64]
24
+ AR_LIKE_M: list[np.datetime64]
25
+
26
+ # Array subtraction
27
+
28
+ # NOTE: mypys `NoReturn` errors are, unfortunately, not that great
29
+ _1 = AR_b - AR_LIKE_b # E: Need type annotation
30
+ _2 = AR_LIKE_b - AR_b # E: Need type annotation
31
+ AR_i - bytes() # E: No overload variant
32
+
33
+ AR_f - AR_LIKE_m # E: Unsupported operand types
34
+ AR_f - AR_LIKE_M # E: Unsupported operand types
35
+ AR_c - AR_LIKE_m # E: Unsupported operand types
36
+ AR_c - AR_LIKE_M # E: Unsupported operand types
37
+
38
+ AR_m - AR_LIKE_f # E: Unsupported operand types
39
+ AR_M - AR_LIKE_f # E: Unsupported operand types
40
+ AR_m - AR_LIKE_c # E: Unsupported operand types
41
+ AR_M - AR_LIKE_c # E: Unsupported operand types
42
+
43
+ AR_m - AR_LIKE_M # E: Unsupported operand types
44
+ AR_LIKE_m - AR_M # E: Unsupported operand types
45
+
46
+ # array floor division
47
+
48
+ AR_M // AR_LIKE_b # E: Unsupported operand types
49
+ AR_M // AR_LIKE_u # E: Unsupported operand types
50
+ AR_M // AR_LIKE_i # E: Unsupported operand types
51
+ AR_M // AR_LIKE_f # E: Unsupported operand types
52
+ AR_M // AR_LIKE_c # E: Unsupported operand types
53
+ AR_M // AR_LIKE_m # E: Unsupported operand types
54
+ AR_M // AR_LIKE_M # E: Unsupported operand types
55
+
56
+ AR_b // AR_LIKE_M # E: Unsupported operand types
57
+ AR_u // AR_LIKE_M # E: Unsupported operand types
58
+ AR_i // AR_LIKE_M # E: Unsupported operand types
59
+ AR_f // AR_LIKE_M # E: Unsupported operand types
60
+ AR_c // AR_LIKE_M # E: Unsupported operand types
61
+ AR_m // AR_LIKE_M # E: Unsupported operand types
62
+ AR_M // AR_LIKE_M # E: Unsupported operand types
63
+
64
+ _3 = AR_m // AR_LIKE_b # E: Need type annotation
65
+ AR_m // AR_LIKE_c # E: Unsupported operand types
66
+
67
+ AR_b // AR_LIKE_m # E: Unsupported operand types
68
+ AR_u // AR_LIKE_m # E: Unsupported operand types
69
+ AR_i // AR_LIKE_m # E: Unsupported operand types
70
+ AR_f // AR_LIKE_m # E: Unsupported operand types
71
+ AR_c // AR_LIKE_m # E: Unsupported operand types
72
+
73
+ # Array multiplication
74
+
75
+ AR_b *= AR_LIKE_u # E: incompatible type
76
+ AR_b *= AR_LIKE_i # E: incompatible type
77
+ AR_b *= AR_LIKE_f # E: incompatible type
78
+ AR_b *= AR_LIKE_c # E: incompatible type
79
+ AR_b *= AR_LIKE_m # E: incompatible type
80
+
81
+ AR_u *= AR_LIKE_i # E: incompatible type
82
+ AR_u *= AR_LIKE_f # E: incompatible type
83
+ AR_u *= AR_LIKE_c # E: incompatible type
84
+ AR_u *= AR_LIKE_m # E: incompatible type
85
+
86
+ AR_i *= AR_LIKE_f # E: incompatible type
87
+ AR_i *= AR_LIKE_c # E: incompatible type
88
+ AR_i *= AR_LIKE_m # E: incompatible type
89
+
90
+ AR_f *= AR_LIKE_c # E: incompatible type
91
+ AR_f *= AR_LIKE_m # E: incompatible type
92
+
93
+ # Array power
94
+
95
+ AR_b **= AR_LIKE_b # E: Invalid self argument
96
+ AR_b **= AR_LIKE_u # E: Invalid self argument
97
+ AR_b **= AR_LIKE_i # E: Invalid self argument
98
+ AR_b **= AR_LIKE_f # E: Invalid self argument
99
+ AR_b **= AR_LIKE_c # E: Invalid self argument
100
+
101
+ AR_u **= AR_LIKE_i # E: incompatible type
102
+ AR_u **= AR_LIKE_f # E: incompatible type
103
+ AR_u **= AR_LIKE_c # E: incompatible type
104
+
105
+ AR_i **= AR_LIKE_f # E: incompatible type
106
+ AR_i **= AR_LIKE_c # E: incompatible type
107
+
108
+ AR_f **= AR_LIKE_c # E: incompatible type
109
+
110
+ # Scalars
111
+
112
+ b_ - b_ # E: No overload variant
113
+
114
+ dt + dt # E: Unsupported operand types
115
+ td - dt # E: Unsupported operand types
116
+ td % 1 # E: Unsupported operand types
117
+ td / dt # E: No overload
118
+ td % dt # E: Unsupported operand types
119
+
120
+ -b_ # E: Unsupported operand type
121
+ +b_ # E: Unsupported operand type
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_constructors.pyi ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ a: np.ndarray
4
+ generator = (i for i in range(10))
5
+
6
+ np.require(a, requirements=1) # E: No overload variant
7
+ np.require(a, requirements="TEST") # E: incompatible type
8
+
9
+ np.zeros("test") # E: incompatible type
10
+ np.zeros() # E: require at least one argument
11
+
12
+ np.ones("test") # E: incompatible type
13
+ np.ones() # E: require at least one argument
14
+
15
+ np.array(0, float, True) # E: No overload variant
16
+
17
+ np.linspace(None, 'bob') # E: No overload variant
18
+ np.linspace(0, 2, num=10.0) # E: No overload variant
19
+ np.linspace(0, 2, endpoint='True') # E: No overload variant
20
+ np.linspace(0, 2, retstep=b'False') # E: No overload variant
21
+ np.linspace(0, 2, dtype=0) # E: No overload variant
22
+ np.linspace(0, 2, axis=None) # E: No overload variant
23
+
24
+ np.logspace(None, 'bob') # E: No overload variant
25
+ np.logspace(0, 2, base=None) # E: No overload variant
26
+
27
+ np.geomspace(None, 'bob') # E: No overload variant
28
+
29
+ np.stack(generator) # E: No overload variant
30
+ np.hstack({1, 2}) # E: No overload variant
31
+ np.vstack(1) # E: No overload variant
32
+
33
+ np.array([1], like=1) # E: No overload variant
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_like.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy._typing import ArrayLike
3
+
4
+
5
+ class A:
6
+ pass
7
+
8
+
9
+ x1: ArrayLike = (i for i in range(10)) # E: Incompatible types in assignment
10
+ x2: ArrayLike = A() # E: Incompatible types in assignment
11
+ x3: ArrayLike = {1: "foo", 2: "bar"} # E: Incompatible types in assignment
12
+
13
+ scalar = np.int64(1)
14
+ scalar.__array__(dtype=np.float64) # E: No overload variant
15
+ array = np.array([1])
16
+ array.__array__(dtype=np.float64) # E: No overload variant
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/array_pad.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import numpy.typing as npt
3
+
4
+ AR_i8: npt.NDArray[np.int64]
5
+
6
+ np.pad(AR_i8, 2, mode="bob") # E: No overload variant
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arrayprint.pyi ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any
3
+ import numpy as np
4
+
5
+ AR: np.ndarray
6
+ func1: Callable[[Any], str]
7
+ func2: Callable[[np.integer[Any]], str]
8
+
9
+ np.array2string(AR, style=None) # E: Unexpected keyword argument
10
+ np.array2string(AR, legacy="1.14") # E: incompatible type
11
+ np.array2string(AR, sign="*") # E: incompatible type
12
+ np.array2string(AR, floatmode="default") # E: incompatible type
13
+ np.array2string(AR, formatter={"A": func1}) # E: incompatible type
14
+ np.array2string(AR, formatter={"float": func2}) # E: Incompatible types
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/arrayterator.pyi ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import numpy as np
3
+
4
+ AR_i8: np.ndarray[Any, np.dtype[np.int64]]
5
+ ar_iter = np.lib.Arrayterator(AR_i8)
6
+
7
+ np.lib.Arrayterator(np.int64()) # E: incompatible type
8
+ ar_iter.shape = (10, 5) # E: is read-only
9
+ ar_iter[None] # E: Invalid index type
10
+ ar_iter[None, 1] # E: Invalid index type
11
+ ar_iter[np.intp()] # E: Invalid index type
12
+ ar_iter[np.intp(), ...] # E: Invalid index type
13
+ ar_iter[AR_i8] # E: Invalid index type
14
+ ar_iter[AR_i8, :] # E: Invalid index type
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/bitwise_ops.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ i8 = np.int64()
4
+ i4 = np.int32()
5
+ u8 = np.uint64()
6
+ b_ = np.bool_()
7
+ i = int()
8
+
9
+ f8 = np.float64()
10
+
11
+ b_ >> f8 # E: No overload variant
12
+ i8 << f8 # E: No overload variant
13
+ i | f8 # E: Unsupported operand types
14
+ i8 ^ f8 # E: No overload variant
15
+ u8 & f8 # E: No overload variant
16
+ ~f8 # E: Unsupported operand type
17
+
18
+ # mypys' error message for `NoReturn` is unfortunately pretty bad
19
+ # TODO: Re-enable this once we add support for numerical precision for `number`s
20
+ # a = u8 | 0 # E: Need type annotation
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/char.pyi ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import numpy.typing as npt
3
+
4
+ AR_U: npt.NDArray[np.str_]
5
+ AR_S: npt.NDArray[np.bytes_]
6
+
7
+ np.char.equal(AR_U, AR_S) # E: incompatible type
8
+
9
+ np.char.not_equal(AR_U, AR_S) # E: incompatible type
10
+
11
+ np.char.greater_equal(AR_U, AR_S) # E: incompatible type
12
+
13
+ np.char.less_equal(AR_U, AR_S) # E: incompatible type
14
+
15
+ np.char.greater(AR_U, AR_S) # E: incompatible type
16
+
17
+ np.char.less(AR_U, AR_S) # E: incompatible type
18
+
19
+ np.char.encode(AR_S) # E: incompatible type
20
+ np.char.decode(AR_U) # E: incompatible type
21
+
22
+ np.char.join(AR_U, b"_") # E: incompatible type
23
+ np.char.join(AR_S, "_") # E: incompatible type
24
+
25
+ np.char.ljust(AR_U, 5, fillchar=b"a") # E: incompatible type
26
+ np.char.ljust(AR_S, 5, fillchar="a") # E: incompatible type
27
+ np.char.rjust(AR_U, 5, fillchar=b"a") # E: incompatible type
28
+ np.char.rjust(AR_S, 5, fillchar="a") # E: incompatible type
29
+
30
+ np.char.lstrip(AR_U, chars=b"a") # E: incompatible type
31
+ np.char.lstrip(AR_S, chars="a") # E: incompatible type
32
+ np.char.strip(AR_U, chars=b"a") # E: incompatible type
33
+ np.char.strip(AR_S, chars="a") # E: incompatible type
34
+ np.char.rstrip(AR_U, chars=b"a") # E: incompatible type
35
+ np.char.rstrip(AR_S, chars="a") # E: incompatible type
36
+
37
+ np.char.partition(AR_U, b"a") # E: incompatible type
38
+ np.char.partition(AR_S, "a") # E: incompatible type
39
+ np.char.rpartition(AR_U, b"a") # E: incompatible type
40
+ np.char.rpartition(AR_S, "a") # E: incompatible type
41
+
42
+ np.char.replace(AR_U, b"_", b"-") # E: incompatible type
43
+ np.char.replace(AR_S, "_", "-") # E: incompatible type
44
+
45
+ np.char.split(AR_U, b"_") # E: incompatible type
46
+ np.char.split(AR_S, "_") # E: incompatible type
47
+ np.char.rsplit(AR_U, b"_") # E: incompatible type
48
+ np.char.rsplit(AR_S, "_") # E: incompatible type
49
+
50
+ np.char.count(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
51
+ np.char.count(AR_S, "a", end=9) # E: incompatible type
52
+
53
+ np.char.endswith(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
54
+ np.char.endswith(AR_S, "a", end=9) # E: incompatible type
55
+ np.char.startswith(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
56
+ np.char.startswith(AR_S, "a", end=9) # E: incompatible type
57
+
58
+ np.char.find(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
59
+ np.char.find(AR_S, "a", end=9) # E: incompatible type
60
+ np.char.rfind(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
61
+ np.char.rfind(AR_S, "a", end=9) # E: incompatible type
62
+
63
+ np.char.index(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
64
+ np.char.index(AR_S, "a", end=9) # E: incompatible type
65
+ np.char.rindex(AR_U, b"a", start=[1, 2, 3]) # E: incompatible type
66
+ np.char.rindex(AR_S, "a", end=9) # E: incompatible type
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/chararray.pyi ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from typing import Any
3
+
4
+ AR_U: np.chararray[Any, np.dtype[np.str_]]
5
+ AR_S: np.chararray[Any, np.dtype[np.bytes_]]
6
+
7
+ AR_S.encode() # E: Invalid self argument
8
+ AR_U.decode() # E: Invalid self argument
9
+
10
+ AR_U.join(b"_") # E: incompatible type
11
+ AR_S.join("_") # E: incompatible type
12
+
13
+ AR_U.ljust(5, fillchar=b"a") # E: incompatible type
14
+ AR_S.ljust(5, fillchar="a") # E: incompatible type
15
+ AR_U.rjust(5, fillchar=b"a") # E: incompatible type
16
+ AR_S.rjust(5, fillchar="a") # E: incompatible type
17
+
18
+ AR_U.lstrip(chars=b"a") # E: incompatible type
19
+ AR_S.lstrip(chars="a") # E: incompatible type
20
+ AR_U.strip(chars=b"a") # E: incompatible type
21
+ AR_S.strip(chars="a") # E: incompatible type
22
+ AR_U.rstrip(chars=b"a") # E: incompatible type
23
+ AR_S.rstrip(chars="a") # E: incompatible type
24
+
25
+ AR_U.partition(b"a") # E: incompatible type
26
+ AR_S.partition("a") # E: incompatible type
27
+ AR_U.rpartition(b"a") # E: incompatible type
28
+ AR_S.rpartition("a") # E: incompatible type
29
+
30
+ AR_U.replace(b"_", b"-") # E: incompatible type
31
+ AR_S.replace("_", "-") # E: incompatible type
32
+
33
+ AR_U.split(b"_") # E: incompatible type
34
+ AR_S.split("_") # E: incompatible type
35
+ AR_S.split(1) # E: incompatible type
36
+ AR_U.rsplit(b"_") # E: incompatible type
37
+ AR_S.rsplit("_") # E: incompatible type
38
+
39
+ AR_U.count(b"a", start=[1, 2, 3]) # E: incompatible type
40
+ AR_S.count("a", end=9) # E: incompatible type
41
+
42
+ AR_U.endswith(b"a", start=[1, 2, 3]) # E: incompatible type
43
+ AR_S.endswith("a", end=9) # E: incompatible type
44
+ AR_U.startswith(b"a", start=[1, 2, 3]) # E: incompatible type
45
+ AR_S.startswith("a", end=9) # E: incompatible type
46
+
47
+ AR_U.find(b"a", start=[1, 2, 3]) # E: incompatible type
48
+ AR_S.find("a", end=9) # E: incompatible type
49
+ AR_U.rfind(b"a", start=[1, 2, 3]) # E: incompatible type
50
+ AR_S.rfind("a", end=9) # E: incompatible type
51
+
52
+ AR_U.index(b"a", start=[1, 2, 3]) # E: incompatible type
53
+ AR_S.index("a", end=9) # E: incompatible type
54
+ AR_U.rindex(b"a", start=[1, 2, 3]) # E: incompatible type
55
+ AR_S.rindex("a", end=9) # E: incompatible type
56
+
57
+ AR_U == AR_S # E: Unsupported operand types
58
+ AR_U != AR_S # E: Unsupported operand types
59
+ AR_U >= AR_S # E: Unsupported operand types
60
+ AR_U <= AR_S # E: Unsupported operand types
61
+ AR_U > AR_S # E: Unsupported operand types
62
+ AR_U < AR_S # E: Unsupported operand types
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/comparisons.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import numpy as np
3
+
4
+ AR_i: np.ndarray[Any, np.dtype[np.int64]]
5
+ AR_f: np.ndarray[Any, np.dtype[np.float64]]
6
+ AR_c: np.ndarray[Any, np.dtype[np.complex128]]
7
+ AR_m: np.ndarray[Any, np.dtype[np.timedelta64]]
8
+ AR_M: np.ndarray[Any, np.dtype[np.datetime64]]
9
+
10
+ AR_f > AR_m # E: Unsupported operand types
11
+ AR_c > AR_m # E: Unsupported operand types
12
+
13
+ AR_m > AR_f # E: Unsupported operand types
14
+ AR_m > AR_c # E: Unsupported operand types
15
+
16
+ AR_i > AR_M # E: Unsupported operand types
17
+ AR_f > AR_M # E: Unsupported operand types
18
+ AR_m > AR_M # E: Unsupported operand types
19
+
20
+ AR_M > AR_i # E: Unsupported operand types
21
+ AR_M > AR_f # E: Unsupported operand types
22
+ AR_M > AR_m # E: Unsupported operand types
23
+
24
+ AR_i > str() # E: No overload variant
25
+ AR_i > bytes() # E: No overload variant
26
+ str() > AR_M # E: Unsupported operand types
27
+ bytes() > AR_M # E: Unsupported operand types
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/constants.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ np.Inf = np.Inf # E: Cannot assign to final
4
+ np.ALLOW_THREADS = np.ALLOW_THREADS # E: Cannot assign to final
5
+ np.little_endian = np.little_endian # E: Cannot assign to final
6
+ np.UFUNC_PYVALS_NAME = "bob" # E: Incompatible types
7
+ np.CLIP = 2 # E: Incompatible types
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/datasource.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import numpy as np
3
+
4
+ path: Path
5
+ d1: np.DataSource
6
+
7
+ d1.abspath(path) # E: incompatible type
8
+ d1.abspath(b"...") # E: incompatible type
9
+
10
+ d1.exists(path) # E: incompatible type
11
+ d1.exists(b"...") # E: incompatible type
12
+
13
+ d1.open(path, "r") # E: incompatible type
14
+ d1.open(b"...", encoding="utf8") # E: incompatible type
15
+ d1.open(None, newline="/n") # E: incompatible type
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/dtype.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ class Test1:
5
+ not_dtype = np.dtype(float)
6
+
7
+
8
+ class Test2:
9
+ dtype = float
10
+
11
+
12
+ np.dtype(Test1()) # E: No overload variant of "dtype" matches
13
+ np.dtype(Test2()) # E: incompatible type
14
+
15
+ np.dtype( # E: No overload variant of "dtype" matches
16
+ {
17
+ "field1": (float, 1),
18
+ "field2": (int, 3),
19
+ }
20
+ )
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/einsumfunc.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import numpy as np
3
+
4
+ AR_i: np.ndarray[Any, np.dtype[np.int64]]
5
+ AR_f: np.ndarray[Any, np.dtype[np.float64]]
6
+ AR_m: np.ndarray[Any, np.dtype[np.timedelta64]]
7
+ AR_U: np.ndarray[Any, np.dtype[np.str_]]
8
+
9
+ np.einsum("i,i->i", AR_i, AR_m) # E: incompatible type
10
+ np.einsum("i,i->i", AR_f, AR_f, dtype=np.int32) # E: incompatible type
11
+ np.einsum("i,i->i", AR_i, AR_i, out=AR_U) # E: Value of type variable "_ArrayType" of "einsum" cannot be
12
+ np.einsum("i,i->i", AR_i, AR_i, out=AR_U, casting="unsafe") # E: No overload variant
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/flatiter.pyi ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import numpy as np
4
+ from numpy._typing import _SupportsArray
5
+
6
+
7
+ class Index:
8
+ def __index__(self) -> int:
9
+ ...
10
+
11
+
12
+ a: "np.flatiter[np.ndarray]"
13
+ supports_array: _SupportsArray
14
+
15
+ a.base = Any # E: Property "base" defined in "flatiter" is read-only
16
+ a.coords = Any # E: Property "coords" defined in "flatiter" is read-only
17
+ a.index = Any # E: Property "index" defined in "flatiter" is read-only
18
+ a.copy(order='C') # E: Unexpected keyword argument
19
+
20
+ # NOTE: Contrary to `ndarray.__getitem__` its counterpart in `flatiter`
21
+ # does not accept objects with the `__array__` or `__index__` protocols;
22
+ # boolean indexing is just plain broken (gh-17175)
23
+ a[np.bool_()] # E: No overload variant of "__getitem__"
24
+ a[Index()] # E: No overload variant of "__getitem__"
25
+ a[supports_array] # E: No overload variant of "__getitem__"
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/fromnumeric.pyi ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for :mod:`numpy.core.fromnumeric`."""
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ A = np.array(True, ndmin=2, dtype=bool)
7
+ A.setflags(write=False)
8
+ AR_U: npt.NDArray[np.str_]
9
+
10
+ a = np.bool_(True)
11
+
12
+ np.take(a, None) # E: No overload variant
13
+ np.take(a, axis=1.0) # E: No overload variant
14
+ np.take(A, out=1) # E: No overload variant
15
+ np.take(A, mode="bob") # E: No overload variant
16
+
17
+ np.reshape(a, None) # E: No overload variant
18
+ np.reshape(A, 1, order="bob") # E: No overload variant
19
+
20
+ np.choose(a, None) # E: No overload variant
21
+ np.choose(a, out=1.0) # E: No overload variant
22
+ np.choose(A, mode="bob") # E: No overload variant
23
+
24
+ np.repeat(a, None) # E: No overload variant
25
+ np.repeat(A, 1, axis=1.0) # E: No overload variant
26
+
27
+ np.swapaxes(A, None, 1) # E: No overload variant
28
+ np.swapaxes(A, 1, [0]) # E: No overload variant
29
+
30
+ np.transpose(A, axes=1.0) # E: No overload variant
31
+
32
+ np.partition(a, None) # E: No overload variant
33
+ np.partition( # E: No overload variant
34
+ a, 0, axis="bob"
35
+ )
36
+ np.partition( # E: No overload variant
37
+ A, 0, kind="bob"
38
+ )
39
+ np.partition(
40
+ A, 0, order=range(5) # E: Argument "order" to "partition" has incompatible type
41
+ )
42
+
43
+ np.argpartition(
44
+ a, None # E: incompatible type
45
+ )
46
+ np.argpartition(
47
+ a, 0, axis="bob" # E: incompatible type
48
+ )
49
+ np.argpartition(
50
+ A, 0, kind="bob" # E: incompatible type
51
+ )
52
+ np.argpartition(
53
+ A, 0, order=range(5) # E: Argument "order" to "argpartition" has incompatible type
54
+ )
55
+
56
+ np.sort(A, axis="bob") # E: No overload variant
57
+ np.sort(A, kind="bob") # E: No overload variant
58
+ np.sort(A, order=range(5)) # E: Argument "order" to "sort" has incompatible type
59
+
60
+ np.argsort(A, axis="bob") # E: Argument "axis" to "argsort" has incompatible type
61
+ np.argsort(A, kind="bob") # E: Argument "kind" to "argsort" has incompatible type
62
+ np.argsort(A, order=range(5)) # E: Argument "order" to "argsort" has incompatible type
63
+
64
+ np.argmax(A, axis="bob") # E: No overload variant of "argmax" matches argument type
65
+ np.argmax(A, kind="bob") # E: No overload variant of "argmax" matches argument type
66
+
67
+ np.argmin(A, axis="bob") # E: No overload variant of "argmin" matches argument type
68
+ np.argmin(A, kind="bob") # E: No overload variant of "argmin" matches argument type
69
+
70
+ np.searchsorted( # E: No overload variant of "searchsorted" matches argument type
71
+ A[0], 0, side="bob"
72
+ )
73
+ np.searchsorted( # E: No overload variant of "searchsorted" matches argument type
74
+ A[0], 0, sorter=1.0
75
+ )
76
+
77
+ np.resize(A, 1.0) # E: No overload variant
78
+
79
+ np.squeeze(A, 1.0) # E: No overload variant of "squeeze" matches argument type
80
+
81
+ np.diagonal(A, offset=None) # E: No overload variant
82
+ np.diagonal(A, axis1="bob") # E: No overload variant
83
+ np.diagonal(A, axis2=[]) # E: No overload variant
84
+
85
+ np.trace(A, offset=None) # E: No overload variant
86
+ np.trace(A, axis1="bob") # E: No overload variant
87
+ np.trace(A, axis2=[]) # E: No overload variant
88
+
89
+ np.ravel(a, order="bob") # E: No overload variant
90
+
91
+ np.compress( # E: No overload variant
92
+ [True], A, axis=1.0
93
+ )
94
+
95
+ np.clip(a, 1, 2, out=1) # E: No overload variant of "clip" matches argument type
96
+
97
+ np.sum(a, axis=1.0) # E: No overload variant
98
+ np.sum(a, keepdims=1.0) # E: No overload variant
99
+ np.sum(a, initial=[1]) # E: No overload variant
100
+
101
+ np.all(a, axis=1.0) # E: No overload variant
102
+ np.all(a, keepdims=1.0) # E: No overload variant
103
+ np.all(a, out=1.0) # E: No overload variant
104
+
105
+ np.any(a, axis=1.0) # E: No overload variant
106
+ np.any(a, keepdims=1.0) # E: No overload variant
107
+ np.any(a, out=1.0) # E: No overload variant
108
+
109
+ np.cumsum(a, axis=1.0) # E: No overload variant
110
+ np.cumsum(a, dtype=1.0) # E: No overload variant
111
+ np.cumsum(a, out=1.0) # E: No overload variant
112
+
113
+ np.ptp(a, axis=1.0) # E: No overload variant
114
+ np.ptp(a, keepdims=1.0) # E: No overload variant
115
+ np.ptp(a, out=1.0) # E: No overload variant
116
+
117
+ np.amax(a, axis=1.0) # E: No overload variant
118
+ np.amax(a, keepdims=1.0) # E: No overload variant
119
+ np.amax(a, out=1.0) # E: No overload variant
120
+ np.amax(a, initial=[1.0]) # E: No overload variant
121
+ np.amax(a, where=[1.0]) # E: incompatible type
122
+
123
+ np.amin(a, axis=1.0) # E: No overload variant
124
+ np.amin(a, keepdims=1.0) # E: No overload variant
125
+ np.amin(a, out=1.0) # E: No overload variant
126
+ np.amin(a, initial=[1.0]) # E: No overload variant
127
+ np.amin(a, where=[1.0]) # E: incompatible type
128
+
129
+ np.prod(a, axis=1.0) # E: No overload variant
130
+ np.prod(a, out=False) # E: No overload variant
131
+ np.prod(a, keepdims=1.0) # E: No overload variant
132
+ np.prod(a, initial=int) # E: No overload variant
133
+ np.prod(a, where=1.0) # E: No overload variant
134
+ np.prod(AR_U) # E: incompatible type
135
+
136
+ np.cumprod(a, axis=1.0) # E: No overload variant
137
+ np.cumprod(a, out=False) # E: No overload variant
138
+ np.cumprod(AR_U) # E: incompatible type
139
+
140
+ np.size(a, axis=1.0) # E: Argument "axis" to "size" has incompatible type
141
+
142
+ np.around(a, decimals=1.0) # E: No overload variant
143
+ np.around(a, out=type) # E: No overload variant
144
+ np.around(AR_U) # E: incompatible type
145
+
146
+ np.mean(a, axis=1.0) # E: No overload variant
147
+ np.mean(a, out=False) # E: No overload variant
148
+ np.mean(a, keepdims=1.0) # E: No overload variant
149
+ np.mean(AR_U) # E: incompatible type
150
+
151
+ np.std(a, axis=1.0) # E: No overload variant
152
+ np.std(a, out=False) # E: No overload variant
153
+ np.std(a, ddof='test') # E: No overload variant
154
+ np.std(a, keepdims=1.0) # E: No overload variant
155
+ np.std(AR_U) # E: incompatible type
156
+
157
+ np.var(a, axis=1.0) # E: No overload variant
158
+ np.var(a, out=False) # E: No overload variant
159
+ np.var(a, ddof='test') # E: No overload variant
160
+ np.var(a, keepdims=1.0) # E: No overload variant
161
+ np.var(AR_U) # E: incompatible type
venv/lib/python3.10/site-packages/numpy/typing/tests/data/fail/histograms.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import numpy.typing as npt
3
+
4
+ AR_i8: npt.NDArray[np.int64]
5
+ AR_f8: npt.NDArray[np.float64]
6
+
7
+ np.histogram_bin_edges(AR_i8, range=(0, 1, 2)) # E: incompatible type
8
+
9
+ np.histogram(AR_i8, range=(0, 1, 2)) # E: incompatible type
10
+
11
+ np.histogramdd(AR_i8, range=(0, 1)) # E: incompatible type
12
+ np.histogramdd(AR_i8, range=[(0, 1, 2)]) # E: incompatible type